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
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
33 changes: 18 additions & 15 deletions include/metal_kernels.metal
Original file line number Diff line number Diff line change
Expand Up @@ -391,8 +391,8 @@ static inline uint frag_col_(uint lane) {
// 16-byte boundaries and stagger across the threadgroup banks.
template <typename ST> 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 f32 either way).
template <short BROWS, short BCOLS, short dst_ld, short reduction_dim, short tgp_size,
typename ST = float>
struct SteelLoader {
Expand Down Expand Up @@ -662,10 +662,14 @@ METAL_FUNC SteelLoaderF<BN, BK, ld, tgp, F, ST> steel_b_(
return {f, col0, Bs, sid, lane};
}

// 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 BM, short BN, short BK, short WM, short WN,
short lda_tgp, short ldb_tgp, typename ST = float>
struct SteelMMA {
typedef vec<ST, 2> frag_type;
typedef float2 acc_type;
STEEL_CONST short kFrag = 8;
STEEL_CONST short TM = BM / (kFrag * WM);
STEEL_CONST short TN = BN / (kFrag * WN);
Expand All @@ -680,7 +684,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;
Expand All @@ -698,7 +702,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(
Expand All @@ -712,14 +716,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<ST, 8, 8> A_mat, B_mat, C_mat;
thread acc_type& D, thread frag_type& A,
thread frag_type& B, thread acc_type& C) {
simdgroup_matrix<ST, 8, 8> A_mat, B_mat;
simdgroup_matrix<float, 8, 8> C_mat;
reinterpret_cast<thread frag_type&>(A_mat.thread_elements()) = A;
reinterpret_cast<thread frag_type&>(B_mat.thread_elements()) = B;
reinterpret_cast<thread frag_type&>(C_mat.thread_elements()) = C;
reinterpret_cast<thread acc_type&>(C_mat.thread_elements()) = C;
simdgroup_multiply_accumulate(C_mat, A_mat, B_mat, C_mat);
D = reinterpret_cast<thread frag_type&>(C_mat.thread_elements());
D = reinterpret_cast<thread acc_type&>(C_mat.thread_elements());
}

// Per kk step: load one K-slice of fragments, immediately MMA, serpentine
Expand Down Expand Up @@ -767,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<device float2*>(&C[off]) = val;
Expand All @@ -786,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) {
Expand Down Expand Up @@ -923,7 +928,7 @@ 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.
// 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)]], \
Expand All @@ -937,10 +942,8 @@ void steel_body_(device const float* A, BSrc B,
gemm_slice_(A, B, C, p, tgid.z); \
steel_body_<BM, TA, TB, BK>(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)
#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)

Expand Down
Loading
Loading