Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
41 changes: 21 additions & 20 deletions bench/models/check_qwen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -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:
// 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
// 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<int>& ids,
const std::vector<float>& ref, const Oracle& O) {
static bool check_f16_gemms(qm::Model& B, const std::vector<int>& ids,
const std::vector<float>& 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");
Expand Down Expand Up @@ -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,
Expand Down Expand Up @@ -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
Expand All @@ -545,15 +546,15 @@ 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);
qm::captured_decoder d;
d.begin(B, spread);
const std::vector<float> 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);
Expand Down Expand Up @@ -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);
}
}
Expand Down
43 changes: 25 additions & 18 deletions bench/models/qwen.h
Original file line number Diff line number Diff line change
Expand Up @@ -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: 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.
bool f16_acc = false;
int64_t f16_retries = 0;
Expand Down Expand Up @@ -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 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;
}
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.
Expand All @@ -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
Expand All @@ -1214,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
Expand All @@ -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).
Expand All @@ -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;
}
Expand All @@ -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);
}
};
Expand Down Expand Up @@ -1469,8 +1476,8 @@ inline int64_t prefill_batched(Model& M, const std::vector<int>& 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
Expand Down
5 changes: 4 additions & 1 deletion docs/backends.md
Original file line number Diff line number Diff line change
Expand Up @@ -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`).
Expand Down
4 changes: 2 additions & 2 deletions include/cuda_nn.h
Original file line number Diff line number Diff line change
Expand Up @@ -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<unsigned>(n_kv_heads * ((group + attn_dec_heads(D) - 1) / attn_dec_heads(D)));
return static_cast<unsigned>(
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
Expand Down
9 changes: 9 additions & 0 deletions include/gpu_abi.h
Original file line number Diff line number Diff line change
Expand Up @@ -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) {
Expand Down
27 changes: 21 additions & 6 deletions include/gpu_ops_nn.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <class Own = own>
inline bool gemm_bf16_nt_f16acc(span A, span B, span C, int64_t M, int64_t N,
Expand All @@ -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: 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 <class Own = own>
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<Own>::value) {
if (detail::ran(Own::gemm_quant_f16(type, A, W, C, m, n, k, ldc))) return true;
}
return gemm_quant<Own>(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)
Expand Down
Loading
Loading