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:
// 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<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
41 changes: 24 additions & 17 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: 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;
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 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.
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 @@ -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
15 changes: 15 additions & 0 deletions include/gpu_ops_nn.h
Original file line number Diff line number Diff line change
Expand Up @@ -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 <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
37 changes: 20 additions & 17 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 SteelMMA's AT).
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,12 @@ METAL_FUNC SteelLoaderF<BN, BK, ld, tgp, F, ST> steel_b_(
return {f, col0, Bs, sid, lane};
}

// ST the tiles' type, AT the sums' (ST, or float over half tiles).
template <short BM, short BN, short BK, short WM, short WN,
short lda_tgp, short ldb_tgp, typename ST = float>
short lda_tgp, short ldb_tgp, typename ST = float, typename AT = ST>
struct SteelMMA {
typedef vec<ST, 2> frag_type;
typedef vec<AT, 2> 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 +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;
Expand All @@ -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(
Expand All @@ -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<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<AT, 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 @@ -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 <short BM, bool TA = false, bool TB = false, short BK = 16, typename BSrc,
typename ST>
template <short BM, bool TA = false, bool TB = false, short BK = 16, typename AT = float,
typename BSrc, typename ST>
void steel_body_(device const float* A, BSrc B,
device float* C, constant gemm_params& p,
threadgroup ST* As, threadgroup ST* Bs,
Expand All @@ -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_<TB, BN, BK, ldb_nn, tgp_size>(
B, p, col0, Bs, ushort(sid), ushort(lane));
SteelMMA<BM, BN, BK, WM, WN, lda_nn, ldb_nn, ST> mma_op(sid, lane);
SteelMMA<BM, BN, BK, WM, WN, lda_nn, ldb_nn, ST, AT> mma_op(sid, lane);

int k_iters = int(p.K / BK);
short lbk = short(p.K) - short(k_iters * BK);
Expand Down Expand Up @@ -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)]], \
Expand All @@ -935,10 +938,10 @@ void steel_body_(device const float* A, BSrc B,
threadgroup ST As[BM * (BK + steel_pad_<ST>())]; \
threadgroup ST Bs[BK * (64 + steel_pad_<ST>())]; \
gemm_slice_(A, B, C, p, tgid.z); \
steel_body_<BM, TA, TB, BK>(A, BSRC, C, p, As, Bs, tgid, sid, lane); \
steel_body_<BM, TA, TB, BK, AT>(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) \
Expand Down
13 changes: 10 additions & 3 deletions include/metal_kernels_nn.metal
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
Loading
Loading