From 2b4465edcad54de1ff27c1ae517319129b644a6e Mon Sep 17 00:00:00 2001 From: yhirose Date: Sat, 7 Nov 2026 10:47:41 -0500 Subject: [PATCH] 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; }); + } } } }