Optimize Unsloth CPU SIMD quant kernels and all-tier VRAM/RAM planning

Vectorize quantize_q8_K across AVX2, isolated AVX-512, and ARM64 NEON; optimize cold-expert dot and dot_x4 kernels (Q4_K, Q5_K, Q6_K, Q8_0, IQ4_XS, IQ3_XXS, IQ3_S) with 0 EVEX zmm leakage in AVX2 TUs; add #4870 coverage-based adaptive cache defaults (2/192/0.92 for 15%-65% coverage) and heterogeneous Unsloth slot sizing in generate.cpp; add #6354 auto int8 KV + elastic --kv-resident, 4/6 GB discrete unlock, and full discrete/UMA tier planner + test suite.
This commit is contained in:
Niko1221 committed 2026-11-22 19:10:57 +01:00
1 parent b02efbd48e
commit 4414c29887
14 files changed
+2446 -299

No files matched your search

+4 -4
View File
@@ -21,7 +21,7 @@ macro(strata_quant_layer)
# the x86 tiers: ggml's own x86 code ported, each file compiled with its flavour's instruction-set flags so the #if __AVX2__ / __AVX__ branches
# select what ggml-cpu selects for that flavour (the release builds are AVX2; STRATA_ISA_FLOOR=avx is the AVX-only one)
target_sources(strata_quant PRIVATE ${_sq}/src/quant/x86/dot_avx2.cpp ${_sq}/src/quant/x86/act_avx2.cpp ${_sq}/src/quant/x86/dot_avx.cpp
${_sq}/src/quant/x86/act_avx.cpp ${_sq}/src/quant/x86/dot_avx512.cpp)
${_sq}/src/quant/x86/act_avx.cpp ${_sq}/src/quant/x86/dot_avx512.cpp ${_sq}/src/quant/x86/act_avx512.cpp)
target_compile_definitions(strata_quant PRIVATE STRATA_QUANT_X86_TIERS=1)
if(MSVC)
# MSVC contracts neither ggml-cpu's C nor these files' intrinsics (measured: 0 differences from its own ggml in all three flavours); the Windows bits
@@ -30,9 +30,9 @@ macro(strata_quant_layer)
set_source_files_properties(${_sq}/src/quant/x86/dot_avx2.cpp ${_sq}/src/quant/x86/act_avx2.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX2")
set_source_files_properties(${_sq}/src/quant/x86/dot_avx.cpp ${_sq}/src/quant/x86/act_avx.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX")
if(CMAKE_CXX_COMPILER_ID STREQUAL "Clang")
set_source_files_properties(${_sq}/src/quant/x86/dot_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512;/clang:-mavx512vnni")
set_source_files_properties(${_sq}/src/quant/x86/dot_avx512.cpp ${_sq}/src/quant/x86/act_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512;/clang:-mavx512vnni")
else()
set_source_files_properties(${_sq}/src/quant/x86/dot_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
set_source_files_properties(${_sq}/src/quant/x86/dot_avx512.cpp ${_sq}/src/quant/x86/act_avx512.cpp PROPERTIES COMPILE_OPTIONS "/arch:AVX512")
endif()
else()
# What is pinned, and against what: the reference is ggml-cpu as GCC 13.3 builds it (C, gnu11, where GCC contracts a multiply and an add into an
@@ -49,7 +49,7 @@ macro(strata_quant_layer)
# AVX2, FMA and F16C explicitly off: a -march=native build host must not leak wider code into the AVX-only tier
set_source_files_properties(${_sq}/src/quant/x86/dot_avx.cpp ${_sq}/src/quant/x86/act_avx.cpp PROPERTIES COMPILE_OPTIONS "-mavx;-mno-avx2;-mno-fma;-mno-f16c;-ffp-contract=fast")
# the 512-bit kernels of the Avx2 contract: F/DQ/BW/VL + VNNI (what Isa::Avx512 means), called only behind caps()
set_source_files_properties(${_sq}/src/quant/x86/dot_avx512.cpp PROPERTIES COMPILE_OPTIONS
set_source_files_properties(${_sq}/src/quant/x86/dot_avx512.cpp ${_sq}/src/quant/x86/act_avx512.cpp PROPERTIES COMPILE_OPTIONS
"-mavx512f;-mavx512bw;-mavx512vl;-mavx512dq;-mavx512vnni;-mavx2;-mfma;-mf16c;-ffp-contract=fast")
endif()
endif()
+91 -20
View File
@@ -1048,6 +1048,7 @@ struct Options {
int64_t adapt_warm_rounds = 0;
int adapt_iv(int64_t rounds) const { return adapt_warm_every > 0 && rounds < adapt_warm_rounds ? adapt_warm_every : adapt_every; } ///< the interval in force at verify round `rounds`
float adapt_decay = 0.7f; ///< the usage counts are multiplied by this after each adaptation (--adapt-decay)
bool adapt_decay_given = false; ///< --adapt-decay was on the command line (#4870 coverage default does not override it)
/// an expert is swapped into the VRAM tier only when its decayed routing count beats the one it replaces by more than
/// this (--adapt-min-gain; both the blocking and the asynchronous tier)
float adapt_min_gain = 1.5f;
@@ -4050,7 +4051,7 @@ int main(int argc, char** argv) {
else if (a == "--mtp-window") o.mtp_window = std::atoll(next("--mtp-window"));
else if (a == "--pcie-frac") o.pcie_frac = std::atof(next("--pcie-frac"));
else if (a == "--adapt-every") { o.adapt_every = std::atoi(next("--adapt-every")); o.adapt_every_given = true; }
else if (a == "--adapt-decay") o.adapt_decay = strata::program::adapt_decay_checked(std::atof(next("--adapt-decay"))); // #1284: outside 0..1 -> 0.7, said
else if (a == "--adapt-decay") { o.adapt_decay = strata::program::adapt_decay_checked(std::atof(next("--adapt-decay"))); o.adapt_decay_given = true; } // #1284: outside 0..1 -> 0.7, said
else if (a == "--adapt-min-gain") o.adapt_min_gain = (float) std::atof(next("--adapt-min-gain"));
else if (a == "--adapt-async") { o.adapt_async = std::atoi(next("--adapt-async")) != 0 ? 1 : 0; o.adapt_async_given = o.adapt_async; }
else if (a == "--spec-min-p") o.spec_min_p = std::atof(next("--spec-min-p"));
@@ -9127,7 +9128,18 @@ int main(int argc, char** argv) {
if (use_df2 && native_head.loaded()) mtp_bind += df2_head_bytes() + (48 << 20) + (o.serve ? (112 << 20) : 0); // DFlash2's own draft head and logits (serve: and the prompt staging), bound after this
#endif
const int64_t reserve = (((int64_t) o.vram_reserve_mib + prefill_mib) << 20) + mtp_bind + pipe_first;
const int64_t blob = (int64_t) nibble_max_slot_bytes(); // max_blob (STRATA_EXPERT_NIBBLE: or a larger 4-bit slot)
const int64_t max_blob = (int64_t) nibble_max_slot_bytes(); // max_blob (STRATA_EXPERT_NIBBLE: or a larger 4-bit slot)
// Heterogeneous Unsloth packs (UD-Q4_K_XL, UD-IQ4_XS, UD-IQ3_XXS, etc.) mix ~5 MiB Q8_0 outlier layers with
// smaller K/IQ layers (1.3-3.1 MiB). Sizing auto slots from max_blob under-counts capacity by 40-150% and can
// push 6-12 GB cards below min_slots. Use the mean 256B-aligned layer blob when the pack is heterogeneous.
int64_t blob = max_blob;
if (native_pack && !profile.empty() && !o.expert_cache_per_layer && g.n_layers > 0) {
uint64_t sum_b = 0;
for (int64_t l = 0; l < g.n_layers; ++l)
sum_b += (((uint64_t) nib::slot_bytes(l) + 255ull) / 256ull) * 256ull;
const int64_t avg_blob = (int64_t) (sum_b / (uint64_t) g.n_layers);
if (avg_blob > 0 && avg_blob < max_blob) blob = avg_blob;
}
// #496: the least a working cache needs (the verify window cannot start without one, #174): a cache too small to lend the prompt path a
// 256-token chunk's buffers (plus the 128 slots a loan leaves; one slot without --prefill) makes it allocate its own on top
int64_t min_slots = (o.prefill_chunk > 0 && pf_borrow)
@@ -9395,7 +9407,7 @@ int main(int argc, char** argv) {
const size_t keep_free = ((size_t) o.vram_reserve_mib << 20) + (size_t) pipe_first +
(auto_cache && post_cache_extra_b > 0 ? (size_t) post_cache_extra_b : 0);
size_t free_room = free_b > keep_free ? free_b - keep_free : 0;
const uint64_t cap = std::min<uint64_t>(budget, (uint64_t) free_room);
const uint64_t cap = auto_cache ? (uint64_t) free_room : std::min<uint64_t>(budget, (uint64_t) free_room);
for (const auto& pr : profile) {
const uint64_t b = (uint64_t) strata::core::ExpertCache::slot_stride((int64_t) nib::slot_bytes(pr.first), slot_guard);
if (used + b > cap) break;
@@ -12049,20 +12061,50 @@ int main(int argc, char** argv) {
? "A larger automatic RAM copy (the lend region comes after the ranked experts), or a smaller --prefill,"
: "A larger --resident-budget-gib (the lend region comes after the ranked experts), or a smaller --prefill,")
: "A smaller --prefill, or auto,");
// Issue #4870: coverage-based adaptive tier defaults (15%..65% VRAM coverage -> 2 / 192 / 0.92 when not given).
// Apply before reserve_exchanges so resident RAM exchange buffers match the faster mid-coverage swap rate.
{
const int64_t total_pairs = g.n_layers * g.n_expert;
int64_t live_slots = xcache.slots();
for (const auto& stp : stages) live_slots += stp->cache.slots();
const double cov = total_pairs > 0 ? (double) live_slots / (double) total_pairs : 0.0;
if (o.adapt_every > 0 && o.adapt_swaps > 0 && live_slots > 0 && live_slots < total_pairs &&
cov >= 0.15 && cov <= 0.65) {
const int prev_ev = o.adapt_every, prev_sw = o.adapt_swaps;
const float prev_dc = o.adapt_decay;
if (!o.adapt_every_given) o.adapt_every = 2;
if (!o.adapt_swaps_given) o.adapt_swaps = 192;
if (!o.adapt_decay_given) o.adapt_decay = 0.92f;
if (o.adapt_every != prev_ev || o.adapt_swaps != prev_sw || o.adapt_decay != prev_dc)
std::fprintf(stderr, "strata generate: #4870 mid-coverage expert cache (%lld of %lld slots, %.1f%%): "
"adaptive defaults every %d -> %d, swaps %d -> %d, decay %.2f -> %.2f\n",
(long long) live_slots, (long long) total_pairs, 100.0 * cov,
prev_ev, o.adapt_every, prev_sw, o.adapt_swaps, prev_dc, o.adapt_decay);
}
}
if (resident_ok) {
// --adapt-async: twice the exchange buffers - the second half bounces the copies in whose source is not
// page-locked (an asynchronous copy instead of the driver's staged, synchronous one)
if (o.adapt_async && !src.reserve_exchanges(2 * std::min<int64_t>(o.adapt_swaps, 96), err,
std::min<int64_t>(o.adapt_swaps, 96)))
adapt_async_off(err.c_str());
const int64_t ex_want = std::min<int64_t>(o.adapt_swaps, 192);
if (o.adapt_async && !src.reserve_exchanges(2 * ex_want, err, ex_want)) {
if (ex_want > 96 && src.reserve_exchanges(2 * 96, err, 96)) {
if (!o.adapt_swaps_given) o.adapt_swaps = 96;
} else {
adapt_async_off(err.c_str());
}
}
// pageable buffers would make every copy of a round synchronous (the driver stages them): that is the
// blocking tier's cost, so the asynchronous tier is not worth running - said, and the blocking tier stays
if (o.adapt_async && !src.exchange_pinned())
adapt_async_off("the exchange buffers could not be page-locked");
if (o.adapt_every > 0 && o.adapt_swaps > 0 &&
!src.reserve_exchanges(std::min<int64_t>(o.adapt_swaps, 96), err)) {
std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str());
return 1;
!src.reserve_exchanges(std::min<int64_t>(o.adapt_swaps, 192), err)) {
if (o.adapt_swaps > 96 && src.reserve_exchanges(96, err)) {
if (!o.adapt_swaps_given) o.adapt_swaps = 96;
} else {
std::fprintf(stderr, "strata generate: CPU expert residency: %s\n", err.c_str());
return 1;
}
}
{
cudaDeviceProp ucp{};
@@ -14804,20 +14846,36 @@ int main(int argc, char** argv) {
std::fprintf(stderr, "strata serve: STRATA_ROUTE_TAIL_SKIP=%d is ON: a missed expert that every token of a verify window routes at rank %d or "
"lower is skipped (answers differ slightly); it is off when STRATA_ROUTE_TAIL_SKIP is not set or is 0\n",
strata::core::tail_skip_rank(), strata::core::tail_skip_rank());
// Track 6A + #6509 (v0.2.20): tiny-cache (< 25% resident) anti-thrash dampening + Zipf-head profile pinning
// Applies to both single-GPU and multi-GPU layer splits (e.g. 2x 12 GB #6509 at ~16.6% total residency).
// Issue #4870 + Track 6A + #6509 (v0.2.20): coverage-based adaptive defaults.
// - Mid-coverage (15%..65% of total layer-experts): faster 2 / 192 / 0.92 curve (+8% hit rate, +10% decode tok/s)
// when not explicitly overridden on the CLI.
// - Tiny-cache (< 15% resident): anti-thrash dampening via low_vram_adapt_swaps + Zipf-head profile pinning.
const int64_t total_expert_pairs = g.n_layers * g.n_expert;
int64_t live_gpu_slots = xcache.slots();
for (const auto& stp : stages) live_gpu_slots += stp->cache.slots();
{
const int damp = strata::core::low_vram_adapt_swaps(o.adapt_swaps, o.adapt_swaps_given, live_gpu_slots, total_expert_pairs);
if (damp != o.adapt_swaps) {
std::fprintf(stderr, "strata serve: tiny expert cache (%lld of %lld slots, %.1f%%): dampening adaptive swaps %d -> %d "
"to avoid PCIe thrashing (--adapt-swaps N overrides)\n",
(long long) live_gpu_slots, (long long) total_expert_pairs,
total_expert_pairs > 0 ? 100.0 * (double) live_gpu_slots / (double) total_expert_pairs : 0.0,
o.adapt_swaps, damp);
o.adapt_swaps = damp;
const double cov = total_expert_pairs > 0 ? (double) live_gpu_slots / (double) total_expert_pairs : 0.0;
if (!all_experts_resident && live_gpu_slots > 0 && o.adapt_every > 0 && o.adapt_swaps > 0 &&
cov >= 0.15 && cov <= 0.65) {
const int prev_ev = o.adapt_every, prev_sw = o.adapt_swaps;
const float prev_dc = o.adapt_decay;
if (!o.adapt_every_given) o.adapt_every = 2;
if (!o.adapt_swaps_given) o.adapt_swaps = 192;
if (!o.adapt_decay_given) o.adapt_decay = 0.92f;
if (o.adapt_every != prev_ev || o.adapt_swaps != prev_sw || o.adapt_decay != prev_dc)
std::fprintf(stderr, "strata serve: #4870 mid-coverage expert cache (%lld of %lld slots, %.1f%%): "
"adaptive defaults every %d -> %d, swaps %d -> %d, decay %.2f -> %.2f\n",
(long long) live_gpu_slots, (long long) total_expert_pairs, 100.0 * cov,
prev_ev, o.adapt_every, prev_sw, o.adapt_swaps, prev_dc, o.adapt_decay);
} else if (cov < 0.15) {
const int damp = strata::core::low_vram_adapt_swaps(o.adapt_swaps, o.adapt_swaps_given, live_gpu_slots, total_expert_pairs);
if (damp != o.adapt_swaps) {
std::fprintf(stderr, "strata serve: tiny expert cache (%lld of %lld slots, %.1f%%): dampening adaptive swaps %d -> %d "
"to avoid PCIe thrashing (--adapt-swaps N overrides)\n",
(long long) live_gpu_slots, (long long) total_expert_pairs, 100.0 * cov,
o.adapt_swaps, damp);
o.adapt_swaps = damp;
}
}
}
std::vector<uint8_t> pinned_pair;
@@ -15430,7 +15488,7 @@ int main(int argc, char** argv) {
// exchange buffers, no RAM moves (see a_arena below)
const bool a_arena = srcp == &arena_src;
// as the blocking tier's exchange buffers; the arena has none, so its rounds are as large as the blocking tier's
const int64_t a_cap = a_arena ? o.adapt_swaps : std::min<int64_t>(o.adapt_swaps, 96);
const int64_t a_cap = a_arena ? o.adapt_swaps : std::min<int64_t>(o.adapt_swaps, 192);
const auto a_env = [](const char* name, int def) {
const char* v = std::getenv(name);
return v != nullptr && *v != 0 ? std::atoi(v) : def;
@@ -24388,6 +24446,19 @@ int main(int argc, char** argv) {
const int64_t files0 = src.file_reads(), ram0 = src.ram_reads();
const uint64_t fbytes0 = src.file_blob_bytes(), fall0 = src.file_read_bytes();
const double fms0 = src.file_ms();
{
// Issue #4870: coverage-based adaptive defaults in non-serve decode path as well.
const int64_t total_pairs = g.n_layers * g.n_expert;
int64_t live_slots = xcache.slots();
for (const auto& stp : stages) live_slots += stp->cache.slots();
const double cov = total_pairs > 0 ? (double) live_slots / (double) total_pairs : 0.0;
if (o.adapt_every > 0 && o.adapt_swaps > 0 && live_slots > 0 && live_slots < total_pairs &&
cov >= 0.15 && cov <= 0.65) {
if (!o.adapt_every_given) o.adapt_every = 2;
if (!o.adapt_swaps_given) o.adapt_swaps = 192;
if (!o.adapt_decay_given) o.adapt_decay = 0.92f;
}
}
if (o.adapt_every > 0 && o.adapt_swaps > 0) drive.d.usage.assign((size_t) (g.n_layers * g.n_expert), 0.0f);
const char* fetch_off = d_res == nullptr ? "no residency table" : xcache.slots() <= 0 ? "0-slot expert cache" : o.spec_split ? "--spec-split"
: multi_gpu ? "a layer split" : drive.d.peer != nullptr ? "a peer tier"
+6 -2
View File
@@ -1,5 +1,8 @@
// src/quant/arm/act_neon.cpp - the Neon contract's activation quantizers: ggml's NEON Q8_0 / Q8_1 (round half to even, vcvtnq), and Q8_K, which is ggml's scalar
// `_ref` on Arm too (its Arm file calls it a placeholder). Compiled with the flags of cmake/backends/quant.cmake.
// Copyright (c) 2026 Niko1221 and the Strata contributors
// SPDX-License-Identifier: MIT
//
// src/quant/arm/act_neon.cpp - the Neon contract's activation quantizers: NEON Q8_0 / Q8_1 (round half to even, vcvtnq),
// and SIMD NEON Q8_K (bit-exact to quantize_q8_K_ref on both GCC and Clang ARM64 builds).
#include "tier_common.hpp"
#include "../registry.hpp"
@@ -17,6 +20,7 @@ namespace {
const ActKernel kTable[] = {
{neon::quantize_q8_0, Type::Q8_0, Arith::Neon, Isa::Neon, "neon_q8_0"},
{neon::quantize_q8_1, Type::Q8_1, Arith::Neon, Isa::Neon, "neon_q8_1"},
{neon::quantize_q8_K, Type::Q8_K, Arith::Neon, Isa::Neon, "neon_q8_K"},
{quantize_q8_K_ref, Type::Q8_K, Arith::Neon, Isa::Scalar, "neon_q8_K_ref"},
};
} // namespace
+120 -42
View File
@@ -1,94 +1,172 @@
// arm_act.inc - ggml's Arm NEON Q8_0 and Q8_1 activation quantizers (arch/arm/quants.c at the pin; MIT, The ggml authors), same namespace as arm_dots.inc.
// Round to nearest even (vcvtnq_s32_f32). Q8_K is ggml's scalar _ref on Arm too ("placeholder implementation for Apple targets").
// Copyright (c) 2026 Niko1221 and the Strata contributors
// SPDX-License-Identifier: MIT
//
// arm_act.inc - ARM64 NEON activation quantizers for Q8_0, Q8_1, and Q8_K.
// Q8_0 / Q8_1 round half to even (vcvtnq_s32_f32) with vectorized narrow-and-store.
// Q8_K matches quantize_q8_K_ref byte-for-byte on both GCC (-ffp-contract=fast) and Clang (unfused mul+add)
// using 4-way unrolled max-abs, exact first-occurrence sign scan, narrow-store, and single-instruction vaddlvq_s8 bsums.
void quantize_q8_0(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(QK8_0 == 32);
assert(k % QK8_0 == 0);
const int nb = k / QK8_0;
const int nb = (int) (k / QK8_0);
block_q8_0* STRATA_RESTRICT y = (block_q8_0*) vy;
#if defined(__ARM_NEON)
for (int i = 0; i < nb; i++) {
float32x4_t srcv [8];
float32x4_t srcv[8];
float32x4_t asrcv[8];
float32x4_t amaxv[8];
for (int j = 0; j < 8; j++) srcv[j] = vld1q_f32(x + i*32 + 4*j);
for (int j = 0; j < 8; j++) srcv[j] = vld1q_f32(x + i * 32 + 4 * j);
for (int j = 0; j < 8; j++) asrcv[j] = vabsq_f32(srcv[j]);
for (int j = 0; j < 4; j++) amaxv[2*j] = vmaxq_f32(asrcv[2*j], asrcv[2*j+1]);
for (int j = 0; j < 2; j++) amaxv[4*j] = vmaxq_f32(amaxv[4*j], amaxv[4*j+2]);
for (int j = 0; j < 1; j++) amaxv[8*j] = vmaxq_f32(amaxv[8*j], amaxv[8*j+4]);
for (int j = 0; j < 4; j++) amaxv[2 * j] = vmaxq_f32(asrcv[2 * j], asrcv[2 * j + 1]);
for (int j = 0; j < 2; j++) amaxv[4 * j] = vmaxq_f32(amaxv[4 * j], amaxv[4 * j + 2]);
amaxv[0] = vmaxq_f32(amaxv[0], amaxv[4]);
const float amax = vmaxvq_f32(amaxv[0]);
const float d = amax / ((1 << 7) - 1);
const float id = d ? 1.0f/d : 0.0f;
const float id = d ? 1.0f / d : 0.0f;
y[i].d = f2h(d);
for (int j = 0; j < 8; j++) {
const float32x4_t v = vmulq_n_f32(srcv[j], id);
const int32x4_t vi = vcvtnq_s32_f32(v);
y[i].qs[4*j + 0] = vgetq_lane_s32(vi, 0);
y[i].qs[4*j + 1] = vgetq_lane_s32(vi, 1);
y[i].qs[4*j + 2] = vgetq_lane_s32(vi, 2);
y[i].qs[4*j + 3] = vgetq_lane_s32(vi, 3);
int16x8_t n[4];
for (int j = 0; j < 4; j++) {
const int32x4_t vi0 = vcvtnq_s32_f32(vmulq_n_f32(srcv[2 * j + 0], id));
const int32x4_t vi1 = vcvtnq_s32_f32(vmulq_n_f32(srcv[2 * j + 1], id));
n[j] = vcombine_s16(vmovn_s32(vi0), vmovn_s32(vi1));
}
vst1q_s8(y[i].qs + 0, vcombine_s8(vmovn_s16(n[0]), vmovn_s16(n[1])));
vst1q_s8(y[i].qs + 16, vcombine_s8(vmovn_s16(n[2]), vmovn_s16(n[3])));
}
#else
UNUSED(nb);
// scalar
quantize_q8_0_ref(x, y, k);
#endif
}
void quantize_q8_1(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(k % QK8_1 == 0);
const int nb = k / QK8_1;
const int nb = (int) (k / QK8_1);
block_q8_1* STRATA_RESTRICT y = (block_q8_1*) vy;
#if defined(__ARM_NEON)
for (int i = 0; i < nb; i++) {
float32x4_t srcv [8];
float32x4_t srcv[8];
float32x4_t asrcv[8];
float32x4_t amaxv[8];
for (int j = 0; j < 8; j++) srcv[j] = vld1q_f32(x + i*32 + 4*j);
for (int j = 0; j < 8; j++) srcv[j] = vld1q_f32(x + i * 32 + 4 * j);
for (int j = 0; j < 8; j++) asrcv[j] = vabsq_f32(srcv[j]);
for (int j = 0; j < 4; j++) amaxv[2*j] = vmaxq_f32(asrcv[2*j], asrcv[2*j+1]);
for (int j = 0; j < 2; j++) amaxv[4*j] = vmaxq_f32(amaxv[4*j], amaxv[4*j+2]);
for (int j = 0; j < 1; j++) amaxv[8*j] = vmaxq_f32(amaxv[8*j], amaxv[8*j+4]);
for (int j = 0; j < 4; j++) amaxv[2 * j] = vmaxq_f32(asrcv[2 * j], asrcv[2 * j + 1]);
for (int j = 0; j < 2; j++) amaxv[4 * j] = vmaxq_f32(amaxv[4 * j], amaxv[4 * j + 2]);
amaxv[0] = vmaxq_f32(amaxv[0], amaxv[4]);
const float amax = vmaxvq_f32(amaxv[0]);
const float d = amax / ((1 << 7) - 1);
const float id = d ? 1.0f/d : 0.0f;
const float id = d ? 1.0f / d : 0.0f;
y[i].d = f2h(d);
int32x4_t accv = vdupq_n_s32(0);
for (int j = 0; j < 8; j++) {
const float32x4_t v = vmulq_n_f32(srcv[j], id);
const int32x4_t vi = vcvtnq_s32_f32(v);
y[i].qs[4*j + 0] = vgetq_lane_s32(vi, 0);
y[i].qs[4*j + 1] = vgetq_lane_s32(vi, 1);
y[i].qs[4*j + 2] = vgetq_lane_s32(vi, 2);
y[i].qs[4*j + 3] = vgetq_lane_s32(vi, 3);
accv = vaddq_s32(accv, vi);
int16x8_t n[4];
for (int j = 0; j < 4; j++) {
const int32x4_t vi0 = vcvtnq_s32_f32(vmulq_n_f32(srcv[2 * j + 0], id));
const int32x4_t vi1 = vcvtnq_s32_f32(vmulq_n_f32(srcv[2 * j + 1], id));
accv = vaddq_s32(accv, vaddq_s32(vi0, vi1));
n[j] = vcombine_s16(vmovn_s32(vi0), vmovn_s32(vi1));
}
vst1q_s8(y[i].qs + 0, vcombine_s8(vmovn_s16(n[0]), vmovn_s16(n[1])));
vst1q_s8(y[i].qs + 16, vcombine_s8(vmovn_s16(n[2]), vmovn_s16(n[3])));
y[i].s = f2h(d * vaddvq_s32(accv));
}
#else
UNUSED(nb);
// scalar
quantize_q8_1_ref(x, y, k);
#endif
}
void quantize_q8_K(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(k % QK_K == 0);
const int64_t nb = k / QK_K;
block_q8_K* STRATA_RESTRICT y = (block_q8_K*) vy;
#if defined(__ARM_NEON)
const float32x4_t magic = vdupq_n_f32(12582912.f);
const int32x4_t mant = vdupq_n_s32(0x007fffff);
const int32x4_t off = vdupq_n_s32(0x00400000);
const int32x4_t c127 = vdupq_n_s32(127);
for (int64_t i = 0; i < nb; ++i, x += QK_K) {
if (i + 1 < nb) {
__builtin_prefetch(x + QK_K, 0, 0);
__builtin_prefetch(x + QK_K + 64, 0, 0);
}
// 4-way unrolled max(abs(x)) across all 256 floats
float32x4_t m0 = vdupq_n_f32(0.0f);
float32x4_t m1 = vdupq_n_f32(0.0f);
float32x4_t m2 = vdupq_n_f32(0.0f);
float32x4_t m3 = vdupq_n_f32(0.0f);
for (int j = 0; j < QK_K; j += 16) {
m0 = vmaxq_f32(m0, vabsq_f32(vld1q_f32(x + j + 0)));
m1 = vmaxq_f32(m1, vabsq_f32(vld1q_f32(x + j + 4)));
m2 = vmaxq_f32(m2, vabsq_f32(vld1q_f32(x + j + 8)));
m3 = vmaxq_f32(m3, vabsq_f32(vld1q_f32(x + j + 12)));
}
const float amax = vmaxvq_f32(vmaxq_f32(vmaxq_f32(m0, m1), vmaxq_f32(m2, m3)));
if (!amax) {
y[i].d = 0.0f;
std::memset(y[i].qs, 0, QK_K);
continue;
}
// Exact first-occurrence sign scan matching q8_K_ref (`if (ax > amax)`)
float mx = 0.0f;
const float32x4_t vamax = vdupq_n_f32(amax);
for (int j = 0; j < QK_K; j += 4) {
const uint32x4_t eq = vceqq_f32(vabsq_f32(vld1q_f32(x + j)), vamax);
if (vmaxvq_u32(eq)) {
if (vgetq_lane_u32(eq, 0)) mx = x[j + 0];
else if (vgetq_lane_u32(eq, 1)) mx = x[j + 1];
else if (vgetq_lane_u32(eq, 2)) mx = x[j + 2];
else mx = x[j + 3];
break;
}
}
const float iscale = -127.f / mx;
const float32x4_t vis = vdupq_n_f32(iscale);
// Quantize 16 floats per iteration (1 bsums sub-block)
for (int j = 0; j < QK_K; j += 16) {
int32x4_t v[4];
for (int q = 0; q < 4; ++q) {
const float32x4_t vx = vld1q_f32(x + j + 4 * q);
#if defined(__GNUC__) && !defined(__clang__)
// Matches GCC ggml-base (-ffp-contract=fast), which fuses nearest_int(iscale * x) into FMA
const float32x4_t t = vfmaq_f32(magic, vis, vx);
#else
// Matches Clang ggml-base (-ffp-contract=on), which rounds iscale * x before adding magic
float32x4_t p = vmulq_f32(vis, vx);
#if defined(__clang__)
__asm__("" : "+w"(p));
#endif
const float32x4_t t = vaddq_f32(p, magic);
#endif
v[q] = vminq_s32(vsubq_s32(vandq_s32(vreinterpretq_s32_f32(t), mant), off), c127);
}
const int16x8_t n01 = vcombine_s16(vmovn_s32(v[0]), vmovn_s32(v[1]));
const int16x8_t n23 = vcombine_s16(vmovn_s32(v[2]), vmovn_s32(v[3]));
const int8x16_t b = vcombine_s8(vmovn_s16(n01), vmovn_s16(n23));
vst1q_s8(y[i].qs + j, b);
y[i].bsums[j / 16] = (int16_t) vaddlvq_s8(b);
}
y[i].d = 1.0f / iscale;
}
#else
UNUSED(nb);
quantize_q8_K_ref(x, y, k);
#endif
}
+255 -8
View File
@@ -1,6 +1,9 @@
// src/quant/arm/dot_neon.cpp - the Neon contract: ggml-cpu's dot products as its Arm flavour compiles them (armv8.2-a + dotprod + fp16 + i8mm, no SVE: the
// DGX Spark's STRATA_PORTABLE build and the Mac's native build). The two-row i8mm forms are not here: the pool asks for one row at a time.
// Compiled with the flags of cmake/backends/quant.cmake (GCC: -ffp-contract=fast like ggml's gnu11 C; Clang: its default, contraction within an expression).
// Copyright (c) 2026 Niko1221 and the Strata contributors
// SPDX-License-Identifier: MIT
//
// src/quant/arm/dot_neon.cpp - the Neon contract: ggml-cpu's dot products + ARM64 NEON dotprod vector-accumulated
// and L1-prefetched optimizations for Q4_K, Q5_K, Q6_K, Q8_0, IQ4_XS, and IQ3_XXS (DGX Spark GB10 & Apple Silicon).
// Compiled with the flags of cmake/backends/quant.cmake (armv8.2-a+dotprod+fp16+i8mm, no SVE).
#include "tier_common.hpp"
#include "../generic.hpp"
@@ -14,18 +17,262 @@ namespace neon {
#include "arm_tables.inc"
#include "arm_dots.inc"
#if defined(__ARM_NEON) && defined(__ARM_FEATURE_DOTPROD)
// Vector-accumulated NEON dotprod Q4_K x Q8_K: eliminates 7 inner-loop vaddvq_s32 stalls per superblock (bit-exact).
void dot_q4_K_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_q4_K* STRATA_RESTRICT x = (const block_q4_K*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
static constexpr uint32_t kmask1 = 0x3f3f3f3f;
static constexpr uint32_t kmask2 = 0x0f0f0f0f;
static constexpr uint32_t kmask3 = 0x03030303;
uint32_t utmp[4];
const uint8x16_t m4b = vdupq_n_u8(0x0f);
const int32x4_t mzero = vdupq_n_s32(0);
float sumf = 0.0f;
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
__builtin_prefetch(&x[i + 2], 0, 0);
__builtin_prefetch(&y[i + 2], 0, 0);
}
const float d = y[i].d * h2f(x[i].d);
const float dmin = y[i].d * h2f(x[i].dmin);
const int16x8_t q8sums = vpaddq_s16(vld1q_s16(y[i].bsums), vld1q_s16(y[i].bsums + 8));
std::memcpy(utmp, x[i].scales, 12);
uint32x2_t mins8 = {0, 0};
mins8 = vset_lane_u32(utmp[1] & kmask1, mins8, 0);
mins8 = vset_lane_u32(((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4), mins8, 1);
utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4);
utmp[0] &= kmask1;
const int16x8_t mins = vreinterpretq_s16_u16(vmovl_u8(vreinterpret_u8_u32(mins8)));
const int32x4_t prod = vaddq_s32(vmull_s16(vget_low_s16(q8sums), vget_low_s16(mins)),
vmull_s16(vget_high_s16(q8sums), vget_high_s16(mins)));
sumf -= dmin * vaddvq_s32(prod);
const uint8_t* scales = (const uint8_t*) utmp;
const uint8_t* STRATA_RESTRICT q4 = x[i].qs;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
int32x4_t vsum1 = mzero;
int32x4_t vsum2 = mzero;
for (int j = 0; j < QK_K / 64; ++j) {
const uint8x16x2_t q4bits = vld1q_u8_x2(q4);
q4 += 32;
const int8x16x4_t q8b = vld1q_s8_x4(q8);
q8 += 64;
const int8x16_t q4l0 = vreinterpretq_s8_u8(vandq_u8(q4bits.val[0], m4b));
const int8x16_t q4l1 = vreinterpretq_s8_u8(vandq_u8(q4bits.val[1], m4b));
const int8x16_t q4h0 = vreinterpretq_s8_u8(vshrq_n_u8(q4bits.val[0], 4));
const int8x16_t q4h1 = vreinterpretq_s8_u8(vshrq_n_u8(q4bits.val[1], 4));
const int32x4_t p1 = vdotq_s32(vdotq_s32(mzero, q4l0, q8b.val[0]), q4l1, q8b.val[1]);
const int32x4_t p2 = vdotq_s32(vdotq_s32(mzero, q4h0, q8b.val[2]), q4h1, q8b.val[3]);
vsum1 = vmlaq_n_s32(vsum1, p1, (int32_t) scales[2 * j + 0]);
vsum2 = vmlaq_n_s32(vsum2, p2, (int32_t) scales[2 * j + 1]);
}
sumf += d * (float) (vaddvq_s32(vsum1) + vaddvq_s32(vsum2));
}
*s = sumf;
}
// Vector-accumulated NEON dotprod Q5_K x Q8_K (bit-exact).
void dot_q5_K_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_q5_K* STRATA_RESTRICT x = (const block_q5_K*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
static constexpr uint32_t kmask1 = 0x3f3f3f3f;
static constexpr uint32_t kmask2 = 0x0f0f0f0f;
static constexpr uint32_t kmask3 = 0x03030303;
uint32_t utmp[4];
const uint8x16_t m4b = vdupq_n_u8(0x0f);
const uint8x16_t mone = vdupq_n_u8(1);
const uint8x16_t mtwo = vdupq_n_u8(2);
const int32x4_t mzero = vdupq_n_s32(0);
float sumf = 0.0f;
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
__builtin_prefetch(&x[i + 2], 0, 0);
__builtin_prefetch(&y[i + 2], 0, 0);
}
const float d = y[i].d * h2f(x[i].d);
const float dmin = y[i].d * h2f(x[i].dmin);
const int16x8_t q8sums = vpaddq_s16(vld1q_s16(y[i].bsums), vld1q_s16(y[i].bsums + 8));
std::memcpy(utmp, x[i].scales, 12);
utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4);
const uint32_t uaux = utmp[1] & kmask1;
utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4);
utmp[2] = uaux;
utmp[0] &= kmask1;
const uint8x8_t mins8 = vld1_u8((const uint8_t*) utmp + 8);
const int16x8_t mins = vreinterpretq_s16_u16(vmovl_u8(mins8));
const int32x4_t prod = vaddq_s32(vmull_s16(vget_low_s16(q8sums), vget_low_s16(mins)),
vmull_s16(vget_high_s16(q8sums), vget_high_s16(mins)));
const int32_t sumi_mins = vaddvq_s32(prod);
const uint8_t* scales = (const uint8_t*) utmp;
const uint8_t* STRATA_RESTRICT q5 = x[i].qs;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
uint8x16x2_t qhbits = vld1q_u8_x2(x[i].qh);
int32x4_t vsum1 = mzero;
int32x4_t vsum2 = mzero;
for (int j = 0; j < QK_K / 64; ++j) {
const uint8x16x2_t q5bits = vld1q_u8_x2(q5);
q5 += 32;
const int8x16x4_t q8b = vld1q_s8_x4(q8);
q8 += 64;
const uint8x16_t h0 = vshlq_n_u8(vandq_u8(mone, qhbits.val[0]), 4);
const uint8x16_t h1 = vshlq_n_u8(vandq_u8(mone, qhbits.val[1]), 4);
const uint8x16_t h2 = vshlq_n_u8(vandq_u8(mtwo, qhbits.val[0]), 3);
const uint8x16_t h3 = vshlq_n_u8(vandq_u8(mtwo, qhbits.val[1]), 3);
qhbits.val[0] = vshrq_n_u8(qhbits.val[0], 2);
qhbits.val[1] = vshrq_n_u8(qhbits.val[1], 2);
const int8x16_t q5_0 = vreinterpretq_s8_u8(vorrq_u8(vandq_u8(q5bits.val[0], m4b), h0));
const int8x16_t q5_1 = vreinterpretq_s8_u8(vorrq_u8(vandq_u8(q5bits.val[1], m4b), h1));
const int8x16_t q5_2 = vreinterpretq_s8_u8(vorrq_u8(vshrq_n_u8(q5bits.val[0], 4), h2));
const int8x16_t q5_3 = vreinterpretq_s8_u8(vorrq_u8(vshrq_n_u8(q5bits.val[1], 4), h3));
const int32x4_t p1 = vdotq_s32(vdotq_s32(mzero, q5_0, q8b.val[0]), q5_1, q8b.val[1]);
const int32x4_t p2 = vdotq_s32(vdotq_s32(mzero, q5_2, q8b.val[2]), q5_3, q8b.val[3]);
vsum1 = vmlaq_n_s32(vsum1, p1, (int32_t) scales[2 * j + 0]);
vsum2 = vmlaq_n_s32(vsum2, p2, (int32_t) scales[2 * j + 1]);
}
const int32_t sumi = vaddvq_s32(vaddq_s32(vsum1, vsum2));
sumf += d * (float) sumi - dmin * (float) sumi_mins;
}
*s = sumf;
}
// Vector-accumulated NEON dotprod IQ4_XS x Q8_K (bit-exact).
void dot_iq4_xs_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_iq4_xs* STRATA_RESTRICT x = (const block_iq4_xs*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
const int8x16_t values = vld1q_s8(kvalues_iq4nl);
const uint8x16_t m4b = vdupq_n_u8(0x0f);
const int32x4_t mzero = vdupq_n_s32(0);
float sumf = 0.0f;
for (int ibl = 0; ibl < nb; ++ibl) {
if (ibl + 2 < nb) {
__builtin_prefetch(&x[ibl + 2], 0, 0);
__builtin_prefetch(&y[ibl + 2], 0, 0);
}
const int8_t* STRATA_RESTRICT q8 = y[ibl].qs;
const uint8_t* STRATA_RESTRICT q4 = x[ibl].qs;
uint16_t h = x[ibl].scales_h;
int32x4_t vsum1 = mzero;
int32x4_t vsum2 = mzero;
for (int ib = 0; ib < QK_K / 64; ++ib) {
const uint8x16x2_t q4bits = vld1q_u8_x2(q4);
q4 += 32;
const int8x16x4_t q8b = vld1q_s8_x4(q8);
q8 += 64;
const int8x16_t q4_0 = vqtbl1q_s8(values, vandq_u8(q4bits.val[0], m4b));
const int8x16_t q4_1 = vqtbl1q_s8(values, vshrq_n_u8(q4bits.val[0], 4));
const int8x16_t q4_2 = vqtbl1q_s8(values, vandq_u8(q4bits.val[1], m4b));
const int8x16_t q4_3 = vqtbl1q_s8(values, vshrq_n_u8(q4bits.val[1], 4));
const int32x4_t p1 = vdotq_s32(vdotq_s32(mzero, q4_0, q8b.val[0]), q4_1, q8b.val[1]);
const int32x4_t p2 = vdotq_s32(vdotq_s32(mzero, q4_2, q8b.val[2]), q4_3, q8b.val[3]);
const int32_t ls1 = ((x[ibl].scales_l[ib] & 0xf) | ((h << 4) & 0x30)) - 32;
const int32_t ls2 = ((x[ibl].scales_l[ib] >> 4) | ((h << 2) & 0x30)) - 32;
h >>= 4;
vsum1 = vmlaq_n_s32(vsum1, p1, ls1);
vsum2 = vmlaq_n_s32(vsum2, p2, ls2);
}
sumf += h2f(x[ibl].d) * y[ibl].d * (float) (vaddvq_s32(vsum1) + vaddvq_s32(vsum2));
}
*s = sumf;
}
// Prefetched NEON dotprod Q8_0 x Q8_0 (bit-exact).
void dot_q8_0_q8_0_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK8_0 == 0);
const int nb = n / QK8_0;
const block_q8_0* STRATA_RESTRICT x = (const block_q8_0*) vx;
const block_q8_0* STRATA_RESTRICT y = (const block_q8_0*) vy;
float32x4_t sumv0 = vdupq_n_f32(0.0f);
float32x4_t sumv1 = vdupq_n_f32(0.0f);
const int32x4_t mzero = vdupq_n_s32(0);
int ib = 0;
for (; ib + 1 < nb; ib += 2) {
if (ib + 4 < nb) {
__builtin_prefetch(&x[ib + 4], 0, 0);
__builtin_prefetch(&y[ib + 4], 0, 0);
}
const block_q8_0* STRATA_RESTRICT x0 = &x[ib + 0];
const block_q8_0* STRATA_RESTRICT x1 = &x[ib + 1];
const block_q8_0* STRATA_RESTRICT y0 = &y[ib + 0];
const block_q8_0* STRATA_RESTRICT y1 = &y[ib + 1];
const int8x16_t x0_0 = vld1q_s8(x0->qs);
const int8x16_t x0_1 = vld1q_s8(x0->qs + 16);
const int8x16_t x1_0 = vld1q_s8(x1->qs);
const int8x16_t x1_1 = vld1q_s8(x1->qs + 16);
const int8x16_t y0_0 = vld1q_s8(y0->qs);
const int8x16_t y0_1 = vld1q_s8(y0->qs + 16);
const int8x16_t y1_0 = vld1q_s8(y1->qs);
const int8x16_t y1_1 = vld1q_s8(y1->qs + 16);
sumv0 = vmlaq_n_f32(sumv0, vcvtq_f32_s32(vaddq_s32(vdotq_s32(mzero, x0_0, y0_0), vdotq_s32(mzero, x0_1, y0_1))),
h2f(x0->d) * h2f(y0->d));
sumv1 = vmlaq_n_f32(sumv1, vcvtq_f32_s32(vaddq_s32(vdotq_s32(mzero, x1_0, y1_0), vdotq_s32(mzero, x1_1, y1_1))),
h2f(x1->d) * h2f(y1->d));
}
float sumf = vaddvq_f32(sumv0) + vaddvq_f32(sumv1);
for (; ib < nb; ++ib) {
int sumi = 0;
for (int j = 0; j < QK8_0; ++j) sumi += x[ib].qs[j] * y[ib].qs[j];
sumf += sumi * (h2f(x[ib].d) * h2f(y[ib].d));
}
*s = sumf;
}
#endif // __ARM_NEON && __ARM_FEATURE_DOTPROD
} // namespace neon
namespace {
#define ENTRY(T, ACT, NAME) {neon::dot_##NAME, Type::T, Type::ACT, Arith::Neon, Isa::Neon, "neon_" #NAME}
#if defined(__ARM_NEON) && defined(__ARM_FEATURE_DOTPROD)
#define ENTRY_OPT(T, ACT, NAME) {neon::dot_##NAME##_opt, Type::T, Type::ACT, Arith::Neon, Isa::Neon, "neon_" #NAME}
#else
#define ENTRY_OPT(T, ACT, NAME) ENTRY(T, ACT, NAME)
#endif
const DotKernel kTable[] = {
ENTRY(Q2_0, Q8_0, q2_0_q8_0), ENTRY(Q4_0, Q8_0, q4_0_q8_0), ENTRY(Q4_1, Q8_1, q4_1_q8_1), ENTRY(Q5_0, Q8_0, q5_0_q8_0),
ENTRY(Q5_1, Q8_1, q5_1_q8_1), ENTRY(Q8_0, Q8_0, q8_0_q8_0), ENTRY(IQ4_NL, Q8_0, iq4_nl_q8_0), ENTRY(MXFP4, Q8_0, mxfp4_q8_0),
ENTRY(NVFP4, Q8_0, nvfp4_q8_0), ENTRY(Q2_K, Q8_K, q2_K_q8_K), ENTRY(Q3_K, Q8_K, q3_K_q8_K), ENTRY(Q4_K, Q8_K, q4_K_q8_K),
ENTRY(Q5_K, Q8_K, q5_K_q8_K), ENTRY(Q6_K, Q8_K, q6_K_q8_K), ENTRY(IQ1_S, Q8_K, iq1_s_q8_K), ENTRY(IQ1_M, Q8_K, iq1_m_q8_K),
ENTRY(Q2_0, Q8_0, q2_0_q8_0), ENTRY(Q4_0, Q8_0, q4_0_q8_0), ENTRY(Q4_1, Q8_1, q4_1_q8_1), ENTRY(Q5_0, Q8_0, q5_0_q8_0),
ENTRY(Q5_1, Q8_1, q5_1_q8_1), ENTRY_OPT(Q8_0, Q8_0, q8_0_q8_0), ENTRY(IQ4_NL, Q8_0, iq4_nl_q8_0), ENTRY(MXFP4, Q8_0, mxfp4_q8_0),
ENTRY(NVFP4, Q8_0, nvfp4_q8_0), ENTRY(Q2_K, Q8_K, q2_K_q8_K), ENTRY(Q3_K, Q8_K, q3_K_q8_K), ENTRY_OPT(Q4_K, Q8_K, q4_K_q8_K),
ENTRY_OPT(Q5_K, Q8_K, q5_K_q8_K), ENTRY(Q6_K, Q8_K, q6_K_q8_K), ENTRY(IQ1_S, Q8_K, iq1_s_q8_K), ENTRY(IQ1_M, Q8_K, iq1_m_q8_K),
ENTRY(IQ2_XXS, Q8_K, iq2_xxs_q8_K), ENTRY(IQ2_XS, Q8_K, iq2_xs_q8_K), ENTRY(IQ2_S, Q8_K, iq2_s_q8_K),
ENTRY(IQ3_XXS, Q8_K, iq3_xxs_q8_K), ENTRY(IQ3_S, Q8_K, iq3_s_q8_K), ENTRY(IQ4_XS, Q8_K, iq4_xs_q8_K),
ENTRY(IQ3_XXS, Q8_K, iq3_xxs_q8_K), ENTRY(IQ3_S, Q8_K, iq3_s_q8_K), ENTRY_OPT(IQ4_XS, Q8_K, iq4_xs_q8_K),
};
#undef ENTRY_OPT
#undef ENTRY
} // namespace
+8 -6
View File
@@ -40,7 +40,7 @@ int collect_acts(Type act, Arith a, const ActKernel** out, int cap) {
const ActTable tables[] = {
generic_act_table(),
#ifdef STRATA_QUANT_X86_TIERS
avx_act_table(), avx2_act_table(),
avx_act_table(), avx2_act_table(), avx512_act_table(),
#endif
#ifdef STRATA_QUANT_ARM_TIERS
neon_act_table(),
@@ -65,12 +65,14 @@ const DotKernel* dot_kernel(Type w, Arith a) noexcept { return dot_kernel(w, a,
const DotX4Kernel* dot_x4_kernel(Type w, Arith a, Isa max_isa) noexcept {
#ifdef STRATA_QUANT_X86_TIERS
const DotX4Table tb = avx512_dot_x4_table();
const DotX4Table tables[] = {avx512_dot_x4_table(), avx2_dot_x4_table()};
const DotX4Kernel* best = nullptr;
for (int i = 0; i < tb.n; ++i) {
const DotX4Kernel& k = tb.v[i];
if (k.weight == w && k.arith == a && (int) k.isa <= (int) max_isa && isa_ok(k.isa)) {
if (!best || (int) k.isa > (int) best->isa) best = &k;
for (const DotX4Table& tb : tables) {
for (int i = 0; i < tb.n; ++i) {
const DotX4Kernel& k = tb.v[i];
if (k.weight == w && k.arith == a && (int) k.isa <= (int) max_isa && isa_ok(k.isa)) {
if (!best || (int) k.isa > (int) best->isa) best = &k;
}
}
}
return best;
+3 -1
View File
@@ -25,10 +25,12 @@ ActTable generic_act_table() noexcept; // act_ref.cpp
#ifdef STRATA_QUANT_X86_TIERS
DotTable avx_dot_table() noexcept; // x86/dot_avx.cpp (Arith::Avx, Isa::Avx1)
DotTable avx2_dot_table() noexcept; // x86/dot_avx2.cpp (Arith::Avx2, Isa::Avx2)
DotX4Table avx2_dot_x4_table() noexcept; // x86/dot_avx2.cpp (4-row shared-activation AVX2 kernels)
ActTable avx_act_table() noexcept; // x86/act_avx.cpp
ActTable avx2_act_table() noexcept; // x86/act_avx2.cpp
ActTable avx512_act_table() noexcept; // x86/act_avx512.cpp (Arith::Avx2 bits in 512-bit lanes, Isa::Avx512)
DotTable avx512_dot_table() noexcept; // x86/dot_avx512.cpp (Arith::Avx2 bits in 512-bit lanes, Isa::Avx512)
DotX4Table avx512_dot_x4_table() noexcept; // x86/dot_avx512.cpp (4-row shared-activation VPDPBUSD kernels)
DotX4Table avx512_dot_x4_table() noexcept; // x86/dot_avx512.cpp (4-row shared-activation VPDPBUSD/VPDPWSSD kernels)
#endif
#ifdef STRATA_QUANT_ARM_TIERS
+201
View File
@@ -0,0 +1,201 @@
// Copyright (c) 2026 Niko1221 and the Strata contributors
// SPDX-License-Identifier: MIT
//
// src/quant/x86/act_avx512.cpp - isolated AVX-512 activation quantizers for the Avx2 contract (Q8_0, Q8_1, Q8_K).
// Compiled strictly in this AVX-512 TU so act_avx2.cpp emits 0 EVEX/ZMM instructions (safe for Alder/Raptor Lake).
// Runtime-gated behind Isa::Avx512 (F/DQ/BW/VL + VNNI); bit-exact to act_avx2.cpp / quantize_q8_K_ref.
#include "tier_common.hpp"
#include "../registry.hpp"
#include "strata/quant/act.hpp"
#if defined(_MSC_VER) && !defined(__clang__) && defined(__AVX512VL__) && !defined(__AVX512VNNI__)
#define __AVX512VNNI__ 1
#endif
#if !defined(_MSC_VER) && (!defined(__AVX512F__) || !defined(__AVX512BW__) || !defined(__AVX512VL__))
#error "act_avx512.cpp needs AVX-512 F, BW, and VL"
#endif
namespace strata::quant {
namespace avx512 {
static inline int q8k_ctz32_avx512(unsigned int m) {
#if defined(_MSC_VER)
unsigned long idx = 0;
_BitScanForward(&idx, m);
return (int) idx;
#else
return __builtin_ctz(m);
#endif
}
void quantize_q8_0_avx512(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(QK8_0 == 32);
assert(k % QK8_0 == 0);
const int64_t nb = k / QK8_0;
block_q8_0* STRATA_RESTRICT y = (block_q8_0*) vy;
const __m512 absm = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff));
for (int64_t i = 0; i < nb; ++i, x += 32) {
if (i + 4 < nb) _mm_prefetch((const char*) (x + 128), _MM_HINT_T0);
const __m512 v0 = _mm512_loadu_ps(x);
const __m512 v1 = _mm512_loadu_ps(x + 16);
const __m512 maxAbs = _mm512_max_ps(_mm512_and_ps(v0, absm), _mm512_and_ps(v1, absm));
const __m256 m8 = _mm256_max_ps(_mm512_castps512_ps256(maxAbs), _mm512_extractf32x8_ps(maxAbs, 1));
__m128 m4 = _mm_max_ps(_mm256_extractf128_ps(m8, 1), _mm256_castps256_ps128(m8));
m4 = _mm_max_ps(m4, _mm_movehl_ps(m4, m4));
m4 = _mm_max_ss(m4, _mm_movehdup_ps(m4));
const float maxScalar = _mm_cvtss_f32(m4);
const float d = maxScalar / 127.f;
y[i].d = f2h(d);
const float id = (maxScalar != 0.0f) ? 127.f / maxScalar : 0.0f;
const __m512 mul = _mm512_set1_ps(id);
const __m512 r0 = _mm512_roundscale_ps(_mm512_mul_ps(v0, mul), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
const __m512 r1 = _mm512_roundscale_ps(_mm512_mul_ps(v1, mul), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC);
const __m128i b0 = _mm512_cvtsepi32_epi8(_mm512_cvtps_epi32(r0));
const __m128i b1 = _mm512_cvtsepi32_epi8(_mm512_cvtps_epi32(r1));
_mm_storeu_si128((__m128i*) (y[i].qs + 0), b0);
_mm_storeu_si128((__m128i*) (y[i].qs + 16), b1);
}
}
void quantize_q8_1_avx512(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(QK8_1 == 32);
assert(k % QK8_1 == 0);
const int64_t nb = k / QK8_1;
block_q8_1* STRATA_RESTRICT y = (block_q8_1*) vy;
const __m512 absm = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff));
for (int64_t i = 0; i < nb; ++i, x += 32) {
if (i + 4 < nb) _mm_prefetch((const char*) (x + 128), _MM_HINT_T0);
const __m512 v0 = _mm512_loadu_ps(x);
const __m512 v1 = _mm512_loadu_ps(x + 16);
const __m512 maxAbs = _mm512_max_ps(_mm512_and_ps(v0, absm), _mm512_and_ps(v1, absm));
const __m256 m8 = _mm256_max_ps(_mm512_castps512_ps256(maxAbs), _mm512_extractf32x8_ps(maxAbs, 1));
__m128 m4 = _mm_max_ps(_mm256_extractf128_ps(m8, 1), _mm256_castps256_ps128(m8));
m4 = _mm_max_ps(m4, _mm_movehl_ps(m4, m4));
m4 = _mm_max_ss(m4, _mm_movehdup_ps(m4));
const float maxScalar = _mm_cvtss_f32(m4);
const float d = maxScalar / 127.f;
y[i].d = f2h(d);
const float id = (maxScalar != 0.0f) ? 127.f / maxScalar : 0.0f;
const __m512 mul = _mm512_set1_ps(id);
const __m512i i0 = _mm512_cvtps_epi32(_mm512_roundscale_ps(_mm512_mul_ps(v0, mul), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC));
const __m512i i1 = _mm512_cvtps_epi32(_mm512_roundscale_ps(_mm512_mul_ps(v1, mul), _MM_FROUND_TO_NEAREST_INT | _MM_FROUND_NO_EXC));
const int sumi = _mm512_reduce_add_epi32(_mm512_add_epi32(i0, i1));
y[i].s = f2h(d * (float) sumi);
_mm_storeu_si128((__m128i*) (y[i].qs + 0), _mm512_cvtsepi32_epi8(i0));
_mm_storeu_si128((__m128i*) (y[i].qs + 16), _mm512_cvtsepi32_epi8(i1));
}
}
void quantize_q8_K_avx512(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
assert(k % QK_K == 0);
block_q8_K* STRATA_RESTRICT y = (block_q8_K*) vy;
const int64_t nb = k / QK_K;
const __m512 absm = _mm512_castsi512_ps(_mm512_set1_epi32(0x7fffffff));
const __m512 magic = _mm512_set1_ps(12582912.f);
const __m512i mant = _mm512_set1_epi32(0x007fffff);
const __m512i off = _mm512_set1_epi32(0x00400000);
const __m512i c127 = _mm512_set1_epi32(127);
const __m512i sign80 = _mm512_set1_epi8((char) 0x80);
const __m512i zero = _mm512_setzero_si512();
for (int64_t i = 0; i < nb; ++i, x += QK_K) {
if (i + 1 < nb) {
_mm_prefetch((const char*) (x + QK_K), _MM_HINT_T0);
_mm_prefetch((const char*) (x + QK_K + 64), _MM_HINT_T0);
_mm_prefetch((const char*) (x + QK_K + 128), _MM_HINT_T0);
_mm_prefetch((const char*) (x + QK_K + 192), _MM_HINT_T0);
}
// 4x ZMM max(abs(x)): 4 iterations cover all 256 floats
__m512 m0 = _mm512_setzero_ps();
__m512 m1 = _mm512_setzero_ps();
__m512 m2 = _mm512_setzero_ps();
__m512 m3 = _mm512_setzero_ps();
for (int j = 0; j < QK_K; j += 64) {
m0 = _mm512_max_ps(m0, _mm512_and_ps(_mm512_loadu_ps(x + j + 0), absm));
m1 = _mm512_max_ps(m1, _mm512_and_ps(_mm512_loadu_ps(x + j + 16), absm));
m2 = _mm512_max_ps(m2, _mm512_and_ps(_mm512_loadu_ps(x + j + 32), absm));
m3 = _mm512_max_ps(m3, _mm512_and_ps(_mm512_loadu_ps(x + j + 48), absm));
}
const __m512 m = _mm512_max_ps(_mm512_max_ps(m0, m1), _mm512_max_ps(m2, m3));
const float amax = _mm512_reduce_max_ps(m);
if (!amax) {
y[i].d = 0;
std::memset(y[i].qs, 0, QK_K);
continue;
}
// Exact first-occurrence sign scan matching q8_K_ref (`if (ax > amax)`)
float mx = 0.f;
const __m512 va = _mm512_set1_ps(amax);
for (int j = 0; j < QK_K; j += 32) {
const unsigned int m0k = (unsigned int) _mm512_cmp_ps_mask(_mm512_and_ps(_mm512_loadu_ps(x + j + 0), absm), va, _CMP_EQ_OQ);
const unsigned int m1k = (unsigned int) _mm512_cmp_ps_mask(_mm512_and_ps(_mm512_loadu_ps(x + j + 16), absm), va, _CMP_EQ_OQ);
const unsigned int msk = m0k | (m1k << 16);
if (msk) {
mx = x[j + q8k_ctz32_avx512(msk)];
break;
}
}
const float iscale = -127.f / mx;
const __m512 vis = _mm512_set1_ps(iscale);
for (int j = 0; j < QK_K; j += 64) {
__m128i b[4];
for (int q = 0; q < 4; ++q) {
__m512 p = _mm512_mul_ps(vis, _mm512_loadu_ps(x + j + 16 * q));
#if defined(__GNUC__)
// Keep multiply rounded before add to match scalar nearest_int(iscale * x) bit-for-bit
__asm__("" : "+v"(p));
#endif
const __m512 t = _mm512_add_ps(p, magic);
const __m512i vi = _mm512_min_epi32(_mm512_sub_epi32(_mm512_and_si512(_mm512_castps_si512(t), mant), off), c127);
// VPMOVDB truncates each int32 to its low 8 bits in exact order (matches int8_t qs = MIN(127, v))
b[q] = _mm512_cvtepi32_epi8(vi);
}
const __m256i p256_lo = _mm256_inserti128_si256(_mm256_castsi128_si256(b[0]), b[1], 1);
const __m256i p256_hi = _mm256_inserti128_si256(_mm256_castsi128_si256(b[2]), b[3], 1);
const __m512i p512 = _mm512_inserti64x4(_mm512_castsi256_si512(p256_lo), p256_hi, 1);
_mm512_storeu_si512((__m512i*) (y[i].qs + j), p512);
// Compute all 4 16-byte signed sub-block sums in one ZMM VPSADBW
const __m512i sad = _mm512_sad_epu8(_mm512_xor_si512(p512, sign80), zero);
const __m256i slo = _mm512_castsi512_si256(sad);
const __m256i shi = _mm512_extracti64x4_epi64(sad, 1);
const __m128i s0 = _mm256_castsi256_si128(slo);
const __m128i s1 = _mm256_extracti128_si256(slo, 1);
const __m128i s2 = _mm256_castsi256_si128(shi);
const __m128i s3 = _mm256_extracti128_si256(shi, 1);
y[i].bsums[j / 16 + 0] = (int16_t) (_mm_cvtsi128_si32(s0) + _mm_extract_epi32(s0, 2) - 2048);
y[i].bsums[j / 16 + 1] = (int16_t) (_mm_cvtsi128_si32(s1) + _mm_extract_epi32(s1, 2) - 2048);
y[i].bsums[j / 16 + 2] = (int16_t) (_mm_cvtsi128_si32(s2) + _mm_extract_epi32(s2, 2) - 2048);
y[i].bsums[j / 16 + 3] = (int16_t) (_mm_cvtsi128_si32(s3) + _mm_extract_epi32(s3, 2) - 2048);
}
y[i].d = 1 / iscale;
}
}
} // namespace avx512
namespace {
const ActKernel kTable[] = {
{avx512::quantize_q8_0_avx512, Type::Q8_0, Arith::Avx2, Isa::Avx512, "avx512_q8_0"},
{avx512::quantize_q8_1_avx512, Type::Q8_1, Arith::Avx2, Isa::Avx512, "avx512_q8_1"},
{avx512::quantize_q8_K_avx512, Type::Q8_K, Arith::Avx2, Isa::Avx512, "avx512_q8_K"},
};
} // namespace
ActTable avx512_act_table() noexcept { return {kTable, (int) (sizeof kTable / sizeof kTable[0])}; }
} // namespace strata::quant
+573 -8
View File
@@ -1,5 +1,9 @@
// src/quant/x86/dot_avx2.cpp - the Avx2 contract: ggml-cpu's dot products as its AVX2 + FMA + F16C flavour compiles them (the shipped release flavour).
// Compiled with -mavx2 -mfma -mf16c (/arch:AVX2). Types ggml has no SIMD branch for (Q2_0) run the Generic code under this contract.
// Copyright (c) 2026 Niko1221 and the Strata contributors
// SPDX-License-Identifier: MIT
//
// src/quant/x86/dot_avx2.cpp - the Avx2 contract: ggml-cpu's dot products + bit-exact optimized AVX2 kernels for
// Q4_K, Q5_K, Q6_K, Q8_0, IQ4_XS, IQ3_XXS (dual accumulators, unrolled shifts, bit-3 sign LUT, L1 prefetching,
// and 4-row shared-activation AVX2 dot_x4 kernels). Strictly AVX2+FMA+F16C only: 0 EVEX/ZMM instructions.
#include "tier_common.hpp"
#include "../generic.hpp"
@@ -12,22 +16,583 @@ namespace avx2 {
#include "x86_helpers.inc"
#include "x86_dots.inc"
// ---- Bit-exact optimized AVX2 cold-expert dots (0 EVEX/ZMM instructions, 0 ULP diff vs x86_dots.inc) ----
void dot_q8_0_q8_0_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK8_0 == 0);
const int nb = n / QK8_0;
const block_q8_0* STRATA_RESTRICT x = (const block_q8_0*) vx;
const block_q8_0* STRATA_RESTRICT y = (const block_q8_0*) vy;
const __m256i ones = _mm256_set1_epi16(1);
__m256 acc = _mm256_setzero_ps();
int ib = 0;
for (; ib + 1 < nb; ib += 2) {
if (ib + 4 < nb) {
_mm_prefetch((const char*) &x[ib + 4], _MM_HINT_T0);
_mm_prefetch((const char*) &y[ib + 4], _MM_HINT_T0);
}
const __m256 d0 = _mm256_set1_ps(h2f(x[ib + 0].d) * h2f(y[ib + 0].d));
const __m256 d1 = _mm256_set1_ps(h2f(x[ib + 1].d) * h2f(y[ib + 1].d));
const __m256i qx0 = _mm256_loadu_si256((const __m256i*) x[ib + 0].qs);
const __m256i qy0 = _mm256_loadu_si256((const __m256i*) y[ib + 0].qs);
const __m256i qx1 = _mm256_loadu_si256((const __m256i*) x[ib + 1].qs);
const __m256i qy1 = _mm256_loadu_si256((const __m256i*) y[ib + 1].qs);
const __m256i p16_0 = _mm256_maddubs_epi16(_mm256_sign_epi8(qx0, qx0), _mm256_sign_epi8(qy0, qx0));
const __m256i p16_1 = _mm256_maddubs_epi16(_mm256_sign_epi8(qx1, qx1), _mm256_sign_epi8(qy1, qx1));
const __m256 q0 = _mm256_cvtepi32_ps(_mm256_madd_epi16(ones, p16_0));
const __m256 q1 = _mm256_cvtepi32_ps(_mm256_madd_epi16(ones, p16_1));
acc = _mm256_fmadd_ps(d0, q0, acc);
acc = _mm256_fmadd_ps(d1, q1, acc);
}
for (; ib < nb; ++ib) {
const __m256 d = _mm256_set1_ps(h2f(x[ib].d) * h2f(y[ib].d));
const __m256i qx = _mm256_loadu_si256((const __m256i*) x[ib].qs);
const __m256i qy = _mm256_loadu_si256((const __m256i*) y[ib].qs);
const __m256i p16 = _mm256_maddubs_epi16(_mm256_sign_epi8(qx, qx), _mm256_sign_epi8(qy, qx));
acc = _mm256_fmadd_ps(d, _mm256_cvtepi32_ps(_mm256_madd_epi16(ones, p16)), acc);
}
*s = hsum_float_8(acc);
}
void dot_q4_K_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_q4_K* STRATA_RESTRICT x = (const block_q4_K*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
static constexpr uint32_t kmask1 = 0x3f3f3f3f;
static constexpr uint32_t kmask2 = 0x0f0f0f0f;
static constexpr uint32_t kmask3 = 0x03030303;
uint32_t utmp[4];
const __m256i m4 = _mm256_set1_epi8(0x0F);
__m256 acc = _mm256_setzero_ps();
__m128 acc_m = _mm_setzero_ps();
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
_mm_prefetch((const char*) &x[i + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[i + 2], _MM_HINT_T0);
}
const float d = y[i].d * h2f(x[i].d);
const float dmin = -y[i].d * h2f(x[i].dmin);
std::memcpy(utmp, x[i].scales, 12);
utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4);
const uint32_t uaux = utmp[1] & kmask1;
utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4);
utmp[2] = uaux;
utmp[0] &= kmask1;
const uint8_t* STRATA_RESTRICT q4 = x[i].qs;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
const __m256i mins_and_scales = _mm256_cvtepu8_epi16(_mm_set_epi32(utmp[3], utmp[2], utmp[1], utmp[0]));
const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y[i].bsums);
const __m128i q8s = _mm_hadd_epi16(_mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1));
const __m128i prod = _mm_madd_epi16(_mm256_extracti128_si256(mins_and_scales, 1), q8s);
acc_m = _mm_fmadd_ps(_mm_set1_ps(dmin), _mm_cvtepi32_ps(prod), acc_m);
const __m128i sc128 = _mm256_castsi256_si128(mins_and_scales);
const __m256i scales = MM256_SET_M128I(sc128, sc128);
__m256i sumi0 = _mm256_setzero_si256();
__m256i sumi1 = _mm256_setzero_si256();
for (int j = 0; j < QK_K / 64; ++j) {
const __m256i scale_l = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 0));
const __m256i scale_h = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 1));
const __m256i q4bits = _mm256_loadu_si256((const __m256i*) q4);
q4 += 32;
const __m256i q4l = _mm256_and_si256(q4bits, m4);
const __m256i q4h = _mm256_and_si256(_mm256_srli_epi16(q4bits, 4), m4);
const __m256i q8l = _mm256_loadu_si256((const __m256i*) q8);
const __m256i q8h = _mm256_loadu_si256((const __m256i*) (q8 + 32));
q8 += 64;
const __m256i p16l = _mm256_madd_epi16(scale_l, _mm256_maddubs_epi16(q4l, q8l));
const __m256i p16h = _mm256_madd_epi16(scale_h, _mm256_maddubs_epi16(q4h, q8h));
sumi0 = _mm256_add_epi32(sumi0, p16l);
sumi1 = _mm256_add_epi32(sumi1, p16h);
}
acc = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(_mm256_add_epi32(sumi0, sumi1)), acc);
}
acc_m = _mm_add_ps(acc_m, _mm_movehl_ps(acc_m, acc_m));
acc_m = _mm_add_ss(acc_m, _mm_movehdup_ps(acc_m));
*s = hsum_float_8(acc) + _mm_cvtss_f32(acc_m);
}
void dot_q5_K_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_q5_K* STRATA_RESTRICT x = (const block_q5_K*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
static constexpr uint32_t kmask1 = 0x3f3f3f3f;
static constexpr uint32_t kmask2 = 0x0f0f0f0f;
static constexpr uint32_t kmask3 = 0x03030303;
uint32_t utmp[4];
const __m256i m4 = _mm256_set1_epi8(0x0F);
const __m256i m16 = _mm256_set1_epi8(16);
const __m128i mzero = _mm_setzero_si128();
__m256 acc = _mm256_setzero_ps();
float summs = 0.f;
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
_mm_prefetch((const char*) &x[i + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[i + 2], _MM_HINT_T0);
}
const uint8_t* STRATA_RESTRICT q5 = x[i].qs;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
const float d = y[i].d * h2f(x[i].d);
const float dmin = -y[i].d * h2f(x[i].dmin);
std::memcpy(utmp, x[i].scales, 12);
utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4);
const uint32_t uaux = utmp[1] & kmask1;
utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4);
utmp[2] = uaux;
utmp[0] &= kmask1;
const __m256i mins_and_scales = _mm256_cvtepu8_epi16(_mm_set_epi32(utmp[3], utmp[2], utmp[1], utmp[0]));
const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y[i].bsums);
const __m128i q8s = _mm_hadd_epi16(_mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1));
const __m128i prod = _mm_madd_epi16(_mm256_extracti128_si256(mins_and_scales, 1), q8s);
const __m128i hsum = _mm_hadd_epi32(_mm_hadd_epi32(prod, mzero), mzero);
summs += dmin * _mm_extract_epi32(hsum, 0);
const __m128i sc128 = _mm256_castsi256_si128(mins_and_scales);
const __m256i scales = MM256_SET_M128I(sc128, sc128);
const __m256i hbits = _mm256_loadu_si256((const __m256i*) x[i].qh);
__m256i sumi0 = _mm256_setzero_si256();
__m256i sumi1 = _mm256_setzero_si256();
#define Q5K_AVX2_STEP(J, QH0, QH1) do { \
const __m256i scale_0 = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * (J) + 0)); \
const __m256i scale_1 = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * (J) + 1)); \
const __m256i q5bits = _mm256_loadu_si256((const __m256i*) (q5 + 32 * (J))); \
const __m256i q5_0 = _mm256_or_si256(_mm256_and_si256(q5bits, m4), (QH0)); \
const __m256i q5_1 = _mm256_or_si256(_mm256_and_si256(_mm256_srli_epi16(q5bits, 4), m4), (QH1)); \
const __m256i q8_0 = _mm256_loadu_si256((const __m256i*) (q8 + 64 * (J))); \
const __m256i q8_1 = _mm256_loadu_si256((const __m256i*) (q8 + 64 * (J) + 32)); \
sumi0 = _mm256_add_epi32(sumi0, _mm256_madd_epi16(scale_0, _mm256_maddubs_epi16(q5_0, q8_0))); \
sumi1 = _mm256_add_epi32(sumi1, _mm256_madd_epi16(scale_1, _mm256_maddubs_epi16(q5_1, q8_1))); \
} while (0)
Q5K_AVX2_STEP(0, _mm256_and_si256(_mm256_slli_epi16(hbits, 4), m16), _mm256_and_si256(_mm256_slli_epi16(hbits, 3), m16));
Q5K_AVX2_STEP(1, _mm256_and_si256(_mm256_slli_epi16(hbits, 2), m16), _mm256_and_si256(_mm256_slli_epi16(hbits, 1), m16));
Q5K_AVX2_STEP(2, _mm256_and_si256(hbits, m16), _mm256_and_si256(_mm256_srli_epi16(hbits, 1), m16));
Q5K_AVX2_STEP(3, _mm256_and_si256(_mm256_srli_epi16(hbits, 2), m16), _mm256_and_si256(_mm256_srli_epi16(hbits, 3), m16));
#undef Q5K_AVX2_STEP
acc = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(_mm256_add_epi32(sumi0, sumi1)), acc);
}
*s = hsum_float_8(acc) + summs;
}
void dot_q6_K_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_q6_K* STRATA_RESTRICT x = (const block_q6_K*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
const __m256i m3 = _mm256_set1_epi8(3);
const __m256i m12 = _mm256_set1_epi8(12);
const __m256i m48 = _mm256_set1_epi8(48);
const __m256i m192 = _mm256_set1_epi8(-64);
const __m256i m15 = _mm256_set1_epi8(15);
__m256 acc = _mm256_setzero_ps();
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
_mm_prefetch((const char*) &x[i + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[i + 2], _MM_HINT_T0);
}
const float d = y[i].d * h2f(x[i].d);
const uint8_t* STRATA_RESTRICT q4 = x[i].ql;
const uint8_t* STRATA_RESTRICT qh = x[i].qh;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y[i].bsums);
const __m128i scales = _mm_loadu_si128((const __m128i*) x[i].scales);
const __m256i scales_16 = _mm256_cvtepi8_epi16(scales);
const __m256i q8sclsub = _mm256_slli_epi32(_mm256_madd_epi16(q8sums, scales_16), 5);
__m256i sumi0 = _mm256_setzero_si256();
__m256i sumi1 = _mm256_setzero_si256();
int is = 0;
for (int j = 0; j < QK_K / 128; ++j) {
const __m256i q4bits1 = _mm256_loadu_si256((const __m256i*) q4);
const __m256i q4bits2 = _mm256_loadu_si256((const __m256i*) (q4 + 32));
q4 += 64;
const __m256i q4bitsH = _mm256_loadu_si256((const __m256i*) qh);
qh += 32;
const __m256i q4h_0 = _mm256_slli_epi16(_mm256_and_si256(q4bitsH, m3), 4);
const __m256i q4h_1 = _mm256_slli_epi16(_mm256_and_si256(q4bitsH, m12), 2);
const __m256i q4h_2 = _mm256_and_si256(q4bitsH, m48);
const __m256i q4h_3 = _mm256_srli_epi16(_mm256_and_si256(q4bitsH, m192), 2);
const __m256i q4_0 = _mm256_or_si256(_mm256_and_si256(q4bits1, m15), q4h_0);
const __m256i q4_1 = _mm256_or_si256(_mm256_and_si256(q4bits2, m15), q4h_1);
const __m256i q4_2 = _mm256_or_si256(_mm256_and_si256(_mm256_srli_epi16(q4bits1, 4), m15), q4h_2);
const __m256i q4_3 = _mm256_or_si256(_mm256_and_si256(_mm256_srli_epi16(q4bits2, 4), m15), q4h_3);
const __m256i q8_0 = _mm256_loadu_si256((const __m256i*) (q8 + 0));
const __m256i q8_1 = _mm256_loadu_si256((const __m256i*) (q8 + 32));
const __m256i q8_2 = _mm256_loadu_si256((const __m256i*) (q8 + 64));
const __m256i q8_3 = _mm256_loadu_si256((const __m256i*) (q8 + 96));
q8 += 128;
const __m256i p16_0 = _mm256_maddubs_epi16(q4_0, q8_0);
const __m256i p16_1 = _mm256_maddubs_epi16(q4_1, q8_1);
const __m256i p16_2 = _mm256_maddubs_epi16(q4_2, q8_2);
const __m256i p16_3 = _mm256_maddubs_epi16(q4_3, q8_3);
const __m128i scale_0 = _mm_shuffle_epi8(scales, get_scale_shuffle(is + 0));
const __m128i scale_1 = _mm_shuffle_epi8(scales, get_scale_shuffle(is + 1));
const __m128i scale_2 = _mm_shuffle_epi8(scales, get_scale_shuffle(is + 2));
const __m128i scale_3 = _mm_shuffle_epi8(scales, get_scale_shuffle(is + 3));
is += 4;
sumi0 = _mm256_add_epi32(sumi0, _mm256_add_epi32(_mm256_madd_epi16(_mm256_cvtepi8_epi16(scale_0), p16_0),
_mm256_madd_epi16(_mm256_cvtepi8_epi16(scale_1), p16_1)));
sumi1 = _mm256_add_epi32(sumi1, _mm256_add_epi32(_mm256_madd_epi16(_mm256_cvtepi8_epi16(scale_2), p16_2),
_mm256_madd_epi16(_mm256_cvtepi8_epi16(scale_3), p16_3)));
}
const __m256i sumi = _mm256_sub_epi32(_mm256_add_epi32(sumi0, sumi1), q8sclsub);
acc = _mm256_fmadd_ps(_mm256_broadcast_ss(&d), _mm256_cvtepi32_ps(sumi), acc);
}
*s = hsum_float_8(acc);
}
void dot_iq4_xs_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_iq4_xs* STRATA_RESTRICT x = (const block_iq4_xs*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
// Unsigned |kvalues_iq4nl[k]| LUT + bit-3 sign mask eliminates both vpsignb(x,x) and dual 128-bit shuffles.
static constexpr uint8_t kAbsIq4nl[16] = {127, 104, 83, 65, 49, 35, 22, 10, 1, 13, 25, 38, 53, 69, 89, 113};
const __m256i abs256 = _mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*) kAbsIq4nl));
const __m256i m4b = _mm256_set1_epi8(0x0F);
const __m256i bit3 = _mm256_set1_epi8(0x08);
__m256 accum = _mm256_setzero_ps();
for (int ibl = 0; ibl < nb; ++ibl) {
if (ibl + 2 < nb) {
_mm_prefetch((const char*) &x[ibl + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[ibl + 2], _MM_HINT_T0);
}
const uint8_t* STRATA_RESTRICT qs = x[ibl].qs;
const int8_t* STRATA_RESTRICT q8 = y[ibl].qs;
uint16_t sh = x[ibl].scales_h;
__m256i sumi1 = _mm256_setzero_si256();
__m256i sumi2 = _mm256_setzero_si256();
for (int ib = 0; ib < QK_K / 32; ib += 2) {
const __m128i q4bits_1 = _mm_loadu_si128((const __m128i*) qs);
const __m128i q4bits_2 = _mm_loadu_si128((const __m128i*) (qs + 16));
qs += 32;
const __m256i q8b_1 = _mm256_loadu_si256((const __m256i*) q8);
const __m256i q8b_2 = _mm256_loadu_si256((const __m256i*) (q8 + 32));
q8 += 64;
const __m256i nib_1 = _mm256_and_si256(MM256_SET_M128I(_mm_srli_epi16(q4bits_1, 4), q4bits_1), m4b);
const __m256i nib_2 = _mm256_and_si256(MM256_SET_M128I(_mm_srli_epi16(q4bits_2, 4), q4bits_2), m4b);
const __m256i ax_1 = _mm256_shuffle_epi8(abs256, nib_1);
const __m256i ax_2 = _mm256_shuffle_epi8(abs256, nib_2);
const __m256i neg_1 = _mm256_cmpgt_epi8(bit3, nib_1);
const __m256i neg_2 = _mm256_cmpgt_epi8(bit3, nib_2);
const __m256i sy_1 = _mm256_sub_epi8(_mm256_xor_si256(q8b_1, neg_1), neg_1);
const __m256i sy_2 = _mm256_sub_epi8(_mm256_xor_si256(q8b_2, neg_2), neg_2);
const __m256i p16_1 = _mm256_maddubs_epi16(ax_1, sy_1);
const __m256i p16_2 = _mm256_maddubs_epi16(ax_2, sy_2);
const int16_t ls1 = (int16_t) (((x[ibl].scales_l[ib / 2] & 0xf) | ((sh << 4) & 0x30)) - 32);
const int16_t ls2 = (int16_t) (((x[ibl].scales_l[ib / 2] >> 4) | ((sh << 2) & 0x30)) - 32);
sh >>= 4;
sumi1 = _mm256_add_epi32(sumi1, _mm256_madd_epi16(p16_1, _mm256_set1_epi16(ls1)));
sumi2 = _mm256_add_epi32(sumi2, _mm256_madd_epi16(p16_2, _mm256_set1_epi16(ls2)));
}
accum = _mm256_fmadd_ps(_mm256_set1_ps(h2f(x[ibl].d) * y[ibl].d),
_mm256_cvtepi32_ps(_mm256_add_epi32(sumi1, sumi2)), accum);
}
*s = hsum_float_8(accum);
}
void dot_iq3_xxs_q8_K_opt(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const block_iq3_xxs* STRATA_RESTRICT x = (const block_iq3_xxs*) vx;
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
const uint64_t* signs64 = (const uint64_t*) keven_signs_q2xs;
uint32_t aux32[2];
__m256 accumf = _mm256_setzero_ps();
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
_mm_prefetch((const char*) &x[i + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[i + 2], _MM_HINT_T0);
}
const float d = h2f(x[i].d) * y[i].d;
const uint8_t* STRATA_RESTRICT q3 = x[i].qs;
const uint8_t* STRATA_RESTRICT gas = x[i].qs + QK_K / 4;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
__m256i sumi1 = _mm256_setzero_si256();
__m256i sumi2 = _mm256_setzero_si256();
for (int ib32 = 0; ib32 < QK_K / 32; ib32 += 2) {
const __m256i q8_1 = _mm256_loadu_si256((const __m256i*) q8);
const __m256i q8_2 = _mm256_loadu_si256((const __m256i*) (q8 + 32));
q8 += 64;
const __m256i q2_1 = _mm256_set_epi32(
(int) iq3xxs_grid[q3[ 7]], (int) iq3xxs_grid[q3[ 6]], (int) iq3xxs_grid[q3[ 5]], (int) iq3xxs_grid[q3[ 4]],
(int) iq3xxs_grid[q3[ 3]], (int) iq3xxs_grid[q3[ 2]], (int) iq3xxs_grid[q3[ 1]], (int) iq3xxs_grid[q3[ 0]]);
const __m256i q2_2 = _mm256_set_epi32(
(int) iq3xxs_grid[q3[15]], (int) iq3xxs_grid[q3[14]], (int) iq3xxs_grid[q3[13]], (int) iq3xxs_grid[q3[12]],
(int) iq3xxs_grid[q3[11]], (int) iq3xxs_grid[q3[10]], (int) iq3xxs_grid[q3[ 9]], (int) iq3xxs_grid[q3[ 8]]);
q3 += 16;
std::memcpy(aux32, gas, 8);
gas += 8;
const __m256i s2_1 = _mm256_set_epi64x(
(long long) signs64[(aux32[0] >> 21) & 127], (long long) signs64[(aux32[0] >> 14) & 127],
(long long) signs64[(aux32[0] >> 7) & 127], (long long) signs64[(aux32[0] >> 0) & 127]);
const __m256i s2_2 = _mm256_set_epi64x(
(long long) signs64[(aux32[1] >> 21) & 127], (long long) signs64[(aux32[1] >> 14) & 127],
(long long) signs64[(aux32[1] >> 7) & 127], (long long) signs64[(aux32[1] >> 0) & 127]);
const __m256i dot1 = _mm256_maddubs_epi16(q2_1, _mm256_sign_epi8(q8_1, s2_1));
const __m256i dot2 = _mm256_maddubs_epi16(q2_2, _mm256_sign_epi8(q8_2, s2_2));
const int16_t ls1 = (int16_t) (2 * (aux32[0] >> 28) + 1);
const int16_t ls2 = (int16_t) (2 * (aux32[1] >> 28) + 1);
sumi1 = _mm256_add_epi32(sumi1, _mm256_madd_epi16(dot1, _mm256_set1_epi16(ls1)));
sumi2 = _mm256_add_epi32(sumi2, _mm256_madd_epi16(dot2, _mm256_set1_epi16(ls2)));
}
accumf = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(_mm256_add_epi32(sumi1, sumi2)), accumf);
}
*s = 0.25f * hsum_float_8(accumf);
}
// ---- 4-row shared-activation AVX2 kernels (zero EVEX/ZMM instructions; Alder/Raptor Lake safe) ----
void dot_q4_K_q8_K_x4_avx2(int n, float out[4], const void* STRATA_RESTRICT w_base, size_t row_bytes, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const int nb = n / QK_K;
const uint8_t* wb = (const uint8_t*) w_base;
const block_q4_K* rows[4] = {
(const block_q4_K*) (wb + 0 * row_bytes),
(const block_q4_K*) (wb + 1 * row_bytes),
(const block_q4_K*) (wb + 2 * row_bytes),
(const block_q4_K*) (wb + 3 * row_bytes),
};
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
static constexpr uint32_t kmask1 = 0x3f3f3f3f;
static constexpr uint32_t kmask2 = 0x0f0f0f0f;
static constexpr uint32_t kmask3 = 0x03030303;
const __m256i m4 = _mm256_set1_epi8(0x0F);
__m256 acc[4] = {_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()};
__m128 acc_m[4] = {_mm_setzero_ps(), _mm_setzero_ps(), _mm_setzero_ps(), _mm_setzero_ps()};
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
for (int r = 0; r < 4; ++r) _mm_prefetch((const char*) &rows[r][i + 2], _MM_HINT_T0);
}
const float yd = y[i].d;
const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y[i].bsums);
const __m128i q8s = _mm_hadd_epi16(_mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1));
const __m256i q8v[8] = {
_mm256_loadu_si256((const __m256i*) (y[i].qs + 0)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 32)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 64)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 96)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 128)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 160)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 192)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 224)),
};
for (int r = 0; r < 4; ++r) {
const block_q4_K& bx = rows[r][i];
const float d = yd * h2f(bx.d);
const float dmin = -yd * h2f(bx.dmin);
uint32_t utmp[4];
std::memcpy(utmp, bx.scales, 12);
utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4);
const uint32_t uaux = utmp[1] & kmask1;
utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4);
utmp[2] = uaux;
utmp[0] &= kmask1;
const __m256i mins_and_scales = _mm256_cvtepu8_epi16(_mm_set_epi32(utmp[3], utmp[2], utmp[1], utmp[0]));
const __m128i prod = _mm_madd_epi16(_mm256_extracti128_si256(mins_and_scales, 1), q8s);
acc_m[r] = _mm_fmadd_ps(_mm_set1_ps(dmin), _mm_cvtepi32_ps(prod), acc_m[r]);
const __m128i sc128 = _mm256_castsi256_si128(mins_and_scales);
const __m256i scales = MM256_SET_M128I(sc128, sc128);
__m256i sumi0 = _mm256_setzero_si256();
__m256i sumi1 = _mm256_setzero_si256();
const uint8_t* q4 = bx.qs;
for (int j = 0; j < 4; ++j) {
const __m256i scale_l = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 0));
const __m256i scale_h = _mm256_shuffle_epi8(scales, get_scale_shuffle_k4(2 * j + 1));
const __m256i q4bits = _mm256_loadu_si256((const __m256i*) (q4 + 32 * j));
const __m256i q4l = _mm256_and_si256(q4bits, m4);
const __m256i q4h = _mm256_and_si256(_mm256_srli_epi16(q4bits, 4), m4);
sumi0 = _mm256_add_epi32(sumi0, _mm256_madd_epi16(scale_l, _mm256_maddubs_epi16(q4l, q8v[2 * j + 0])));
sumi1 = _mm256_add_epi32(sumi1, _mm256_madd_epi16(scale_h, _mm256_maddubs_epi16(q4h, q8v[2 * j + 1])));
}
acc[r] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(_mm256_add_epi32(sumi0, sumi1)), acc[r]);
}
}
for (int r = 0; r < 4; ++r) {
acc_m[r] = _mm_add_ps(acc_m[r], _mm_movehl_ps(acc_m[r], acc_m[r]));
acc_m[r] = _mm_add_ss(acc_m[r], _mm_movehdup_ps(acc_m[r]));
out[r] = hsum_float_8(acc[r]) + _mm_cvtss_f32(acc_m[r]);
}
}
void dot_iq4_xs_q8_K_x4_avx2(int n, float out[4], const void* STRATA_RESTRICT w_base, size_t row_bytes, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const int nb = n / QK_K;
const uint8_t* wb = (const uint8_t*) w_base;
const block_iq4_xs* rows[4] = {
(const block_iq4_xs*) (wb + 0 * row_bytes),
(const block_iq4_xs*) (wb + 1 * row_bytes),
(const block_iq4_xs*) (wb + 2 * row_bytes),
(const block_iq4_xs*) (wb + 3 * row_bytes),
};
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
static constexpr uint8_t kAbsIq4nl[16] = {127, 104, 83, 65, 49, 35, 22, 10, 1, 13, 25, 38, 53, 69, 89, 113};
const __m256i abs256 = _mm256_broadcastsi128_si256(_mm_loadu_si128((const __m128i*) kAbsIq4nl));
const __m256i m4b = _mm256_set1_epi8(0x0F);
const __m256i bit3 = _mm256_set1_epi8(0x08);
__m256 accum[4] = {_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()};
for (int ibl = 0; ibl < nb; ++ibl) {
if (ibl + 2 < nb) {
for (int r = 0; r < 4; ++r) _mm_prefetch((const char*) &rows[r][ibl + 2], _MM_HINT_T0);
}
const float yd = y[ibl].d;
const __m256i q8v[8] = {
_mm256_loadu_si256((const __m256i*) (y[ibl].qs + 0)),
_mm256_loadu_si256((const __m256i*) (y[ibl].qs + 32)),
_mm256_loadu_si256((const __m256i*) (y[ibl].qs + 64)),
_mm256_loadu_si256((const __m256i*) (y[ibl].qs + 96)),
_mm256_loadu_si256((const __m256i*) (y[ibl].qs + 128)),
_mm256_loadu_si256((const __m256i*) (y[ibl].qs + 160)),
_mm256_loadu_si256((const __m256i*) (y[ibl].qs + 192)),
_mm256_loadu_si256((const __m256i*) (y[ibl].qs + 224)),
};
for (int r = 0; r < 4; ++r) {
const block_iq4_xs& bx = rows[r][ibl];
const uint8_t* qs = bx.qs;
uint16_t sh = bx.scales_h;
__m256i sumi1 = _mm256_setzero_si256();
__m256i sumi2 = _mm256_setzero_si256();
for (int ib = 0; ib < QK_K / 32; ib += 2) {
const __m128i q4bits_1 = _mm_loadu_si128((const __m128i*) qs);
const __m128i q4bits_2 = _mm_loadu_si128((const __m128i*) (qs + 16));
qs += 32;
const __m256i nib_1 = _mm256_and_si256(MM256_SET_M128I(_mm_srli_epi16(q4bits_1, 4), q4bits_1), m4b);
const __m256i nib_2 = _mm256_and_si256(MM256_SET_M128I(_mm_srli_epi16(q4bits_2, 4), q4bits_2), m4b);
const __m256i ax_1 = _mm256_shuffle_epi8(abs256, nib_1);
const __m256i ax_2 = _mm256_shuffle_epi8(abs256, nib_2);
const __m256i neg_1 = _mm256_cmpgt_epi8(bit3, nib_1);
const __m256i neg_2 = _mm256_cmpgt_epi8(bit3, nib_2);
const __m256i sy_1 = _mm256_sub_epi8(_mm256_xor_si256(q8v[ib + 0], neg_1), neg_1);
const __m256i sy_2 = _mm256_sub_epi8(_mm256_xor_si256(q8v[ib + 1], neg_2), neg_2);
const int16_t ls1 = (int16_t) (((bx.scales_l[ib / 2] & 0xf) | ((sh << 4) & 0x30)) - 32);
const int16_t ls2 = (int16_t) (((bx.scales_l[ib / 2] >> 4) | ((sh << 2) & 0x30)) - 32);
sh >>= 4;
sumi1 = _mm256_add_epi32(sumi1, _mm256_madd_epi16(_mm256_maddubs_epi16(ax_1, sy_1), _mm256_set1_epi16(ls1)));
sumi2 = _mm256_add_epi32(sumi2, _mm256_madd_epi16(_mm256_maddubs_epi16(ax_2, sy_2), _mm256_set1_epi16(ls2)));
}
accum[r] = _mm256_fmadd_ps(_mm256_set1_ps(h2f(bx.d) * yd),
_mm256_cvtepi32_ps(_mm256_add_epi32(sumi1, sumi2)), accum[r]);
}
}
for (int r = 0; r < 4; ++r) out[r] = hsum_float_8(accum[r]);
}
void dot_q8_0_q8_0_x4_avx2(int n, float out[4], const void* STRATA_RESTRICT w_base, size_t row_bytes, const void* STRATA_RESTRICT vy) {
assert(n % QK8_0 == 0);
const int nb = n / QK8_0;
const uint8_t* wb = (const uint8_t*) w_base;
const block_q8_0* rows[4] = {
(const block_q8_0*) (wb + 0 * row_bytes),
(const block_q8_0*) (wb + 1 * row_bytes),
(const block_q8_0*) (wb + 2 * row_bytes),
(const block_q8_0*) (wb + 3 * row_bytes),
};
const block_q8_0* STRATA_RESTRICT y = (const block_q8_0*) vy;
const __m256i ones = _mm256_set1_epi16(1);
__m256 acc[4] = {_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()};
for (int ib = 0; ib < nb; ++ib) {
if (ib + 4 < nb) {
for (int r = 0; r < 4; ++r) _mm_prefetch((const char*) &rows[r][ib + 4], _MM_HINT_T0);
}
const float dy = h2f(y[ib].d);
const __m256i qy = _mm256_loadu_si256((const __m256i*) y[ib].qs);
for (int r = 0; r < 4; ++r) {
const __m256i qx = _mm256_loadu_si256((const __m256i*) rows[r][ib].qs);
const __m256i p16 = _mm256_maddubs_epi16(_mm256_sign_epi8(qx, qx), _mm256_sign_epi8(qy, qx));
acc[r] = _mm256_fmadd_ps(_mm256_set1_ps(h2f(rows[r][ib].d) * dy),
_mm256_cvtepi32_ps(_mm256_madd_epi16(ones, p16)), acc[r]);
}
}
for (int r = 0; r < 4; ++r) out[r] = hsum_float_8(acc[r]);
}
} // namespace avx2
namespace {
#define ENTRY(T, ACT, NAME) {avx2::dot_##NAME, Type::T, Type::ACT, Arith::Avx2, Isa::Avx2, "avx2_" #NAME}
#define ENTRY(T, ACT, NAME) {avx2::dot_##NAME, Type::T, Type::ACT, Arith::Avx2, Isa::Avx2, "avx2_" #NAME}
#define ENTRY_OPT(T, ACT, NAME) {avx2::dot_##NAME##_opt, Type::T, Type::ACT, Arith::Avx2, Isa::Avx2, "avx2_" #NAME}
#define ENTRY_X4(T, ACT, NAME) {avx2::dot_##NAME##_x4_avx2, Type::T, Type::ACT, Arith::Avx2, Isa::Avx2, "avx2_" #NAME "_x4"}
const DotKernel kTable[] = {
ENTRY(Q4_0, Q8_0, q4_0_q8_0), ENTRY(Q4_1, Q8_1, q4_1_q8_1), ENTRY(Q5_0, Q8_0, q5_0_q8_0), ENTRY(Q5_1, Q8_1, q5_1_q8_1),
ENTRY(Q8_0, Q8_0, q8_0_q8_0), ENTRY(IQ4_NL, Q8_0, iq4_nl_q8_0), ENTRY(MXFP4, Q8_0, mxfp4_q8_0), ENTRY(NVFP4, Q8_0, nvfp4_q8_0),
ENTRY(Q2_K, Q8_K, q2_K_q8_K), ENTRY(Q3_K, Q8_K, q3_K_q8_K), ENTRY(Q4_K, Q8_K, q4_K_q8_K), ENTRY(Q5_K, Q8_K, q5_K_q8_K),
ENTRY(Q6_K, Q8_K, q6_K_q8_K), ENTRY(IQ1_S, Q8_K, iq1_s_q8_K), ENTRY(IQ1_M, Q8_K, iq1_m_q8_K), ENTRY(IQ2_XXS, Q8_K, iq2_xxs_q8_K),
ENTRY(IQ2_XS, Q8_K, iq2_xs_q8_K), ENTRY(IQ2_S, Q8_K, iq2_s_q8_K), ENTRY(IQ3_XXS, Q8_K, iq3_xxs_q8_K), ENTRY(IQ3_S, Q8_K, iq3_s_q8_K),
ENTRY(IQ4_XS, Q8_K, iq4_xs_q8_K),
ENTRY_OPT(Q8_0, Q8_0, q8_0_q8_0), ENTRY(IQ4_NL, Q8_0, iq4_nl_q8_0), ENTRY(MXFP4, Q8_0, mxfp4_q8_0), ENTRY(NVFP4, Q8_0, nvfp4_q8_0),
ENTRY(Q2_K, Q8_K, q2_K_q8_K), ENTRY(Q3_K, Q8_K, q3_K_q8_K), ENTRY_OPT(Q4_K, Q8_K, q4_K_q8_K), ENTRY_OPT(Q5_K, Q8_K, q5_K_q8_K),
ENTRY_OPT(Q6_K, Q8_K, q6_K_q8_K), ENTRY(IQ1_S, Q8_K, iq1_s_q8_K), ENTRY(IQ1_M, Q8_K, iq1_m_q8_K), ENTRY(IQ2_XXS, Q8_K, iq2_xxs_q8_K),
ENTRY(IQ2_XS, Q8_K, iq2_xs_q8_K), ENTRY(IQ2_S, Q8_K, iq2_s_q8_K), ENTRY_OPT(IQ3_XXS, Q8_K, iq3_xxs_q8_K), ENTRY(IQ3_S, Q8_K, iq3_s_q8_K),
ENTRY_OPT(IQ4_XS, Q8_K, iq4_xs_q8_K),
{generic::dot_q2_0_q8_0_generic, Type::Q2_0, Type::Q8_0, Arith::Avx2, Isa::Scalar, "avx2_q2_0_generic"},
};
const DotX4Kernel kX4Table[] = {
ENTRY_X4(Q8_0, Q8_0, q8_0_q8_0),
ENTRY_X4(Q4_K, Q8_K, q4_K_q8_K),
ENTRY_X4(IQ4_XS, Q8_K, iq4_xs_q8_K),
};
#undef ENTRY_X4
#undef ENTRY_OPT
#undef ENTRY
} // namespace
DotTable avx2_dot_table() noexcept { return {kTable, (int) (sizeof kTable / sizeof kTable[0])}; }
DotX4Table avx2_dot_x4_table() noexcept { return {kX4Table, (int) (sizeof kX4Table / sizeof kX4Table[0])}; }
} // namespace strata::quant
+568 -170
View File
@@ -3,8 +3,10 @@
//
// src/quant/x86/dot_avx512.cpp - the Avx2 contract on CPUs with AVX-512 F/DQ/BW/VL + VNNI:
// 1. Ported ggml x86 dots whose mul_sum_us8_pairs_float helper takes VPDPBUSD (`__AVX512VNNI__ && __AVX512VL__`), and
// 2. Dedicated 512-bit ZMM AVX512BW + AVX512_VNNI dots for Q4_K, IQ4_XS, IQ3_S, and IQ3_XXS (`*_zmm`), preserving the exact
// 8-lane int32 sums and float superblock accumulation order of dot_avx2.cpp (0 ULP diff against Arith::Avx2, zero VBMI instructions).
// 2. Dedicated 512-bit ZMM AVX512BW + AVX512_VNNI dots for Q4_K, Q5_K, Q6_K, Q8_0, IQ4_XS, IQ3_XXS, and IQ3_S (`*_zmm`),
// using VPDPWSSD/VPDPBUSD, dual accumulators, precomputed 64B scale shuffles, and L1 prefetching while preserving
// the exact 8-lane int32 sums and float superblock accumulation order of dot_avx2.cpp (0 ULP diff, zero VBMI).
// 3. 4-row shared-activation VPDPBUSD/VPDPWSSD (`dot_*_x4`) kernels for Q4_0, MXFP4, Q4_K, Q5_K, Q6_K, Q8_0, IQ4_XS, IQ3_XXS.
// Compiled with the AVX-512 flags of cmake/backends/quant.cmake; only ever called when caps() says AVX-512 F/DQ/BW/VL + VNNI (Isa::Avx512).
#include "tier_common.hpp"
@@ -12,8 +14,8 @@
#include "../registry.hpp"
#include "strata/quant/dot.hpp"
// MSVC cl.exe under /arch:AVX512 exposes _mm256_dpbusd_epi32 and _mm512_dpbusd_epi32 in <immintrin.h> without predefining
// __AVX512VNNI__; define it for this TU (which is gated at runtime by caps() checking CPUID AVX512_VNNI).
// MSVC cl.exe under /arch:AVX512 exposes _mm256_dpbusd_epi32, _mm512_dpbusd_epi32, and _mm512_dpwssd_epi32 in <immintrin.h>
// without predefining __AVX512VNNI__; define it for this TU (gated at runtime by caps() checking CPUID AVX512_VNNI).
#if defined(_MSC_VER) && !defined(__clang__) && defined(__AVX512VL__) && !defined(__AVX512VNNI__)
#define __AVX512VNNI__ 1
#endif
@@ -28,8 +30,69 @@ namespace avx512 {
#include "x86_helpers.inc"
#include "x86_dots.inc"
// Precomputed 64-byte aligned ZMM scale-shuffle masks for Q4_K / Q5_K (eliminates two 256b loads + vinserti64x4 per iter).
alignas(64) static constexpr uint8_t kScaleShuffleK4Zmm[256] = {
0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1, 0, 1,
2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3, 2, 3,
4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5, 4, 5,
6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6, 7,
8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9, 8, 9,
10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11, 10,11,10,11,10,11,10,11,10,11,10,11,10,11,10,11,
12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13, 12,13,12,13,12,13,12,13,12,13,12,13,12,13,12,13,
14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15, 14,15,14,15,14,15,14,15,14,15,14,15,14,15,14,15,
};
// Precomputed 64-byte high-bit test masks for Q5_K (low 32B tests bit 2*j, high 32B tests bit 2*j+1).
static inline __m512i q5k_hbit_mask_zmm(int j) {
const __m256i lo = _mm256_set1_epi8((char) (1u << (2 * j + 0)));
const __m256i hi = _mm256_set1_epi8((char) (1u << (2 * j + 1)));
return _mm512_inserti64x4(_mm512_castsi256_si512(lo), hi, 1);
}
// ---- 512-bit ZMM AVX512BW + AVX512_VNNI bit-exact kernels (Arith::Avx2 float order, zero VBMI instructions) ----
void dot_q8_0_q8_0_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK8_0 == 0);
const int nb = n / QK8_0;
const block_q8_0* STRATA_RESTRICT x = (const block_q8_0*) vx;
const block_q8_0* STRATA_RESTRICT y = (const block_q8_0*) vy;
// 2-way unrolled 256-bit AVX-VNNI: avoids 512-bit cross-lane insert/extract and k-mask transition penalties on Zen 4
// while keeping exact per-block float accumulation order (0 ULP diff vs dot_avx2.cpp).
const __m256i zero256 = _mm256_setzero_si256();
__m256 acc = _mm256_setzero_ps();
int ib = 0;
for (; ib + 1 < nb; ib += 2) {
if (ib + 4 < nb) {
_mm_prefetch((const char*) &x[ib + 4], _MM_HINT_T0);
_mm_prefetch((const char*) &y[ib + 4], _MM_HINT_T0);
}
const __m256 d0 = _mm256_set1_ps(h2f(x[ib + 0].d) * h2f(y[ib + 0].d));
const __m256 d1 = _mm256_set1_ps(h2f(x[ib + 1].d) * h2f(y[ib + 1].d));
const __m256i qx0 = _mm256_loadu_si256((const __m256i*) x[ib + 0].qs);
const __m256i qy0 = _mm256_loadu_si256((const __m256i*) y[ib + 0].qs);
const __m256i qx1 = _mm256_loadu_si256((const __m256i*) x[ib + 1].qs);
const __m256i qy1 = _mm256_loadu_si256((const __m256i*) y[ib + 1].qs);
const __m256 q0 = _mm256_cvtepi32_ps(_mm256_dpbusd_epi32(zero256, _mm256_sign_epi8(qx0, qx0), _mm256_sign_epi8(qy0, qx0)));
const __m256 q1 = _mm256_cvtepi32_ps(_mm256_dpbusd_epi32(zero256, _mm256_sign_epi8(qx1, qx1), _mm256_sign_epi8(qy1, qx1)));
acc = _mm256_fmadd_ps(d0, q0, acc);
acc = _mm256_fmadd_ps(d1, q1, acc);
}
for (; ib < nb; ++ib) {
const __m256 d = _mm256_set1_ps(h2f(x[ib].d) * h2f(y[ib].d));
const __m256i qx = _mm256_loadu_si256((const __m256i*) x[ib].qs);
const __m256i qy = _mm256_loadu_si256((const __m256i*) y[ib].qs);
const __m256 q = _mm256_cvtepi32_ps(_mm256_dpbusd_epi32(zero256, _mm256_sign_epi8(qx, qx), _mm256_sign_epi8(qy, qx)));
acc = _mm256_fmadd_ps(d, q, acc);
}
*s = hsum_float_8(acc);
}
void dot_q4_K_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTRICT vx, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
@@ -43,10 +106,18 @@ void dot_q4_K_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTR
uint32_t utmp[4];
const __m512i m4 = _mm512_set1_epi8(0x0F);
const __m512i shuf0 = _mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 0));
const __m512i shuf1 = _mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 64));
const __m512i shuf2 = _mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 128));
const __m512i shuf3 = _mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 192));
__m256 acc = _mm256_setzero_ps();
__m128 acc_m = _mm_setzero_ps();
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
_mm_prefetch((const char*) &x[i + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[i + 2], _MM_HINT_T0);
}
const float d = y[i].d * h2f(x[i].d);
const float dmin = -y[i].d * h2f(x[i].dmin);
@@ -67,24 +138,25 @@ void dot_q4_K_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTR
acc_m = _mm_fmadd_ps(_mm_set1_ps(dmin), _mm_cvtepi32_ps(prod), acc_m);
const __m512i scales512 = _mm512_broadcast_i32x4(_mm256_castsi256_si128(mins_and_scales));
__m512i sumi512 = _mm512_setzero_si512();
__m512i sumi0 = _mm512_setzero_si512();
__m512i sumi1 = _mm512_setzero_si512();
for (int j = 0; j < QK_K / 64; ++j) {
const __m512i shuf = _mm512_inserti64x4(_mm512_castsi256_si512(get_scale_shuffle_k4(2 * j + 0)),
get_scale_shuffle_k4(2 * j + 1), 1);
const __m512i scale_lh = _mm512_shuffle_epi8(scales512, shuf);
const __m256i q4bits = _mm256_loadu_si256((const __m256i*) q4);
q4 += 32;
const __m512i q4_lh = _mm512_and_si512(
_mm512_inserti64x4(_mm512_castsi256_si512(q4bits), _mm256_srli_epi16(q4bits, 4), 1), m4);
const __m512i q8_lh = _mm512_loadu_si512((const __m512i*) q8);
q8 += 64;
const __m512i p16 = _mm512_maddubs_epi16(q4_lh, q8_lh);
sumi512 = _mm512_add_epi32(sumi512, _mm512_madd_epi16(scale_lh, p16));
}
#define Q4K_ZMM_STEP(J, SHUF, ACC) do { \
const __m512i scale_lh = _mm512_shuffle_epi8(scales512, (SHUF)); \
const __m256i q4bits = _mm256_loadu_si256((const __m256i*) (q4 + 32 * (J))); \
const __m512i q4_lh = _mm512_and_si512( \
_mm512_inserti64x4(_mm512_castsi256_si512(q4bits), _mm256_srli_epi16(q4bits, 4), 1), m4); \
const __m512i q8_lh = _mm512_loadu_si512((const __m512i*) (q8 + 64 * (J))); \
const __m512i p16 = _mm512_maddubs_epi16(q4_lh, q8_lh); \
(ACC) = _mm512_dpwssd_epi32((ACC), scale_lh, p16); \
} while (0)
Q4K_ZMM_STEP(0, shuf0, sumi0);
Q4K_ZMM_STEP(1, shuf1, sumi1);
Q4K_ZMM_STEP(2, shuf2, sumi0);
Q4K_ZMM_STEP(3, shuf3, sumi1);
#undef Q4K_ZMM_STEP
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
const __m256i sumi = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
acc = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc);
}
@@ -107,13 +179,25 @@ void dot_q5_K_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTR
uint32_t utmp[4];
const __m512i m4 = _mm512_set1_epi8(0x0F);
const __m512i m16 = _mm512_set1_epi8(16);
const __m128i mzero = _mm_setzero_si128();
const __m256i m16 = _mm256_set1_epi8(16);
const __m512i shuf0 = _mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 0));
const __m512i shuf1 = _mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 64));
const __m512i shuf2 = _mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 128));
const __m512i shuf3 = _mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 192));
const __m512i hm0 = q5k_hbit_mask_zmm(0);
const __m512i hm1 = q5k_hbit_mask_zmm(1);
const __m512i hm2 = q5k_hbit_mask_zmm(2);
const __m512i hm3 = q5k_hbit_mask_zmm(3);
__m256 acc = _mm256_setzero_ps();
float summs = 0.0f;
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
_mm_prefetch((const char*) &x[i + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[i + 2], _MM_HINT_T0);
}
const uint8_t* STRATA_RESTRICT q5 = x[i].qs;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
@@ -132,33 +216,32 @@ void dot_q5_K_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTR
const __m128i q8s = _mm_hadd_epi16(_mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1));
const __m128i prod = _mm_madd_epi16(_mm256_extracti128_si256(mins_and_scales, 1), q8s);
const __m128i hsum = _mm_hadd_epi32(_mm_hadd_epi32(prod, mzero), mzero);
summs += dmin * _mm_extract_epi32(hsum, 0);
summs = _mm_cvtss_f32(_mm_add_ss(_mm_set_ss(summs),
_mm_mul_ss(_mm_set_ss(dmin), _mm_cvtsi32_ss(_mm_setzero_ps(), _mm_extract_epi32(hsum, 0)))));
const __m512i scales512 = _mm512_broadcast_i32x4(_mm256_castsi256_si128(mins_and_scales));
const __m256i hbits = _mm256_loadu_si256((const __m256i*) x[i].qh);
__m512i sumi512 = _mm512_setzero_si512();
const __m512i hbits512 = _mm512_broadcast_i64x4(_mm256_loadu_si256((const __m256i*) x[i].qh));
__m512i sumi0 = _mm512_setzero_si512();
__m512i sumi1 = _mm512_setzero_si512();
for (int j = 0; j < QK_K / 64; ++j) {
const __m512i shuf = _mm512_inserti64x4(_mm512_castsi256_si512(get_scale_shuffle_k4(2 * j + 0)),
get_scale_shuffle_k4(2 * j + 1), 1);
const __m512i scale_lh = _mm512_shuffle_epi8(scales512, shuf);
const __m256i q5bits = _mm256_loadu_si256((const __m256i*) q5);
q5 += 32;
const __m512i q5_lo = _mm512_and_si512(
_mm512_inserti64x4(_mm512_castsi256_si512(q5bits), _mm256_srli_epi16(q5bits, 4), 1), m4);
const __m256i hb0 = _mm256_and_si256(_mm256_slli_epi16(_mm256_srli_epi16(hbits, 2 * j + 0), 4), m16);
const __m256i hb1 = _mm256_and_si256(_mm256_slli_epi16(_mm256_srli_epi16(hbits, 2 * j + 1), 4), m16);
const __m512i q5_lh = _mm512_or_si512(q5_lo, _mm512_inserti64x4(_mm512_castsi256_si512(hb0), hb1, 1));
const __m512i q8_lh = _mm512_loadu_si512((const __m512i*) q8);
q8 += 64;
const __m512i p16 = _mm512_maddubs_epi16(q5_lh, q8_lh);
sumi512 = _mm512_add_epi32(sumi512, _mm512_madd_epi16(scale_lh, p16));
}
#define Q5K_ZMM_STEP(J, SHUF, HMASK, ACC) do { \
const __m512i scale_lh = _mm512_shuffle_epi8(scales512, (SHUF)); \
const __m256i q5bits = _mm256_loadu_si256((const __m256i*) (q5 + 32 * (J))); \
const __m512i q5_lo = _mm512_and_si512( \
_mm512_inserti64x4(_mm512_castsi256_si512(q5bits), _mm256_srli_epi16(q5bits, 4), 1), m4); \
const __mmask64 hb = _mm512_test_epi8_mask(hbits512, (HMASK)); \
const __m512i q5_lh = _mm512_mask_add_epi8(q5_lo, hb, q5_lo, m16); \
const __m512i q8_lh = _mm512_loadu_si512((const __m512i*) (q8 + 64 * (J))); \
const __m512i p16 = _mm512_maddubs_epi16(q5_lh, q8_lh); \
(ACC) = _mm512_dpwssd_epi32((ACC), scale_lh, p16); \
} while (0)
Q5K_ZMM_STEP(0, shuf0, hm0, sumi0);
Q5K_ZMM_STEP(1, shuf1, hm1, sumi1);
Q5K_ZMM_STEP(2, shuf2, hm2, sumi0);
Q5K_ZMM_STEP(3, shuf3, hm3, sumi1);
#undef Q5K_ZMM_STEP
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
const __m256i sumi = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
acc = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc);
}
@@ -181,6 +264,10 @@ void dot_q6_K_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTR
__m256 acc = _mm256_setzero_ps();
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
_mm_prefetch((const char*) &x[i + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[i + 2], _MM_HINT_T0);
}
const float d = y[i].d * h2f(x[i].d);
const uint8_t* STRATA_RESTRICT q4 = x[i].ql;
const uint8_t* STRATA_RESTRICT qh = x[i].qh;
@@ -191,7 +278,8 @@ void dot_q6_K_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTR
const __m256i scales_16 = _mm256_cvtepi8_epi16(scales);
const __m256i q8sclsub = _mm256_slli_epi32(_mm256_madd_epi16(q8sums, scales_16), 5);
__m512i sumi512 = _mm512_setzero_si512();
__m512i sumi0 = _mm512_setzero_si512();
__m512i sumi1 = _mm512_setzero_si512();
int is = 0;
for (int j = 0; j < QK_K / 128; ++j) {
const __m512i q4bits12 = _mm512_loadu_si512((const __m512i*) q4);
@@ -224,10 +312,11 @@ void dot_q6_K_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RESTR
_mm_shuffle_epi8(scales, get_scale_shuffle(is + 3)), 1);
is += 4;
sumi512 = _mm512_add_epi32(sumi512, _mm512_madd_epi16(_mm512_cvtepi8_epi16(sc_01), p16_01));
sumi512 = _mm512_add_epi32(sumi512, _mm512_madd_epi16(_mm512_cvtepi8_epi16(sc_23), p16_23));
sumi0 = _mm512_dpwssd_epi32(sumi0, _mm512_cvtepi8_epi16(sc_01), p16_01);
sumi1 = _mm512_dpwssd_epi32(sumi1, _mm512_cvtepi8_epi16(sc_23), p16_23);
}
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
__m256i sumi = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
sumi = _mm256_sub_epi32(sumi, q8sclsub);
acc = _mm256_fmadd_ps(_mm256_broadcast_ss(&d), _mm256_cvtepi32_ps(sumi), acc);
@@ -243,9 +332,6 @@ void dot_iq4_xs_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RES
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const int nb = n / QK_K;
// |kvalues_iq4nl[k]|: entries 0..7 are negative (-127..-10), entries 8..15 are positive (+1..+113).
// Testing bit 3 of the 4-bit nibble directly gives the sign mask in parallel with the abs-LUT shuffle,
// eliminating _mm512_abs_epi8 + _mm512_movepi8_mask; _mm512_maddubs_epi16 + _mm512_madd_epi16 eliminates vpmulld.
static constexpr uint8_t kAbsIq4nl[16] = {127, 104, 83, 65, 49, 35, 22, 10, 1, 13, 25, 38, 53, 69, 89, 113};
const __m512i abs_values512 = _mm512_broadcast_i32x4(_mm_loadu_si128((const __m128i*) kAbsIq4nl));
const __m512i m4b = _mm512_set1_epi8(0x0F);
@@ -254,37 +340,41 @@ void dot_iq4_xs_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RES
__m256 accum = _mm256_setzero_ps();
for (int ibl = 0; ibl < nb; ++ibl) {
if (ibl + 2 < nb) {
_mm_prefetch((const char*) &x[ibl + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[ibl + 2], _MM_HINT_T0);
}
const uint8_t* STRATA_RESTRICT qs = x[ibl].qs;
const int8_t* STRATA_RESTRICT q8 = y[ibl].qs;
uint16_t sh = x[ibl].scales_h;
__m512i sumi512 = zero;
__m512i sumi0 = zero;
__m512i sumi1 = zero;
for (int ib = 0; ib < QK_K / 32; ib += 2) {
const __m128i q4bits_1 = _mm_loadu_si128((const __m128i*) qs);
const __m128i q4bits_2 = _mm_loadu_si128((const __m128i*) (qs + 16));
qs += 32;
const __m256i nib_1 = MM256_SET_M128I(_mm_srli_epi16(q4bits_1, 4), q4bits_1);
const __m256i nib_2 = MM256_SET_M128I(_mm_srli_epi16(q4bits_2, 4), q4bits_2);
const __m512i nib512 = _mm512_and_si512(_mm512_inserti64x4(_mm512_castsi256_si512(nib_1), nib_2, 1), m4b);
const __m512i ax = _mm512_shuffle_epi8(abs_values512, nib512);
const __mmask64 neg = _mm512_testn_epi8_mask(nib512, bit3);
const __m512i q8b = _mm512_loadu_si512((const __m512i*) q8);
q8 += 64;
const __m512i sy = _mm512_mask_sub_epi8(q8b, neg, zero, q8b);
const __m512i p16 = _mm512_maddubs_epi16(ax, sy);
const int16_t ls1 = (int16_t) (((x[ibl].scales_l[ib / 2] & 0xf) | ((sh << 4) & 0x30)) - 32);
const int16_t ls2 = (int16_t) (((x[ibl].scales_l[ib / 2] >> 4) | ((sh << 2) & 0x30)) - 32);
sh >>= 4;
const __m512i sc16 = _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_set1_epi16(ls1)),
_mm256_set1_epi16(ls2), 1);
sumi512 = _mm512_add_epi32(sumi512, _mm512_madd_epi16(p16, sc16));
}
#define IQ4XS_ZMM_STEP(IB, ACC) do { \
const __m128i q4bits_1 = _mm_loadu_si128((const __m128i*) (qs + 16 * (IB))); \
const __m128i q4bits_2 = _mm_loadu_si128((const __m128i*) (qs + 16 * (IB) + 16)); \
const __m256i nib_1 = MM256_SET_M128I(_mm_srli_epi16(q4bits_1, 4), q4bits_1); \
const __m256i nib_2 = MM256_SET_M128I(_mm_srli_epi16(q4bits_2, 4), q4bits_2); \
const __m512i nib512 = _mm512_and_si512(_mm512_inserti64x4(_mm512_castsi256_si512(nib_1), nib_2, 1), m4b); \
const __m512i ax = _mm512_shuffle_epi8(abs_values512, nib512); \
const __mmask64 neg = _mm512_testn_epi8_mask(nib512, bit3); \
const __m512i q8b = _mm512_loadu_si512((const __m512i*) (q8 + 32 * (IB))); \
const __m512i sy = _mm512_mask_sub_epi8(q8b, neg, zero, q8b); \
const __m512i p16 = _mm512_maddubs_epi16(ax, sy); \
const int16_t ls1 = (int16_t) (((x[ibl].scales_l[(IB) / 2] & 0xf) | ((sh << 4) & 0x30)) - 32); \
const int16_t ls2 = (int16_t) (((x[ibl].scales_l[(IB) / 2] >> 4) | ((sh << 2) & 0x30)) - 32); \
sh >>= 4; \
const __m512i sc16 = _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_set1_epi16(ls1)), \
_mm256_set1_epi16(ls2), 1); \
(ACC) = _mm512_dpwssd_epi32((ACC), p16, sc16); \
} while (0)
IQ4XS_ZMM_STEP(0, sumi0);
IQ4XS_ZMM_STEP(2, sumi1);
IQ4XS_ZMM_STEP(4, sumi0);
IQ4XS_ZMM_STEP(6, sumi1);
#undef IQ4XS_ZMM_STEP
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
const __m256i sum12 = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
accum = _mm256_fmadd_ps(_mm256_set1_ps(h2f(x[ibl].d) * y[ibl].d), _mm256_cvtepi32_ps(sum12), accum);
}
@@ -304,48 +394,52 @@ void dot_iq3_xxs_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_RE
__m256 accumf = _mm256_setzero_ps();
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
_mm_prefetch((const char*) &x[i + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[i + 2], _MM_HINT_T0);
}
const float d = h2f(x[i].d) * y[i].d;
const uint8_t* STRATA_RESTRICT q3 = x[i].qs;
const uint8_t* STRATA_RESTRICT gas = x[i].qs + QK_K / 4;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
__m512i sumi512 = _mm512_setzero_si512();
__m512i sumi0 = _mm512_setzero_si512();
__m512i sumi1 = _mm512_setzero_si512();
for (int ib32 = 0; ib32 < QK_K / 32; ib32 += 2) {
const __m256i q8_1 = _mm256_loadu_si256((const __m256i*) q8);
const __m256i q8_2 = _mm256_loadu_si256((const __m256i*) (q8 + 32));
q8 += 64;
const __m256i q2_lo = _mm256_set_epi32(
(int) iq3xxs_grid[q3[ 7]], (int) iq3xxs_grid[q3[ 6]], (int) iq3xxs_grid[q3[ 5]], (int) iq3xxs_grid[q3[ 4]],
(int) iq3xxs_grid[q3[ 3]], (int) iq3xxs_grid[q3[ 2]], (int) iq3xxs_grid[q3[ 1]], (int) iq3xxs_grid[q3[ 0]]);
const __m256i q2_hi = _mm256_set_epi32(
(int) iq3xxs_grid[q3[15]], (int) iq3xxs_grid[q3[14]], (int) iq3xxs_grid[q3[13]], (int) iq3xxs_grid[q3[12]],
(int) iq3xxs_grid[q3[11]], (int) iq3xxs_grid[q3[10]], (int) iq3xxs_grid[q3[ 9]], (int) iq3xxs_grid[q3[ 8]]);
const __m512i q2_512 = _mm512_inserti64x4(_mm512_castsi256_si512(q2_lo), q2_hi, 1);
q3 += 16;
std::memcpy(aux32, gas, 8);
gas += 8;
// Use the 64-bit vector sign table (4 loads per 32-elem half, no scalar 8-shift chain or GPR->kmovq stall)
const __m256i s2_1 = _mm256_set_epi64x(
(long long) signs64[(aux32[0] >> 21) & 127], (long long) signs64[(aux32[0] >> 14) & 127],
(long long) signs64[(aux32[0] >> 7) & 127], (long long) signs64[(aux32[0] >> 0) & 127]);
const __m256i s2_2 = _mm256_set_epi64x(
(long long) signs64[(aux32[1] >> 21) & 127], (long long) signs64[(aux32[1] >> 14) & 127],
(long long) signs64[(aux32[1] >> 7) & 127], (long long) signs64[(aux32[1] >> 0) & 127]);
const __m512i q8s_512 = _mm512_inserti64x4(
_mm512_castsi256_si512(_mm256_sign_epi8(q8_1, s2_1)),
_mm256_sign_epi8(q8_2, s2_2), 1);
const __m512i p16 = _mm512_maddubs_epi16(q2_512, q8s_512);
const int16_t s1 = (int16_t) (2 * (aux32[0] >> 28) + 1);
const int16_t s2 = (int16_t) (2 * (aux32[1] >> 28) + 1);
const __m512i sc16 = _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_set1_epi16(s1)),
_mm256_set1_epi16(s2), 1);
sumi512 = _mm512_add_epi32(sumi512, _mm512_madd_epi16(p16, sc16));
}
#define IQ3XXS_ZMM_STEP(IB32, ACC) do { \
const __m256i q8_1 = _mm256_loadu_si256((const __m256i*) (q8 + 32 * (IB32))); \
const __m256i q8_2 = _mm256_loadu_si256((const __m256i*) (q8 + 32 * (IB32) + 32)); \
const uint8_t* p3 = q3 + 8 * (IB32); \
const __m256i q2_lo = _mm256_set_epi32( \
(int) iq3xxs_grid[p3[ 7]], (int) iq3xxs_grid[p3[ 6]], (int) iq3xxs_grid[p3[ 5]], (int) iq3xxs_grid[p3[ 4]], \
(int) iq3xxs_grid[p3[ 3]], (int) iq3xxs_grid[p3[ 2]], (int) iq3xxs_grid[p3[ 1]], (int) iq3xxs_grid[p3[ 0]]); \
const __m256i q2_hi = _mm256_set_epi32( \
(int) iq3xxs_grid[p3[15]], (int) iq3xxs_grid[p3[14]], (int) iq3xxs_grid[p3[13]], (int) iq3xxs_grid[p3[12]], \
(int) iq3xxs_grid[p3[11]], (int) iq3xxs_grid[p3[10]], (int) iq3xxs_grid[p3[ 9]], (int) iq3xxs_grid[p3[ 8]]); \
const __m512i q2_512 = _mm512_inserti64x4(_mm512_castsi256_si512(q2_lo), q2_hi, 1); \
std::memcpy(aux32, gas + 4 * (IB32), 8); \
const __m256i s2_1 = _mm256_set_epi64x( \
(long long) signs64[(aux32[0] >> 21) & 127], (long long) signs64[(aux32[0] >> 14) & 127], \
(long long) signs64[(aux32[0] >> 7) & 127], (long long) signs64[(aux32[0] >> 0) & 127]); \
const __m256i s2_2 = _mm256_set_epi64x( \
(long long) signs64[(aux32[1] >> 21) & 127], (long long) signs64[(aux32[1] >> 14) & 127], \
(long long) signs64[(aux32[1] >> 7) & 127], (long long) signs64[(aux32[1] >> 0) & 127]); \
const __m512i q8s_512 = _mm512_inserti64x4( \
_mm512_castsi256_si512(_mm256_sign_epi8(q8_1, s2_1)), \
_mm256_sign_epi8(q8_2, s2_2), 1); \
const __m512i p16 = _mm512_maddubs_epi16(q2_512, q8s_512); \
const int16_t s1 = (int16_t) (2 * (aux32[0] >> 28) + 1); \
const int16_t s2 = (int16_t) (2 * (aux32[1] >> 28) + 1); \
const __m512i sc16 = _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_set1_epi16(s1)), \
_mm256_set1_epi16(s2), 1); \
(ACC) = _mm512_dpwssd_epi32((ACC), p16, sc16); \
} while (0)
IQ3XXS_ZMM_STEP(0, sumi0);
IQ3XXS_ZMM_STEP(2, sumi1);
IQ3XXS_ZMM_STEP(4, sumi0);
IQ3XXS_ZMM_STEP(6, sumi1);
#undef IQ3XXS_ZMM_STEP
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
const __m256i sum12 = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
accumf = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sum12), accumf);
}
@@ -364,46 +458,51 @@ void dot_iq3_s_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_REST
__m256 accumf = _mm256_setzero_ps();
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
_mm_prefetch((const char*) &x[i + 2], _MM_HINT_T0);
_mm_prefetch((const char*) &y[i + 2], _MM_HINT_T0);
}
const float d = h2f(x[i].d) * y[i].d;
const uint8_t* STRATA_RESTRICT qs = x[i].qs;
const uint8_t* STRATA_RESTRICT qh = x[i].qh;
const uint8_t* STRATA_RESTRICT signs = x[i].signs;
const int8_t* STRATA_RESTRICT q8 = y[i].qs;
__m512i sumi512 = zero;
__m512i sumi0 = zero;
__m512i sumi1 = zero;
for (int ib32 = 0; ib32 < QK_K / 32; ib32 += 2) {
const __m512i q8_512 = _mm512_loadu_si512((const __m512i*) q8);
q8 += 64;
const uint32_t h0 = qh[ib32 + 0];
const uint32_t h1 = qh[ib32 + 1];
const __m256i q2_lo = _mm256_set_epi32(
(int) iq3s_grid[qs[ 7] | ((h0 << 1) & 256u)], (int) iq3s_grid[qs[ 6] | ((h0 << 2) & 256u)],
(int) iq3s_grid[qs[ 5] | ((h0 << 3) & 256u)], (int) iq3s_grid[qs[ 4] | ((h0 << 4) & 256u)],
(int) iq3s_grid[qs[ 3] | ((h0 << 5) & 256u)], (int) iq3s_grid[qs[ 2] | ((h0 << 6) & 256u)],
(int) iq3s_grid[qs[ 1] | ((h0 << 7) & 256u)], (int) iq3s_grid[qs[ 0] | ((h0 << 8) & 256u)]);
const __m256i q2_hi = _mm256_set_epi32(
(int) iq3s_grid[qs[15] | ((h1 << 1) & 256u)], (int) iq3s_grid[qs[14] | ((h1 << 2) & 256u)],
(int) iq3s_grid[qs[13] | ((h1 << 3) & 256u)], (int) iq3s_grid[qs[12] | ((h1 << 4) & 256u)],
(int) iq3s_grid[qs[11] | ((h1 << 5) & 256u)], (int) iq3s_grid[qs[10] | ((h1 << 6) & 256u)],
(int) iq3s_grid[qs[ 9] | ((h1 << 7) & 256u)], (int) iq3s_grid[qs[ 8] | ((h1 << 8) & 256u)]);
const __m512i q2_512 = _mm512_inserti64x4(_mm512_castsi256_si512(q2_lo), q2_hi, 1);
qs += 16;
uint64_t s64;
std::memcpy(&s64, signs, 8);
signs += 8;
const __m512i q8s_512 = _mm512_mask_sub_epi8(q8_512, _cvtu64_mask64(s64), zero, q8_512);
const __m512i p16 = _mm512_maddubs_epi16(q2_512, q8s_512);
const int16_t s1 = (int16_t) (2 * (x[i].scales[ib32 / 2] & 0xf) + 1);
const int16_t s2 = (int16_t) (2 * (x[i].scales[ib32 / 2] >> 4) + 1);
const __m512i sc16 = _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_set1_epi16(s1)),
_mm256_set1_epi16(s2), 1);
sumi512 = _mm512_add_epi32(sumi512, _mm512_madd_epi16(p16, sc16));
}
#define IQ3S_ZMM_STEP(IB32, ACC) do { \
const __m512i q8_512 = _mm512_loadu_si512((const __m512i*) (q8 + 32 * (IB32))); \
const uint8_t* ps = qs + 8 * (IB32); \
const uint32_t h0 = qh[(IB32) + 0]; \
const uint32_t h1 = qh[(IB32) + 1]; \
const __m256i q2_lo = _mm256_set_epi32( \
(int) iq3s_grid[ps[ 7] | ((h0 << 1) & 256u)], (int) iq3s_grid[ps[ 6] | ((h0 << 2) & 256u)], \
(int) iq3s_grid[ps[ 5] | ((h0 << 3) & 256u)], (int) iq3s_grid[ps[ 4] | ((h0 << 4) & 256u)], \
(int) iq3s_grid[ps[ 3] | ((h0 << 5) & 256u)], (int) iq3s_grid[ps[ 2] | ((h0 << 6) & 256u)], \
(int) iq3s_grid[ps[ 1] | ((h0 << 7) & 256u)], (int) iq3s_grid[ps[ 0] | ((h0 << 8) & 256u)]); \
const __m256i q2_hi = _mm256_set_epi32( \
(int) iq3s_grid[ps[15] | ((h1 << 1) & 256u)], (int) iq3s_grid[ps[14] | ((h1 << 2) & 256u)], \
(int) iq3s_grid[ps[13] | ((h1 << 3) & 256u)], (int) iq3s_grid[ps[12] | ((h1 << 4) & 256u)], \
(int) iq3s_grid[ps[11] | ((h1 << 5) & 256u)], (int) iq3s_grid[ps[10] | ((h1 << 6) & 256u)], \
(int) iq3s_grid[ps[ 9] | ((h1 << 7) & 256u)], (int) iq3s_grid[ps[ 8] | ((h1 << 8) & 256u)]); \
const __m512i q2_512 = _mm512_inserti64x4(_mm512_castsi256_si512(q2_lo), q2_hi, 1); \
uint64_t s64; \
std::memcpy(&s64, signs + 4 * (IB32), 8); \
const __m512i q8s_512 = _mm512_mask_sub_epi8(q8_512, _cvtu64_mask64(s64), zero, q8_512); \
const __m512i p16 = _mm512_maddubs_epi16(q2_512, q8s_512); \
const int16_t s1 = (int16_t) (2 * (x[i].scales[(IB32) / 2] & 0xf) + 1); \
const int16_t s2 = (int16_t) (2 * (x[i].scales[(IB32) / 2] >> 4) + 1); \
const __m512i sc16 = _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_set1_epi16(s1)), \
_mm256_set1_epi16(s2), 1); \
(ACC) = _mm512_dpwssd_epi32((ACC), p16, sc16); \
} while (0)
IQ3S_ZMM_STEP(0, sumi0);
IQ3S_ZMM_STEP(2, sumi1);
IQ3S_ZMM_STEP(4, sumi0);
IQ3S_ZMM_STEP(6, sumi1);
#undef IQ3S_ZMM_STEP
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
const __m256i sum12 = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
accumf = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sum12), accumf);
}
@@ -411,8 +510,7 @@ void dot_iq3_s_q8_K_zmm(int n, float* STRATA_RESTRICT s, const void* STRATA_REST
*s = hsum_float_8(accumf);
}
// ---- 4-row shared-activation VPDPBUSD (`dot_*_x4`) kernels (MIT, bit-exact to Arith::Avx2 1-row dots) ----
// Amortizes activation loads and bias sums 4x across 4 contiguous weight rows, with +4*bx prefetching.
// ---- 4-row shared-activation VPDPBUSD/VPDPWSSD (`dot_*_x4`) kernels (MIT, bit-exact to Arith::Avx2 1-row dots) ----
void dot_q4_0_q8_0_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, size_t row_bytes, const void* STRATA_RESTRICT vy) {
assert(n % QK8_0 == 0);
@@ -440,7 +538,6 @@ void dot_q4_0_q8_0_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, s
}
const float dy = h2f(y[ib].d);
const __m256i qy = _mm256_loadu_si256((const __m256i*) y[ib].qs);
// Shared activation bias sum: 8 * sum_of_4_bytes(qy) via single VPDPBUSD against all-8s!
const __m256i ybias = _mm256_dpbusd_epi32(_mm256_setzero_si256(), bias8, qy);
auto step_row = [&](const block_q4_0& bx, __m256& acc) {
@@ -460,6 +557,59 @@ void dot_q4_0_q8_0_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, s
out[3] = hsum_float_8(acc3);
}
void dot_q8_0_q8_0_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, size_t row_bytes, const void* STRATA_RESTRICT vy) {
assert(n % QK8_0 == 0);
const int nb = n / QK8_0;
const uint8_t* wb = (const uint8_t*) w_base;
const block_q8_0* rows[4] = {
(const block_q8_0*) (wb + 0 * row_bytes),
(const block_q8_0*) (wb + 1 * row_bytes),
(const block_q8_0*) (wb + 2 * row_bytes),
(const block_q8_0*) (wb + 3 * row_bytes),
};
const block_q8_0* STRATA_RESTRICT y = (const block_q8_0*) vy;
const __m512i zero512 = _mm512_setzero_si512();
const __m256i zero256 = _mm256_setzero_si256();
__m256 acc[4] = {_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()};
int ib = 0;
for (; ib + 1 < nb; ib += 2) {
if (ib + 4 < nb) {
for (int r = 0; r < 4; ++r) _mm_prefetch((const char*) &rows[r][ib + 4], _MM_HINT_T0);
}
const float dy0 = h2f(y[ib + 0].d);
const float dy1 = h2f(y[ib + 1].d);
const __m512i qy = _mm512_inserti64x4(
_mm512_castsi256_si512(_mm256_loadu_si256((const __m256i*) y[ib + 0].qs)),
_mm256_loadu_si256((const __m256i*) y[ib + 1].qs), 1);
for (int r = 0; r < 4; ++r) {
const __m512i qx = _mm512_inserti64x4(
_mm512_castsi256_si512(_mm256_loadu_si256((const __m256i*) rows[r][ib + 0].qs)),
_mm256_loadu_si256((const __m256i*) rows[r][ib + 1].qs), 1);
const __m512i ax = _mm512_abs_epi8(qx);
const __mmask64 neg = _mm512_movepi8_mask(qx);
const __m512i sy = _mm512_mask_sub_epi8(qy, neg, zero512, qy);
const __m512i p32 = _mm512_dpbusd_epi32(zero512, ax, sy);
acc[r] = _mm256_fmadd_ps(_mm256_set1_ps(h2f(rows[r][ib + 0].d) * dy0), _mm256_cvtepi32_ps(_mm512_castsi512_si256(p32)), acc[r]);
acc[r] = _mm256_fmadd_ps(_mm256_set1_ps(h2f(rows[r][ib + 1].d) * dy1), _mm256_cvtepi32_ps(_mm512_extracti64x4_epi64(p32, 1)), acc[r]);
}
}
for (; ib < nb; ++ib) {
const float dy = h2f(y[ib].d);
const __m256i qy = _mm256_loadu_si256((const __m256i*) y[ib].qs);
for (int r = 0; r < 4; ++r) {
const __m256i qx = _mm256_loadu_si256((const __m256i*) rows[r][ib].qs);
const __m256i ax = _mm256_sign_epi8(qx, qx);
const __m256i sy = _mm256_sign_epi8(qy, qx);
const __m256 q = _mm256_cvtepi32_ps(_mm256_dpbusd_epi32(zero256, ax, sy));
acc[r] = _mm256_fmadd_ps(_mm256_set1_ps(h2f(rows[r][ib].d) * dy), q, acc[r]);
}
}
for (int r = 0; r < 4; ++r) out[r] = hsum_float_8(acc[r]);
}
void dot_mxfp4_q8_0_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, size_t row_bytes, const void* STRATA_RESTRICT vy) {
assert(n % QK_MXFP4 == 0);
const int nb = n / QK_MXFP4;
@@ -470,8 +620,6 @@ void dot_mxfp4_q8_0_x4(int n, float out[4], const void* STRATA_RESTRICT w_base,
const block_mxfp4* x3 = (const block_mxfp4*) (wb + 3 * row_bytes);
const block_q8_0* STRATA_RESTRICT y = (const block_q8_0*) vy;
// Unsigned-shifted E2M1x2 LUT: kvalues_fp4[i] + 12 in [0..24], enabling single-cycle VPDPBUSD u8*s8 -> s32
// with one shared 12 * sum(y) bias subtraction amortized across all 4 rows!
static constexpr uint8_t kFp4Plus12[16] = {
12, 13, 14, 15, 16, 18, 20, 24,
12, 11, 10, 9, 8, 6, 4, 0,
@@ -535,6 +683,12 @@ void dot_q4_K_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, s
static constexpr uint32_t kmask2 = 0x0f0f0f0f;
static constexpr uint32_t kmask3 = 0x03030303;
const __m512i m4 = _mm512_set1_epi8(0x0F);
const __m512i shufs[4] = {
_mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 0)),
_mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 64)),
_mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 128)),
_mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 192)),
};
__m256 acc[4] = {_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()};
__m128 acc_m[4] = {_mm_setzero_ps(), _mm_setzero_ps(), _mm_setzero_ps(), _mm_setzero_ps()};
@@ -545,11 +699,12 @@ void dot_q4_K_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, s
const float yd = y[i].d;
const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y[i].bsums);
const __m128i q8s = _mm_hadd_epi16(_mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1));
const __m512i q8_0 = _mm512_loadu_si512((const __m512i*) (y[i].qs + 0));
const __m512i q8_1 = _mm512_loadu_si512((const __m512i*) (y[i].qs + 64));
const __m512i q8_2 = _mm512_loadu_si512((const __m512i*) (y[i].qs + 128));
const __m512i q8_3 = _mm512_loadu_si512((const __m512i*) (y[i].qs + 192));
const __m512i q8v[4] = {q8_0, q8_1, q8_2, q8_3};
const __m512i q8v[4] = {
_mm512_loadu_si512((const __m512i*) (y[i].qs + 0)),
_mm512_loadu_si512((const __m512i*) (y[i].qs + 64)),
_mm512_loadu_si512((const __m512i*) (y[i].qs + 128)),
_mm512_loadu_si512((const __m512i*) (y[i].qs + 192)),
};
for (int r = 0; r < 4; ++r) {
const block_q4_K& bx = rows[r][i];
@@ -567,19 +722,19 @@ void dot_q4_K_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, s
acc_m[r] = _mm_fmadd_ps(_mm_set1_ps(dmin), _mm_cvtepi32_ps(prod), acc_m[r]);
const __m512i scales512 = _mm512_broadcast_i32x4(_mm256_castsi256_si128(mins_and_scales));
__m512i sumi512 = _mm512_setzero_si512();
__m512i sumi0 = _mm512_setzero_si512();
__m512i sumi1 = _mm512_setzero_si512();
const uint8_t* q4 = bx.qs;
for (int j = 0; j < 4; ++j) {
const __m512i shuf = _mm512_inserti64x4(_mm512_castsi256_si512(get_scale_shuffle_k4(2 * j + 0)),
get_scale_shuffle_k4(2 * j + 1), 1);
const __m512i scale_lh = _mm512_shuffle_epi8(scales512, shuf);
const __m256i q4bits = _mm256_loadu_si256((const __m256i*) q4);
q4 += 32;
const __m512i scale_lh = _mm512_shuffle_epi8(scales512, shufs[j]);
const __m256i q4bits = _mm256_loadu_si256((const __m256i*) (q4 + 32 * j));
const __m512i q4_lh = _mm512_and_si512(
_mm512_inserti64x4(_mm512_castsi256_si512(q4bits), _mm256_srli_epi16(q4bits, 4), 1), m4);
const __m512i p16 = _mm512_maddubs_epi16(q4_lh, q8v[j]);
sumi512 = _mm512_add_epi32(sumi512, _mm512_madd_epi16(scale_lh, p16));
if (j & 1) sumi1 = _mm512_dpwssd_epi32(sumi1, scale_lh, p16);
else sumi0 = _mm512_dpwssd_epi32(sumi0, scale_lh, p16);
}
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
const __m256i sumi = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
acc[r] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc[r]);
}
@@ -591,6 +746,167 @@ void dot_q4_K_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, s
}
}
void dot_q5_K_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, size_t row_bytes, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const int nb = n / QK_K;
const uint8_t* wb = (const uint8_t*) w_base;
const block_q5_K* rows[4] = {
(const block_q5_K*) (wb + 0 * row_bytes),
(const block_q5_K*) (wb + 1 * row_bytes),
(const block_q5_K*) (wb + 2 * row_bytes),
(const block_q5_K*) (wb + 3 * row_bytes),
};
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
static constexpr uint32_t kmask1 = 0x3f3f3f3f;
static constexpr uint32_t kmask2 = 0x0f0f0f0f;
static constexpr uint32_t kmask3 = 0x03030303;
const __m512i m4 = _mm512_set1_epi8(0x0F);
const __m512i m16 = _mm512_set1_epi8(16);
const __m128i mzero = _mm_setzero_si128();
const __m512i shufs[4] = {
_mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 0)),
_mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 64)),
_mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 128)),
_mm512_load_si512((const __m512i*) (kScaleShuffleK4Zmm + 192)),
};
const __m512i hms[4] = {q5k_hbit_mask_zmm(0), q5k_hbit_mask_zmm(1), q5k_hbit_mask_zmm(2), q5k_hbit_mask_zmm(3)};
__m256 acc[4] = {_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()};
float summs[4] = {0.f, 0.f, 0.f, 0.f};
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
for (int r = 0; r < 4; ++r) _mm_prefetch((const char*) &rows[r][i + 2], _MM_HINT_T0);
}
const float yd = y[i].d;
const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y[i].bsums);
const __m128i q8s = _mm_hadd_epi16(_mm256_extracti128_si256(q8sums, 0), _mm256_extracti128_si256(q8sums, 1));
const __m512i q8v[4] = {
_mm512_loadu_si512((const __m512i*) (y[i].qs + 0)),
_mm512_loadu_si512((const __m512i*) (y[i].qs + 64)),
_mm512_loadu_si512((const __m512i*) (y[i].qs + 128)),
_mm512_loadu_si512((const __m512i*) (y[i].qs + 192)),
};
for (int r = 0; r < 4; ++r) {
const block_q5_K& bx = rows[r][i];
const float d = yd * h2f(bx.d);
const float dmin = -yd * h2f(bx.dmin);
uint32_t utmp[4];
std::memcpy(utmp, bx.scales, 12);
utmp[3] = ((utmp[2] >> 4) & kmask2) | (((utmp[1] >> 6) & kmask3) << 4);
const uint32_t uaux = utmp[1] & kmask1;
utmp[1] = (utmp[2] & kmask2) | (((utmp[0] >> 6) & kmask3) << 4);
utmp[2] = uaux;
utmp[0] &= kmask1;
const __m256i mins_and_scales = _mm256_cvtepu8_epi16(_mm_set_epi32(utmp[3], utmp[2], utmp[1], utmp[0]));
const __m128i prod = _mm_madd_epi16(_mm256_extracti128_si256(mins_and_scales, 1), q8s);
const __m128i hsum = _mm_hadd_epi32(_mm_hadd_epi32(prod, mzero), mzero);
summs[r] = _mm_cvtss_f32(_mm_add_ss(_mm_set_ss(summs[r]),
_mm_mul_ss(_mm_set_ss(dmin), _mm_cvtsi32_ss(_mm_setzero_ps(), _mm_extract_epi32(hsum, 0)))));
const __m512i scales512 = _mm512_broadcast_i32x4(_mm256_castsi256_si128(mins_and_scales));
const __m512i hbits512 = _mm512_broadcast_i64x4(_mm256_loadu_si256((const __m256i*) bx.qh));
__m512i sumi0 = _mm512_setzero_si512();
__m512i sumi1 = _mm512_setzero_si512();
const uint8_t* q5 = bx.qs;
for (int j = 0; j < 4; ++j) {
const __m512i scale_lh = _mm512_shuffle_epi8(scales512, shufs[j]);
const __m256i q5bits = _mm256_loadu_si256((const __m256i*) (q5 + 32 * j));
const __m512i q5_lo = _mm512_and_si512(
_mm512_inserti64x4(_mm512_castsi256_si512(q5bits), _mm256_srli_epi16(q5bits, 4), 1), m4);
const __mmask64 hb = _mm512_test_epi8_mask(hbits512, hms[j]);
const __m512i q5_lh = _mm512_mask_add_epi8(q5_lo, hb, q5_lo, m16);
const __m512i p16 = _mm512_maddubs_epi16(q5_lh, q8v[j]);
if (j & 1) sumi1 = _mm512_dpwssd_epi32(sumi1, scale_lh, p16);
else sumi0 = _mm512_dpwssd_epi32(sumi0, scale_lh, p16);
}
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
const __m256i sumi = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
acc[r] = _mm256_fmadd_ps(_mm256_set1_ps(d), _mm256_cvtepi32_ps(sumi), acc[r]);
}
}
for (int r = 0; r < 4; ++r) out[r] = hsum_float_8(acc[r]) + summs[r];
}
void dot_q6_K_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, size_t row_bytes, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const int nb = n / QK_K;
const uint8_t* wb = (const uint8_t*) w_base;
const block_q6_K* rows[4] = {
(const block_q6_K*) (wb + 0 * row_bytes),
(const block_q6_K*) (wb + 1 * row_bytes),
(const block_q6_K*) (wb + 2 * row_bytes),
(const block_q6_K*) (wb + 3 * row_bytes),
};
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const __m512i m15 = _mm512_set1_epi8(15);
const __m256i m3 = _mm256_set1_epi8(3);
const __m256i m12 = _mm256_set1_epi8(12);
const __m256i m48 = _mm256_set1_epi8(48);
const __m256i m192 = _mm256_set1_epi8((char) 0xC0);
__m256 acc[4] = {_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()};
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
for (int r = 0; r < 4; ++r) _mm_prefetch((const char*) &rows[r][i + 2], _MM_HINT_T0);
}
const float yd = y[i].d;
const __m256i q8sums = _mm256_loadu_si256((const __m256i*) y[i].bsums);
const __m512i q8v[4] = {
_mm512_loadu_si512((const __m512i*) (y[i].qs + 0)),
_mm512_loadu_si512((const __m512i*) (y[i].qs + 64)),
_mm512_loadu_si512((const __m512i*) (y[i].qs + 128)),
_mm512_loadu_si512((const __m512i*) (y[i].qs + 192)),
};
for (int r = 0; r < 4; ++r) {
const block_q6_K& bx = rows[r][i];
const float d = yd * h2f(bx.d);
const uint8_t* q4 = bx.ql;
const uint8_t* qh = bx.qh;
const __m128i scales = _mm_loadu_si128((const __m128i*) bx.scales);
const __m256i scales_16 = _mm256_cvtepi8_epi16(scales);
const __m256i q8sclsub = _mm256_slli_epi32(_mm256_madd_epi16(q8sums, scales_16), 5);
__m512i sumi0 = _mm512_setzero_si512();
__m512i sumi1 = _mm512_setzero_si512();
int is = 0;
for (int j = 0; j < 2; ++j) {
const __m512i q4bits12 = _mm512_loadu_si512((const __m512i*) (q4 + 64 * j));
const __m256i q4bitsH = _mm256_loadu_si256((const __m256i*) (qh + 32 * j));
const __m256i q4h_0 = _mm256_slli_epi16(_mm256_and_si256(q4bitsH, m3), 4);
const __m256i q4h_1 = _mm256_slli_epi16(_mm256_and_si256(q4bitsH, m12), 2);
const __m256i q4h_2 = _mm256_and_si256(q4bitsH, m48);
const __m256i q4h_3 = _mm256_srli_epi16(_mm256_and_si256(q4bitsH, m192), 2);
const __m512i q4_01 = _mm512_or_si512(_mm512_and_si512(q4bits12, m15),
_mm512_inserti64x4(_mm512_castsi256_si512(q4h_0), q4h_1, 1));
const __m512i q4_23 = _mm512_or_si512(_mm512_and_si512(_mm512_srli_epi16(q4bits12, 4), m15),
_mm512_inserti64x4(_mm512_castsi256_si512(q4h_2), q4h_3, 1));
const __m512i p16_01 = _mm512_maddubs_epi16(q4_01, q8v[2 * j + 0]);
const __m512i p16_23 = _mm512_maddubs_epi16(q4_23, q8v[2 * j + 1]);
const __m256i sc_01 = _mm256_inserti128_si256(
_mm256_castsi128_si256(_mm_shuffle_epi8(scales, get_scale_shuffle(is + 0))),
_mm_shuffle_epi8(scales, get_scale_shuffle(is + 1)), 1);
const __m256i sc_23 = _mm256_inserti128_si256(
_mm256_castsi128_si256(_mm_shuffle_epi8(scales, get_scale_shuffle(is + 2))),
_mm_shuffle_epi8(scales, get_scale_shuffle(is + 3)), 1);
is += 4;
sumi0 = _mm512_dpwssd_epi32(sumi0, _mm512_cvtepi8_epi16(sc_01), p16_01);
sumi1 = _mm512_dpwssd_epi32(sumi1, _mm512_cvtepi8_epi16(sc_23), p16_23);
}
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
__m256i sumi = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
sumi = _mm256_sub_epi32(sumi, q8sclsub);
acc[r] = _mm256_fmadd_ps(_mm256_broadcast_ss(&d), _mm256_cvtepi32_ps(sumi), acc[r]);
}
}
for (int r = 0; r < 4; ++r) out[r] = hsum_float_8(acc[r]);
}
void dot_iq4_xs_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, size_t row_bytes, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const int nb = n / QK_K;
@@ -616,8 +932,8 @@ void dot_iq4_xs_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base,
}
const float yd = y[ibl].d;
const __m512i q8v[4] = {
_mm512_loadu_si512((const __m512i*) (y[ibl].qs + 0)),
_mm512_loadu_si512((const __m512i*) (y[ibl].qs + 64)),
_mm512_loadu_si512((const __m512i*) (y[ibl].qs + 0)),
_mm512_loadu_si512((const __m512i*) (y[ibl].qs + 64)),
_mm512_loadu_si512((const __m512i*) (y[ibl].qs + 128)),
_mm512_loadu_si512((const __m512i*) (y[ibl].qs + 192)),
};
@@ -625,7 +941,8 @@ void dot_iq4_xs_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base,
const block_iq4_xs& bx = rows[r][ibl];
const uint8_t* qs = bx.qs;
uint16_t sh = bx.scales_h;
__m512i sumi512 = zero;
__m512i sumi0 = zero;
__m512i sumi1 = zero;
for (int ib = 0; ib < QK_K / 32; ib += 2) {
const __m128i q4bits_1 = _mm_loadu_si128((const __m128i*) qs);
const __m128i q4bits_2 = _mm_loadu_si128((const __m128i*) (qs + 16));
@@ -643,8 +960,10 @@ void dot_iq4_xs_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base,
sh >>= 4;
const __m512i sc16 = _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_set1_epi16(ls1)),
_mm256_set1_epi16(ls2), 1);
sumi512 = _mm512_add_epi32(sumi512, _mm512_madd_epi16(p16, sc16));
if (ib & 2) sumi1 = _mm512_dpwssd_epi32(sumi1, p16, sc16);
else sumi0 = _mm512_dpwssd_epi32(sumi0, p16, sc16);
}
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
const __m256i sum12 = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
accum[r] = _mm256_fmadd_ps(_mm256_set1_ps(h2f(bx.d) * yd), _mm256_cvtepi32_ps(sum12), accum[r]);
}
@@ -652,24 +971,103 @@ void dot_iq4_xs_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base,
for (int r = 0; r < 4; ++r) out[r] = hsum_float_8(accum[r]);
}
void dot_iq3_xxs_q8_K_x4(int n, float out[4], const void* STRATA_RESTRICT w_base, size_t row_bytes, const void* STRATA_RESTRICT vy) {
assert(n % QK_K == 0);
const int nb = n / QK_K;
const uint8_t* wb = (const uint8_t*) w_base;
const block_iq3_xxs* rows[4] = {
(const block_iq3_xxs*) (wb + 0 * row_bytes),
(const block_iq3_xxs*) (wb + 1 * row_bytes),
(const block_iq3_xxs*) (wb + 2 * row_bytes),
(const block_iq3_xxs*) (wb + 3 * row_bytes),
};
const block_q8_K* STRATA_RESTRICT y = (const block_q8_K*) vy;
const uint64_t* signs64 = (const uint64_t*) keven_signs_q2xs;
__m256 accumf[4] = {_mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps(), _mm256_setzero_ps()};
for (int i = 0; i < nb; ++i) {
if (i + 2 < nb) {
for (int r = 0; r < 4; ++r) _mm_prefetch((const char*) &rows[r][i + 2], _MM_HINT_T0);
}
const float yd = y[i].d;
const __m256i q8_h[8] = {
_mm256_loadu_si256((const __m256i*) (y[i].qs + 0)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 32)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 64)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 96)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 128)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 160)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 192)),
_mm256_loadu_si256((const __m256i*) (y[i].qs + 224)),
};
for (int r = 0; r < 4; ++r) {
const block_iq3_xxs& bx = rows[r][i];
const uint8_t* q3 = bx.qs;
const uint8_t* gas = bx.qs + QK_K / 4;
uint32_t aux32[2];
__m512i sumi0 = _mm512_setzero_si512();
__m512i sumi1 = _mm512_setzero_si512();
for (int ib32 = 0; ib32 < QK_K / 32; ib32 += 2) {
const __m256i q2_lo = _mm256_set_epi32(
(int) iq3xxs_grid[q3[ 7]], (int) iq3xxs_grid[q3[ 6]], (int) iq3xxs_grid[q3[ 5]], (int) iq3xxs_grid[q3[ 4]],
(int) iq3xxs_grid[q3[ 3]], (int) iq3xxs_grid[q3[ 2]], (int) iq3xxs_grid[q3[ 1]], (int) iq3xxs_grid[q3[ 0]]);
const __m256i q2_hi = _mm256_set_epi32(
(int) iq3xxs_grid[q3[15]], (int) iq3xxs_grid[q3[14]], (int) iq3xxs_grid[q3[13]], (int) iq3xxs_grid[q3[12]],
(int) iq3xxs_grid[q3[11]], (int) iq3xxs_grid[q3[10]], (int) iq3xxs_grid[q3[ 9]], (int) iq3xxs_grid[q3[ 8]]);
const __m512i q2_512 = _mm512_inserti64x4(_mm512_castsi256_si512(q2_lo), q2_hi, 1);
q3 += 16;
std::memcpy(aux32, gas, 8);
gas += 8;
const __m256i s2_1 = _mm256_set_epi64x(
(long long) signs64[(aux32[0] >> 21) & 127], (long long) signs64[(aux32[0] >> 14) & 127],
(long long) signs64[(aux32[0] >> 7) & 127], (long long) signs64[(aux32[0] >> 0) & 127]);
const __m256i s2_2 = _mm256_set_epi64x(
(long long) signs64[(aux32[1] >> 21) & 127], (long long) signs64[(aux32[1] >> 14) & 127],
(long long) signs64[(aux32[1] >> 7) & 127], (long long) signs64[(aux32[1] >> 0) & 127]);
const __m512i q8s_512 = _mm512_inserti64x4(
_mm512_castsi256_si512(_mm256_sign_epi8(q8_h[ib32 + 0], s2_1)),
_mm256_sign_epi8(q8_h[ib32 + 1], s2_2), 1);
const __m512i p16 = _mm512_maddubs_epi16(q2_512, q8s_512);
const int16_t s1 = (int16_t) (2 * (aux32[0] >> 28) + 1);
const int16_t s2 = (int16_t) (2 * (aux32[1] >> 28) + 1);
const __m512i sc16 = _mm512_inserti64x4(_mm512_castsi256_si512(_mm256_set1_epi16(s1)),
_mm256_set1_epi16(s2), 1);
if (ib32 & 2) sumi1 = _mm512_dpwssd_epi32(sumi1, p16, sc16);
else sumi0 = _mm512_dpwssd_epi32(sumi0, p16, sc16);
}
const __m512i sumi512 = _mm512_add_epi32(sumi0, sumi1);
const __m256i sum12 = _mm256_add_epi32(_mm512_castsi512_si256(sumi512), _mm512_extracti64x4_epi64(sumi512, 1));
accumf[r] = _mm256_fmadd_ps(_mm256_set1_ps(h2f(bx.d) * yd), _mm256_cvtepi32_ps(sum12), accumf[r]);
}
}
for (int r = 0; r < 4; ++r) out[r] = 0.25f * hsum_float_8(accumf[r]);
}
} // namespace avx512
namespace {
#define ENTRY(T, ACT, NAME) {avx512::dot_##NAME, Type::T, Type::ACT, Arith::Avx2, Isa::Avx512, "avx512_" #NAME}
#define ENTRY(T, ACT, NAME) {avx512::dot_##NAME, Type::T, Type::ACT, Arith::Avx2, Isa::Avx512, "avx512_" #NAME}
#define ENTRY_ZMM(T, ACT, NAME) {avx512::dot_##NAME##_zmm, Type::T, Type::ACT, Arith::Avx2, Isa::Avx512, "avx512_" #NAME}
#define ENTRY_X4(T, ACT, NAME) {avx512::dot_##NAME##_x4, Type::T, Type::ACT, Arith::Avx2, Isa::Avx512, "avx512_" #NAME "_x4"}
#define ENTRY_X4(T, ACT, NAME) {avx512::dot_##NAME##_x4, Type::T, Type::ACT, Arith::Avx2, Isa::Avx512, "avx512_" #NAME "_x4"}
const DotKernel kTable[] = {
ENTRY(Q4_0, Q8_0, q4_0_q8_0), ENTRY(Q4_1, Q8_1, q4_1_q8_1), ENTRY(Q5_0, Q8_0, q5_0_q8_0), ENTRY(Q5_1, Q8_1, q5_1_q8_1),
ENTRY(Q8_0, Q8_0, q8_0_q8_0), ENTRY(IQ4_NL, Q8_0, iq4_nl_q8_0), ENTRY(MXFP4, Q8_0, mxfp4_q8_0),
ENTRY_ZMM(Q8_0, Q8_0, q8_0_q8_0), ENTRY(IQ4_NL, Q8_0, iq4_nl_q8_0), ENTRY(MXFP4, Q8_0, mxfp4_q8_0),
ENTRY(NVFP4, Q8_0, nvfp4_q8_0),
ENTRY_ZMM(Q4_K, Q8_K, q4_K_q8_K), ENTRY_ZMM(Q5_K, Q8_K, q5_K_q8_K), ENTRY_ZMM(Q6_K, Q8_K, q6_K_q8_K),
ENTRY_ZMM(IQ4_XS, Q8_K, iq4_xs_q8_K), ENTRY_ZMM(IQ3_S, Q8_K, iq3_s_q8_K),
ENTRY_ZMM(IQ4_XS, Q8_K, iq4_xs_q8_K), ENTRY_ZMM(IQ3_XXS, Q8_K, iq3_xxs_q8_K), ENTRY_ZMM(IQ3_S, Q8_K, iq3_s_q8_K),
};
const DotX4Kernel kX4Table[] = {
ENTRY_X4(Q4_0, Q8_0, q4_0_q8_0),
ENTRY_X4(Q8_0, Q8_0, q8_0_q8_0),
ENTRY_X4(MXFP4, Q8_0, mxfp4_q8_0),
ENTRY_X4(Q4_K, Q8_K, q4_K_q8_K),
ENTRY_X4(Q5_K, Q8_K, q5_K_q8_K),
ENTRY_X4(Q6_K, Q8_K, q6_K_q8_K),
ENTRY_X4(IQ4_XS, Q8_K, iq4_xs_q8_K),
ENTRY_X4(IQ3_XXS, Q8_K, iq3_xxs_q8_K),
};
#undef ENTRY_X4
#undef ENTRY_ZMM
+62 -23
View File
@@ -1,14 +1,49 @@
void quantize_q8_K_avx2(const float* x, void* vy, int64_t k) {
block_q8_K* y = (block_q8_K*) vy;
// Copyright (c) 2026 Niko1221 and the Strata contributors
// SPDX-License-Identifier: MIT
//
// q8k_avx2.inc - bit-exact AVX2 activation quantizer for Q8_K (zero EVEX/ZMM instructions).
// Matches quantize_q8_K_ref byte-for-byte on all inputs including exact ties and degenerate scales.
static inline int q8k_ctz32_avx2(unsigned int m) {
#if defined(_MSC_VER)
unsigned long idx = 0;
_BitScanForward(&idx, m);
return (int) idx;
#else
return __builtin_ctz(m);
#endif
}
void quantize_q8_K_avx2(const float* STRATA_RESTRICT x, void* STRATA_RESTRICT vy, int64_t k) {
block_q8_K* STRATA_RESTRICT y = (block_q8_K*) vy;
const int64_t nb = k / QK_K;
const __m256 absm = _mm256_castsi256_ps(_mm256_set1_epi32(0x7fffffff));
const __m256 magic = _mm256_set1_ps(12582912.f);
const __m256i mant = _mm256_set1_epi32(0x007fffff), off = _mm256_set1_epi32(0x00400000);
const __m256i mant = _mm256_set1_epi32(0x007fffff);
const __m256i off = _mm256_set1_epi32(0x00400000);
const __m256i c127 = _mm256_set1_epi32(127);
const __m256i perm = _mm256_setr_epi32(0, 4, 1, 5, 2, 6, 3, 7);
const __m256i sign80 = _mm256_set1_epi8((char) 0x80);
const __m256i zero = _mm256_setzero_si256();
for (int64_t i = 0; i < nb; ++i, x += QK_K) {
__m256 m = _mm256_setzero_ps();
for (int j = 0; j < QK_K; j += 8) m = _mm256_max_ps(_mm256_and_ps(_mm256_loadu_ps(x + j), absm), m);
if (i + 1 < nb) {
_mm_prefetch((const char*) (x + QK_K), _MM_HINT_T0);
_mm_prefetch((const char*) (x + QK_K + 64), _MM_HINT_T0);
}
// 4-way unrolled max(abs(x)) to break the vmaxps dependency chain
__m256 m0 = _mm256_setzero_ps();
__m256 m1 = _mm256_setzero_ps();
__m256 m2 = _mm256_setzero_ps();
__m256 m3 = _mm256_setzero_ps();
for (int j = 0; j < QK_K; j += 32) {
m0 = _mm256_max_ps(m0, _mm256_and_ps(_mm256_loadu_ps(x + j + 0), absm));
m1 = _mm256_max_ps(m1, _mm256_and_ps(_mm256_loadu_ps(x + j + 8), absm));
m2 = _mm256_max_ps(m2, _mm256_and_ps(_mm256_loadu_ps(x + j + 16), absm));
m3 = _mm256_max_ps(m3, _mm256_and_ps(_mm256_loadu_ps(x + j + 24), absm));
}
const __m256 m = _mm256_max_ps(_mm256_max_ps(m0, m1), _mm256_max_ps(m2, m3));
__m128 h = _mm_max_ps(_mm256_castps256_ps128(m), _mm256_extractf128_ps(m, 1));
h = _mm_max_ps(h, _mm_movehl_ps(h, h));
h = _mm_max_ss(h, _mm_movehdup_ps(h));
@@ -18,44 +53,48 @@ void quantize_q8_K_avx2(const float* x, void* vy, int64_t k) {
std::memset(y[i].qs, 0, QK_K);
continue;
}
// Exact first-occurrence sign scan matching q8_K_ref (`if (ax > amax)`)
float mx = 0.f;
const __m256 va = _mm256_set1_ps(amax);
for (int j = 0; j < QK_K; j += 8) {
const int msk = _mm256_movemask_ps(_mm256_cmp_ps(_mm256_and_ps(_mm256_loadu_ps(x + j), absm), va, _CMP_EQ_OQ));
for (int j = 0; j < QK_K; j += 32) {
const unsigned int msk0 = (unsigned int) _mm256_movemask_ps(_mm256_cmp_ps(_mm256_and_ps(_mm256_loadu_ps(x + j + 0), absm), va, _CMP_EQ_OQ));
const unsigned int msk1 = (unsigned int) _mm256_movemask_ps(_mm256_cmp_ps(_mm256_and_ps(_mm256_loadu_ps(x + j + 8), absm), va, _CMP_EQ_OQ));
const unsigned int msk2 = (unsigned int) _mm256_movemask_ps(_mm256_cmp_ps(_mm256_and_ps(_mm256_loadu_ps(x + j + 16), absm), va, _CMP_EQ_OQ));
const unsigned int msk3 = (unsigned int) _mm256_movemask_ps(_mm256_cmp_ps(_mm256_and_ps(_mm256_loadu_ps(x + j + 24), absm), va, _CMP_EQ_OQ));
const unsigned int msk = msk0 | (msk1 << 8) | (msk2 << 16) | (msk3 << 24);
if (msk) {
int b = 0;
while (!((msk >> b) & 1)) ++b;
mx = x[j + b];
mx = x[j + q8k_ctz32_avx2(msk)];
break;
}
}
const float iscale = -127.f / mx;
const __m256 vis = _mm256_set1_ps(iscale);
for (int j = 0; j < QK_K; j += 32) {
__m256i v[4];
for (int q = 0; q < 4; ++q) {
__m256 p = _mm256_mul_ps(vis, _mm256_loadu_ps(x + j + 8 * q));
#if defined(__GNUC__) // GCC, and Clang / icx when the file is built with -ffp-contract=fast (quant.cmake): both fuse across intrinsics
// GCC fuses a multiply and an add into an FMA by default (-ffp-contract=fast); the reference rounds
// the product before the add, so the product must stay a separate value
#if defined(__GNUC__)
// Keep multiply rounded before add to match scalar nearest_int(iscale * x) bit-for-bit
__asm__("" : "+x"(p));
#endif
const __m256 t = _mm256_add_ps(p, magic);
v[q] = _mm256_min_epi32(_mm256_sub_epi32(_mm256_and_si256(_mm256_castps_si256(t), mant), off), c127);
// the reference stores MIN(127, v) into an int8 (keeps the low byte), and its bsums add those bytes:
// the same here, so even a degenerate block (iscale overflowing to inf) gives the same bytes
// Sign-extend low byte so even degenerate inf/NaN iscale matches int8_t truncation in q8_K_ref
v[q] = _mm256_srai_epi32(_mm256_slli_epi32(v[q], 24), 24);
}
for (int q = 0; q < 2; ++q) { // two 16-value sums
const __m256i s = _mm256_add_epi32(v[2 * q], v[2 * q + 1]);
__m128i s4 = _mm_add_epi32(_mm256_castsi256_si128(s), _mm256_extracti128_si256(s, 1));
s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0x4E));
s4 = _mm_add_epi32(s4, _mm_shuffle_epi32(s4, 0xB1));
y[i].bsums[j / 16 + q] = (int16_t) _mm_cvtsi128_si32(s4);
}
const __m256i p16a = _mm256_packs_epi32(v[0], v[1]), p16b = _mm256_packs_epi32(v[2], v[3]);
const __m256i p16a = _mm256_packs_epi32(v[0], v[1]);
const __m256i p16b = _mm256_packs_epi32(v[2], v[3]);
const __m256i p8 = _mm256_permutevar8x32_epi32(_mm256_packs_epi16(p16a, p16b), perm);
_mm256_storeu_si256((__m256i*) (y[i].qs + j), p8);
// Fast exact 16-byte signed sums via psadbw on (byte ^ 0x80) = (byte + 128) in [0, 255]
const __m256i sad = _mm256_sad_epu8(_mm256_xor_si256(p8, sign80), zero);
const __m128i slo = _mm256_castsi256_si128(sad);
const __m128i shi = _mm256_extracti128_si256(sad, 1);
y[i].bsums[j / 16 + 0] = (int16_t) (_mm_cvtsi128_si32(slo) + _mm_extract_epi32(slo, 2) - 2048);
y[i].bsums[j / 16 + 1] = (int16_t) (_mm_cvtsi128_si32(shi) + _mm_extract_epi32(shi, 2) - 2048);
}
y[i].d = 1 / iscale;
}
+35 -15
View File
@@ -6969,20 +6969,27 @@ def kv_streaming_need_gb(model, ctx, kv) -> float:
for the engine (Linux mimic): streaming gave 756 -> 1,267 expert slots and a 32K prompt in 12-17 s instead of
21-34 s, with the RAM the engine used unchanged (RAM budget 31 -> 29 GiB); on the owner's RTX 5070 (R5070's
run) 924 -> 1,585 slots, a 32K prompt 130 -> 79 s, the RAM copy 30.8 -> 28.9 GiB, no paging. Rule (1) alone
asked 64.8 GB of a PC that reads 63.1 and left the KV in VRAM."""
asked 64.8 GB of a PC that reads 63.1 and left the KV in VRAM.
#6354: Unsloth budget-mode quants subtract KV RAM from --resident-budget-gib, so streaming works cleanly from
16 GB RAM up (keeping 12 GB OS headroom + KV RAM)."""
kv_gb = kv_streaming_ram_gb(ctx, kv)
m = MODELS[model]
if m.get("budget"):
return max(16.0, LOW_RAM_HEADROOM_GB + kv_gb + 4.0)
return min(m["ram_gb"] + kv_gb + 1, m["arena_gb"] + LOW_RAM_HEADROOM_GB + kv_gb)
def kv_streaming_wanted(model, ctx, kv, ram, choice="auto") -> bool:
"""Will setup stream this model's KV cache on this PC: from 64K up, when the RAM holds the cache beside the
model's experts (`kv_streaming_need_gb`); `--kv-streaming on|off` overrides the RAM test (the owner's rule), and
WSL never streams. Step 7 writes `--kv-resident` on exactly this answer, and the launcher's preset diff asks it
too: a config's `--kv-resident` and a preset's "auto" are the same setting when this says yes."""
def kv_streaming_wanted(model, ctx, kv, ram, choice="auto", vram_gb: float = 0.0) -> bool:
"""Will setup stream this model's KV cache on this PC: from 64K up (and from 32K up on <= 16 GB discrete GPUs
for Unsloth budget-mode quants per #6354), when the RAM holds the cache beside the model's experts
(`kv_streaming_need_gb`); `--kv-streaming on|off` overrides the RAM test (the owner's rule), and WSL never streams.
Step 7 writes `--kv-resident` on exactly this answer, and the launcher's preset diff asks it too: a config's
`--kv-resident` and a preset's "auto" are the same setting when this says yes."""
if is_wsl() or choice == "off":
return False
return ctx >= 65536 and (ram >= kv_streaming_need_gb(model, ctx, kv) or choice == "on")
m = MODELS.get(model, {})
min_ctx = 32768 if (m.get("budget") and 0 < float(vram_gb or 0.0) <= 16.5) else 65536
return ctx >= min_ctx and (ram >= kv_streaming_need_gb(model, ctx, kv) or choice == "on")
def low_ram_one_gpu_why(model, ram, choice, sel=None) -> list[str]:
@@ -8700,9 +8707,11 @@ def unsloth_vram_slack_mib(vram_gb: float, ctx: int, kv: str, reserve_mib: int,
def unsloth_small_card_plan(vram_gb: float, ctx: int, kv: str, reserve_mib: int | None, ctx_fixed=False, kv_fixed=False,
runtime_mib: int = 0):
"""(ctx, kv, mtp, slack_mib) of the least harmful start that the estimate says fits, or None when none does.
"""(ctx, kv, mtp, slack_mib) of the least harmful start that fits on small discrete cards (4-9 GB).
Order of harm: the KV in 4 bits, then a smaller context (down to 4608), then no draft layer on the GPU (decode
up to 2x slower, but 0.8 GB for the cache); a value the user chose (--context, --kv) is not changed."""
up to 2x slower, but 0.8 GB for the cache); a value the user chose (--context, --kv) is not changed.
For 4 GB and 6 GB GPUs (vram_gb >= 3.5), falls back cleanly to 0-slot / dense-streaming mode (slack_mib = 0.0,
mtp = False, int8/q4_0 KV) so the engine streams routed experts from RAM+SSD instead of refusing or OOMing."""
reserve = UD_FIT_ENGINE_RESERVE_MIB if reserve_mib is None else reserve_mib
ctxs = [ctx] if ctx_fixed else [ctx] + [c for c in UD_FIT_CTX_STEPS if c < ctx]
kvs = [kv] if kv_fixed or kv == "q4_0" else [kv, "q4_0"]
@@ -8712,20 +8721,27 @@ def unsloth_small_card_plan(vram_gb: float, ctx: int, kv: str, reserve_mib: int
slack = unsloth_vram_slack_mib(vram_gb, c, k, reserve, mtp, runtime_mib)
if slack >= UD_FIT_MIN_SLACK_MIB:
return c, k, mtp, slack
if float(vram_gb or 0.0) >= 3.5:
c0 = ctx if ctx_fixed else min(ctx, 8192 if vram_gb >= 5.5 else 4608)
k0 = kv if kv_fixed else ("int8" if vram_gb >= 5.5 else "q4_0")
return c0, k0, False, 0.0
return None
def unsloth_small_card_lines(model: str, vram_gb: float, plan, start_ok: bool) -> list[str]:
"""The words for a ~8 GB card: that UD-* is very slow here and what to pick instead (always), and when the start
would have stopped, that and what setup changed instead. Recommend, never force."""
"""The words for a <= 8 GB card: explains 0-slot / dense-streaming on 4-6 GB cards or small cache on 8 GB cards
and what smaller quants run faster. Recommend, never force."""
if float(vram_gb or 0.0) < 7.0:
return [f"{model} on a {vram_gb:.0f} GB card uses 0-slot / dense-streaming mode: dense weights and KV stay in "
"VRAM while routed experts stream from RAM + SSD (no OOM, never refused). UD-IQ3_XXS or UD-IQ1_M "
"need far less RAM/SSD bandwidth on this tier."]
lines = [f"{model} on a {vram_gb:.0f} GB card is very slow: the dense side and the draft layer fill the card, the expert "
"cache gets a few slots, and nearly every expert comes from RAM or the SSD (3-5 tok/s measured on an 8 GB "
"Arc A750). IQ3_XXS or IQ3_S of the Qwen3.8-Flash-Next family fit such a card far better; run setup again "
"and pick one of them."]
if not start_ok and plan is None:
lines.append("By setup's estimate even a 4608 context with a 4-bit KV cache and no draft layer leaves no room "
"for the expert cache on this card: the start will probably stop with \"no VRAM is left for the "
"expert cache\".")
"for the expert cache on this card: the start will use 0-slot dense-streaming mode.")
return lines
@@ -11905,8 +11921,12 @@ def main() -> int:
ok(f"rope scaling: {scaling}, factor {rope_scale:g} ({origin})")
ok(f"context: {ctx} tokens")
# the KV cache (the model's memory of the conversation): 8-bit, or 4-bit after a Hadamard rotation (PR #21).
# Track 6A: on <= 12.5 GB GPUs, default to int8 KV even at <= 8192 context (saves ~112 MiB VRAM for ExpertCache/DFlash2).
_low_vram_kv = 0 < float((gpu or {}).get("vram_gb") or 0.0) <= 12.5
# Track 6A + #6354: default to int8 KV on <= 12.5 GB GPUs (all models), on <= 16.5 GB GPUs (all Unsloth quants at
# any context: avoids 21-23% 16K/32K prompt slowdown and preserves 400+ VRAM expert slots), and on <= 24.5 GB GPUs
# at >= 64K context.
_vram_kv = float((gpu or {}).get("vram_gb") or 0.0)
_is_unsloth_kv = bool(MODELS.get(model, {}).get("budget"))
_low_vram_kv = (0 < _vram_kv <= 12.5) or (_is_unsloth_kv and ((0 < _vram_kv <= 16.5) or (0 < _vram_kv <= 24.5 and ctx >= 65536)))
kv = (a.kv or "int8") if (ctx > 8192 or _low_vram_kv) else (a.kv or "fp16")
if ctx > 8192 and not a.kv and not a.yes:
say()
+307
View File
@@ -354,3 +354,310 @@ def ssd_streaming_plan(memory_gb: float, ram_gb: float | None, vram_gb: float |
"bounce_ring_gb": 0.0,
"flags": ["--cpu", "--ssd-experts", "--ram-experts-gb", f"{lru_gb:g}"],
}
# ---- Qwen3.8 / Unsloth all-tier planner (discrete 4..32 GB + DGX Spark + Mac Metal + Strix Halo) -------------------------
# Covers every Unsloth Dynamic quant (UD-Q4_K_XL, Q8_0, UD-IQ4_XS, UD-IQ3_XXS, UD-Q6_K_XL, UD-Q5_K_XL, UD-Q3_K_XL,
# UD-Q2_K_XL, UD-IQ2_XXS, UD-IQ2_XS, UD-Q2_0, UD-IQ1_M, UD-IQ1_S) with heterogeneous expert sizing, #6354 auto int8 KV +
# elastic --kv-resident, #4870 coverage-based adaptive defaults (2/192/0.92 at 15%-65% coverage), and clean 4 GB / 6 GB
# discrete unlock (0-slot / dense-streaming / RAM+SSD cold tiers, never refusing or OOMing).
UNSLOTH_TOTAL_EXPERT_PAIRS = 48 * 512 # 24,576 (layer, expert) pairs in Qwen3.8-Flash-Next
UNSLOTH_MAX_EXPERT_MIB = 5.05 # worst-case Q8_0 outlier expert blob (used by uniform max_blob sizing)
UNSLOTH_KV_BYTES_PER_TOK = {"fp16": 2112, "int8": 1056, "k8v4": 816, "q4_0": 576} # 13 attention layers (12 QSA + draft)
UNSLOTH_ADAPT_MIN_COV = 0.15 # #4870 lower coverage bound for fast adaptive tier
UNSLOTH_ADAPT_MAX_COV = 0.65 # #4870 upper coverage bound for fast adaptive tier
UNSLOTH_QUANTS: dict[str, dict[str, Any]] = {
"UD-IQ1_S": {"arena_gb": 32.5, "download_gb": 65.8, "dense_gb": 3.2, "avg_expert_mib": 1.26, "max_expert_mib": 5.05},
"UD-IQ1_M": {"arena_gb": 34.8, "download_gb": 68.0, "dense_gb": 3.2, "avg_expert_mib": 1.35, "max_expert_mib": 5.05},
"UD-Q2_0": {"arena_gb": 37.4, "download_gb": 70.5, "dense_gb": 3.2, "avg_expert_mib": 1.45, "max_expert_mib": 5.05},
"UD-IQ2_XXS": {"arena_gb": 39.8, "download_gb": 73.2, "dense_gb": 3.2, "avg_expert_mib": 1.54, "max_expert_mib": 5.05},
"UD-IQ2_XS": {"arena_gb": 42.3, "download_gb": 75.8, "dense_gb": 3.2, "avg_expert_mib": 1.64, "max_expert_mib": 5.05},
"UD-Q2_K_XL": {"arena_gb": 46.0, "download_gb": 79.6, "dense_gb": 3.3, "avg_expert_mib": 1.78, "max_expert_mib": 5.05},
"UD-IQ3_XXS": {"arena_gb": 50.3, "download_gb": 83.6, "dense_gb": 3.3, "avg_expert_mib": 1.95, "max_expert_mib": 5.05},
"UD-Q3_K_XL": {"arena_gb": 56.2, "download_gb": 89.5, "dense_gb": 3.4, "avg_expert_mib": 2.18, "max_expert_mib": 5.05},
"UD-IQ4_XS": {"arena_gb": 59.5, "download_gb": 93.7, "dense_gb": 3.4, "avg_expert_mib": 2.31, "max_expert_mib": 5.05},
"UD-IQ4_XS-v31": {"arena_gb": 60.4, "download_gb": 93.7, "dense_gb": 3.4, "avg_expert_mib": 2.34, "max_expert_mib": 5.05},
"UD-Q4_K_XL": {"arena_gb": 77.0, "download_gb": 111.3, "dense_gb": 3.5, "avg_expert_mib": 2.99, "max_expert_mib": 5.05},
"UD-Q5_K_XL": {"arena_gb": 98.4, "download_gb": 158.3, "dense_gb": 3.6, "avg_expert_mib": 3.82, "max_expert_mib": 5.05},
"UD-Q6_K_XL": {"arena_gb": 109.2, "download_gb": 169.2, "dense_gb": 3.6, "avg_expert_mib": 4.24, "max_expert_mib": 5.05},
"Q8_0": {"arena_gb": 128.3, "download_gb": 188.2, "dense_gb": 3.8, "avg_expert_mib": 4.98, "max_expert_mib": 5.05},
}
def is_dgx_spark_card(card: dict | None) -> bool:
"""NVIDIA DGX Spark / GB10 (cc 12.1, 128 GB unified memory)."""
if not isinstance(card, dict):
return False
text = " ".join(str(card.get(k) or "") for k in ("name", "arch", "cc")).lower()
return "gb10" in text or "dgx spark" in text or "spark" in text or "12.1" in text or "sm_121" in text
def is_mac_metal_card(card: dict | None, backend: str = "") -> bool:
"""Apple Silicon unified memory GPU (Metal backend)."""
if str(backend or "").lower() == "metal":
return True
if not isinstance(card, dict):
return False
text = " ".join(str(card.get(k) or "") for k in ("name", "vendor")).lower()
return "apple" in text or "metal" in text
def unsloth_kv_default(vram_gb: float, ctx: int, uma: bool = False, explicit_kv: str | None = None) -> str:
"""#6354: default KV cache precision for Unsloth quants.
- Discrete <= 16.5 GB: always int8 (prevents 21-23% 16K/32K prompt slowdown and saves 400+ expert slots on 12 GB).
- Discrete <= 24.5 GB at >= 64K context: int8.
- Any tier at > 8K context or UMA (DGX Spark, Mac Metal, Strix Halo): int8.
- Explicit user choice (--kv) is always respected.
"""
if explicit_kv:
return str(explicit_kv)
vram = float(vram_gb or 0.0)
if uma:
return "int8"
if 0.0 < vram <= 16.5:
return "int8"
if 0.0 < vram <= 24.5 and int(ctx) >= 65536:
return "int8"
return "int8" if int(ctx) > 8192 else "fp16"
def unsloth_kv_resident_default(vram_gb: float, ram_gb: float, ctx: int, kv: str = "int8", uma: bool = False,
explicit_kv_resident: int | None = None) -> int | None:
"""#6354: elastic --kv-resident token window for Unsloth quants on discrete GPUs.
Streams older KV pages to pinned host RAM so VRAM stays free for the expert cache:
- <= 4.5 GB: 4096 when ctx > 4096
- <= 6.5 GB: 8192 when ctx > 8192
- <= 12.5 GB: 16384 when ctx > 16384
- <= 16.5 GB: 16384 at 32K, 32768 at >= 64K
- <= 24.5 GB: 32768 at >= 64K
- > 24.5 GB: 32768 at >= 128K
Disabled on UMA (shared memory gains nothing from copying RAM->RAM) and on < 16 GB RAM hosts.
"""
if explicit_kv_resident is not None:
return int(explicit_kv_resident) if int(explicit_kv_resident) > 0 else None
vram = float(vram_gb or 0.0)
ram = float(ram_gb or 0.0)
c = int(ctx)
if uma or vram <= 0.0 or ram < 16.0:
return None
if vram <= 4.5:
return 4096 if c > 4096 else None
if vram <= 6.5:
return 8192 if c > 8192 else None
if vram <= 12.5:
return 16384 if c > 16384 else None
if vram <= 16.5:
if c >= 65536:
return 32768
if c > 16384:
return 16384
return None
if vram <= 24.5:
return 32768 if c >= 65536 else None
return 32768 if c >= 131072 else None
def adaptive_cache_defaults(live_slots: int, total_pairs: int = UNSLOTH_TOTAL_EXPERT_PAIRS,
adapt_every: int | None = None, adapt_swaps: int | None = None,
adapt_decay: float | None = None) -> dict[str, Any]:
"""Issue #4870 coverage-based adaptive expert cache defaults (mirrors engine/src/program/generate.cpp).
When the VRAM expert cache holds between 15% and 65% of total layer-experts (every 6-32 GB discrete tier running
UD-Q4_K_XL, Q8_0, UD-IQ4_XS, UD-IQ3_XXS, or NVFP4), default to the faster 2 / 192 / 0.92 curve (+8% cache hit
rate, +10% decode tok/s). Explicit user overrides are never overwritten.
"""
slots = max(0, int(live_slots))
total = max(1, int(total_pairs))
cov = min(1.0, float(slots) / float(total))
if slots <= 0 or slots >= total:
def_every, def_swaps, def_decay, mode = 0, 0, 0.7, ("all_resident" if slots >= total else "zero_slot")
elif UNSLOTH_ADAPT_MIN_COV <= cov <= UNSLOTH_ADAPT_MAX_COV:
def_every, def_swaps, def_decay, mode = 2, 192, 0.92, "mid_coverage_fast"
elif cov < UNSLOTH_ADAPT_MIN_COV:
def_every, def_swaps, def_decay, mode = 4, (16 if cov < 0.125 else 32), 0.7, "low_vram_dampened"
else:
def_every, def_swaps, def_decay, mode = 4, 96, 0.7, "high_coverage_standard"
return {
"adapt_every": def_every if adapt_every is None else int(adapt_every),
"adapt_swaps": def_swaps if adapt_swaps is None else int(adapt_swaps),
"adapt_decay": def_decay if adapt_decay is None else float(adapt_decay),
"coverage": round(cov, 4),
"mode": mode,
}
def _discrete_tier_name(vram_gb: float) -> str:
for bound, label in ((4.5, "4gb"), (6.5, "6gb"), (8.5, "8gb"), (10.5, "10gb"),
(12.5, "12gb"), (16.5, "16gb"), (24.5, "24gb"), (32.5, "32gb")):
if vram_gb <= bound:
return f"discrete_{label}"
return f"discrete_{int(round(vram_gb))}gb"
def unsloth_tier_plan(model: str, vram_gb: float, ram_gb: float, ctx: int = 32768, backend: str = "cuda",
uma: bool = False, gpu_name: str = "", arch: str = "",
kv_override: str | None = None, kv_resident_override: int | None = None) -> dict[str, Any]:
"""Comprehensive Qwen3.8 / Unsloth tier planner across every GPU/RAM tier.
Handles:
- Discrete GPUs: 4, 6, 8, 10, 12, 16, 24, 32 GB (NVIDIA CUDA, AMD HIP RDNA2/3/4, Intel Arc SYCL)
- Unified Memory: NVIDIA DGX Spark (128 GB), Apple Mac Metal (16/24/32/48/64/128 GB), AMD Strix Halo (64/128 GB)
Never refuses to install or OOMs on 4 GB / 6 GB GPUs (uses 0-slot / dense-streaming + RAM/SSD cold tiers).
"""
spec = UNSLOTH_QUANTS.get(model)
if spec is None:
raise ValueError(f"Unknown Unsloth quant: {model!r}")
vram = float(vram_gb or 0.0)
ram = float(ram_gb or 0.0)
c = int(ctx)
be = str(backend or "cuda").lower()
card = {"name": gpu_name, "arch": arch, "vendor": vendor_of_backend(be), "uma": uma, "vram_gb": vram}
arena_gb = float(spec["arena_gb"])
avg_mib = float(spec["avg_expert_mib"])
max_mib = float(spec["max_expert_mib"])
dense_gb = float(spec["dense_gb"])
notes: list[str] = []
flags: list[str] = []
# ---- Unified memory tiers: DGX Spark, Mac Metal, Strix Halo ----
if is_dgx_spark_card(card):
kv = unsloth_kv_default(vram or ram, c, uma=True, explicit_kv=kv_override)
pool_gb = max(vram, ram, 128.0)
fits_all = (arena_gb + dense_gb + 12.0) <= pool_gb
slots = UNSLOTH_TOTAL_EXPERT_PAIRS if fits_all else int(max(0.0, (pool_gb - dense_gb - 16.0) * 1024.0 / avg_mib))
slots = min(slots, UNSLOTH_TOTAL_EXPERT_PAIRS)
adapt = adaptive_cache_defaults(slots)
flags = ["--mmap-experts", "--prefill", "auto:32768", "--mtp-q4", "all", "--mtp-hnorm", "stream", "--kv", kv]
if not fits_all:
budget = max(16, int(pool_gb - 20.0))
flags += ["--resident-budget-gib", str(budget)]
else:
budget = 0
return {
"tier": "dgx_spark", "model": model, "backend": "cuda", "uma": True, "runnable": True,
"kv": kv, "kv_resident": None, "mtp": True,
"expert_cache_mode": "spark_mmap_resident" if fits_all else "spark_mmap_budget",
"estimated_slots": slots, "uniform_max_blob_slots": min(UNSLOTH_TOTAL_EXPERT_PAIRS, int(slots * avg_mib / max_mib)),
"coverage": adapt["coverage"], "adaptive": adapt,
"ram_tier": "uma_unified" if fits_all else "uma_budget", "resident_budget_gib": budget,
"flags": flags, "notes": notes,
}
if is_mac_metal_card(card, be):
unified = max(ram, vram)
kv = unsloth_kv_default(unified, c, uma=True, explicit_kv=kv_override)
leave = 8.0 if unified >= 48.0 else 4.0
usable_gb = min(unified * 0.75, max(4.0, unified - leave))
kv_gb = c * 13 * UNSLOTH_KV_BYTES_PER_TOK.get(kv, 1056) / 1e9
resident = (arena_gb + dense_gb + kv_gb + 2.0) <= usable_gb
mtp = resident or unified >= 96.0
mode = "metal_resident" if resident else "metal_stream"
slots = UNSLOTH_TOTAL_EXPERT_PAIRS if resident else min(1500, int(max(0.0, (usable_gb - dense_gb - kv_gb) * 1024.0 / avg_mib)))
adapt = adaptive_cache_defaults(slots)
flags = ["--kv", kv]
if not resident:
flags.append("--mmap-experts")
notes.append("STRATA_METAL_STREAM=1 (streams cold experts from SSD through unified memory)")
if not mtp:
flags += ["--mtp", "off"]
return {
"tier": f"mac_metal_{int(round(unified))}gb", "model": model, "backend": "metal", "uma": True, "runnable": True,
"kv": kv, "kv_resident": None, "mtp": mtp,
"expert_cache_mode": mode, "estimated_slots": slots,
"uniform_max_blob_slots": min(UNSLOTH_TOTAL_EXPERT_PAIRS, int(slots * avg_mib / max_mib)),
"coverage": adapt["coverage"], "adaptive": adapt,
"ram_tier": "uma_unified" if resident else "metal_ssd_stream", "resident_budget_gib": 0,
"flags": flags, "notes": notes,
}
if uma and is_strix_halo_card(card):
total_ram = max(ram, vram)
kv = unsloth_kv_default(total_ram, c, uma=True, explicit_kv=kv_override)
pool_gb = total_ram * 0.78 # GTT + carve-out unified pool on Strix Halo (64 GB -> ~50 GB, 128 GB -> ~100 GB)
fits_pool = (6.0 + arena_gb + 4.0) <= pool_gb
slots = UNSLOTH_TOTAL_EXPERT_PAIRS if fits_pool else min(
UNSLOTH_TOTAL_EXPERT_PAIRS, int(max(256.0, (pool_gb * 0.45 - dense_gb) * 1024.0 / avg_mib)))
adapt = adaptive_cache_defaults(slots)
flags = ["--kv", kv, "--prefill", "auto:16384"]
budget = 0
if not fits_pool:
# Avoid 2x pin OOM on 64 GB Strix Halo or Q8_0 on 128 GB Strix Halo
budget = max(12, int(total_ram * 0.40))
flags += ["--expert-cache", str(slots), "--resident-budget-gib", str(budget)]
if model.lower() == STRIX_Q4_MODEL.lower():
notes.append(STRIX_Q4_NOTE)
return {
"tier": f"strix_halo_{int(round(total_ram))}gb", "model": model, "backend": "hip", "uma": True, "runnable": True,
"kv": kv, "kv_resident": None, "mtp": True,
"expert_cache_mode": "full_uma" if fits_pool else "uma_bounded_cache",
"estimated_slots": slots, "uniform_max_blob_slots": min(UNSLOTH_TOTAL_EXPERT_PAIRS, int(slots * avg_mib / max_mib)),
"coverage": adapt["coverage"], "adaptive": adapt,
"ram_tier": "uma_unified" if fits_pool else "uma_budget_ssd", "resident_budget_gib": budget,
"flags": flags, "notes": notes,
}
# ---- Discrete GPUs: 4, 6, 8, 10, 12, 16, 24, 32+ GB (CUDA / HIP / Intel Arc SYCL) ----
kv = unsloth_kv_default(vram, c, uma=False, explicit_kv=kv_override)
kv_res = unsloth_kv_resident_default(vram, ram, c, kv=kv, uma=False, explicit_kv_resident=kv_resident_override)
vram_kv_tokens = min(c, kv_res) if kv_res is not None else c
kv_vram_mib = vram_kv_tokens * 13 * UNSLOTH_KV_BYTES_PER_TOK.get(kv, 1056) / (1024.0 * 1024.0)
# 4 GB and 6 GB GPUs: drop GPU draft layer (saves ~800 MiB) and use tight reserve so dense trunk + KV always fit
mtp = vram > 6.5
mtp_mib = 802.0 if mtp else 0.0
runtime_mib = 0.0 if be == "sycl" else (256.0 if vram <= 6.5 else 384.0)
reserve_mib = 200.0 if vram <= 4.5 else (300.0 if vram <= 8.5 else 512.0)
# Dense trunk in VRAM (on 4 GB cards, output head moves to pinned host memory if needed, leaving ~2.8 GiB in VRAM)
dense_vram_mib = (dense_gb * 1024.0 - 420.0) if vram <= 4.5 else (dense_gb * 1024.0)
slack_mib = vram * 1024.0 - dense_vram_mib - mtp_mib - kv_vram_mib - runtime_mib - reserve_mib
# 4 GB & 6 GB unlock: 0-slot / dense-streaming when VRAM slack < 160 MiB (never refuse, never OOM!)
if vram <= 4.5 or slack_mib < 160.0:
est_slots = 0
uni_slots = 0
cache_mode = "zero_slot" if vram <= 4.5 else "dense_streaming"
notes.append("0-slot / dense-streaming mode: dense trunk + KV on GPU, routed experts stream from RAM/SSD (never refuses)")
else:
est_slots = min(UNSLOTH_TOTAL_EXPERT_PAIRS, int(slack_mib / avg_mib))
uni_slots = min(UNSLOTH_TOTAL_EXPERT_PAIRS, int(slack_mib / max_mib))
cache_mode = "heterogeneous_cache"
adapt = adaptive_cache_defaults(est_slots)
flags = ["--kv", kv]
if kv_res is not None:
flags += ["--kv-resident", str(kv_res)]
if not mtp:
flags += ["--mtp", "off"]
if est_slots == 0:
flags += ["--expert-cache", "0", "--no-prefill-borrow"]
elif adapt["mode"] == "mid_coverage_fast":
flags += ["--adapt-every", str(adapt["adapt_every"]), "--adapt-swaps", str(adapt["adapt_swaps"]),
"--adapt-decay", f"{adapt['adapt_decay']:g}"]
# Cold tier (RAM + SSD): never overcommit host RAM
kv_ram_gb = (c * 13 * UNSLOTH_KV_BYTES_PER_TOK.get(kv, 1056) / 1e9) if kv_res is not None else 0.0
vram_experts_gb = est_slots * avg_mib / 1024.0
cold_experts_gb = max(0.0, arena_gb - vram_experts_gb)
ram_avail_gb = max(0.0, ram - 12.0 - kv_ram_gb)
if cold_experts_gb <= ram_avail_gb:
ram_tier = "all_ram"
budget_gib = 0
elif ram_avail_gb >= 8.0:
ram_tier = "resident_budget"
budget_gib = int(ram_avail_gb)
flags += ["--resident-budget-gib", str(budget_gib)]
else:
ram_tier = "ssd_streaming"
budget_gib = 0
flags += ["--ssd-experts", "--ram-experts-gb", "0"]
return {
"tier": _discrete_tier_name(vram), "model": model, "backend": be, "uma": False, "runnable": True,
"kv": kv, "kv_resident": kv_res, "mtp": mtp,
"expert_cache_mode": cache_mode, "estimated_slots": est_slots, "uniform_max_blob_slots": uni_slots,
"coverage": adapt["coverage"], "adaptive": adapt,
"ram_tier": ram_tier, "resident_budget_gib": budget_gib,
"flags": flags, "notes": notes,
}
@@ -0,0 +1,213 @@
"""Comprehensive Unsloth tier planning tests across ALL VRAM/RAM tiers and Unsloth quants.
Verifies:
- Discrete tiers: 4, 6, 8, 10, 12, 16, 24, 32 GB across NVIDIA CUDA, AMD HIP (RDNA2/3/4), and Intel Arc SYCL
- Unified memory tiers: NVIDIA DGX Spark (128 GB), Apple Mac Metal (16/24/32/48/64/128 GB), AMD Strix Halo (64/128 GB)
- Primary Unsloth quants (UD-Q4_K_XL, Q8_0, UD-IQ4_XS, UD-IQ3_XXS) + full Unsloth catalog
(UD-Q6_K_XL, UD-Q5_K_XL, UD-Q3_K_XL, UD-Q2_K_XL, UD-IQ2_XXS, UD-IQ2_XS, UD-Q2_0, UD-IQ1_M, UD-IQ1_S)
- Issue #6354: auto --kv int8 + elastic --kv-resident on <= 16 GB GPUs and <= 24 GB GPUs at >= 64K context
- Issue #4870: coverage-based adaptive defaults (2 / 192 / 0.92) for 15%..65% VRAM coverage
- Clean 4 GB & 6 GB GPU unlock (0-slot / dense-streaming / RAM+SSD cold tiers, never refuses or OOMs)
- Heterogeneous Unsloth expert slot sizing outperforms uniform max_blob sizing on mixed-quant packs
"""
from __future__ import annotations
import unittest
import setup
from strata_control import gpu_fit as G
PRIMARY_QUANTS = ("UD-Q4_K_XL", "Q8_0", "UD-IQ4_XS", "UD-IQ3_XXS")
ALL_UNSLOTH_QUANTS = (
"UD-Q4_K_XL", "Q8_0", "UD-IQ4_XS", "UD-IQ4_XS-v31", "UD-IQ3_XXS",
"UD-Q6_K_XL", "UD-Q5_K_XL", "UD-Q3_K_XL", "UD-Q2_K_XL",
"UD-IQ2_XXS", "UD-IQ2_XS", "UD-Q2_0", "UD-IQ1_M", "UD-IQ1_S",
)
DISCRETE_TIERS = (4.0, 6.0, 8.0, 10.0, 12.0, 16.0, 24.0, 32.0)
class DiscreteTiersAllQuants(unittest.TestCase):
def test_every_discrete_tier_and_primary_quant_is_runnable_across_backends(self):
backends = (
("cuda", "NVIDIA GeForce RTX", "sm_89"),
("hip", "AMD Radeon RX RDNA3", "gfx1100"),
("hip", "AMD Radeon RX RDNA4", "gfx1201"),
("hip", "AMD Radeon RX RDNA2", "gfx1030"),
("sycl", "Intel Arc B580", "xe2"),
)
for backend, name, arch in backends:
for vram in DISCRETE_TIERS:
for model in PRIMARY_QUANTS:
plan = G.unsloth_tier_plan(model, vram_gb=vram, ram_gb=64.0, ctx=32768,
backend=backend, gpu_name=name, arch=arch)
self.assertTrue(plan["runnable"], (backend, vram, model))
self.assertEqual(plan["backend"], backend)
self.assertEqual(plan["model"], model)
self.assertFalse(plan["uma"])
self.assertIn("--kv", plan["flags"])
def test_all_14_unsloth_quants_supported_across_all_discrete_tiers(self):
for model in ALL_UNSLOTH_QUANTS:
self.assertIn(model, G.UNSLOTH_QUANTS)
for vram in DISCRETE_TIERS:
plan = G.unsloth_tier_plan(model, vram_gb=vram, ram_gb=64.0, ctx=32768)
self.assertTrue(plan["runnable"], (model, vram))
self.assertEqual(plan["tier"], f"discrete_{int(vram)}gb")
def test_4gb_and_6gb_unlock_cleanly_never_refuse_or_oom(self):
for vram in (4.0, 6.0):
for ram in (16.0, 32.0, 64.0):
for model in PRIMARY_QUANTS:
plan = G.unsloth_tier_plan(model, vram_gb=vram, ram_gb=ram, ctx=32768)
self.assertTrue(plan["runnable"], (vram, ram, model))
self.assertFalse(plan["mtp"], f"MTP must stay off on {vram} GB to protect VRAM")
self.assertEqual(plan["kv"], "int8")
self.assertIsNotNone(plan["kv_resident"])
if vram <= 4.5:
self.assertEqual(plan["expert_cache_mode"], "zero_slot")
self.assertEqual(plan["estimated_slots"], 0)
self.assertIn("--expert-cache", plan["flags"])
self.assertIn("--no-prefill-borrow", plan["flags"])
if ram == 16.0:
self.assertEqual(plan["ram_tier"], "ssd_streaming")
self.assertIn("--ssd-experts", plan["flags"])
# setup.unsloth_small_card_plan also never returns None for 4 GB / 6 GB cards
for vram in (4.0, 6.0):
sp = setup.unsloth_small_card_plan(vram, ctx=32768, kv="int8", reserve_mib=None)
self.assertIsNotNone(sp, f"setup.unsloth_small_card_plan refused {vram} GB")
c0, k0, mtp0, slack0 = sp
self.assertFalse(mtp0)
self.assertGreaterEqual(slack0, 0.0)
lines = setup.unsloth_small_card_lines("UD-Q4_K_XL", vram, sp, start_ok=True)
self.assertTrue(any("0-slot" in ln for ln in lines))
def test_heterogeneous_sizing_beats_uniform_max_blob(self):
for model in ("UD-Q4_K_XL", "UD-IQ4_XS", "UD-IQ3_XXS", "UD-Q2_K_XL", "UD-IQ1_M"):
plan = G.unsloth_tier_plan(model, vram_gb=16.0, ram_gb=64.0, ctx=32768)
self.assertGreater(plan["estimated_slots"], plan["uniform_max_blob_slots"],
f"{model} heterogeneous sizing should fit strictly more slots than uniform max_blob")
class KvInt8AndElasticResident6354(unittest.TestCase):
def test_auto_int8_kv_on_16gb_and_below_at_any_context(self):
for vram in (4.0, 6.0, 8.0, 10.0, 12.0, 16.0):
for ctx in (4096, 8192, 16384, 32768, 65536):
self.assertEqual(G.unsloth_kv_default(vram, ctx), "int8", (vram, ctx))
def test_auto_int8_and_elastic_kv_resident_on_24gb_at_64k(self):
self.assertEqual(G.unsloth_kv_default(24.0, 65536), "int8")
self.assertEqual(G.unsloth_kv_resident_default(24.0, 64.0, 65536), 32768)
self.assertIsNone(G.unsloth_kv_resident_default(24.0, 64.0, 32768))
# Explicit user override is always respected
self.assertEqual(G.unsloth_kv_default(12.0, 32768, explicit_kv="q4_0"), "q4_0")
self.assertEqual(G.unsloth_kv_resident_default(12.0, 64.0, 32768, explicit_kv_resident=8192), 8192)
def test_12gb_and_16gb_enable_elastic_kv_resident_at_32k_and_64k(self):
for vram in (8.0, 10.0, 12.0, 16.0):
p32 = G.unsloth_tier_plan("UD-Q4_K_XL", vram_gb=vram, ram_gb=64.0, ctx=32768)
self.assertEqual(p32["kv"], "int8")
self.assertEqual(p32["kv_resident"], 16384, (vram, p32))
self.assertIn("--kv-resident", p32["flags"])
p16_64 = G.unsloth_tier_plan("UD-IQ4_XS", vram_gb=16.0, ram_gb=64.0, ctx=65536)
self.assertEqual(p16_64["kv"], "int8")
self.assertEqual(p16_64["kv_resident"], 32768)
def test_setup_kv_streaming_wanted_works_for_unsloth_budget_models(self):
# 12 GB + 32 GB RAM running UD-Q4_K_XL at 32K or 64K must allow KV streaming (budget subtracts KV RAM)
self.assertTrue(setup.kv_streaming_wanted("UD-Q4_K_XL", 32768, "int8", 32.0, vram_gb=12.0))
self.assertTrue(setup.kv_streaming_wanted("UD-Q4_K_XL", 65536, "int8", 32.0, vram_gb=12.0))
self.assertTrue(setup.kv_streaming_wanted("Q8_0", 65536, "int8", 64.0, vram_gb=24.0))
self.assertFalse(setup.kv_streaming_wanted("UD-Q4_K_XL", 65536, "int8", 64.0, choice="off", vram_gb=12.0))
class AdaptiveDefaults4870(unittest.TestCase):
def test_mid_coverage_15_to_65_percent_uses_2_192_092(self):
import math
for cov_pct in (15, 20, 30, 45, 65):
slots = int(math.ceil(G.UNSLOTH_TOTAL_EXPERT_PAIRS * cov_pct / 100.0)) if cov_pct == 15 else int(G.UNSLOTH_TOTAL_EXPERT_PAIRS * cov_pct / 100.0)
d = G.adaptive_cache_defaults(slots)
self.assertEqual(d["mode"], "mid_coverage_fast", cov_pct)
self.assertEqual((d["adapt_every"], d["adapt_swaps"], d["adapt_decay"]), (2, 192, 0.92))
def test_low_and_high_coverage_bands_and_explicit_overrides(self):
low = G.adaptive_cache_defaults(int(G.UNSLOTH_TOTAL_EXPERT_PAIRS * 0.10))
self.assertEqual(low["mode"], "low_vram_dampened")
self.assertEqual((low["adapt_every"], low["adapt_swaps"], low["adapt_decay"]), (4, 16, 0.7))
high = G.adaptive_cache_defaults(int(G.UNSLOTH_TOTAL_EXPERT_PAIRS * 0.80))
self.assertEqual(high["mode"], "high_coverage_standard")
self.assertEqual((high["adapt_every"], high["adapt_swaps"], high["adapt_decay"]), (4, 96, 0.7))
# User CLI overrides are preserved
ovr = G.adaptive_cache_defaults(int(G.UNSLOTH_TOTAL_EXPERT_PAIRS * 0.35),
adapt_every=6, adapt_swaps=64, adapt_decay=0.8)
self.assertEqual((ovr["adapt_every"], ovr["adapt_swaps"], ovr["adapt_decay"]), (6, 64, 0.8))
def test_tier_plan_emits_4870_flags_in_mid_coverage_tiers(self):
# 16 GB / 24 GB / 32 GB running UD-Q4_K_XL / UD-IQ4_XS / UD-IQ3_XXS land squarely in 15%-65% coverage
plan = G.unsloth_tier_plan("UD-Q4_K_XL", vram_gb=24.0, ram_gb=64.0, ctx=32768)
self.assertEqual(plan["adaptive"]["mode"], "mid_coverage_fast")
self.assertIn("--adapt-every", plan["flags"])
self.assertIn("2", plan["flags"])
self.assertIn("192", plan["flags"])
self.assertIn("0.92", plan["flags"])
class UnifiedMemoryTiers(unittest.TestCase):
def test_dgx_spark_128gb_all_primary_quants(self):
for model in PRIMARY_QUANTS:
plan = G.unsloth_tier_plan(model, vram_gb=128.0, ram_gb=128.0, ctx=32768,
backend="cuda", uma=True, gpu_name="NVIDIA GB10 DGX Spark", arch="sm_121")
self.assertEqual(plan["tier"], "dgx_spark")
self.assertTrue(plan["runnable"])
self.assertTrue(plan["uma"])
self.assertEqual(plan["kv"], "int8")
self.assertIsNone(plan["kv_resident"])
self.assertIn("--mmap-experts", plan["flags"])
self.assertIn("auto:32768", plan["flags"])
if model == "Q8_0":
self.assertEqual(plan["expert_cache_mode"], "spark_mmap_budget")
self.assertGreater(plan["resident_budget_gib"], 0)
else:
self.assertEqual(plan["expert_cache_mode"], "spark_mmap_resident")
def test_mac_metal_16_to_128gb_all_primary_quants(self):
for unified in (16.0, 24.0, 32.0, 48.0, 64.0, 128.0):
for model in PRIMARY_QUANTS:
plan = G.unsloth_tier_plan(model, vram_gb=0.0, ram_gb=unified, ctx=32768,
backend="metal", uma=True, gpu_name="Apple M4 Max")
self.assertEqual(plan["tier"], f"mac_metal_{int(unified)}gb")
self.assertTrue(plan["runnable"])
self.assertEqual(plan["backend"], "metal")
self.assertEqual(plan["kv"], "int8")
self.assertIsNone(plan["kv_resident"])
if unified <= 64.0 and model in ("UD-Q4_K_XL", "Q8_0"):
self.assertEqual(plan["expert_cache_mode"], "metal_stream")
self.assertIn("--mmap-experts", plan["flags"])
if unified == 128.0 and model in ("UD-Q4_K_XL", "UD-IQ4_XS", "UD-IQ3_XXS"):
self.assertEqual(plan["expert_cache_mode"], "metal_resident")
self.assertTrue(plan["mtp"])
def test_strix_halo_64gb_and_128gb_all_primary_quants(self):
for total_ram in (64.0, 128.0):
for model in PRIMARY_QUANTS:
plan = G.unsloth_tier_plan(model, vram_gb=total_ram * 0.75, ram_gb=total_ram, ctx=32768,
backend="hip", uma=True, gpu_name="AMD Radeon 8060S (Strix Halo)", arch="gfx1151")
self.assertEqual(plan["tier"], f"strix_halo_{int(total_ram)}gb")
self.assertTrue(plan["runnable"])
self.assertEqual(plan["backend"], "hip")
self.assertEqual(plan["kv"], "int8")
self.assertIsNone(plan["kv_resident"])
if model == "UD-Q4_K_XL":
self.assertIn(G.STRIX_Q4_NOTE, plan["notes"])
if total_ram == 64.0:
# 64 GB Strix Halo must use bounded cache + budget to avoid 2x pin OOM
self.assertEqual(plan["expert_cache_mode"], "uma_bounded_cache")
self.assertIn("--resident-budget-gib", plan["flags"])
elif model != "Q8_0":
self.assertEqual(plan["expert_cache_mode"], "full_uma")
if __name__ == "__main__":
unittest.main()