From 2b4465edcad54de1ff27c1ae517319129b644a6e Mon Sep 17 00:00:00 2001 From: yhirose Date: Sat, 7 Nov 2026 10:47:41 -0500 Subject: [PATCH 1/3] metal: the quantized prefill GEMM over half tiles, its sums f32 Metal's prefill ran a block-quantized weight's GEMM over f32 tiles, its exact form, since the backend has no f16 activations; a bf16 weight's already took the f16 trade under f16_acc. - gpu::gemm_quant_f16 (gpu_ops_nn.h): A and the dequantized weight rounded to f16 as they are staged, the sums f32, as llama.cpp's Metal kernel_mul_mm. f16's range, so the caller checks for inf as with gemm_bf16_nt_f16acc; a backend without the form (CUDA) runs gemm_quant's exact one. - STEEL's SteelMMA and steel_body_ take the sums' type (AT) apart from the tiles' (ST). TL_STEEL_KERNEL_ST keeps AT = ST, so gemm_bf16_f16acc_ still sums in half. - Each block format gets gemm__f16_ and _f16_32_ (half tiles, f32 sums, K step 32). quant_fmt holds its GEMMs as gemm[f16][band32], and detail_::gemm_quant_run_ launches either form. - qwen.h: prefill_sums_f16 becomes prefill_gemm_f16, true for a quantized model where the backend has f16 activations or this form; the prefill's quantized GEMMs take it when not on f16 activations. check_qwen's check_f16_sums becomes check_f16_gemms, and now runs on Metal's quantized models. Summing in half too was 5 to 9% faster still, but on check_qwen's 96-token prompt its top-5 logits were 5.2e-2 (Qwen3 0.6B Q4_K_M) and 4.1e-2 (Qwen3.5 0.8B Q4_K_M) off the f32 forward's, past the check's 2e-2; with f32 sums they are 4.5e-4 and 9.5e-4. pp512 (bench_qwen_llama, M1 Pro, tok/s, alternating), before -> after: Gemma 4 E2B 1517 -> 1603, E4B 493 -> 528, Qwen3 0.6B Q4_K_M 2474 -> 2662, Llama 3.2 1B Q4_K_M 1298 -> 1399, Gemma 3 1B 1547 -> 1634, Qwen3.5 0.8B Q4_K_M 1422 -> 1498. Tests: test_nn's GEMM over block-quantized rows runs both forms, the f16 one to 3e-4 of the terms' magnitude (9.6e-5 measured; a misread weight is off by ~1/K), skipped where the backend has no such form. Mutants fail it: q4k's f16 kernels bound to q6k's, q80's 32-row one to q40's, the bands swapped, the sums half (42 failures). Tiles left f32 pass it but fail check_qwen's overflow check (no retry). check_qwen is ALL OK on Gemma 4 E2B and E4B, Gemma 3 1B, PLaMo 3 0.8B, Qwen3 0.6B Q4_K_M and F16, Qwen3.5 0.8B Q4_K_M, and Llama 3.2 1B Q4_K_M, Q4_0 and Q5_K_M, f16 GEMMs within 7.2e-5 to 9.5e-4 and one overflow retry each. The test case takes 0.72 s (0.68 before); ctest 10.5 s. Not changed here: Metal's bf16 f16-sum GEMM is 3.2e-2 off on the same 96-token prompt (Qwen3 0.6B F16), a check its path never runs. --- bench/models/check_qwen.cpp | 41 +++++++-------- bench/models/qwen.h | 41 +++++++++------ docs/backends.md | 5 +- include/gpu_ops_nn.h | 15 ++++++ include/metal_kernels.metal | 37 +++++++------ include/metal_kernels_nn.metal | 13 +++-- include/metal_nn.h | 94 +++++++++++++++++++++++++++------- test/test_nn.cpp | 71 ++++++++++++++----------- 8 files changed, 210 insertions(+), 107 deletions(-) diff --git a/bench/models/check_qwen.cpp b/bench/models/check_qwen.cpp index 610dc22..95fd9d2 100644 --- a/bench/models/check_qwen.cpp +++ b/bench/models/check_qwen.cpp @@ -173,28 +173,29 @@ static void fixed_sums(bool on) { #endif } -// The batched prefill's f16 sums (the default where the backend has them), -// against `ref`, an f32 forward's logits for the same prompt: the top-5 logits to -// 2e-2 and the same greedy token (a sensitive model's as Oracle::agree holds -// it). Then the safety net: with the first layer's FFN norm scaled by 1e5 the -// f16 sums overflow (the MLP's input -// passes f16's range), and the prompt must be redone once, exactly, from the -// state it started at: an exact prefill of the same model, both with their -// sums in a fixed order (fixed_sums). Split-K's atomics would move them apart +// The batched prefill's f16 GEMMs (the default where the backend has them: +// sums f16, or a block-quantized weight's operands f16 over f32 sums), against +// `ref`, an f32 forward's logits for the same prompt: the top-5 logits to 2e-2 +// and the same greedy token (a sensitive model's as Oracle::agree holds it). +// Then the safety net: with the first layer's FFN norm scaled by 1e5 the f16 +// GEMMs overflow (the MLP's input passes f16's range), and the prompt must be +// redone once, exactly, from the state it started at: an exact prefill of the +// same model, both with their sums in a fixed order (fixed_sums). Split-K's +// atomics would move them apart // by their own rounding, which Gemma 4 E2B grows to 2e-3 to 6e-3; a missed // restore is off by far more. -static bool check_f16_sums(qm::Model& B, const std::vector& ids, - const std::vector& ref, const Oracle& O) { +static bool check_f16_gemms(qm::Model& B, const std::vector& ids, + const std::vector& ref, const Oracle& O) { const bool was = B.f16_acc; B.f16_acc = true; - if (!qm::prefill_sums_f16(B, false)) { // nothing to hold: its prefill sums in f32 still - std::printf("\nf16 sums: none on this build (block-quantized weights, f32 activations) — skipped\n"); + if (!qm::prefill_gemm_f16(B, false)) { // nothing to hold: its prefill GEMMs are exact still + std::printf("\nf16 GEMMs: none on this build for block-quantized weights, skipped\n"); B.f16_acc = was; return true; } qm::reset_cache(B); const int64_t tok = qm::prefill_batched(B, ids); - std::printf("\nf16 sums vs f32: "); + std::printf("\nf16 GEMMs vs f32: "); const bool close = O.agree(ref, logits_of(B), 2e-2) && (O.sensitive || tok == qm::argmax(ref)); std::printf(", token %lld %s\n", (long long)tok, close ? "OK" : "FAIL"); @@ -370,8 +371,8 @@ static bool check_imperative(const qm::gg::model& m, const Oracle& O, bool held) // that is the model's (Gemma 3 ~70x Qwen's: docs/llama-cpp-comparison.md, // "Accuracy"), so the structural checks below read the blocks with float // activations, where their bounds hold for every model, and the default forms - // are held to the f32 reference after them. The checks run the f32 sums, so - // their bounds stay tight; check_f16_sums holds the default f16 ones to the + // are held to the f32 reference after them. The checks run the exact GEMMs, so + // their bounds stay tight; check_f16_gemms holds the default f16 ones to the // same prompts after. const int64_t NB = 8; qm::Model B = qm::build(m, tl::dtype::bf16, false, false, 4096, /*oracle=*/false, @@ -529,9 +530,9 @@ static bool check_imperative(const qm::gg::model& m, const Oracle& O, bool held) std::printf(" %s\n", one_ok ? "OK" : "FAIL"); } const bool f16_ok = !qm::can_prefill_batched(B, (int64_t)longp.size()) || - check_f16_sums(B, longp, imp_long, O); + check_f16_gemms(B, longp, imp_long, O); - // The chat's own defaults, its activation forms and f16 sums: the decoder's logits + // The chat's own defaults, its activation forms and f16 GEMMs: the decoder's logits // after a spread-out prompt, held to the f32 forward's by the KL of their // distributions (a chat prompt's next token is too certain for one position to // show anything: Gemma 3 4B's KL there is ~1e-13 though its logits move by up to @@ -545,7 +546,7 @@ static bool check_imperative(const qm::gg::model& m, const Oracle& O, bool held) B.f16_acc = true; // A quantized file's (ref_spread is its f32 forward's), where its forms are not // the f32 ones the checks above ran. - const bool mmq = qm::prefill_mmq(B, false), f16 = qm::prefill_sums_f16(B, false); + const bool mmq = qm::prefill_mmq(B, false), f16 = qm::prefill_gemm_f16(B, false); if (B.quant && (chat_form != tl::gpu::act_form::f32 || mmq || f16)) { B.gemv_form = chat_form; qm::reset_cache(B); @@ -553,7 +554,7 @@ static bool check_imperative(const qm::gg::model& m, const Oracle& O, bool held) d.begin(B, spread); const std::vector got = logits_of(B); d.destroy(); - std::printf("\nthe chat's defaults (decode GEMV activations %s, prefill MMQ %s, sums in %s), a " + std::printf("\nthe chat's defaults (decode GEMV activations %s, prefill MMQ %s, GEMMs %s), a " "spread-out prompt, from the f32 forward: ", qm::act_form_name(chat_form), mmq ? "on" : "off", f16 ? "f16" : "f32"); defaults_ok = kl_agree(ref_spread, got); @@ -757,7 +758,7 @@ int main(int argc, char** argv) { for (auto t : got) std::printf(" %lld", (long long)t); bf16_ok = got == want; std::printf("\n greedy %s\n", bf16_ok ? "MATCH" : "DIVERGE"); - bf16_ok &= check_f16_sums(B, ids, array_prompt, O); + bf16_ok &= check_f16_gemms(B, ids, array_prompt, O); bf16_ok &= check_sampled(B, ids); } } diff --git a/bench/models/qwen.h b/bench/models/qwen.h index dc979fd..540d0a7 100644 --- a/bench/models/qwen.h +++ b/bench/models/qwen.h @@ -958,10 +958,11 @@ struct Model { bool row = false; // imperative gemvs use warp-per-row [N,K] (bf16 only) bool q4_mlp = false; // imperative MLP gemvs (wgu, wd) use q4 bool q4_lmhead = false; // imperative lm_head gemv uses q4 - // The batched prefill's GEMMs sum in f16 where the backend can (twice the - // tensor-core rate here, at a small cost in precision). A prompt whose - // logits come out non-finite — an f16 overflow, in these sums or in the - // attention's f16 operands — is redone exactly (prefill_batched), and + // The batched prefill's GEMMs take f16 where the backend can + // (prefill_gemm_f16: f16 sums, twice the tensor-core rate here, or f16 + // operands over f32 sums), at a small cost in precision. A prompt whose + // logits come out non-finite (an f16 overflow, in these GEMMs or in the + // attention's f16 operands) is redone exactly (prefill_batched), and // counted in f16_retries. bool f16_acc = false; int64_t f16_retries = 0; @@ -1167,14 +1168,16 @@ inline void set_cache_pos(Model& M, int64_t p) { // The batched prefill's f16 forms, in one place (prefill_chunk_ takes them, the // checks ask): its activations are f16 (a16) where f16_acc asks for f16 and the -// backend has the producers that write them; its GEMMs sum in f16 under f16_acc, -// a bf16 weight's on either activation (gemm_bf16_nt_f16acc reads f32 too), a -// block-quantized one's only on f16 ones. The exact form takes neither. +// backend has the producers that write them; its GEMMs take f16's precision and +// range under f16_acc (prefill_gemm_f16): a bf16 weight's sums f16 on either +// activation (gemm_bf16_nt_f16acc reads f32 too), a block-quantized one's sums +// f16 on f16 activations, or its operands f16 where the backend has that form +// over f32 ones (gemm_quant_f16). The exact form takes none. inline bool prefill_a16(const Model& M, bool exact) { return M.f16_acc && !exact && gpu::f16_activations; } -inline bool prefill_sums_f16(const Model& M, bool exact) { - return M.f16_acc && !exact && (!M.quant || gpu::f16_activations); +inline bool prefill_gemm_f16(const Model& M, bool exact) { + return M.f16_acc && !exact && (!M.quant || gpu::f16_activations || gpu::has_gemm_quant_f16); } // MMQ (block-quantized weights' int8 GEMM) quantizes the f16 activation a16 // makes, so it runs only where that is made. @@ -1199,8 +1202,8 @@ inline bool prefill_mmq(const Model& M, bool exact) { return M.mmq && prefill_a1 // // bf16 row-major weights only (the layout gemm_bf16_nt shares with the decode // GEMV); callers check Model.row and fall back to token-by-token otherwise. -// `exact` runs the chunk at full precision — the GEMMs' sums in f32 and the -// attention's operands f32 — as the retry after an f16 overflow does. +// `exact` runs the chunk at full precision (the GEMMs' operands and sums f32, +// and the attention's operands f32), as the retry after an f16 overflow does. // // The layers past the KV-sharing line (Config::KV_SHARED) write no cache, so a // prompt needs them for its last row alone (llama.cpp's prune_shared): a chunk @@ -1225,6 +1228,7 @@ inline int64_t prefill_chunk_(Model& M, int64_t T, bool exact = false, bool last mmq = T > 1 && prefill_mmq(M, exact); }; set_forms(); + const bool gemm_f16 = prefill_gemm_f16(M, exact); // A GEMM a run of one format, each into its columns of y. The bf16 GEMMs // write y densely, so a bf16 run is the whole projection, as every bf16 build // loads it (load_wmat). @@ -1233,10 +1237,13 @@ inline int64_t prefill_chunk_(Model& M, int64_t T, bool exact = false, bool last if (T == 1) return gemv_m(W, a, y, exact ? gpu::act_form::f32 : M.gemv_form, sp(M.scratch.act)); for (const auto& p : W.parts) { - const gpu::span w = W.at(p); + const gpu::span w = W.at(p), yp = y.at(p.row_off * 4); if (p.type != bf16_type) { - if (!gpu::gemm_quant(p.type, a16, a16 ? a16s : a, w, y.at(p.row_off * 4), T, p.rows, - k, n, mmq)) + const bool ran = + a16 ? gpu::gemm_quant(p.type, true, a16s, w, yp, T, p.rows, k, n, mmq) + : gemm_f16 ? gpu::gemm_quant_f16(p.type, a, w, yp, T, p.rows, k, n) + : gpu::gemm_quant(p.type, false, a, w, yp, T, p.rows, k, n); + if (!ran) throw std::logic_error("qwen: the block-quantized prefill GEMM refused its operands"); continue; } @@ -1246,7 +1253,7 @@ inline int64_t prefill_chunk_(Model& M, int64_t T, bool exact = false, bool last if (a16) { if (!gpu::gemm_bf16_nt_f16acc_a16(a16s, w, y, T, n, k)) throw std::logic_error("qwen: the f16 prefill GEMM refused its operands"); - } else if (prefill_sums_f16(M, exact)) gpu::gemm_bf16_nt_f16acc(a, w, y, T, n, k); + } else if (gemm_f16) gpu::gemm_bf16_nt_f16acc(a, w, y, T, n, k); else gpu::gemm_bf16_nt(a, w, y, T, n, k); } }; @@ -1469,8 +1476,8 @@ inline int64_t prefill_batched(Model& M, const std::vector& ids, run(true); return argmax_logits(M); } - // f16 operands can overflow — the attention's always, the GEMMs' sums under - // f16_acc — and an inf anywhere reaches every logit as NaN through the next + // f16 can overflow (the attention's operands always, the GEMMs' sums or + // operands under f16_acc), and an inf anywhere reaches every logit as NaN through the next // RMSNorm, so a non-finite logit sum is the test. The retry is exact, so it // cannot overflow the same way; first the sequence goes back to where it // started: the caches' position, and a DeltaNet layer's state, which the diff --git a/docs/backends.md b/docs/backends.md index f506d6e..ea2c7e6 100644 --- a/docs/backends.md +++ b/docs/backends.md @@ -208,7 +208,10 @@ backend's kernel and requires the same numbers. What each backend covers: CUDA has kernels in all three layers; so does Metal, short of the graph-capture forms, the forms over f16 activations (`gemm_quant_glu` among them) and the prepared activations of the -block-quantized GEMVs (`prepare_act`, `quant_act_reads`, `gemv_quant_act`); WebGPU is general tensor computation (the core layer, plus +block-quantized GEMVs (`prepare_act`, `quant_act_reads`, `gemv_quant_act`). +In place of the f16-activation forms Metal has one of its own, +`gemm_quant_f16` (the quantized prefill GEMM over f16 operands, its sums +f32). WebGPU is general tensor computation (the core layer, plus the nn kernels that pay off in a browser: softmax, layer norm, RoPE) and leaves the llm layer to the compositions, short of the small pieces of the decode contract (`argmax_to`, `embed_row` on f32 tables, `read_later`). diff --git a/include/gpu_ops_nn.h b/include/gpu_ops_nn.h index e78ae73..14950aa 100644 --- a/include/gpu_ops_nn.h +++ b/include/gpu_ops_nn.h @@ -723,6 +723,21 @@ inline bool gemm_quant(int type, bool a16, span A, span W, span C, int64_t m, in } } +// The same product of an f32 A over f16 operands: A and the dequantized weight +// rounded to f16 as they are staged, the sums f32 (Metal's, where the prefill +// has no f16 activations; llama.cpp's Metal GEMM). f16's range, as +// gemm_bf16_nt_f16acc's: an activation past 65504 turns to inf, which the +// caller must check for. A backend without the form runs gemm_quant's exact one. +TL_GPU_DETECT_OWN(gemm_quant_f16) +template +inline bool gemm_quant_f16(int type, span A, span W, span C, int64_t m, int64_t n, + int64_t k, int64_t ldc) { + if constexpr (detail::owns_gemm_quant_f16::value) { + if (detail::ran(Own::gemm_quant_f16(type, A, W, C, m, n, k, ldc))) return true; + } + return gemm_quant(type, false, A, W, C, m, n, k, ldc); +} + // act(gate) * up of a fused gate|up block-quantized projection in one MMQ GEMM (see // own::gemm_quant_glu in cuda.h). False where the backend has none or it does not apply. TL_GPU_DETECT_OWN(gemm_quant_glu) diff --git a/include/metal_kernels.metal b/include/metal_kernels.metal index 49e7e55..1deff35 100644 --- a/include/metal_kernels.metal +++ b/include/metal_kernels.metal @@ -391,8 +391,8 @@ static inline uint frag_col_(uint lane) { // 16-byte boundaries and stagger across the threadgroup banks. template constexpr short steel_pad_() { return 16 / sizeof(ST); } -// The tiles hold ST: float, or half for a GEMM summed in f16 (the MMA -// multiplies and sums in the tiles' type). +// The tiles hold ST: float, or half for a GEMM over f16 operands (the MMA +// multiplies in the tiles' type, and sums in SteelMMA's AT). template struct SteelLoader { @@ -662,10 +662,12 @@ METAL_FUNC SteelLoaderF steel_b_( return {f, col0, Bs, sid, lane}; } +// ST the tiles' type, AT the sums' (ST, or float over half tiles). template + short lda_tgp, short ldb_tgp, typename ST = float, typename AT = ST> struct SteelMMA { typedef vec frag_type; + typedef vec acc_type; STEEL_CONST short kFrag = 8; STEEL_CONST short TM = BM / (kFrag * WM); STEEL_CONST short TN = BN / (kFrag * WN); @@ -680,7 +682,7 @@ struct SteelMMA { frag_type Atile[TM]; frag_type Btile[TN]; - frag_type Ctile[TM * TN]; + acc_type Ctile[TM * TN]; short sm, sn; short As_off, Bs_off; @@ -698,7 +700,7 @@ struct SteelMMA { sm += tm; sn += tn; STEEL_PRAGMA_UNROLL - for (short i = 0; i < TM * TN; i++) Ctile[i] = frag_type(0); + for (short i = 0; i < TM * TN; i++) Ctile[i] = acc_type(0); } METAL_FUNC static constexpr void load_frag_contig( @@ -712,14 +714,15 @@ struct SteelMMA { } METAL_FUNC static constexpr void frag_mma( - thread frag_type& D, thread frag_type& A, - thread frag_type& B, thread frag_type& C) { - simdgroup_matrix A_mat, B_mat, C_mat; + thread acc_type& D, thread frag_type& A, + thread frag_type& B, thread acc_type& C) { + simdgroup_matrix A_mat, B_mat; + simdgroup_matrix C_mat; reinterpret_cast(A_mat.thread_elements()) = A; reinterpret_cast(B_mat.thread_elements()) = B; - reinterpret_cast(C_mat.thread_elements()) = C; + reinterpret_cast(C_mat.thread_elements()) = C; simdgroup_multiply_accumulate(C_mat, A_mat, B_mat, C_mat); - D = reinterpret_cast(C_mat.thread_elements()); + D = reinterpret_cast(C_mat.thread_elements()); } // Per kk step: load one K-slice of fragments, immediately MMA, serpentine @@ -808,8 +811,8 @@ struct SteelMMA { // view (backward-pass matmuls, attention's Q·Kᵀ); the MMA stays NN. B is // whatever steel_b_ takes: a pointer, or a functor over W's rows. C's rows // are p.ldc apart. -template +template void steel_body_(device const float* A, BSrc B, device float* C, constant gemm_params& p, threadgroup ST* As, threadgroup ST* Bs, @@ -836,7 +839,7 @@ void steel_body_(device const float* A, BSrc B, loader_a(A, int(p.lda), As, sid, ushort(lane)); auto loader_b = steel_b_( B, p, col0, Bs, ushort(sid), ushort(lane)); - SteelMMA mma_op(sid, lane); + SteelMMA mma_op(sid, lane); int k_iters = int(p.K / BK); short lbk = short(p.K) - short(k_iters * BK); @@ -923,8 +926,8 @@ void steel_body_(device const float* A, BSrc B, // BT: B's element type (float here; a bf16 weight's ushort in the nn layer); // BSRC what steel_body_ reads B through: B itself, or a reader f(n, k) over // it (the nn layer's GGUF formats), built after the slice moved B; ST the -// tiles' type, which the product is summed in; BK the K step. -#define TL_STEEL_KERNEL_BK(name, BM, TA, TB, BT, BSRC, ST, BK) \ +// tiles' type, AT the sums' (TL_STEEL_KERNEL_ST sums in ST); BK the K step. +#define TL_STEEL_KERNEL_BK(name, BM, TA, TB, BT, BSRC, ST, AT, BK) \ kernel void name(device const float* A [[buffer(0)]], \ device const BT* B [[buffer(1)]], \ device float* C [[buffer(2)]], \ @@ -935,10 +938,10 @@ void steel_body_(device const float* A, BSrc B, threadgroup ST As[BM * (BK + steel_pad_())]; \ threadgroup ST Bs[BK * (64 + steel_pad_())]; \ gemm_slice_(A, B, C, p, tgid.z); \ - steel_body_(A, BSRC, C, p, As, Bs, tgid, sid, lane); \ + steel_body_(A, BSRC, C, p, As, Bs, tgid, sid, lane); \ } #define TL_STEEL_KERNEL_ST(name, BM, TA, TB, BT, BSRC, ST) \ - TL_STEEL_KERNEL_BK(name, BM, TA, TB, BT, BSRC, ST, 16) + TL_STEEL_KERNEL_BK(name, BM, TA, TB, BT, BSRC, ST, ST, 16) #define TL_STEEL_KERNEL_SRC(name, BM, TA, TB, BT, BSRC) \ TL_STEEL_KERNEL_ST(name, BM, TA, TB, BT, BSRC, float) #define TL_STEEL_KERNEL(name, BM, TA, TB, BT) \ diff --git a/include/metal_kernels_nn.metal b/include/metal_kernels_nn.metal index 96e75c6..f98f0b1 100644 --- a/include/metal_kernels_nn.metal +++ b/include/metal_kernels_nn.metal @@ -1354,12 +1354,19 @@ TL_STEEL_KERNEL_SRC(gemm_bf16_nt32_, 32, false, true, ushort, TL_READ_BF16) // the K-quants' readers (one scale decoded for them) or two of the others', // and a step's barriers serve twice the weights. Against a step of 16, at // Gemma 4 E2B's and E4B's MLP shapes (512 rows): Q4_K 2 to 3% faster, Q5_K 7 -// to 8%, Q6_K 15%. +// to 8%, Q6_K 15%. Each also over half tiles (gpu_ops_nn.h's gemm_quant_f16): +// A and the dequantized weight rounded to half as they are staged, the sums +// f32 (llama.cpp's kernel_mul_mm). Summed in half too, pp512 was 5 to 9% +// faster still, and the logits 40 to 120 times as far off the f32 forward's. #define TL_GEMM_Q(F) \ TL_STEEL_KERNEL_BK(gemm_##F##_nt_, 64, false, true, uchar, \ - TL_READ_Q(read_##F##_), float, 32) \ + TL_READ_Q(read_##F##_), float, float, 32) \ TL_STEEL_KERNEL_BK(gemm_##F##_nt32_, 32, false, true, uchar, \ - TL_READ_Q(read_##F##_), float, 32) + TL_READ_Q(read_##F##_), float, float, 32) \ + TL_STEEL_KERNEL_BK(gemm_##F##_f16_, 64, false, true, uchar, \ + TL_READ_Q(read_##F##_), half, float, 32) \ + TL_STEEL_KERNEL_BK(gemm_##F##_f16_32_, 32, false, true, uchar, \ + TL_READ_Q(read_##F##_), half, float, 32) TL_GEMM_Q(q4k) TL_GEMM_Q(q5k) TL_GEMM_Q(q6k) diff --git a/include/metal_nn.h b/include/metal_nn.h index 30d51dd..323a49d 100644 --- a/include/metal_nn.h +++ b/include/metal_nn.h @@ -19,6 +19,9 @@ enum class nn_kernel { gemv_q4k, gemv_q6k, gemv_q80, gemv_q50, gemv_q5k, gemv_q40, gemv_q41, gemm_q4k, gemm_q4k_32, gemm_q6k, gemm_q6k_32, gemm_q80, gemm_q80_32, gemm_q50, gemm_q50_32, gemm_q5k, gemm_q5k_32, gemm_q40, gemm_q40_32, gemm_q41, gemm_q41_32, + gemm_q4k_f16, gemm_q4k_f16_32, gemm_q6k_f16, gemm_q6k_f16_32, gemm_q80_f16, + gemm_q80_f16_32, gemm_q50_f16, gemm_q50_f16_32, gemm_q5k_f16, gemm_q5k_f16_32, + gemm_q40_f16, gemm_q40_f16_32, gemm_q41_f16, gemm_q41_f16_32, rmsnorm_rope_64, rmsnorm_rope_128, rmsnorm_rope_256, gated_rmsnorm, gemm_bf16_steel, gemm_bf16_steel_32, gemm_bf16_f16acc, gemm_bf16_f16acc_32, embed_row_f32, embed_row_bf16, embed_row_q4k, embed_row_q6k, embed_row_q80, embed_row_q50, @@ -48,6 +51,20 @@ inline const char* nn_kernel_name_(nn_kernel t) { case nn_kernel::gemm_q40_32: return "gemm_q40_nt32_"; case nn_kernel::gemm_q41: return "gemm_q41_nt_"; case nn_kernel::gemm_q41_32: return "gemm_q41_nt32_"; + case nn_kernel::gemm_q4k_f16: return "gemm_q4k_f16_"; + case nn_kernel::gemm_q4k_f16_32: return "gemm_q4k_f16_32_"; + case nn_kernel::gemm_q6k_f16: return "gemm_q6k_f16_"; + case nn_kernel::gemm_q6k_f16_32: return "gemm_q6k_f16_32_"; + case nn_kernel::gemm_q80_f16: return "gemm_q80_f16_"; + case nn_kernel::gemm_q80_f16_32: return "gemm_q80_f16_32_"; + case nn_kernel::gemm_q50_f16: return "gemm_q50_f16_"; + case nn_kernel::gemm_q50_f16_32: return "gemm_q50_f16_32_"; + case nn_kernel::gemm_q5k_f16: return "gemm_q5k_f16_"; + case nn_kernel::gemm_q5k_f16_32: return "gemm_q5k_f16_32_"; + case nn_kernel::gemm_q40_f16: return "gemm_q40_f16_"; + case nn_kernel::gemm_q40_f16_32: return "gemm_q40_f16_32_"; + case nn_kernel::gemm_q41_f16: return "gemm_q41_f16_"; + case nn_kernel::gemm_q41_f16_32: return "gemm_q41_f16_32_"; case nn_kernel::rmsnorm_rope_64: return "rmsnorm_rope_64_"; case nn_kernel::rmsnorm_rope_128: return "rmsnorm_rope_128_"; case nn_kernel::rmsnorm_rope_256: return "rmsnorm_rope_256_"; @@ -113,6 +130,8 @@ struct own_nn { static bool gemm_quant(int type, bool a16, gpu::span A, gpu::span W, gpu::span C, int64_t m, int64_t n, int64_t k, int64_t ldc, bool mmq); + static bool gemm_quant_f16(int type, gpu::span A, gpu::span W, gpu::span C, + int64_t m, int64_t n, int64_t k, int64_t ldc); // Every gpu::rope_freq: a part of the row, a scaled position, per-pair factors. static bool rope(gpu::span x, gpu::span out, int64_t rows, int64_t T, int64_t D, int64_t pos, const gpu::rope_freq& f, gpu::span bias); @@ -328,22 +347,44 @@ inline constexpr unsigned long gemv_quant_qrows_ = 2, gemv_quant_sg_ = 2, gemv_quant_rows_ = gemv_quant_sg_ * gemv_quant_qrows_; // The GGUF block formats the kernels read, a row each (cuda_nn.h's quant_fmts_): -// the ggml type, its GEMV, GEMM (64- and 32-row bands) and row-lookup kernels, and -// whether its reader takes 32-bit loads into a block (W word_aligned_) or 16-bit -// ones (W 2-byte aligned). A block's geometry is ggml's (gguf::ggml_block). +// the ggml type, its GEMV, GEMMs (gemm[f16][band32]: over f32 tiles or half +// ones, in the 64- or the 32-row band) and row-lookup kernels, and whether its +// reader takes 32-bit loads into a block (W word_aligned_) or 16-bit ones (W +// 2-byte aligned). A block's geometry is ggml's (gguf::ggml_block). struct quant_fmt { int type; - nn_kernel gemv, gemm, gemm32, embed; + nn_kernel gemv, gemm[2][2], embed; bool word; }; inline constexpr quant_fmt quant_fmts_[] = { - {12, nn_kernel::gemv_q4k, nn_kernel::gemm_q4k, nn_kernel::gemm_q4k_32, nn_kernel::embed_row_q4k, true}, - {14, nn_kernel::gemv_q6k, nn_kernel::gemm_q6k, nn_kernel::gemm_q6k_32, nn_kernel::embed_row_q6k, false}, - {8, nn_kernel::gemv_q80, nn_kernel::gemm_q80, nn_kernel::gemm_q80_32, nn_kernel::embed_row_q80, false}, - {6, nn_kernel::gemv_q50, nn_kernel::gemm_q50, nn_kernel::gemm_q50_32, nn_kernel::embed_row_q50, false}, - {13, nn_kernel::gemv_q5k, nn_kernel::gemm_q5k, nn_kernel::gemm_q5k_32, nn_kernel::embed_row_q5k, true}, - {2, nn_kernel::gemv_q40, nn_kernel::gemm_q40, nn_kernel::gemm_q40_32, nn_kernel::embed_row_q40, false}, - {3, nn_kernel::gemv_q41, nn_kernel::gemm_q41, nn_kernel::gemm_q41_32, nn_kernel::embed_row_q41, false}, + {12, nn_kernel::gemv_q4k, + {{nn_kernel::gemm_q4k, nn_kernel::gemm_q4k_32}, + {nn_kernel::gemm_q4k_f16, nn_kernel::gemm_q4k_f16_32}}, + nn_kernel::embed_row_q4k, true}, + {14, nn_kernel::gemv_q6k, + {{nn_kernel::gemm_q6k, nn_kernel::gemm_q6k_32}, + {nn_kernel::gemm_q6k_f16, nn_kernel::gemm_q6k_f16_32}}, + nn_kernel::embed_row_q6k, false}, + {8, nn_kernel::gemv_q80, + {{nn_kernel::gemm_q80, nn_kernel::gemm_q80_32}, + {nn_kernel::gemm_q80_f16, nn_kernel::gemm_q80_f16_32}}, + nn_kernel::embed_row_q80, false}, + {6, nn_kernel::gemv_q50, + {{nn_kernel::gemm_q50, nn_kernel::gemm_q50_32}, + {nn_kernel::gemm_q50_f16, nn_kernel::gemm_q50_f16_32}}, + nn_kernel::embed_row_q50, false}, + {13, nn_kernel::gemv_q5k, + {{nn_kernel::gemm_q5k, nn_kernel::gemm_q5k_32}, + {nn_kernel::gemm_q5k_f16, nn_kernel::gemm_q5k_f16_32}}, + nn_kernel::embed_row_q5k, true}, + {2, nn_kernel::gemv_q40, + {{nn_kernel::gemm_q40, nn_kernel::gemm_q40_32}, + {nn_kernel::gemm_q40_f16, nn_kernel::gemm_q40_f16_32}}, + nn_kernel::embed_row_q40, false}, + {3, nn_kernel::gemv_q41, + {{nn_kernel::gemm_q41, nn_kernel::gemm_q41_32}, + {nn_kernel::gemm_q41_f16, nn_kernel::gemm_q41_f16_32}}, + nn_kernel::embed_row_q41, false}, }; // The row of `type` where rows of k weights are a whole number of its blocks, else null. inline const quant_fmt* quant_fmt_(int type, int64_t k) { @@ -371,6 +412,20 @@ inline void gemm_nt_launch_(context& c, const steel_grid& g, gpu::span A, gpu::s gemm_launch_(c, A, W, C, p, g.gx, g.gy, 1); } +// A GEMM over block-quantized rows on STEEL's body, over half tiles (f16) or +// f32 ones (the format's kernels for the band steel_grid_ picks); false where +// the kernels do not read W. +inline bool gemm_quant_run_(bool f16, int type, gpu::span A, gpu::span W, gpu::span C, + int64_t m, int64_t n, int64_t k, int64_t ldc) { + auto& c = context::get(); + const quant_fmt* f = quant_ok_(type, k, W); + if (!c.device || m <= 0 || n <= 0 || ldc < n || !f) return false; + const steel_grid g = steel_grid_(m, n); + bind_(c, f->gemm[f16][g.band32]); + gemm_nt_launch_(c, g, A, W, C, m, n, k, ldc); + return true; +} + struct attn_decode_params { uint32_t ctx, kv_stride, group, chunk; float scale; @@ -595,13 +650,16 @@ inline bool own_nn::gemm_quant(int type, bool a16, gpu::span A, gpu::span W, gpu::span C, int64_t m, int64_t n, int64_t k, int64_t ldc, bool mmq) { (void)mmq; - auto& c = context::get(); - const detail_::quant_fmt* f = detail_::quant_ok_(type, k, W); - if (!c.device || a16 || m <= 0 || n <= 0 || ldc < n || !f) return false; - const detail_::steel_grid g = detail_::steel_grid_(m, n); - detail_::bind_(c, g.band32 ? f->gemm32 : f->gemm); - detail_::gemm_nt_launch_(c, g, A, W, C, m, n, k, ldc); - return true; + return !a16 && detail_::gemm_quant_run_(false, type, A, W, C, m, n, k, ldc); +} + +// The same over f16 operands (gpu_ops_nn.h's contract): STEEL's body over half +// tiles, A and the dequantized weight rounded to half as they are staged, the +// sums f32. +inline bool own_nn::gemm_quant_f16(int type, gpu::span A, gpu::span W, + gpu::span C, int64_t m, int64_t n, + int64_t k, int64_t ldc) { + return detail_::gemm_quant_run_(true, type, A, W, C, m, n, k, ldc); } // One decode step: q [n_q_heads,D] against a [n_kv_heads,kv_max,D] cache read diff --git a/test/test_nn.cpp b/test/test_nn.cpp index bc81a60..b3e3c0c 100644 --- a/test/test_nn.cpp +++ b/test/test_nn.cpp @@ -1708,17 +1708,8 @@ TEST_CASE("generic compositions agree with the fused kernels") { array a = random_array({M, K}, 1060 + type); a.eval(); array W = dev(q.W), ad = dev(a); - array C = dev(array::from(std::vector((size_t)(M * ldc), 7.0f), {M, ldc})); - REQUIRE(gpu::gemm_quant(type, false, ad.device_span(), W.device_span(), - C.device_span().at(off * 4), M, N, K, ldc)); - tl::gpu::flush(); // The product and its terms' magnitude, and the worst error of an - // output's N columns from col0 (rows ldc apart) relative to it. f32 - // sums over f32 operands (CUDA's tensor cores hold each as a bf16 - // pair, to ~2^-16; Metal's keep f32): ~1e-6 of the terms' magnitude, - // where operands rounded to bf16 were 3e-4..7e-4 off, enough to move - // the batched prefill's logits off the token-by-token ones'. A misread - // weight is off by whole terms. + // output's N columns from col0 (rows ldc apart) relative to it. std::vector ref((size_t)(M * N)), mag((size_t)(M * N)); for (int64_t i = 0; i < M; i++) for (int64_t j = 0; j < N; j++) @@ -1737,28 +1728,46 @@ TEST_CASE("generic compositions agree with the fused kernels") { } return worst; }; - constexpr double bound = 2e-5; - const std::vector got = host_values(C); - bool kept = true; - for (int64_t i = 0; i < M; i++) - for (int64_t j = 0; j < ldc; j++) - if (j < off || j >= off + N) kept = kept && got[(size_t)(i * ldc + j)] == 7.0f; - CHECK(worst_rel(got, off) < bound); - CHECK(kept); - // C one column off its float2 stores, and the weight 4 bytes off its - // base (a format read by halves still fits; Q4_K's and Q5_K's vectors - // do not): each refused or computed as above, never misplaced. array Wl = dev(with_lead(q.W, 1)); - for (const bool shift_w : {false, true}) { - array C1 = dev(array::zeros({M * ldc + 1})); - check_misaligned( - shift_w ? "quantized GEMM, W off its base" : "quantized GEMM, C off 8 bytes", - [&] { - return gpu::gemm_quant(type, false, ad.device_span(), - shift_w ? Wl.device_span().at(4) : W.device_span(), - C1.device_span().at(shift_w ? 0 : 4), M, N, K, ldc); - }, - [&] { return worst_rel(after_lead(C1, shift_w ? 0 : 1, M * ldc), 0) < bound; }); + for (const bool f16 : {false, true}) { + if (f16 && !gpu::has_gemm_quant_f16) continue; // it would run the exact form again + CAPTURE(f16); + auto run = [&](gpu::span w, gpu::span c) { + return f16 ? gpu::gemm_quant_f16(type, ad.device_span(), w, c, M, N, K, ldc) + : gpu::gemm_quant(type, false, ad.device_span(), w, c, M, N, K, ldc); + }; + array C = dev(array::from(std::vector((size_t)(M * ldc), 7.0f), {M, ldc})); + REQUIRE(run(W.device_span(), C.device_span().at(off * 4))); + tl::gpu::flush(); + // The exact form: f32 sums over f32 operands (CUDA's tensor cores + // hold each as a bf16 pair, to ~2^-16; Metal's keep f32), ~1e-6 + // of the terms' magnitude, where operands rounded to bf16 were + // 3e-4..7e-4 off, enough to move the batched prefill's logits off + // the token-by-token ones'. The f16 operands round each to + // 2^-11, up to 9.6e-5 of the magnitude here (Metal's). A misread + // weight is off by whole terms, ~1/K of it. + const double bound = f16 ? 3e-4 : 2e-5; + const std::vector got = host_values(C); + bool kept = true; + for (int64_t i = 0; i < M; i++) + for (int64_t j = 0; j < ldc; j++) + if (j < off || j >= off + N) kept = kept && got[(size_t)(i * ldc + j)] == 7.0f; + CHECK(worst_rel(got, off) < bound); + CHECK(kept); + // C one column off its float2 stores, and the weight 4 bytes off + // its base (a format read by halves still fits; Q4_K's and Q5_K's + // vectors do not): each refused or computed as above, never + // misplaced. + for (const bool shift_w : {false, true}) { + array C1 = dev(array::zeros({M * ldc + 1})); + check_misaligned( + shift_w ? "quantized GEMM, W off its base" : "quantized GEMM, C off 8 bytes", + [&] { + return run(shift_w ? Wl.device_span().at(4) : W.device_span(), + C1.device_span().at(shift_w ? 0 : 4)); + }, + [&] { return worst_rel(after_lead(C1, shift_w ? 0 : 1, M * ldc), 0) < bound; }); + } } } } From f3529d0c40454a9b1e3d12d16aed381c3a715164 Mon Sep 17 00:00:00 2001 From: yhirose Date: Sat, 7 Nov 2026 11:11:27 -0500 Subject: [PATCH 2/3] metal: the bf16 prefill GEMM's f16 form sums in f32, as the quantized one Stacked on #57. Metal's gemm_bf16_f16acc_ summed in half. On check_qwen's 96-token prompt (the long-prompt path, forced on for these array-path files, which normally check a short prompt only), its top-5 logits were 3.2e-2 (Qwen3 0.6B F16), 7.3e-3 (Qwen2.5 0.5B) and 2.6e-3 (Llama 3.2 1B F16) off the f32 forward's; the check's bound is 2e-2. With f32 sums over the same half tiles (#57's form, llama.cpp's kernel_mul_mm) they are 2.8e-4, 3.0e-4 and 8.2e-5. - The kernels are gemm_bf16_f16_ and gemm_bf16_f16_32_ (half tiles, f32 sums, K step 16), named as the quantized gemm__f16_. - No Metal kernel sums in half now, so STEEL's sum-type parameter (#57's AT) is gone: SteelMMA always sums in float2, and TL_STEEL_KERNEL_ST with it. Half sums cannot come back by a kernel's instantiation. - gpu_ops_nn.h's gemm_bf16_nt_f16acc contract says what each backend does: CUDA sums in f16, Metal rounds the operands to f16 and sums in f32. The op keeps its name, shared with CUDA. Comments in qwen.h, check_qwen and test_llm that said Metal sums in f16 are updated. pp512 (bench_qwen_llama, M1 Pro, tok/s, alternating), half sums -> f32 sums: Qwen3 0.6B F16 3050 -> 2955, Qwen2.5 0.5B 4170 -> 3990, Qwen3.5 0.8B F16 1692 -> 1587, Llama 3.2 1B F16 1716 -> 1615 (3 to 6%). A K step of 32 for these kernels was within noise (-1% to +4% by model) and is not taken. Tests: check_qwen is ALL OK on Qwen3 0.6B F16 and Q4_K_M, Qwen2.5 0.5B, Qwen3.5 0.8B F16, Llama 3.2 1B F16 and Gemma 4 E2B; Qwen3 0.6B F16's f16 GEMMs on its own prompt went from 1.0e-2 to 6.4e-4. ctest passes (15.8 to 17.7 s on a loaded machine; the base measured 18.4 s alongside). No test is added: summing in half is no longer expressible in STEEL. --- bench/models/check_qwen.cpp | 2 +- bench/models/qwen.h | 14 +++++++------- include/gpu_ops_nn.h | 18 +++++++++--------- include/metal_kernels.metal | 32 ++++++++++++++++---------------- include/metal_kernels_nn.metal | 21 ++++++++++++--------- include/metal_nn.h | 12 ++++++------ test/test_llm.cpp | 16 ++++++++-------- 7 files changed, 59 insertions(+), 56 deletions(-) diff --git a/bench/models/check_qwen.cpp b/bench/models/check_qwen.cpp index 95fd9d2..a9c22fa 100644 --- a/bench/models/check_qwen.cpp +++ b/bench/models/check_qwen.cpp @@ -174,7 +174,7 @@ static void fixed_sums(bool on) { } // The batched prefill's f16 GEMMs (the default where the backend has them: -// sums f16, or a block-quantized weight's operands f16 over f32 sums), against +// CUDA's sums f16, Metal's operands f16 over f32 sums), against // `ref`, an f32 forward's logits for the same prompt: the top-5 logits to 2e-2 // and the same greedy token (a sensitive model's as Oracle::agree holds it). // Then the safety net: with the first layer's FFN norm scaled by 1e5 the f16 diff --git a/bench/models/qwen.h b/bench/models/qwen.h index 540d0a7..f3a3869 100644 --- a/bench/models/qwen.h +++ b/bench/models/qwen.h @@ -959,8 +959,8 @@ struct Model { bool q4_mlp = false; // imperative MLP gemvs (wgu, wd) use q4 bool q4_lmhead = false; // imperative lm_head gemv uses q4 // The batched prefill's GEMMs take f16 where the backend can - // (prefill_gemm_f16: f16 sums, twice the tensor-core rate here, or f16 - // operands over f32 sums), at a small cost in precision. A prompt whose + // (prefill_gemm_f16: CUDA's f16 sums, twice the tensor-core rate, or Metal's + // f16 operands over f32 sums), at a small cost in precision. A prompt whose // logits come out non-finite (an f16 overflow, in these GEMMs or in the // attention's f16 operands) is redone exactly (prefill_batched), and // counted in f16_retries. @@ -1169,10 +1169,10 @@ inline void set_cache_pos(Model& M, int64_t p) { // The batched prefill's f16 forms, in one place (prefill_chunk_ takes them, the // checks ask): its activations are f16 (a16) where f16_acc asks for f16 and the // backend has the producers that write them; its GEMMs take f16's precision and -// range under f16_acc (prefill_gemm_f16): a bf16 weight's sums f16 on either -// activation (gemm_bf16_nt_f16acc reads f32 too), a block-quantized one's sums -// f16 on f16 activations, or its operands f16 where the backend has that form -// over f32 ones (gemm_quant_f16). The exact form takes none. +// range under f16_acc (prefill_gemm_f16): a bf16 weight's on either activation +// (gemm_bf16_nt_f16acc reads f32 too), a block-quantized one's on f16 +// activations, or on f32 ones where the backend has that form +// (gemm_quant_f16). The exact form takes none. inline bool prefill_a16(const Model& M, bool exact) { return M.f16_acc && !exact && gpu::f16_activations; } @@ -1217,7 +1217,7 @@ inline int64_t prefill_chunk_(Model& M, int64_t T, bool exact = false, bool last // same place, and kv_cache::prefill appends there, so rope reads it from the // same source rather than taking it as a parameter that could disagree. int64_t pos0 = seq_cache(M).pos; - // The f16-sum GEMMs read their activation as f16 where prefill_a16 says; `a16s` + // The f16 GEMMs read their activation as f16 where prefill_a16 says; `a16s` // is that copy of `a`. One row (a one-token chunk, or the last row past the // KV-sharing line) is a decode step's product: the decode's GEMVs, which read the // weights once at their bandwidth where a tile GEMM wastes all its rows but one diff --git a/include/gpu_ops_nn.h b/include/gpu_ops_nn.h index 14950aa..ff09834 100644 --- a/include/gpu_ops_nn.h +++ b/include/gpu_ops_nn.h @@ -693,12 +693,12 @@ inline bool gemm_bf16_nt(span A, span B, span C, int64_t M, int64_t N, } } -// The same product summed in f16, for an inference prefill that takes the -// trade: f16 sums run at twice the f32 rate on tensor cores that have them -// (CUDA's gemm_bf16_nt_f16acc), and somewhat faster where the two rates -// match (Metal's), at a small cost in precision and with f16's range — an -// activation or partial sum past 65504 turns to inf, which the caller must -// check for. A backend without the form sums in f32. +// The same product in f16, for an inference prefill that takes the trade: +// summed in f16 where tensor cores run that at twice the f32 rate (CUDA's), +// or over f16 operands with f32 sums (Metal's, as gemm_quant_f16), at a small +// cost in precision and with f16's range: an activation (on CUDA a partial +// sum too) past 65504 turns to inf, which the caller must check for. A +// backend without the form runs the f32 GEMM. TL_GPU_DETECT_OWN(gemm_bf16_nt_f16acc) template inline bool gemm_bf16_nt_f16acc(span A, span B, span C, int64_t M, int64_t N, @@ -725,9 +725,9 @@ inline bool gemm_quant(int type, bool a16, span A, span W, span C, int64_t m, in // The same product of an f32 A over f16 operands: A and the dequantized weight // rounded to f16 as they are staged, the sums f32 (Metal's, where the prefill -// has no f16 activations; llama.cpp's Metal GEMM). f16's range, as -// gemm_bf16_nt_f16acc's: an activation past 65504 turns to inf, which the -// caller must check for. A backend without the form runs gemm_quant's exact one. +// has no f16 activations; llama.cpp's Metal GEMM). f16's range: an activation +// past 65504 turns to inf, which the caller must check for. A backend without +// the form runs gemm_quant's exact one. TL_GPU_DETECT_OWN(gemm_quant_f16) template inline bool gemm_quant_f16(int type, span A, span W, span C, int64_t m, int64_t n, diff --git a/include/metal_kernels.metal b/include/metal_kernels.metal index 1deff35..9f67756 100644 --- a/include/metal_kernels.metal +++ b/include/metal_kernels.metal @@ -392,7 +392,7 @@ static inline uint frag_col_(uint lane) { template constexpr short steel_pad_() { return 16 / sizeof(ST); } // The tiles hold ST: float, or half for a GEMM over f16 operands (the MMA -// multiplies in the tiles' type, and sums in SteelMMA's AT). +// multiplies in the tiles' type, and sums in f32 either way). template struct SteelLoader { @@ -662,12 +662,14 @@ METAL_FUNC SteelLoaderF steel_b_( return {f, col0, Bs, sid, lane}; } -// ST the tiles' type, AT the sums' (ST, or float over half tiles). +// ST the tiles' type; the sums are f32 over either (half sums put a +// prefill's logits 25 to 120 times as far off the f32 forward's, on F16 and +// Q4_K_M files alike: check_qwen's f16 GEMMs on a 96-token prompt). template + short lda_tgp, short ldb_tgp, typename ST = float> struct SteelMMA { typedef vec frag_type; - typedef vec acc_type; + typedef float2 acc_type; STEEL_CONST short kFrag = 8; STEEL_CONST short TM = BM / (kFrag * WM); STEEL_CONST short TN = BN / (kFrag * WN); @@ -717,7 +719,7 @@ struct SteelMMA { thread acc_type& D, thread frag_type& A, thread frag_type& B, thread acc_type& C) { simdgroup_matrix A_mat, B_mat; - simdgroup_matrix C_mat; + simdgroup_matrix C_mat; reinterpret_cast(A_mat.thread_elements()) = A; reinterpret_cast(B_mat.thread_elements()) = B; reinterpret_cast(C_mat.thread_elements()) = C; @@ -770,7 +772,7 @@ struct SteelMMA { STEEL_PRAGMA_UNROLL for (short j = 0; j < TN; j++) { int off = (i * kFrag) * WM * ldd + (j * kFrag) * WN; - float2 val = float2(Ctile[i * TN + j]); + float2 val = Ctile[i * TN + j]; val[0] = fma(val[0], scale, offset); val[1] = fma(val[1], scale, offset); *reinterpret_cast(&C[off]) = val; @@ -789,7 +791,7 @@ struct SteelMMA { for (short j = 0; j < TN; j++) { short r = (i * kFrag) * WM; short c = (j * kFrag) * WN; - float2 val = float2(Ctile[i * TN + j]); + float2 val = Ctile[i * TN + j]; val[0] = fma(val[0], scale, offset); val[1] = fma(val[1], scale, offset); if (r < dims.y) { @@ -811,8 +813,8 @@ struct SteelMMA { // view (backward-pass matmuls, attention's Q·Kᵀ); the MMA stays NN. B is // whatever steel_b_ takes: a pointer, or a functor over W's rows. C's rows // are p.ldc apart. -template +template void steel_body_(device const float* A, BSrc B, device float* C, constant gemm_params& p, threadgroup ST* As, threadgroup ST* Bs, @@ -839,7 +841,7 @@ void steel_body_(device const float* A, BSrc B, loader_a(A, int(p.lda), As, sid, ushort(lane)); auto loader_b = steel_b_( B, p, col0, Bs, ushort(sid), ushort(lane)); - SteelMMA mma_op(sid, lane); + SteelMMA mma_op(sid, lane); int k_iters = int(p.K / BK); short lbk = short(p.K) - short(k_iters * BK); @@ -926,8 +928,8 @@ void steel_body_(device const float* A, BSrc B, // BT: B's element type (float here; a bf16 weight's ushort in the nn layer); // BSRC what steel_body_ reads B through: B itself, or a reader f(n, k) over // it (the nn layer's GGUF formats), built after the slice moved B; ST the -// tiles' type, AT the sums' (TL_STEEL_KERNEL_ST sums in ST); BK the K step. -#define TL_STEEL_KERNEL_BK(name, BM, TA, TB, BT, BSRC, ST, AT, BK) \ +// tiles' type (the sums f32 over either); BK the K step. +#define TL_STEEL_KERNEL_BK(name, BM, TA, TB, BT, BSRC, ST, BK) \ kernel void name(device const float* A [[buffer(0)]], \ device const BT* B [[buffer(1)]], \ device float* C [[buffer(2)]], \ @@ -938,12 +940,10 @@ void steel_body_(device const float* A, BSrc B, threadgroup ST As[BM * (BK + steel_pad_())]; \ threadgroup ST Bs[BK * (64 + steel_pad_())]; \ gemm_slice_(A, B, C, p, tgid.z); \ - steel_body_(A, BSRC, C, p, As, Bs, tgid, sid, lane); \ + steel_body_(A, BSRC, C, p, As, Bs, tgid, sid, lane); \ } -#define TL_STEEL_KERNEL_ST(name, BM, TA, TB, BT, BSRC, ST) \ - TL_STEEL_KERNEL_BK(name, BM, TA, TB, BT, BSRC, ST, ST, 16) #define TL_STEEL_KERNEL_SRC(name, BM, TA, TB, BT, BSRC) \ - TL_STEEL_KERNEL_ST(name, BM, TA, TB, BT, BSRC, float) + TL_STEEL_KERNEL_BK(name, BM, TA, TB, BT, BSRC, float, 16) #define TL_STEEL_KERNEL(name, BM, TA, TB, BT) \ TL_STEEL_KERNEL_SRC(name, BM, TA, TB, BT, B) diff --git a/include/metal_kernels_nn.metal b/include/metal_kernels_nn.metal index f98f0b1..6f292aa 100644 --- a/include/metal_kernels_nn.metal +++ b/include/metal_kernels_nn.metal @@ -1342,10 +1342,13 @@ struct read_q41_ { // A bf16 W whose K is whole 8-element vectors: the vectorized loader. TL_STEEL_KERNEL(gemm_bf16_steel_, 64, false, true, ushort) TL_STEEL_KERNEL(gemm_bf16_steel32_, 32, false, true, ushort) -// The same summed in f16 (cuda's gemm_bf16_nt_f16acc): A and W rounded to -// half as they are staged, and the MMA's sums half. -TL_STEEL_KERNEL_ST(gemm_bf16_f16acc_, 64, false, true, ushort, B, half) -TL_STEEL_KERNEL_ST(gemm_bf16_f16acc32_, 32, false, true, ushort, B, half) +// The same over f16 operands (gpu_ops_nn.h's gemm_bf16_nt_f16acc): A and W +// rounded to half as they are staged, the sums f32 as the quantized formats' +// (below). Half sums were 3 to 6% faster at pp512 on F16 files (Qwen3 0.6B, +// Qwen2.5 0.5B, Qwen3.5 0.8B, Llama 3.2 1B), at the precision SteelMMA's note +// gives. +TL_STEEL_KERNEL_BK(gemm_bf16_f16_, 64, false, true, ushort, B, half, 16) +TL_STEEL_KERNEL_BK(gemm_bf16_f16_32_, 32, false, true, ushort, B, half, 16) // The rest through a reader (steel_b_'s functor loader); the 32-row band for // a short chunk (steel_grid_). TL_STEEL_KERNEL_SRC(gemm_bf16_nt_, 64, false, true, ushort, TL_READ_BF16) @@ -1357,16 +1360,16 @@ TL_STEEL_KERNEL_SRC(gemm_bf16_nt32_, 32, false, true, ushort, TL_READ_BF16) // to 8%, Q6_K 15%. Each also over half tiles (gpu_ops_nn.h's gemm_quant_f16): // A and the dequantized weight rounded to half as they are staged, the sums // f32 (llama.cpp's kernel_mul_mm). Summed in half too, pp512 was 5 to 9% -// faster still, and the logits 40 to 120 times as far off the f32 forward's. +// faster still, at the precision SteelMMA's note gives. #define TL_GEMM_Q(F) \ TL_STEEL_KERNEL_BK(gemm_##F##_nt_, 64, false, true, uchar, \ - TL_READ_Q(read_##F##_), float, float, 32) \ + TL_READ_Q(read_##F##_), float, 32) \ TL_STEEL_KERNEL_BK(gemm_##F##_nt32_, 32, false, true, uchar, \ - TL_READ_Q(read_##F##_), float, float, 32) \ + TL_READ_Q(read_##F##_), float, 32) \ TL_STEEL_KERNEL_BK(gemm_##F##_f16_, 64, false, true, uchar, \ - TL_READ_Q(read_##F##_), half, float, 32) \ + TL_READ_Q(read_##F##_), half, 32) \ TL_STEEL_KERNEL_BK(gemm_##F##_f16_32_, 32, false, true, uchar, \ - TL_READ_Q(read_##F##_), half, float, 32) + TL_READ_Q(read_##F##_), half, 32) TL_GEMM_Q(q4k) TL_GEMM_Q(q5k) TL_GEMM_Q(q6k) diff --git a/include/metal_nn.h b/include/metal_nn.h index 323a49d..5a805ca 100644 --- a/include/metal_nn.h +++ b/include/metal_nn.h @@ -23,7 +23,7 @@ enum class nn_kernel { gemm_q80_f16_32, gemm_q50_f16, gemm_q50_f16_32, gemm_q5k_f16, gemm_q5k_f16_32, gemm_q40_f16, gemm_q40_f16_32, gemm_q41_f16, gemm_q41_f16_32, rmsnorm_rope_64, rmsnorm_rope_128, rmsnorm_rope_256, gated_rmsnorm, - gemm_bf16_steel, gemm_bf16_steel_32, gemm_bf16_f16acc, gemm_bf16_f16acc_32, + gemm_bf16_steel, gemm_bf16_steel_32, gemm_bf16_f16, gemm_bf16_f16_32, embed_row_f32, embed_row_bf16, embed_row_q4k, embed_row_q6k, embed_row_q80, embed_row_q50, embed_row_q5k, embed_row_q40, embed_row_q41, }; @@ -71,8 +71,8 @@ inline const char* nn_kernel_name_(nn_kernel t) { case nn_kernel::gated_rmsnorm: return "gated_rmsnorm_"; case nn_kernel::gemm_bf16_steel: return "gemm_bf16_steel_"; case nn_kernel::gemm_bf16_steel_32: return "gemm_bf16_steel32_"; - case nn_kernel::gemm_bf16_f16acc: return "gemm_bf16_f16acc_"; - case nn_kernel::gemm_bf16_f16acc_32: return "gemm_bf16_f16acc32_"; + case nn_kernel::gemm_bf16_f16: return "gemm_bf16_f16_"; + case nn_kernel::gemm_bf16_f16_32: return "gemm_bf16_f16_32_"; case nn_kernel::embed_row_f32: return "embed_row_f32_"; case nn_kernel::embed_row_bf16: return "embed_row_bf16_"; case nn_kernel::embed_row_q4k: return "embed_row_q4k_"; @@ -583,8 +583,8 @@ inline bool own_nn::gemm_bf16_nt(gpu::span A, gpu::span B, gpu::span C, int64_t return true; } -// The same summed in f16, cuda.h's contract: STEEL's body over half tiles, -// for a W the vectorized loader reads (bf16_rows_vec_); otherwise +// The same in f16 (gpu_ops_nn.h's contract): STEEL's body over half tiles, its +// sums f32, for a W the vectorized loader reads (bf16_rows_vec_); otherwise // false, and the caller's f32 GEMM. inline bool own_nn::gemm_bf16_nt_f16acc(gpu::span A, gpu::span B, gpu::span C, int64_t M, int64_t N, int64_t K) { @@ -592,7 +592,7 @@ inline bool own_nn::gemm_bf16_nt_f16acc(gpu::span A, gpu::span B, gpu::span C, if (!c.device || M <= 0 || N <= 0 || K <= 0 || !detail_::bf16_rows_vec_(K, B)) return false; const detail_::steel_grid g = detail_::steel_grid_(M, N); - detail_::bind_(c, g.band32 ? nn_kernel::gemm_bf16_f16acc_32 : nn_kernel::gemm_bf16_f16acc); + detail_::bind_(c, g.band32 ? nn_kernel::gemm_bf16_f16_32 : nn_kernel::gemm_bf16_f16); detail_::gemm_nt_launch_(c, g, A, B, C, M, N, K, N); return true; } diff --git a/test/test_llm.cpp b/test/test_llm.cpp index eb51d3c..fc40210 100644 --- a/test/test_llm.cpp +++ b/test/test_llm.cpp @@ -825,30 +825,30 @@ TEST_CASE("the KV cache and the decode step's kernels match their array forms") k2)); tl::gpu::flush(); CHECK(same(C2, A2.dot(W2t), 1e-4f)); - // The f16-sum form (below) past one band too (K = 76 isn't whole + // The f16 form (below) past one band too (K = 76 isn't whole // vectors: Metal declines it, and this is the f32 fallback). Its - // 136-term sums, up to 16 in size, round by up to about 0.06 in f16; - // a misplaced tile would be off by the products themselves. + // 136-term sums, up to 16 in size, round by up to about 0.06 in f16 + // (CUDA's); a misplaced tile would be off by the products themselves. array C2h = array::empty({M2, N2}); REQUIRE(gpu::gemm_bf16_nt_f16acc(A2.device_span(), W2b.device_span(), C2h.device_span(), M2, N2, k2)); tl::gpu::flush(); CHECK(same(C2h, A2.dot(W2t), 0.25f)); } - // The f16-sum form: the activations rounded to f16 (2^-11) and the sums - // f16, the second by far the larger. A backend without the form sums in - // f32 and passes trivially. + // The f16 form: the activations rounded to f16 (2^-11), and on CUDA the + // sums f16 too, by far the larger error (Metal sums in f32). A backend + // without the form sums in f32 and passes trivially. array C16 = array::empty({M, N}); REQUIRE(gpu::gemm_bf16_nt_f16acc(A.device_span(), Wb.device_span(), C16.device_span(), M, N, K)); tl::gpu::flush(); CHECK(same(C16, A.dot(Wt), 1e-2f)); - // W off as above: the backend's f16 sums, or (where it declines) the + // W off as above: the backend's f16 form, or (where it declines) the // f32 GEMM the op falls back to, so never refused; within the f16 // rounding of the f32 product either way. for (const auto& c : {cases[2], cases[3]}) { array C16s = array::empty({M, N}); - const std::string what = std::string("f16-sum ") + c.what; + const std::string what = std::string("f16 ") + c.what; check_misaligned( what.c_str(), [&] { From 4a77bce50420602e9c9261210831d8152ec12cc5 Mon Sep 17 00:00:00 2001 From: yhirose Date: Sat, 7 Nov 2026 10:58:47 -0500 Subject: [PATCH 3/3] gpu: the decode attention's kv-head slices counted in gpu::policy CUDA's attn_dec_rows and Metal's attn_decode_rows_ each spelled out the same count: every kv head's q heads, a backend's heads a group at a time. It is now gpu::policy::kv_head_slices(n_q_heads, n_kv_heads, per), beside per_head, and both call it with their own heads a group (attn_dec_heads, attn_dec_heads_), which stay each backend's: they are its kernel's ABI, and the kernels cut their slices by the same count. "Slices" is the kernels' word for the unit; "group" already means the q heads a kv head serves. Nothing changes in what either backend launches. Tests: a mutant that rounds the count down fails 3 test cases (25 checks) on Metal. ctest passes. CUDA builds in CI; its numbers are the same by construction. --- include/cuda_nn.h | 4 ++-- include/gpu_abi.h | 9 +++++++++ include/metal_nn.h | 4 ++-- 3 files changed, 13 insertions(+), 4 deletions(-) diff --git a/include/cuda_nn.h b/include/cuda_nn.h index 2c328e7..80d276c 100644 --- a/include/cuda_nn.h +++ b/include/cuda_nn.h @@ -718,8 +718,8 @@ inline bool own_nn::cvt_h16(gpu::span src, gpu::span dst16, int64_t n) { inline constexpr int64_t attn_dec_heads(int64_t D) { return D == 256 ? 1 : 2; } inline constexpr unsigned attn_dec_threads(int64_t D) { return 32 * (D == 512 ? 4 : 8); } inline unsigned attn_dec_rows(int64_t n_q_heads, int64_t n_kv_heads, int64_t D) { - const int64_t group = n_q_heads / n_kv_heads; - return static_cast(n_kv_heads * ((group + attn_dec_heads(D) - 1) / attn_dec_heads(D))); + return static_cast( + gpu::policy::kv_head_slices(n_q_heads, n_kv_heads, attn_dec_heads(D))); } // Split-KV split-count heuristic: how many ctx-splits make grid = rows×S fill diff --git a/include/gpu_abi.h b/include/gpu_abi.h index 3be142d..4d401a7 100644 --- a/include/gpu_abi.h +++ b/include/gpu_abi.h @@ -366,6 +366,15 @@ inline constexpr int64_t max_group_threads = 1024; // a decoder hands the next step on the device (gpu_ops_llm.h). inline constexpr int64_t max_f32_index = int64_t(1) << 24; +// A GQA decode attention's slices, a group each: a kv head and `per` of the q +// heads that share it (each backend's kernel says how many, and cuts its slices +// by the same count), the last of a kv head's slices holding fewer where `per` +// does not divide them. A split launches this many groups a part +// (split_parts' `groups`). +inline int64_t kv_head_slices(int64_t n_q_heads, int64_t n_kv_heads, int64_t per) { + return n_kv_heads * ((n_q_heads / n_kv_heads + per - 1) / per); +} + // One group per (head, row), a thread per head-dim element: the attention // and KV-cache kernels' shape. inline grid per_head(int64_t heads, int64_t rows, int64_t D) { diff --git a/include/metal_nn.h b/include/metal_nn.h index 5a805ca..5acb9ec 100644 --- a/include/metal_nn.h +++ b/include/metal_nn.h @@ -452,8 +452,8 @@ static_assert(attn_decode_tg_bytes_(64) <= 32768 && attn_decode_tg_bytes_(128) < "the decode merge must fit a threadgroup's 32 KB"); // grid.x: a kv head's q heads, attn_dec_heads_ at a time, over every kv head. inline unsigned long attn_decode_rows_(int64_t n_q_heads, int64_t n_kv_heads, int64_t D) { - const int64_t group = n_q_heads / n_kv_heads, g = attn_dec_heads_(D); - return static_cast(n_kv_heads * ((group + g - 1) / g)); + return static_cast( + gpu::policy::kv_head_slices(n_q_heads, n_kv_heads, attn_dec_heads_(D))); } // Keys per split, or 0 for the single-pass kernel: one threadgroup a row