diff --git a/.gitignore b/.gitignore index fad0db0a..7e1a6424 100644 --- a/.gitignore +++ b/.gitignore @@ -5,3 +5,4 @@ compile_commands.json *.rad /sync-jarvis.sh __pycache__/ +.cache/ diff --git a/NOTICE b/NOTICE index d81cbbbe..bd429121 100644 --- a/NOTICE +++ b/NOTICE @@ -6,18 +6,21 @@ MXFP4 GEMM, the A-tiled MXFP4 prefill GEMM and the GDN kernels' overflow guards) MXFP4 decode and prefill GEMMs, the MXFP4 linear and the DFlash2 drafter's MXFP4 linears, stop strings after the reasoning block, and the draft refill on a prefix hit), goodman-b (four-rank tensor parallelism for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the -fused four-rank writes, the n-gram table in RAM, the four-class expert split, the Grafana -dashboard, the routed GEMM's decode loads and run search, the gated residual's prefill read form -and row groups, the fused router launch, the adaptive draft window, the MoE prefill forms and the -sorted operand's decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000 -(the n-gram gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor -parallelism, serving any world size from the shipped container, the request log, an uneven world's -per-rank KV and weights split, --rope-scaling, the model entry's context length, root and -capabilities, /props, the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of -the three-rank lossy-wire crash, cardclock.py, --busy-prefill-chunk, and curl, jq and a CA bundle -in the image with hfget.sh under its busybox), hazyumps (static YaRN for the Qwen rotary paths), -redxherring (--model taking a Hugging Face repo id) and zivius (LiquidAI's LFM2 and LFM2-VL and -d1's /v1/systemone, after the design of their Codeberg PR 50). +fused four-rank writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard, +the routed GEMM's decode loads and run search, the gated residual's prefill read form and row +groups, the fused router launch, the adaptive draft window, the MoE prefill forms, the sorted +operand's decode kernel, and for Gemma 4 its assistant head as a drafter that reads the trunk's +cache, bf16 checkpoints, the fused w4a8 decode step, the vision tower and window snapshots that let +a prefix hit resume), mechkbfan (the token embedding in the pinned host pool), Code000 (the n-gram +gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor parallelism, +serving any world size from the shipped container, the request log, an uneven world's per-rank KV +and weights split, --rope-scaling, the model entry's context length, root and capabilities, /props, +the three-rank two-shot all-reduce and tiered-int8 wire, the diagnosis of the three-rank lossy-wire +crash, cardclock.py, --busy-prefill-chunk, and curl, jq and a CA bundle in the image with hfget.sh +under its busybox), hazyumps (static YaRN for the Qwen rotary paths), redxherring (--model taking a +Hugging Face repo id), sfjes (Gemma 4 31B dense: its plugin, its two attention classes and their +kernels, and prefix reuse that leaves a windowed group alone) and zivius (LiquidAI's LFM2 and +LFM2-VL and d1's /v1/systemone, after the design of their Codeberg PR 50). This product includes software from the following projects, each under the MIT License. The license text is in the file named beside each. diff --git a/README.md b/README.md index 8ef6b27a..c6898613 100644 --- a/README.md +++ b/README.md @@ -22,6 +22,7 @@ If you wish to support the developement of the radiance engine you can do so [he | Qwen3.6-35B-A3B FP8, MTP | `qwen3.6-35b-a3b-fp8.rad` (35 GiB) | [download](https://huggingface.co/StillDeadcode/qwen3.6-35b-a3b-fp8) | `qwen3.6-35b-a3b.yaml` | | MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` | | MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` | +| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` | | Qwen3.8-27B bf16 | `qwen3.8-27b-bf16.rad` (50 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-bf16.yaml` | | Qwen3.8-Flash-Next bf16, a disk-streamed reference | `qwen3.8-flash-next-bf16.rad` (335 GiB) | [convert](#convert-a-checkpoint) | `flashnext-bf16.yaml` | | EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `embeddinggemma2.yaml` | @@ -35,6 +36,13 @@ mkdir -p /srv/models/rad && cd /srv/models/rad curl -LC - -O https://huggingface.co/StillDeadcode/minicpm5-2b-fp8/resolve/main/minicpm5-2b-fp8.rad ``` +The Gemma 4 container is keptn42's: GPTQ calibrated in transformers, with an int8 lm_head; its +repository has the recipe and the calibration step. To convert Google's bf16 checkpoint yourself, +`data/recipes/gemma4-31b-dense-bf16-w4a8.recipe` quantises without calibration (round-to-nearest +with a scale search, bf16 lm_head); see [Convert a checkpoint](#convert-a-checkpoint). On two R9700s +that container decodes at 103 tok/s on prose and 141 on code, against 112 and 150 for keptn42's, +and its drafts are accepted a little less often (0.46 against 0.50 of them on prose). + ## Run with Docker The host needs Docker and an `amdgpu` driver that supports ROCm 10.1; it does not need ROCm. The @@ -149,6 +157,10 @@ budgets, long context, speculative decoding and operating a server. build/bin/rad-convert ~/models/Qwen/Qwen3.8-27B -o qwen3.8-27b-bf16.rad \ --recipe data/recipes/q38-27b-bf16.recipe build/bin/rad-convert ~/models/Qwen/Qwen3.8-Flash-Next -o qwen3.8-flash-next-bf16.rad --max-ctx 4096 +build/bin/rad-convert ~/models/google/gemma-4-31B-it -o gemma4-31b-w4a8.rad \ + --recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \ + --set quantization_config.quant_method=compressed-tensors \ + --draft-model ~/models/google/gemma-4-31B-it-assistant ``` With Docker, use `docker run --rm -v ~/models:/models --entrypoint rad-convert stilldeadcode/radiance ...`. In diff --git a/abi/rad_builder.h b/abi/rad_builder.h index a0540103..a2efb946 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -546,6 +546,31 @@ typedef struct RadDrafterDecl { int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d); +/* A SERIAL HEAD WITH NO CACHE OF ITS OWN. Every attention layer of it reads one of the TRUNK's + * layers' K and V and writes none -- Gemma 4's assistant head, whose layers have a query + * projection and nothing else, reads the last sliding and the last global trunk layer. Called + * once, after rad_declare_drafter, by a plugin whose serial head is that shape. Additive export: a + * plugin that does not call it drafts exactly as before, and RAD_ABI_VERSION does not move. + * + * What it changes in the serial driver, and each item follows from the head writing nothing: + * + * NO HISTORY IS OWED. A history pass exists to fill a head's own K and V, and there are none to + * fill. The pass carries round 1 alone: ONE row a drafting sequence, at the committed position, + * with the token the trunk chose after it and the trunk's hidden state there (out_ids). A + * sequence that does not draft gets no row, and a step with nothing to draft no pass. + * + * EVERY ROUND RUNS AT THAT SAME POSITION, OVER THE SAME CONTEXT. A head with a cache of its own + * steps one position a round and attends to what it wrote there. This one has nowhere to write, + * and the trunk's cache past the committed position holds the K and V of drafts the last verify + * REJECTED, or of nothing. So every round's `seqused` ends at the committed position, and what + * the head proposed travels forward in its hidden state and its next input token instead. + * + * `pos_offset` is where those rows sit for the rotary, as an offset from the committed position: + * 0 is the position of the trunk hidden state the head continues from, 1 the position of the token + * it embeds. It moves nothing else -- the context ends at the committed position either way -- and + * which one a checkpoint was trained with is the plugin's to know. */ +int rad_drafter_shared_kv(RadBuilder* b, int pos_offset); + /* ================================================================== the encoder */ /* A MEDIA ENCODER THE PLUGIN RUNS ON AN ENCODER PASS (RadBatch::enc), declared for the reason the * logits buffer and the drafter are: the core drives the pass and reads its result, so it has to @@ -679,6 +704,18 @@ int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); * UTF-8; NULL reads as "". The engine copies what it needs while loading, so static storage in * the plugin is enough. * + * The other family is a call written as a name and ONE object holding its arguments + * (args_form = RAD_CHAT_ARGS_OBJECT): + * + * [call_open] name_prefix NAME name_suffix { key: value, ... } [call_end] [call_close] + * + * The object is JSON, or a dialect of it: strings between object_string_open and + * object_string_close, their text verbatim, and keys written bare (object_bare_keys). Gemma 4 is + * "<|tool_call>" / "", "call:" / "" / "", strings "<|\"|>" / "<|\"|>", bare keys -- + * `<|tool_call>call:get_weather{city:<|"|>Paris<|"|>}` -- and the reply's JSON + * arguments are that object respelled as JSON. The arg_* fields describe tagged arguments only + * and are empty in this family. + * * THE STRUCT GROWS AT ITS END AND NEVER CHANGES IN THE MIDDLE. `struct_size` is * sizeof(RadChatFormat) as the plugin was compiled; the engine reads only the fields that size * covers and treats the rest as zero, so a plugin built against an older header keeps loading @@ -700,6 +737,11 @@ enum { RAD_CHAT_THINK_NEVER = 2 /* the model opens its own block, if any */ }; +enum { + RAD_CHAT_ARGS_TAGGED = 0, /* each argument in its own tags: arg_prefix .. arg_value_suffix */ + RAD_CHAT_ARGS_OBJECT = 1 /* one object after the name, in JSON or the object_* dialect */ +}; + typedef struct RadChatFormat { uint32_t struct_size; const char* name; /* for the startup log; NULL is the plugin's name */ @@ -739,6 +781,23 @@ typedef struct RadChatFormat { * reply is read unconstrained. */ const char* const* triggers; uint32_t n_triggers; + + /* RAD_CHAT_ARGS_*: how a call's arguments are written. Zero is the tagged family above. With + * RAD_CHAT_ARGS_OBJECT, name_suffix may be empty -- the name then ends where the object + * begins -- and so may call_end, when the object's own closing brace ends the call. */ + uint32_t args_form; + /* RAD_CHAT_ARGS_OBJECT: a string delimiter of the object's dialect besides JSON's `"`. What + * stands between the two is the string, verbatim -- the dialect has no escapes. NULL: the + * object writes JSON strings only. */ + const char* object_string_open; + const char* object_string_close; + /* RAD_CHAT_ARGS_OBJECT: non-zero when the dialect writes a key bare, `key:value`. */ + uint32_t object_bare_keys; + + /* Non-zero: a reasoning block may open again LATER in the reply -- after its answer, between + * calls -- and is read as reasoning there as well, and a reasoning_close with no block open + * is not part of the answer. Zero: only a block the reply starts with is reasoning. */ + uint32_t reasoning_anywhere; } RadChatFormat; /* Return the format, or NULL for "derive it from the chat template". Called once at startup. */ diff --git a/arch/gemma4_bf16/CMakeLists.txt b/arch/gemma4_bf16/CMakeLists.txt new file mode 100644 index 00000000..1a4f2317 --- /dev/null +++ b/arch/gemma4_bf16/CMakeLists.txt @@ -0,0 +1,11 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/gemma4_bf16 -B build -DCMAKE_PREFIX_PATH=`) -- the same +# rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(gemma4_bf16 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(gemma4_bf16 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/gemma4_bf16.cpp) diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp new file mode 100644 index 00000000..2549d404 --- /dev/null +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -0,0 +1,1575 @@ +/* gemma4_bf16.cpp -- Gemma 4 dense, bf16, with its vision tower (gemma4_vision.h). + * + * Two attention classes over ONE residual stream, alternating by layer. A "sliding" layer is + * sliding-window attention over head_dim 256 with a v projection and standard RoPE; a "global" + * layer is windowless attention over head_dim 512 with no v projection (k == v) and proportional + * RoPE (the "head" ladder) over the partial rotary width. Every layer is GemmaRMSNorm -- x_hat * + * (1 + w) -- with a SECOND norm on each projection's output before its residual, a weightless RMS + * on the value, and a GELU (not SwiGLU) feed-forward. The final logits are soft-capped to + * cap * tanh(x / cap). + */ +#include + +#include "gemma4_chat_format.h" + +#include +#include +#include +#include +#include +#include + +#include "gemma4_vision.h" + +namespace gemma4_bf16 { + +using namespace rad::arch; + +/* ---- container geometry RadModelMeta does not name. Both spellings are accepted: a .rad + * converted from the HF safetensors carries the flat HuggingFace keys and one converted from a + * GGUF carries llama.cpp's. */ +static long long g4_i(const RadModelMeta* m, const char* bare, long long dflt) { + long long v = rad_meta_geti(m, bare, dflt); + if (v == dflt) v = rad_meta_geti(m, (std::string("text_config.") + bare).c_str(), dflt); + return v; +} +static double g4_f(const RadModelMeta* m, const char* bare, double dflt) { + double v = rad_meta_getf(m, bare, dflt); + if (v == dflt) v = rad_meta_getf(m, (std::string("text_config.") + bare).c_str(), dflt); + return v; +} + +/* THE RESIDUAL JUNCTIONS AS ONE OP EACH. A w4a8 block opens with rmsnorm -> quant_act_i8 and closes + * with rmsnorm (post) -> add -> [scale], so between two blocks the stream runs five single-row + * dispatches -- the previous block's post-norm, the add, the layer scalar, this block's norm and + * its quantiser. libr4d's `rmsnorm_quant_i8` is that chain in one dispatch, byte-identical to it, + * and q, k and v read one quantised pair instead of three; `qkv_norm_rope` does the same for the + * attention prologue's five ops, `gelu_mul_quant_i8` for down's input, and at two ranks + * `ar_rmsnorm_quant_i8` folds the all-reduce in front of each junction into it. A kernel set without + * an op keeps that op's chain. */ + +/* layer_types is optional. When present it must name EVERY layer "full_attention" or + * "sliding_attention"; when absent the (l + 1) % interval == 0 fallback is the model card. */ +static int g4_parse_types(const char* lt, int64_t n, std::vector& is_global) { + is_global.assign((size_t)n, -1); + size_t got = 0; + const char* p = lt; + while (*p) { + if (!std::strncmp(p, "full_attention", 14)) { + if (got >= (size_t)n) return RAD_E_INVAL; + is_global[got++] = 1; p += 14; + } else if (!std::strncmp(p, "sliding_attention", 17)) { + if (got >= (size_t)n) return RAD_E_INVAL; + is_global[got++] = 0; p += 17; + } else { + ++p; /* separators: whitespace, quotes, [ ] , and / */ + } + } + if (got != (size_t)n) return RAD_E_INVAL; + for (size_t i = 0; i < is_global.size(); ++i) if (is_global[i] < 0) return RAD_E_INVAL; + return RAD_OK; +} + +static int g4_schedule(const RadModelMeta* m, int64_t n, int64_t interval, + std::vector& is_global) { + const char* lt = rad_meta_gets(m, "layer_types", rad_meta_gets(m, "text_config.layer_types", nullptr)); + is_global.assign((size_t)n, 0); + if (lt && *lt) { + RAD_ARCH_TRY(g4_parse_types(lt, n, is_global)); + } else { + if (interval <= 0) { + fprintf(stderr, "radiance: gemma4: no layer_types and invalid full_attention_interval %lld\n", + (long long)interval); + return RAD_E_INVAL; + } + for (int64_t l = 0; l < n; ++l) is_global[(size_t)l] = ((l + 1) % interval == 0) ? 1 : 0; + } + return RAD_OK; +} + +/* A LINEAR'S WEIGHT IS ITS CHECKPOINT'S `X.weight`. Google's bf16 release names it so; its CT-INT4 + * (QAT) release ships `X.weight_packed` and `X.weight_scale`, which the checkpoint reader imports + * as `X.weight` (core/format/checkpoint.h, CT-INT4), so the name map is the same for both. */ + +/* The two attention classes share the residual stream and the FFN but differ in head geometry, + * the value path and the RoPE. The main Geom (from geom_from) is the slider; the global class is + * read from the container head and folded in here. */ +struct ClassGeom { + int64_t n_head = 0, n_head_kv = 0, head_dim = 0, n_rot = 0; + int64_t window = 0; + double theta = 1.0; + float scale = 1.0f; + bool head_ladder = false; /* true: proportional over head_dim (global) */ + bool has_v = true; /* false: k == v (global) */ + int64_t q_dim() const { return n_head * head_dim; } + int64_t kv_dim() const { return n_head_kv * head_dim; } + int64_t gqa() const { return n_head / n_head_kv; } +}; + +/* ---- one linear, plain bf16 or w4a8. The recipe re-quantises the GEMM weights to int4 codes + * with an f16 scale per [1 x 128] (group 128); a weight no rule matches stays bf16. This probes + * the weight's encoding and chooses the op by it: `gemm_nt` for a plain bf16 weight, `gemm_nt_q` + * at dtype w4a8 for the codes + their scale. w4a8 is the int8-activation grid: it reads an int8 + * activation + an f32 per-row scale, which the model's bf16 activation has to be quantised into. + * The quantiser is declared here (quant_act_i8) over the activation's bf16 plane and writes the + * int8 pair (q8, s8) the GEMM reads -- in the GEMM's fragment byte order, with one scale per row. + * quant_act_i8g (row-major, a per-(row,group) scale) is i8a8's producer, not this one's; pairing + * it with w4a8 is the compounding-into-inf seed of the all-NaN logits (see the declare comment). + * w4a16 was tried and is the WRONG grid: its row declares an f16 activation and + * its launcher never checks the operand dtype, so feeding it the model's bf16 bits reinterprets + * them as f16 -- a magnitude-compressed garbage stream (bf16 0.1 -> 1.45, 1.0 -> 1.875), finite + * nonsense that propagates through the residual. The name map is made here, before the weight is + * asked what it is (Builder::finish() needs the map entry before the declaration). */ +struct G4Linear { + rad_weight w = 0, ws = 0; /* the codes + scale (w4a8), or the single bf16 weight */ + rad_op op = 0, op_q = 0; /* the quantised GEMM and, for w4a8, its activation quantiser */ + rad_buf q8 = 0, s8 = 0; /* the int8 pair (i8 codes + f32 row scale) the quantiser writes */ + int64_t N = 0, K = 0; + bool quant = false; /* true: w4a8 */ + /* READS ANOTHER LINEAR'S INT8 PAIR. q, k and v quantise the same norm output into the same + * per-row grid (quant_act_i8 over [T, n_embd]), so three quantisers write three identical + * pairs. With `in_from` set at declare this linear reads that linear's pair and declares no + * quantiser of its own: the GEMM's input bytes are the same bytes, one dispatch instead of + * three. */ + bool shared_in = false; + + int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, + std::initializer_list src, + int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, + rad_buf a, rad_buf y, + std::initializer_list row_parts = {}, + const G4Linear* in_from = nullptr); + void step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const; + /* the GEMM alone, for a caller that wrote the int8 pair itself (a fused norm + quantiser) */ + void gemm(RadCtx* c, rad_buf y, int64_t T) const; +}; + +inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, + std::initializer_list src, + int64_t n_out, int64_t n_in, int shard, RadWeightGroup grp, + rad_buf a, rad_buf y, + std::initializer_list row_parts, + const G4Linear* in_from) { + N = n_out; K = n_in; + if (N <= 0 || K <= 0 || src.size() == 0) return RAD_E_INVAL; + const char* wn = nm.f("%s.weight", base); + if (src.size() == 1) RAD_ARCH_TRY(map_copy(b, wn, *src.begin())); + else RAD_ARCH_TRY(map_concat(b, wn, src, 0)); + RadEncoding enc{}; + const bool known = weight_enc(b, wn, &enc); + /* a builder with no model behind it (a test, a synthetic tool) answers RAD_E_NOTFOUND, and a + * weight declared there is read as plain in its declared dtype -- the bf16 path. */ + const bool plain = !known || (rad_enc_is(&enc, "plain") && enc.n_planes == 1 && + enc.plane[0].dtype == RAD_BF16); + int64_t parts[RAD_MAX_ROW_PARTS] = {0}; + int np = 0; + for (int64_t p : row_parts) if (np < RAD_MAX_ROW_PARTS) parts[np++] = p; + + if (plain) { + w = decl_w(b, wn, RAD_BF16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, 0, row_parts); + if (!w) return RAD_E_INVAL; + op = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w)), + { a }, { y }); + return op ? RAD_OK : RAD_E_INVAL; + } + + /* a w4 weight: i4 codes + an f16 scale per [1 x 128]. The GEMM (gemm_nt_q at w4a8) reads an + * int8 activation + an f32 per-row scale, which the model's bf16 activation has to be quantised + * into, so the quantiser (quant_act_i8g) is declared over the activation's bf16 plane `a` and + * writes the int8 pair (q8, s8) the GEMM reads. The codes + scale layout is byte-for-byte the + * w4a16 one -- the container serves unchanged; only the op dtype and the activation producer + * differ. */ + const RadEncPlane* sc = rad_enc_plane(&enc, "scale"); + /* An 8-bit weight on the same grid -- i8 codes, an f16 scale per [1 x 128] -- is the same + * pair at twice the radix: gemm_nt_q at w8a8 reads the identical int8 activation + per-row + * scale the w4a8 GEMM reads, so the quantiser declaration is shared. It is how a recipe keeps + * a linear the int4 grid hurts (the attention, down_proj) closer to the checkpoint. */ + const uint32_t cdt = known && enc.n_planes > 0 ? enc.plane[0].dtype : 0; + const bool w4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 2 && !enc.transform[0] && + (cdt == RAD_I4 || cdt == RAD_I8) && enc.plane[0].block[1] == 1 && + sc && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == 128; + if (w4) { + if (N % 16 || K % 128) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a w4 weight takes rows in " + "16s and K in whole 128-column scale groups.\n", base, + (long long)N, (long long)K); + return RAD_E_INVAL; + } + const char* sn = nm.f("%s.scale", base); + w = decl_view(b, wn, nullptr, "codes", cdt, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + ws = decl_view(b, sn, wn, "scale", RAD_F16, { N, K / 128 }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + if (!w || !ws) return RAD_E_INVAL; + if (in_from && in_from->quant && in_from->q8 && in_from->K == K) { + q8 = in_from->q8; + s8 = in_from->s8; + shared_in = true; + } else { + q8 = decl_b(b, nm.f("%s.q8", base), RAD_I8, { g.max_tok, K }); + s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, 1 }); + } + if (!q8 || !s8) return RAD_E_INVAL; + /* quant_act_i8, NOT quant_act_i8g: the w4a8 GEMM's A fragment reads a byte-shuffled plane + * (r4d_gemm_w4a8_nt_m64.hip:46-52, "the quantiser writes it") and applies an f32 per-ROW + * scale at the store (:61-63), so the producer must be the fragment-order per-row quantiser + * (r4d_quant_act_i8.hip:1-2). quant_act_i8g writes PLAIN ROW-MAJOR codes with a + * per-(row,group) scale (r4d_rows.cpp:2043-2046, "what the int8 trunk GEMMs (i8a8) read") + * -- pairing it with this GEMM shuffles the dot and broadcasts the wrong scale grid, the + * compounding-into-inf seed of the all-NaN logits. */ + /* group=K, NOT 128: the host quantisers (libref/libavx) are per-`group` -- one f32 scale + * per group of `group` elements -- while the device one (r4d_quant_act_i8) is per-ROW and + * ignores `group` in this 3-operand form (it only reads it in the asum form). group=K makes + * the host ngrp=1 (one scale per row, the [M,1] buffer the arch declares) and is a no-op on + * the device, so the same declaration is self-consistent on both backends. group=128 left + * the host quantiser refusing the [M,1] scale (it wants [M, K/128]). */ + if (!shared_in) + op_q = rw(b, RAD_OP(b, "quant_act_i8", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K), + RAD_INT("group", K), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a }, { q8, s8 }); + op = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", 128), RAD_STR("dtype", cdt == RAD_I8 ? "w8a8" : "w4a8")), + RAD_WEIGHTS(w, ws)), + { q8, s8 }, { y }); + quant = true; + return ((op_q || shared_in) && op) ? RAD_OK : RAD_E_INVAL; + } + + char en[256]; + rad_enc_format(&enc, en, sizeof en); + fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16, w4a8 or w8a8 -- " + "neither matches\n", wn, en); + return RAD_E_DTYPE; +} + +inline void G4Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const { + if (quant) { + /* quantise the bf16 activation into the int8 pair (fragment order + a per-row scale), then + * read the pair. The scale plane is one f32 per row, browsed at T rows like the codes. + * quant_act_i8's schema is 4 operands -- x, q, scale, asum -- and `asum` (the per-group row + * sums the asymmetric grids subtract) is absent on this symmetric grid, so it is passed as + * a null tensor, not dropped: operands are positional (issue.cpp). */ + if (!shared_in) + RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE); + gemm(c, y, T); + } else + RAD_ISSUE(c, op, brows(a, T), RAD_W(w), brows(y, T)); +} + +inline void G4Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const { + RAD_ISSUE_N(c, op, T, brows(q8, T), brows(s8, T), RAD_W(w), RAD_W(ws), + brows(y, T), RAD_NONE, RAD_NONE); +} + +/* ---- one attention block, parameterised by class. */ +struct Gemma4Attn { + struct Wire { rad_buf x = 0, h = 0, q = 0, k = 0, v = 0, attn = 0; }; + + Wire w{}; + Geom g{}; + ClassGeom cls{}; + int layer = 0; + rad_kvgroup kv = 0; + + rad_weight w_norm = 0, w_qn = 0, w_kn = 0, w_post = 0; /* the norms (always bf16) */ + G4Linear ln_q{}, ln_k{}, ln_v{}, ln_o{}; /* the GEMM weights (bf16 or w4a8) */ + rad_op op_norm = 0, op_vn = 0, op_qn = 0, op_kn = 0, + op_rq = 0, op_rk = 0, op_attn = 0, op_kv = 0, op_post = 0, op_ar = 0, op_add = 0; + /* the five prologue ops (v norm, q norm, k norm, two rotaries) as one, where it resolves */ + rad_op op_qnr = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, + rad_kvgroup group, const Wire& wire, const char* pre); + /* `entry_done`: a junction op already wrote this block's quantised input (ln_q's pair). + * `tail_fused`: the caller issues the post-norm and the add as a junction op. */ + void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false, + bool ar_fused = false) const; +}; + +int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, + rad_kvgroup group, const Wire& wire, const char* pre) { + g = geom; cls = cgeo; layer = l; kv = group; w = wire; + const int64_t qd = cls.q_dim(), kvd = cls.kv_dim(); + + /* the norms: always bf16 (no rule matches them), name map first. */ + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), nm.ckpt("%s.%lld.self_attn.k_norm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_post_norm.weight", l), nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l))); + /* declared bf16, not f32: the checkpoint holds them bf16 and no rule re-quantises them, so an + * f32 declaration would widen them at load -- and a widened weight cannot be served from the + * mapped tier, which the whole layer group is pinned to because the w4a16 GEMM has no device + * kernel for the M > 64 prefill band. Reading the gain in its own (bf16) dtype is identical: + * the widening was a lossless upcast of the same bf16 value. */ + w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_qn = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_BF16, {cls.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_kn = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_BF16, {cls.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_post = decl_w(b, nm.f("blk.%d.attn_post_norm.weight", l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + + /* the GEMM weights: bf16 or w4a8, probed by G4Linear. */ + RAD_ARCH_TRY(ln_q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), + { nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l) }, + qd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.q)); + const G4Linear* qin = &ln_q; /* k and v read q's int8 pair */ + RAD_ARCH_TRY(ln_k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), + { nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l) }, + kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.k, {}, qin)); + if (cls.has_v) + RAD_ARCH_TRY(ln_v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), + { nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l) }, + kvd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.v, {}, qin)); + RAD_ARCH_TRY(ln_o.declare(b, nm, g, nm.f("blk.%d.attn_o", l), + { nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l) }, + g.n_embd, qd, RAD_SHARD_COL, grp_layer(l), w.attn, w.h)); + + /* input norm: x_hat * w over the residual stream. */ + op_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + + /* Gemma normalises the value with a WEIGHTLESS rms (the checkpoint has no v_norm gain). A + * sliding class normalises v in place; a k_eq_v class derives v from the RAW k into its own + * buffer, which must happen before k_norm rewrites k. */ + op_vn = rw(b, RAD_OP(b, "rmsnorm_p", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * cls.n_head_kv), RAD_INT("n", cls.head_dim), + RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {cls.has_v ? w.v : w.k}, {w.v}); + + op_qn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * cls.n_head), RAD_INT("n", cls.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_qn)), + {w.q}, {w.q}); + op_kn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * cls.n_head_kv), RAD_INT("n", cls.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_kn)), + {w.k}, {w.k}); + + /* sliding: standard RoPE over the full width, theta_s. global: proportional over the partial + * width (the "head" ladder), theta_g. q names its query heads; k its kv heads. */ + op_rq = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", 0), + RAD_F64("theta", cls.theta), RAD_F64("scale", cls.scale), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", cls.n_rot), + RAD_STR("ladder", cls.head_ladder ? "head" : "rotary")), + RAD_NOWEIGHTS), + {w.q}, {w.q}); + /* The rope kernel serves the fused QKV row and requires n_head > 0 (it rotates n_head + + * n_head_kv heads over a row of (n_head + 2*n_head_kv)*head_dim). The K heads are a separate + * buffer, so the K-only form is expressed as a Q-only form over the K heads: n_head is the + * count of heads to rotate (here n_head_kv) and n_head_kv is 0, so the row is + * n_head_kv*head_dim -- exactly the K buffer's width. RoPE is identical for Q and K (same + * theta, same positions), so this is the reference's separate K rope (llama.cpp ggml_rope_ext + * over the K buffer). */ + op_rk = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head", cls.n_head_kv), RAD_INT("n_head_kv", 0), + RAD_F64("theta", cls.theta), RAD_F64("scale", cls.scale), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", cls.n_rot), + RAD_STR("ladder", cls.head_ladder ? "head" : "rotary")), + RAD_NOWEIGHTS), + {w.k}, {w.k}); + + /* Gemma 4 scores Q.K WITHOUT the 1/sqrt(head_dim) factor: both the HF reference + * (Gemma4TextAttention: self.scaling = 1.0) and the vLLM oracle use scaling = 1.0 -- + * the learnable q/k RMSNorm weights absorb the scaling, so no extra 1/sqrt(d) is applied. + * attn_paged's default is 1/sqrt(head_dim), so pass 1.0 explicitly to match the reference. */ + op_attn = rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1), RAD_INT("window", cls.window), + RAD_INT("n_head", cls.n_head), RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_F64("scale", 1.0), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.q}, {w.attn}); + + /* THE PROLOGUE AS ONE OP: libr4d's `qkv_norm_rope` is rmsnorm_p + rmsnorm + rmsnorm + rope + + * rope over the three separate projections, byte-identical to them, one workgroup a (token, + * head). Declared beside the unfused five and used only where it resolves; a multi-component + * or YaRN rotary keeps the five. */ + if (!g.rope_mc && g.yarn.factor == 0.0f) + op_qnr = rw(b, RAD_OP(b, "qkv_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", cls.n_head_kv), + RAD_F64("theta", cls.theta), RAD_F64("eps", g.eps), + RAD_F64("scale", cls.scale), RAD_STR("mode", "neox"), + RAD_INT("rotary_dim", cls.n_rot), + RAD_STR("ladder", cls.head_ladder ? "head" : "rotary"), + RAD_F64("wadd", g.wadd_qk), RAD_INT("v_from_k", cls.has_v ? 0 : 1), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_qn, w_kn)), + {w.q, w.k, w.v}, {w.q, w.k, w.v}); + + op_kv = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head_kv", cls.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.k, w.v}, {}); + + /* o_proj is column-sharded: the rank's partial sum is reduced FIRST, then normed. */ + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + + /* the SECOND residual: the (reduced) attention output is itself normed before the add. */ + op_post = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_post)), + {w.h}, {w.h}); + + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + return RAD_OK; +} + +void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused, + bool ar_fused) const { + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int32_t* table = kvb ? kvb->block_table : nullptr; + const int32_t* used = kvb ? kvb->seqused : nullptr; + const int64_t T = batch->n_tok; + + if (entry_done) { + ln_q.gemm(c, w.q, T); + ln_k.gemm(c, w.k, T); + if (cls.has_v) ln_v.gemm(c, w.v, T); + } else { + RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + ln_q.step(c, w.h, w.q, T); + ln_k.step(c, w.h, w.k, T); + if (cls.has_v) ln_v.step(c, w.h, w.v, T); + } + + if (op_qnr) { + RAD_ISSUE(c, op_qnr, brows(w.q, T), brows(w.k, T), brows(w.v, T), rope_posmc(g, batch, T), + RAD_W(w_qn), RAD_W(w_kn)); + } else { + /* normalise v FIRST: on a k_eq_v class v is derived from the raw k, before k_norm rewrites it. */ + RAD_ISSUE_N(c, op_vn, T * cls.n_head_kv, brows(cls.has_v ? w.v : w.k, T), brows(w.v, T)); + RAD_ISSUE_N(c, op_qn, T * cls.n_head, brows(w.q, T), RAD_W(w_qn), brows(w.q, T)); + RAD_ISSUE_N(c, op_kn, T * cls.n_head_kv, brows(w.k, T), RAD_W(w_kn), brows(w.k, T)); + + RAD_ISSUE(c, op_rq, brows(w.q, T), rope_posmc(g, batch, T)); + RAD_ISSUE(c, op_rk, brows(w.k, T), rope_posmc(g, batch, T)); + } + + RAD_ISSUE(c, op_kv, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), kv_cache(kv, layer)); + + RAD_ISSUE_N(c, op_attn, batch->max_q_len, + brows(w.q, T), kv_cache(kv, layer), + praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), + praw(used, RAD_I32, batch->n_seq), + RAD_NONE, RAD_NONE, + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), + brows(w.attn, T)); + + ln_o.step(c, w.attn, w.h, T); + /* THE ALL-REDUCE BEFORE THE POST-NORM. o_proj is column-sharded, so each rank holds a PARTIAL + * sum here; the norm is of the whole output (HF, and vLLM's RowParallelLinear, reduce first). + * Normed per rank and then summed is sum_r rmsnorm(p_r), not rmsnorm(sum_r p_r). */ + if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + if (tail_fused) return; + RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); + RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T)); +} + +/* ---- the feed-forward: GELU (not SwiGLU), with a second norm on the down-projection output. */ +struct Gemma4Mlp { + struct Wire { rad_buf x = 0, h = 0, gu = 0, ffn = 0; }; + + Wire w{}; + Geom g{}; + int layer = 0; + rad_weight w_norm = 0, w_post = 0; /* the norms (always bf16) */ + G4Linear ln_gu{}, ln_down{}; /* the GEMM weights (bf16 or w4a8) */ + rad_op op_norm = 0, op_act = 0, op_post = 0, op_ar = 0, op_add = 0; + /* gelu_mul and down's quantiser as one, where it resolves (libr4d `gelu_mul_quant_i8`) */ + rad_op op_gq = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre); + void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false, + bool ar_fused = false) const; +}; + +int Gemma4Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* pre) { + g = geom; layer = l; w = wire; + + /* the norms: always bf16 (no rule matches them), name map first. */ + RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_norm.weight", l), nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_post_norm.weight", l), nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l))); + /* bf16, not f32: same reason as the attention norms -- an f32 declaration widens them and a + * widened weight cannot be served from the mapped tier the whole layer group is pinned to. */ + w_norm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_post = decl_w(b, nm.f("blk.%d.ffn_post_norm.weight", l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + + /* the GEMM weights: bf16 or w4a8, probed by G4Linear. gate_up is the gate|up fusion. */ + RAD_ARCH_TRY(ln_gu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), + { nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l), + nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l) }, + 2 * g.n_ff, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.gu, + { g.n_ff, g.n_ff })); + RAD_ARCH_TRY(ln_down.declare(b, nm, g, nm.f("blk.%d.ffn_down", l), + { nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l) }, + g.n_embd, g.n_ff, RAD_SHARD_COL, grp_layer(l), w.ffn, w.h)); + + op_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + op_act = rw(b, RAD_OP(b, "gelu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.gu}, {w.ffn}); + if (ln_down.quant && !ln_down.shared_in) + op_gq = rw(b, RAD_OP(b, "gelu_mul_quant_i8", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.gu}, {ln_down.q8, ln_down.s8}); + /* down_proj is column-sharded: reduce first, then the post-norm. */ + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + op_post = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_post)), + {w.h}, {w.h}); + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + return RAD_OK; +} + +void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused, + bool ar_fused) const { + const int64_t T = batch->n_tok; + if (entry_done) { + ln_gu.gemm(c, w.gu, T); + } else { + RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + ln_gu.step(c, w.h, w.gu, T); + } + if (op_gq) { + RAD_ISSUE_N(c, op_gq, T, brows(w.gu, T), brows(ln_down.q8, T), brows(ln_down.s8, T), RAD_NONE); + ln_down.gemm(c, w.h, T); + } else { + RAD_ISSUE(c, op_act, brows(w.gu, T), brows(w.ffn, T)); + ln_down.step(c, w.ffn, w.h, T); + } + /* The all-reduce before the post-norm, as in the attention block: down_proj is column-sharded. */ + if (op_ar && !(tail_fused && ar_fused)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + if (tail_fused) return; + RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); + RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T)); +} + +/* ---- one residual junction as one op: [post-norm of the branch `x`, the add into `res`, the + * layer scalar,] the next block's norm and its int8 quantiser (libr4d `rmsnorm_quant_i8`). `res` + * null is the plain form, the norm of `x` itself -- the first block's entry. */ +struct G4Junction { + rad_op op = 0; + rad_op op_ar = 0; /* the same with the two-rank exact all-reduce of `x` in front, or 0 */ + rad_buf x = 0, res = 0, q8 = 0, s8 = 0; + rad_weight w = 0, wp = 0, sc = 0; + + int declare(RadBuilder* b, const Geom& g, rad_buf x_, rad_buf res_, rad_weight w_, + rad_weight wp_, rad_weight sc_, const G4Linear& into) { + x = x_; res = res_; w = w_; wp = wp_; sc = sc_; q8 = into.q8; s8 = into.s8; + if (!into.quant || into.shared_in || !q8 || !s8 || !w || (sc && !wp) || ((wp || sc) && !res)) + return RAD_E_INVAL; + const RadParam p[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_STR("dtype", g.dtype), + RAD_F64("wadd", g.wadd) }; + const rad_weight ws[3] = { w, wp, sc }; + const int nw = sc ? 3 : (wp ? 2 : 1); + op = rad_decl_op(b, "rmsnorm_quant_i8", p, (int)(sizeof p / sizeof p[0]), ws, nw); + if (!op) return RAD_OK; /* not resolved: the caller keeps the unfused chain */ + const rad_buf rd[2] = { x, res }; + const rad_buf wr[3] = { q8, s8, res }; + rad_op_reads (b, op, rd, res ? 2 : 1); + rad_op_writes(b, op, wr, res ? 3 : 2); + /* THE ALL-REDUCE IN FRONT, at two ranks on the exact wire: `x` is then a rank's partial sum + * of a column-sharded linear, the message as well as the input. A deployment that allows + * the lossy wire keeps the standalone all-reduce, which may pick it. */ + if (res && g.world == 2 && g.wire_exact) { + const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_INT("world_size", g.world), + RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) }; + op_ar = rad_decl_op(b, "ar_rmsnorm_quant_i8", pa, (int)(sizeof pa / sizeof pa[0]), ws, nw); + if (op_ar) { + const rad_buf wa[4] = { x, q8, s8, res }; + rad_op_reads (b, op_ar, rd, 2); + rad_op_writes(b, op_ar, wa, 4); + } + } + return RAD_OK; + } + void step(RadCtx* c, int64_t T, bool with_ar = false) const { + RAD_ISSUE_N(c, with_ar ? op_ar : op, T, brows(x, T), res ? brows(res, T) : RAD_NONE, RAD_W(w), + brows(q8, T), brows(s8, T), RAD_NONE, + wp ? RAD_W(wp) : RAD_NONE, sc ? RAD_W(sc) : RAD_NONE); + } +}; + +/* ==================================================================== the assistant head + * + * GEMMA 4'S DRAFT HEAD, the "assistant" (Gemma4AssistantForCausalLM), merged under `draft.` by + * `rad-convert --draft-model `. Read off the checkpoint and three reference + * implementations -- transformers' modeling_gemma4_assistant.py with its candidate generator, + * vLLM's gemma4_mtp.py with spec_decode/gemma4.py, and llama.cpp's gemma4-assistant.cpp: + * + * x = pre_projection( concat( E_trunk[tok] * sqrt(n_trunk), h_trunk ) ) 2*n_trunk -> n + * x = the head's layers over x (31B: sliding, sliding, sliding, full) + * hd = norm(x) + * logits = lm_head(hd) the head's OWN table, tied to its embed_tokens; no soft-cap + * h' = post_projection(hd) n -> n_trunk + * + * `h_trunk` is the trunk's FINAL-NORMED hidden state -- the trunk lm_head's input -- and `E_trunk` + * the trunk's embedding table, scaled the way the trunk scales it. The head's own embed_tokens is + * its lm_head and nothing else (vLLM swaps the trunk's table in for the input side). The + * concatenation is the embedding FIRST, then the hidden state; all three references agree. + * + * A LAYER IS A TRUNK LAYER WITH THE KEY AND VALUE TAKEN AWAY: q_proj, the per-head q norm, the + * rotary of its class, attention over the TRUNK'S cache at scale 1, o_proj, the same four + * plain-gain norms, the GELU feed-forward and the per-layer scalar. Each layer reads the LAST trunk + * layer of its own class -- the sliding ones the last sliding layer, the full one the last full + * layer, 58 and 59 on the 31B (vLLM's _setup_gemma4_kv_sharing). So the head's q heads and the + * trunk's kv heads must be the same geometry, and declare checks that they are. + * + * IT KEEPS NO CACHE OF ITS OWN, and that is what the core is told (rad_drafter_shared_kv): no + * history pass, one row a drafting sequence, every round at the committed position over the + * committed context. Round 1's row embeds the token the trunk chose and continues from the trunk's + * hidden state; round r embeds round r-1's proposal and continues from its h'. What the head + * proposed reaches the next round through those two and nothing else -- which is the whole design + * of the head, not a shortcut taken here. + * + * THE TENSOR-PARALLEL SPLIT IS THE TRUNK'S: q heads row-sharded over the ranks, so each rank's + * queries meet its own share of the trunk's kv heads; o_proj and the feed-forward down projection + * column-sharded, each followed by an all-reduce BEFORE its post-norm (the norm of a partial sum is + * not the partial of a norm). The two projections and every norm are replicated: they read and + * write the replicated stream, and a split would cost an all-reduce to save a few MiB. The lm_head + * is vocab-sharded like the trunk's and goes through the same sampler chain, greedy. */ +/* Where the head's rows sit for the rotary, relative to the committed position + * (rad_drafter_shared_kv), and the depth `--num-speculative-tokens auto` takes. */ +static constexpr int kHeadPosOffset = 0; +static constexpr int kHeadDepth = 3; + +struct Gemma4Head { + struct HLayer { + bool global = false; + int trunk_layer = 0; /* the trunk layer whose cache this layer reads */ + rad_kvgroup kv = 0; + ClassGeom cls{}; + rad_buf q = 0, attn = 0; /* the class's own rows: the two widths differ */ + rad_weight w_norm = 0, w_qn = 0, w_post = 0, w_fnorm = 0, w_fpost = 0, w_scalar = 0; + G4Linear ln_q{}, ln_o{}, ln_gu{}, ln_down{}; + rad_op op_norm = 0, op_qn = 0, op_rq = 0, op_attn = 0, op_ar = 0, op_post = 0, + op_add = 0, op_fnorm = 0, op_act = 0, op_far = 0, op_fpost = 0, op_fadd = 0, + op_scale = 0; + }; + + Geom g{}; /* the trunk's, with max_tok cut to the head's rows */ + int64_t n = 0; /* the head's width (1024 on the 31B) */ + int64_t n_trunk = 0; /* the trunk's width, which the two projections join */ + int64_t n_ff = 0; /* this rank's share of the feed-forward */ + int64_t rows = 0; /* the most rows one pass carries: one a drafting sequence */ + double softcap = 0.0; /* 0: none, which is what the 31B's head says */ + std::vector layers; + + rad_buf src = 0; /* the trunk's final-normed hidden state, [max_tok, n_trunk] */ + rad_buf logits = 0; /* the trunk's logits plane: the sampler reads the head's from it */ + rad_buf b_c = 0, b_e = 0, b_x = 0, b_h = 0, b_gu = 0, b_ffn = 0, b_hd = 0, b_hn = 0; + rad_weight w_tok = 0, w_norm = 0, w_lm = 0; + G4Linear ln_pre{}, ln_post{}; + rad_op op_hsrc = 0, op_hcopy = 0, op_embed = 0, op_embed_ar = 0, op_ecopy = 0, op_norm = 0, + op_logits = 0, op_cap = 0; + + int declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, const Geom& trunk, + const ClassGeom& cs, const ClassGeom& cg, rad_kvgroup kv_s, rad_kvgroup kv_g, + int last_sliding, int last_full, int64_t n_main, rad_weight tok_embd, + rad_buf trunk_h, rad_buf trunk_logits); + void step(RadCtx* c, const RadBatch* batch) const; +}; + +/* A `draft.` key under the head's text config, where Gemma4AssistantConfig nests every dimension, + * or at the top of it. */ +static long long hd_i(const RadModelMeta* m, const char* k, long long d) { + long long v = rad_meta_geti(m, (std::string("draft.text_config.") + k).c_str(), -0x7FFFFFFFll); + return v != -0x7FFFFFFFll ? v : rad_meta_geti(m, (std::string("draft.") + k).c_str(), d); +} +static double hd_f(const RadModelMeta* m, const char* k, double d) { + const double nan = std::nan(""); + double v = rad_meta_getf(m, (std::string("draft.text_config.") + k).c_str(), nan); + return std::isnan(v) ? rad_meta_getf(m, (std::string("draft.") + k).c_str(), d) : v; +} + +/* Does the container carry an assistant head at all? */ +static bool has_assistant(const RadModelMeta* m) { + const char* a = rad_meta_gets(m, "draft.architectures", ""); + return a && std::strstr(a, "Gemma4Assistant") != nullptr; +} + +int Gemma4Head::declare(RadBuilder* b, Names& nm, const RadModelMeta* meta, const Geom& trunk, + const ClassGeom& cs, const ClassGeom& cg, rad_kvgroup kv_s, + rad_kvgroup kv_g, int last_sliding, int last_full, int64_t n_main, + rad_weight tok_embd, rad_buf trunk_h, rad_buf trunk_logits) { + g = trunk; + rows = trunk.max_seqs > 0 ? trunk.max_seqs : 1; + g.max_tok = rows; + src = trunk_h; + logits = trunk_logits; + w_tok = tok_embd; + + /* ---- the head's own geometry, and what it must share with the trunk's. */ + n = hd_i(meta, "hidden_size", 0); + n_trunk = rad_meta_geti(meta, "draft.backbone_hidden_size", 0); + const long long n_l = hd_i(meta, "num_hidden_layers", 0); + const long long n_h = hd_i(meta, "num_attention_heads", 0); + const long long n_kv = hd_i(meta, "num_key_value_heads", 0); + const long long n_kv_g = hd_i(meta, "num_global_key_value_heads", n_kv); + const long long head_s = hd_i(meta, "head_dim", 0); + const long long head_g = hd_i(meta, "global_head_dim", head_s); + const long long ff = hd_i(meta, "intermediate_size", 0); + const long long win = hd_i(meta, "sliding_window", 0); + const long long vocab = hd_i(meta, "vocab_size", 0); + const long long ordered = rad_meta_geti(meta, "draft.use_ordered_embeddings", 0); + const double eps = hd_f(meta, "rms_norm_eps", 0.0); + const double theta_s = hd_f(meta, "rope_parameters.sliding_attention.rope_theta", 0.0); + const double theta_g = hd_f(meta, "rope_parameters.full_attention.rope_theta", 0.0); + double prf = hd_f(meta, "rope_parameters.full_attention.partial_rotary_factor", -1.0); + softcap = hd_f(meta, "final_logit_softcapping", 0.0); + if (!(prf > 0.0)) prf = 1.0; + + if (n <= 0 || n_l <= 0 || n_h <= 0 || ff <= 0 || !(eps > 0.0)) { + fprintf(stderr, "radiance: gemma4 assistant: the `draft.` config is incomplete (hidden %lld, " + "layers %lld, heads %lld, ffn %lld, eps %g)\n", + (long long)n, n_l, n_h, ff, eps); + return RAD_E_INVAL; + } + /* IT READS THE TRUNK'S CACHE, so everything the cache's shape depends on must agree: the two + * head widths, the two kv head counts and the window. A head that disagrees was trained beside + * another trunk, and its attention would read keys that are not the ones it learned against. */ + if (n_trunk != trunk.n_embd || vocab != trunk.n_vocab_all || head_s != cs.head_dim || + head_g != cg.head_dim || n_kv != cs.n_head_kv * trunk.world || + n_kv_g != cg.n_head_kv * trunk.world || win != cs.window) { + fprintf(stderr, "radiance: gemma4 assistant: this head was not made for this trunk -- it " + "states width %lld, vocabulary %lld, heads %lld/%lld x %lld/%lld kv over a " + "window of %lld; the trunk's cache is %lld/%lld kv heads of %lld/%lld over " + "%lld, at width %lld and vocabulary %lld\n", + (long long)n_trunk, vocab, n_kv, n_kv_g, head_s, head_g, win, + (long long)(cs.n_head_kv * trunk.world), (long long)(cg.n_head_kv * trunk.world), + (long long)cs.head_dim, (long long)cg.head_dim, (long long)cs.window, + (long long)trunk.n_embd, (long long)trunk.n_vocab_all); + return RAD_E_INVAL; + } + /* THE QUERIES MUST ROTATE AS THE TRUNK'S KEYS DID, or q.k measures the wrong distance. */ + const int64_t rot_g = (int64_t)(head_g * prf + 0.5); + if (theta_s != cs.theta || theta_g != cg.theta || rot_g != cg.n_rot) { + fprintf(stderr, "radiance: gemma4 assistant: its rotary (theta %g / %g, %lld of %lld global " + "dims) is not the trunk's (%g / %g, %lld): its queries would meet the " + "trunk's keys at the wrong angle\n", + theta_s, theta_g, (long long)rot_g, head_g, cs.theta, cg.theta, + (long long)cg.n_rot); + return RAD_E_INVAL; + } + /* CENTROID MASKING (use_ordered_embeddings) scores a top-k of vocabulary clusters instead of + * the whole head. The 31B's head does not use it, and nothing here implements it; refusing is + * better than a head that scores every token while its checkpoint expects a mask. */ + if (ordered) { + fprintf(stderr, "radiance: gemma4 assistant: use_ordered_embeddings (centroid-masked logits) " + "is not implemented\n"); + return RAD_E_UNSUPPORTED; + } + int64_t nh = 0; + if (divide_or_fail(n_h, trunk.world, "draft num_attention_heads", &nh) < 0) return RAD_E_INVAL; + if (divide_or_fail(ff, trunk.world, "draft intermediate_size", &n_ff) < 0) return RAD_E_INVAL; + if (nh % cs.n_head_kv || nh % cg.n_head_kv) { + fprintf(stderr, "radiance: gemma4 assistant: %lld query heads a rank do not group over %lld " + "sliding / %lld global kv heads\n", + (long long)nh, (long long)cs.n_head_kv, (long long)cg.n_head_kv); + return RAD_E_INVAL; + } + + /* The layer schedule: `layer_types` names every layer, as the trunk's does. */ + std::vector is_global; + { + const char* lt = rad_meta_gets(meta, "draft.text_config.layer_types", + rad_meta_gets(meta, "draft.layer_types", nullptr)); + if (!lt || !*lt || g4_parse_types(lt, n_l, is_global) < 0) { + fprintf(stderr, "radiance: gemma4 assistant: the `draft.` config's layer_types does not " + "name its %lld layers\n", n_l); + return RAD_E_INVAL; + } + } + + const int64_t base = n_main; /* the head's weight groups, past the trunk's layers */ + g.eps = (float)eps; + + /* ---- the rows. The two classes keep their own query and attention rows, as in the trunk. */ + ClassGeom hs = cs; hs.n_head = nh; + ClassGeom hgc = cg; hgc.n_head = nh; + b_c = decl_b(b, nm.f("mtp_c"), g.act_dtype, {rows, 2 * n_trunk}); + b_e = decl_b(b, nm.f("mtp_e"), g.act_dtype, {rows, n_trunk}); + b_x = decl_b(b, nm.f("mtp_x"), g.act_dtype, {rows, n}); + b_h = decl_b(b, nm.f("mtp_h"), g.act_dtype, {rows, n}); + b_gu = decl_b(b, nm.f("mtp_gu"), g.act_dtype, {rows, 2 * n_ff}); + b_ffn = decl_b(b, nm.f("mtp_ffn"), g.act_dtype, {rows, n_ff}); + b_hd = decl_b(b, nm.f("mtp_hd"), g.act_dtype, {rows, n}); + b_hn = decl_b(b, nm.f("mtp_hn"), g.act_dtype, {rows, n_trunk}); + const rad_buf q_s = decl_b(b, nm.f("mtp_qs"), g.act_dtype, {rows, hs.q_dim()}); + const rad_buf a_s = decl_b(b, nm.f("mtp_as"), g.act_dtype, {rows, hs.q_dim()}); + const rad_buf q_g = decl_b(b, nm.f("mtp_qg"), g.act_dtype, {rows, hgc.q_dim()}); + const rad_buf a_g = decl_b(b, nm.f("mtp_ag"), g.act_dtype, {rows, hgc.q_dim()}); + + /* ---- the entry: the trunk's hidden state into the right half of `c`, the trunk's scaled + * embedding into the left. A history pass gathers the hidden state from the trunk's rows; a + * round copies the head's own h' from the round before. Both write the half in place: a + * gather and a cast read their destination's row pitch off the operand. */ + op_hsrc = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n_trunk), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {src}, {b_c}); + op_hcopy = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n_trunk), + RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)), + RAD_NOWEIGHTS), + {b_hn}, {b_c}); + op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_embd", n_trunk), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off), + RAD_F64("mult", std::sqrt((double)n_trunk))), + RAD_WEIGHTS(w_tok)), + {}, {b_e}); + if (g.world > 1) + op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", n_trunk, rows * n_trunk), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {b_e}, {b_e}); + op_ecopy = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n_trunk), + RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)), + RAD_NOWEIGHTS), + {b_e}, {b_c}); + if (!op_hsrc || !op_hcopy || !op_embed || !op_ecopy) return RAD_E_INVAL; + + /* pre_projection: the joined row to the head's width. Replicated: it reads and writes the + * replicated stream. */ + RAD_ARCH_TRY(ln_pre.declare(b, nm, g, nm.f("mtp.pre_proj"), { nm.ckpt("draft.pre_projection.weight") }, + n, 2 * n_trunk, RAD_SHARD_NONE, grp_layer((int)(base + n_l)), + b_c, b_x)); + + /* ---- the layers. */ + layers.resize((size_t)n_l); + for (int64_t l = 0; l < n_l; ++l) { + HLayer& L = layers[(size_t)l]; + const int gl = (int)(base + l); + L.global = is_global[(size_t)l] == 1; + L.cls = L.global ? hgc : hs; + L.trunk_layer = L.global ? last_full : last_sliding; + L.kv = L.global ? kv_g : kv_s; + L.q = L.global ? q_g : q_s; + L.attn = L.global ? a_g : a_s; + if (L.trunk_layer < 0) { + fprintf(stderr, "radiance: gemma4 assistant: layer %lld reads a %s trunk layer and the " + "trunk has none\n", (long long)l, L.global ? "full" : "sliding"); + return RAD_E_INVAL; + } + const char* pre = "draft.model.layers"; + RAD_ARCH_TRY(map_copy(b, nm.f("mtp.blk.%lld.attn_norm.weight", (long long)l), + nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("mtp.blk.%lld.attn_q_norm.weight", (long long)l), + nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("mtp.blk.%lld.attn_post_norm.weight", (long long)l), + nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("mtp.blk.%lld.ffn_norm.weight", (long long)l), + nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("mtp.blk.%lld.ffn_post_norm.weight", (long long)l), + nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("mtp.blk.%lld.layer_scalar", (long long)l), + nm.ckpt("%s.%lld.layer_scalar", pre, (long long)l))); + L.w_norm = decl_w(b, nm.f("mtp.blk.%lld.attn_norm.weight", (long long)l), RAD_BF16, {n}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(gl)); + L.w_qn = decl_w(b, nm.f("mtp.blk.%lld.attn_q_norm.weight", (long long)l), RAD_BF16, + {L.cls.head_dim}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(gl)); + L.w_post = decl_w(b, nm.f("mtp.blk.%lld.attn_post_norm.weight", (long long)l), RAD_BF16, {n}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(gl)); + L.w_fnorm = decl_w(b, nm.f("mtp.blk.%lld.ffn_norm.weight", (long long)l), RAD_BF16, {n}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(gl)); + L.w_fpost = decl_w(b, nm.f("mtp.blk.%lld.ffn_post_norm.weight", (long long)l), RAD_BF16, {n}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(gl)); + L.w_scalar = decl_w(b, nm.f("mtp.blk.%lld.layer_scalar", (long long)l), RAD_BF16, {1}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(gl)); + + RAD_ARCH_TRY(L.ln_q.declare(b, nm, g, nm.f("mtp.blk.%lld.attn_q", (long long)l), + { nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l) }, + L.cls.q_dim(), n, RAD_SHARD_ROW, grp_layer(gl), b_h, L.q)); + RAD_ARCH_TRY(L.ln_o.declare(b, nm, g, nm.f("mtp.blk.%lld.attn_o", (long long)l), + { nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l) }, + n, L.cls.q_dim(), RAD_SHARD_COL, grp_layer(gl), L.attn, b_h)); + RAD_ARCH_TRY(L.ln_gu.declare(b, nm, g, nm.f("mtp.blk.%lld.ffn_gate_up", (long long)l), + { nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l), + nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l) }, + 2 * n_ff, n, RAD_SHARD_ROW, grp_layer(gl), b_h, b_gu, + { n_ff, n_ff })); + RAD_ARCH_TRY(L.ln_down.declare(b, nm, g, nm.f("mtp.blk.%lld.ffn_down", (long long)l), + { nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l) }, + n, n_ff, RAD_SHARD_COL, grp_layer(gl), b_ffn, b_h)); + + L.op_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(L.w_norm)), + {b_x}, {b_h}); + L.op_qn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows * L.cls.n_head), RAD_INT("n", L.cls.head_dim), + RAD_F64("eps", eps), RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(L.w_qn)), + {L.q}, {L.q}); + L.op_rq = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", L.cls.head_dim), + RAD_INT("n_head", L.cls.n_head), RAD_INT("n_head_kv", 0), + RAD_F64("theta", L.cls.theta), RAD_F64("scale", L.cls.scale), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", L.cls.n_rot), + RAD_STR("ladder", L.cls.head_ladder ? "head" : "rotary")), + RAD_NOWEIGHTS), + {L.q}, {L.q}); + /* ONE QUERY ROW A SEQUENCE over the trunk's cache, at scale 1 like the trunk's. The + * context is the committed positions (the core's doing: rad_drafter_shared_kv), so the + * decode band is the only band there is. */ + L.op_attn = rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, 1), RAD_INT("head_dim", L.cls.head_dim), + RAD_INT("gqa", L.cls.gqa()), RAD_INT("causal", 1), + RAD_INT("window", L.cls.window), RAD_INT("n_head", L.cls.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), RAD_INT("max_seqs", rows), + RAD_INT("max_ctx", g.max_ctx), RAD_F64("scale", 1.0), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {L.q}, {L.attn}); + if (g.world > 1) + L.op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", n, rows * n), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {b_h}, {b_h}); + L.op_post = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(L.w_post)), + {b_h}, {b_h}); + L.op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {b_x, b_h}, {b_x}); + L.op_fnorm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(L.w_fnorm)), + {b_x}, {b_h}); + L.op_act = rw(b, RAD_OP(b, "gelu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n_ff), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {b_gu}, {b_ffn}); + if (g.world > 1) + L.op_far = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", n, rows * n), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {b_h}, {b_h}); + L.op_fpost = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(L.w_fpost)), + {b_h}, {b_h}); + L.op_fadd = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {b_x, b_h}, {b_x}); + L.op_scale = rw(b, RAD_OP(b, "scale", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(L.w_scalar)), + {b_x}, {b_x}); + if (!L.op_norm || !L.op_qn || !L.op_rq || !L.op_attn || !L.op_post || !L.op_add || + !L.op_fnorm || !L.op_act || !L.op_fpost || !L.op_fadd || !L.op_scale || + (g.world > 1 && (!L.op_ar || !L.op_far))) + return RAD_E_INVAL; + } + + /* ---- the exit: the final norm, the head's own lm_head, and h' for the next round. */ + RAD_ARCH_TRY(map_copy(b, nm.f("mtp.output_norm.weight"), nm.ckpt("draft.model.norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("mtp.output.weight"), nm.ckpt("draft.model.embed_tokens.weight"))); + w_norm = decl_w(b, nm.f("mtp.output_norm.weight"), RAD_BF16, {n}, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer((int)(base + n_l))); + /* VOCAB-SHARDED, LIKE THE TRUNK'S: the draft's logits go through the same sampler chain, which + * merges the ranks' candidate sets, so a rank holds its own slice of the vocabulary. Declared + * at its codes' dtype: bf16 as Google ships it, or int8 / block fp8 where a recipe makes it so, + * and the logits_gemm kernel that reads that encoding serves it. It is the largest read of a + * round, and a draft is only a proposal: the trunk verifies every token with its own head. */ + w_lm = decl_w(b, nm.f("mtp.output.weight"), weight_codes_dtype(b, nm.f("mtp.output.weight"), RAD_BF16), + {g.n_vocab, n}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_layer((int)(base + n_l))); + op_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {b_x}, {b_hd}); + op_logits = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n_vocab", g.n_vocab), + RAD_INT("n_embd", n), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_lm)), + {b_hd}, {logits}); + if (softcap > 0.0) + op_cap = rw(b, RAD_OP(b, "logit_softcap", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_vocab), + RAD_F64("cap", softcap), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {logits}, {logits}); + if (!op_norm || !op_logits || (softcap > 0.0 && !op_cap)) return RAD_E_INVAL; + /* post_projection LAST: h' is the next round's input, and the op that reads it (op_hcopy) is + * the head's first. Declared here, its life runs the whole head, so no op of a pass can be laid + * over it before the round after has read it. */ + RAD_ARCH_TRY(ln_post.declare(b, nm, g, nm.f("mtp.post_proj"), { nm.ckpt("draft.post_projection.weight") }, + n_trunk, n, RAD_SHARD_NONE, grp_layer((int)(base + n_l)), + b_hd, b_hn)); + + rad_note(b, "the assistant head is declared: %lld layer(s) of width %lld at absolute %lld..%lld, " + "reading the trunk's cache at layer %d (sliding) and %d (full); no cache of its own, " + "every round at the committed position", + (long long)n_l, (long long)n, (long long)base, (long long)(base + n_l - 1), + last_sliding, last_full); + return RAD_OK; +} + +/* One pass. The batch is the one the scheduler staged for a head with no cache of its own: one row + * a drafting sequence, at the committed position, its context ending there. */ +void Gemma4Head::step(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (T <= 0) return; + if (batch->draft_pass < 0) { + /* Every row of the pass is a drafting row: that is what rad_drafter_shared_kv asked the + * scheduler for. Anything else is a batch built for a head with a cache of its own. */ + if (batch->n_draft_out != T || batch->n_out != T) { + rad_step_fail(c, "the gemma4 assistant head was handed a history pass that is not one row " + "a drafting sequence; it keeps no cache of its own and drafts from that " + "shape only (rad_drafter_shared_kv)"); + return; + } + RAD_ISSUE_N(c, op_hsrc, T, RAD_B(src), praw(batch->out_ids, RAD_I32, T), + bcol(b_c, n_trunk, n_trunk, T)); + } else { + RAD_ISSUE_N(c, op_hcopy, T, brows(b_hn, T), bcol(b_c, n_trunk, n_trunk, T)); + } + RAD_ISSUE(c, op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(b_e, T)); + if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * n_trunk, brows(b_e, T), RAD_NONE); + RAD_ISSUE_N(c, op_ecopy, T, brows(b_e, T), bcol(b_c, 0, n_trunk, T)); + ln_pre.step(c, b_c, b_x, T); + + for (const HLayer& L : layers) { + const RadKVGroupBatch* kvb = kv_batch(batch, L.kv); + RAD_ISSUE(c, L.op_norm, brows(b_x, T), RAD_W(L.w_norm), brows(b_h, T)); + L.ln_q.step(c, b_h, L.q, T); + RAD_ISSUE_N(c, L.op_qn, T * L.cls.n_head, brows(L.q, T), RAD_W(L.w_qn), brows(L.q, T)); + RAD_ISSUE(c, L.op_rq, brows(L.q, T), rope_posmc(g, batch, T)); + RAD_ISSUE_N(c, L.op_attn, batch->max_q_len, + brows(L.q, T), kv_cache(L.kv, L.trunk_layer), + praw2(kvb ? kvb->block_table : nullptr, RAD_I32, batch->n_seq, + kvb ? kvb->block_table_pitch : 0), + praw(kvb ? kvb->seqused : nullptr, RAD_I32, batch->n_seq), + RAD_NONE, RAD_NONE, + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), + brows(L.attn, T)); + L.ln_o.step(c, L.attn, b_h, T); + if (L.op_ar) RAD_ISSUE_N(c, L.op_ar, T * n, brows(b_h, T), RAD_NONE); + RAD_ISSUE_N(c, L.op_post, T, brows(b_h, T), RAD_W(L.w_post), brows(b_h, T)); + RAD_ISSUE(c, L.op_add, brows(b_x, T), brows(b_h, T), brows(b_x, T)); + + RAD_ISSUE(c, L.op_fnorm, brows(b_x, T), RAD_W(L.w_fnorm), brows(b_h, T)); + L.ln_gu.step(c, b_h, b_gu, T); + RAD_ISSUE(c, L.op_act, brows(b_gu, T), brows(b_ffn, T)); + L.ln_down.step(c, b_ffn, b_h, T); + if (L.op_far) RAD_ISSUE_N(c, L.op_far, T * n, brows(b_h, T), RAD_NONE); + RAD_ISSUE_N(c, L.op_fpost, T, brows(b_h, T), RAD_W(L.w_fpost), brows(b_h, T)); + RAD_ISSUE(c, L.op_fadd, brows(b_x, T), brows(b_h, T), brows(b_x, T)); + RAD_ISSUE(c, L.op_scale, brows(b_x, T), RAD_W(L.w_scalar), brows(b_x, T)); + } + + RAD_ISSUE(c, op_norm, brows(b_x, T), RAD_W(w_norm), brows(b_hd, T)); + RAD_ISSUE_N(c, op_logits, T, brows(b_hd, T), RAD_W(w_lm), brows(logits, T)); + if (op_cap) RAD_ISSUE_N(c, op_cap, T, brows(logits, T), brows(logits, T)); + ln_post.step(c, b_hd, b_hn, T); +} + +struct Layer { + bool global = false; + Gemma4Attn attn{}; + Gemma4Mlp mlp{}; + rad_weight w_scalar = 0; /* the per-layer [1] residual scalar, `cur = cur * scalar` */ + rad_op op_scale = 0; + /* the fused junctions (see THE RESIDUAL JUNCTIONS above): attention -> this layer's feed-forward, and this layer's + * feed-forward -> the next layer's attention, scalar included. The last layer has no j_ma: its + * stream goes to the final norm, which feeds the lm_head and not a quantiser. */ + G4Junction j_am{}, j_ma{}; +}; + +struct Model { + Names nm{""}; + Geom g{}; + ClassGeom cs{}; /* sliding class */ + ClassGeom cg{}; /* global class */ + int64_t n_main = 0; + + rad_kvgroup kv_s = 0, kv_g = 0; + + rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0; + rad_buf b_qs = 0, b_ks = 0, b_vs = 0, b_attns = 0; /* sliding rows */ + rad_buf b_qg = 0, b_kg = 0, b_vg = 0, b_atting = 0; /* global rows */ + rad_buf b_gu = 0, b_ffn = 0; + + rad_weight w_tok = 0, w_out = 0, w_lm = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_final = 0, op_gather = 0, op_logits = 0, op_cap = 0; + + std::vector layers; + + /* The assistant head, declared only when the container carries one and the deployment + * speculates (`max_spec` > 0). */ + Gemma4Head head{}; + bool have_head = false; + + /* The vision tower (gemma4_vision.h), declared when the container carries one and the + * deployment serves media; `op_mm` writes its rows over the placeholders' embeddings. */ + Vision vis{}; + rad_op op_mm = 0; + + G4Junction j0{}; /* the first block's entry: norm + quantiser of the embedding stream */ + bool fuse = false; + bool fuse_ar = false; /* every junction also carries the all-reduce in front of it */ +}; + +static Model g_model[MAX_RANKS]; + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + + if (meta->n_expert > 0) { + fprintf(stderr, "radiance: gemma4_bf16 refuses a checkpoint with %lld experts; that is not this arch\n", + (long long)meta->n_expert); + return RAD_E_UNSUPPORTED; + } + + Geom& g = m.g; + Names& nm = m.nm; + + /* ---- geometry RadModelMeta does not name. */ + const int64_t kv_g_all = g4_i(meta, "num_global_key_value_heads", 0); + const int64_t head_g = g4_i(meta, "global_head_dim", 0); + const int64_t sliding_win = g4_i(meta, "sliding_window", 0); + const int64_t kv_shared = g4_i(meta, "num_kv_shared_layers", 0); + const int64_t interval = g4_i(meta, "full_attention_interval", 0); + /* Whether the global layers read V from K: 31B's do (attention_k_eq_v), and then they have no + * v_proj. A checkpoint that does not say is refused rather than guessed at -- the wrong + * guess either asks for weights that are not there or ignores ones that are. */ + const long long k_eq_v = g4_i(meta, "attention_k_eq_v", -1); + if (k_eq_v != 0 && k_eq_v != 1) { + fprintf(stderr, "radiance: gemma4: the config does not say whether the global layers read " + "V from K (attention_k_eq_v)\n"); + return RAD_E_INVAL; + } + const double theta_s = g4_f(meta, "rope_parameters.sliding_attention.rope_theta", 0.0); + const double theta_g = g4_f(meta, "rope_parameters.full_attention.rope_theta", 0.0); + const double softcap = g4_f(meta, "final_logit_softcapping", 0.0); + double prf = g4_f(meta, "rope_parameters.full_attention.partial_rotary_factor", -1.0); + + if (head_g <= 0 || kv_g_all <= 0) { + fprintf(stderr, "radiance: gemma4: global_head_dim %lld / num_global_key_value_heads %lld; both required\n", + (long long)head_g, (long long)kv_g_all); + return RAD_E_INVAL; + } + if (head_g & 1) { fprintf(stderr, "radiance: gemma4: global head_dim %lld is odd\n", (long long)head_g); return RAD_E_INVAL; } + if (!(theta_s > 0.0) || !(theta_g > 0.0)) { + fprintf(stderr, "radiance: gemma4: both rope_parameters...rope_theta are required\n"); + return RAD_E_INVAL; + } + if (!(softcap > 0.0)) { fprintf(stderr, "radiance: gemma4: final_logit_softcapping is required\n"); return RAD_E_INVAL; } + if (kv_shared < 0) { fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld is negative\n", (long long)kv_shared); return RAD_E_INVAL; } + if (kv_shared > 0) { + fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld needs a shared-KV reuse path; refusing\n", + (long long)kv_shared); + return RAD_E_UNSUPPORTED; + } + if (sliding_win <= 0) { fprintf(stderr, "radiance: gemma4: sliding_window %lld is required\n", (long long)sliding_win); return RAD_E_INVAL; } + if (!(prf > 0.0)) prf = 1.0; + const int64_t n_rot_g = (int64_t)(head_g * prf + 0.5); + if (n_rot_g <= 0 || n_rot_g > head_g || (n_rot_g & 1)) { + fprintf(stderr, "radiance: gemma4: global rotary width %lld out of range for head_dim %lld\n", + (long long)n_rot_g, (long long)head_g); + return RAD_E_INVAL; + } + + int64_t kv_g = 0; + if (divide_or_fail(kv_g_all, g.world, "num_global_key_value_heads", &kv_g) < 0) return RAD_E_INVAL; + + /* Plain RMSNorm: x_hat * w, on every norm including the post-projection ones. Gemma 4 + * (unlike Gemma 2/3) does NOT use the (1 + w) form: the vLLM 0.27.1 oracle (which serves + * this checkpoint correctly) uses the stock RMSNorm (weight init 1.0), HF transformers' + * Gemma4RMSNorm multiplies by the weight with no +1 (weight init 1.0), and llama.cpp's + * gemma4 uses LLM_NORM_RMS with no load-time offset. wadd=0.0 = the plain form. */ + g.wadd = 0.0f; + g.wadd_qk = 0.0f; + const float final_wadd = 0.0f; + + m.n_main = g.n_layer; + std::vector is_global; + RAD_ARCH_TRY(g4_schedule(meta, g.n_layer, interval, is_global)); + int n_global = 0; + for (int v : is_global) n_global += v; + + /* the slider comes off geom_from (head_dim 256, 16 kv heads, full rotation, theta_s); the global + * class is built from the container head. */ + m.cs.n_head = g.n_head; m.cs.n_head_kv = g.n_head_kv; m.cs.head_dim = g.head_dim; + m.cs.n_rot = g.head_dim; m.cs.window = sliding_win; m.cs.theta = theta_s; + m.cs.scale = g.rope_scale; m.cs.head_ladder = false; m.cs.has_v = true; + m.cg.n_head = g.n_head; m.cg.n_head_kv = kv_g; m.cg.head_dim = head_g; + m.cg.n_rot = n_rot_g; m.cg.window = 0; m.cg.theta = theta_g; + m.cg.scale = g.rope_scale; m.cg.head_ladder = true; m.cg.has_v = k_eq_v == 0; + + /* ---- the two KV groups. */ + const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16); + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_WINDOW; sd.dtype = kvdt; sd.window = sliding_win; + sd.n_head_kv = g.n_head_kv; sd.head_dim = g.head_dim; + m.kv_s = rad_decl_kv_group(b, nm.f("kv_sliding"), &sd); + RadKVGroupDecl gd{}; + gd.kind = RAD_KV_FULL; gd.dtype = kvdt; gd.window = 0; + gd.n_head_kv = kv_g; gd.head_dim = head_g; + m.kv_g = rad_decl_kv_group(b, nm.f("kv_global"), &gd); + g.kv_dtype = rad_dtype_name(kvdt); + if (m.kv_s == 0 || m.kv_g == 0) { fprintf(stderr, "radiance: gemma4: a KV group failed to declare\n"); return RAD_E_INVAL; } + + /* ---- buffers. The two classes have different row widths, so they keep their own rows. */ + m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd}); + m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd}); + m.b_qs = decl_b(b, nm.f("attn_qs"), g.act_dtype, {g.max_tok, m.cs.q_dim()}); + m.b_ks = decl_b(b, nm.f("attn_ks"), g.act_dtype, {g.max_tok, m.cs.kv_dim()}); + m.b_vs = decl_b(b, nm.f("attn_vs"), g.act_dtype, {g.max_tok, m.cs.kv_dim()}); + m.b_attns = decl_b(b, nm.f("attn_outs"), g.act_dtype, {g.max_tok, m.cs.q_dim()}); + m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {g.max_tok, m.cg.q_dim()}); + m.b_kg = decl_b(b, nm.f("attn_kg"), g.act_dtype, {g.max_tok, m.cg.kv_dim()}); + m.b_vg = decl_b(b, nm.f("attn_vg"), g.act_dtype, {g.max_tok, m.cg.kv_dim()}); + m.b_atting= decl_b(b, nm.f("attn_outg"), g.act_dtype, {g.max_tok, m.cg.q_dim()}); + m.b_gu = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff}); + m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff}); + m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd}); + m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); + RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits)); + + /* ---- the vocabulary edges. Gemma 4 ties the head to the embedding. */ + const char* pre = "model.language_model.layers"; + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.language_model.embed_tokens.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.language_model.norm.weight"))); + RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"), nm.ckpt("model.language_model.embed_tokens.weight"))); + m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd}, + RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); + /* bf16, not f32: the model group is pinned to the mapped tier (token_embd's embed_lookup is + * host-only), so an f32-declared output_norm would widen and fail to serve from the mapping. */ + m.w_out = decl_w(b, nm.f("output_norm.weight"), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + /* DECLARED AT ITS CODES' DTYPE, as the assistant head's lm_head is: bf16 as the checkpoint ships + * it, or int8 / block fp8 where a recipe (`--quant output.weight=...`) makes it so, and the + * logits_gemm kernel for that encoding serves it. At a decode step it is the largest single read + * of the trunk (n_vocab x n_embd a rank), so its encoding is a direct share of the step. */ + m.w_lm = decl_w(b, nm.f("output.weight"), weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16), + {g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); + + /* The embedding is scaled by sqrt(n_embd) at the LOOKUP, not baked into the table (the + * reference's build_inp_embd and HF's ScaledWordEmbedding both do it there), and the + * checkpoint's table is plain -- so the scale rides the op and the table stays tied to the + * head's. Absent it, the residual stream carries a 73x-too-small token signal and the first + * layer's scale-invariant norm hides nothing downstream. */ + m.op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off), + RAD_F64("mult", std::sqrt((double)g.n_embd))), + RAD_WEIGHTS(m.w_tok)), + {}, {m.b_x}); + if (g.world > 1) + m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + /* An image's rows over its placeholders' embeddings, after the (all-reduced) lookup and + * before the first block reads the stream: the reference scales the token embeddings by + * sqrt(n_embd) and scatters the image features in unscaled. */ + if (Vision::present(meta) && ctx->max_enc_patches > 0) + m.op_mm = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + + /* ---- the layers. This loop is the model card. */ + Gemma4Attn::Wire sw{}; sw.x = m.b_x; sw.h = m.b_h; sw.q = m.b_qs; sw.k = m.b_ks; sw.v = m.b_vs; sw.attn = m.b_attns; + Gemma4Attn::Wire gw{}; gw.x = m.b_x; gw.h = m.b_h; gw.q = m.b_qg; gw.k = m.b_kg; gw.v = m.b_vg; gw.attn = m.b_atting; + Gemma4Mlp::Wire mw{}; mw.x = m.b_x; mw.h = m.b_h; mw.gu = m.b_gu; mw.ffn = m.b_ffn; + + m.layers.resize((size_t)m.n_main); + for (int64_t l = 0; l < m.n_main; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.global = (is_global[(size_t)l] == 1); + const ClassGeom& cgeo = lay.global ? m.cg : m.cs; + const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s; + const Gemma4Attn::Wire& aw = lay.global ? gw : sw; + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg)); + RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre)); + RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, pre)); + + /* the per-layer scalar: `cur = cur * scalar`, a [1] bf16 over the residual stream. */ + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.layer_scalar", (int)l), + nm.ckpt("%s.%lld.layer_scalar", pre, (long long)l))); + lay.w_scalar = decl_w(b, nm.f("blk.%d.layer_scalar", (int)l), RAD_BF16, {1}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer((int)l)); + lay.op_scale = rw(b, RAD_OP(b, "scale", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_scalar)), + {mw.x}, {mw.x}); + } + + /* ---- the junctions, declared once every layer exists (j_ma reads the next layer's gain). Used + * only when every one of them resolved and every linear a junction feeds reads its int8 pair: + * q, k and v (k and v through q's) and gate_up. A junction writes that pair and not the bf16 + * norm output, so a bf16 k or v beside an int8 q would read a stale buffer. Otherwise the + * blocks keep their own norms, quantisers, post-norms and adds. */ + if (m.n_main > 0) { + bool ok = true; + for (const Layer& lay : m.layers) + ok = ok && lay.attn.ln_q.quant && lay.attn.ln_k.shared_in && + (!lay.attn.cls.has_v || lay.attn.ln_v.shared_in) && lay.mlp.ln_gu.quant; + if (ok) { + RAD_ARCH_TRY(m.j0.declare(b, g, m.b_x, 0, m.layers[0].attn.w_norm, 0, 0, m.layers[0].attn.ln_q)); + ok = m.j0.op != 0; + for (int64_t l = 0; ok && l < m.n_main; ++l) { + Layer& lay = m.layers[(size_t)l]; + RAD_ARCH_TRY(lay.j_am.declare(b, g, m.b_h, m.b_x, lay.mlp.w_norm, lay.attn.w_post, 0, + lay.mlp.ln_gu)); + ok = lay.j_am.op != 0; + if (ok && l + 1 < m.n_main) { + const Layer& nx = m.layers[(size_t)l + 1]; + RAD_ARCH_TRY(lay.j_ma.declare(b, g, m.b_h, m.b_x, nx.attn.w_norm, lay.mlp.w_post, + lay.w_scalar, nx.attn.ln_q)); + ok = lay.j_ma.op != 0; + } + } + } + m.fuse = ok; + bool ar = ok && g.world == 2; + for (int64_t l = 0; ar && l < m.n_main; ++l) { + const Layer& lay = m.layers[(size_t)l]; + ar = lay.j_am.op_ar != 0 && (l + 1 >= m.n_main || lay.j_ma.op_ar != 0); + } + m.fuse_ar = ar; + } + + /* ---- the tail: final norm, the sampled rows, the lm_head, and the soft-cap. */ + m.op_final = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", final_wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_out)), + {m.b_x}, {m.b_h}); + m.op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_h}, {m.b_hout}); + m.op_logits = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n_vocab", g.n_vocab), + RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_lm)), + {m.b_hout}, {m.b_logits}); + m.op_cap = rw(b, RAD_OP(b, "logit_softcap", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_vocab), + RAD_F64("cap", softcap), RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {m.b_logits}, {m.b_logits}); + + /* ---- the assistant head, when the container carries one (`rad-convert --draft-model`) and + * the deployment speculates. A container converted without it, or a serve at max_spec 0, + * declares none of it: half a gigabyte of weights stays off the card. */ + if (ctx->max_spec > 0 && has_assistant(meta)) { + int last_s = -1, last_f = -1; + for (int64_t l = 0; l < m.n_main; ++l) (is_global[(size_t)l] ? last_f : last_s) = (int)l; + RAD_ARCH_TRY(m.head.declare(b, nm, meta, g, m.cs, m.cg, m.kv_s, m.kv_g, last_s, last_f, + m.n_main, m.w_tok, m.b_h, m.b_logits)); + m.have_head = true; + + /* WHAT THE ENGINE DRIVES. Serial: `max_spec` dependent passes, each embedding what the + * last one proposed, through the ordinary sampler chain (proposal 0) -- and a head with no + * cache of its own, so the core stages every pass at the committed position. */ + RadDrafterDecl dd{}; + dd.name = "mtp"; + dd.kind = RAD_DRAFT_SERIAL; + dd.depth = ctx->max_spec; + dd.proposal = 0; + dd.proposal_pitch = 1; + dd.mask_token = -1; + RAD_ARCH_TRY(rad_declare_drafter(b, &dd)); + RAD_ARCH_TRY(rad_drafter_shared_kv(b, kHeadPosOffset)); + } + + /* ---- the vision tower, its weight groups past the trunk's and the head's (whether or not + * this deployment declares the head, so the groups do not move with max_spec). */ + { + const int64_t head_groups = has_assistant(meta) ? hd_i(meta, "num_hidden_layers", 0) + 1 : 0; + RAD_ARCH_TRY(m.vis.declare(b, meta, ctx, nm, g.n_embd, (int)(m.n_main + head_groups))); + } + + rad_note(b, "rank %d/%d: %lld layers (%lld global, %lld sliding), sliding window %lld, " + "slider %lld heads x %lld, global %lld heads x %lld, soft-capped logits", + g.rank, g.world, (long long)g.n_layer, (long long)n_global, + (long long)(g.n_layer - n_global), (long long)sliding_win, + (long long)g.n_head, (long long)g.head_dim, (long long)g.n_head, (long long)head_g); + return RAD_OK; +} + +static void step(RadCtx* c, const RadBatch* batch) { + Model& m = g_model[rad_rank(c)]; + + /* AN ENCODER PASS RUNS THE TOWER AND NOTHING ELSE. */ + if (batch->enc) { + m.vis.step(c, batch); + return; + } + /* A DRAFT PASS RUNS THE HEAD AND NOTHING ELSE. The trunk already ran this step and left its + * final-normed hidden state in `h`, which the head's history pass gathers from. */ + if (batch->draft_pass != 0) { + if (!m.have_head) { + rad_step_fail(c, "the batch asks for a drafter pass and no drafter is declared: the " + "container carries no `draft.` assistant, or declare ran at max_spec 0"); + return; + } + m.head.step(c, batch); + return; + } + RAD_ISSUE(c, m.op_embed, + praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok), + brows(m.b_x, batch->n_tok)); + if (m.op_embed_ar) + RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd, + brows(m.b_x, batch->n_tok), RAD_NONE); + if (m.op_mm && batch->n_mm_rows > 0) + RAD_ISSUE_N(c, m.op_mm, batch->n_mm_rows, + praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, m.g.n_embd), + praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, batch->n_tok)); + + const int64_t T = batch->n_tok; + if (m.fuse) m.j0.step(c, T); + for (size_t li = 0; li < m.layers.size(); ++li) { + const Layer& l = m.layers[li]; + const bool last = li + 1 == m.layers.size(); + l.attn.step(c, batch, m.fuse, m.fuse, m.fuse_ar); + if (m.fuse) l.j_am.step(c, T, m.fuse_ar); + l.mlp.step(c, batch, m.fuse, m.fuse && !last, m.fuse_ar); + if (m.fuse && !last) { + /* [all-reduce,] post-norm, add, the layer scalar, the next block's norm and quantiser: one op */ + l.j_ma.step(c, T, m.fuse_ar); + continue; + } + /* the per-layer scalar: `cur = cur * scalar`, the [1] bf16 over the residual stream, + * applied at the end of each layer (after the mlp add) -- exactly the vLLM oracle's + * `hidden_states = hidden_states * self.layer_scalar`. The checkpoint's values (0.03-0.99, + * the vLLM text-only loader remaps `model.language_model.` -> `model.` and loads the + * buffer, gemma4.py:1419/1644) are the trained weights: they rescale the residual toward + * O(1) (the RMSNorms normalise magnitude but keep direction, so the input signal survives + * through the branch, not the identity path). */ + RAD_ISSUE(c, l.op_scale, brows(m.b_x, batch->n_tok), RAD_W(l.w_scalar), + brows(m.b_x, batch->n_tok)); + } + + RAD_ISSUE(c, m.op_final, + brows(m.b_x, batch->n_tok), RAD_W(m.w_out), brows(m.b_h, batch->n_tok)); + + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.op_gather, batch->n_out, + brows(m.b_h, batch->n_tok), + praw(batch->out_ids, RAD_I32, batch->n_out), + brows(m.b_hout, batch->n_out)); + RAD_ISSUE_N(c, m.op_logits, batch->n_out, + brows(m.b_hout, batch->n_out), RAD_W(m.w_lm), + brows(m.b_logits, batch->n_out)); + RAD_ISSUE_N(c, m.op_cap, batch->n_out, + brows(m.b_logits, batch->n_out), + brows(m.b_logits, batch->n_out)); + } +} + +/* The reply format: gemma4_chat_format.h. */ +const RadChatFormat* chat_format(const RadModelMeta*) { return chat_format_decl(); } + +/* WHAT THIS CONTAINER'S HEAD IS WORTH SPECULATING TO, for `--num-speculative-tokens auto`. A serial + * head names an operating point, not a trained depth: one more round is one more pass of the head, + * and every depth still runs. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + if (has_assistant(meta)) { + out->draft_depth = kHeadDepth; + out->draft_depth_fixed = 0; + } + /* The tower's pooling window, so a pass size the core picks itself is whole windows. */ + if (Vision::present(meta)) { + const int64_t k = rad_meta_geti(meta, "vision_config.pooling_kernel_size", 0); + if (k > 0) out->enc_merge = k * k; + } + return RAD_OK; +} + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0", + "Gemma 4 dense (text and images), w4a8 from its bf16 or its CT-INT4 (QAT) release: " + "sliding-window and proportional-RoPE global attention over a GemmaRMSNorm stream " + "with GELU feed-forward, per-layer scalar scaling and soft-capped logits") +RAD_ARCH_CHAT_FORMAT(gemma4_bf16) +RAD_ARCH_PROBE(gemma4_bf16) +#endif + +} /* namespace gemma4_bf16 */ diff --git a/arch/gemma4_bf16/gemma4_chat_format.h b/arch/gemma4_bf16/gemma4_chat_format.h new file mode 100644 index 00000000..7520d298 --- /dev/null +++ b/arch/gemma4_bf16/gemma4_chat_format.h @@ -0,0 +1,60 @@ +/* gemma4_chat_format.h -- how Gemma 4 spells a turn: its reasoning and its tool calls, as data. + * + * The chat template is one llama.cpp reads with a hand-written handler, so the template analysis + * finds nothing in it, and the engine would serve the model with no reasoning split and refuse + * every request that sends tools. The model's own tokenizer_config.json states the format instead + * (`response_template`), and this is that statement in the engine's terms: + * + * thinking <|channel>thought\n ... + * tool calls <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3,flag:true}, repeated + * the object unquoted keys, strings between <|"|> and <|"|> with their text verbatim, every + * other value as JSON writes it + * the turn ends at ; after its calls the model writes <|tool_response> and stops + * (generation_config.json names it beside and ) + * + * llama.cpp's handler records two habits of the model beyond that: an extra thought channel after + * the answer, and a lone . `reasoning_anywhere` reads the first as reasoning and drops + * the second, so neither reaches the content. + * + * Kept in a header of its own so the reply-format tests read the declaration the plugin exports + * rather than a copy of it. */ +#pragma once +#include "rad_builder.h" + +namespace gemma4_bf16 { + +inline const RadChatFormat* chat_format_decl() { + static const char* const kBreaks[] = { "<|tool_call>" }; + static const char* const kTriggers[] = { "<|tool_call>" }; + static const RadChatFormat f = [] { + RadChatFormat c{}; + c.struct_size = (uint32_t)sizeof(RadChatFormat); + c.name = "plugin:gemma4"; + c.reasoning_open = "<|channel>thought\n"; + c.reasoning_close = ""; + /* A call that starts inside an unclosed thought ends it there. */ + c.reasoning_breaks = kBreaks; + c.n_reasoning_breaks = 1; + /* Thinking off, the template closes an empty channel in the generation prompt; on, the + * model opens its own -- or, after a tool response, the prompt has opened it. */ + c.reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT; + c.reasoning_anywhere = 1; + + c.call_open = "<|tool_call>"; + c.call_close = ""; + c.name_prefix = "call:"; + c.name_suffix = ""; /* the name ends at the object's `{` */ + c.call_end = ""; /* and the object's `}` ends the call */ + c.args_form = RAD_CHAT_ARGS_OBJECT; + c.object_string_open = "<|\"|>"; + c.object_string_close = "<|\"|>"; + c.object_bare_keys = 1; + + c.triggers = kTriggers; + c.n_triggers = 1; + return c; + }(); + return &f; +} + +} /* namespace gemma4_bf16 */ diff --git a/arch/gemma4_bf16/gemma4_vision.h b/arch/gemma4_bf16/gemma4_vision.h new file mode 100644 index 00000000..5dd0b122 --- /dev/null +++ b/arch/gemma4_bf16/gemma4_vision.h @@ -0,0 +1,321 @@ +/* gemma4_vision.h -- the vision tower of Gemma 4's large dense models (31B), for gemma4_bf16. + * + * The same tower family embgemma2 serves (transformers' Gemma4VisionModel), at the 31B's size and + * with the two parts that model leaves out: + * + * a patch is 16 x 16 x 3, staged by the core's Gemma 4 processor as 2 * (u / 255) - 1 in bf16, + * (y, x, channel); patch embedding a [width, 768] linear plus a learned row for the patch's + * column and one for its row ([2, 10240, width] table) + * 27 layers of width 1152: sandwich norms (gain w, not 1 + w), q/k RMS-normed with a gain and v + * without one, a 2-D rotary over two 36-channel neox blocks a 72-wide head -- x (the column) + * over the first, y over the second, each block at theta^(-j / 18) (rope_type "default"; the + * embedding model spells the same rotary "axial") -- bidirectional attention within an image at + * scale 1, a gated gelu-tanh MLP + * pooling: the mean of each 3 x 3 window times sqrt(width) (the processor lays a window's nine + * patches out consecutively, raster order of windows, as the reference's position pooling) + * STANDARDISATION (vision_config.standardize): (z - std_bias) * std_scale per channel. The + * reference does it in f32 because a few channels carry ~5e4 with a bias that cancels them; + * here z is the pooler's bf16 row, so those channels keep bf16's spacing at their magnitude + * (about 1e-2 after the scale -- measured against the reference, see vision.md). The bias row + * is made on the card: fill(-1) times std_bias, added to z; then times std_scale. + * the multimodal embedder: an RMS norm with no gain and a width -> n_embd linear. Its rows + * replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the + * image rows are not scaled). + * + * Every rank runs the whole tower (engine_mm.cpp), so its weights are replicated (RAD_SHARD_NONE) + * and each rank writes the rows into its own copy of the embedding stream. */ +#pragma once + +namespace gemma4_bf16 { + +using namespace rad::arch; + +struct Vision { + struct Layer { + rad_weight in_norm = 0, qkv = 0, q_norm = 0, k_norm = 0, o = 0, post_attn = 0; + rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0; + rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0; + rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0; + }; + bool on = false, standardize = false; + int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0; + int64_t npos = 0, n_embd = 0; + rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0; + rad_op op_patch = 0, op_px = 0, op_py = 0, op_padd = 0, op_add = 0, op_pool = 0, op_norm = 0; + rad_op op_out = 0, op_sfill = 0, op_sbias = 0, op_sadd = 0, op_sscale = 0; + rad_buf b_x = 0, b_h = 0, b_o = 0, b_qkv = 0, b_att = 0, b_gu = 0, b_ff = 0, b_px = 0, + b_py = 0, b_pool = 0, b_sb = 0, b_pn = 0, b_out = 0; + std::vector L; + + static bool present(const RadModelMeta* m) { + const char* t = rad_meta_gets(m, "vision_config.model_type", ""); + return t && !std::strcmp(t, "gemma4_vision"); + } + + int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm, + int64_t model_embd, int first_group) { + on = false; + if (!present(m) || ctx->max_enc_patches <= 0) return RAD_OK; + width = rad_meta_geti(m, "vision_config.hidden_size", 0); + heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0); + hd = rad_meta_geti(m, "vision_config.head_dim", 0); + ff = rad_meta_geti(m, "vision_config.intermediate_size", 0); + pool = rad_meta_geti(m, "vision_config.pooling_kernel_size", 0); + npos = rad_meta_geti(m, "vision_config.position_embedding_size", 0); + const int64_t depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0); + const int64_t patch = rad_meta_geti(m, "vision_config.patch_size", 0); + const int64_t kvh = rad_meta_geti(m, "vision_config.num_key_value_heads", heads); + const double eps = rad_meta_getf(m, "vision_config.rms_norm_eps", 1e-6); + const double theta = rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 0.0); + const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", ""); + const char* act = rad_meta_gets(m, "vision_config.hidden_activation", ""); + standardize = rad_meta_geti(m, "vision_config.standardize", 0) != 0; + if (width <= 0 || heads <= 0 || hd <= 0 || ff <= 0 || pool <= 0 || npos <= 0 || + depth <= 0 || patch <= 0 || !(theta > 0) || heads * hd != width || kvh != heads || + hd % 4) { + fprintf(stderr, "radiance: gemma4_bf16: the container's vision_config is incomplete or " + "not the shape this plugin serves (hidden %lld, heads %lld x %lld, kv " + "%lld, ff %lld, pooling %lld, layers %lld)\n", (long long)width, + (long long)heads, (long long)hd, (long long)kvh, (long long)ff, + (long long)pool, (long long)depth); + return RAD_E_INVAL; + } + if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) || + (std::strcmp(rt, "default") && std::strcmp(rt, "axial")) || + std::strcmp(act, "gelu_pytorch_tanh")) { + fprintf(stderr, "radiance: gemma4_bf16: this vision tower uses clipped linears, a '%s' " + "rotary or a '%s' activation, which this plugin does not serve\n", + rt, act); + return RAD_E_UNSUPPORTED; + } + n_embd = model_embd; + patch_dim = 3 * patch * patch; + const int64_t kk = pool * pool; + P = ctx->max_enc_patches; + if (P % kk) P -= P % kk; + R = P / kk; + const int A = RAD_ACCESS_PER_REQUEST, N = RAD_SHARD_NONE; + const char* V = "model.vision_tower"; + + RAD_ARCH_TRY(map_copy(b, nm.f("v.patch.weight"), nm.ckpt("%s.patch_embedder.input_proj.weight", V))); + RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_x.weight"), + nm.ckpt("%s.patch_embedder.position_embedding_table", V), 0)); + RAD_ARCH_TRY(map_slice(b, nm.f("v.pos_y.weight"), + nm.ckpt("%s.patch_embedder.position_embedding_table", V), 1)); + RAD_ARCH_TRY(map_copy(b, nm.f("v.embed.weight"), nm.ckpt("model.embed_vision.embedding_projection.weight"))); + w_in = decl_w(b, nm.f("v.patch.weight"), RAD_BF16, {width, patch_dim}, A, N, grp_model()); + w_px = decl_w(b, nm.f("v.pos_x.weight"), RAD_BF16, {npos, width}, A, N, grp_model()); + w_py = decl_w(b, nm.f("v.pos_y.weight"), RAD_BF16, {npos, width}, A, N, grp_model()); + w_proj = decl_w(b, nm.f("v.embed.weight"), RAD_BF16, {n_embd, width}, A, N, grp_model()); + if (standardize) { + RAD_ARCH_TRY(map_copy(b, nm.f("v.std_bias"), nm.ckpt("%s.std_bias", V))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.std_scale"), nm.ckpt("%s.std_scale", V))); + w_sbias = decl_w(b, nm.f("v.std_bias"), RAD_BF16, {width}, A, N, grp_model()); + w_sscale = decl_w(b, nm.f("v.std_scale"), RAD_BF16, {width}, A, N, grp_model()); + } + L.assign((size_t)depth, Layer{}); + for (int64_t i = 0; i < depth; ++i) { + Layer& l = L[(size_t)i]; + const long long li = (long long)i; + const RadWeightGroup g = grp_layer(first_group + (int)i); + auto src = [&](const char* s) { return nm.ckpt("%s.encoder.layers.%lld.%s", V, li, s); }; + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.in_norm", li), src("input_layernorm.weight"))); + RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.qkv", li), + {src("self_attn.q_proj.linear.weight"), + src("self_attn.k_proj.linear.weight"), + src("self_attn.v_proj.linear.weight")})); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.q_norm", li), src("self_attn.q_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.k_norm", li), src("self_attn.k_norm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.o", li), src("self_attn.o_proj.linear.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_attn", li), src("post_attention_layernorm.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.pre_ff", li), src("pre_feedforward_layernorm.weight"))); + RAD_ARCH_TRY(map_concat(b, nm.f("v.blk.%lld.gate_up", li), + {src("mlp.gate_proj.linear.weight"), + src("mlp.up_proj.linear.weight")})); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.down", li), src("mlp.down_proj.linear.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("v.blk.%lld.post_ff", li), src("post_feedforward_layernorm.weight"))); + l.in_norm = decl_w(b, nm.f("v.blk.%lld.in_norm", li), RAD_BF16, {width}, A, N, g); + l.qkv = decl_w(b, nm.f("v.blk.%lld.qkv", li), RAD_BF16, {3 * width, width}, A, N, g); + l.q_norm = decl_w(b, nm.f("v.blk.%lld.q_norm", li), RAD_BF16, {hd}, A, N, g); + l.k_norm = decl_w(b, nm.f("v.blk.%lld.k_norm", li), RAD_BF16, {hd}, A, N, g); + l.o = decl_w(b, nm.f("v.blk.%lld.o", li), RAD_BF16, {width, width}, A, N, g); + l.post_attn = decl_w(b, nm.f("v.blk.%lld.post_attn", li), RAD_BF16, {width}, A, N, g); + l.pre_ff = decl_w(b, nm.f("v.blk.%lld.pre_ff", li), RAD_BF16, {width}, A, N, g); + l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g); + l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g); + l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g); + } + + b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width}); + b_h = decl_b(b, nm.f("v.h"), RAD_BF16, {P, width}); + b_o = decl_b(b, nm.f("v.o"), RAD_BF16, {P, width}); + b_qkv = decl_b(b, nm.f("v.qkv"), RAD_BF16, {P, 3 * width}); + b_att = decl_b(b, nm.f("v.att"), RAD_BF16, {P, width}); + b_gu = decl_b(b, nm.f("v.gu"), RAD_BF16, {P, 2 * ff}); + b_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, {P, ff}); + b_px = decl_b(b, nm.f("v.px"), RAD_BF16, {P, width}); + b_py = decl_b(b, nm.f("v.py"), RAD_BF16, {P, width}); + b_pool = decl_b(b, nm.f("v.pool"), RAD_BF16, {R, width}); + b_sb = decl_b(b, nm.f("v.sb"), RAD_BF16, {R, width}); + b_pn = decl_b(b, nm.f("v.pn"), RAD_BF16, {R, width}); + b_out = decl_b(b, nm.f("v.out"), RAD_BF16, {R, n_embd}); + + auto rms = [&](int64_t rows, rad_weight w) { + if (!w) + return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_F64("eps", eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + return RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_F64("eps", eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto gemm = [&](int64_t rows, int64_t Nn, int64_t K, rad_weight w) { + return RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", Nn), + RAD_INT("K", K), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto add = [&](int64_t rows) { + return RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", width), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + }; + auto lookup = [&](rad_weight w) { + return RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n_embd", width), + RAD_INT("n_vocab", npos), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)), + RAD_WEIGHTS(w)); + }; + auto gain = [&](rad_weight w) { + return RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width), + RAD_STR("dtype", "bf16"), RAD_INT("scalar", 0)), + RAD_WEIGHTS(w)); + }; + op_patch = rw(b, gemm(P, width, patch_dim, w_in), {}, {b_x}); + op_px = rw(b, lookup(w_px), {}, {b_px}); + op_py = rw(b, lookup(w_py), {}, {b_py}); + op_padd = rw(b, add(P), {b_px, b_py}, {b_px}); + op_add = rw(b, add(P), {b_x, b_px}, {b_x}); + /* Two neox blocks of hd / 4 pairs, x (staged plane 1, the column) then y (plane 0). */ + char sec[48]; + std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4)); + for (Layer& l : L) { + l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h}); + l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv}); + l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads), + RAD_F64("theta", theta), RAD_F64("eps", eps), + RAD_STR("mode", "blocks"), RAD_INT("v_norm", 1), + RAD_STR("sections", sec), RAD_STR("comps", "1 0")), + RAD_WEIGHTS(l.q_norm, l.k_norm)), + {b_qkv}, {b_qkv}); + l.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", hd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), RAD_F64("scale", 1.0), + RAD_INT("max_seqlen", P), RAD_INT("window", 0)), + RAD_NOWEIGHTS), + {b_qkv}, {b_att}); + l.op_o = rw(b, gemm(P, width, width, l.o), {b_att}, {b_o}); + l.op_pa = rw(b, rms(P, l.post_attn), {b_o}, {b_o}); + l.op_add1 = rw(b, add(P), {b_x, b_o}, {b_x}); + l.op_pf = rw(b, rms(P, l.pre_ff), {b_x}, {b_h}); + l.op_gu = rw(b, gemm(P, 2 * ff, width, l.gate_up), {b_h}, {b_gu}); + l.op_act = rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", ff), + RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_gu}, {b_ff}); + l.op_down = rw(b, gemm(P, width, ff, l.down), {b_ff}, {b_o}); + l.op_pff = rw(b, rms(P, l.post_ff), {b_o}, {b_o}); + l.op_add2 = rw(b, add(P), {b_x, b_o}, {b_x}); + } + op_pool = rw(b, RAD_OP(b, "pool_rows", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), + RAD_INT("k", kk), RAD_F64("mult", std::sqrt((double)width)), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_x}, {b_pool}); + if (standardize) { + op_sfill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width), + RAD_STR("dtype", "bf16"), RAD_F64("value", -1.0)), + RAD_NOWEIGHTS), + {}, {b_sb}); + op_sbias = rw(b, gain(w_sbias), {b_sb}, {b_sb}); + op_sadd = rw(b, add(R), {b_pool, b_sb}, {b_pool}); + op_sscale = rw(b, gain(w_sscale), {b_pool}, {b_pool}); + } + op_norm = rw(b, rms(R, 0), {b_pool}, {b_pn}); + op_out = rw(b, gemm(R, n_embd, width, w_proj), {b_pn}, {b_out}); + + RadEncoderDecl e{}; + e.name = "vision"; + e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO; + e.patch_dim = patch_dim; + e.merge = kk; + e.max_patches = P; + e.n_embd = n_embd; + e.out = b_out; + RAD_ARCH_TRY(rad_declare_encoder(b, &e)); + rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, " + "pooled %lldx%lld%s; %lld patches a pass -> %lld rows of %lld", + (long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff, + (long long)patch, (long long)pool, (long long)pool, + standardize ? ", standardised" : "", (long long)P, (long long)R, + (long long)n_embd); + on = true; + return RAD_OK; + } + + void step(RadCtx* c, const RadBatch* batch) const { + const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg, kk = pool * pool; + if (!on || Pn <= 0 || Pn > P || Pn % kk || S <= 0) { + rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, " + "more patches than it was declared for, or not whole pooling windows"); + return; + } + const int64_t Rn = Pn / kk; + const int32_t* crd = batch->enc_coord; + const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim); + const RadOperand rc = praw2(crd, RAD_I32, 2, Pn); + const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1); + + RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_in), brows(b_x, Pn)); + RAD_ISSUE_N(c, op_px, Pn, praw(crd + Pn, RAD_I32, Pn), RAD_W(w_px), brows(b_px, Pn)); + RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn)); + RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn)); + RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn)); + for (const Layer& l : L) { + RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn)); + RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn)); + RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm)); + RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn), + bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn)); + RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn)); + RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn)); + RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn)); + RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn)); + RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn)); + RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn), + brows(b_ff, Pn)); + RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn)); + RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn)); + RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn)); + } + RAD_ISSUE_N(c, op_pool, Pn, brows(b_x, Pn), brows(b_pool, Rn)); + if (standardize) { + RAD_ISSUE_N(c, op_sfill, Rn, brows(b_sb, Rn)); + RAD_ISSUE_N(c, op_sbias, Rn, brows(b_sb, Rn), RAD_W(w_sbias), brows(b_sb, Rn)); + RAD_ISSUE_N(c, op_sadd, Rn, brows(b_pool, Rn), brows(b_sb, Rn), brows(b_pool, Rn)); + RAD_ISSUE_N(c, op_sscale, Rn, brows(b_pool, Rn), RAD_W(w_sscale), brows(b_pool, Rn)); + } + RAD_ISSUE_N(c, op_norm, Rn, brows(b_pool, Rn), RAD_NONE, brows(b_pn, Rn)); + RAD_ISSUE_N(c, op_out, Rn, brows(b_pn, Rn), RAD_W(w_proj), brows(b_out, Rn)); + } +}; + +} /* namespace gemma4_bf16 */ diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 6504fc57..2dd5e6e0 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -134,6 +134,7 @@ public: int declare_logits(rad_buf b); int declare_pooled(rad_buf b); int declare_drafter(const RadDrafterDecl* d); + int drafter_shared_kv(int pos_offset); int declare_encoder(const RadEncoderDecl* d); void note_v (const char* f, va_list ap); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 09c76aca..6e04d262 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1272,6 +1272,32 @@ int Builder::declare_drafter(const RadDrafterDecl* d) { return RAD_OK; } +/* A SERIAL HEAD THAT READS THE TRUNK'S CACHE AND KEEPS NONE (rad_builder.h). Checked here for the + * reason declare_drafter checks everything: the driver only reaches the head once a request + * speculates, and a head staged the wrong way round costs acceptance and says nothing. */ +int Builder::drafter_shared_kv(int pos_offset) { + if (finished_) { + err(RAD_E_STATE, "drafter_shared_kv after declare finished"); + return RAD_E_STATE; + } + if (prog_.drafter.kind != RAD_DRAFT_SERIAL) { + err(RAD_E_STATE, "drafter_shared_kv: %s. Only a SERIAL head runs round after round at one " + "position; declare it with rad_declare_drafter first.", + prog_.drafter.kind == RAD_DRAFT_NONE ? "no drafter is declared" + : "the declared drafter is a BLOCK drafter"); + return RAD_E_STATE; + } + if (pos_offset != 0 && pos_offset != 1) { + err(RAD_E_INVAL, "drafter_shared_kv '%s': pos_offset %d. The rows sit at the committed " + "position (0) or one past it (1); nothing else names a position the head " + "was trained at.", prog_.drafter_name.c_str(), pos_offset); + return RAD_E_INVAL; + } + prog_.drafter_shared_kv = true; + prog_.drafter_pos_offset = pos_offset; + return RAD_OK; +} + void Builder::note_v(const char* f, va_list ap) { char msg[1024]; vsnprintf(msg, sizeof msg, f ? f : "", ap); @@ -1522,6 +1548,8 @@ void Builder::finish_kv_groups() { default: break; } std::sort(gi.layers.begin(), gi.layers.end()); + gi.drafter = prog_.meta.n_layers > 0 && !gi.layers.empty() && + gi.layers.front() >= prog_.meta.n_layers; /* A group nothing is bound to is a group the block manager cannot size: how many state * instances a sequence owns is the layer count, and assuming one would make the page size @@ -1628,6 +1656,19 @@ int Builder::finish() { finish_weight_uses(); finish_layouts(); finish_kv_groups(); + /* A HEAD DECLARED TO KEEP NO CACHE OF ITS OWN (rad_drafter_shared_kv) is given no history pass: + * the scheduler owes it none. A KV group bound at one of its layers -- meta.n_layers and above + * are the drafter's -- would then be read without anything ever having written it. */ + if (prog_.drafter_shared_kv) + for (size_t g = 1; g < prog_.kv_groups.size(); ++g) + for (int l : prog_.kv_groups[g].layers) + if (l >= prog_.meta.n_layers) { + err(RAD_E_STATE, "drafter '%s' keeps no cache of its own (rad_drafter_shared_kv) " + "and its layer %d is bound to KV group '%s', which no pass " + "would ever write", prog_.drafter_name.c_str(), l, + prog_.kv_groups[g].name.c_str()); + break; + } finish_buffer_liveness(); int s = plan_buffers(prog_, &bufrep_); @@ -1762,6 +1803,11 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { return B(b)->declare_drafter(d); } +int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) { + if (!b) return RAD_E_INVAL; + return B(b)->drafter_shared_kv(pos_offset); +} + int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { if (!b) return RAD_E_INVAL; return B(b)->declare_encoder(d); diff --git a/core/build/rad_graph.cpp b/core/build/rad_graph.cpp index a595918b..5da19486 100644 --- a/core/build/rad_graph.cpp +++ b/core/build/rad_graph.cpp @@ -289,6 +289,10 @@ std::string dump_graph_str(const Program& p, const std::vector* err "%d, drafter window %lld\n", (long long)p.drafter.block, p.drafter.depth, (int)p.drafter.mask_token, (long long)p.drafter.window); + if (p.drafter_shared_kv) + s += fmt(" cache none of its own: it reads the trunk's, owes no history, and " + "every round runs at the committed position%s\n", + p.drafter_pos_offset ? " (rotated one past it)" : ""); s += "\n"; } diff --git a/core/config.cpp b/core/config.cpp index b7051fa4..71347377 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -85,7 +85,8 @@ static const Flag g_flags[] = { { "--prefix-cache-host-mib", "N", "copy finished conversations' KV to host memory, up to N MiB,\n" " so their VRAM can go to experts and a return restores\n" " instead of re-prefilling. 0 is off. Part of it holds\n" - " linear-state snapshots on a hybrid model; startup says how many" }, + " snapshots on a hybrid or sliding-window model;\n" + " startup says how many" }, { "--prefix-cache-dir", "DIR", "where the disk tier keeps them. Not --weights-disk-tier, which is\n" " about WEIGHTS" }, { "--prefix-cache-disk-mib", "N", "and copy them on to disk under --prefix-cache-dir, up to N MiB,\n" @@ -104,7 +105,8 @@ static const Flag g_flags[] = { * 2 for the whole server rather than 2 x --max-num-seqs. At the default 8 slots and * 8 sequences that is one snapshot a sequence, which is what an append-only chat wants -- * the next turn's hit lands at the end of the last one. */ - { "--checkpoint-slots", "N", "linear-state snapshots retained IN TOTAL (not " + { "--checkpoint-slots", "N", "linear-state or sliding-window snapshots " + "retained IN TOTAL (not " "per sequence), in pinned host memory; compare " "against --max-num-seqs" }, { "--no-prefix-cache", nullptr, "disable prefix caching" }, diff --git a/core/engine.cpp b/core/engine.cpp index 45a91d0a..1dd5a67a 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -704,13 +704,21 @@ int Engine::step_loop() { for (const StepEntry& e : plan.e) { if (e.ckpt_restore < 0) continue; if (!state_slots_of(e.seq, &ckpt_slots_)) continue; + /* The window behind the hit, in the blocks admit_one seeded at its floor. */ + if (ranks_[0]->kv.has_window_snapshot() && + !ranks_[0]->kv.window_rows(e.seq, e.ctx_len, &ckpt_win_)) { + RAD_ERR("sequence %llu: no window rows at %d to restore into", + (unsigned long long)e.seq, (int)e.ctx_len); + return RAD_E_STATE; + } for (size_t ri = 0; ri < ranks_.size(); ++ri) { auto& rk = ranks_[ri]; /* This rank's device, for its own stream and its own state slots. */ if (ranks_.size() > 1) (void)rad_dev_set(rk->device); const int s = rk->kv.checkpoint_restore(ckpt_slots_.data(), (int)ckpt_slots_.size(), - e.ckpt_restore, rk->ctx.stream()); + e.ckpt_restore, rk->ctx.stream(), + &ckpt_win_); if (s < 0) { RAD_ERR("could not restore sequence %llu from checkpoint slot %d on " "rank %d: %s", (unsigned long long)e.seq, @@ -809,11 +817,23 @@ int Engine::step_loop() { for (const StepEntry& e : plan.e) { if (e.ckpt_slot < 0 || e.ckpt_tok < 0) continue; if (!state_slots_of(e.seq, &ckpt_slots_)) continue; + /* The window behind the checkpoint position. The chunk that ends there + * still holds it (its ensure kept the window behind the chunk's first + * query), so a miss is a broken invariant -- and skipping would leave the + * cache a slot it commits as valid with somebody else's pages in it. */ + if (ranks_[0]->kv.has_window_snapshot() && + !ranks_[0]->kv.window_rows(e.seq, e.ctx_len + e.ckpt_tok + 1, + &ckpt_win_)) { + RAD_ERR("sequence %llu: the window behind checkpoint %d is not held", + (unsigned long long)e.seq, (int)(e.ctx_len + e.ckpt_tok + 1)); + return RAD_E_STATE; + } for (auto& rk : ranks_) { if (ranks_.size() > 1) (void)rad_dev_set(rk->device); const int s = rk->kv.checkpoint_save(ckpt_slots_.data(), (int)ckpt_slots_.size(), - e.ckpt_slot, rk->ctx.stream()); + e.ckpt_slot, rk->ctx.stream(), + &ckpt_win_); if (s < 0) { RAD_ERR("rank %d could not snapshot sequence %llu into checkpoint slot " "%d: %s", rk->index, (unsigned long long)e.seq, @@ -1924,7 +1944,8 @@ bool Engine::state_slots_of(uint64_t seq, std::vector* out) const { (*out)[(size_t)g] = s; any = true; } - return any; + /* A window snapshot is a snapshot with no state slots (KVManager::has_window_snapshot). */ + return any || (kv.has_window_snapshot() && kv.has_sequence(seq)); } /* ------------------------------------------------------------------ the HTTP frontend */ diff --git a/core/engine.h b/core/engine.h index 37cd6455..c200ca5e 100644 --- a/core/engine.h +++ b/core/engine.h @@ -249,6 +249,7 @@ private: /* Scratch for the checkpoint copies: the state slots of one sequence, reused so the step path * does not allocate. See state_slots_of. */ std::vector ckpt_slots_; + std::vector ckpt_win_; /* KVManager::window_rows, same reuse */ bool state_slots_of(uint64_t seq, std::vector* out) const; int load_vocab(); diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 717b63cc..59e725c0 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -2910,15 +2910,17 @@ int Engine::configure_kv() { slot += ranks_[i]->kv.checkpoint_bytes(); } const int64_t n = cfg_.checkpoint_slots > 0 ? cfg_.checkpoint_slots : 0; + /* A slot holds linear state or a trunk's window, never both (KVGroupPlan::win_snap). */ + const char* what = ranks_[0]->kv.has_window_snapshot() ? "sliding-window" : "linear-state"; if (slot > 0 && n > 0 && cfg_.prefix_cache) { if (ck_store_.open(slot, slot * n) != RAD_OK) { - RAD_WARN("checkpoint slots: no pinned host memory for %lld snapshot(s) of %s; a " - "hybrid session's prefix hits replay their linear layers from zero. " - "Lower --checkpoint-slots.", (long long)n, humanb(slot).c_str()); + RAD_WARN("checkpoint slots: no pinned host memory for %lld %s snapshot(s) of %s; " + "a session's prefix hits prefill from the start. Lower " + "--checkpoint-slots.", (long long)n, what, humanb(slot).c_str()); } else { - RAD_INFO("checkpoint slots: %lld linear-state snapshot(s) of %s in pinned host " - "memory (%s), none of it on the card", (long long)n, - humanb(slot).c_str(), humanb(ck_store_.cap_bytes()).c_str()); + RAD_INFO("checkpoint slots: %lld %s snapshot(s) of %s in pinned host memory (%s), " + "none of it on the card", (long long)n, what, humanb(slot).c_str(), + humanb(ck_store_.cap_bytes()).c_str()); } } for (auto& r : ranks_) @@ -3893,6 +3895,19 @@ int Engine::load_vocab() { vb.chat_template = std::move(t); } + /* The checkpoint's own end-of-generation list travels as metadata, flattened from + * generation_config.json -- a space-separated list, or one id. */ + if (const char* ids = rad_meta_gets(&meta_, "generation.eos_token_id", nullptr)) { + const char* q = ids; + while (*q) { + char* end = nullptr; + const long v = std::strtol(q, &end, 10); + if (end == q) break; + if (v >= 0 && v <= INT32_MAX) vb.eos_ids.push_back((int32_t)v); + q = end; + } + } + auto v = std::make_shared(); RAD_TRY(v->load(std::move(vb))); vocab_ = v; diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index ff3f7880..e13476a0 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -547,6 +547,44 @@ void Checkpoint::detect_import() { else import_why_ = "Quark's weight scheme here is not MXFP4 (fp4, per_group 32, e8m0 scales) " "throughout, which is the one this reads"; + } else if (qm == "compressed-tensors") { + /* COMPRESSED-TENSORS' PACK-QUANTIZED INT4, symmetric and grouped -- Google's Gemma 4 QAT + * release (w4a16-ct) is one. Every config group must say so: a zero point, act-order, a + * dynamic or activation scheme would each change what a code means. */ + std::vector groups; + const std::string cg = "quantization_config.config_groups."; + for (const std::string& k : meta_.keys) + if (k.rfind(cg, 0) == 0) { + const std::string g = k.substr(cg.size(), k.find('.', cg.size()) - cg.size()); + if (std::find(groups.begin(), groups.end(), g) == groups.end()) groups.push_back(g); + } + std::string why; + int64_t group = 0; + if (qc("format") != "pack-quantized") + why = "its format is '" + qc("format") + "', and pack-quantized is the one this reads"; + if (groups.empty() && why.empty()) why = "its quantization_config names no config group"; + for (const std::string& g : groups) { + if (!why.empty()) break; + const std::string w = "config_groups." + g + ".weights."; + const std::string gs = qc(w + "group_size"); + const long long gn = gs.empty() ? 0 : std::atoll(gs.c_str()); + if (qc("config_groups." + g + ".format") != "pack-quantized" || + qc(w + "num_bits") != "4" || qc(w + "type") != "int" || qc(w + "symmetric") != "1" || + qc(w + "strategy") != "group" || qc(w + "dynamic") != "0" || gn <= 0 || + !qc(w + "actorder").empty() || any_under("config_groups." + g + ".input_activations.")) + why = "config group '" + g + "' is not symmetric 4-bit int weights in groups, packed, " + "with no act-order and unquantised activations, which is the one this reads"; + else if (group && gn != group) + why = "its config groups state different group sizes"; + else + group = gn; + } + if (why.empty()) { + import_ = Import::CtInt4; + ct_group_ = group; + } else { + import_why_ = "compressed-tensors: " + why; + } } /* THE TOOL'S DESCRIPTION IS KEPT, UNDER ANOTHER NAME. A plugin reads quantization_config as * the statement of the format it serves (qwen35_fp8 checks quant_method is "fp8"), and an @@ -594,6 +632,53 @@ int Checkpoint::import_piece(const std::string& name, const SrcTensor** codes, return RAD_OK; } + if (import_ == Import::CtInt4) { + /* CT-INT4: `X.weight` is shipped as X.weight_packed (i32 [N, K/8], eight codes a word from + * the low bits, unsigned about 8) and X.weight_scale ([N, K/group]). The words are the + * logical [N, K] code matrix in row order already; only the offset is left for the + * relayout. A layer the config ignores is an ordinary X.weight. */ + const std::string suffix = ".weight"; + if (name.size() <= suffix.size() || + name.compare(name.size() - suffix.size(), suffix.size(), suffix) != 0) + return RAD_E_NOTFOUND; + const SrcTensor* pk = find(name + "_packed"); + if (!pk) return RAD_E_NOTFOUND; + const SrcTensor* sc = find(name + "_scale"); + const std::string what = "'" + pk->name + "'"; + if (pk->rad_dtype != RAD_I32 || pk->shape.size() != 2) + return refuse(RAD_E_FORMAT, what + " is not an int32 [N, K/8] matrix"); + if (find(name + "_zero_point")) + return refuse(RAD_E_UNSUPPORTED, what + " has a zero point beside it, which a symmetric " + "config does not; an asymmetric weight is not read"); + const int64_t N = pk->shape[0], K = pk->shape[1] * 8; + if (K % ct_group_) + return refuse(RAD_E_SHAPE, what + " has " + std::to_string(K) + " columns, not whole " + "groups of " + std::to_string(ct_group_)); + if (!sc || sc->shape.size() != 2 || sc->shape[0] != N || sc->shape[1] != K / ct_group_ || + (sc->rad_dtype != RAD_F16 && sc->rad_dtype != RAD_BF16 && sc->rad_dtype != RAD_F32)) + return refuse(RAD_E_FORMAT, what + " has no float [" + std::to_string(N) + ", " + + std::to_string(K / ct_group_) + "] '" + name + + "_scale' beside it"); + if (const SrcTensor* ws = find(name + "_shape")) { + int64_t dims[2] = { 0, 0 }; + for (int i = 0; i < 2 && i < (int)ws->numel(); ++i) + dims[i] = (int64_t)rad_load_f32(ws->data, ws->rad_dtype, i); + if (ws->numel() != 2 || dims[0] != N || dims[1] != K) + return refuse(RAD_E_SHAPE, "'" + ws->name + "' does not state the [" + + std::to_string(N) + ", " + std::to_string(K) + + "] its codes hold"); + } + SrcTensor c = *pk; + c.rad_dtype = RAD_I4; + c.shape = { N, K }; + c.ct_group = ct_group_; + sliced_.push_back(std::move(c)); + *codes = &sliced_.back(); + *scale = sc; + imported_[name] = { *codes, *scale }; + return RAD_OK; + } + /* GPTQ-PACKED: `X.weight` is shipped as X.qweight, X.scales, X.qzeros and, optionally, * X.g_idx. The width is read off the tensors rather than quantization_config, because a * release may mix widths -- int4 experts beside int8 projections -- and say so only per layer. */ @@ -965,6 +1050,28 @@ int ckpt_resolve(Checkpoint& ck, const Program& prog, const std::string& name, b rad_enc_add_plane(&out->enc, "codes", dt, 1, 1); rad_enc_add_plane(&out->enc, "scale", sdt, br, bc); } + } else if (p0.ct_group) { + /* CT-INT4, IMPORTED: one group throughout and joined only along rows, as GPTQ's. The codes + * become signed i4 (the offset flipped out at relayout) and the scale is the plane as + * shipped, one a group of K. A kernel reads that group or a recipe re-quantises it. */ + out->imported = true; + for (size_t k = 1; k < out->pieces.size() && out->imported; ++k) + if (out->pieces[k]->ct_group != p0.ct_group || + out->scales[k]->rad_dtype != out->scales[0]->rad_dtype) { + out->imported = false; + out->why = "its CT-INT4 pieces differ in group or scale dtype"; + } + if (out->imported && d != 0 && out->pieces.size() > 1) { + out->imported = false; + out->why = "its CT-INT4 pieces are joined along a column, across their groups"; + } + if (out->imported) { + rad_enc_clear(&out->enc); + rad_enc_copy_str(out->enc.scheme, "affine"); + rad_enc_add_plane(&out->enc, "codes", RAD_I4, 1, 1); + rad_enc_add_plane(&out->enc, "scale", out->scales[0]->rad_dtype, 1, p0.ct_group); + out->why = "it is CT-INT4, which rad-convert imports -- serve the container it writes"; + } } else if (!unscaled) { out->why = "some of its pieces carry a scale plane and some do not"; } else if (dt == RAD_F8E4M3 || dt == RAD_F8E5M2) { @@ -1077,6 +1184,18 @@ struct Joined { /* `n` elements of a stored-dtype piece from element `e`, as f32. */ int piece_f32(const SrcTensor& t, int64_t e, int64_t n, float* out) { + if (t.ct_group) { + /* the signed code: element (row, k) of the logical [N, K] matrix is nibble k % 8 of word + * [row, k / 8], less 8 */ + const int64_t K = t.shape[1]; + for (int64_t i = 0; i < n; ++i) { + const int64_t row = (e + i) / K, k = (e + i) % K; + uint32_t w; + std::memcpy(&w, (const uint8_t*)t.data + (row * (K / 8) + k / 8) * 4, 4); + out[i] = (float)((int)((w >> ((k % 8) * 4)) & 0xFu) - 8); + } + return RAD_OK; + } if (t.gptq_bits) { /* the signed code: element (row, k) of the logical [N, K] matrix is field k % (32/bits) * of word [k / (32/bits), row], less its zero point */ @@ -1148,8 +1267,8 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std:: : "?") : std::string(rad_dtype_name(w.pieces[0]->rad_dtype))) + ")"); - /* A GPTQ-PACKED CODE TIMES ITS GROUP'S SCALE, the scale read as shipped: the scale tensor is - * [groups, N], so row r's scales are a column of it. */ + /* AN IMPORTED CODE TIMES ITS GROUP'S SCALE, the scale read as shipped: GPTQ's scale tensor is + * [groups, N], so row r's scales are a column of it; CT-INT4's is [N, groups], a row. */ if (w.imported) { int64_t base = 0; for (size_t k = 0; k < w.pieces.size(); ++k) { @@ -1158,8 +1277,10 @@ int ckpt_rows_f32(const CkptWeight& w, int64_t r0, int64_t nr, float* out, std:: const int64_t pr = pk.shape[0]; for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + pr); ++r) for (int64_t c = 0; c < w.cols; ++c) - out[(r - r0) * w.cols + c] *= - rad_load_f32(sk.data, sk.rad_dtype, (c / pk.gptq_group) * pr + (r - base)); + out[(r - r0) * w.cols + c] *= rad_load_f32( + sk.data, sk.rad_dtype, + pk.ct_group ? (r - base) * (w.cols / pk.ct_group) + c / pk.ct_group + : (c / pk.gptq_group) * pr + (r - base)); base += pr; } return RAD_OK; @@ -1212,6 +1333,24 @@ int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* ds const SrcTensor& c = *w.pieces[p]; const SrcTensor& s = *w.scales[p]; const int64_t N = c.shape[0], K = c.shape[1]; + if (c.ct_group) { + /* CT-INT4, RE-LAID: a row of codes is a row of the packed words, already two codes + * a byte low nibble first, each offset to signed by flipping its top bit; a row of + * scales is a row of the scale tensor, as shipped. */ + for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) { + const int64_t n = r - base; + if (k == 0) { + const uint8_t* q = (const uint8_t*)c.data + n * (K / 2); + for (int64_t i = 0; i < K / 2; ++i) *o++ = q[i] ^ 0x88; + } else { + const int64_t g = K / c.ct_group, sb = rad_dtype_bits(s.rad_dtype) / 8; + std::memcpy(o, (const uint8_t*)s.data + n * g * sb, (size_t)(g * sb)); + o += g * sb; + } + } + base += N; + continue; + } const uint8_t flip = c.gptq_bits == 4 ? 0x88 : 0x80; for (int64_t r = std::max(r0, base); r < std::min(r0 + nr, base + N); ++r) { const int64_t n = r - base; diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 1b5cf248..339a8400 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -56,6 +56,12 @@ struct SrcTensor { * the K columns one row of its scale tensor covers. 0 for any other tensor. */ int32_t gptq_bits = 0; int64_t gptq_group = 0; + /* CT-INT4 (compressed-tensors' pack-quantized int4, symmetric): `data` is X.weight_packed's + * int32 words [N, K / 8], eight codes a word along K from the low bits up, stored unsigned with + * the zero point 8. The tensor this describes is the logical [N, K] code matrix, `rad_dtype` + * RAD_I4; `ct_group` is the K columns one scale of X.weight_scale [N, K / group] covers. 0 for + * any other tensor. */ + int64_t ct_group = 0; int64_t numel() const { int64_t n = 1; @@ -132,7 +138,7 @@ public: * this does not read stays None, with the reason in import_refusal(). */ /* Its quantization_config keys are then renamed `imported_quantization_config.*`: they * describe the tool, not a served format, and a plugin reads the latter there. */ - enum class Import { None, Gptq, QuarkMx }; + enum class Import { None, Gptq, QuarkMx, CtInt4 }; Import imports() const { return import_; } const std::string& import_refusal() const { return import_why_; } @@ -164,6 +170,7 @@ private: int64_t fp8_br_ = 128, fp8_bc_ = 128; Import import_ = Import::None; std::string import_why_; + int64_t ct_group_ = 0; /* CtInt4: the group every weight's config states */ /* import_piece's answers by name, so a weight resolved twice reads one pair of views. */ std::unordered_map> imported_; }; diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index 0d78e1ea..c84467cb 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -271,7 +271,19 @@ int KVManager::plan_groups(const std::vector& groups, const Config& /* ---- fixed costs first: they are not negotiable and they are not per-token ---- */ checkpoint_bytes_ = 0; + window_ck_bytes_ = 0; for (const auto& p : plans_) if (p.stateful()) checkpoint_bytes_ += p.bytes_per_state; + /* AND THE WINDOW BEHIND A CHECKPOINT, after the linear state (see has_window_snapshot). */ + bool has_state = false; + for (const auto& p : plans_) has_state = has_state || p.stateful(); + for (size_t i = 1; i < plans_.size(); ++i) { + KVGroupPlan& p = plans_[i]; + p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 && + !groups[i].drafter; + if (p.win_snap && !p.zero && p.n_layers > 0) + window_ck_bytes_ += p.window_blocks * p.bytes_per_block; + } + checkpoint_bytes_ += window_ck_bytes_; /* EVERY RESERVATION IS PADDED TO RAD_ALIGN_UNIT AND THE BUDGET HAS TO SAY SO. Summing the * fixed costs as raw bytes leaves the paged split free to spend the difference, and the plan @@ -307,7 +319,7 @@ int64_t KVManager::ceiling(int64_t ctx) const { if (!p.paged() || p.block_size <= 0) continue; int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size); if (p.kind == RAD_KV_WINDOW && p.window_blocks > 0) - blocks = std::min(blocks, max_seqs_ * p.window_blocks); + blocks = std::min(blocks, window_pool_cap(p)); need += blocks * p.bytes_per_block; } return need; @@ -382,10 +394,10 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector* block for (int32_t i : open) { const auto& p = plans_[i]; if (p.kind != RAD_KV_WINDOW) continue; - if (tokens / p.block_size > max_seqs_ * p.window_blocks) { capped = i; break; } + if (tokens / p.block_size > window_pool_cap(p)) { capped = i; break; } } if (capped < 0) break; - out[capped] = max_seqs_ * plans_[capped].window_blocks; + out[capped] = window_pool_cap(plans_[capped]); remaining -= out[capped] * plans_[capped].bytes_per_block; open.erase(std::find(open.begin(), open.end(), capped)); } @@ -419,7 +431,7 @@ int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const { int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const { if (tokens == kUnboundedTokens) return 0; const int64_t b = tokens / p.block_size; - if (p.kind == RAD_KV_WINDOW && b > max_seqs_ * p.window_blocks) return max_seqs_ * p.window_blocks; + if (p.kind == RAD_KV_WINDOW && b > window_pool_cap(p)) return window_pool_cap(p); return b; } @@ -921,7 +933,7 @@ int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const { const KVGroupPlan* p = plan(g); if (!p || !p->paged() || n_tokens <= 0) return 0; int64_t n = ceil_div(n_tokens, p->block_size); - if (p->kind == RAD_KV_WINDOW) n = std::min(n, p->window_blocks); + if (p->kind == RAD_KV_WINDOW) n = std::min(n, window_seq_cap(*p)); return n; } @@ -1156,19 +1168,29 @@ std::vector KVManager::take_pending_copies() { /* ------------------------------------------------------------------ ensure */ -int KVManager::ensure(uint64_t id, int64_t n_tokens) { - Seq* s = find(id); - if (!s) return RAD_E_NOTFOUND; - if (n_tokens <= s->n_tokens) return RAD_OK; +int64_t KVManager::window_seq_cap(const KVGroupPlan& p) const { + return p.window_blocks + (max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0) + 1; +} - /* Pass 0: recycle whatever the window has slid past. This only frees, so it cannot fail, and - * doing it first means the availability check below sees the memory it releases. */ +int64_t KVManager::window_pool_cap(const KVGroupPlan& p) const { + return max_seqs_ * p.window_blocks + (max_tok_ > 0 ? ceil_div(max_tok_, p.block_size) : 0) + + max_seqs_; +} + +/* SLID PAST THE STEP'S FIRST QUERY, NOT ITS LAST. The query at keep_from reads keys down to + * keep_from - window + 1, which lies in block keep_from / block - (window_blocks - 1) or later + * (window_blocks - 1 >= window / block). A target taken from the END of the step -- + * ceil(n_tokens / block) - window_blocks -- is the same block for a decode step and drops the keys + * every row of a longer prefill chunk still needs. Measured on Gemma 4 (#75: 50 of 60 layers + * windowed at 1024): a 2185-token prompt rebased the table at 1152, its sliding layers held no KV + * for positions 0..1151, and every prompt past ~1040 tokens came back as nonsense. */ +void KVManager::recycle_window(Seq* s, int64_t keep_from) { for (size_t g = 0; g < plans_.size(); ++g) { const auto& p = plans_[g]; if (p.kind != RAD_KV_WINDOW) continue; - int64_t want_end = ceil_div(n_tokens, p.block_size); int64_t first = s->first_block_pos[g] / p.block_size; - int64_t target = std::max(first, want_end - p.window_blocks); + int64_t target = std::max(first, + keep_from / p.block_size - (p.window_blocks - 1)); while (first < target && !s->blocks[g].empty()) { drop_block((int32_t)g, s->blocks[g].front()); s->blocks[g].erase(s->blocks[g].begin()); @@ -1178,6 +1200,24 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens) { if (s->blocks[g].empty()) first = target; /* nothing held: rebase to the window */ s->first_block_pos[g] = first * p.block_size; } +} + +void KVManager::trim_window(uint64_t id, int64_t keep_from) { + Seq* s = find(id); + if (!s || keep_from < 0) return; + if (keep_from > s->n_tokens) keep_from = s->n_tokens; + recycle_window(s, keep_from); +} + +int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) { + Seq* s = find(id); + if (!s) return RAD_E_NOTFOUND; + if (n_tokens <= s->n_tokens) return RAD_OK; + if (keep_from < 0 || keep_from > s->n_tokens) keep_from = s->n_tokens; + + /* Pass 0: recycle whatever the window has slid past. This only frees, so it cannot fail, and + * doing it first means the availability check below sees the memory it releases. */ + recycle_window(s, keep_from); /* Pass 1: can every group serve this? Check before touching anything, so a group that runs * out does not leave the sequence half-extended and the caller unable to say what it owns. */ @@ -1316,7 +1356,7 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens, if (p.paged()) { int64_t first = s->first_block_pos[g] / p.block_size; int64_t want = ceil_div(n_tokens, p.block_size) - first; - if (p.kind == RAD_KV_WINDOW) want = std::min(want, p.window_blocks); + if (p.kind == RAD_KV_WINDOW) want = std::min(want, window_seq_cap(p)); int64_t extra = want - (int64_t)s->blocks[g].size() + 1; /* +1 for a COW copy */ if (extra > available_blocks((int32_t)g)) return false; } else if (p.stateful() && s->state[g] < 0 && free_states_[g].empty()) return false; @@ -1374,7 +1414,7 @@ void* KVManager::checkpoint_ptr(int32_t slot) const { * exactly one piece of code decides its order. Two functions that agreed today would be two * functions that could stop agreeing. */ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, - bool save, RadStream s) { + bool save, RadStream s, const std::vector* win) { /* A SLOT NOBODY HOLDS IS NOT ONE TO WRITE. Rank 0 hands the ids out, so a follower checks the * shared store rather than a list of its own. Each refusal says which check it is: a slot the * store gave back is a lifetime fault in whoever handed the id out, and nothing about the copy. */ @@ -1438,14 +1478,111 @@ int KVManager::checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t } off += nbytes * p.n_layers; } + + /* THE WINDOW SECTION: window_blocks pages a WINDOW group, page j of the window in slot j, each + * page n_layers rows of one layer's block -- one pitched copy a page. `win` names the pages + * (window_rows); -1 is a page below position zero and is left alone either way. */ + if (window_ck_bytes_ > 0) { + if (!win) { + RAD_ERR("checkpoint %s slot %d: this model snapshots its window and no window rows " + "were named", dir, (int)ck_slot); + return RAD_E_INVAL; + } + size_t wi = 0; + for (size_t g = 0; g < plans_.size(); ++g) { + const KVGroupPlan& p = plans_[g]; + if (!p.win_snap) continue; + const size_t row0 = wi; + wi += (size_t)p.window_blocks; + if (p.zero || p.n_layers <= 0) continue; + if (wi > win->size() || !p.base) { + RAD_ERR("checkpoint %s slot %d: window group %d has %zu row(s) named for %lld", + dir, (int)ck_slot, (int)g, win->size(), (long long)wi); + return RAD_E_STATE; + } + const int64_t lb = p.layer_bytes_per_block(); + for (int64_t j = 0; j < p.window_blocks; ++j) { + const int32_t b = (*win)[row0 + (size_t)j]; + if (b < 0) continue; + if (b >= p.n_blocks) return RAD_E_STATE; + char* dev = (char*)p.base + (int64_t)b * lb; + char* host = ck + off + j * p.bytes_per_block; + const int cs = save ? rad_memcpy_2d_async(host, lb, dev, p.layer_stride(), lb, + p.n_layers, s) + : rad_memcpy_2d_async(dev, p.layer_stride(), host, lb, lb, + p.n_layers, s); + if (cs < 0) { + RAD_ERR("checkpoint %s slot %d: the device refused window page %lld of " + "group %d: %s", dir, (int)ck_slot, (long long)j, (int)g, + rad_strerror(cs)); + return cs; + } + } + off += p.window_blocks * p.bytes_per_block; + } + if (off > checkpoint_bytes_) return RAD_E_STATE; + } return RAD_OK; } -int KVManager::checkpoint_save(const int32_t* slots, int n, int32_t ck, RadStream s) { - return checkpoint_copy(slots, n, ck, /*save=*/true, s); +int KVManager::checkpoint_save(const int32_t* slots, int n, int32_t ck, RadStream s, + const std::vector* win) { + return checkpoint_copy(slots, n, ck, /*save=*/true, s, win); } -int KVManager::checkpoint_restore(const int32_t* slots, int n, int32_t ck, RadStream s) { - return checkpoint_copy(slots, n, ck, /*save=*/false, s); +int KVManager::checkpoint_restore(const int32_t* slots, int n, int32_t ck, RadStream s, + const std::vector* win) { + return checkpoint_copy(slots, n, ck, /*save=*/false, s, win); +} + +bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector* out) const { + out->clear(); + const Seq* s = find(id); + if (!s || pos <= 0) return false; + for (size_t g = 0; g < plans_.size(); ++g) { + const KVGroupPlan& p = plans_[g]; + if (!p.win_snap) continue; + const size_t row0 = out->size(); + out->resize(row0 + (size_t)p.window_blocks, -1); + if (p.zero || p.block_size <= 0 || pos % p.block_size != 0) { + if (p.zero) continue; + return false; + } + const int64_t lo = window_lo(p, pos), hi = pos / p.block_size; + const int64_t first = s->first_block_pos[g] / p.block_size; + if (lo < first || hi - first > (int64_t)s->blocks[g].size()) return false; + for (int64_t j = lo; j < hi; ++j) + (*out)[row0 + (size_t)(j - lo)] = s->blocks[g][(size_t)(j - first)]; + } + return true; +} + +int KVManager::seed_window(uint64_t id, int64_t pos) { + Seq* s = find(id); + if (!s) return RAD_E_NOTFOUND; + /* Check every group before taking anything, as ensure() does. */ + for (size_t g = 0; g < plans_.size(); ++g) { + const KVGroupPlan& p = plans_[g]; + if (!p.win_snap) continue; + if (!s->blocks[g].empty()) return RAD_E_STATE; + if (pos % p.block_size != 0) return RAD_E_INVAL; + const int64_t need = pos / p.block_size - window_lo(p, pos); + if (need > available_blocks((int32_t)g)) return RAD_E_FULL; + RAD_TRY(grow_for((int32_t)g, need)); + } + for (size_t g = 0; g < plans_.size(); ++g) { + const KVGroupPlan& p = plans_[g]; + if (!p.win_snap) continue; + const int64_t lo = window_lo(p, pos), hi = pos / p.block_size; + s->first_block_pos[g] = lo * p.block_size; + for (int64_t j = lo; j < hi; ++j) { + int32_t b = -1; + grab_block((int32_t)g, &b); + s->blocks[g].push_back(b); + } + s->dirty_from[g] = 0; + } + if (s->n_tokens == 0) s->n_tokens = pos; + return RAD_OK; } /* HOW MANY COLUMNS A SEQUENCE'S state_index ROW HAS. One per physical copy would be the obvious diff --git a/core/mem/kv.h b/core/mem/kv.h index d8869d67..a37f1169 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -73,6 +73,11 @@ struct KVGroupPlan { int64_t bytes_per_state = 0; /* LINEAR/CONV: per sequence, every layer */ int64_t conv_slots = 0; /* CONV: conv_width - 1 + n_spec */ int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */ + /* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Only a trunk + * group of a model with no linear state: a prefix hit there resumes at a checkpoint from the + * window behind it. A drafter's own window is recomputed by draft refill, and a model with + * linear state re-prefills a hit on a windowed trunk, so neither snapshot would ever be read. */ + bool win_snap = false; int64_t n_blocks = 0; /* paged groups: blocks carved from the pool */ /* rad_kv_group_zero: this rank keeps no cache for the group. The plan exists for its position @@ -207,8 +212,31 @@ public: /* Grow the sequence's mapping to cover `n_tokens` in every group. Unshares a shared partial * block first (copy-on-write) and appends the copy request to the pending list. - * RAD_E_FULL when a group's free list is empty -- the caller preempts and retries. */ - int ensure(uint64_t seq, int64_t n_tokens); + * RAD_E_FULL when a group's free list is empty -- the caller preempts and retries. + * + * `keep_from` is the position of the FIRST query the coming step runs (the scheduler's + * n_computed); -1 means the sequence's current end. A WINDOW group recycles only the blocks no + * query at or past it can read -- below keep_from - window + 1 -- and NOT the blocks below the + * window of the step's END: a prefill chunk longer than a block would otherwise lose the keys + * its first rows attend to (a chunk of C tokens from position 0 rebased the table at + * ceil(C/block) - window_blocks and left every position below it with no KV at all). */ + int ensure(uint64_t seq, int64_t n_tokens, int64_t keep_from = -1); + + /* A WINDOW group's caps: a sequence holds its window behind the step's first query AND the + * step's own tokens (window_blocks + ceil(max_tok / block) + 1 at most), and one step carries + * at most max_tok tokens across every sequence in it, so the pool needs max_seqs windows plus + * one step's worth on top. */ + int64_t window_seq_cap(const KVGroupPlan& p) const; + int64_t window_pool_cap(const KVGroupPlan& p) const; + + /* GIVE BACK A FINISHED CHUNK'S BLOCKS once it is committed. ensure() keeps a chunk's own blocks + * beside the window behind its first query, and only the sequence's NEXT ensure() recycles + * them -- so a prefill waiting a step for its next chunk would sit on a whole chunk of window + * blocks while other sequences prefill, and eight of them exhaust the pool (measured on + * Gemma 4: "the KV pool cannot hold 12480 tokens" with eight 16K prompts). Called by the + * scheduler when it advances n_computed: keep_from is the new n_computed, the first query any + * later step can run. */ + void trim_window(uint64_t seq, int64_t keep_from); /* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's * block size: a partial block is never shared, because the next token written into it would @@ -462,8 +490,35 @@ public: * and the restore has to precede the step that consumes it, and both are ordered by the * stream rather than by waiting. One pitched copy a stateful group between the card and the * store, at the link's rate. RAD_E_INVAL on a bad slot or an unknown sequence. */ - int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s); - int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s); + int checkpoint_save(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s, + const std::vector* win = nullptr); + int checkpoint_restore(const int32_t* state_slots, int n_slots, int32_t ck_slot, RadStream s, + const std::vector* win = nullptr); + + /* ---------------- window snapshots (the sliding-window half of a prefix hit) ---------------- + * A WINDOW group keeps only the blocks its window can still read, so no block list from the + * prefix cache describes it. What a later prompt that extends a cached prefix at position P + * needs from it is exactly the window behind P: blocks [lo, P/B) with + * lo = max(0, P/B - (window_blocks - 1)) -- the floor recycle_window keeps for a query at P. + * A checkpoint slot therefore carries, after the linear state, window_blocks pages a WINDOW + * group (every layer, layer-major rows), and a hit at a checkpoint restores them into fresh + * blocks seeded at that floor. + * + * has_window_snapshot(): this rank's slot carries a window section. window_rows() names, from + * the LEADER's table, the block ids [lo, P/B) of every non-zero snapshot group (win_snap) in + * plans() order, each group padded with -1 to window_blocks -- one vector every rank addresses + * with its own pool, because followers keep no sequence tables. False when the sequence does + * not hold that range (it is gone, or its floor moved past lo). seed_window() gives a sequence + * with an empty table in each snapshot group the blocks [lo, P/B) a restore will fill, before + * the ensure that extends it; any other WINDOW group starts at the floor that ensure sets. */ + bool has_window_snapshot() const { return window_ck_bytes_ > 0; } + bool window_rows(uint64_t seq, int64_t pos, std::vector* out) const; + int seed_window(uint64_t seq, int64_t pos); + /* The floor and end (block indices) of the window a query at `pos` reads in a group. */ + static int64_t window_lo(const KVGroupPlan& p, int64_t pos) { + const int64_t b = pos / p.block_size - (p.window_blocks - 1); + return b > 0 ? b : 0; + } /* Byte address of a state slot, for the slot-mapping builder. Null when the pool has no * host-visible base (a device pool), which is the normal case -- the offset is what the step @@ -486,7 +541,7 @@ private: /* One traversal serving both checkpoint directions; see checkpoint_save. */ int checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save, - RadStream s); + RadStream s, const std::vector* win); struct Seq { uint64_t id = 0; @@ -509,6 +564,8 @@ private: void drop_state(int32_t g, int32_t s); Seq* find(uint64_t seq); const Seq* find(uint64_t seq) const; + /* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. */ + void recycle_window(Seq* s, int64_t keep_from); std::vector plans_; std::vector> free_blocks_; /* per group */ @@ -524,6 +581,7 @@ private: HostArena* ck_store_ = nullptr; /* set_checkpoint_store */ int64_t ck_rank_off_ = 0; int64_t checkpoint_bytes_ = 0; + int64_t window_ck_bytes_ = 0; /* the window section of checkpoint_bytes_ */ std::vector clears_; /* grabbed slots the engine must zero */ void* pool_base_ = nullptr; BundleComparison bundling_; diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index a2a9c07e..142bee1a 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -158,6 +158,9 @@ int PrefixCache::configure(const Config& cfg, KVManager* kv, int64_t checkpoint_ } interval_ = checkpoint_interval; + /* A WINDOW SNAPSHOT is state in the same sense: a hit is reusable at a checkpoint only, where + * the slot carries the window behind it (KVManager::has_window_snapshot). */ + if (kv->has_window_snapshot() && interval_ > 0) has_linear_ = true; if (has_linear_) { if (interval_ <= 0) { RAD_ERR("checkpoint_interval is %lld but the model has linear-attention state. A " diff --git a/core/rad_core.h b/core/rad_core.h index f121ea92..df44afb9 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -320,6 +320,9 @@ struct KVGroupInfo { int64_t bytes_per_state = 0; /* linear/conv: per sequence */ std::vector layers; bool zero = false; /* rad_kv_group_zero: declared for position, nothing carved */ + /* Bound only at meta.n_layers and above: the drafter's own cache, which no trunk layer reads. + * Set at declare (Builder::finish_kv_groups). */ + bool drafter = false; }; /* A RAD_KV_CONV GROUP'S WINDOW, IN ENTRIES: conv_width - 1 of history and one more for every @@ -362,6 +365,12 @@ public: * RadDrafterDecl::name points into the plugin's own storage. */ RadDrafterDecl drafter{}; std::string drafter_name; + /* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv): it reads the trunk's K and V + * and writes none, so the driver owes it no history and runs every round at the committed + * position. `drafter_pos_offset` is where those rows sit for the rotary, 0 or 1 past it. Both + * are false and 0 for every drafter that did not ask, which is every one that predates it. */ + bool drafter_shared_kv = false; + int32_t drafter_pos_offset = 0; /* THE MEDIA ENCODER THIS PLUGIN DECLARED (rad_declare_encoder). `modalities == 0` when it * declared none, which is every text-only program and every deployment that asked for no diff --git a/core/sched/advance.h b/core/sched/advance.h index 855c518b..44a3cf16 100644 --- a/core/sched/advance.h +++ b/core/sched/advance.h @@ -94,6 +94,13 @@ struct AdvanceArgs { * the host's position keeps the host's three components, which is what a media token needs. */ int64_t rope_off = -1; int32_t rope_pitch = 0; + /* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv), read by ADV_HIST and + * ADV_ROUND alone: its history pass is one row a sequence at the committed position, and every + * round sits there too, its context ending at that position. `rot_shift` is where those rows + * sit for the rotary, 0 or 1 past the committed position. Zero for every other head, whose + * passes advance exactly as they always did. */ + int32_t shared_kv = 0; + int32_t rot_shift = 0; }; /* Issue one advance on `s`. The rows are independent, so the card runs them in parallel. */ diff --git a/core/sched/advance_impl.h b/core/sched/advance_impl.h index 504fbfdb..667e6b03 100644 --- a/core/sched/advance_impl.h +++ b/core/sched/advance_impl.h @@ -109,6 +109,22 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) { return; } case ADV_HIST: { + if (a.shared_kv) { + /* A HEAD THAT READS THE TRUNK'S CACHE AND KEEPS NONE (rad_drafter_shared_kv). There is + * no history to fill, so the pass is round 1 alone and its one row is the last one of + * the run below: the committed position, the trunk's row there, the token the trunk + * chose after it. Its context is the committed positions and NOT the verify step's + * whole run -- the cache past the committed position holds the K and V of the drafts + * this verify rejected. The host staged the run's first trunk row; the card adds the + * drafts it accepted. */ + int32_t* out = adv_i32(a, a.out_off); + tok[k] = a.src[rout + S.acc]; + adv_pos(a, pos, k, S.head + a.rot_shift); + out[k] += S.acc; + ctx[i] = S.head; + adv_groups(a, i, k, S.head, 1); + return; + } /* `aux` positions the host already knew the tokens of, then the verify step's own * positions up to the last one it committed, each with the token committed after it -- * the sampler's pick there, since the drafts before it agreed with it. The pass has a @@ -133,12 +149,14 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) { } case ADV_ROUND: { /* Round 2 onward: round 1 is the history pass's last row (ADV_HIST above), so every - * round embeds the proposal of the round before it. */ - const int32_t base = S.head + a.round - 1; + * round embeds the proposal of the round before it. A head with no cache of its own does + * not step forward: it stays at the committed position over the committed context, and + * what it proposed reaches the next round through its own hidden state. */ + const int32_t base = a.shared_kv ? S.head : S.head + a.round - 1; const int32_t t = a.src[(int64_t)i * a.src_pitch]; S.tok[a.round - 1] = t; tok[k] = t; - adv_pos(a, pos, k, base); + adv_pos(a, pos, k, a.shared_kv ? base + a.rot_shift : base); ctx[i] = base; adv_groups(a, i, k, base, 1); return; diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index 97a6aed0..3fcb64b2 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -185,8 +185,12 @@ void BatchBuilder::size_set(Set& s, const std::vector& groups) { s.groups[gi].block_size = e.block_size; int64_t mb = 1; if (e.paged) { - int64_t span = (e.kind == RAD_KV_WINDOW && e.window > 0 && e.window < max_ctx_) - ? e.window : max_ctx_; + /* A WINDOW row holds the window behind the step's first query AND the step's own + * tokens (KVManager::ensure keeps both), so it is sized for a whole chunk past the + * window -- plus the speculative lookahead, which a verify row carries on top. */ + const int64_t wspan = e.window + max_tok_ + 2 * ((int64_t)std::max(cfg_.n_spec, 0) + 1); + int64_t span = (e.kind == RAD_KV_WINDOW && e.window > 0 && wspan < max_ctx_) + ? wspan : max_ctx_; mb = (span + e.block_size - 1) / e.block_size + 1; } s.groups[gi].max_blocks = mb; diff --git a/core/sched/geometry.cpp b/core/sched/geometry.cpp index e686c19b..a70e1595 100644 --- a/core/sched/geometry.cpp +++ b/core/sched/geometry.cpp @@ -47,12 +47,16 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry * the same block size -- libr4d's is 16 for all of them -- but a hybrid model with a * sliding-window group served by a different kernel is exactly the case §7.2 is written for, * and lcm is the answer that is right for both. */ - bool has_linear = false; + bool has_linear = false, has_window = false; for (const KVGroupInfo& kg : prog.kv_groups) { if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) { if (kg.block_size > 0) { g.attn_block = lcm64(g.attn_block, kg.block_size); note(g.why, "attn_block", kg.block_size, kg.name.c_str()); + /* A drafter's window is recomputed by draft refill; only the trunk's needs a + * snapshot for a prefix hit to resume. */ + if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter) + has_window = true; } } else { has_linear = true; @@ -123,11 +127,14 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry * because down can reach zero and because a longer interval costs retention, not correctness. * * No linear state means no checkpoints: the interval is a property of a state kind that this - * model does not have, and pretending otherwise would split chunks for nothing. */ - if (has_linear && cfg.checkpoint_interval > 0) + * model does not have, and pretending otherwise would split chunks for nothing. The one + * exception is a trunk window under a prefix cache, which snapshots the window behind a + * prompt's tail (window_ckpt) and does not split chunks for it. */ + if ((has_linear || (has_window && cfg.prefix_cache)) && cfg.checkpoint_interval > 0) g.checkpoint_interval = align_up(cfg.checkpoint_interval, g.quantum); else g.checkpoint_interval = 0; + g.window_ckpt = !has_linear && g.checkpoint_interval > 0; /* One full quantum has to fit in one step. Below that, every chunk is short, no chunk ever * ends on a boundary, and the checkpoint lands wherever the step happened to end -- which is @@ -150,8 +157,10 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry * always written, and that clamp comes FIRST. Printing only the budget would hide it -- every * budget above the interval runs the same chunk length, so a sweep over them reads as * "prefill is flat against the chunk" when nothing about the chunk changed. The clamp itself - * is correct; a budget that silently does nothing is what has to be visible. */ - const int64_t eff = (g.checkpoint_interval > 0 && g.checkpoint_interval < cfg.max_tok) + * is correct; a budget that silently does nothing is what has to be visible. A window + * snapshot is taken at the prompt's tail and splits nothing. */ + const int64_t eff = (g.checkpoint_interval > 0 && !g.window_ckpt && + g.checkpoint_interval < cfg.max_tok) ? g.checkpoint_interval : cfg.max_tok; RAD_INFO("chunk geometry: quantum %lld (attn block %lld, state chunk %lld), checkpoint " "interval %lld, max_tok %lld -> prefill chunks of at most %lld%s", diff --git a/core/sched/geometry.h b/core/sched/geometry.h index 77596dfc..c11ba385 100644 --- a/core/sched/geometry.h +++ b/core/sched/geometry.h @@ -48,6 +48,12 @@ struct ChunkGeometry { /* Every contributor by name, for the startup line and for the refusal. Built once. */ std::string why; + /* NO LINEAR STATE, A SLIDING WINDOW: the checkpoint snapshots the window behind a prompt's + * tail (KVManager::has_window_snapshot) and nothing else. Chunks are not split at the + * interval -- a window snapshot in the middle of a prompt buys a later hit nothing its tail + * does not -- and the interval is only the shortest prompt worth a snapshot. */ + bool window_ckpt = false; + bool checkpoints() const { return checkpoint_interval > 0; } }; diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index 8e77fb40..f6bf781b 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -46,6 +46,20 @@ struct IKVManager { * free list is empty, which is a scheduling signal and not an error: the caller preempts a * victim and retries. */ virtual int ensure(uint64_t seq, int64_t n_tokens) = 0; + /* The same, for a step whose first query sits at `keep_from` (the request's n_computed): a + * WINDOW group then keeps every block that query can still read, however long the step is. + * See KVManager::ensure. The default is for a manager with no windowed group. */ + virtual int ensure_from(uint64_t seq, int64_t n_tokens, int64_t keep_from) { + (void)keep_from; + return ensure(seq, n_tokens); + } + /* A committed step: a WINDOW group gives back what no later query can read. A no-op for a + * manager with no windowed group. See KVManager::trim_window. */ + virtual void trim_window(uint64_t seq, int64_t keep_from) { (void)seq; (void)keep_from; } + /* The window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The + * defaults are a manager with none: no hit on a windowed trunk is ever resumed. */ + virtual bool has_window_snapshot() const { return false; } + virtual int seed_window(uint64_t seq, int64_t pos) { (void)seq; (void)pos; return -1; } /* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's * block size -- a partial block is never shared, because the next token written into it would @@ -282,6 +296,10 @@ struct KVBinding final : IKVManager { bool has_sequence(uint64_t s) const override { return m->has_sequence(s); } void free_sequence(uint64_t s) override { m->free_sequence(s); } int ensure(uint64_t s, int64_t n) override { return m->ensure(s, n); } + int ensure_from(uint64_t s, int64_t n, int64_t k) override { return m->ensure(s, n, k); } + void trim_window(uint64_t s, int64_t k) override { m->trim_window(s, k); } + bool has_window_snapshot() const override { return m->has_window_snapshot(); } + int seed_window(uint64_t s, int64_t p) override { return m->seed_window(s, p); } int adopt(uint64_t s, int32_t g, const std::vector& b, int64_t n) override { return m->adopt(s, g, b, n); } diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index a2b5bf78..baa4fafb 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -87,6 +87,21 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac n_paged, pc->cached_groups().size(), hit_holes_draft_ ? "LEAVES a hole in a drafter's own KV" : "leaves no hole"); } + /* THE TRUNK'S SHARE of that question: a paged group a TRUNK layer reads (a bound layer below + * the trunk's layer count — a drafter borrows from base_layer and above) that the cache does + * not index. Its hole is not repairable by recomputing the tail; see scheduler.h. */ + hit_holes_trunk_ = false; + for (size_t i = 0; i < prog.kv_groups.size(); ++i) { + if (kv->block_tokens((int32_t)i) <= 0) continue; + bool trunk = false; + for (int l : prog.kv_groups[i].layers) if (l < prog.meta.n_layers) { trunk = true; break; } + if (!trunk) continue; + const std::vector& cg = pc->cached_groups(); + if (std::find(cg.begin(), cg.end(), (int32_t)i) == cg.end()) { hit_holes_trunk_ = true; break; } + } + if (hit_holes_trunk_ && cfg.prefix_cache) + RAD_INFO("prefix cache: a trunk layer's windowed group is not prefix-cached -- a hit " + "resumes from a window snapshot (a checkpoint slot) or re-prefills"); draft_refill_ = 0; if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 && hit_holes_draft_) { @@ -95,6 +110,14 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac "drafter's window is recomputed", (long long)draft_refill_); } + serial_shared_ = cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_SERIAL && + prog.drafter_shared_kv; + serial_rot_shift_ = serial_shared_ ? prog.drafter_pos_offset : 0; + if (serial_shared_) + RAD_INFO("serial drafter: reads the trunk's cache and keeps none -- no history pass, one " + "row a drafting sequence, every round at the committed position%s", + serial_rot_shift_ ? " (rotated one past it)" : ""); + DraftController::Params dp; dp.max_depth = cfg.n_spec; /* THE ADAPTIVE WINDOW IS THE SERIAL DRAFTER'S POLICY (draft.h): it prices a draft as one more @@ -726,6 +749,7 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg if (geo_.checkpoints()) { const int64_t I = geo_.checkpoint_interval; int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */ + if (geo_.window_ckpt) next = INT64_MAX; /* a window snapshot: the tail only */ if (n_computed + want > next) want = next - n_computed; if (n_computed + want == next) { if (checkpoint_pos) *checkpoint_pos = next; @@ -778,6 +802,7 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg bool Scheduler::last_checkpoint(int64_t pos, int64_t target) const { if (!geo_.checkpoints()) return false; const int64_t I = geo_.checkpoint_interval; + if (geo_.window_ckpt) { const int64_t t = tail_checkpoint(target); return t > 0 && t <= pos; } if ((pos / I + 1) * I <= target) return false; return tail_checkpoint(target) <= pos; } @@ -789,6 +814,15 @@ int64_t Scheduler::tail_checkpoint(int64_t target) const { const int64_t I = geo_.checkpoint_interval, Q = geo_.quantum; if (I <= 0 || Q <= 0) return -1; const int64_t tail = target / Q * Q; + /* A WINDOW SNAPSHOT is taken at the tail of any prompt of an interval or more. */ + /* A block short of the end: the next turn re-renders the last few tokens (a generation + * prompt it replaces with the reply), and a snapshot past where the two renderings part is + * one no hit can reach -- measured: every prompt whose length left fewer than ~8 tokens in + * its last block missed. */ + if (geo_.window_ckpt) { + const int64_t t = (target - std::max(Q, 16)) / Q * Q; + return t >= I ? t : -1; + } return tail > I && tail - tail / I * I >= std::max(Q, I / 4) ? tail : -1; } @@ -864,7 +898,7 @@ int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget cap = std::max(cap, floor); const int64_t remaining = n_target - n_computed; int64_t span = remaining; /* where this run of chunks must end */ - if (geo_.checkpoints()) { + if (geo_.checkpoints() && !geo_.window_ckpt) { const int64_t I = geo_.checkpoint_interval; span = std::min(span, ((n_computed / I) + 1) * I - n_computed); } @@ -978,6 +1012,36 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { * snapshot to resume from -- that is every recurrent layer continuing from whatever the * slot last held, and it reads as fluent text rather than as a failure. */ if (reuse > 0 && has_linear_state_ && h.checkpoint_slot < 0) reuse = 0; + /* A WINDOW SNAPSHOT COVERS THE TRUNK'S WINDOWED GROUPS -- at the checkpoint and nowhere + * else. The lookup clamped the hit to it (PrefixCache: a window counts as state there), + * so a hit with a slot is exactly at a snapshot; one without is no hit. */ + const bool win_hit = geo_.window_ckpt && kv_->has_window_snapshot() && reuse > 0 && + h.checkpoint_slot >= 0 && reuse == h.n_linear_tokens; + + /* THE WINDOWED-GROUP CLAMP — a prefix hit on a model whose OWN (trunk) KV includes a + * paged group the cache does not index. prefix.cpp skips RAD_KV_WINDOW groups — their + * blocks below the window are recycled, so no block list describes them; the comment + * there says a hit "costs the sequences ... a windowed layer whose cache starts where + * the hit ended" — this is that cost in KV corruption. The adopted blocks cover the + * cached groups ONLY, while `used = ctx_len + n_tokens` (batch.cpp) makes every + * windowed trunk layer read the positions below ctx_len that this sequence NEVER WROTE + * — and grab_block's min-heap (kv.cpp) hands this sequence the very blocks the most + * recent tenant wrote. The model then attends to the PREVIOUS REQUEST'S KV as its own + * prefix: fluent text carrying the last request's CONTENT. Zero the reuse; the whole + * prompt re-prefills, which is what a window snapshot (below) exists to avoid -- seconds + * to minutes of first-token time on a long agent turn. + * + * NOT the drafter's hole. A drafter's own group (bound at base_layer and above — see + * scheduler.h) is repaired by draft refill, which CAPS the hit so the recompute covers + * the drafter's window while the trunk reuses the rest; zeroing here would delete that + * design. The trunk's hole, which no tail-recompute can fix, is this clamp's own. */ + if (reuse > 0 && hit_holes_trunk_ && !win_hit) { + reuse = 0; + RAD_DEBUG("admit %llu: prefix hit %lld zeroed -- a trunk paged group is not " + "prefix-cached (windowed) and no window snapshot covers it; re-prefilling", + (unsigned long long)r.id, + (long long)h.n_attn_tokens); + } /* Claim the cached blocks. Without this the hit is only an accounting entry: the sequence * would skip computing those tokens and then attend to blocks it does not own. adopt() @@ -998,11 +1062,18 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { break; } } + /* The windowed groups start at the floor of the window behind the hit, in fresh + * blocks the entry's restore fills from the snapshot. */ + if (reuse > 0 && win_hit && kv_->seed_window(r.id, reuse) < 0) { + kv_->preempt(r.id); + reuse = 0; + } } r.n_computed = reuse; r.n_cached = reuse; - s.ckpt_src = (reuse > 0 && reuse == h.n_linear_tokens) ? h.checkpoint_slot : -1; + s.ckpt_src = (reuse > 0 && reuse == h.n_linear_tokens && + (has_linear_state_ || win_hit)) ? h.checkpoint_slot : -1; s.hit_attn = h.n_attn_tokens; } @@ -1026,7 +1097,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { /* THE CACHE GIVES WAY TO A NEW REQUEST as it does to a running one: with nothing running, * no other path would ever take blocks back from it, and the request would wait for good. */ int rounds = 0; - while (kv_->ensure(r.id, r.n_computed + want) < 0) { + while (kv_->ensure_from(r.id, r.n_computed + want, r.n_computed) < 0) { if (++rounds > 256 || !cfg_.prefix_cache || pc_->evict(256) <= 0) { rc = RAD_E_NOMEM; break; @@ -1217,7 +1288,7 @@ const RadBatch* Scheduler::step() { static const int kMaxEvictRounds = 256; int evict_rounds = 0; bool failed = false; - while (kv_->ensure(r.id, r.n_computed + want) < 0) { + while (kv_->ensure_from(r.id, r.n_computed + want, r.n_computed) < 0) { /* THE CACHE GIVES ITS BLOCKS BACK BEFORE A RUNNING REQUEST DOES. Everything the prefix * cache holds is a saving on work that has already been done once; everything a * running request holds is work in flight. Evicting first is therefore strictly the @@ -1429,7 +1500,7 @@ const RadBatch* Scheduler::step() { int64_t ckpt = -1; const int64_t grown = e.ckpt_slot < 0 && limit > had ? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt, r.checkpoint_at) : had; - if (grown > had && kv_->ensure(r.id, r.n_computed + grown) >= 0) { + if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) { e.n_tokens = (int32_t)grown; e.produces_token = (r.n_computed + grown >= s.seq_len()); if (ckpt > 0) { @@ -1681,7 +1752,7 @@ const RadBatch* Scheduler::step_next_locked() { const int32_t d = s.draft_next; const int64_t want = 1 + d; if (ctx_limit_ > 0 && ctx_up + want > ctx_limit_) return nullptr; - if (kv_->ensure(r.id, ctx_up + want) < 0) return nullptr; + if (kv_->ensure_from(r.id, ctx_up + want, r.n_computed) < 0) return nullptr; StepEntry n; n.req = &r; @@ -1822,6 +1893,10 @@ int Scheduler::commit(const StepResult& res) { if (e.is_prefill) { r.n_computed += e.n_tokens; + /* The chunk is committed: a window group gives its blocks below the window back now, + * not at this sequence's next ensure(), which may be steps away while others + * prefill. */ + kv_->trim_window(r.id, r.n_computed); step_prefill_tok_ += e.n_tokens; server::sink_prompt_progress(r.sink, r.n_computed, (int32_t)r.prompt.size(), r.n_cached); @@ -2158,7 +2233,8 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) { * unwritten in the head's layer for good. The same goes for a row too near the end of the * context for its rounds, whose last positions do not exist. */ if (can_draft && ctx_limit_ > 0 && head_max + *rounds > ctx_limit_) can_draft = false; - if (can_draft && kv_->ensure(r.id, head_max + *rounds) < 0) can_draft = false; + if (can_draft && kv_->ensure_from(r.id, head_max + *rounds, r.n_computed) < 0) + can_draft = false; /* THE HISTORY THIS STEP OWES, in two parts. Before the verified positions, the positions * the step computed whose next token the host holds -- a prefill chunk's prompt -- from @@ -2179,9 +2255,19 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) { const int64_t owed_end = e.produces_token ? vstart : (int64_t)e.ctx_len + e.n_tokens; int64_t hs = s.draft_filled > e.ctx_len ? s.draft_filled : (int64_t)e.ctx_len; if (hs > owed_end) hs = owed_end; - const int64_t lead = owed_end - hs; + int64_t lead = owed_end - hs; const int64_t verified = e.produces_token ? e.n_spec + 1 : 0; - const int64_t hist_n = lead + verified; + int64_t hist_n = lead + verified; + + /* A HEAD WITH NO CACHE OF ITS OWN IS OWED NO HISTORY (rad_drafter_shared_kv). Its one row + * is round 1's -- the committed position, whichever of the verified ones the card says it + * is -- and a sequence that does not draft has nothing to run at all. */ + if (serial_shared_) { + if (!can_draft) continue; + hs = vstart; + lead = 0; + hist_n = 1; + } if (!can_draft && hist_n <= 0) continue; /* nothing owed and nothing to draft */ @@ -2191,7 +2277,9 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) { m.card = e.card; m.hist_row = (int32_t)(base + (hs - e.ctx_len)); m.hist_n = (int32_t)hist_n; - m.hist_pos = hs; + /* The shared head's one row sits wherever the card's acceptance puts it; the host stages + * the furthest that can be, as it does for every round. */ + m.hist_pos = serial_shared_ ? head_max : hs; m.dev = e.produces_token; m.dev_tok = (int32_t)(base + (vstart - e.ctx_len)); m.dev_out = e.dev_out; @@ -2250,8 +2338,10 @@ const RadBatch* Scheduler::serial_batch(int round, int step) { e.card = m.card; e.n_tokens = round == 0 ? m.hist_n : 1; /* A round's position is the card's; the host stages the furthest it can be, which is what - * every host-side ceiling reads. The history's are known here exactly. */ - e.ctx_len = (int32_t)(round == 0 ? m.hist_pos : m.base_pos + (round - 1)); + * every host-side ceiling reads. The history's are known here exactly. A head with no + * cache of its own does not step forward, so neither does its ceiling. */ + e.ctx_len = (int32_t)(round == 0 ? m.hist_pos + : m.base_pos + (serial_shared_ ? 0 : round - 1)); e.n_spec = 0; /* One-based and constant: a head pass commits exactly the tokens it was handed. The head * issues no linear-state op, so nothing reads it; it is set rather than left at a value @@ -2409,7 +2499,8 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block /* The query block writes positions n_computed .. n_computed + block - 1, and none of them * may be at or past the end of the context. */ const bool ok_ctx = ctx_limit_ <= 0 || r.n_computed + block <= ctx_limit_; - const bool ok_kv = ok_room && ok_ctx && kv_->ensure(r.id, r.n_computed + block) >= 0; + const bool ok_kv = ok_room && ok_ctx && + kv_->ensure_from(r.id, r.n_computed + block, r.n_computed) >= 0; static const bool dbg = [] { const char* v = std::getenv("RADIANCE_DEBUG_DRAFT"); return v && *v && *v != '0'; }(); if (dbg) { diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index 9c4e7b1a..000cb4c6 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -191,8 +191,14 @@ public: /* The batch the last build produced for one rank; see BatchBuilder::batch_for. */ const RadBatch* batch_for(int rank) const { return builder_.batch_for(rank); } - /* The advance's view of that build on one rank; see BatchBuilder::advance_args. */ - AdvanceArgs advance_args(int rank) const { return builder_.advance_args(rank); } + /* The advance's view of that build on one rank; see BatchBuilder::advance_args. It carries + * the serial head's shape as well, which only the draft passes' modes read. */ + AdvanceArgs advance_args(int rank) const { + AdvanceArgs a = builder_.advance_args(rank); + a.shared_kv = serial_shared_ ? 1 : 0; + a.rot_shift = serial_rot_shift_; + return a; + } void fini(); /* ---------------------------------------------------------- off the step path */ @@ -505,6 +511,18 @@ private: * also skips on a block-size mismatch. A bound like this lives in exactly one place; a second * copy is free to drift out of step with the first. */ bool hit_holes_draft_ = true; + /* DOES A HIT HOLE THE TRUNK ITSELF? hit_holes_draft_ is the drafter's guard, and draft_refill_ + * repairs a drafter hole by recomputing the prompt's TAIL. A TRUNK group the cache does not + * index admits no such repair: the adopted blocks cover the cached groups only, while the + * windowed trunk layers read the positions below ctx_len this sequence never wrote — the KV of + * whoever held these blocks last. So a trunk hole refuses the hit outright. + * + * THE TRUNK IS WHICH GROUPS? The one a drafter borrows is bound at `base_layer` and above — + * the drafter's layers run after the trunk's (rad_bind_layer_kv at the drafter declare), so a + * group with a bound layer below meta.n_layers belongs to the trunk and a hit must cover it; + * a drafter's own group is the refill's business, not this clamp's. Read off the Program, + * which carries both the bindings and the trunk's layer count. */ + bool hit_holes_trunk_ = false; /* DRAFT REFILL. Where a hit leaves a hole in a WINDOWED block drafter's cache, the drafter is * declined until its window has slid past the hole, which on the follow-up turn of a chat -- * the turn a prefix hit is for -- is most or all of the reply. So the hit is ended one window @@ -514,6 +532,12 @@ private: * that point would give back more than two windows is kept whole. The drafter's window, or 0 * where no hit can leave such a hole. */ int64_t draft_refill_ = 0; + /* A SERIAL HEAD WITH NO CACHE OF ITS OWN (rad_drafter_shared_kv), off the Program at init. It + * owes no history, so serial_begin gives it one row a drafting sequence and none to a sequence + * that does not draft, and its rounds stay at the committed position (advance.h). False and 0 + * for every other drafter, whose passes are staged exactly as before. */ + bool serial_shared_ = false; + int32_t serial_rot_shift_ = 0; BatchBuilder builder_; DraftController draft_; diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp index 528c59c4..d86943ee 100644 --- a/core/text/chatfmt.cpp +++ b/core/text/chatfmt.cpp @@ -13,6 +13,7 @@ #include #include +#include #include #include #include @@ -45,6 +46,75 @@ bool starts_with(const std::string& s, const std::string& p) { std::string show(const std::string& s) { return nlohmann::json(s).dump(); } +int refuse(std::string* why, const std::string& s) { + if (why) *why = s; + return RAD_E_UNSUPPORTED; +} + +/* A byte that begins a bare word or a JSON value, or is the object's own punctuation. */ +bool object_byte(unsigned char c) { + return c == 0 || std::isalnum(c) || is_ws(c) || std::strchr("-+._'\"{}[],:", (int)c) != nullptr; +} + +/* An argument object, as the streaming parser reads it (chatparse.cpp). Where a key or a value + * may begin, it tells three literals apart by their first bytes: a dialect string's opener, and + * the call's close and end, which a reply that leaves its object unclosed writes there. None may + * begin another. A bare word ends at the object's punctuation or at the call's close; one + * automaton finds both in the order they start only when the close holds none of it. */ +int object_check(const ChatFormat& f, std::string* why) { + const std::string& so = f.object_string_open; + const std::string& sc = f.object_string_close; + if (so.empty() != sc.empty()) + return refuse(why, "object_string_open and object_string_close are set together or not " + "at all"); + if (!so.empty()) { + if (trim_ws(so) != so || trim_ws(sc) != sc) + return refuse(why, "an object string delimiter may not begin or end with " + "whitespace"); + if (object_byte((unsigned char)so[0])) + return refuse(why, "object_string_open " + show(so) + " begins with a byte that also " + "begins a bare word, a JSON value or the object's punctuation"); + } + std::vector lits; + if (!so.empty()) lits.push_back(so); + const std::string cc = trim_ws(f.call_close), ce = trim_ws(f.call_end); + for (const std::string* s : { &cc, &ce }) { + if (s->empty()) continue; + for (char c : *s) + if (std::strchr(",:{}[]\"", c)) + return refuse(why, "the call's close " + show(*s) + " holds " + + show(std::string(1, c)) + ", which is the argument object's " + "punctuation"); + if (std::find(lits.begin(), lits.end(), *s) == lits.end()) lits.push_back(*s); + else if (!so.empty() && *s == so) + return refuse(why, show(*s) + " both opens an object string and closes the call"); + } + for (size_t i = 0; i < lits.size(); ++i) + for (size_t j = 0; j < lits.size(); ++j) + if (i != j && (starts_with(lits[i], lits[j]) || occurs_inside(lits[j], lits[i]))) + return refuse(why, show(lits[j]) + " and " + show(lits[i]) + " cannot be told " + "apart inside an argument object"); + return RAD_OK; +} + +/* Content is scanned for a later reasoning block's opener and for a stray close beside the call + * openers, in one automaton, which reports them in the order they start only when none occurs + * inside another or begins it. */ +int reasoning_anywhere_check(const ChatFormat& f, std::string* why) { + if (!f.reasoning_anywhere) return RAD_OK; + std::vector d = { trim_ws(f.reasoning_open), trim_ws(f.reasoning_close) }; + if (f.has_tools()) { + if (!f.call_open.empty()) d.push_back(trim_ws(f.call_open)); + d.push_back(f.name_prefix); + } + for (size_t i = 0; i < d.size(); ++i) + for (size_t j = 0; j < d.size(); ++j) + if (i != j && (starts_with(d[i], d[j]) || occurs_inside(d[j], d[i]))) + return refuse(why, show(d[j]) + " and " + show(d[i]) + " cannot be told apart in " + "content, which a reasoning block may open anywhere in"); + return RAD_OK; +} + } /* namespace */ /* ================================================================== validity */ @@ -61,16 +131,24 @@ int chat_format_check(const ChatFormat& f, std::string* why) { return no("reasoning_close is only whitespace"); if ((uint32_t)f.reasoning_in_prompt > (uint32_t)ChatThink::Never) return no("reasoning_in_prompt is not a RAD_CHAT_THINK_* value"); + if ((uint32_t)f.args_form > (uint32_t)ChatArgs::Object) + return no("args_form is not a RAD_CHAT_ARGS_* value"); + /* A block that opens later in the reply is found by its opener, in content. */ + if (f.reasoning_anywhere && (!f.has_reasoning() || trim_ws(f.reasoning_open).empty())) + return no("reasoning_anywhere needs a reasoning block with an opener"); if (!f.has_tools()) { for (const std::string* s : { &f.section_open, &f.section_close, &f.call_separator, &f.call_open, &f.call_close, &f.name_suffix, &f.call_end, &f.arg_prefix, &f.arg_name_suffix, &f.arg_value_prefix, - &f.arg_value_suffix }) + &f.arg_value_suffix, &f.object_string_open, + &f.object_string_close }) if (!s->empty()) return no("tool-call delimiters are set but name_prefix is empty"); + if (f.object_args() || f.object_bare_keys) + return no("an argument object is described but name_prefix is empty"); if (!f.reasoning_breaks.empty()) return no("reasoning_breaks without tool calls"); if (!f.triggers.empty()) return no("grammar triggers without tool calls"); - return RAD_OK; + return reasoning_anywhere_check(f, why); } if (!f.section_open.empty() || !f.section_close.empty()) @@ -81,22 +159,43 @@ int chat_format_check(const ChatFormat& f, std::string* why) { ") is not read by the streaming parser; tagged calls separate on whitespace"); if (f.call_open.empty() && !f.call_close.empty()) return no("call_close without call_open"); - if (f.name_suffix.empty() || trim_ws(f.name_suffix).empty()) - return no("name_suffix must end the function name with something besides whitespace"); - if (is_ws((unsigned char)f.name_suffix[0])) - return no("name_suffix " + show(f.name_suffix) + " may not begin with whitespace"); - if (f.call_end.empty()) return no("call_end is empty: a call must close with its own tag"); - if (f.arg_prefix.empty()) return no("arg_prefix is empty"); - if (f.arg_value_suffix.empty()) return no("arg_value_suffix is empty"); - if (f.arg_name_suffix.empty() && f.arg_value_prefix.empty()) - return no("nothing ends an argument name: arg_name_suffix and arg_value_prefix are empty"); - if (!f.arg_name_suffix.empty() && !f.arg_value_prefix.empty()) - return no("arg_name_suffix and arg_value_prefix are both set; the streaming parser reads " - "one delimiter between an argument's name and its value"); - if (f.string_value != ChatValue::Raw && f.string_value != ChatValue::Cdata) - return no("string_value must be RAD_CHAT_VALUE_RAW or RAD_CHAT_VALUE_CDATA"); - if ((uint32_t)f.other_value > (uint32_t)ChatValue::Json) - return no("other_value is not a RAD_CHAT_VALUE_* value"); + const bool object = f.object_args(); + /* An object's own `{` may be what ends the name; anything else needs its suffix. */ + if (!object || !f.name_suffix.empty()) { + if (f.name_suffix.empty() || trim_ws(f.name_suffix).empty()) + return no("name_suffix must end the function name with something besides whitespace"); + if (is_ws((unsigned char)f.name_suffix[0])) + return no("name_suffix " + show(f.name_suffix) + " may not begin with whitespace"); + } + if (!object) { + if (f.call_end.empty()) return no("call_end is empty: a call must close with its own tag"); + if (f.arg_prefix.empty()) return no("arg_prefix is empty"); + if (f.arg_value_suffix.empty()) return no("arg_value_suffix is empty"); + if (f.arg_name_suffix.empty() && f.arg_value_prefix.empty()) + return no("nothing ends an argument name: arg_name_suffix and arg_value_prefix are " + "empty"); + if (!f.arg_name_suffix.empty() && !f.arg_value_prefix.empty()) + return no("arg_name_suffix and arg_value_prefix are both set; the streaming parser " + "reads one delimiter between an argument's name and its value"); + if (f.string_value != ChatValue::Raw && f.string_value != ChatValue::Cdata) + return no("string_value must be RAD_CHAT_VALUE_RAW or RAD_CHAT_VALUE_CDATA"); + if ((uint32_t)f.other_value > (uint32_t)ChatValue::Json) + return no("other_value is not a RAD_CHAT_VALUE_* value"); + if (!f.object_string_open.empty() || !f.object_string_close.empty() || + f.object_bare_keys) + return no("the object_* fields describe an argument object, and args_form is " + "RAD_CHAT_ARGS_TAGGED"); + } else { + for (const std::string* s : { &f.arg_prefix, &f.arg_name_suffix, &f.arg_value_prefix, + &f.arg_value_suffix }) + if (!s->empty()) + return no("the arg_* fields describe tagged arguments, and args_form is " + "RAD_CHAT_ARGS_OBJECT"); + if (!f.call_end.empty() && trim_ws(f.call_end).empty()) + return no("call_end is only whitespace"); + const int st = object_check(f, why); + if (st < 0) return st; + } /* A wrapped format's content is scanned for the wrapper's core and for name_prefix alone, * which opens a call written without its wrapper; the two must not be confusable. */ @@ -127,16 +226,19 @@ int chat_format_check(const ChatFormat& f, std::string* why) { return no("reasoning break " + show(b) + " overlaps reasoning_close " + show(close)); } - /* Inside a call the next tag is an argument or the close, and the close is recognised by its - * core as well: the whitespace around it is optional when a reply leaves the format. */ - const std::string end = trim_ws(f.call_end); - if (end.empty()) return no("call_end is only whitespace"); - for (const std::string* e : { &f.call_end, &end }) - if (starts_with(f.arg_prefix, *e) || starts_with(*e, f.arg_prefix) || - occurs_inside(f.arg_prefix, *e) || occurs_inside(*e, f.arg_prefix)) - return no("arg_prefix " + show(f.arg_prefix) + " and call_end " + show(f.call_end) + - " cannot be told apart"); - return RAD_OK; + if (!object) { + /* Inside a call the next tag is an argument or the close, and the close is recognised by + * its core as well: the whitespace around it is optional when a reply leaves the + * format. */ + const std::string end = trim_ws(f.call_end); + if (end.empty()) return no("call_end is only whitespace"); + for (const std::string* e : { &f.call_end, &end }) + if (starts_with(f.arg_prefix, *e) || starts_with(*e, f.arg_prefix) || + occurs_inside(f.arg_prefix, *e) || occurs_inside(*e, f.arg_prefix)) + return no("arg_prefix " + show(f.arg_prefix) + " and call_end " + + show(f.call_end) + " cannot be told apart"); + } + return reasoning_anywhere_check(f, why); } /* ================================================================== the plugin's declaration */ @@ -183,6 +285,11 @@ int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string* f.other_value = (ChatValue)c.other_value; f.value_newlines = c.value_newlines != 0; list(c.triggers, c.n_triggers, &f.triggers); + f.args_form = (ChatArgs)c.args_form; + f.object_string_open = s(c.object_string_open); + f.object_string_close = s(c.object_string_close); + f.object_bare_keys = c.object_bare_keys != 0; + f.reasoning_anywhere = c.reasoning_anywhere != 0; *out = std::move(f); return RAD_OK; } @@ -286,13 +393,23 @@ int chat_format_from_template(const std::string& jinja, const std::string& bos, std::string chat_format_describe(const ChatFormat& f) { std::string s = f.name + ":"; if (f.has_reasoning()) - s += " reasoning " + show(f.reasoning_open) + ".." + show(f.reasoning_close); + s += " reasoning " + show(f.reasoning_open) + ".." + show(f.reasoning_close) + + (f.reasoning_anywhere ? " anywhere" : ""); else s += " no reasoning"; - if (f.has_tools()) { + if (f.has_tools() && f.object_args()) { + s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) + + " {OBJECT"; + if (!f.object_string_open.empty()) + s += ", strings " + show(f.object_string_open) + ".." + show(f.object_string_close); + if (f.object_bare_keys) s += ", bare keys"; + s += "} " + show(f.call_end) + show(f.call_close); + } else if (f.has_tools()) { s += "; calls " + show(f.call_open) + show(f.name_prefix) + "NAME" + show(f.name_suffix) + " " + show(f.arg_prefix) + "ARG" + show(f.arg_name_suffix) + show(f.arg_value_prefix) + "VALUE" + show(f.arg_value_suffix) + " " + show(f.call_end) + show(f.call_close); + } + if (f.has_tools()) { if (!f.triggers.empty()) { s += "; grammar on"; for (const std::string& t : f.triggers) s += " " + show(t); @@ -310,7 +427,8 @@ std::vector chat_format_markers(const ChatFormat& f) { for (const std::string* s : { &f.reasoning_open, &f.reasoning_close, &f.section_open, &f.section_close, &f.call_open, &f.call_close, &f.name_prefix, &f.name_suffix, &f.call_end, &f.arg_prefix, &f.arg_name_suffix, - &f.arg_value_prefix, &f.arg_value_suffix }) { + &f.arg_value_prefix, &f.arg_value_suffix, + &f.object_string_open, &f.object_string_close }) { const std::string t = trim_ws(*s); if (!t.empty() && std::find(out.begin(), out.end(), t) == out.end()) out.push_back(t); } @@ -538,6 +656,46 @@ void add_json_rules(const common_grammar_builder& b) { "json-null"); } +/* THE ARGUMENT OBJECT of the object family, in its dialect: JSON, or strings between the + * declared delimiters and keys written bare. As llama.cpp's own Gemma 4 grammar does, it fixes + * the syntax and leaves the values to the model: a tool's schema says what JSON a value must be, + * and the dialect is not JSON, so the schema converter has nothing to say about it. Whitespace + * goes where the dialect's writers put it -- after a separator and inside the brackets -- and + * nowhere else. */ +void add_object_rules(const common_grammar_builder& b, const ChatFormat& f) { + const std::string& so = f.object_string_open; + if (!so.empty()) + b.add_rule("obj-string", gbnf_format_literal(so) + " " + + until_pattern({ f.object_string_close }) + " " + + gbnf_format_literal(f.object_string_close)); + else + b.add_rule("obj-string", "\"\\\"\" ( [^\"\\\\] | \"\\\\\" ( [\"\\\\/ bfnrt] | \"u\" " + "[0-9a-fA-F]{4} ) )* \"\\\"\""); + b.add_rule("obj-number", "\"-\"? (\"0\" | [1-9] [0-9]*) (\".\" [0-9]+)? ([eE] [+-]? [0-9]+)?"); + /* A dialect with strings of its own still gets a value in Python's quotes, `'...'`, which + * is how Gemma 4 writes arguments it was handed as JSON (measured). Refused, the model + * takes the next token the grammar allows -- a `-` -- and every such string becomes a + * number; the parser reads the quoted text verbatim but for an escaped quote. */ + const char* sq = so.empty() ? "" : " | obj-sqstring"; + if (!so.empty()) b.add_rule("obj-sqstring", "\"'\" ( [^'\\\\] | \"\\\\\" [^\\x00] )* \"'\""); + b.add_rule("obj-value", std::string("obj-object | obj-array | obj-string") + sq + + " | obj-number | \"true\" | \"false\" | \"null\""); + b.add_rule("obj-array", "\"[\" space (\"]\" | obj-value (\",\" space obj-value)* space " + "\"]\")"); + if (f.object_bare_keys) { + /* A bare key: no whitespace, no punctuation, and not the string opener's first byte. */ + std::string cls = "[^ \\t\\n\\r:,{}\\[\\]\""; + if (!so.empty()) cls += class_char((unsigned char)so[0]); + cls += "]+"; + b.add_rule("obj-key", cls + " | obj-string"); + } else { + b.add_rule("obj-key", "obj-string"); + } + b.add_rule("obj-member", "obj-key \":\" space obj-value"); + b.add_rule("obj-object", "\"{\" space (\"}\" | obj-member (\",\" space obj-member)* space " + "\"}\")"); +} + G optspace(const std::string& tag) { size_t a = 0, b = tag.size(); while (a < b && is_ws((unsigned char)tag[a])) ++a; @@ -644,6 +802,18 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat const auto& fn = tool.at("function"); const std::string name = fn.at("name"); if (!req.only_tool.empty() && name != req.only_tool) continue; + if (f.object_args()) { + /* The name, then the object; the object's own closing brace may be all + * that ends the call. */ + G open = wrap(seq({ lit(f.name_prefix), wrap(lit(name)), lit(f.name_suffix) })); + G func = f.call_end.empty() + ? seq({ open, rule_ref("obj-object") }) + : seq({ open, rule_ref("obj-object"), space(), + wrap(lit(f.call_end)) }); + b.add_rule(rule_name("tool-" + name), render(func)); + choices.push_back(rule_ref(rule_name("tool-" + name))); + continue; + } auto params = fn.contains("parameters") ? fn.at("parameters") : ojson::object(); const auto properties = params.contains("properties") ? params.at("properties") : ojson::object(); @@ -704,7 +874,8 @@ int chat_format_grammar(const ChatFormat& f, const ChatGrammarRequest& req, Chat if (choices.empty() && !req.only_tool.empty()) throw std::invalid_argument("no tool named \"" + req.only_tool + "\" to call"); if (typed) add_json_rules(b); - if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix })); + if (!choices.empty() && f.object_args()) add_object_rules(b, f); + else if (!choices.empty()) b.add_rule("until-suffix", until_pattern({ f.arg_value_suffix })); G choice = alt(choices); G calls; diff --git a/core/text/chatfmt.h b/core/text/chatfmt.h index 9bfe7fa0..b81ab275 100644 --- a/core/text/chatfmt.h +++ b/core/text/chatfmt.h @@ -32,10 +32,21 @@ * the raw text (optionally CDATA-wrapped), any other type is JSON, and text that does not parse as * JSON is taken raw -- a model writing into an XML tag writes Python as often as JSON. * - * The analyser also recognises formats outside this family (a JSON object per call, JSON - * arguments inside a tag, call ids). For those chat_format_from_template keeps the reasoning split - * and names why tool calls are refused, and a model that needs one gets it by adding the shape to - * the parser, not by a fallback. */ + * THE OBJECT FAMILY writes a call as its name and one object holding the arguments + * (ChatArgs::Object): + * + * Gemma 4 <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3} + * + * The object is JSON or a dialect of it -- strings between two declared delimiters with their + * text verbatim, keys written bare -- and the arguments a client receives are that object in + * JSON. Here the values carry their own types, so no schema is consulted to read them; a bare + * word that is no JSON literal or number is read as a string, as a typed argument that is not + * JSON is in the tagged family. + * + * The analyser also recognises formats outside these families (a JSON object per call with its + * name inside it, call ids). For those chat_format_from_template keeps the reasoning split and + * names why tool calls are refused, and a model that needs one gets it by adding the shape to the + * parser, not by a fallback. */ #pragma once #include "rad_internal.h" @@ -68,6 +79,12 @@ enum class ChatThink : uint32_t { Never = 2, /* the model opens its own block, if any */ }; +/* How a call's arguments are written. The numbering is the ABI's (RAD_CHAT_ARGS_*). */ +enum class ChatArgs : uint32_t { + Tagged = 0, /* each argument in its own tags: arg_prefix NAME .. VALUE arg_value_suffix */ + Object = 1, /* one object after the name: `{` key `:` value, ... `}` */ +}; + struct ChatFormat { std::string name; /* for logs: "plugin:" or "template" */ @@ -83,6 +100,10 @@ struct ChatFormat { * Must name the call opener (`call_open`) when non-empty. */ std::vector reasoning_breaks; ChatThink reasoning_in_prompt = ChatThink::FromPrompt; + /* A block may also open later in the reply -- after the answer, between calls -- and is read + * as reasoning there; a close with no block open is dropped. Gemma 4 writes an empty block + * after its answer now and then, and a lone close. Needs `reasoning_open`. */ + bool reasoning_anywhere = false; /* ------------------------------------------------------------------ tool calls * `name_prefix` is what opens a call (after `call_open`, when there is one). Empty means the @@ -94,8 +115,18 @@ struct ChatFormat { /* Around EACH call: "\n", "". When set, a call written without it -- * name_prefix alone -- is still read as a call, leniently (chatparse.h). */ std::string call_open, call_close; - std::string name_prefix, name_suffix; /* "\n" */ - std::string call_end; /* "\n" */ + /* "\n". In the object family name_suffix may be empty: the name then ends + * where the object begins, at its `{`. */ + std::string name_prefix, name_suffix; + std::string call_end; /* "\n"; may be empty for an object */ + + /* How the arguments are written. Object: the arg_* fields below are empty, and these three + * describe the object's dialect -- a string delimiter besides JSON's `"`, between which the + * text is verbatim ("<|\"|>" twice for Gemma 4; empty for JSON strings only), and whether a + * key may be written bare. */ + ChatArgs args_form = ChatArgs::Tagged; + std::string object_string_open, object_string_close; + bool object_bare_keys = false; std::string arg_prefix; /* "\n" (MiniCPM: empty, the value prefix ends it) */ @@ -115,6 +146,7 @@ struct ChatFormat { bool has_reasoning() const { return !reasoning_close.empty(); } bool has_tools() const { return !name_prefix.empty(); } + bool object_args() const { return args_form == ChatArgs::Object; } }; /* Can the streaming parser run this format? RAD_OK, or RAD_E_UNSUPPORTED with *why naming the diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp index ae2f9803..1d2dd59b 100644 --- a/core/text/chatparse.cpp +++ b/core/text/chatparse.cpp @@ -744,6 +744,30 @@ struct ReplyFormat::Impl { std::string cc_core; Dfa think, think_breaks, text, arg_name, value, junk, arg_name_loose, value_loose; size_t longest = 0; /* the longest delimiter */ + + /* THE OBJECT FAMILY. `object`: a call's arguments are one object; `ns_object`: the object's + * own `{` is what ends the name (name_suffix empty), and ns_core is "{". */ + bool object = false, ns_object = false; + /* Where a key or a value may begin, besides the object's punctuation: the dialect string's + * opener, and the call's close and end -- a reply that leaves its object unclosed writes them + * there. Read anchored, by their first bytes (chat_format_check keeps them apart). */ + enum : uint8_t { LitString, LitClose, LitEnd }; + std::vector obj_lits; + std::vector obj_lit_kind; + /* A dialect string runs to its close. A bare value ends at `,` `}` `]` and a bare key at `:` + * `,` `}` -- patterns 0..2 -- or at the call's close or end, which follow at the indices + * below (-1: none). */ + Dfa obj_str, obj_bare, obj_key; + /* A value the model opened with a plain `"` -- or `'` (obj_sqstr) -- in a dialect that has + * strings of its own: read as that dialect's strings are, verbatim, to a quote the object's + * syntax goes on after. Patterns: the quote, the escaped quote, the dialect's string close, + * the call's close (if any). */ + Dfa obj_qstr, obj_sqstr; + int bare_cc = -1, bare_ce = -1, key_cc = -1, key_ce = -1; + + /* REASONING ANYWHERE: content is scanned for a later block's opener and a stray close too, + * after the call openers (text_think) or alone when the request has no calls (think_only). */ + Dfa text_think, think_only; }; ReplyFormat::ReplyFormat() : impl_(std::make_unique()) {} @@ -773,6 +797,12 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr if (f.call_open.empty()) m.openers = { f.name_prefix }; else m.openers = { m.co_core, f.name_prefix }; m.name_end = f.arg_name_suffix.empty() ? f.arg_value_prefix : f.arg_name_suffix; + m.object = f.has_tools() && f.object_args(); + if (m.object && f.name_suffix.empty()) { + m.ns_object = true; + m.ns_core = "{"; + m.ns_trail.clear(); + } if (f.has_reasoning()) { m.think.build({ m.close_core }); @@ -780,7 +810,50 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr for (const std::string& s : f.reasoning_breaks) b.push_back(s); m.think_breaks.build(b); } - if (f.has_tools()) { + if (f.reasoning_anywhere && f.has_reasoning()) { + std::vector t; + if (f.has_tools()) t = m.openers; + t.push_back(m.open_core); + t.push_back(m.close_core); + m.text_think.build(t); + m.think_only.build({ m.open_core, m.close_core }); + } + if (m.object) { + m.text.build(m.openers); + std::string trail; + split_ws(f.call_close, &m.cc_core, &trail); + std::vector bare{ ",", "}", "]" }, key{ ":", ",", "}" }; + if (!f.object_string_open.empty()) { + m.obj_lits.push_back(f.object_string_open); + m.obj_lit_kind.push_back(Impl::LitString); + /* The call's close inside a string: where a model left the string unclosed. */ + std::vector sp{ f.object_string_close }; + std::vector qp{ "\"", "\\\"", f.object_string_close }; + std::vector sq{ "'", "\\'", f.object_string_close }; + if (!m.cc_core.empty()) { + sp.push_back(m.cc_core); + qp.push_back(m.cc_core); + sq.push_back(m.cc_core); + } + m.obj_str.build(sp); + m.obj_qstr.build(qp); + m.obj_sqstr.build(sq); + } + if (!m.cc_core.empty()) { + m.obj_lits.push_back(m.cc_core); + m.obj_lit_kind.push_back(Impl::LitClose); + m.bare_cc = (int)bare.size(); bare.push_back(m.cc_core); + m.key_cc = (int)key.size(); key.push_back(m.cc_core); + } + if (!m.end_core.empty() && m.end_core != m.cc_core) { + m.obj_lits.push_back(m.end_core); + m.obj_lit_kind.push_back(Impl::LitEnd); + m.bare_ce = (int)bare.size(); bare.push_back(m.end_core); + m.key_ce = (int)key.size(); key.push_back(m.end_core); + } + m.obj_bare.build(bare); + m.obj_key.build(key); + } else if (f.has_tools()) { m.text.build(m.openers); m.arg_name.build({ m.name_end }); m.value.build({ f.arg_value_suffix }); @@ -800,7 +873,8 @@ int ReplyFormat::compile(const ChatFormat& f, std::shared_ptr const std::string* const delims[] = { &f.reasoning_open, &f.reasoning_close, &f.call_open, &f.call_close, &f.name_prefix, &f.name_suffix, &f.call_end, &f.arg_prefix, &m.name_end, - &f.arg_value_suffix }; + &f.arg_value_suffix, &f.object_string_open, + &f.object_string_close }; for (const std::string* s : delims) m.longest = std::max(m.longest, s->size()); for (const std::string& s : f.reasoning_breaks) m.longest = std::max(m.longest, s.size()); *out = std::move(r); @@ -831,6 +905,9 @@ struct ReplyParser::Impl { bool calls = false; /* the request sent tools and the format has calls */ bool breaks = false; /* an unclosed reasoning block ends at a call */ bool pure = false; /* no reasoning, calls or document: every byte is content */ + /* A reasoning block may open later in the reply too (ChatFormat::reasoning_anywhere), and + * this request extracts reasoning. */ + bool anywhere = false; std::vector tools; std::unordered_map by_name; std::vector terminators; @@ -897,9 +974,10 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse optional.push_back(pname); } /* A name the argument's own delimiter could end early would be read as a - * different name. */ + * different name. An object's keys are delimited by its own punctuation, and + * one that holds it is written as a string. */ const std::string probe = pname + F.name_end; - if (probe.find(F.name_end) != pname.size()) { + if (!F.object && probe.find(F.name_end) != pname.size()) { *why = "parameter '" + pname + "' of tool '" + t.name + "' contains '" + F.name_end + "', which this model's tool-call format uses to end an " "argument name"; @@ -909,7 +987,8 @@ static int bind_tools(const ReplyFormat::Impl& F, const ojson& tools, ReplyParse } t.arms.insert(t.arms.end(), optional.begin(), optional.end()); if (t.name.find(F.ns_core) != std::string::npos || - (t.name + F.f.name_suffix).find(F.f.name_suffix) != t.name.size()) { + (!F.ns_object && + (t.name + F.f.name_suffix).find(F.f.name_suffix) != t.name.size())) { *why = "tool '" + t.name + "' has a name containing '" + F.ns_core + "', which this model's tool-call format uses to end a function name"; return RAD_E_INVAL; @@ -949,6 +1028,8 @@ int ReplyParser::create(std::shared_ptr fmt, const ReplyOptio P.calls = want_calls && !opt.response_format; P.breaks = want_calls && F.f.has_reasoning() && !F.f.reasoning_breaks.empty(); P.pure = !F.f.has_reasoning() && !want_calls && !opt.response_format; + P.anywhere = F.f.reasoning_anywhere && F.f.has_reasoning() && opt.extract_reasoning && + !opt.response_format; if (F.f.has_reasoning()) { switch (F.f.reasoning_in_prompt) { @@ -1004,6 +1085,19 @@ enum class St : uint8_t { RfClose, /* "```" */ RfEnd, /* after the closing fence */ RfRaw, /* a reply that is not the document it was asked for: content */ + ObjStart, /* after a name_suffix: whitespace, then the argument object's `{` */ + ObjKey, /* where a key may begin, or the object's `}` */ + ObjKeyBare, /* a bare key, to its `:` */ + ObjColon, /* after a quoted key: whitespace, then `:` */ + ObjValue, /* where a value may begin, or an empty array's `]` */ + ObjLit, /* the dialect's string opener, or the call's close or end, being matched */ + ObjStr, /* a dialect string, to its close */ + ObjQStr, /* a value opened with a plain quote in a dialect with strings of its own */ + ObjQLook, /* after a plain quote there: does the object's syntax go on? */ + ObjJStr, /* a JSON string, to its quote */ + ObjBare, /* a bare value: a number, a literal, or a word read as a string */ + ObjAfter, /* after a value: whitespace, then `,` or a closing bracket */ + ObjEnd, /* after the object: whitespace, then call_end */ }; /* A function name the grammar does not know is still read as a call, up to this long. */ @@ -1018,8 +1112,20 @@ struct ReplyStream::Impl { explicit Impl(const ReplyParser::Impl& p) : P(p), F(p.fmt->impl()) { content.init(P.terminators.empty() ? nullptr : &P.terms, &P.terminators); st = P.pure ? St::Text : St::LeadWs; + if (P.anywhere) { + text_dfa = P.calls ? &F.text_think : &F.think_only; + n_open = P.calls ? F.openers.size() : 0; + } else if (P.calls) { + text_dfa = &F.text; + n_open = F.openers.size(); + } } + /* What content is scanned with: the call openers when calls are on, then -- reasoning + * anywhere -- a later block's opener and a stray close. Null: content is every byte. */ + const Dfa* text_dfa = nullptr; + size_t n_open = 0; + ReplyMessage msg; ContentOut content; bool think_text = false; /* the reasoning has had a non-blank byte */ @@ -1062,6 +1168,28 @@ struct ReplyStream::Impl { size_t vs_pos = 0; bool fenced = false; + /* THE ARGUMENT OBJECT being read: its open brackets, whether a key (rather than a value) is + * being read, a separator read but not yet written -- it is written only once the next + * member shows the object goes on, so a trailing one never reaches the JSON -- whether the + * container was just opened, and whether a key's `:` went out with no value yet. */ + std::vector ostack; + bool okey = false, ocomma = false, ofirst = false, vpending = false; + /* A bare value's first bytes, to tell at its end whether it was a JSON number or literal -- + * which the grammar admits -- or a word read as a string, which it does not. */ + std::string bare_txt; + /* A JSON string's escape being read -- the backslash, and a "u" escape's four hex digits, + * in vheld -- and a high surrogate's escape, held until the low one shows it is a pair. */ + std::string jhi; + /* INSIDE A STRING: its trailing run of whitespace, closing brackets and quotes, held -- the + * brackets are the object's own if the call's close follows (srun) -- the quotes and + * backticks it has written (nq, nb), the bytes after a plain quote while they decide what it + * was (qtail), and how a plain-quoted value writes its quotes: 0 not yet seen, 1 as \" (one + * is unescaped), 2 as they are. */ + std::string srun, qtail; + size_t nq = 0, nb = 0, ns = 0; + uint8_t qmode = 0; + char qc = '"'; + /* published offsets, for the deltas */ size_t sent_r = 0, sent_c = 0, sent_a = 0; int cur = -1; /* the channel last published: 0 r, 1 c, 2 args */ @@ -1202,7 +1330,7 @@ struct ReplyStream::Impl { bool declared_prefix(std::string_view n) const { for (const Tool& t : P.tools) { - const std::string full = t.name + F.f.name_suffix; + const std::string full = t.name + (F.ns_object ? F.ns_core : F.f.name_suffix); if (full.size() >= n.size() && full.compare(0, n.size(), n) == 0) return true; } return false; @@ -1283,14 +1411,307 @@ struct ReplyStream::Impl { cur = -1; event(ReplyEvent::CallBegin, (uint32_t)msg.calls.size() - 1, msg.calls.back().name); depth = 0; in_str = false; esc = false; - args_out("{"); argc = 0; ++calls; att.clear(); post_call = false; + if (F.object) { + /* The arguments are the object's, and its `{` is written now: a reply that ends + * here is a call with no arguments yet, as in the tagged family. */ + obj_out("{"); + ostack.assign(1, '{'); + okey = ocomma = vpending = false; + ofirst = true; + jhi.clear(); + st = F.ns_object ? St::ObjKey : St::ObjStart; + return; + } + args_out("{"); st = St::Body; } + /* ------------------------------------------------------------ the argument object + * + * The object of the object family, read as it streams and written as JSON as it is read: + * brackets and separators as they come, a key as soon as its `:` shows it is one, a string + * as its bytes arrive, and a bare value as the tagged family writes a typed one (ValueOut, + * Raw): held while it could still be a literal or a number, else a string. What the dialect + * spells otherwise -- its string delimiters, its bare keys -- is respelled; what leaves it + * -- a missing separator, a trailing one, a bracket of the wrong kind, an object the call's + * close cuts off -- is repaired locally and said so (strict). The arguments a closed call + * reports are JSON whatever was written. */ + + void obj_out(std::string_view s) { + if (s.empty()) return; + touch(2); + msg.calls.back().arguments.append(s.data(), s.size()); + } + void obj_flush() { if (!scratch.empty()) { obj_out(scratch); scratch.clear(); } } + + /* A member or an element begins: the separator before it, if one was read, goes out now. */ + void obj_sep() { + if (ocomma) { obj_out(","); ocomma = false; } + ofirst = false; + } + + /* The outermost bracket closed: what follows the object. */ + void obj_done() { + if (!F.end_core.empty()) { lpos = 0; lhold.clear(); st = St::ObjEnd; } + else end_call(); + } + + /* A closing bracket where a key, a value or a separator may stand. A separator before it is + * dropped, and a bracket of the other kind closes the open container all the same. */ + void obj_close_bracket(char c) { + if (ocomma) { lenient(); ocomma = false; } + const char top = ostack.back(); + if ((top == '{') != (c == '}')) lenient(); + if (vpending) { lenient(); obj_out("null"); vpending = false; } + ostack.pop_back(); + ofirst = false; + obj_out(top == '{' ? "}" : "]"); + if (ostack.empty()) obj_done(); + else st = St::ObjAfter; + } + + /* The punctuation after a value. */ + void obj_struct(char c) { + if (c != ',') { obj_close_bracket(c); return; } + if (ocomma) lenient(); /* `,,`: one separator */ + ocomma = true; + ofirst = false; + okey = ostack.back() == '{'; + st = okey ? St::ObjKey : St::ObjValue; + } + + bool obj_lit_start(unsigned char c) const { + for (const std::string& l : F.obj_lits) + if ((unsigned char)l[0] == c) return true; + return false; + } + + /* Bytes that open no string and close no call: a bare key or a bare value. */ + void obj_bare_begin() { + ds = 0; + hold.clear(); + if (okey) { + if (!F.f.object_bare_keys) lenient(); + name.clear(); + st = St::ObjKeyBare; + return; + } + obj_sep(); + vpending = false; + bare_txt.clear(); + val.begin(ValueOut::Raw, /*cdata=*/false, /*lead=*/false, /*trail=*/false, scratch); + obj_flush(); + st = St::ObjBare; + } + + static constexpr size_t kBareKeep = 64; /* longer than any number a model writes */ + + /* A bare value ended: one that is no JSON number or literal was read by the recovery rule. */ + void bare_done() { + std::string_view v(bare_txt); + while (!v.empty() && is_ws((unsigned char)v.back())) v.remove_suffix(1); + const bool json = bare_txt.size() < kBareKeep && !v.empty() && + (v == "true" || v == "false" || v == "null" || + ((v[0] == '-' || (v[0] >= '0' && v[0] <= '9')) && + nlohmann::json::accept(v))); + if (!json) lenient(); + } + + /* A JSON string, which is the dialect's own only when it declares no string delimiters. */ + void json_string_begin() { + if (!F.f.object_string_open.empty()) lenient(); + obj_out("\""); + vheld.clear(); + st = St::ObjJStr; + } + + /* One of the anchored literals matched where a key or a value may begin. */ + void obj_lit_done(uint8_t kind) { + if (kind == ReplyFormat::Impl::LitString) { + obj_sep(); + if (!okey) vpending = false; + obj_out("\""); + ds = 0; + hold.clear(); + str_begin(); + st = St::ObjStr; + return; + } + /* The call's close or end where the object wanted more: the reply left the object + * unclosed, and the call ends here with it closed. */ + lenient(); + ocomma = false; + if (kind == ReplyFormat::Impl::LitClose) end_call_at_close(); + else end_core_done(); + } + + /* A JSON string's text goes out as it is, its escapes checked: one JSON has not is the + * backslash and the letter as text, a raw control character is escaped, and a surrogate + * escape that is not half of a pair is U+FFFD -- a client's JSON parser refuses all three. */ + void jstr_char(const char* q, size_t n) { + if (n == 0) return; + if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); } + touch(2); + json_escape_into(msg.calls.back().arguments, q, n); + } + + void jstr_escape_done(const std::string& e) { + /* e: a complete two-character escape, or a "u" escape with its four digits. */ + if (e.size() == 6) { + const unsigned long cp = std::strtoul(e.c_str() + 2, nullptr, 16); + if (cp >= 0xD800 && cp <= 0xDBFF) { + if (!jhi.empty()) { lenient(); obj_out("\\ufffd"); } + jhi = e; + return; + } + if (cp >= 0xDC00 && cp <= 0xDFFF) { + if (jhi.empty()) { lenient(); obj_out("\\ufffd"); return; } + obj_out(jhi + e); + jhi.clear(); + return; + } + } + if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); } + obj_out(e); + } + + static constexpr size_t kRunKeep = 16; /* the closers a string's end may hold back */ + static constexpr size_t kLookKeep = 32; /* what deciding a close may read ahead */ + + static bool run_byte(char c) { + return c == '}' || c == ']' || c == '"' || c == '`' || c == '\'' || is_ws((unsigned char)c); + } + + void str_begin() { srun.clear(); nq = nb = ns = 0; } + void str_emit(const char* q, size_t n) { + if (n == 0) return; + nq += (size_t)std::count(q, q + n, '"'); + nb += (size_t)std::count(q, q + n, '`'); + ns += (size_t)std::count(q, q + n, '\''); + touch(2); + json_escape_into(msg.calls.back().arguments, q, n); + } + void str_flush() { str_emit(srun.data(), srun.size()); srun.clear(); } + + /* A string's text: all of it goes out but a trailing run of whitespace and closers. */ + void str_text(const char* q, size_t n) { + size_t k = n; + while (k > 0 && run_byte(q[k - 1])) --k; + if (k > 0) { str_flush(); str_emit(q, k); } + srun.append(q + k, n - k); + if (srun.size() > kRunKeep) { + const size_t out = srun.size() - kRunKeep; + str_emit(srun.data(), out); + srun.erase(0, out); + } + } + + /* Where the held run stops being text: the closers after it close every open bracket of the + * object, innermost first, as the model writes them before the call's close -- read from the + * end, the last closes the outermost. npos: they do not. */ + size_t run_cut() const { + size_t i = srun.size(), k = 0; + while (i > 0 && k < ostack.size()) { + const char c = srun[i - 1]; + if (is_ws((unsigned char)c)) { --i; continue; } + if (c != (ostack[k] == '{' ? '}' : ']')) break; + --i; + ++k; + } + return k == ostack.size() && k > 0 ? i : std::string::npos; + } + + static bool starts(std::string_view a, std::string_view b) { + return a.size() >= b.size() && a.compare(0, b.size(), b) == 0; + } + + /* The call's close in a string whose held run closes the whole object: the model left the + * string open (measured: the close delimiter at p=0.86, `}` at p=0.08), and this is where + * the call ends -- as vLLM's and HF's Gemma 4 parsers end it, at the first `}`. + * The closers are the object's. A quote or backtick just before them that leaves the string + * with an odd count of its kind was the string's close, written in the wrong spelling. */ + void cut_begin() { + const size_t cut = run_cut(); + if (cut == std::string::npos) { str_flush(); str_emit(F.cc_core.data(), F.cc_core.size()); return; } + lenient(); + size_t keep = cut; + if (keep > 0 && (srun[keep - 1] == '"' || srun[keep - 1] == '`' || srun[keep - 1] == '\'')) { + const char c = srun[keep - 1]; + const size_t n = (c == '"' ? nq : c == '`' ? nb : ns) + + (size_t)std::count(srun.begin(), srun.begin() + (long)keep, c); + if (n % 2 == 1) --keep; + } + str_emit(srun.data(), keep); + srun.clear(); + if (!jhi.empty()) jhi.clear(); + obj_out(okey ? "\":null" : "\""); + vpending = false; + ocomma = false; + /* As after a call's close of its own: a repeated close goes with it. */ + end_call(); + } + + /* After a plain quote in a plain-quoted value: 0 not yet known, 1 it closed the value -- the + * object goes on with a member, an element, its closers and the call's close -- 2 it was + * text. */ + int q_verdict() const { + const std::string& q = qtail; + if (q.size() > kLookKeep) return 2; + const size_t n = q.size(); + size_t i = 0, top = ostack.size(); + auto ws = [&] { while (i < n && is_ws((unsigned char)q[i])) ++i; }; + ws(); + while (i < n && top > 0 && q[i] == (ostack[top - 1] == '{' ? '}' : ']')) { --top; ++i; ws(); } + if (i == n) return 0; + const std::string& so = F.f.object_string_open; + std::string_view r(q.data() + i, n - i); + if (!F.cc_core.empty()) { + if (starts(r, F.cc_core)) return 1; + if (starts(F.cc_core, r)) return 0; + } + if (top == 0 || q[i] != ',') return 2; + ++i; + ws(); + if (i == n) return 0; + r = std::string_view(q.data() + i, n - i); + const unsigned char c = (unsigned char)q[i]; + if (starts(r, so)) return 1; + if (starts(so, r)) return 0; + if (ostack[top - 1] == '{') { + if (!(std::isalpha(c) || c == '_')) return 2; + while (i < n && (std::isalnum((unsigned char)q[i]) || q[i] == '_')) ++i; + ws(); + if (i == n) return 0; + return q[i] == ':' ? 1 : 2; + } + return (c == '"' || c == '\'' || c == '{' || c == '[' || c == '-' || std::isdigit(c)) ? 1 : 2; + } + + void q_done(bool closed) { + std::string again; + again.swap(qtail); + if (closed) { + str_flush(); + obj_string_done(); + } else { + if (qmode == 0) qmode = 2; + str_text(&qc, 1); + st = St::ObjQStr; + } + read_again(again); + } + + /* A string or a key closed. */ + void obj_string_done() { + if (!jhi.empty()) { lenient(); jhi.clear(); obj_out("\\ufffd"); } + obj_out("\""); + st = okey ? St::ObjColon : St::ObjAfter; + } + /* The core of call_end has matched. The whitespace the format writes after it is part of the * tag, so the call closes when that has arrived too -- a reply that ends in between leaves the * call open, as the grammar does -- and a reply that goes straight on without it has closed @@ -1306,8 +1727,18 @@ struct ReplyStream::Impl { * match, so no quote is ever pending here; a raw value that left a string open is passed * through as the model wrote it. */ void end_call() { - std::string close((size_t)std::max(depth, 0), '}'); - args_out(close); + if (F.object) { + /* What the object left open is closed, so the arguments are JSON: a key whose value + * never came is null, and each bracket gets its partner. */ + std::string close = vpending ? "null" : ""; + vpending = false; + for (auto it = ostack.rbegin(); it != ostack.rend(); ++it) close += *it == '{' ? '}' : ']'; + ostack.clear(); + obj_out(close); + } else { + std::string close((size_t)std::max(depth, 0), '}'); + args_out(close); + } publish(2, true); msg.calls.back().closed = true; event(ReplyEvent::CallEnd, (uint32_t)msg.calls.size() - 1, {}); @@ -1499,14 +1930,22 @@ struct ReplyStream::Impl { return p; case St::Text: - if (!P.calls) { + if (!text_dfa) { text_out(p, (size_t)(e - p)); return e; } - p = scan(F.text, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); }); - if (hit >= 0) { + p = scan(*text_dfa, p, e, &hit, [this](const char* q, size_t n) { text_out(q, n); }); + if (hit < 0) return p; + if ((size_t)hit < n_open) { att_at = here(p) - F.openers[(size_t)hit].size(); begin_text_attempt(hit); + } else if ((size_t)hit == n_open) { + /* A reasoning block opens again, later in the reply. */ + trail = 0; + st = St::ThinkOpenWs; + } else { + /* Its close with no block open: not part of the answer. */ + lenient(); } return p; @@ -1558,12 +1997,18 @@ struct ReplyStream::Impl { lpos = 0; lhold.clear(); tag_end = att.size(); - if (loose) st = St::OpenPeek; + if (loose && F.object) { + /* A call written without its wrapper, in the object family: a declared + * tool's name and the object's opening are what make it one. */ + if (tool < 0) { fail_attempt(); return p + 1; } + begin_call(false); + } else if (loose) st = St::OpenPeek; else if (F.ns_trail.empty()) begin_call(true); else st = St::OpenTail; return p + 1; } - if (name.size() > kMaxLooseName || (c == '<' && !declared_prefix(name))) { + if (name.size() > kMaxLooseName || (c == '<' && !declared_prefix(name)) || + (loose && F.object && !declared_prefix(name))) { fail_attempt(); return p + 1; } @@ -1775,6 +2220,279 @@ struct ReplyStream::Impl { if (p < e) { post_call = true; ds = 0; hold.clear(); st = St::Text; } return p; + case St::ObjStart: + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + if (*p == '{') { ofirst = true; okey = true; st = St::ObjKey; return p + 1; } + /* No object after the name: the call takes none, and what stands there instead is + * read as what follows a call. */ + lenient(); + obj_done(); + return p; + + case St::ObjKey: { + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + const char c = *p; + okey = true; + if (c == '}' || c == ']') { obj_close_bracket(c); return p + 1; } + if (c == ',') { lenient(); return p + 1; } /* an empty member */ + if (c == '"') { + obj_sep(); + json_string_begin(); + return p + 1; + } + if (obj_lit_start((unsigned char)c)) { lhold.clear(); st = St::ObjLit; return p; } + obj_bare_begin(); + return p; + } + + case St::ObjKeyBare: + p = scan(F.obj_key, p, e, &hit, [this](const char* q, size_t n) { name.append(q, n); }); + if (hit < 0) return p; + if (hit <= 2) { + std::string_view k(name); + while (!k.empty() && is_ws((unsigned char)k.back())) k.remove_suffix(1); + if (k.empty()) lenient(); + obj_sep(); + std::string out = json_quote(k); + name.clear(); + if (hit == 0) { + obj_out(out + ":"); + vpending = true; + okey = false; + st = St::ObjValue; + return p; + } + /* A key with no value: it is null. */ + lenient(); + obj_out(out + ":null"); + obj_struct(hit == 1 ? ',' : '}'); + return p; + } + /* The call's close or end inside a key: the key had no value, and goes. */ + name.clear(); + lenient(); + ocomma = false; + if (hit == F.key_cc) end_call_at_close(); + else end_core_done(); + return p; + + case St::ObjColon: + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + vpending = true; + okey = false; + st = St::ObjValue; + if (*p == ':') { obj_out(":"); return p + 1; } + lenient(); + obj_out(":"); + return p; + + case St::ObjValue: { + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + const char c = *p; + const bool in_array = ostack.back() == '['; + okey = false; + if (c == '{' || c == '[') { + obj_sep(); + vpending = false; + obj_out(c == '{' ? "{" : "["); + ostack.push_back(c); + ofirst = true; + okey = c == '{'; + st = c == '{' ? St::ObjKey : St::ObjValue; + return p + 1; + } + if (c == ']' && in_array && ofirst) { obj_close_bracket(c); return p + 1; } + if (c == '}' || c == ']' || c == ',') { + /* No value where one was due: a member's is null, and an array's gap is no + * element. */ + lenient(); + if (!in_array) { + obj_out("null"); + vpending = false; + st = St::ObjAfter; + return p; + } + if (c == ',') return p + 1; + obj_close_bracket(c); + return p + 1; + } + if ((c == '"' || c == '\'') && !F.f.object_string_open.empty()) { + /* Measured on Gemma 4: such a quote -- `"`, or `'` as Python and JavaScript + * write strings -- is followed by the text verbatim, or with only its quotes + * escaped, never JSON's other escapes. */ + obj_sep(); + vpending = false; + lenient(); + obj_out("\""); + qc = c; + qmode = 0; + str_begin(); + st = St::ObjQStr; + return p + 1; + } + if (c == '"') { + obj_sep(); + vpending = false; + json_string_begin(); + return p + 1; + } + if (obj_lit_start((unsigned char)c)) { lhold.clear(); st = St::ObjLit; return p; } + obj_bare_begin(); + return p; + } + + case St::ObjLit: { + const char c = *p; + lhold.push_back(c); + bool part = false; + for (size_t i = 0; i < F.obj_lits.size(); ++i) { + const std::string& l = F.obj_lits[i]; + if (lhold.size() > l.size() || l.compare(0, lhold.size(), lhold) != 0) continue; + if (lhold.size() < l.size()) { part = true; continue; } + lhold.clear(); + obj_lit_done(F.obj_lit_kind[i]); + return p + 1; + } + if (part) return p + 1; + /* None of them: the bytes begin a bare key or value. */ + std::string again; + again.swap(lhold); + obj_bare_begin(); + read_again(again); + return p + 1; + } + + case St::ObjStr: + p = scan(F.obj_str, p, e, &hit, [this](const char* q, size_t n) { str_text(q, n); }); + if (hit < 0) return p; + if (hit == 0) { str_flush(); obj_string_done(); } + else cut_begin(); + return p; + + case St::ObjQStr: + p = scan(qc == '"' ? F.obj_qstr : F.obj_sqstr, p, e, &hit, + [this](const char* q, size_t n) { str_text(q, n); }); + if (hit < 0) return p; + if (hit == 0) { qtail.clear(); st = St::ObjQLook; } + else if (hit == 1) { + if (qmode == 0) qmode = 1; + const char esc[2] = { '\\', qc }; + if (qmode == 1) str_text(&qc, 1); + else str_text(esc, 2); + } else if (hit == 2) { lenient(); str_flush(); obj_string_done(); } + else cut_begin(); + return p; + + case St::ObjQLook: { + qtail.push_back(*p); + const int v = q_verdict(); + if (v) q_done(v == 1); + return p + 1; + } + + case St::ObjJStr: { + const char* run = p; + while (p < e) { + const unsigned char c = (unsigned char)*p; + if (vheld.size() == 1) { /* after the backslash */ + if (c && std::strchr("\"\\/bfnrt", (int)c)) { + vheld.push_back((char)c); + jstr_escape_done(vheld); + vheld.clear(); + run = ++p; + continue; + } + if (c == 'u') { vheld.push_back('u'); run = ++p; continue; } + /* No JSON escape: the backslash is text, and what follows it is read as + * the string's next byte. */ + lenient(); + vheld.clear(); + jstr_char("\\", 1); + run = p; + continue; + } + if (!vheld.empty()) { /* a "u" escape's digits */ + if (std::isxdigit(c)) { + vheld.push_back((char)c); + if (vheld.size() == 6) { jstr_escape_done(vheld); vheld.clear(); } + run = ++p; + continue; + } + lenient(); + const std::string text = vheld; + vheld.clear(); + jstr_char(text.data(), text.size()); + run = p; + continue; + } + if (c != '"' && c != '\\') { ++p; continue; } + jstr_char(run, (size_t)(p - run)); + ++p; + if (c == '"') { obj_string_done(); return p; } + vheld.assign(1, '\\'); + run = p; + } + jstr_char(run, (size_t)(p - run)); + return p; + } + + case St::ObjBare: + p = scan(F.obj_bare, p, e, &hit, [this](const char* q, size_t n) { + if (bare_txt.size() < kBareKeep) + bare_txt.append(q, std::min(n, kBareKeep - bare_txt.size())); + val.add(q, n, scratch); + obj_flush(); + }); + if (hit < 0) return p; + val.finish(false, scratch); + obj_flush(); + bare_done(); + if (hit <= 2) { obj_struct(",}]"[hit]); return p; } + lenient(); + if (hit == F.bare_cc) end_call_at_close(); + else end_core_done(); + return p; + + case St::ObjAfter: { + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + const char c = *p; + if (c == ',' || c == '}' || c == ']') { obj_struct(c); return p + 1; } + /* A key or a value with no separator before it: one is supplied. */ + lenient(); + ocomma = true; + ofirst = false; + okey = ostack.back() == '{'; + st = okey ? St::ObjKey : St::ObjValue; + return p; + } + + case St::ObjEnd: { + if (lpos == 0) { + while (p < e && is_ws((unsigned char)*p)) ++p; + if (p == e) return p; + } + const char c = *p; + if (c == F.end_core[lpos]) { + lhold.push_back(c); + if (++lpos == F.end_core.size()) { lhold.clear(); lpos = 0; end_core_done(); } + return p + 1; + } + /* The object is not followed by the call's end: the call ends with it all the same, + * and what stands there is read as what follows a call. */ + lenient(); + std::string again; + again.swap(lhold); + lpos = 0; + end_call(); + read_again(again); + return p; + } + case St::RfWs: while (p < e && is_ws((unsigned char)*p)) ++p; if (p < e) { @@ -1962,6 +2680,14 @@ struct ReplyStream::Impl { } void finish_all() { + /* The reply ended while a close was being decided: it was one. */ + while (st == St::ObjQLook) { + q_done(true); + std::string again = std::move(refeed); + refeed.clear(); + run(again, fed >= again.size() ? fed - again.size() : 0); + } + if (st == St::ObjStr || st == St::ObjQStr) str_flush(); while (in_loose_attempt()) { fail_attempt(); std::string again = std::move(refeed); @@ -1998,6 +2724,11 @@ struct ReplyStream::Impl { case St::ValJsonEnd: json_value_done(std::string_view(vheld).substr(0, vheld.size() - vs_pos)); break; + case St::ObjBare: + /* A bare value the reply was cut off inside: as it arrived. The call is open. */ + val.finish(true, scratch); + obj_flush(); + break; default: break; } @@ -2066,7 +2797,9 @@ ReplyHeld ReplyStream::held() const { (m.msg.reasoning.size() - m.sent_r) + (m.msg.content.size() - m.sent_c) + (m.msg.calls.empty() ? 0 : m.msg.calls.back().arguments.size() - m.sent_a); h.space = m.content.held_space() + m.think_pend.size(); - h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container(); + h.delimiter += m.srun.size() + m.qtail.size(); + h.structure = m.att.size() + m.name.size() + m.vheld.size() + m.val.held_container() + + m.jhi.size(); return h; } diff --git a/core/text/tokenizer.cpp b/core/text/tokenizer.cpp index bd747a9a..8ff945a4 100644 --- a/core/text/tokenizer.cpp +++ b/core/text/tokenizer.cpp @@ -623,6 +623,22 @@ int Vocab::load(VocabBuild b) { RAD_INFO("vocab: end-of-generation also on %s (a control token the container declares " "neither as eos nor eot; without this a turn ending on it runs on)", added.c_str()); + + /* AND WHAT THE CHECKPOINT ITSELF NAMES. generation_config.json's eos_token_id is the + * model's own list of tokens a generation ends on, and the one that is not a guess: + * Gemma 4 names <|tool_response> there beside and , because after its calls + * the model writes it and waits for the response -- a turn that runs past it answers + * its own call. Every id in range is honoured, as transformers honours them. */ + std::string named; + for (int32_t id : b_.eos_ids) { + if (id < 0 || id >= (int32_t)b_.tokens.size()) continue; + if (std::find(eog_.begin(), eog_.end(), id) != eog_.end()) continue; + eog_.push_back(id); + named += (named.empty() ? "" : " ") + b_.tokens[id] + "=" + std::to_string(id); + } + if (!named.empty()) + RAD_INFO("vocab: end-of-generation also on %s (named by the checkpoint's " + "generation_config.json)", named.c_str()); } /* The encoder: the chain compiled and the tables flattened. A pattern the regex compiler diff --git a/core/text/tokenizer.h b/core/text/tokenizer.h index c678131d..8d686c40 100644 --- a/core/text/tokenizer.h +++ b/core/text/tokenizer.h @@ -86,6 +86,11 @@ struct VocabBuild { /* Diagnostics only: what rad-convert thought it was reading. Not baked. */ std::string source; + + /* The ids the checkpoint's generation_config.json names as eos_token_id, which the container + * carries as metadata (`generation.eos_token_id`) rather than in the vocabulary section. The + * engine fills it from there before load(); not baked. */ + std::vector eos_ids; }; /* ================================================================== the loaded vocab */ diff --git a/data/recipes/gemma4-31b-dense-bf16-w4a8.recipe b/data/recipes/gemma4-31b-dense-bf16-w4a8.recipe new file mode 100644 index 00000000..007a60d6 --- /dev/null +++ b/data/recipes/gemma4-31b-dense-bf16-w4a8.recipe @@ -0,0 +1,28 @@ +# gemma4-31b-dense-bf16-w4a8.recipe -- Gemma 4 31B dense (text) from a bf16 checkpoint: Google's +# gemma-4-31B-it, or any finetune of it, which ships no QAT form. Same grid and size as the CT +# recipe (int4, an f16 scale a 128 columns, ~20 GiB with the assistant head), with the +# least-squares scale search instead of absmax. +# +# rad-convert --recipe data/recipes/gemma4-31b-dense-bf16-w4a8.recipe \ +# --set quantization_config.quant_method=compressed-tensors \ +# [--draft-model ] -o gemma4-31b-dense-bf16-w4a8.rad +# +# The --set selects the gemma4 plugin, which is registered for the quantised form both releases +# convert to. The plugin names the same `X.weight` for either: the CT-INT4 release's packed codes +# are imported under that name by the checkpoint reader. +# Norms, the embedding/lm_head and the assistant head are kept bf16 (no rule matches them). +# +# Why from bf16 when a QAT release exists: the assistant head was trained against the bf16 trunk. +# Served from this container it accepts 0.71/0.62/0.63 of its k=3 drafts on prose, against +# 0.49/0.50/0.44 from the QAT container, at the same step time. +# +# A linear may be kept at int8 on the same grid (gemm_nt_q w8a8), e.g. +# blk.*.attn_o.weight rtn codes=i8 group=128 scale=f16 +# Measured with attention + down_proj at int8: acceptance unchanged, decode 20 % slower. + +blk.*.attn_q.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_k.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_v.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_o.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.ffn_down.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.ffn_gate_up.weight rtn codes=i4 group=128 scale=f16 rule=search diff --git a/data/recipes/gemma4-31b-dense-w4a8.recipe b/data/recipes/gemma4-31b-dense-w4a8.recipe new file mode 100644 index 00000000..18f686e7 --- /dev/null +++ b/data/recipes/gemma4-31b-dense-w4a8.recipe @@ -0,0 +1,27 @@ +# gemma4-31b-dense-w4a8.recipe -- Gemma 4 31B dense (text), from its CT-INT4 (w4a16) +# checkpoint, as the w4a8 container serves it. +# +# rad-convert \ +# --recipe data/recipes/gemma4-31b-dense-w4a8.recipe -o gemma4-31b-dense-w4a8.rad +# +# The checkpoint's GEMM weights are CT-INT4 (group-32, a bf16 scale a 32 codes, no zero point), +# imported as such (core/format/checkpoint.h); the rules re-quantise them to group-128 int4 with an +# f16 scale, the grid the w4a8 kernels read. The norms +# (input / post-attention / pre- and post-feedforward layernorms, the q/k head norms) and the +# embedding + lm_head are bf16 and are kept as the checkpoint holds them -- a weight no rule +# matches is served in its checkpoint form. A rank-1 weight a pattern happens to match is declined +# by the quantiser and kept as it is, so the norms stay bf16 even under a broad pattern. +# +# With the assistant (draft) head merged in -- add `--draft-model ` -- +# its weights are declared as `mtp.*` and no rule below matches them: the head is served bf16 as +# Google ships it (0.9 GB). The patterns are anchored, so `blk.*` never reaches `mtp.blk.*`. +# Its lm_head (`mtp.output.weight`, 0.5 GB, read once a draft round) may be made int8 with +# mtp.output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +# and the head then reads it through logits_gemm_i8; a draft only proposes, the trunk verifies. + +blk.*.attn_q.weight rtn codes=i4 group=128 scale=f16 +blk.*.attn_k.weight rtn codes=i4 group=128 scale=f16 +blk.*.attn_v.weight rtn codes=i4 group=128 scale=f16 +blk.*.attn_o.weight rtn codes=i4 group=128 scale=f16 +blk.*.ffn_gate_up.weight rtn codes=i4 group=128 scale=f16 +blk.*.ffn_down.weight rtn codes=i4 group=128 scale=f16 diff --git a/deploy/compose/gemma4-31b-w4a8.yaml b/deploy/compose/gemma4-31b-w4a8.yaml new file mode 100644 index 00000000..4889a172 --- /dev/null +++ b/deploy/compose/gemma4-31b-w4a8.yaml @@ -0,0 +1,14 @@ +# Gemma 4 31B-it: int4 trunk (GPTQ from the bf16 checkpoint) with int8 activations, Google's +# assistant head merged in as the MTP drafter (depth 3), and the vision tower. Sampling defaults are +# the checkpoint's generation_config; thinking is switched per request (chat_template_kwargs). +# For the full 262,144-token context use --max-model-len 262144 --max-num-seqs 2. +name: radiance-gemma4-31b-w4a8 +services: + radiance: + extends: { file: common.yaml, service: radiance } + container_name: radiance-gemma4-31b-w4a8 + command: > + --model /models/gemma4-31b-w4a8.rad + --host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env} + --tp 2 --max-num-seqs 8 --max-model-len 65536 --kv-cache-dtype fp8 + --num-speculative-tokens 3 --temp 1.0 --top-p 0.95 --top-k 64 diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index cbd4186d..24961413 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -14,6 +14,7 @@ into the id an architecture plugin claims. | `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed | | `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert | | `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector | +| `arch/gemma4_bf16` | `gemma4_bf16` | `i4` (group-128 codes, f16 scale) | Gemma 4 31B dense (text): two attention classes — sliding-window and proportional-RoPE global (`attention_k_eq_v`) — over one GemmaRMSNorm stream, GELU ffn, two KV groups, softcapped logits, tied scaled embedding; served from a CT-INT4 (QAT w4a16) checkpoint. Optional draft head: Google's assistant (`rad-convert --draft-model`), a serial head with no cache of its own (`rad_drafter_shared_kv`) | This document is the geometry of each, and the handful of readings that are **arithmetically silent** — wrong in a way that produces fluent output and no error anywhere. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index 32970ecc..185661b2 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -1099,7 +1099,7 @@ one line naming each one the command line moved. | `--placement MODE` | auto | `all_vram`, `layer_offload`, `expert_tiered`, `auto` | | `--deterministic` | off | pin placement to the loader's plan, so the resident set cannot change under the heat engine | | `--checkpoint-interval N` | 2048 | linear-attention state checkpoint interval, in tokens | -| `--checkpoint-slots N` | 8 | linear-state snapshots the server may hold at once, **in total**, not per sequence. They live in pinned host memory, not VRAM: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`), allocated at startup. A snapshot is copied off the card after the step that produced it and back before the step that resumes from it. With a disk tier a full store detaches its least recently used snapshot to disk instead of losing it | +| `--checkpoint-slots N` | 8 | linear-state (hybrid) or sliding-window snapshots the server may hold at once, **in total**, not per sequence. They live in pinned host memory, not VRAM: one slot is a snapshot of every rank's shard (113 MB on Flash-Next at `--tp 2`; on Gemma 4 31B the 1024-token window of every sliding layer, 406 MiB at `--tp 2`), allocated at startup. A snapshot is copied off the card after the step that produced it and back before the step that resumes from it. With a disk tier a full store detaches its least recently used snapshot to disk instead of losing it | | `--checkpoint-policy NAME` | geometric-backoff | also `tip-only`, `keep-all` | | `--no-prefix-cache` | — | disable prefix caching | diff --git a/docs/KERNELS.md b/docs/KERNELS.md index 81b5bee7..302662f4 100644 --- a/docs/KERNELS.md +++ b/docs/KERNELS.md @@ -57,16 +57,24 @@ the core can tune, fuse and check against a container: | `attn_decode_h128_gqa8_fp8kv` | `attn_paged` | | `attn_decode_h256_gqa12_bf16kv` | `attn_paged` | | `attn_decode_h256_gqa12_fp8kv` | `attn_paged` | +| `attn_decode_h256_gqa2_bf16kv` | `attn_paged` | +| `attn_decode_h256_gqa2_fp8kv` | `attn_paged` | | `attn_decode_h256_gqa6_fp8kv` | `attn_paged` | | `attn_decode_h256_gqa8_bf16kv` | `attn_paged` | | `attn_decode_h256_gqa8_fp8kv` | `attn_paged` | +| `attn_decode_h512_gqa8_bf16kv` | `attn_paged` | +| `attn_decode_h512_gqa8_fp8kv` | `attn_paged` | | `attn_prefill_h128_gqa8_bf16kv` | `attn_paged` | | `attn_prefill_h128_gqa8_fp8kv` | `attn_paged` | | `attn_prefill_h256_gqa12_bf16kv` | `attn_paged` | | `attn_prefill_h256_gqa12_fp8kv` | `attn_paged` | +| `attn_prefill_h256_gqa2_bf16kv` | `attn_paged` | +| `attn_prefill_h256_gqa2_fp8kv` | `attn_paged` | | `attn_prefill_h256_gqa6_fp8kv` | `attn_paged` | | `attn_prefill_h256_gqa8_bf16kv` | `attn_paged` | | `attn_prefill_h256_gqa8_fp8kv` | `attn_paged` | +| `attn_prefill_h512_gqa8_bf16kv` | `attn_paged` | +| `attn_prefill_h512_gqa8_fp8kv` | `attn_paged` | | `attn_vit_h72_bf16` | `attn_dense` | | `dequant_w4_bf16` | `dequant_w4` | | `dflash_conv_t2_g16_bf16` | `dflash_conv` | diff --git a/docs/OPS.md b/docs/OPS.md index d190d409..3c96d423 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -159,6 +159,7 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th | op | params | operands | |---|---|---| | `rmsnorm` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt `mult`:f64/opt | `x`, `w`w? → `y` (no gain operand: a gain of one) | +| `rmsnorm_p` | `M`(range) `n` `eps`:f64 `dtype` | `x` → `y` | | `rmsnorm_add` | `M`(range) `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`, `w`w → `y`, `residual_out` | | `hc_enter` | `M`(range) `n` `hc` `dtype` | `x` → `h` | | `hc_read` | `M`(range) `n` `hc` `lowrank` `eps`:f64 `dtype` `wadd`:f64/opt `inject`/opt `group`/opt `rotate`/opt `mix`/opt | `h`, `w`w, `mix_down`w, `mix_up`w, `inject_w`w? → `x`, `inj`?, `q`?, `scale`?, `rq`?, `rscale`? | @@ -178,10 +179,13 @@ adding a kernel plugin; "refused at load" names one op and leaves you to find th | `conv2d` | `M`(range) `width` `cin` `cout` `kh` `kw` `stride` `pad` `cu_div`/opt `valid_stride`/opt `dtype` | `x`, `w`w, `cu_seqlens`, `valid`? → `y` | | `conv1d_dw` | `M`(range) `n` `k` `cu_div`/opt `dtype` | `x`, `w`w, `cu_seqlens` → `y` | | `rel_sinusoid` | `M`(range) `n` `max_timescale`:f64/opt `dtype` | → `y` | +| `gelu_mul` | `M`(range) `n` `dtype` | `gate_up` → `y` (splits `[M,2n]` into gelu·up, tanh approx) | | `gelu` / `silu` | `M`(range) `n` `dtype` | `x` → `y` | | `cast` | `M`(range) `n` `from` `to` | `x` → `y` | | `softmax` | `M`(range) `n` `dtype` | `x` → `y` | | `sigmoid` | `M`(range) `n` `dtype` | `x` → `y` | +| `logit_softcap` | `M`(range) `n` `cap`:f64 `dtype` | `x` → `y` | +| `scale` | `M`(range) `n` `dtype` | `x`, `s`w → `y` | | `silu` | `M` `n` `dtype` | `x` → `y` | | `fill` | `M`(range) `n` `dtype` `value`:f64/opt | → `y` | @@ -191,6 +195,15 @@ names one op. `rmsnorm_add` exists because the residual add and the next norm are one pass in every real implementation. A plugin asks for it first and falls back to `add` + `rmsnorm` (`spec.md` §2.3). +`rmsnorm_p` is `rmsnorm` with the gain removed: `x * rsqrt(mean(x^2) + eps)` and no `w` at all. +Gemma's attention normalises the value with a bare RMS (a weightless norm) while normalising the +key with the `k_norm` gain in the same layer, and there is no checkpoint plane to feed the value +through a gain -- `rmsnorm` would need a phantom all-zero weight to say the same thing. + +`gelu_mul` is `silu_mul` with the tanh GELU instead of silu -- Gemma's gated FFN is trained with +`gelu_pytorch_tanh`, and gated feed-forwards ask for the tanh form rather than the unary `gelu`'s +exact erf one. Both split the fused `gate_up` with the gate in the FIRST half. + `hc_read` / `hc_write` are the GATED RESIDUAL pair, which is what a hyper-connection model has instead of a pre-norm and a residual add. The stream is `hc` times the model width and every block reads a mix of the `hc` sub-streams and writes back into all of them, both gated by data: @@ -375,6 +388,17 @@ spelling of `act`, not the vocabulary's. | `had_quant_act_i8g` | `M` `n` `group` `dtype` | `x` → `q`, `scale` | | `gated_had_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate_up` → `q`, `scale`, `out_bf16`? | | `gate_quant_fp8` | `M` `n` `group` `dtype` `act`:str/opt | `gate`, `x` → `q`, `scale`, `out_bf16`? | +| `rmsnorm_quant_i8` | `M` `n` `eps`:f64 `dtype` `wadd`:f64/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? | +| `gelu_mul_quant_i8` | `M` `n` `dtype` | `gate_up` → `q`, `scale`, `out_bf16`? | + +`gelu_mul_quant_i8` is `gelu_mul` with the same quantiser on its pass, byte-identical to the pair. + +`rmsnorm_quant_i8` is `rmsnorm` with `quant_act_i8`'s quantiser on its pass — fragment-order int8 +codes and one f32 scale per row, the grid `gemm_nt_q` reads at `dtype=w4a8`. With `residual` the +norm is of `residual + x`, stored back; `w_post` normalises `x` before that add and `scalar` (`[1]`) +multiplies the sum after it, which together are a sandwich-norm model's residual junction +(`rmsnorm` → `add` → `scale` → `rmsnorm` → `quant_act_i8`). Byte-identical to that chain: every +intermediate the chain stores is rounded to bf16, and both sums of squares take `rmsnorm`'s partition. `gemm_nt_q_gated` is the row above pulled into the projection that feeds it: `gemm_nt_q` over a `[N, K]` gate_up plane — `N` is the WEIGHT's rows, twice the fused width, gate half first — with @@ -430,9 +454,10 @@ that folds dequantisation into its epilogue still receives them. | `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt `window`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` | | `attn_local_rel` | `M`(range) `head_dim` `n_head` `left` `right` `softcap`:f64 `cu_div`/opt `dtype` | `q`, `k`, `v`, `relk`, `pds`w, `cu_seqlens` → `out` | | `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout | -| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `qkv`:inout, `positions` | -| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `positions` → `cos_sin` | +| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `ladder`/opt | `qkv`:inout, `positions` | +| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt `head_dim`/opt `ladder`/opt | `positions` → `cos_sin` | | `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt `v_norm`/opt `sections`/opt `comps`/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w | +| `qkv_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `ladder`/opt `wadd`:f64/opt `v_from_k`/opt `dtype` | `q`:inout, `k`:inout, `v`:inout, `positions`, `q_w`w, `k_w`w | **`attn_local_rel`** is Gemma 4's audio attention: local, with a relative-position term and a softcap. Query row `i` of a segment sees the key rows `j` of the same segment with `0 <= i - j <= @@ -465,6 +490,11 @@ of radius `r` (`|i - j| <= r`) is `window = r + 1`. `q`, `k` and `v` may each be `[tokens, heads * head_dim]`, and the second form may be a column slice of a fused projection read at that projection's row pitch -- which is how a tower's `[q|k|v]` row reaches it without a copy. +**`qkv_norm_rope`** is the same prologue over SEPARATE `q`, `k` and `v` projections (Gemma 4's text +attention, three GEMMs): the q and k norms, the unit-gain value norm and the rotary in one dispatch. +`v_from_k` 1 takes v from the RAW k before the k norm (the k == v global class). The rotary parameters +are `rope`'s, `ladder` included; byte-identical to `rmsnorm_p` + `rmsnorm` x2 + `rope` x2. + **`qk_norm_rope`'s `v_norm`** set to 1 also RMS-norms every v head of the fused row with a UNIT gain and does not rotate it: Gemma 4's value norm, which has no weight to name. @@ -485,6 +515,16 @@ restarts the frequency ladder in each, `theta^(-2j / (2 s_c))` for the run's `j` vision tower's 2-D rotary over row and column). With `[M]` positions every component is that one position, so `mrope` and `imrope` over a text batch are `neox` exactly. +**`ladder` names the width the base frequency ladder is measured in.** Absent, or `rotary`, the +exponent divides by `rotary_dim`: a partial rotary is a complete rotation of its own width, and +every existing model is bit-for-bit unchanged. `head` divides by `head_dim` instead -- the +**proportional** variant, where the `rotary_dim / 2` frequencies are a prefix of the full-width +table rather than a table rescaled to the rotated width: at `head_dim 512, rotary_dim 128`, +frequency `i = 1` wants `theta^(-1 / 256)`, not `theta^(-1 / 64)`. Only the base ladder moves +(`axial` keeps its per-section ladders), and the tail of the head past `rotary_dim` is untouched +either way. `rope_table` carries a `head_dim` param for the same reason: its angles must stay +`rope`'s to the last operation. + **`gemm_nt_bias`'s epilogue** is a linear layer's: the biased product rounded to `y`'s dtype, then `act` of it (`none`, `gelu` exact, `gelu_tanh`) rounded, then `res` added and rounded -- each step what a separate tensor would hold, so the fused form is the unfused chain to the bit. @@ -883,6 +923,7 @@ by ~1 ULP, which breaks the replicated-state invariant. The build sets it global | op | params | operands | |---|---|---| | `ar_rmsnorm_quant_fp8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | +| `ar_rmsnorm_quant_i8` | `M` `n` `eps`:f64 `world_size` `dtype` `wadd`:f64/opt | `x`:inout, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`?; `w_post`w?, `scalar`w? | | `ar_hc_write` | `M`(range) `n` `hc` `world_size` `dtype` `wire`/opt | `y`:inout, `inj`, `h`:inout | | `ar_gather_hc_write` | `M`(range) `n` `hc` `top_k` `world_size` `dtype` `act`/opt `wire`/opt | `y_expert`, `expert_w`, `sorted_tok`, `shared`?, `shared_gate`?, `y`:inout, `inj`, `h`:inout | | `ar_ln_had_quant_i8` | `M` `n` `eps`:f64 `group` `world_size` `dtype` `wadd`:f64/opt `wire`/opt | `x`, `residual`:inout?, `w`w → `q`, `scale`, `out_bf16`? | @@ -1000,6 +1041,24 @@ holds only where the rank holds the WHOLE vocabulary -- `world_size` 1, not mere on most steps, so a check keyed on the offset alone refuses correct calls. Bounding ids is the caller's, and the tokeniser and the sampler both already are. +### `embed_lookup`'s runtime `mult` + +`mult` (optional f64, default 1) multiplies the rows that are FOUND: `x[m] = wte[id] * mult`. +A missed row — negative padding or another rank's token — writes zero, not zero times the scale. +Absent it is the plain gather the op has always been, which is what keeps every other caller in +the tree bit-identical. + +**Not `wscale`.** `wscale` is the scale `embed_lookup_q`'s LAYOUT quantises with — a property of +the stored table, read back as the dequant. `mult` is applied AFTER the gather, to the rows that +come out of it; `embed_lookup_q` takes no `mult` at all, because its rows arrive already scaled by +the table's own dequant. + +**Why it exists**: Gemma 4 scales its embedding by `sqrt(n_embd)` at the lookup — the reference's +`build_inp_embd` and HF's `Gemma4TextScaledWordEmbedding` both do it there, and the checkpoint's +table is plain. Baking it into the table instead would untie it from the head, which the model +ties and which the checkpoint stores twice; scaling the lookup leaves the table and the head the +same tensor the weights loader already maps. + ### `embed_lookup_q`, the n-gram gather **A gather from a table quantised with ONE scale for all of it**: `x[m] = wte[id] * scale[0]`. diff --git a/libavx/avx_attn.cpp b/libavx/avx_attn.cpp index b772e576..d26fbfb7 100644 --- a/libavx/avx_attn.cpp +++ b/libavx/avx_attn.cpp @@ -1149,13 +1149,31 @@ static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot, } } -static float* inv_freqs(int64_t half, int64_t rot, float theta) { +/* `den` is the width the base ladder is measured in: `rot` for a `rotary` ladder (a partial rotary + * is a complete rotation of its own width) and `head_dim` for `head`, the proportional variant. + * Shared by `rope` and `rope_table` because the two must compute the same angles. */ +static float* inv_freqs(int64_t half, int64_t den, float theta) { float* f = (float*)scratch_raw((size_t)half * sizeof(float)); for (int64_t i = 0; i < half; ++i) - f[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot); + f[i] = 1.0f / std::pow(theta, (float)(2 * i) / (float)den); return f; } +/* `ladder` names the width the base frequency ladder is measured in -- see inv_freqs. Absent and + * `rotary` divide by `rot` (every existing model); `head` divides by `head_dim`, which it needs. An + * unknown value is a schema error, not a silent default. */ +static int rope_ladder(const RadArgs* a, int64_t rot, int64_t head_dim, int64_t* den) { + const char* lad = p_str(a, "ladder", nullptr); + if (!lad) { *den = rot; return RAD_OK; } + if (!std::strcmp(lad, "rotary")) { *den = rot; return RAD_OK; } + if (!std::strcmp(lad, "head")) { + if (head_dim <= 0) return RAD_E_SHAPE; + *den = head_dim; + return RAD_OK; + } + return RAD_E_UNSUPPORTED; +} + AVX_KERNEL(rope) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *qkv = &a->t[0], *pos = &a->t[1]; @@ -1168,8 +1186,11 @@ AVX_KERNEL(rope) { static const char* kModes[] = { "neox", "gptj", "mrope", "imrope", "axial" }; const int mode = p_enum(a, "mode", kModes, 5, -1); if (mode < 0) return RAD_E_UNSUPPORTED; - const int64_t rot = p_int(a, "rotary_dim", head_dim); + int64_t rot = p_int(a, "rotary_dim", head_dim); if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE; + int64_t den; + const int lrc = rope_ladder(a, rot, head_dim, &den); + if (lrc != RAD_OK) return lrc; /* [M] one component a token, or [C, M] component-major with `sections`. */ int64_t sec[8] = {}; @@ -1193,8 +1214,12 @@ AVX_KERNEL(rope) { if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE; const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row; const int64_t ds = laststride(qkv); + /* THE PROPORTIONAL LADDER (`head`) is HF's: the rotation spans the whole head -- pair i is + * (i, i + head_dim/2) -- and every frequency past rotary_dim/2 is zero (libref, ref_rope). */ + const int64_t nfreq = rot / 2; + if (den == head_dim && rot < head_dim && !multi && mode == ROPE_NEOX) rot = head_dim; const int64_t half = rot / 2; - float* invf = inv_freqs(half, rot, theta); + float* invf = inv_freqs(half, den, theta); int comp[512] = {}; if (half > 512) return RAD_E_UNSUPPORTED; if (multi) { @@ -1222,6 +1247,7 @@ AVX_KERNEL(rope) { if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED; for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i); } + for (int64_t i = nfreq; i < half; ++i) invf[i] = 0.0f; const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0; AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * rot >= AVX_PAR_MIN) @@ -1416,20 +1442,25 @@ AVX_KERNEL(qk_norm_rope) { AVX_KERNEL(rope_table) { if (!rad_args_have(a, 2)) return RAD_E_INVAL; const RadTensor *pos = &a->t[0], *cs = &a->t[1]; - const int64_t rot = p_int(a, "rot", 0); + const int64_t rot = p_int(a, "rot", 0); + const int64_t head_dim = p_int(a, "head_dim", 0); const float theta = p_f32(a, "theta", 10000.0f); const float rscale = p_f32(a, "scale", 1.0f); if (rot < 2 || (rot & 1)) return RAD_E_SHAPE; + int64_t den; + const int lrc = rope_ladder(a, rot, head_dim, &den); + if (lrc != RAD_OK) return lrc; const int64_t M = numel(pos); if (M <= 0 || numel(cs) % rot) return RAD_E_SHAPE; const int64_t rows = numel(cs) / rot; const int64_t half = rot / 2; - float* invf = inv_freqs(half, rot, theta); + float* invf = inv_freqs(half, den, theta); const RadYarn yarn = rad_yarn_args(a); if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL; if (yarn.factor != 0.0f) for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i); + AVX_PARALLEL_FOR_IF(M * rot >= AVX_PAR_MIN) for (int64_t m = 0; m < M; ++m) { const int64_t pp = ldi(pos, offlin(pos, m)); diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index d9034c5d..22281ed2 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -43,7 +43,11 @@ std::vector build_cases() { add("rmsnorm", { HI("M", 7), HI("n", 640), HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 0) }, EB(7, 640, w, 2)); add("rmsnorm", { HI("M", 3), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt), - HF("wadd", 1) }, EB(3, 645, w, 2)); + HF("wadd", 1) }, EB(3, 645, w, 2)); + add("rmsnorm_p", { HI("M", 7), HI("n", 640), HF("eps", 1e-6), HS("dtype", dt) }, + EB(7, 640, w, 2)); + add("rmsnorm_p", { HI("M", 3), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt) }, + EB(3, 645, w, 2)); add("rmsnorm_add", { HI("M", 5), HI("n", 640), HF("eps", 1e-6), HS("dtype", dt), HF("wadd", 0) }, EB(5, 640, w, 4)); add("layernorm", { HI("M", 5), HI("n", 645), HF("eps", 1e-5), HS("dtype", dt) }, @@ -51,11 +55,15 @@ std::vector build_cases() { add("add", { HI("M", 9), HI("n", 645), HS("dtype", dt) }, EB(9, 645, w, 3)); add("mul", { HI("M", 9), HI("n", 640), HS("dtype", dt) }, EB(9, 640, w, 3)); add("silu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3)); + add("gelu_mul", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 3)); add("gelu", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); add("silu", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2)); add("sigmoid", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); add("fill", { HI("M", 6), HI("n", 645), HS("dtype", dt), HF("value", 1.3) }, EB(6, 645, w, 1)); + add("logit_softcap", { HI("M", 6), HI("n", 645), HF("cap", 30.0), HS("dtype", dt) }, + EB(6, 645, w, 2)); + add("scale", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); add("softmax", { HI("M", 6), HI("n", 645), HS("dtype", dt) }, EB(6, 645, w, 2)); add("gather_rows", { HI("M", 6), HI("n", 640), HS("dtype", dt) }, EB(6, 640, w, 2)); for (const char* act : { "silu", "gelu", "gelu_tanh", "sigmoid" }) @@ -298,8 +306,17 @@ std::vector build_cases() { add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64), HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 0), HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14), - HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) }); + HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) }); } + /* The proportional ladder: a partial rotary (rotary_dim < head_dim) with `ladder` head, so the + * denominator is head_dim and libavx's answer must agree with libref's on it. */ + for (const char* mode : { "neox", "gptj" }) { + add("rope", { HI("M", 12), HI("head_dim", 64), HI("n_head", 4), HI("n_head_kv", 2), + HF("theta", 10000.0), HF("scale", 1.0), HS("mode", mode), + HI("rotary_dim", 32), HS("ladder", "head") }); + } + add("rope_table", { HI("M", 12), HI("rot", 32), HF("theta", 10000.0), HF("scale", 1.0), + HS("dtype", "f32"), HI("head_dim", 64), HS("ladder", "head") }); /* The multi-component forms: Qwen3-VL's interleaved M-RoPE over a partial rotary, and a vision * tower's 2-D axial rotary over a whole 72-wide head. */ for (const char* dt : { "f32", "bf16" }) { diff --git a/libavx/avx_elementwise.cpp b/libavx/avx_elementwise.cpp index 13f7c086..a5ef8b97 100644 --- a/libavx/avx_elementwise.cpp +++ b/libavx/avx_elementwise.cpp @@ -551,6 +551,39 @@ AVX_KERNEL(silu_mul) { return RAD_OK; } +/* ------------------------------------------------------------------ gelu_mul + * + * y[i] = gelu_tanh(gate_up[i]) * gate_up[n + i], the gate the FIRST half exactly as in silu_mul. + * The activation keeps libref's ONE definition of gelu_tanh (act_gelu_tanh, std::tanh): the tree's + * rule for a non-polynomial activation is a single source of truth, so this runs libref's scalar + * formula into the f32 scratch rather than a second vectorised tanh whose agreement with the first + * would be a property of its coefficients -- the same decision the unary gelu above makes. */ +AVX_KERNEL(gelu_mul) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *gu = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", numel(y)); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n); + if (rows <= 0 || numel(gu) < rows * 2 * n) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + /* One in_row over the whole 2n row, as silu_mul does: the halves are adjacent and one + * conversion of 2n beats two of n. */ + float* s = scratch_f32((size_t)(2 * n)); + float* sy = scratch_f32_b((size_t)n); + const float* g = in_row(gu, rowoff(gu, r, 2 * n), 2 * n, s); + const float* u = g + n; + for (int64_t i = 0; i < n; ++i) { + const float x = g[i]; + const float t = std::tanh(0.7978845608028654f * (x + 0.044715f * x * x * x)); + sy[i] = 0.5f * x * (1.0f + t) * u[i]; + } + out_row(y, rowoff(y, r, n), n, sy); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ gelu / silu / sigmoid * * These run over the whole tensor rather than row by row -- libref's `unary` does the same -- so @@ -640,6 +673,95 @@ AVX_KERNEL(fill) { return RAD_OK; } +/* ------------------------------------------------------------------ logit_softcap */ +/* y = cap * tanh(x / cap). Its own list entry rather than another unary, because WHICH is + * a compile-time choice and `cap` is a runtime parameter -- the template has nowhere to put it. + * The vector path keeps the tree's one definition of the non-polynomial part: tanh(z) is + * 2*sigmoid(2z) - 1, so the work is vf_sigmoid's existing minimax exp plus two multiplies. The + * scalar fallback is libm's tanhf, which is what libref's oracle computes. */ +AVX_KERNEL(logit_softcap) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t nel = numel(y); + if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE; + const float cap = p_f32(a, "cap", 30.0f); + if (!(cap > 0.0f)) return RAD_E_INVAL; + + if (!dense_row(x) || !dense_row(y) || !rad_tensor_is_contiguous(x) || + !rad_tensor_is_contiguous(y)) { + AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN) + for (int64_t i = 0; i < nel; ++i) { + const float v = ldt(x, offlin(x, i)); + stt(y, offlin(y, i), cap * std::tanhf(v / cap)); + } + return RAD_OK; + } + + const int64_t TILE = 4096; + const int64_t ntile = (nel + TILE - 1) / TILE; + AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN) + for (int64_t t = 0; t < ntile; ++t) { + const int64_t off = t * TILE; + const int64_t m = (nel - off) < TILE ? (nel - off) : TILE; + float* s = scratch_f32((size_t)TILE); + float* so = scratch_f32_b((size_t)TILE); + const float* v = in_row(x, off, m, s); + const vf z = vf_set1(2.0f / cap); /* x / cap, doubled: the argument of the sigmoid */ + const vf c2 = vf_set1(2.0f * cap); /* 2*cap * sigmoid(...) */ + const vf c1 = vf_set1(-cap); /* ... - cap */ + int64_t i = 0; + for (; i + VF_N <= m; i += VF_N) + vf_storeu(so + i, vf_fma(c2, vf_sigmoid(vf_mul(vf_loadu(v + i), z)), c1)); + for (; i < m; ++i) + so[i] = cap * std::tanhf(v[i] / cap); + out_row(y, off, m, so); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ scale */ +/* y = x * s, s a [1] weight broadcast over every element. A plain multiply by a scalar: the + * vector path is vf_mul against a broadcast, and the scalar fallback is a plain multiply. There is + * no non-polynomial part, so nothing is reused from the sigmoid path; it is its own list entry + * (rather than a `mul` with a [1] operand) for the same reason `mul` refuses a scalar broadcast -- + * a silent choice between a row-broadcast and a scalar-broadcast is how a shape bug becomes a + * plausible number. The scalar is read once, outside the loop: a per-element reload of a [1] + * tensor is the same value every time and costs a load per element. */ +AVX_KERNEL(scale) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *s = &a->t[1], *y = &a->t[2]; + const int64_t nel = numel(y); + if (nel <= 0 || numel(x) < nel || numel(s) < 1) return RAD_E_SHAPE; + const float sv = ldt(s, 0); + + if (!dense_row(x) || !dense_row(y) || !rad_tensor_is_contiguous(x) || + !rad_tensor_is_contiguous(y)) { + AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN) + for (int64_t i = 0; i < nel; ++i) + stt(y, offlin(y, i), ldt(x, offlin(x, i)) * sv); + return RAD_OK; + } + + const int64_t TILE = 4096; + const int64_t ntile = (nel + TILE - 1) / TILE; + AVX_PARALLEL_FOR_IF(nel >= AVX_PAR_MIN) + for (int64_t t = 0; t < ntile; ++t) { + const int64_t off = t * TILE; + const int64_t m = (nel - off) < TILE ? (nel - off) : TILE; + float* sbuf = scratch_f32((size_t)TILE); + float* so = scratch_f32_b((size_t)TILE); + const float* v = in_row(x, off, m, sbuf); + const vf sc = vf_set1(sv); + int64_t i = 0; + for (; i + VF_N <= m; i += VF_N) + vf_storeu(so + i, vf_mul(vf_loadu(v + i), sc)); + for (; i < m; ++i) + so[i] = v[i] * sv; + out_row(y, off, m, so); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ gather_rows */ /* y[i, :] = x[idx[i], :]. A negative index writes a ZERO ROW -- the padding rule embed_lookup * follows, and what a step with fewer sampled rows than the buffer's extent leaves behind. An diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index 090ec8ea..68a93cae 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -84,15 +84,16 @@ int avx_isa_force(int level); * suffix of every implementation symbol: avx__sc / _v1 / _v2 / _v3. */ #define AVX_OP_LIST(X) \ /* ---- elementwise and norms */ \ - X(rmsnorm) X(rmsnorm_add) X(hc_enter) X(hc_read) \ - X(hc_write) X(mtp_enter) X(layernorm) X(add) \ - X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \ - X(mul) X(silu_mul) X(gelu) X(silu) \ - X(sigmoid) X(gather_rows) X(scatter_rows) X(ngram_ids) \ + X(rmsnorm) X(rmsnorm_p) X(rmsnorm_add) X(hc_enter) \ + X(hc_read) X(hc_write) X(mtp_enter) X(layernorm) \ + X(add) X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \ + X(mul) X(silu_mul) X(gelu_mul) X(gelu) \ + X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \ + X(scatter_rows) X(ngram_ids) \ X(ple_gate) X(ple_conv) X(cast) X(softmax) \ - X(scale_rows) X(fill) X(act_mul) X(seg_mean) \ - X(mul_weight) X(pool_rows) X(relu) X(clamp) \ - X(conv2d) X(conv1d_dw) X(rel_sinusoid) \ + X(scale_rows) X(scale) X(fill) X(act_mul) \ + X(seg_mean) X(mul_weight) X(pool_rows) X(relu) \ + X(clamp) X(conv2d) X(conv1d_dw) X(rel_sinusoid) \ /* ---- quantisation and rotation */ \ X(quant_act_i8) X(had_quant_act_i8) X(quant_act_fp8) X(had_quant_act_fp8) \ X(gram_accum) X(rmsnorm_had_quant_i8) X(gated_had_quant_i8) X(dequant) \ diff --git a/libavx/avx_norm.cpp b/libavx/avx_norm.cpp index 4323bee5..06d0632a 100644 --- a/libavx/avx_norm.cpp +++ b/libavx/avx_norm.cpp @@ -98,6 +98,36 @@ AVX_KERNEL(rmsnorm) { return RAD_OK; } +/* ------------------------------------------------------------------ rmsnorm_p */ +/* y = x * rsqrt(mean(x^2) + eps) -- the rmsnorm with no gain. Same one-conversion, two-pass shape + * and same four-accumulator sum of squares as rmsnorm; the only difference is there is no weight + * to widen and no gain to multiply in, because the op has no `w` at all. */ +AVX_KERNEL(rmsnorm_p) { + if (!rad_args_have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + const float eps = p_f32(a, "eps", 1e-6f); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(x, n); + if (rows <= 0 || numel(y) < rows * n) return RAD_E_SHAPE; + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* sx = scratch_f32((size_t)n); + float* sy = scratch_f32_b((size_t)n); + const float* v = in_row(x, rowoff(x, r, n), n, sx); + const float ss = row_sumsq(v, n); + const float s = 1.0f / std::sqrt(ss / (float)n + eps); + const vf vs = vf_set1(s); + int64_t i = 0; + for (; i + VF_N <= n; i += VF_N) + vf_storeu(sy + i, vf_mul(vf_loadu(v + i), vs)); + for (; i < n; ++i) sy[i] = v[i] * s; + out_row(y, rowoff(y, r, n), n, sy); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ rmsnorm_add */ /* residual_out = x + residual; y = rmsnorm(residual_out) * (w + wadd), with the variance from the * unrounded sum and the multiply from the narrowed one. */ diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 98ddc3d2..9ae6973d 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -136,6 +136,8 @@ static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coor static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") }; +/* `cap` required, for the reason libref's pMnCap states: a softcap without a cap is a different op. */ +static const RadParamSpec pMnCap[] = { P_INT("M"), P_INT("n"), P_F64("cap"), P_STR("dtype") }; static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") }; static const RadOperandSpec oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") }; static const RadParamSpec pActMul[] = { P_INT("M"), P_INT("n"), P_STR("act"), P_STR("dtype") }; @@ -167,6 +169,7 @@ static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OP /* `fill` has no input: `value` is the whole of what it writes. */ static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") }; static const RadOperandSpec oFill[] = { OUT("y") }; +static const RadOperandSpec oScale[] = { OPD("x"), WGT("s"), OUT("y") }; static const RadOperandSpec oGather[] = { OPD("x"), OPD("idx"), OUT("y") }; static const RadOperandSpec oScatterRows[] = { OPD("v"), OPD("idx"), INOUT("x") }; @@ -255,13 +258,15 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_ P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"), P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"), P_F64O("yarn_factor"), P_F64O("yarn_low"), - P_F64O("yarn_high"), P_F64O("yarn_magnitude") }; + P_F64O("yarn_high"), P_F64O("yarn_magnitude"), + P_STRO("ladder") }; static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") }; static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"), P_F64("scale"), P_STR("dtype"), P_F64O("yarn_factor"), P_F64O("yarn_low"), - P_F64O("yarn_high"), P_F64O("yarn_magnitude") }; + P_F64O("yarn_high"), P_F64O("yarn_magnitude"), + P_INTO("head_dim"), P_STRO("ladder") }; static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") }; /* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio` @@ -481,6 +486,9 @@ static const RadOpSchema kSchemas[] = { { "rmsnorm", ARR(pRmsnorm), ARR(oRmsnorm), "y = x * rsqrt(mean(x^2) + eps) * (w + wadd). The sum of squares is a four-accumulator vector " "reduction, so it does not sum in libref's order and does not claim to." }, +{ "rmsnorm_p", ARR(pLayernorm), ARR(oUnary), + "y = x * rsqrt(mean(x^2) + eps), the rmsnorm with no gain at all. Same four-accumulator sum of " + "squares as rmsnorm; the only difference is there is no weight to widen, so the op has no `w`." }, { "rmsnorm_add", ARR(pRmsnormAdd), ARR(oRmsnormAdd), "residual_out = x + residual, then y = rmsnorm(residual_out) * w. The variance is taken from the " "unrounded f32 sum and the multiply reads residual_out back AFTER narrowing -- both are libref's " @@ -524,10 +532,15 @@ static const RadOpSchema kSchemas[] = { "y[r] = the mean of x's rows [r*k, r*k + k), rounded to y's dtype, times mult, rounded again." }, { "silu_mul", ARR(pMnD), ARR(oGateUp), "silu-gated product over a fused [M, 2n] gate_up: y = silu(gate) * up." }, +{ "gelu_mul", ARR(pMnD), ARR(oGateUp), + "gelu_mul over a fused [M, 2n] gate_up: y = gelu_tanh(gate) * up, gate the FIRST half, the tanh " + "form (libref's act_gelu_tanh, std::tanh) rather than the exact-erf gelu." }, { "gelu", ARR(pMnD), ARR(oUnary), "exact erf gelu." }, { "silu", ARR(pMnD), ARR(oUnary), "silu." }, { "sigmoid", ARR(pMnD), ARR(oUnary), "logistic sigmoid." }, { "fill", ARR(pFill), ARR(oFill), "y = value over [M, n], rounded once to y's dtype (default 0)." }, +{ "logit_softcap", ARR(pMnCap), ARR(oUnary), "cap * tanh(x / cap), the final-logit softcap." }, +{ "scale", ARR(pMnD), ARR(oScale), "y = x * s, s a [1] weight broadcast over every element." }, { "ple_gate", ARR(pPleGate), ARR(oPleGate), "PLE gate: three grouped norms, a dot, a signed sqrt." }, { "ple_conv", ARR(pPleConv), ARR(oPleConv), @@ -692,6 +705,8 @@ AVX_OP_LIST(AVX_THUNK_DECL) static const RadKernelInfo kKernels[] = { SIMPLE("avx_rmsnorm", "rmsnorm", "norm", "root-mean-square norm with a gain", DT_FLOAT, L(rmsnorm)), +SIMPLE("avx_rmsnorm_p", "rmsnorm_p", "norm", "weightless RMS norm (no gain)", DT_FLOAT, + L(rmsnorm_p)), SIMPLE("avx_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", DT_FLOAT, L(rmsnorm_add)), SIMPLE("avx_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT, @@ -731,10 +746,15 @@ SIMPLE("avx_attn_local_rel", "attn_local_rel", "attn", L(attn_local_rel)), SIMPLE("avx_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT, L(silu_mul)), +SIMPLE("avx_gelu_mul", "gelu_mul", "elem", "gelu_tanh-gated product over a fused gate_up", DT_FLOAT, + L(gelu_mul)), SIMPLE("avx_gelu", "gelu", "elem", "exact erf gelu", DT_FLOAT, L(gelu)), SIMPLE("avx_silu", "silu", "elem", "silu", DT_FLOAT, L(silu)), SIMPLE("avx_sigmoid", "sigmoid", "elem", "logistic sigmoid", DT_FLOAT, L(sigmoid)), SIMPLE("avx_fill", "fill", "elem", "constant fill", DT_FLOAT, L(fill)), +SIMPLE("avx_logit_softcap", "logit_softcap", "elem", "final-logit softcap: cap * tanh(x / cap)", + DT_FLOAT, L(logit_softcap)), +SIMPLE("avx_scale", "scale", "elem", "a [1] weight broadcast over every element", DT_FLOAT, L(scale)), SIMPLE("avx_gather_rows", "gather_rows", "elem", "y[i,:] = x[idx[i],:]", DT_ANY, L(gather_rows)), SIMPLE("avx_scatter_rows", "scatter_rows", "elem", "x[idx[i],:] = v[i,:]", DT_ANY, L(scatter_rows)), diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index d36d4198..b228c10e 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -57,6 +57,13 @@ set(RAD_W4_GROUP 128 CACHE STRING "libr4d quantised-weight group size (must matc set(R4D_UNITS "r4d_attn_paged_h256_gqa6|" "r4d_attn_paged_h128_gqa4|" + # Gemma 4 dense sliding window: head_dim 256, 2 queries per KV head, windowed decode only + # (prefill falls to the caller's libref path). The windowed twin of the drafter leg above. + "r4d_attn_paged_h256_gqa2|" + # Gemma 4 dense global layers: head_dim 512, 8 queries per KV head, full attention (window 0). + # The head_dim the library had not compiled before -- the prefill KV tile drops to 16 to fit 64 + # KiB of LDS, and the decode combine takes the head-generic merge (DPL 16 breaks the vector form). + "r4d_attn_paged_h512_gqa8|" # Eight queries per KV head, at both head widths: the routed 35B-A3B is 16 over 2 at 256 # and MiniCPM5-2B is 16 over 2 at 128. Same device code, different instantiations. "r4d_attn_paged_gqa8|" @@ -134,6 +141,9 @@ set(R4D_UNITS "r4d_model_bf16|" "r4d_sample_stages_f32|" "r4d_quant_act_i8|" + "r4d_rmsnorm_quant_i8|" + "r4d_qkv_norm_rope|" + "r4d_gelu_mul_quant_i8|" "r4d_had_quant_act_i8|" "r4d_rmsnorm_had_quant_i8|" "r4d_ar_ln_had_quant_i8|" diff --git a/libr4d/r4d.h b/libr4d/r4d.h index b3038fbc..4827de66 100644 --- a/libr4d/r4d.h +++ b/libr4d/r4d.h @@ -108,6 +108,24 @@ int r4d_attn_h128_gqa4_have_prefill(void); // Bytes of split-KV partial buffer one decode launch of this shape needs. Independent of the cache // dtype: the partials are f16 either way. long r4d_attn_decode_h256_gqa6_scratch_bytes(const R4DArgs* a); + // The Gemma 4 dense sliding-window geometry: head_dim 256, 2 queries per KV head, sliding window. + // Both bands: the decode band (q_len*gqa <= 64, i.e. q_len <= 32) and the windowed prefill band + // (a prefill-length query, WIN on). The prefill leg is the same r4d_attn_prefill_kernel the + // h256/gqa6 and h512/gqa8 dispatches instantiate, with the window bit turned on. + int r4d_attn_prefill_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream); + int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream); + int r4d_attn_decode_h256_gqa2_fp8kv (const R4DArgs* a, hipStream_t stream); + int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t stream); + long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a); +// The Gemma 4 dense global geometry: head_dim 512, 8 queries per KV head, full attention (window 0). +// The one head_dim the library had not compiled -- a stand-alone instantiation, not the gqa8 +// parameterised body (whose prefill tile of 48 does not fit 512-channel tiles in LDS). Both legs +// spill ~384 VGPRs at this head; a 3b tuning question, not a 3a one. +int r4d_attn_prefill_h512_gqa8_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_prefill_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h512_gqa8_fp8kv (const R4DArgs* a, hipStream_t stream); +int r4d_attn_decode_h512_gqa8_bf16kv (const R4DArgs* a, hipStream_t stream); +long r4d_attn_decode_h512_gqa8_scratch_bytes(const R4DArgs* a); // The geometry the attention kernels above are compiled for, so a caller can test a model against // it instead of discovering the mismatch at the first launch. void r4d_attn_dims(int* head_dim, int* gqa, int* block_size, int* max_decode_rows); @@ -784,6 +802,15 @@ int r4d_ar_rmsnorm_quant_fp8(long peer_scratch, long my_scratch, long peer_flag long loc_pack, long loc_scale_off); int r4d_ar_rmsnorm_quant_fp8_chunk_elems(void); +// The same IPC with the sandwich-norm junction after it (r4d_rmsnorm_quant_i8.hip): post-norm of the +// reduced `x` (`wp`), the residual add, the [1] scalar (`sc`), the norm (`w`) and the w4a8 GEMM's +// per-row int8 quantiser. Exact wire only; `x` is the message and takes no pitch. +int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags, long my_flags, + long seq_ctrs, long slot_stride16, long x, long res, long w, long wp, + long sc, int sc_f32, long y, long q, long s, int M, int n, float eps, + float wadd, int w_f32, int r_ld, int y_ld, long stream, int nblocks, + int drain, int acq); + // ---- sampling ---------------------------------------------------------------------------------- // // One workgroup a position: temperature, softmax, top_k, top_p, min_p, renormalise and the draw, in @@ -896,6 +923,11 @@ void r4d_dequant_w4_bf16(long wq, long ws, long out, int N, int K, int group, in // whole table, an unsliced lookup. int r4d_embed_lookup_bf16(long tok, long wte, long x, int M, int n_embd, int n_vocab, int vocab_off, int x_ld, long stream); +// The same lookup with a RUNTIME gather scale on the rows that are found (x = table[id] * +// scale); 1.0 is the plain copy, and a missed row still writes zero rather than zero * scale. +// Gemma 4's embedding is scaled by sqrt(n_embd) at the lookup, not baked into the table. +int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, int n_embd, int n_vocab, + int vocab_off, int x_ld, float scale, long stream); int r4d_gather_rows_bf16(long x, long idx, long y, int M, int n, int src_rows, int x_ld, int y_ld, long stream); // y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in f32 after @@ -904,6 +936,9 @@ int r4d_gather_rows_bf16(long x, long idx, long y, int M, int n, int src_rows, // is -- or bf16. The activation either side is bf16 in both cases. int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, float wadd, int w_f32, int x_ld, int y_ld, long stream); +// y = x * rsqrt(mean(x^2) + eps). The weightless RMS: the same two-pass sum of squares as rmsnorm +// with the gain multiply dropped, gemma's bare value normalisation. +int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps, int x_ld, int y_ld, long stream); // `op` 0 sums, 1 multiplies. A `b_ld` of 0 is the ONE broadcast form: every row reads the same n // elements, which is what makes a bias add this op rather than a second one. int r4d_binary_bf16(long a, long b, long y, int M, int n, int op, @@ -913,6 +948,9 @@ int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long stream); // y[.., i] = silu(gu[.., i]) * gu[.., n + i]. The GATE IS THE FIRST HALF -- the order rad-convert // fuses gate_proj and up_proj in. int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream); +// y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. The GATE IS THE FIRST HALF, the tanh +// approximation (gemma's gelu_pytorch_tanh), not the erf one. +int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream); // In place over `n_rope_heads` consecutive heads of a row; anything after them (the V heads of a // fused projection) is untouched. `gptj` 0 pairs i with i + rot/2 (NeoX, and mrope, which is the // same arithmetic when every position component is equal); 1 pairs 2i with 2i+1. `rot` may be less @@ -922,9 +960,12 @@ int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int float theta, float rscale, int row_pitch, long stream); // The multi-component rotary (docs/OPS.md, `rope`): `mode` 2 mrope, 3 imrope, 4 axial over // `sec[0..n_sec)`, component c of token m at pos[c * plane + m]. plane 0 is the call above. -int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int gptj, - float theta, float rscale, int row_pitch, int mode, const int* sec, int n_sec, - int plane, long stream); +// `den` is the width the base ladder's exponent divides by: `rot` (the `rotary` ladder, the +// default) or `head_dim` (the `head` ladder, the proportional variant). The `rope` row resolves it +// from its `ladder` param; the plain form above passes `rot`. +int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den, + int gptj, float theta, float rscale, int row_pitch, int mode, const int* sec, + int n_sec, int plane, long stream); // C[M,N] f32 = A[M,K] bf16 @ W[N,K]^T bf16, f32 accumulate. THE OUTPUT IS f32 and that is why this // is not r4d_gemm_bf16_nt_m16 under another name: the engine declares its logits buffer f32, // because a bf16 logit has eight bits of mantissa and a nucleus cut compares neighbouring diff --git a/libr4d/r4d_ar_entry.hip b/libr4d/r4d_ar_entry.hip index 65bd7d87..755c8336 100644 --- a/libr4d/r4d_ar_entry.hip +++ b/libr4d/r4d_ar_entry.hip @@ -1246,6 +1246,62 @@ extern "C" int r4d_rad_ar_rmsnorm_quant_fp8(const RadArgs* a, RadStream s) { return e == 0 ? RAD_OK : RAD_E_SHAPE; } +/* THE ALL-REDUCE AND THE SANDWICH-NORM JUNCTION AFTER IT, int8 out: `all_reduce` (exact) of `x`, then + * `rmsnorm_quant_i8` -- post-norm of the reduced x, the residual add, the scalar, the norm and the + * per-row int8 quantiser the w4a8 skinny GEMM reads. Operands are rmsnorm_quant_i8's with `x` + * INOUT, because it is the message and the reduced sum lands back in it. The exact wire only: a + * deployment that allows the lossy one keeps the standalone all-reduce. Width and block count as + * ar_rmsnorm_quant_fp8 resolves them, for the same reasons: the norm's width from M, one block a + * row. */ +enum { AQ8_X = 0, AQ8_RES, AQ8_W, AQ8_Q, AQ8_S, AQ8_Y, AQ8_WP, AQ8_SC }; + +extern "C" int r4d_rad_ar_rmsnorm_quant_i8(const RadArgs* a, RadStream s) { + const ArInst* in = (const ArInst*)(a ? a->instance : nullptr); + if (!in) return RAD_E_STATE; + if (in->world != 2) return RAD_E_SHAPE; + const RadTensor* x = r4d_opt(a, AQ8_X); + const RadTensor* rs = r4d_opt(a, AQ8_RES); + const RadTensor* w = r4d_opt(a, AQ8_W); + const RadTensor* q = r4d_opt(a, AQ8_Q); + const RadTensor* sc = r4d_opt(a, AQ8_S); + const RadTensor* ob = r4d_opt(a, AQ8_Y); + const RadTensor* wp = r4d_opt(a, AQ8_WP); + const RadTensor* sl = r4d_opt(a, AQ8_SC); + if (!x || !w || !q || !sc) return RAD_E_INVAL; + if ((wp || sl) && !rs) return RAD_E_INVAL; + if (!r4d_contig(w) || (wp && !r4d_contig(wp))) return RAD_E_STRIDE; + if (x->dtype != RAD_BF16 || q->dtype != RAD_I8 || sc->dtype != RAD_F32) return RAD_E_DTYPE; + long long M = 0, K = 0; + if (r4d_rows_of(x, &M, &K) != RAD_OK) return RAD_E_SHAPE; + if (M * K > in->max_numel) return RAD_E_SHAPE; + if (K % 16) return RAD_E_SHAPE; + if (r4d_numel(w) != K || (w->dtype != RAD_F32 && w->dtype != RAD_BF16)) return RAD_E_DTYPE; + if (wp && (r4d_numel(wp) != K || wp->dtype != w->dtype)) return RAD_E_SHAPE; + if (sl && (r4d_numel(sl) != 1 || (sl->dtype != RAD_F32 && sl->dtype != RAD_BF16))) return RAD_E_SHAPE; + if (r4d_numel(q) != M * K || !r4d_contig(q)) return RAD_E_SHAPE; + if (r4d_numel(sc) != M || !r4d_contig(sc)) return RAD_E_SHAPE; + if (ob && r4d_numel(ob) != M * K) return RAD_E_SHAPE; + if (rs && r4d_numel(rs) != M * K) return RAD_E_SHAPE; + const long long xp = r4d_row_pitch(x), yp = ob ? r4d_row_pitch(ob) : 0, rp = rs ? r4d_row_pitch(rs) : 0; + if (xp != K || yp < 0 || rp < 0) return RAD_E_STRIDE; /* x is the message: tight */ + if (r4d_geti_or(a, "wire", 0) != 0) return RAD_E_INVAL; + + R4dArCfg cfgv; + r4d_cfg_ar(a, &cfgv); + int nblocks = cfgv.nblocks > 0 ? cfgv.nblocks : (int)M; + if (nblocks > (int)M) nblocks = (int)M; + if (nblocks > 256) nblocks = 256; + if (nblocks > in->max_blocks) nblocks = in->max_blocks; + if (nblocks < 1) nblocks = 1; + const int e = r4d_ar_rmsnorm_quant_i8( + in->peer_scratch[0], in->my_scratch, in->peer_flags[0], in->my_flags, in->my_seq, + in->slot16, r4d_addr(x), r4d_addr(rs), r4d_addr(w), r4d_addr(wp), r4d_addr(sl), + sl ? (sl->dtype == RAD_F32) : 0, r4d_addr(ob), r4d_addr(q), r4d_addr(sc), (int)M, (int)K, + (float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 0.0), w->dtype == RAD_F32, + (int)rp, (int)yp, (long)(uintptr_t)s, nblocks, cfgv.drain, cfgv.acq); + return e == 0 ? RAD_OK : RAD_E_SHAPE; +} + /* THE ALL-REDUCE WITH THE GATED RESIDUAL'S WRITE IN IT: `all_reduce` of `y` and then `hc_write` * of the reduced `y` into `h`, one kernel. A block whose output feeds a hyper-connection write * skips its own collective when this runs, and the write carries it. diff --git a/libr4d/r4d_attn_paged_h256_gqa2.hip b/libr4d/r4d_attn_paged_h256_gqa2.hip new file mode 100644 index 00000000..d06574a7 --- /dev/null +++ b/libr4d/r4d_attn_paged_h256_gqa2.hip @@ -0,0 +1,174 @@ +// R4D attention dispatch for the Gemma 4 dense model's sliding-window geometry: head_dim 256, +// 2 queries per KV head, paged block 16, and a SLIDING WINDOW (window 1024 in the model, 50 of its +// 60 layers). It is the same device code as the 27B target's h256/gqa6 dispatch -- the kernels are +// templates on head_dim and gqa, so this file is another set of instantiations, not a second +// kernel -- with the window bit (template arg WIN) turned on, the way the DFlash2 drafter leg does +// it at head_dim 128. +// +// Both bands, now. The decode band (q_len * gqa <= 64, i.e. q_len <= 32 at gqa 2) is the +// windowed decode kernel above. The prefill band (a query long enough to want the query-tiled +// prefill kernel) is the windowed prefill kernel below -- the same r4d_attn_prefill_kernel the +// h256/gqa6 and h512/gqa8 dispatches instantiate, with the window bit (template arg WIN) turned on, +// the way the decode leg does. A trunk layer prefills, so it needs the prefill band on the device: +// libref is an opt-in fallback the engine refuses by default (spec §17). The drafter leg is +// decode-only because a drafter never prefills. +#include "r4d.h" +#include "r4d_attn_args.h" +#include "r4d_common.h" +#include +#include +using std::max; +// The decode and prefill kernels share their query conversion and fragment helpers, so the prefill +// header comes first here for the same reason it does in the h256 dispatch. This translation unit +// instantiates BOTH r4d_attn_prefill_kernel (below, WIN=1) and the windowed decode kernel. +#include "r4d_attn_prefill_h256_gqa6.hip" +#include "r4d_attn_decode_h256_gqa6.hip" + +#define CHK4() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0) + +#define B_HEAD_DIM 256 +#define B_GQA 2 +#define B_BLOCK_SIZE 16 +#define B_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold +#define B_TILE 16 +// The same option set the h256 decode kernel ships, K prefetch of 2 included. At head_dim 256 it +// is the same register picture gqa6 has (256 VGPRs with a small spill), so this is a correctness +// instantiation here -- the register count is a 3b tuning question, not a 3a one. The window bit +// is already in the template; this file only turns it on. +#define B_OPT 3429947 +#ifndef B_JPB +#define B_JPB 2 +#endif +#ifndef B_VECMIN +#define B_VECMIN 256 +#endif + +// Split law, the drafter leg's with the same window-aware term. It aims at 192 workgroups, snaps +// DOWN to a power of two but never below 16, clamps to at least two tiles a segment, and then steps +// UP off the exact grid size `splits * units == 256`, a pothole in this geometry's timing. +// +// THE WINDOW-AWARE TERM is the one thing it does that the h256 full-attention law does not: under a +// sliding window the context the kernel actually walks is the window, not the sequence, so the tile +// count that feeds the machine-fill target and the thin-segment clamp comes from the window. +// Without that the law reads a 16K sequence and asks for segments two tiles deep off a 1024-token +// walk. +static int decode_splits_h256_gqa2(const R4DArgs* a) { + if (a->splits > 0) return a->splits; + const int span = (a->window > 0 && a->window + a->q_len < a->max_ctx) + ? a->window + a->q_len : a->max_ctx; + const int tiles = (span + B_TILE - 1) / B_TILE; + const int units = std::max(1, a->kv_heads * a->num_seqs); + const int raw = 192 / units; + int s = 128; + while (s > 16 && s > raw) s >>= 1; + const int cap = tiles / 2; + while (s > 16 && s > cap) s >>= 1; + if (s > tiles) s = tiles; + if (s < 1) s = 1; + if (s * units == 256 && s * 2 <= tiles) s <<= 1; // step off the pothole, see above + return s; +} + +extern "C" long r4d_attn_decode_h256_gqa2_scratch_bytes(const R4DArgs* a) { + const int splits = decode_splits_h256_gqa2(a); + const long rows = (long)r4d_q_total(*a) * a->q_heads; + return (B_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8) + : rows * splits * (long)(a->head_dim + 2) * 4L; +} + +template +static int decode_launch_h256_gqa2(const R4DArgs* a, hipStream_t s) { + if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1; + if (a->q_heads / a->kv_heads != B_GQA) return -2; + const int rows = a->q_len * B_GQA; + if (rows > B_MAX_DECODE_ROWS) return -4; + const int nw = (rows + 15) / 16; + const int splits = decode_splits_h256_gqa2(a); + +#define B_LAUNCH(NW) \ + hipLaunchKernelGGL((r4d_attn_decode_kernel), \ + dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits) + if (nw == 1) B_LAUNCH(1); + else if (nw == 2) B_LAUNCH(2); + else if (nw == 3) B_LAUNCH(3); + else B_LAUNCH(4); +#undef B_LAUNCH + CHK4(); + + // Same two merge forms, and the same rule for choosing between them, as the h256 dispatch: + // a wave a row while there are enough rows to fill the part and the segment count fits a + // wave, the general LDS-tree form otherwise. Both produce the same bytes, and both carry the + // window bit here (the final template argument) for the same reason the decode kernel does. + const int jobs3 = r4d_q_total(*a) * a->q_heads; + if (splits <= 64 && jobs3 >= B_VECMIN) { + const int blocks = (jobs3 + B_JPB - 1) / B_JPB; + if (B_OPT & 32) + hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel), + dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE); + else + hipLaunchKernelGGL((r4d_attn_splitkv_combine_vec_kernel), + dim3(blocks), dim3(32 * B_JPB), 0, s, *a, splits, B_TILE); + } else if (B_OPT & 32) + hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), + dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE); + else + hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), + dim3(B_HEAD_DIM), splits * sizeof(float), s, *a, splits, B_TILE); + CHK4(); + return 0; +} + +extern "C" int r4d_attn_decode_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s) { + return decode_launch_h256_gqa2<0>(a, s); +} +extern "C" int r4d_attn_decode_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) { + return decode_launch_h256_gqa2<1>(a, s); +} + +// ---- prefill --------------------------------------------------------------------------------- +// The h256/gqa6 prefill option set (P_OPT 3955211) is reused unchanged: at head_dim 256 the wide K +// fetch (O_KWIDE) is valid -- it is written for 16 channels = head_dim 256 exactly -- so unlike the +// h512 leg (which turns it off because 512 reads past the tile) this one keeps it. gqa 2 makes +// BLOCK_Q (NWARPS*16/2 = 192) larger than gqa 6's 64, so a workgroup covers more query positions: +// fewer grid.x blocks, the same KV tile. WIN is on (the last template arg); window <= 0 folds it +// away to the full-attention form, so a windowless launch is safe. +#define P_NWARPS 24 +#define P_TILE 48 +#define P_OPT 3955211 + +template +static int prefill_launch_h256_gqa2(const R4DArgs* a, hipStream_t s) { + if (a->head_dim != B_HEAD_DIM || a->block_size != B_BLOCK_SIZE) return -1; + if (a->q_heads / a->kv_heads != B_GQA) return -2; + constexpr int BQ = (P_NWARPS * 16) / B_GQA; + dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs); + hipLaunchKernelGGL((r4d_attn_prefill_kernel), + grid, dim3(P_NWARPS * 32), 0, s, *a); + CHK4(); + return 0; +} + +extern "C" int r4d_attn_prefill_h256_gqa2_fp8kv(const R4DArgs* a, hipStream_t s) { + return prefill_launch_h256_gqa2<0>(a, s); +} +extern "C" int r4d_attn_prefill_h256_gqa2_bf16kv(const R4DArgs* a, hipStream_t s) { + return prefill_launch_h256_gqa2<1>(a, s); +} + +/* The prefill RadArgs wrappers, defined here (not in the h256 dispatch) for the same reason the + * h512 leg's live in theirs: an entry point appended to a textual inclusion compiles into nothing. + * Absent descales mean 1.0 (fill_paged leaves them null and the kernel reads 1.0). */ +extern "C" int r4d_rad_attn_prefill_h256_gqa2_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = fill_paged(a, &r, B_HEAD_DIM); + if (rc != RAD_OK) return rc; + return r4d_attn_prefill_h256_gqa2_fp8kv(&r, (hipStream_t)s); +} +extern "C" int r4d_rad_attn_prefill_h256_gqa2_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = fill_paged(a, &r, B_HEAD_DIM); + if (rc != RAD_OK) return rc; + return r4d_attn_prefill_h256_gqa2_bf16kv(&r, (hipStream_t)s); +} diff --git a/libr4d/r4d_attn_paged_h256_gqa6.hip b/libr4d/r4d_attn_paged_h256_gqa6.hip index 781fc281..b6a67c85 100644 --- a/libr4d/r4d_attn_paged_h256_gqa6.hip +++ b/libr4d/r4d_attn_paged_h256_gqa6.hip @@ -254,6 +254,15 @@ extern "C" int r4d_rad_attn_prefill_h256_bf16(const RadArgs* a, RadStream s) { * step off its pothole doubles the splits at one count and not at the next. A step may carry any * count up to the bound, so the region is the largest over all of them. The laws are closed forms * and this runs at declare, so the sweep costs nothing a step. */ +// One hook per geometry but one shared (seqs x heads x rows) partial layout, so the worst-over- +// the-batch sweep below asks each geometry its own bytes in one place instead of triplicating the +// sweep. which: 0 = h256/gqa6, 1 = h128/gqa4, 2 = h256/gqa2 (the Gemma 4 windowed leg). +static int64_t decode_scratch_bytes_of(const R4DArgs* r, int which) { + if (which == 1) return (int64_t)r4d_attn_decode_h128_gqa4_scratch_bytes(r); + if (which == 2) return (int64_t)r4d_attn_decode_h256_gqa2_scratch_bytes(r); + return (int64_t)r4d_attn_decode_h256_gqa6_scratch_bytes(r); +} + static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) { const int sp = split_of(a); if (sp < 0) return R4D_NO(RAD_E_INVAL); @@ -278,8 +287,7 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) { int64_t worst = 0; for (long long n = 1; n <= max_seqs; ++n) { r.num_seqs = (int)n; - const int64_t need = which == 0 ? r4d_attn_decode_h256_gqa6_scratch_bytes(&r) - : r4d_attn_decode_h128_gqa4_scratch_bytes(&r); + const int64_t need = decode_scratch_bytes_of(&r, which); if (need > worst) worst = need; } return worst; @@ -288,8 +296,7 @@ static int64_t decode_scratch(const RadArgs* a, int head_dim, int which) { int rc = fill_paged(a, &r, head_dim); if (rc != RAD_OK) return rc; r.splits = sp; - return which == 0 ? r4d_attn_decode_h256_gqa6_scratch_bytes(&r) - : r4d_attn_decode_h128_gqa4_scratch_bytes(&r); + return decode_scratch_bytes_of(&r, which); } extern "C" int64_t r4d_rad_attn_decode_h256_scratch(const RadArgs* a) { @@ -306,8 +313,7 @@ static int decode_common(const RadArgs* a, R4DArgs* r, int head_dim, int which) int rc = fill_paged(a, r, head_dim); if (rc != RAD_OK) return rc; r->splits = sp; - const int64_t need = (which == 0) ? r4d_attn_decode_h256_gqa6_scratch_bytes(r) - : r4d_attn_decode_h128_gqa4_scratch_bytes(r); + const int64_t need = decode_scratch_bytes_of(r, which); if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH); return RAD_OK; } @@ -343,3 +349,26 @@ extern "C" int r4d_rad_attn_decode_h128_bf16(const RadArgs* a, RadStream s) { if (rc != RAD_OK) return rc; return r4d_attn_decode_h128_gqa4_bf16kv(&r, (hipStream_t)s); } + +/* Gemma 4 dense sliding window -- head_dim 256, 2 queries per KV head, window 1024. Decode only; + * a prefill step does not match the row's q_len band and takes the caller's (windowed) fallback. + * Same shape as the drafter leg above (h128): one `which` routing to the gqa2 scratch law and the + * gqa2 decode launch, no check_dims_once because this is not the geometry that reports dims. */ +extern "C" int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs* a) { + return decode_scratch(a, 256, 2); +} + +extern "C" int r4d_rad_attn_decode_h256_gqa2_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 256, 2); + if (rc != RAD_OK) return rc; + /* Absent descales mean 1.0; see the prefill twin above. */ + return r4d_attn_decode_h256_gqa2_fp8kv(&r, (hipStream_t)s); +} + +extern "C" int r4d_rad_attn_decode_h256_gqa2_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = decode_common(a, &r, 256, 2); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h256_gqa2_bf16kv(&r, (hipStream_t)s); +} diff --git a/libr4d/r4d_attn_paged_h512_gqa8.hip b/libr4d/r4d_attn_paged_h512_gqa8.hip new file mode 100644 index 00000000..a92e0f61 --- /dev/null +++ b/libr4d/r4d_attn_paged_h512_gqa8.hip @@ -0,0 +1,212 @@ +// R4D attention dispatch for the Gemma 4 dense model's GLOBAL layers: head_dim 512, 8 queries per +// KV head, full attention (window 0), paged block 16. This is the one head_dim the library has not +// compiled before -- no h512 kernel existed -- so this file is a real new instantiation, not a +// rename. It is the same device code as the h256/gqa6 and gqa8 dispatches (the kernels are +// templates on head_dim and gqa), with the two changes head_dim 512 forces: +// +// PREFILL -- TILE 16, not 48. The 16-bit K+V tiles are sK[TILE*(512+8)] + sV16[512*(TILE+8)]; +// at TILE 48 that is 107264 B, past the 64 KiB of LDS the part has, and only TILE 16 clears it +// (41216 B). The prefill warps tile the QUERY dimension (BLOCK_Q = NWARPS*16/gqa) and loop the +// KV in TILE chunks, so shrinking the KV tile costs loop iterations, not a different tiling. +// `O_KWIDE` is off -- its thread-to-(key,channel) map is written for 16 channels, head_dim 256 +// exactly, and at 512 it would read past the tile; the h128 prefill runs the same set minus it, +// so the non-wide path is already a shipped, correct one. +// +// DECODE -- the split-KV combine is the HEAD-GENERIC plain form (one thread per channel, a block +// of head_dim threads), not the vectorised form: that one pins a lane's width to eight or four +// dwords, and head_dim 512 would give it sixteen and refuse to compile. The plain form is slower +// but merges off the decode critical path; the trade is a 3b question. +// +// Register pressure at head_dim 512 is the one thing this file does not fix -- a thread carries +// head_dim/16 query fragments plus head_dim/8 accumulator floats, ~384 VGPRs, which the part tops +// out at, so both legs spill. That is correct and a tuning (3b) question, not a 3a one. +#include "r4d.h" +#include "r4d_attn_args.h" +#include "r4d_common.h" +#include +#include +using std::max; +#include "r4d_attn_prefill_h256_gqa6.hip" +#include "r4d_attn_decode_h256_gqa6.hip" + +#define CHK5() do { hipError_t e_ = hipGetLastError(); if (e_ != hipSuccess) return -100 - (int)e_; } while (0) + +#define H5_HEAD_DIM 512 +#define H5_GQA 8 +#define H5_BLOCK_SIZE 16 +#define H5_MAX_DECODE_ROWS 64 // q_len * gqa a single decode workgroup can hold: q_len <= 8 +// The h256 prefill option set (3955211) minus O_KWIDE -- the only head-512 option change; the h128 +// prefill ships this exact number. +#define H5_P_NWARPS 24 +#define H5_P_TILE 16 // the KV tile that fits 64 KiB LDS at head_dim 512 (see above) +#define H5_P_OPT 3430923 +#define H5_D_TILE 16 +#define H5_D_OPT 3429947 // the shared decode opt set; bit 32 (f16 partials) is set +#define H5_D_JPB 2 +#define H5_D_VECMIN 256 + +// ---- prefill ----------------------------------------------------------------------------------- +template +static int h5_prefill_launch(const R4DArgs* a, hipStream_t s) { + if (a->head_dim != H5_HEAD_DIM || a->block_size != H5_BLOCK_SIZE) return -1; + if (a->q_heads / a->kv_heads != H5_GQA) return -2; + constexpr int BQ = (H5_P_NWARPS * 16) / H5_GQA; + dim3 grid((a->q_len + BQ - 1) / BQ, a->kv_heads, a->num_seqs); + hipLaunchKernelGGL((r4d_attn_prefill_kernel), + grid, dim3(H5_P_NWARPS * 32), 0, s, *a); + CHK5(); + return 0; +} + +extern "C" int r4d_attn_prefill_h512_gqa8_fp8kv(const R4DArgs* a, hipStream_t s) { + return h5_prefill_launch<0>(a, s); +} +extern "C" int r4d_attn_prefill_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t s) { + return h5_prefill_launch<1>(a, s); +} + +// ---- decode ------------------------------------------------------------------------------------ +// The h256 full-attention split law: as many workgroups as fit under 128, at least two tiles a +// segment. It reads kv_heads, num_seqs and max_ctx and nothing about gqa or head_dim, so there is +// nothing to re-derive for this geometry; a window does not exist at full attention. +static int h5_decode_splits(const R4DArgs* a) { + if (a->splits > 0) return a->splits; + const int tiles = (a->max_ctx + H5_D_TILE - 1) / H5_D_TILE; + const int units = max(1, a->kv_heads * a->num_seqs); + int s = 128 / units; + const int cap = tiles / 2; + if (s > cap) s = cap; + if (s > tiles) s = tiles; + if (s < 1) s = 1; + return s; +} + +extern "C" long r4d_attn_decode_h512_gqa8_scratch_bytes(const R4DArgs* a) { + const int splits = h5_decode_splits(a); + const long rows = (long)r4d_q_total(*a) * a->q_heads; + return (H5_D_OPT & 32) ? rows * splits * (long)(a->head_dim * 2 + 8) + : rows * splits * (long)(a->head_dim + 2) * 4L; +} + +template +static int h5_decode_launch(const R4DArgs* a, hipStream_t s) { + if (a->head_dim != H5_HEAD_DIM || a->block_size != H5_BLOCK_SIZE) return -1; + if (a->q_heads / a->kv_heads != H5_GQA) return -2; + const int rows = a->q_len * H5_GQA; + if (rows > H5_MAX_DECODE_ROWS) return -4; + const int nw = (rows + 15) / 16; + const int splits = h5_decode_splits(a); + +#define H5_LAUNCH(NW) \ + hipLaunchKernelGGL((r4d_attn_decode_kernel), \ + dim3(splits, a->kv_heads, a->num_seqs), dim3(NW * 32), 0, s, *a, splits) + if (nw == 1) H5_LAUNCH(1); + else if (nw == 2) H5_LAUNCH(2); + else if (nw == 3) H5_LAUNCH(3); + else H5_LAUNCH(4); +#undef H5_LAUNCH + CHK5(); + + // The head-generic plain combine, always: a single thread per channel, one block of head_dim + // threads, no DPL to trip on at 512. H5_D_OPT carries bit 32 (f16 partials), so it reads them + // as such; the f32 half is spelled for the same guard the other dispatches use, not expected. + const int jobs3 = r4d_q_total(*a) * a->q_heads; + if (H5_D_OPT & 32) + hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), + dim3(H5_HEAD_DIM), splits * sizeof(float), s, *a, splits, H5_D_TILE); + else + hipLaunchKernelGGL((r4d_attn_splitkv_combine_kernel), dim3(jobs3), + dim3(H5_HEAD_DIM), splits * sizeof(float), s, *a, splits, H5_D_TILE); + CHK5(); + return 0; +} + +extern "C" int r4d_attn_decode_h512_gqa8_fp8kv(const R4DArgs* a, hipStream_t s) { + return h5_decode_launch<0>(a, s); +} +extern "C" int r4d_attn_decode_h512_gqa8_bf16kv(const R4DArgs* a, hipStream_t s) { + return h5_decode_launch<1>(a, s); +} + +// ============================================================== the plugin ABI entry points +// Defined here, in this translation unit, for the same reason the h128 drafter's live in theirs: +// the prefill and decode headers are textual inclusions, and an entry point appended to either +// compiles into nothing, leaving the .so with an undefined symbol only r4d_selftest would catch. + +extern "C" int r4d_rad_attn_prefill_h512_gqa8_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = fill_paged(a, &r, 512); + if (rc != RAD_OK) return rc; + /* Absent descales mean 1.0; see the prefill twins in the h256 dispatch. */ + return r4d_attn_prefill_h512_gqa8_fp8kv(&r, (hipStream_t)s); +} +extern "C" int r4d_rad_attn_prefill_h512_gqa8_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = fill_paged(a, &r, 512); + if (rc != RAD_OK) return rc; + return r4d_attn_prefill_h512_gqa8_bf16kv(&r, (hipStream_t)s); +} + +/* The split-KV partial buffer, sized at declare from the batch's worst step, the way the other + * decode geometries do it. The h256 split law makes splits * num_seqs flat, but its clamp to + * `>= 2 tiles a segment` breaks that at large batches, so the sweep over every count to the bound + * is still the right size even at full attention. */ +extern "C" int64_t r4d_rad_attn_decode_h512_gqa8_scratch(const RadArgs* a) { + const int sp = split_of(a); + if (sp < 0) return R4D_NO(RAD_E_INVAL); + + R4DArgs r; + const long long n_head = r4d_geti_or(a, "n_head", 0); + const long long max_seqs = r4d_geti_or(a, "max_seqs", 0); + if (n_head > 0 && max_seqs > 0) { + std::memset(&r, 0, sizeof(r)); + r.head_dim = H5_HEAD_DIM; + r.q_heads = (int)n_head; + r.kv_heads = (int)(n_head / H5_GQA); + r.num_seqs = (int)max_seqs; + r.q_len = (int)r4d_geti_or(a, "q_len", 1); + r.max_ctx = (int)r4d_geti_or(a, "max_ctx", 0); + r.block_size = (int)r4d_geti_or(a, "block_size", 16); + r.splits = sp; + if (r.max_ctx <= 0) return R4D_NO(RAD_E_INVAL); + int64_t worst = 0; + for (long long n = 1; n <= max_seqs; ++n) { + r.num_seqs = (int)n; + const int64_t need = r4d_attn_decode_h512_gqa8_scratch_bytes(&r); + if (need > worst) worst = need; + } + return worst; + } + + int rc = fill_paged(a, &r, H5_HEAD_DIM); + if (rc != RAD_OK) return rc; + r.splits = sp; + return r4d_attn_decode_h512_gqa8_scratch_bytes(&r); +} + +static int h5_decode_common(const RadArgs* a, R4DArgs* r, int which) { + const int sp = split_of(a); + if (sp < 0) return R4D_NO(RAD_E_INVAL); + int rc = fill_paged(a, r, H5_HEAD_DIM); + if (rc != RAD_OK) return rc; + r->splits = sp; + const int64_t need = r4d_attn_decode_h512_gqa8_scratch_bytes(r); + if (!a->scratch || a->scratch_bytes < need) return R4D_NO(RAD_E_SCRATCH); + return RAD_OK; +} + +extern "C" int r4d_rad_attn_decode_h512_gqa8_fp8(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = h5_decode_common(a, &r, 0); + if (rc != RAD_OK) return rc; + /* Absent descales mean 1.0; see the prefill twin above. */ + return r4d_attn_decode_h512_gqa8_fp8kv(&r, (hipStream_t)s); +} +extern "C" int r4d_rad_attn_decode_h512_gqa8_bf16(const RadArgs* a, RadStream s) { + R4DArgs r; + int rc = h5_decode_common(a, &r, 1); + if (rc != RAD_OK) return rc; + return r4d_attn_decode_h512_gqa8_bf16kv(&r, (hipStream_t)s); +} diff --git a/libr4d/r4d_attn_prefill_h256_gqa6.hip b/libr4d/r4d_attn_prefill_h256_gqa6.hip index cf54bbb7..6e124859 100644 --- a/libr4d/r4d_attn_prefill_h256_gqa6.hip +++ b/libr4d/r4d_attn_prefill_h256_gqa6.hip @@ -76,7 +76,12 @@ __device__ __forceinline__ uint32_t r4d_qcvt(uint32_t w, float s) { __builtin_bit_cast(float, w & 0xffff0000u) * s); } -template +// WIN turns on a sliding window (a.window positions, ending at each row's causal limit), the way +// the decode kernel's WIN does. The window's lower bound masks the keys before it, and the KV walk +// starts at the tile holding the window's first token (taken at query row 0, whose window reaches +// furthest back) so the tiles no row can reach are never walked. window <= 0 (or WIN off) is the +// full-attention form, unchanged. +template __global__ __launch_bounds__(NWARPS * 32) void r4d_attn_prefill_kernel(const R4DArgs a) { @@ -159,6 +164,11 @@ void r4d_attn_prefill_kernel(const R4DArgs a) } const int klimit = ctx - qlen + qpos; + // The window's first key this row may attend to: the causal limit back by the window, floored + // at zero. The decode kernel's r4d_attn_wlo is the same formula, inlined here because the + // prefill header is compiled before the decode one that defines it. + int wlo = (WIN && a.window > 0) ? (ctx - qlen + qpos - a.window + 1) : 0; + if (WIN && a.window > 0 && wlo < 0) wlo = 0; float m_ref = -3.0e38f; float off = PSHIFT + 3.0e38f; @@ -170,6 +180,13 @@ void r4d_attn_prefill_kernel(const R4DArgs a) const int qmax_cta = min(qb * BLOCK_Q + BLOCK_Q - 1, qlen - 1); const int klimit_cta = ctx - qlen + qmax_cta; const int ntiles = (min(klimit_cta + 1, ctx) + TILE - 1) / TILE; + // The window's first tile, taken at THIS CTA's first query row (whose window reaches furthest + // back among the rows it holds); the walk starts there, so no tile below every row's window is + // fetched. Taken at the CHUNK's row 0 instead, the last CTA of an 8192-token chunk walked eight + // thousand keys none of its rows can see -- fully masked tiles, so skipping them changes no + // value. WIN off (or window <= 0) starts at 0. + const int wlo0 = (WIN && a.window > 0) ? (ctx - qlen + qb * BLOCK_Q - a.window + 1) : 0; + const int tstart = (WIN && a.window > 0 && wlo0 > 0) ? (wlo0 / TILE) : 0; // ---- staging, split into a global FETCH (registers) and an LDS STORE ------------------------ // Splitting them is what lets GPREV move the fetch out from between the barriers; without @@ -302,10 +319,10 @@ void r4d_attn_prefill_kernel(const R4DArgs a) } }; int blk[NB]; - if (BTS) load_bt(0, blk); - if (GPREV) fetchV(0, blk); + if (BTS) load_bt(tstart * NB, blk); + if (GPREV) fetchV(tstart * TILE, blk); - for (int ti = 0; ti < ntiles; ++ti) { + for (int ti = tstart; ti < ntiles; ++ti) { const int k0 = ti * TILE; int blkn[NB]; if (BTS && ti + 1 < ntiles) { @@ -352,9 +369,12 @@ void r4d_attn_prefill_kernel(const R4DArgs a) for (int e = 0; e < 8; ++e) sc[e] = FOLDQ ? s[e] : s[e] * mul; const int kbase = k0 + mt * 16 + 8 * h; - if (!MSKIP || wave_any(kbase + 7 > klimit)) { + // The causal bound masks the keys past klimit; the window bound (WIN) also masks the + // keys before wlo. MSKIP skips both when an m-tile straddles neither limit. + if (!MSKIP || wave_any(kbase + 7 > klimit) || (WIN && wave_any(kbase < wlo))) { #pragma unroll - for (int e = 0; e < 8; ++e) sc[e] = (kbase + e <= klimit) ? sc[e] : -INFINITY; + for (int e = 0; e < 8; ++e) sc[e] = ((kbase + e <= klimit) && (!WIN || kbase + e >= wlo)) + ? sc[e] : -INFINITY; } float smax = sc[0]; diff --git a/libr4d/r4d_encoder_bf16.hip b/libr4d/r4d_encoder_bf16.hip index 9d8008e1..e44db1ea 100644 --- a/libr4d/r4d_encoder_bf16.hip +++ b/libr4d/r4d_encoder_bf16.hip @@ -217,6 +217,61 @@ __global__ __launch_bounds__(kQkThreads) void qk_norm_rope_kernel( } } +// The `blocks` mode at any head_dim and section size (Gemma 4's vision tower: 72-wide heads, two +// sections of 18 pairs) -- what the register layout above cannot hold. A wave a head and a lane a +// rotated pair: the norm's sum of squares first, then each lane re-reads its pair, norms, gains, +// rounds (the norm rounded before the rotation, as above) and rotates it. Channels past `rot` +// are normed only; a v head (v_norm) is normed at unit gain. +__global__ __launch_bounds__(kQkThreads) void qk_norm_rope_any_kernel( + uint16_t* __restrict__ qkv, const int* __restrict__ pos, const uint16_t* __restrict__ qw, + const uint16_t* __restrict__ kw, uint32_t head_dim, uint32_t n_head, uint32_t n_head_kv, + uint32_t rot, int v_norm, float theta, float eps, float rscale, float wadd, uint32_t ld, + QkBlocks blk, uint32_t pplane) { + __shared__ float cs_s[kQkMaxHalf], sn_s[kQkMaxHalf]; + __shared__ int pa_s[kQkMaxHalf], pb_s[kQkMaxHalf]; + const uint32_t m = blockIdx.x; + const uint32_t n_rope = n_head + n_head_kv; + const uint32_t n_norm = n_rope + (v_norm ? n_head_kv : 0); + const uint32_t half = rot / 2; + uint16_t* row = qkv + (size_t)m * ld; + const float div = rscale != 0.0f ? rscale : 1.0f; + for (uint32_t i = threadIdx.x; i < half; i += kQkThreads) { + int c = 0, s0 = 0; + while (c + 1 < blk.n && (int)i >= s0 + blk.sec[c]) { s0 += blk.sec[c]; ++c; } + const float p = (float)pos[(size_t)blk.comp[c] * pplane + m] / div; + const float inv = 1.0f / powf(theta, (float)((int)i - s0) / (float)blk.sec[c]); + sincosf(p * inv, &sn_s[i], &cs_s[i]); + pa_s[i] = 2 * s0 + ((int)i - s0); + pb_s[i] = pa_s[i] + blk.sec[c]; + } + __syncthreads(); + const uint32_t lane = threadIdx.x & 31, wave = threadIdx.x >> 5; + for (uint32_t hh = wave; hh < n_norm; hh += kQkThreads / 32) { + uint16_t* h = row + hh * head_dim; + float ss = 0.0f; + for (uint32_t e = lane; e < head_dim; e += 32) { const float v = bf2f(h[e]); ss += v * v; } + ss = r4d_wave_sum(ss); + const float sc = 1.0f / sqrtf(ss / (float)head_dim + eps); + const bool is_v = hh >= n_rope; + const uint16_t* w = hh < n_head ? qw : kw; + auto nrm = [&](uint32_t e) { + const float g = is_v ? 1.0f : bf2f(w[e]) + wadd; + return bf2f(f32_to_bf16(bf2f(h[e]) * sc * g)); + }; + if (is_v) { + for (uint32_t e = lane; e < head_dim; e += 32) h[e] = f32_to_bf16(nrm(e)); + continue; + } + for (uint32_t i = lane; i < half; i += 32) { + const uint32_t a = (uint32_t)pa_s[i], b = (uint32_t)pb_s[i]; + const float x0 = nrm(a), x1 = nrm(b); + h[a] = f32_to_bf16(x0 * cs_s[i] - x1 * sn_s[i]); + h[b] = f32_to_bf16(x0 * sn_s[i] + x1 * cs_s[i]); + } + for (uint32_t e = rot + lane; e < head_dim; e += 32) h[e] = f32_to_bf16(nrm(e)); + } +} + // ---------------------------------------------------------------------------- pool_rows // ref_pool_rows: row r of y is the mean of x's rows [r*k, r*k + k), summed in f32 and rounded to // bf16, then times `mult` and rounded again. A workgroup an output row, a thread a column. @@ -541,21 +596,32 @@ extern "C" int r4d_qk_norm_rope_bf16(long qkv, long pos, long qw, long kw, int M const QkBlocks* blk, int pplane, long stream) { if (!qkv || !pos || !qw || !kw) return -1; if (M <= 0 || head_dim <= 0 || n_head <= 0 || n_head_kv <= 0 || rot <= 0 || rot > head_dim || - (rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || head_dim % 32 || - mode < 0 || mode > 2) + (rot & 1) || rot / 2 > (int)kQkMaxHalf || head_dim > 32 * kQkMaxE || mode < 0 || mode > 2) return -2; + if (mode != 2 && head_dim % 32) return -2; if (mode == 1 && head_dim % 64) return -2; if (mode == 0 && (rot / 2) % 32) return -2; QkBlocks b{}; + bool any = false; /* the blocks mode outside the register layout: qk_norm_rope_any_kernel */ if (mode == 2) { if (!blk || blk->n <= 0 || blk->n > 8) return -2; b = *blk; int total = 0; for (int c = 0; c < b.n; ++c) { - if ((2 * total) % 32 || (b.sec[c] != 16 && b.sec[c] % 32)) return -2; + if (b.sec[c] <= 0) return -2; + if ((2 * total) % 32 || (b.sec[c] != 16 && b.sec[c] % 32)) any = true; total += b.sec[c]; } if (2 * total != rot) return -2; + if (head_dim % 32) any = true; + } + if (any) { + hipLaunchKernelGGL(qk_norm_rope_any_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0, + (hipStream_t)stream, (uint16_t*)qkv, (const int*)pos, + (const uint16_t*)qw, (const uint16_t*)kw, (uint32_t)head_dim, + (uint32_t)n_head, (uint32_t)n_head_kv, (uint32_t)rot, v_norm, theta, + eps, rscale, wadd, (uint32_t)ld, b, (uint32_t)pplane); + return hipGetLastError() == hipSuccess ? 0 : -4; } #define R4D_QN(MD) \ hipLaunchKernelGGL(qk_norm_rope_kernel, dim3((uint32_t)M), dim3(kQkThreads), 0, \ @@ -766,12 +832,14 @@ extern "C" int r4d_rad_qk_norm_rope(const RadArgs* a, RadStream s) { return R4D_NO(RAD_E_SHAPE); /* A head lives in a wave's registers with both halves of a rotary pair in one lane (or, for a * 16-pair block, in the two half-waves): head_dim a multiple of 32 up to 1024. */ - if (hd % 32 || hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + if (hd > 1024 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); const char* mode = r4d_gets(a, "mode"); int md = 0; if (mode && !std::strcmp(mode, "gptj")) md = 1; else if (mode && !std::strcmp(mode, "blocks")) md = 2; else if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED); + /* Any head_dim in the blocks mode (qk_norm_rope_any_kernel); the others need multiples of 32. */ + if (md != 2 && hd % 32) return R4D_NO(RAD_E_SHAPE); QkBlocks blk{}; long long M = 0, pplane = 0; if (md == 2) { diff --git a/libr4d/r4d_gelu_mul_quant_i8.hip b/libr4d/r4d_gelu_mul_quant_i8.hip new file mode 100644 index 00000000..86901ff8 --- /dev/null +++ b/libr4d/r4d_gelu_mul_quant_i8.hip @@ -0,0 +1,96 @@ +// r4d_gelu_mul_quant_i8.hip - r4d_gelu_mul_quant_i8: gelu(gate) * up and the per-row int8 quantiser +// r4d_gemm_w4a8_nt_m64 reads, in one pass over the row. +// +// The down projection's input of a GELU-gated feed-forward (Gemma) on a w4a8 grid: unfused it is +// gelu_mul and quant_act_i8, two single-row dispatches at a decode batch. This is the pair as one, +// BYTE-IDENTICAL to it: the product is formed exactly as gelu_mul_kernel forms it (the tanh form, +// the same constants, rounded to bf16), and the absmax, scale and codes are quant_act_i8's over +// those bf16 values -- the absmax is a max and so takes no partition, and every code is a function +// of its own value and the row scale. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_emit.h" +#include "r4d_common.h" +#include + +namespace { + +__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } + +template +__global__ __launch_bounds__(THR) void gelu_mul_quant_i8_kernel( + const uint16_t* __restrict__ gu, signed char* __restrict__ q, float* __restrict__ S, + uint16_t* __restrict__ yo, uint32_t n, uint32_t gu_ld, uint32_t y_ld) { + extern __shared__ uint16_t ybuf[]; + __shared__ float lm[THR / 32]; + const uint32_t row = blockIdx.x; + const uint16_t* __restrict__ gr = gu + (size_t)row * gu_ld; + signed char* __restrict__ qr = q + (size_t)row * n; + + float m = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const float g = bf2f(gr[i]); + const float k0 = 0.7978845608028654f, k1 = 0.044715f; + const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g))); + const uint16_t y = f32_to_bf16(gelu * bf2f(gr[n + i])); + ybuf[i] = y; + if (yo) yo[(size_t)row * y_ld + i] = y; + m = fmaxf(m, fabsf(bf2f(y))); + } + m = r4d_wave_max(m); + if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m; + __syncthreads(); // also publishes ybuf to every thread + m = lm[0]; +#pragma unroll + for (uint32_t i = 1; i < THR / 32; i++) m = fmaxf(m, lm[i]); + const float scale = fmaxf(m, 1e-8f) / 127.f; + const float inv = 1.f / scale; + if (threadIdx.x == 0) S[row] = scale; + // quant_act_i8's fragment order, see r4d_quant_act_i8.hip + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const uint32_t s = i >> 4, j = i & 15; + const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3); + const int t = __float2int_rn(bf2f(ybuf[src]) * inv); + qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t)); + } +} + +} // namespace + +// Operands (r4d_rows.cpp, oGeluMulQuantI8): gate_up [M][2n] bf16 (gate first), q [M][n] int8 in the +// fragment order, scale [M][1] f32, out_bf16 [M][n] bf16 optional. +enum { GM_GU = 0, GM_Q, GM_S, GM_Y }; + +static int rad_gelu_mul_quant_i8_body(const RadArgs* a, const R4dSink& sk) { + int emit_rc = RAD_OK; + const RadTensor* gu = r4d_opt(a, GM_GU); + const RadTensor* q = r4d_opt(a, GM_Q); + const RadTensor* s = r4d_opt(a, GM_S); + const RadTensor* y = r4d_opt(a, GM_Y); + if (!gu || !q || !s) return R4D_NO(RAD_E_INVAL); + if (gu->dtype != RAD_BF16 || q->dtype != RAD_I8 || s->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + long long M = 0, n = 0; + if (r4d_rows_of(q, &M, &n) != RAD_OK) return R4D_NO(RAD_E_SHAPE); + if (n % 16 || !r4d_contig(q)) return R4D_NO(RAD_E_SHAPE); + long long Mg = 0; + const long long gp = r4d_rows_pitch(gu, 2 * n, &Mg); + if (gp < 0) return R4D_NO(RAD_E_STRIDE); + if (Mg < M) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(s) != M || !r4d_contig(s)) return R4D_NO(RAD_E_SHAPE); + if (y && r4d_numel(y) != M * n) return R4D_NO(RAD_E_SHAPE); + const long long yp = y ? r4d_row_pitch(y) : n; + if (yp < 0) return R4D_NO(RAD_E_STRIDE); + const size_t lds = (size_t)n * sizeof(uint16_t); + if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE); + const int thr = r4d_act_threads((int)M, (int)n); +#define R4D_GMQ_T(T) emit_rc = R4D_EMIT(sk, (gelu_mul_quant_i8_kernel), dim3((uint32_t)M), dim3(T), lds, \ + (const uint16_t*)r4d_p(gu), (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), \ + (uint32_t)n, (uint32_t)gp, (uint32_t)yp) + if (thr == 1024) R4D_GMQ_T(1024); + else if (thr == 512) R4D_GMQ_T(512); + else if (thr == 256) R4D_GMQ_T(256); + else return R4D_NO(RAD_E_INVAL); +#undef R4D_GMQ_T + return emit_rc; +} +R4D_ENTRY(r4d_rad_gelu_mul_quant_i8, rad_gelu_mul_quant_i8_body) diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 5d9d848d..e56c8bef 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -49,6 +49,7 @@ #include "r4d_fp8_wmma.h" #include +#include namespace { @@ -273,6 +274,29 @@ __global__ __launch_bounds__(THR) void rmsnorm_kernel( } } +// ---------------------------------------------------------------------------- rmsnorm_p +// ref_rmsnorm_p: y = x * rsqrt(mean(x^2) + eps) -- the SAME normalisation as rmsnorm with NO gain. +// It is the weightless value normalisation Gemma's attention uses on V (llama.cpp's +// ggml_rms_norm(V, eps), no tensor); there is no checkpoint plane to feed a gain through, so an +// rmsnorm call would need a phantom all-zero weight. Two passes over the row, the sum of squares +// in f32; the second pass drops the gain multiply rmsnorm has. The mean accumulates in f32 in +// ascending index order, exactly as rmsnorm does, so the two agree bit-for-bit where rmsnorm's +// gain happens to be one. +__global__ __launch_bounds__(kThreads) void rmsnorm_p_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, + uint32_t n, float eps, uint32_t x_ld, uint32_t y_ld) { + __shared__ float lds[kThreads / kWave]; + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) { const float v = bf2f(xr[i]); ss += v * v; } + ss = block_sum(ss, lds); + const float s = rsqrtf(ss / (float)n + eps); + for (uint32_t i = threadIdx.x; i < n; i += kThreads) + yr[i] = f32_to_bf16(bf2f(xr[i]) * s); +} + // ---------------------------------------------------------------------------- add / mul // ref_add / ref_mul, including THE ONE BROADCAST RULE: an operand carrying exactly n elements // against an output of rows*n broadcasts along rows, and nothing else broadcasts at all. That is @@ -310,6 +334,53 @@ __global__ __launch_bounds__(kThreads) void sigmoid_kernel( yr[i] = f32_to_bf16(1.0f / (1.0f + expf(-bf2f(xr[i])))); } +// ---------------------------------------------------------------------------- logit_softcap +// ref_logit_softcap: y = cap * tanh(x / cap), the final-logit softcap. THE ROW-WISE-WITH-A-PITCH +// SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the logits_gemm's output, +// and the pitch form costs nothing on a contiguous buffer -- it is x_ld == n. +__global__ __launch_bounds__(kThreads) void logit_softcap_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ y, + uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) { + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) + yr[i] = f32_to_bf16(cap * tanhf(bf2f(xr[i]) / cap)); +} + +/* The f32 leg: the 1.3.0 sampling chain carries the logits in f32 from the gemm, so the softcap + * is issued against f32 rows. The same row-with-pitch shape as the bf16 leg, and the math is the + * op's definition verbatim -- no rounding pass, the buffer already holds the arithmetic dtype. */ +__global__ __launch_bounds__(kThreads) void logit_softcap_kernel_f32( + const float* __restrict__ x, float* __restrict__ y, + uint32_t n, float cap, uint32_t x_ld, uint32_t y_ld) { + const uint32_t m = blockIdx.x; + const float* __restrict__ xr = x + (size_t)m * x_ld; + float* __restrict__ yr = y + (size_t)m * y_ld; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) + yr[i] = cap * tanhf(xr[i] / cap); +} + +// ---------------------------------------------------------------------------- scale +// ref_scale: y = x * s, s a [1] weight broadcast over every element. THE ROW-WISE-WITH-A-PITCH +// SHAPE IS COPIED FROM sigmoid on purpose: Gemma's arch issues it against the residual stream at +// the end of every layer (the per-layer scalar), and the pitch form costs nothing on a contiguous +// buffer -- it is x_ld == n. The scalar is read once per block (a single load, cached), not per +// element: a per-element reload of a [1] tensor is the same value every time and costs a load per +// element. `s` is f32 or bf16 (the layer_scalar weight is bf16 in the checkpoint); the branch is +// on its dtype, so the op is dtype-generic in the scalar and the bf16 kernel is the residual +// stream's, which is what a served Gemma 4 issues it against. +__global__ __launch_bounds__(kThreads) void scale_kernel( + const uint16_t* __restrict__ x, const void* __restrict__ s, uint32_t s_dt, + uint16_t* __restrict__ y, uint32_t n, uint32_t x_ld, uint32_t y_ld) { + const uint32_t m = blockIdx.x; + const float sv = (s_dt == RAD_F32) ? ((const float*)s)[0] : bf2f(((const uint16_t*)s)[0]); + const uint16_t* __restrict__ xr = x + (size_t)m * x_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) + yr[i] = f32_to_bf16(bf2f(xr[i]) * sv); +} + // ---------------------------------------------------------------------------- silu_mul // ref_silu_mul: y[.., i] = silu(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, which is // the order rad-convert fuses gate_proj and up_proj into one weight in; the two conventions cannot @@ -343,6 +414,26 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel( } } +// ---------------------------------------------------------------------------- gelu_mul +// ref_gelu_mul: y[.., i] = gelu_tanh(gu[.., i]) * gu[.., n + i]. THE GATE IS THE FIRST HALF, the +// same order-lock as silu_mul. The tanh-approx GELU (gemma's gelu_pytorch_tanh), NOT the erf one: +// gated feed-forwards are trained with the tanh form, and the constants are the standard fit the +// gemm_nt_bias "gelu_tanh" epilogue uses (the identical function, so a GELU-gated FFN and a +// tanh-gelu epilogue agree to the last bit). +__global__ __launch_bounds__(kThreads) void gelu_mul_kernel( + const uint16_t* __restrict__ gu, uint16_t* __restrict__ y, + uint32_t n, uint32_t gu_ld, uint32_t y_ld) { + const uint32_t m = blockIdx.x; + const uint16_t* __restrict__ gr = gu + (size_t)m * gu_ld; + uint16_t* __restrict__ yr = y + (size_t)m * y_ld; + for (uint32_t i = threadIdx.x; i < n; i += kThreads) { + const float g = bf2f(gr[i]); + const float k0 = 0.7978845608028654f, k1 = 0.044715f; + const float gelu = 0.5f * g * (1.0f + tanhf(k0 * (g + k1 * g * g * g))); + yr[i] = f32_to_bf16(gelu * bf2f(gr[n + i])); + } +} + // ---------------------------------------------------------------------------- rope // ref_rope, in place over a fused [n_head + 2*n_head_kv] head row -- the V heads at the end are // left alone, which is the whole reason the op takes the fused projection rather than two tensors. @@ -354,8 +445,10 @@ __global__ __launch_bounds__(kThreads) void silu_mul_kernel( // (rad_block_attn_gated.h says so and says what would have to change first), so the shim maps it. // // PARTIAL ROTARY. `rot` may be less than head_dim -- 64 of 256 on this target -- and the tail of -// the head is untouched. The frequency exponent divides by `rot`, not by head_dim: the rotated -// prefix is a complete rotary of its own width. +// the head is untouched. The base ladder's exponent divides by `den`, which `ladder` resolves: +// `rot` for `rotary` (the rotated prefix, a complete rotary of its own width) and `head_dim` for +// `head` (the proportional variant, a prefix of the full-width table). `den` = `rot` on the +// default path, so existing models are bit-for-bit unchanged. // // One thread a PAIR. The pair's two loads and two stores are the whole body, so there is no // reduction and no LDS; the grid is (M, heads). @@ -379,7 +472,7 @@ __device__ __forceinline__ int rope_comp(int mode, uint32_t i, const int* sec, i __global__ __launch_bounds__(kThreads) void rope_kernel( uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos, - uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, int gptj, + uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, uint32_t nfreq, int den, int gptj, float theta, float rscale, uint32_t row_pitch, int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn) { const uint32_t m = blockIdx.x; @@ -392,7 +485,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel( t += kThreads * gridDim.y) { const uint32_t h = t / half, i = t % half; uint16_t* __restrict__ hd = qkv + (size_t)m * row_pitch + (size_t)h * head_dim; - float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot); + float inv = 1.0f / powf(theta, (float)(2 * i) / (float)den); float p = p0; if (plane) { uint32_t j = i; @@ -402,6 +495,10 @@ __global__ __launch_bounds__(kThreads) void rope_kernel( inv = 1.0f / powf(theta, (float)(2 * j) / (float)(2 * sec[c])); } inv = yarn.frequency(inv, (int)i); + /* THE PROPORTIONAL LADDER rotates the whole head with every frequency past nfreq zero + * (HF's _compute_proportional_rope_parameters), so pair i is (i, i + head_dim/2) and the + * pairs past nfreq turn by 0: cos 1, sin 0, the value back exactly. */ + if (i >= nfreq) inv = 0.0f; const float ang = p * inv; float c, s; sincosf(ang, &s, &c); @@ -638,6 +735,13 @@ static int embed_lookup_q_emit(const int32_t* tok, const void* wte, bool q, cons return rc == RAD_OK ? 0 : -4; } +extern "C" int r4d_embed_lookup_bf16_scaled(long tok, long wte, long x, int M, int n_embd, + int n_vocab, int vocab_off, int x_ld, float scale, + long stream) { + R4dSink sk; sk.stream = (RadStream)(uintptr_t)stream; + return embed_lookup_bf16_emit(tok, wte, x, M, n_embd, n_vocab, vocab_off, x_ld, scale, sk); +} + static int gather_rows_bf16_emit(long x, long idx, long y, int M, int n, int src_rows, int x_ld, int y_ld, const R4dSink& sk) { if (!x || !idx || !y) return -1; @@ -734,6 +838,22 @@ extern "C" int r4d_rmsnorm_bf16(long x, long w, long y, int M, int n, float eps, return r4d_rmsnorm_mult_bf16(x, w, y, M, n, eps, wadd, 1.0f, w_f32, x_ld, y_ld, stream); } +// The weightless norm: rmsnorm without the gain multiply. It is not templated on a thread count +// the way rmsnorm is, because rmsnorm's width is pinned to the fused rmsnorm_quant_fp8 by their +// shared byte-identical requirement, and rmsnorm_p has no fused quantiser counterpart to match -- +// kThreads is the same choice the other non-templated row kernels (binary, sigmoid, silu_mul) make. +extern "C" int r4d_rmsnorm_p_bf16(long x, long y, int M, int n, float eps, + int x_ld, int y_ld, long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + hipLaunchKernelGGL(rmsnorm_p_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, + (const uint16_t*)x, (uint16_t*)y, (uint32_t)n, eps, + (uint32_t)x_ld, (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + // `op` is 0 for a sum and 1 for a product. `b_ld` of 0 with the same n is the broadcast form: the // caller passes a b_ld of zero and every row reads the same n elements. // b_ld -1 is a ONE-ELEMENT b, the scalar broadcast; 0 is one row broadcast down the rows. @@ -788,6 +908,48 @@ extern "C" int r4d_fill_bf16(long y, int M, int n, int y_ld, float value, long s return hipGetLastError() == hipSuccess ? 0 : -4; } +extern "C" int r4d_logit_softcap_bf16(long x, long y, int M, int n, float cap, + int x_ld, int y_ld, long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!(cap > 0.0f)) return -3; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + hipLaunchKernelGGL(logit_softcap_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + (hipStream_t)stream, + (const uint16_t*)x, (uint16_t*)y, (uint32_t)n, cap, + (uint32_t)x_ld, (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r4d_logit_softcap_f32(long x, long y, int M, int n, float cap, + int x_ld, int y_ld, long stream) { + if (!x || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!(cap > 0.0f)) return -3; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + hipLaunchKernelGGL(logit_softcap_kernel_f32, dim3((uint32_t)M), dim3(kThreads), 0, + (hipStream_t)stream, + (const float*)x, (float*)y, (uint32_t)n, cap, + (uint32_t)x_ld, (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + +extern "C" int r4d_scale_bf16(long x, long s, uint32_t s_dt, long y, int M, int n, + int x_ld, int y_ld, long stream) { + if (!x || !s || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (s_dt != RAD_F32 && s_dt != RAD_BF16) return -3; + if (!x_ld) x_ld = n; + if (!y_ld) y_ld = n; + hipLaunchKernelGGL(scale_kernel, dim3((uint32_t)M), dim3(kThreads), 0, + (hipStream_t)stream, + (const uint16_t*)x, (const void*)s, s_dt, (uint16_t*)y, (uint32_t)n, + (uint32_t)x_ld, (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) { if (!gu || !y) return -1; if (M <= 0 || n <= 0) return -2; @@ -800,21 +962,38 @@ extern "C" int r4d_silu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y return hipGetLastError() == hipSuccess ? 0 : -4; } +// GELU-gated product, the gemma FFN activation. Same shape and order-lock as silu_mul (the gate +// is the first half of the fused [M, 2n] row); the only difference is the nonlinearity, which is +// the tanh approximation, not the erf one, to match ref_gelu_mul's act_gelu_tanh. +extern "C" int r4d_gelu_mul_bf16(long gu, long y, int M, int n, int gu_ld, int y_ld, long stream) { + if (!gu || !y) return -1; + if (M <= 0 || n <= 0) return -2; + if (!gu_ld) gu_ld = 2 * n; + if (!y_ld) y_ld = n; + hipLaunchKernelGGL(gelu_mul_kernel, dim3((uint32_t)M), dim3(kThreads), 0, (hipStream_t)stream, + (const uint16_t*)gu, (uint16_t*)y, (uint32_t)n, + (uint32_t)gu_ld, (uint32_t)y_ld); + return hipGetLastError() == hipSuccess ? 0 : -4; +} + // `n_rope_heads` is n_head + n_head_kv: the Q heads and the K heads of a fused projection, or just // the one buffer's heads when q and k are separate tensors (which is what the gated block does). extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int gptj, float theta, float rscale, int row_pitch, long stream) { - return r4d_rope_mc_bf16(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale, + return r4d_rope_mc_bf16(qkv, pos, M, head_dim, n_rope_heads, rot, rot, gptj, theta, rscale, row_pitch, 0, nullptr, 0, 0, stream); } // THE ONE LAUNCH OF rope_kernel. `yarn` with factor 0 is the plain rotary: the kernel's YaRN // blend returns the frequency it was given and the magnitude is not applied, so the C entry points -// below and the op without YaRN run the same arithmetic with the same arguments. -static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, +// below and the op without YaRN run the same arithmetic with the same arguments. `den` is the +// ladder's width (`rot` for `rotary`, `head_dim` for `head`) -- the multi-component form passes +// the caller's, and the plain entry passes `rot`, as it always has. +static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot, int den, int gptj, float theta, float rscale, int row_pitch, int mode, - const int* sec, int n_sec, int plane, RadYarn yarn, long stream) { + const int* sec, int n_sec, int plane, RadYarn yarn, long stream, + int nfreq = -1) { if (!qkv || !pos) return -1; if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2; if (rot <= 0 || rot > head_dim || (rot & 1)) return -3; @@ -823,9 +1002,11 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads const uint32_t pairs = (uint32_t)n_rope_heads * (uint32_t)(rot / 2); const uint32_t gy = (pairs + kThreads - 1) / kThreads; const int s0 = n_sec > 0 ? sec[0] : 0, s1 = n_sec > 1 ? sec[1] : 0, s2 = n_sec > 2 ? sec[2] : 0; + if (nfreq < 0) nfreq = rot / 2; hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream, (uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim, - (uint32_t)n_rope_heads, (uint32_t)rot, gptj, theta, rscale, + (uint32_t)n_rope_heads, (uint32_t)rot, (uint32_t)nfreq, (int)den, gptj, theta, + rscale, (uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn); return hipGetLastError() == hipSuccess ? 0 : -4; } @@ -833,10 +1014,11 @@ static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads // The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and // `plane` the component pitch of `pos`; plane 0 is the one-component rotary above. extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads, - int rot, int gptj, float theta, float rscale, int row_pitch, - int mode, const int* sec, int n_sec, int plane, long stream) { - return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale, row_pitch, - mode, sec, n_sec, plane, RadYarn{}, stream); + int rot, int den, int gptj, float theta, float rscale, + int row_pitch, int mode, const int* sec, int n_sec, int plane, + long stream) { + return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, den, gptj, theta, rscale, + row_pitch, mode, sec, n_sec, plane, RadYarn{}, stream); } extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim, @@ -1281,6 +1463,29 @@ extern "C" int r4d_rad_rmsnorm(const RadArgs* a, RadStream s) { : RAD_E_DEVICE; } +/* ------------------------------------------------------------------ rmsnorm_p */ + +extern "C" int r4d_rad_rmsnorm_p(const RadArgs* a, RadStream s) { + const RadTensor* x = r4d_opt(a, 0); + const RadTensor* y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(x)); + R4D_NEED(dt_bf16(y)); + + const long long n = r4d_geti_or(a, "n", r4d_dim(x, (int)x->rank - 1)); + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + long long M = 0, My = 0; + const long long x_ld = r4d_rows_pitch(x, n, &M); + const long long y_ld = r4d_rows_pitch(y, n, &My); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); + + const float eps = (float)r4d_getf(a, "eps", 1e-6); + const int rc = r4d_rmsnorm_p_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, eps, + (int)x_ld, (int)y_ld, (long)(uintptr_t)s); + return rc == 0 ? RAD_OK : RAD_E_DEVICE; +} + /* ------------------------------------------------------------------ add / mul */ enum { BI_A = 0, BI_B, BI_Y }; @@ -1393,6 +1598,76 @@ extern "C" int r4d_rad_fill(const RadArgs* a, RadStream s) { (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; } +/* ------------------------------------------------------------------ logit_softcap */ + +extern "C" int r4d_rad_logit_softcap(const RadArgs* a, RadStream s) { + const RadTensor* x = r4d_opt(a, 0); + const RadTensor* y = r4d_opt(a, 1); + if (!x || !y) return R4D_NO(RAD_E_INVAL); + /* Two legs, one op: bf16 (the logits buffer as the gemm writes it on the bf16 chain) and f32 + * (the 1.3.0 sampling chain, where the gemm hands the sampler f32 rows). The dtype check + * moved from the entry to the call below because the legs differ, not the geometry. */ + const bool leg_bf16 = (x->dtype == RAD_BF16) && (y->dtype == RAD_BF16); + const bool leg_f32 = (x->dtype == RAD_F32) && (y->dtype == RAD_F32); + if (!leg_bf16 && !leg_f32) return R4D_NO(RAD_E_DTYPE); + + /* `cap` is where the model lives: Gemma 4 issues it at 30.0. The default exists for the same + * reason every other one here does (a direct call with no declare in front), and the `> 0` + * test is load-bearing: a zero cap is a division by zero in every lane, not a bad answer. */ + const float cap = (float)r4d_getf(a, "cap", 30.0); + if (!(cap > 0.0f)) return R4D_NO(RAD_E_INVAL); + + /* ROW-WISE WITH A PITCH, same as sigmoid: issued against a column slice there is no contiguous + * extent to walk, and the contiguous case costs nothing. */ + const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + long long M = 0, My = 0; + const long long x_ld = r4d_rows_pitch(x, n, &M); + const long long y_ld = r4d_rows_pitch(y, n, &My); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); + + const int rc = leg_bf16 + ? r4d_logit_softcap_bf16(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap, + (int)x_ld, (int)y_ld, (long)(uintptr_t)s) + : r4d_logit_softcap_f32(r4d_addr(x), r4d_addr(y), (int)M, (int)n, cap, + (int)x_ld, (int)y_ld, (long)(uintptr_t)s); + return rc == 0 ? RAD_OK : RAD_E_DEVICE; +} + +/* ------------------------------------------------------------------ scale */ + +extern "C" int r4d_rad_scale(const RadArgs* a, RadStream s) { + const RadTensor* x = r4d_opt(a, 0); + const RadTensor* sc = r4d_opt(a, 1); + const RadTensor* y = r4d_opt(a, 2); + if (!x || !sc || !y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(x)); + R4D_NEED(dt_bf16(y)); + + /* `s` is a [1] weight, f32 or bf16 (the layer_scalar weight is bf16 in the checkpoint). A + * scalar with no element is a shape error, not a broadcast of zero -- a zero scalar would be + * a plausible number, which is the thing the oracle rules out. Read on the device (the kernel + * reads s[0] once per block) rather than a host copy: a device-to-host copy of one element is + * a synchronisation on the step path, and the per-block read is cached. */ + if (sc->dtype != RAD_F32 && sc->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (r4d_numel(sc) < 1) return R4D_NO(RAD_E_SHAPE); + + /* ROW-WISE WITH A PITCH, same as sigmoid: issued against the residual stream at the end of a + * layer there is no contiguous extent to walk, and the contiguous case costs nothing. */ + const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + long long M = 0, My = 0; + const long long x_ld = r4d_rows_pitch(x, n, &M); + const long long y_ld = r4d_rows_pitch(y, n, &My); + if (x_ld < 0 || y_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || My < M) return R4D_NO(RAD_E_SHAPE); + + return r4d_scale_bf16(r4d_addr(x), r4d_addr(sc), sc->dtype, r4d_addr(y), (int)M, (int)n, + (int)x_ld, (int)y_ld, + (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; +} + /* ------------------------------------------------------------------ silu_mul */ extern "C" int r4d_rad_silu_mul(const RadArgs* a, RadStream s) { @@ -1414,6 +1689,28 @@ extern "C" int r4d_rad_silu_mul(const RadArgs* a, RadStream s) { (long)(uintptr_t)s) == 0 ? RAD_OK : RAD_E_DEVICE; } +/* ------------------------------------------------------------------ gelu_mul */ + +extern "C" int r4d_rad_gelu_mul(const RadArgs* a, RadStream s) { + const RadTensor* gu = r4d_opt(a, 0); + const RadTensor* y = r4d_opt(a, 1); + if (!gu || !y) return R4D_NO(RAD_E_INVAL); + R4D_NEED(dt_bf16(gu)); + R4D_NEED(dt_bf16(y)); + + const long long n = r4d_geti_or(a, "n", r4d_dim(y, (int)y->rank - 1)); + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + long long M = 0, Mg = 0; + const long long y_ld = r4d_rows_pitch(y, n, &M); + const long long gu_ld = r4d_rows_pitch(gu, 2 * n, &Mg); + if (y_ld < 0 || gu_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (M <= 0 || Mg < M) return R4D_NO(RAD_E_SHAPE); + + const int rc = r4d_gelu_mul_bf16(r4d_addr(gu), r4d_addr(y), (int)M, (int)n, (int)gu_ld, (int)y_ld, + (long)(uintptr_t)s); + return rc == 0 ? RAD_OK : RAD_E_DEVICE; +} + /* ------------------------------------------------------------------ rope */ enum { RP_QKV = 0, RP_POS }; @@ -1433,6 +1730,21 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) { if (head_dim <= 0 || n_head <= 0) return R4D_NO(RAD_E_SHAPE); if (rot <= 0 || rot > head_dim || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + /* `ladder`: `rotary` (default) measures the base ladder in `rot`; `head` in `head_dim`, the + * proportional variant. head_dim is already validated above, so `den = head_dim` is safe. */ + const char* lad = r4d_gets(a, "ladder"); + long long den = rot; + if (lad) { + if (!std::strcmp(lad, "head")) den = head_dim; + else if (std::strcmp(lad, "rotary") && std::strcmp(lad, "head")) + return R4D_NO(RAD_E_UNSUPPORTED); + } + /* `head` is HF's proportional RoPE: the rotation spans the WHOLE head (rotate_half over + * head_dim, so pair i is (i, i + head_dim/2)) and only the first rotary_dim/2 frequencies are + * non-zero. Rotating the first rotary_dim dims as a rotary of their own pairs (i, i + rot/2) + * instead -- Gemma 4's global layers, 128 of 512 -- turns the wrong channels, and long-range + * attention degrades with distance. */ + /* THE MODE, and with it how many components a position has. With [M] positions -- one * component a token -- mrope and imrope ARE neox: every frequency reads the same position and * the ladder is the same. With [C, M] positions and `sections`, each frequency reads the @@ -1482,10 +1794,14 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) { if (yarn.factor != 0.0f && (mc == 4 || rscale != 1.0f)) return R4D_NO(RAD_E_UNSUPPORTED); /* The Q heads and the K heads rotate; the V heads that follow them do not, which is the whole * reason this op takes the fused projection rather than two tensors. */ + long long rot_l = rot, nfreq = rot / 2; + if (den == head_dim && rot < head_dim && !multi && !gptj && mc == 0) rot_l = head_dim; return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim, - (int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch, - mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s) == 0 ? RAD_OK - : RAD_E_DEVICE; + (int)(n_head + n_head_kv), (int)rot_l, (int)den, gptj, theta, rscale, + (int)pitch, mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s, + (int)nfreq) == 0 + ? RAD_OK + : RAD_E_DEVICE; } /* ------------------------------------------------------------------ kv_store */ diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 7e660ccc..fb502104 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -89,6 +89,14 @@ int r4d_rad_attn_decode_h128_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_decode_h128_bf16 (const RadArgs*, RadStream); int64_t r4d_rad_attn_decode_h256_scratch(const RadArgs*); int64_t r4d_rad_attn_decode_h128_scratch(const RadArgs*); + /* Gemma 4 dense sliding window (r4d_attn_paged_h256_gqa2.hip): head_dim 256, 2 queries per KV head, + * windowed. Both bands: the decode band (q_len*gqa <= 64, verify width 32 against the gqa6 leg's + * 10) and the windowed prefill band (the same r4d_attn_prefill_kernel the gqa6 leg uses, WIN on). */ + int r4d_rad_attn_prefill_h256_gqa2_fp8 (const RadArgs*, RadStream); + int r4d_rad_attn_prefill_h256_gqa2_bf16 (const RadArgs*, RadStream); + int r4d_rad_attn_decode_h256_gqa2_fp8 (const RadArgs*, RadStream); + int r4d_rad_attn_decode_h256_gqa2_bf16 (const RadArgs*, RadStream); + int64_t r4d_rad_attn_decode_h256_gqa2_scratch(const RadArgs*); int r4d_rad_attn_vit (const RadArgs*, RadStream); int r4d_rad_attn_dense (const RadArgs*, RadStream); /* Eight queries per KV head (r4d_attn_paged_gqa8.hip): the routed 35B-A3B at head_dim 256 @@ -114,6 +122,15 @@ int64_t r4d_rad_attn_decode_h256_gqa4_scratch(const RadArgs*); /* ...and its head_dim 64 prefill leg, LFM2's geometry, which serves every query length. */ int r4d_rad_attn_prefill_h64_gqa4_fp8 (const RadArgs*, RadStream); int r4d_rad_attn_prefill_h64_gqa4_bf16(const RadArgs*, RadStream); +/* Eight queries per KV head at head_dim 512, full attention -- the Gemma 4 dense GLOBAL layers. + * Its own instantiation, not the gqa8 body above: that one's prefill tile is 48, which 512-channel + * tiles do not fit in LDS, so head_dim 512 is a stand-alone dispatch + * (r4d_attn_paged_h512_gqa8.hip). The verify width is the gqa bound, 64/8 = 8. */ +int r4d_rad_attn_prefill_h512_gqa8_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_prefill_h512_gqa8_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_decode_h512_gqa8_fp8 (const RadArgs*, RadStream); +int r4d_rad_attn_decode_h512_gqa8_bf16 (const RadArgs*, RadStream); +int64_t r4d_rad_attn_decode_h512_gqa8_scratch(const RadArgs*); /* Twelve queries a KV head, head_dim 256 only -- Qwen3.8-Flash-Next's QSA layers. Same body, * different instantiation; r4d_attn_paged_h256_gqa12.hip is four lines. */ int r4d_rad_attn_prefill_h256_gqa12_fp8 (const RadArgs*, RadStream); @@ -287,6 +304,13 @@ int64_t r4d_rad_moe_gather_scratch (const RadArgs*); /* -- quantisation, norms and the fusions (r4d_*quant*.hip, r4d_qk_norm_rope_gate.hip) -- */ int r4d_rad_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_quant_act_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); +int r4d_rad_qkv_norm_rope (const RadArgs*, RadStream); +int r4d_rad_qkv_norm_rope_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); +int r4d_rad_gelu_mul_quant_i8 (const RadArgs*, RadStream); +int r4d_rad_gelu_mul_quant_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); +int r4d_rad_ar_rmsnorm_quant_i8 (const RadArgs*, RadStream); +int r4d_rad_rmsnorm_quant_i8 (const RadArgs*, RadStream); +int r4d_rad_rmsnorm_quant_i8_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_had_quant_act_i8 (const RadArgs*, RadStream); int r4d_rad_rmsnorm_had_quant_i8 (const RadArgs*, RadStream); int r4d_rad_gated_had_quant_i8 (const RadArgs*, RadStream); @@ -421,6 +445,7 @@ int r4d_rad_scatter_rows_bf16(const RadArgs*, RadStream); int r4d_rad_scatter_rows_bf16_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_gather_rows_describe(const RadArgs*, RadStream, RadLaunchDesc*, int, int*); int r4d_rad_rmsnorm (const RadArgs*, RadStream); +int r4d_rad_rmsnorm_p (const RadArgs*, RadStream); int r4d_rad_add (const RadArgs*, RadStream); int r4d_rad_mul (const RadArgs*, RadStream); int r4d_rad_mul_weight (const RadArgs*, RadStream); @@ -438,7 +463,10 @@ int r4d_rad_rel_sinusoid (const RadArgs*, RadStream); int r4d_rad_attn_local_rel (const RadArgs*, RadStream); int r4d_rad_sigmoid (const RadArgs*, RadStream); int r4d_rad_fill (const RadArgs*, RadStream); +int r4d_rad_logit_softcap (const RadArgs*, RadStream); +int r4d_rad_scale (const RadArgs*, RadStream); int r4d_rad_silu_mul (const RadArgs*, RadStream); +int r4d_rad_gelu_mul (const RadArgs*, RadStream); int r4d_rad_rope (const RadArgs*, RadStream); /* -- the vision tower's ops (r4d_vit_bf16.hip) -- */ int r4d_rad_layernorm (const RadArgs*, RadStream); @@ -546,6 +574,7 @@ int r4d_shape_moe_gemm_q (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_moe_gemm_q_mod4(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_moe_gather (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_scale_rows (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_scale (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_row_topk_merge (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_quant_act_i8 (const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_qk_norm_rope_gate.hip b/libr4d/r4d_qk_norm_rope_gate.hip index 2366b5e1..8e370c47 100644 --- a/libr4d/r4d_qk_norm_rope_gate.hip +++ b/libr4d/r4d_qk_norm_rope_gate.hip @@ -211,11 +211,12 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel( // addresses are never read. // // THE ARITHMETIC IS r4d_model_bf16.hip's rope_kernel, LINE FOR LINE, and that is what makes the -// fusion bit-for-bit rather than merely close: `1.0f / powf(theta, 2i/rot)`, the position divided -// by `rscale` in f32, `sincosf`, and the products consumed in f32 by the caller. Changing any of -// those here silently changes the model's output -- a different rope is a different model. +// fusion bit-for-bit rather than merely close: `1.0f / powf(theta, 2i/den)`, where `den` is the +// ladder's width (`rot` for `rotary`, `head_dim` for `head`), the position divided by `rscale` +// in f32, `sincosf`, and the products consumed in f32 by the caller. Changing any of those here +// silently changes the model's output -- a different rope is a different model. __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel( - const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, float theta, + const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, int den, float theta, float rscale, int cs_f32, int pos_i64, RadYarn yarn) { const int m = blockIdx.x; const long pp = pos_i64 ? ((const long*)POS)[m] : (long)((const int*)POS)[m]; @@ -227,7 +228,7 @@ __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel( const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f); const size_t o = (size_t)pp * rot; for (int i = threadIdx.x; i < half; i += (int)blockDim.x) { - const float inv = yarn.frequency(1.0f / powf(theta, (float)(2 * i) / (float)rot), i); + const float inv = yarn.frequency(1.0f / powf(theta, (float)(2 * i) / (float)den), i); float c, s; sincosf(p * inv, &s, &c); if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; } @@ -396,12 +397,25 @@ static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) { if (M < 1 || rot < 2 || (rot & 1)) return R4D_NO(RAD_E_SHAPE); if (r4d_numel(cs) % rot) return R4D_NO(RAD_E_SHAPE); + /* `ladder`: `rotary` (default) measures the base ladder in `rot`; `head` in `head_dim`, the + * proportional variant. `rope_table` has no head_dim by default, so `head` needs the parameter. */ + const long long head_dim = r4d_geti_or(args, "head_dim", 0); + const char* lad = r4d_gets(args, "ladder"); + long long den = rot; + if (lad) { + if (!std::strcmp(lad, "head")) { + if (head_dim <= 0) return R4D_NO(RAD_E_SHAPE); + den = head_dim; + } else if (std::strcmp(lad, "rotary") && std::strcmp(lad, "head")) + return R4D_NO(RAD_E_UNSUPPORTED); + } + const float theta = (float)r4d_getf(args, "theta", 10000.0); const float rscale = (float)r4d_getf(args, "scale", 1.0); const RadYarn yarn = rad_yarn_args(args); if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return R4D_NO(RAD_E_INVAL); return R4D_EMIT(sk, r4d_qk_rope_table_kernel, dim3((int)M), dim3(64), 0, - r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, theta, rscale, - cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn); + r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, (int)den, theta, + rscale, cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn); } R4D_ENTRY(r4d_rad_rope_table, rad_rope_table_body) diff --git a/libr4d/r4d_qkv_norm_rope.hip b/libr4d/r4d_qkv_norm_rope.hip new file mode 100644 index 00000000..eb1072fa --- /dev/null +++ b/libr4d/r4d_qkv_norm_rope.hip @@ -0,0 +1,190 @@ +// r4d_qkv_norm_rope.hip - r4d_qkv_norm_rope: the per-head norms and the rotary of separate q, k and +// v projections in one dispatch -- Gemma 4's attention prologue. +// +// WHY. Between its projections and the cache store a Gemma 4 attention block runs five single-pass +// kernels over a few dozen heads: the weightless value norm (rmsnorm_p), the q and the k norms +// (rmsnorm, one row a head) and the two rotaries (rope). At a decode batch each is a handful of +// workgroups, so the block pays five dispatches for work the card does in a fraction of one. This is +// the five as one, one workgroup a (token, head). +// +// BYTE-IDENTICAL TO THE FIVE, for the reason r4d_rmsnorm_quant_i8.hip gives. What makes that hold: +// +// * each norm's sum of squares is taken by THE PARTITION ITS STANDALONE KERNEL USES. rmsnorm runs +// one workgroup a row at r4d_act_threads(rows, head_dim) threads and rmsnorm_p at 256; thread t +// folds columns t, t+THR, ... in order, the waves are summed in order through LDS. Here a +// workgroup is head_dim threads, and thread t < min(THR, head_dim) folds the same columns in the +// same order while the rest hold zero -- which is what the standalone kernel's surplus waves hold +// too, and adding +0.0 to a sum of squares changes no bit; +// * the norm output is rounded to bf16 as the standalone norm stores it, and the rotary reads that; +// * the rotary's per-pair arithmetic is rope_kernel's, written the same way (powf ladder, +// sincosf, `x0*c - x1*s`, `x0*s + x1*c`), under the library's -ffp-contract=off. +// +// `v_from_k` IS GEMMA'S GLOBAL CLASS: k == v, so v is the value norm of the RAW k, taken before the +// k norm rewrites it -- the order the unfused block issues them in. +// +// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_emit.h" +#include "r4d_common.h" +#include +#include +#include + +namespace { + +constexpr uint32_t kWave = 32; + +__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } + +// THR threads' partition of one head's sum of squares, reproduced inside a head_dim-wide workgroup: +// thread t < P = min(THR, HD) folds t, t+P, ...; the waves are then summed in order. +template +__device__ __forceinline__ float head_ss(const uint16_t* __restrict__ x, uint32_t P, float* lds) { + float ss = 0.0f; + if (threadIdx.x < P) + for (uint32_t i = threadIdx.x; i < HD; i += P) { const float v = bf2f(x[i]); ss += v * v; } + ss = r4d_wave_sum(ss); + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + if (lane == 0) lds[wave] = ss; + __syncthreads(); + float s = 0.0f; +#pragma unroll + for (uint32_t w = 0; w < HD / kWave; ++w) s += lds[w]; + return s; +} + +// The rotary over a normed head staged in `nb`, written to `out`: rope_kernel's body for pair i. +template +__device__ __forceinline__ void rotate(const uint16_t* __restrict__ nb, uint16_t* __restrict__ out, + float p0, uint32_t rot, uint32_t nfreq, int den, float theta) { + const uint32_t half = rot / 2, t = threadIdx.x; + if (t < half) { + float inv = 1.0f / powf(theta, (float)(2 * t) / (float)den); + if (t >= nfreq) inv = 0.0f; + const float ang = p0 * inv; + float c, s; + sincosf(ang, &s, &c); + const float x0 = bf2f(nb[t]), x1 = bf2f(nb[t + half]); + out[t] = f32_to_bf16(x0 * c - x1 * s); + out[t + half] = f32_to_bf16(x0 * s + x1 * c); + } + for (uint32_t i = rot + t; i < HD; i += HD) out[i] = nb[i]; // the unrotated tail +} + +// blockIdx.y: [0, nq) a query head, [nq, nq+nkv) a key head (and with VK its value, from the raw +// key), [nq+nkv, nq+2nkv) a value head normalised in place (without VK). +template +__global__ __launch_bounds__(HD) void qkv_norm_rope_kernel( + uint16_t* __restrict__ q, uint16_t* __restrict__ k, uint16_t* __restrict__ v, + const int32_t* __restrict__ pos, const void* __restrict__ qw, const void* __restrict__ kw, + uint32_t nq, uint32_t nkv, uint32_t pq, uint32_t pk, uint32_t pv, + uint32_t q_ld, uint32_t k_ld, uint32_t v_ld, float eps, float wadd, float mult, + uint32_t rot, uint32_t nfreq, int den, float theta, float rscale, uint32_t n_pos) { + __shared__ float l1[HD / kWave], l2[HD / kWave]; + __shared__ uint16_t nb[HD]; + const uint32_t m = blockIdx.x, hh = blockIdx.y, t = threadIdx.x; + const float div = rscale != 0.0f ? rscale : 1.0f; + // rope rotates the rows its positions cover; a row past them is normed and left unrotated + const float p0 = m < n_pos ? (float)pos[m] / div : 0.0f; + + if (hh >= nq + nkv) { // a value head, in place: rmsnorm_p + uint16_t* __restrict__ x = v + (size_t)m * v_ld + (size_t)(hh - nq - nkv) * HD; + const float s = rsqrtf(head_ss(x, pv, l1) / (float)HD + eps); + __syncthreads(); // every thread has read x before any writes it + for (uint32_t i = t; i < HD; i += HD) x[i] = f32_to_bf16(bf2f(x[i]) * s); + return; + } + const bool isq = hh < nq; + const uint32_t h = isq ? hh : hh - nq; + uint16_t* __restrict__ x = isq ? q + (size_t)m * q_ld + (size_t)h * HD + : k + (size_t)m * k_ld + (size_t)h * HD; + const void* __restrict__ w = isq ? qw : kw; + + if (VK && !isq) { // v = rmsnorm_p(raw k), before the k norm rewrites k + uint16_t* __restrict__ vo = v + (size_t)m * v_ld + (size_t)h * HD; + const float sv = rsqrtf(head_ss(x, pv, l2) / (float)HD + eps); + for (uint32_t i = t; i < HD; i += HD) vo[i] = f32_to_bf16(bf2f(x[i]) * sv); + } + const float s = rsqrtf(head_ss(x, isq ? pq : pk, l1) / (float)HD + eps); + for (uint32_t i = t; i < HD; i += HD) { + const float g = WF32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]); + nb[i] = f32_to_bf16(bf2f(x[i]) * s * (g + wadd) * mult); + } + __syncthreads(); // the normed head is complete before any pair reads across it + if (m < n_pos) rotate(nb, x, p0, rot, nfreq, den, theta); + else for (uint32_t i = t; i < HD; i += HD) x[i] = nb[i]; +} + +} // namespace + +// ============================================================== the plugin ABI entry point +enum { QN_Q = 0, QN_K, QN_V, QN_POS, QN_QW, QN_KW }; + +static int rad_qkv_norm_rope_body(const RadArgs* a, const R4dSink& sk) { + int emit_rc = RAD_OK; + const RadTensor* q = r4d_opt(a, QN_Q); + const RadTensor* k = r4d_opt(a, QN_K); + const RadTensor* v = r4d_opt(a, QN_V); + const RadTensor* ps = r4d_opt(a, QN_POS); + const RadTensor* qw = r4d_opt(a, QN_QW); + const RadTensor* kw = r4d_opt(a, QN_KW); + if (!q || !k || !v || !ps || !qw || !kw) return R4D_NO(RAD_E_INVAL); + if (q->dtype != RAD_BF16 || k->dtype != RAD_BF16 || v->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (ps->dtype != RAD_I32 || ps->rank != 1 || !r4d_contig(ps)) return R4D_NO(RAD_E_SHAPE); + if (qw->dtype != kw->dtype || (qw->dtype != RAD_BF16 && qw->dtype != RAD_F32)) return R4D_NO(RAD_E_DTYPE); + const long long hd = r4d_geti_or(a, "head_dim", 0); + const long long nq = r4d_geti_or(a, "n_head", 0); + const long long nkv = r4d_geti_or(a, "n_head_kv", 0); + const long long rot = r4d_geti_or(a, "rotary_dim", hd); + const long long vk = r4d_geti_or(a, "v_from_k", 0); + if (hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE); + if (nq <= 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(qw) != hd || r4d_numel(kw) != hd) return R4D_NO(RAD_E_SHAPE); + const char* mode = r4d_gets(a, "mode"); + if (mode && std::strcmp(mode, "neox")) return R4D_NO(RAD_E_UNSUPPORTED); + if (r4d_getf(a, "yarn_factor", 0.0) != 0.0) return R4D_NO(RAD_E_UNSUPPORTED); + // rope's ladder, resolved exactly as r4d_rad_rope resolves it + const char* lad = r4d_gets(a, "ladder"); + long long den = rot; + if (lad) { + if (!std::strcmp(lad, "head")) den = hd; + else if (std::strcmp(lad, "rotary")) return R4D_NO(RAD_E_UNSUPPORTED); + } + const long long nfreq = rot / 2; + const long long rot_l = (den == hd && rot < hd) ? hd : rot; + + long long M = 0, Mk = 0, Mv = 0; + const long long q_ld = r4d_rows_pitch(q, nq * hd, &M); + const long long k_ld = r4d_rows_pitch(k, nkv * hd, &Mk); + const long long v_ld = r4d_rows_pitch(v, nkv * hd, &Mv); + if (q_ld < 0 || k_ld < 0 || v_ld < 0) return R4D_NO(RAD_E_STRIDE); + const long long Mp = r4d_numel(ps); + if (Mp <= 0 || M < Mp || Mk != M || Mv != M) return R4D_NO(RAD_E_SHAPE); + + // the standalone kernels' widths, from the same function: rmsnorm one row a head at + // r4d_act_threads(rows, head_dim), rmsnorm_p at 256 + const uint32_t pq = (uint32_t)std::min(r4d_act_threads((int)(M * nq), (int)hd), hd); + const uint32_t pk = (uint32_t)std::min(r4d_act_threads((int)(M * nkv), (int)hd), hd); + const uint32_t pv = (uint32_t)std::min(256, hd); + const float eps = (float)r4d_getf(a, "eps", 1e-6); + const float wadd = (float)r4d_getf(a, "wadd", 0.0); + const float theta = (float)r4d_getf(a, "theta", 10000.0); + const float rsc = (float)r4d_getf(a, "scale", 1.0); + const float mult = 1.0f; + const dim3 grid((uint32_t)M, (uint32_t)(nq + nkv + (vk ? 0 : nkv))); + +#define R4D_QNR_T(HD, WF, VK) emit_rc = R4D_EMIT(sk, (qkv_norm_rope_kernel), grid, dim3(HD), 0, \ + (uint16_t*)r4d_wp(q), (uint16_t*)r4d_wp(k), (uint16_t*)r4d_wp(v), (const int32_t*)r4d_p(ps), \ + r4d_p(qw), r4d_p(kw), (uint32_t)nq, (uint32_t)nkv, pq, pk, pv, (uint32_t)q_ld, (uint32_t)k_ld, \ + (uint32_t)v_ld, eps, wadd, mult, (uint32_t)rot_l, (uint32_t)nfreq, (int)den, theta, rsc, (uint32_t)Mp) +#define R4D_QNR(HD) \ + do { if (qw->dtype == RAD_F32) { if (vk) R4D_QNR_T(HD, true, true); else R4D_QNR_T(HD, true, false); } \ + else { if (vk) R4D_QNR_T(HD, false, true); else R4D_QNR_T(HD, false, false); } } while (0) + if (hd == 256) R4D_QNR(256); + else R4D_QNR(512); +#undef R4D_QNR +#undef R4D_QNR_T + return emit_rc; +} +R4D_ENTRY(r4d_rad_qkv_norm_rope, rad_qkv_norm_rope_body) diff --git a/libr4d/r4d_rmsnorm_quant_i8.hip b/libr4d/r4d_rmsnorm_quant_i8.hip new file mode 100644 index 00000000..6ceb0ba7 --- /dev/null +++ b/libr4d/r4d_rmsnorm_quant_i8.hip @@ -0,0 +1,355 @@ +// r4d_rmsnorm_quant_i8.hip - r4d_rmsnorm_quant_i8: the RMS norm and the per-row int8 quantiser +// r4d_gemm_w4a8_nt_m64 reads, in one pass over the row -- optionally with the residual junction +// in front of it: a post-norm on the branch output, the residual add and a scalar on the sum. +// +// WHY. A w4a8 linear needs its activation as int8 codes in the GEMM's fragment order with one f32 +// scale per row (r4d_quant_act_i8), and the producer of that activation is a norm. Unfused, a +// model whose linears take that grid issues the norm and the quantiser as two dispatches, and a +// sandwich-norm model (Gemma 2/3/4) issues four or five at every residual junction: +// +// rmsnorm(branch; w_post) -> add(residual) -> [scale] -> rmsnorm(residual; w) -> quant_act_i8 +// +// each one a single workgroup over one row at a decode batch, so the step pays the dispatch, not +// the bytes. This is that chain as one dispatch. +// +// BYTE-IDENTICAL TO THE CHAIN IT REPLACES, not merely close, because the engine's greedy output is +// compared byte for byte across builds. What makes that hold: +// +// * every intermediate the chain stores in bf16 is rounded to bf16 here too, and the next stage +// reads the rounded value: the post-norm output, the residual sum, the scaled residual and the +// norm output the quantiser takes its absmax and codes over; +// * both sums of squares are taken by the same partition the standalone norm uses -- the width +// r4d_act_threads(M, n) picks, thread t folding columns t, t+THR, ... in ascending order, then +// r4d_wave_sum and the waves in order through LDS (r4d_model_bf16.hip's rmsnorm_kernel and +// block_sum, which this copies rather than shares only because that one lives in another unit); +// * the arithmetic of every element is written the way the standalone kernels write it -- +// `x * s * (g + wadd)`, `a + b`, `x * scalar`, `fmaxf(m, 1e-8f) / 127.f` -- and the library is +// built with -ffp-contract=off, so no stage picks up an fma the chain does not have. +// +// THE RESIDUAL IS READ AND WRITTEN, and nothing else reads it before this kernel is done: each +// thread rewrites only the columns it read, so the second pass reads its own writes back. +// +// Returns a negative code rather than throwing, for the reason given in r4d_gemm_fp8a8.hip. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_emit.h" +#include "r4d_common.h" +#include "r4d_ar_seq.h" +#include + +namespace { + +constexpr uint32_t kWave = 32; + +__device__ __forceinline__ float bf2f(uint16_t h) { return __uint_as_float((uint32_t)h << 16); } + +// The standalone norm's reduction, verbatim (r4d_model_bf16.hip): the wave butterfly, then the +// waves summed IN ORDER by every thread out of LDS. `lds` must not be reused by a second +// reduction without a barrier between them -- the kernel below gives each its own array. +template +__device__ __forceinline__ float block_sum(float v, float* lds) { + v = r4d_wave_sum(v); + const uint32_t lane = threadIdx.x & (kWave - 1), wave = threadIdx.x / kWave; + if (lane == 0) lds[wave] = v; + __syncthreads(); + float s = 0.0f; +#pragma unroll + for (uint32_t w = 0; w < NW; ++w) s += lds[w]; + return s; +} + +__device__ __forceinline__ float gain(const void* w, uint32_t i, bool f32) { + return f32 ? ((const float*)w)[i] : bf2f(((const uint16_t*)w)[i]); +} + +// RES: a residual is present; the norm is taken of `res + d` (stored back into `res`), where d is +// the branch `x` itself or, with POST, rmsnorm(x; w_post). Without RES the norm is of `x`. +// SCL: the sum is multiplied by the [1] scalar before it is stored and normalised. +// `ybuf` holds the row's norm output for the fragment-order store, which reads across threads. +// +// THE ROW BODY, from the junction on: `s1` is the post-norm's factor, already reduced over `xr` by +// the caller (the plain kernel below takes it off the row; the all-reduce form takes it off the +// reduced sum it has just stored). l2 and lm are this function's own reduction planes. +template +__device__ __forceinline__ void junction_row( + const uint16_t* __restrict__ xr, uint16_t* __restrict__ rr, const void* __restrict__ w, + const void* __restrict__ wp, float sv, signed char* __restrict__ qr, float* __restrict__ Sr, + uint16_t* __restrict__ yr, uint32_t n, float eps, float wadd, float s1, + uint16_t* ybuf, float* l2, float* lm) { + // ---- the junction (post-norm, add, scalar), stored, and the norm's sum of squares over it + float ss2 = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + uint16_t v = xr[i]; + if (RES) { + if (POST) v = f32_to_bf16(bf2f(v) * s1 * (gain(wp, i, WF32) + wadd)); + v = f32_to_bf16(bf2f(rr[i]) + bf2f(v)); + if (SCL) v = f32_to_bf16(bf2f(v) * sv); + rr[i] = v; + } + const float f = bf2f(v); + ss2 += f * f; + } + ss2 = block_sum(ss2, l2); + const float s2 = rsqrtf(ss2 / (float)n + eps); + + // ---- the norm output, rounded to bf16 as the standalone norm stores it, and its absmax + const uint16_t* __restrict__ nr = RES ? rr : xr; + float m = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const uint16_t y = f32_to_bf16(bf2f(nr[i]) * s2 * (gain(w, i, WF32) + wadd)); + ybuf[i] = y; + if (yr) yr[i] = y; + m = fmaxf(m, fabsf(bf2f(y))); + } + m = r4d_wave_max(m); + if ((threadIdx.x & 31) == 0) lm[threadIdx.x >> 5] = m; + __syncthreads(); // also publishes ybuf to every thread + m = lm[0]; +#pragma unroll + for (uint32_t i = 1; i < THR / kWave; i++) m = fmaxf(m, lm[i]); + const float scale = fmaxf(m, 1e-8f) / 127.f; + const float inv = 1.f / scale; + if (threadIdx.x == 0) *Sr = scale; + + // ---- the codes, in r4d_quant_act_i8's fragment order: byte j of a k step comes from + // lane-half j>>3 and element j&7, i.e. source 8*((j&7)>>2) + 4*(j>>3) + (j&3) inside the step. + for (uint32_t i = threadIdx.x; i < n; i += THR) { + const uint32_t s = i >> 4, j = i & 15; + const uint32_t src = (s << 4) + 8 * ((j & 7) >> 2) + 4 * (j >> 3) + (j & 3); + const int t = __float2int_rn(bf2f(ybuf[src]) * inv); + qr[i] = (signed char)(t < -128 ? -128 : (t > 127 ? 127 : t)); + } +} + +__device__ __forceinline__ float scalar_of(const void* sc, uint32_t f32) { + return f32 ? ((const float*)sc)[0] : bf2f(((const uint16_t*)sc)[0]); +} + +template +__global__ __launch_bounds__(THR) void rmsnorm_quant_i8_kernel( + const uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, + signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, + uint32_t n, float eps, float wadd, uint32_t x_ld, uint32_t r_ld, uint32_t y_ld) { + extern __shared__ uint16_t ybuf[]; + __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; + const uint32_t row = blockIdx.x; + const uint16_t* __restrict__ xr = x + (size_t)row * x_ld; + + // ---- the post-norm's sum of squares, over the branch output + float s1 = 0.0f; + if (POST) { + float ss = 0.0f; + for (uint32_t i = threadIdx.x; i < n; i += THR) { const float v = bf2f(xr[i]); ss += v * v; } + ss = block_sum(ss, l1); + s1 = rsqrtf(ss / (float)n + eps); + } + junction_row( + xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, SCL ? scalar_of(sc, sc_f32) : 1.0f, + q + (size_t)row * n, S + row, yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1, + ybuf, l2, lm); +} + +// --------------------------------------------------------------------------------------------- +// THE SAME JUNCTION WITH THE TWO-RANK ALL-REDUCE THAT ALWAYS PRECEDES IT: the branch output is a +// rank's partial sum of a column-sharded linear (o_proj, down_proj), and the post-norm is of the +// WHOLE sum. ar_rmsnorm_quant_fp8's handshake, exact wire only: each block pushes the rows it owns +// into the peer's scratch slot as 16B words, publishes its flag, waits for the peer's, and reduces +// `f2bf(mine + peer)` back into `x` -- the bytes the standalone exact all-reduce stores, fp32 add +// commuting exactly so both ranks agree -- on the post-norm's own sum-of-squares pass. A block owns +// whole rows, one a block at a decode batch. +#define R4D_ARQ8_SPIN_MAX 4000000000ULL + +__device__ __forceinline__ void arq8_store_rel(unsigned int* p, unsigned int v) { + __hip_atomic_store(p, v, __ATOMIC_RELEASE, __HIP_MEMORY_SCOPE_SYSTEM); +} +__device__ __forceinline__ unsigned int arq8_load_acq(const unsigned int* p) { + return __hip_atomic_load(p, __ATOMIC_ACQUIRE, __HIP_MEMORY_SCOPE_SYSTEM); +} + +template +__global__ __launch_bounds__(THR) void ar_rmsnorm_quant_i8_kernel( + uint16_t* __restrict__ x, uint16_t* __restrict__ res, const void* __restrict__ w, + const void* __restrict__ wp, const void* __restrict__ sc, uint32_t sc_f32, + signed char* __restrict__ q, float* __restrict__ S, uint16_t* __restrict__ yo, + int4* peer_base, const int4* my_base, unsigned int* peer_flags, unsigned int* my_flags, + unsigned int* seq_ctrs, int M, uint32_t n, float eps, float wadd, uint32_t r_ld, uint32_t y_ld, + int slot_stride16, int drain, int acq, unsigned int nbw) { + extern __shared__ uint16_t ybuf[]; + __shared__ float l1[THR / kWave], l2[THR / kWave], lm[THR / kWave]; + __shared__ unsigned int s_seq, s_slot; + const int b = (int)blockIdx.x, nb = (int)gridDim.x; + const uint32_t tid = threadIdx.x; + const int r0 = (int)(((long)b * M) / nb), r1 = (int)(((long)(b + 1) * M) / nb); + + r4d_ar_seq_take(seq_ctrs, nbw, s_seq, s_slot); /* device-resident, replay-safe */ + const unsigned int sq = s_seq; + int4* const ps = peer_base + (size_t)s_slot * slot_stride16; + const int4* const ms = my_base + (size_t)s_slot * slot_stride16; + + /* push my rows into the peer's slot; `x` is a tight [M][n] of bf16 */ + const int wpr = (int)(n >> 3); + const int4* const in4 = (const int4*)x; + for (int k = r0 * wpr + (int)tid; k < r1 * wpr; k += (int)THR) ps[k] = in4[k]; + if (drain == 1) __threadfence_system(); + else if (drain == 3) asm volatile("s_wait_storecnt 0x0" ::: "memory"); + __syncthreads(); + if (tid == 0) { + if (drain == 2) __threadfence_system(); + arq8_store_rel(&peer_flags[b], sq); + unsigned long long z = 0; + while (r4d_ar_seq_behind(arq8_load_acq(&my_flags[b]), sq)) { + if (++z > R4D_ARQ8_SPIN_MAX) __builtin_trap(); + } + } + __syncthreads(); + if (acq) __threadfence_system(); + + const uint16_t* __restrict__ P = (const uint16_t*)ms; /* the peer's rows, in my scratch */ + const float sv = SCL ? scalar_of(sc, sc_f32) : 1.0f; + for (int row = r0; row < r1; ++row) { + uint16_t* __restrict__ xr = x + (size_t)row * n; + const uint16_t* __restrict__ pr = P + (size_t)row * n; + float ss = 0.0f; + for (uint32_t i = tid; i < n; i += THR) { + const uint16_t a = f32_to_bf16(bf2f(xr[i]) + bf2f(pr[i])); + xr[i] = a; + if (POST) { const float v = bf2f(a); ss += v * v; } + } + float s1 = 0.0f; + if (POST) s1 = rsqrtf(block_sum(ss, l1) / (float)n + eps); + junction_row( + xr, RES ? res + (size_t)row * r_ld : nullptr, w, wp, sv, q + (size_t)row * n, S + row, + yo ? yo + (size_t)row * y_ld : nullptr, n, eps, wadd, s1, ybuf, l2, lm); + __syncthreads(); /* the planes and ybuf are re-used by the next row this block owns */ + } +} + +} // namespace + +// ============================================================== the plugin ABI entry point +// +// Operands, in the schema's order (r4d_rows.cpp, oRmsNormQuantI8): +// 0 x [M][n] bf16 the norm's input, or the branch output with a residual +// 1 residual [M][n] bf16, optional READ AND WRITTEN +// 2 w [n] bf16 or f32 the norm's gain +// 3 q [M][n] int8 fragment order, unpitched +// 4 scale [M][1] f32 one per row +// 5 out_bf16 [M][n] bf16, optional the norm output the unfused norm would have stored +// 6 w_post [n] optional a post-norm on x before the add; needs the residual +// 7 scalar [1] optional multiplies the sum; needs the residual +enum { RQ_X = 0, RQ_RES, RQ_W, RQ_Q, RQ_S, RQ_Y, RQ_WP, RQ_SC }; + +static int rad_rmsnorm_quant_i8_body(const RadArgs* a, const R4dSink& sk) { + int emit_rc = RAD_OK; + const RadTensor* x = r4d_opt(a, RQ_X); + const RadTensor* rs = r4d_opt(a, RQ_RES); + const RadTensor* w = r4d_opt(a, RQ_W); + const RadTensor* q = r4d_opt(a, RQ_Q); + const RadTensor* s = r4d_opt(a, RQ_S); + const RadTensor* y = r4d_opt(a, RQ_Y); + const RadTensor* wp = r4d_opt(a, RQ_WP); + const RadTensor* sc = r4d_opt(a, RQ_SC); + if (!x || !w || !q || !s) return R4D_NO(RAD_E_INVAL); + if ((wp || sc) && !rs) return R4D_NO(RAD_E_INVAL); // a junction without a stream to add into + if (x->dtype != RAD_BF16 || q->dtype != RAD_I8 || s->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + long long M = 0, n = 0; + if (r4d_rows_of(x, &M, &n) != RAD_OK) return R4D_NO(RAD_E_SHAPE); + if (n % 16) return R4D_NO(RAD_E_SHAPE); // a k step is sixteen bytes of one row + if (r4d_numel(w) != n) return R4D_NO(RAD_E_SHAPE); + if (w->dtype != RAD_F32 && w->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (wp && (r4d_numel(wp) != n || wp->dtype != w->dtype)) return R4D_NO(RAD_E_SHAPE); + if (sc && (r4d_numel(sc) != 1 || (sc->dtype != RAD_F32 && sc->dtype != RAD_BF16))) + return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(q) != M * n || !r4d_contig(q)) return R4D_NO(RAD_E_SHAPE); + if (r4d_numel(s) != M || !r4d_contig(s)) return R4D_NO(RAD_E_SHAPE); + if (y && r4d_numel(y) != M * n) return R4D_NO(RAD_E_SHAPE); + if (rs && r4d_numel(rs) != M * n) return R4D_NO(RAD_E_SHAPE); + const long long xp = r4d_row_pitch(x), rp = rs ? r4d_row_pitch(rs) : n, yp = y ? r4d_row_pitch(y) : n; + if (xp < 0 || rp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); + // The row's norm output is staged in LDS for the cross-thread fragment-order store. + const size_t lds = (size_t)n * sizeof(uint16_t); + if (lds > 60 * 1024) return R4D_NO(RAD_E_SHAPE); + + // THE SAME WIDTH AS rmsnorm_bf16 AND quant_act_i8 PICK, from the same function: it decides + // which columns a thread folds into each sum of squares, which is the byte-identity. + const int thr = r4d_act_threads((int)M, (int)n); + const float eps = (float)r4d_getf(a, "eps", 1e-6); + const float wadd = (float)r4d_getf(a, "wadd", 0.0); + const uint32_t scf = sc ? (sc->dtype == RAD_F32) : 0u; + +#define R4D_RQI8_T(WF, RS, PO, SC, T) emit_rc = R4D_EMIT(sk, \ + (rmsnorm_quant_i8_kernel), dim3((uint32_t)M), dim3(T), lds, \ + (const uint16_t*)r4d_p(x), (uint16_t*)r4d_wp(rs), r4d_p(w), r4d_p(wp), r4d_p(sc), scf, \ + (signed char*)r4d_wp(q), (float*)r4d_wp(s), (uint16_t*)r4d_wp(y), (uint32_t)n, eps, wadd, \ + (uint32_t)xp, (uint32_t)rp, (uint32_t)yp) +#define R4D_RQI8(WF, RS, PO, SC) \ + do { if (thr == 1024) R4D_RQI8_T(WF, RS, PO, SC, 1024); \ + else if (thr == 512) R4D_RQI8_T(WF, RS, PO, SC, 512); \ + else if (thr == 256) R4D_RQI8_T(WF, RS, PO, SC, 256); \ + else return R4D_NO(RAD_E_INVAL); } while (0) +#define R4D_RQI8_W(WF) \ + do { if (!rs) R4D_RQI8(WF, false, false, false); \ + else if (!wp && !sc) R4D_RQI8(WF, true, false, false); \ + else if (wp && !sc) R4D_RQI8(WF, true, true, false); \ + else if (wp && sc) R4D_RQI8(WF, true, true, true); \ + else R4D_RQI8(WF, true, false, true); } while (0) + if (w->dtype == RAD_F32) R4D_RQI8_W(true); + else R4D_RQI8_W(false); +#undef R4D_RQI8_W +#undef R4D_RQI8 +#undef R4D_RQI8_T + return emit_rc; +} +R4D_ENTRY(r4d_rad_rmsnorm_quant_i8, rad_rmsnorm_quant_i8_body) + +// The fused all-reduce form's launch. The IPC arguments are r4d_ar_oneshot_2rank_exact's -- the +// double-buffered scratch, the per-block flags and the device-resident sequence counters -- and the +// rest is the junction's. `x` is the message and takes no pitch; `nblocks` is clamped to M (a block +// owns whole rows). Returns 0, or a negative code for a shape it does not serve. +extern "C" int r4d_ar_rmsnorm_quant_i8(long peer_scratch, long my_scratch, long peer_flags, + long my_flags, long seq_ctrs, long slot_stride16, + long x, long res, long w, long wp, long sc, int sc_f32, + long y, long q, long s, int M, int n, float eps, float wadd, + int w_f32, int r_ld, int y_ld, long stream, int nblocks, + int drain, int acq) { + if (!x || !w || !q || !s) return -1; + if (!peer_scratch || !my_scratch || !peer_flags || !my_flags || !seq_ctrs) return -1; + if (M <= 0 || n <= 0) return -2; + if (n % 16) return -3; + if ((wp || sc) && !res) return -5; + if ((size_t)n * sizeof(uint16_t) > 60 * 1024) return -6; + if (!r_ld) r_ld = n; + if (!y_ld) y_ld = n; + int nb = nblocks < 1 ? 1 : nblocks; + if (nb > M) nb = M; + const int nbw = r4d_ar_max_blocks(); + if (nb > nbw) nb = nbw; + const int thr = r4d_act_threads(M, n); + const size_t lds = (size_t)n * sizeof(uint16_t); +#define R4D_ARQ8_T(WF, RS, PO, SC, T) \ + hipLaunchKernelGGL((ar_rmsnorm_quant_i8_kernel), dim3((uint32_t)nb), \ + dim3(T), lds, (hipStream_t)stream, (uint16_t*)x, (uint16_t*)res, \ + (const void*)w, (const void*)wp, (const void*)sc, (uint32_t)sc_f32, \ + (signed char*)q, (float*)s, (uint16_t*)y, (int4*)peer_scratch, \ + (const int4*)my_scratch, (unsigned int*)peer_flags, \ + (unsigned int*)my_flags, (unsigned int*)seq_ctrs, M, (uint32_t)n, eps, \ + wadd, (uint32_t)r_ld, (uint32_t)y_ld, (int)slot_stride16, drain, acq, \ + (unsigned)nbw) +#define R4D_ARQ8(WF, RS, PO, SC) \ + do { if (thr == 1024) R4D_ARQ8_T(WF, RS, PO, SC, 1024); \ + else if (thr == 512) R4D_ARQ8_T(WF, RS, PO, SC, 512); \ + else R4D_ARQ8_T(WF, RS, PO, SC, 256); } while (0) +#define R4D_ARQ8_W(WF) \ + do { if (!res) R4D_ARQ8(WF, false, false, false); \ + else if (!wp && !sc) R4D_ARQ8(WF, true, false, false); \ + else if (wp && !sc) R4D_ARQ8(WF, true, true, false); \ + else if (wp && sc) R4D_ARQ8(WF, true, true, true); \ + else R4D_ARQ8(WF, true, false, true); } while (0) + if (w_f32) R4D_ARQ8_W(true); + else R4D_ARQ8_W(false); +#undef R4D_ARQ8_W +#undef R4D_ARQ8 +#undef R4D_ARQ8_T + return hipGetLastError() == hipSuccess ? 0 : -4; +} diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index cc1791c1..af046483 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -277,11 +277,13 @@ static const RadParamSpec pRopeTable[] = { { "rot", RAD_P_INT, RAD_REQUIRED }, P_F64("theta"), P_F64("scale"), - { "dtype", RAD_P_STR, RAD_REQUIRED }, - { "yarn_factor", RAD_P_F64, RAD_OPTIONAL }, - { "yarn_low", RAD_P_F64, RAD_OPTIONAL }, - { "yarn_high", RAD_P_F64, RAD_OPTIONAL }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, + { "yarn_factor", RAD_P_F64, RAD_OPTIONAL }, + { "yarn_low", RAD_P_F64, RAD_OPTIONAL }, + { "yarn_high", RAD_P_F64, RAD_OPTIONAL }, { "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL }, + { "head_dim", RAD_P_INT, RAD_OPTIONAL }, /* needed only by the `head` ladder */ + { "ladder", RAD_P_STR, RAD_OPTIONAL }, /* the base ladder's width: rotary|head */ }; static const RadOperandSpec oRopeTable[] = { { "positions", RAD_OPD_IN, 0 }, @@ -1312,6 +1314,97 @@ static const RadOperandSpec oArRmsNormQuantFp8[] = { { "out_bf16", RAD_OPD_OUT, 1 }, }; +/* `rmsnorm_quant_i8` is the norm with r4d_gemm_w4a8_nt_m64's own activation producer on its pass: + * int8 codes in the GEMM's fragment order and ONE f32 scale per row -- quant_act_i8's grid, not + * quant_act_i8g's per-group one and not the rotated rmsnorm_had_quant_i8's. Its first six operands + * are rmsnorm_quant_fp8's, so the residual is the fused_add_rms_norm form; two optional weights + * after them make it a sandwich-norm model's whole residual junction: `w_post` normalises the + * branch output BEFORE the add and `scalar` multiplies the sum after it (Gemma's per-layer + * scalar). Every stage rounds to bf16 where the chain it replaces stores bf16, so the op is + * byte-identical to that chain. */ +static const RadParamSpec pRmsNormQuantI8[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + P_F64("eps"), + { "dtype", RAD_P_STR, RAD_REQUIRED }, + P_F64O("wadd"), +}; +static const RadOperandSpec oRmsNormQuantI8[] = { + { "x", RAD_OPD_IN, 0 }, + { "residual", RAD_OPD_INOUT, 1 }, /* present = the norm is of residual + (post-normed) x */ + { "w", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 }, + { "w_post", RAD_OPD_WEIGHT, 1 }, /* rmsnorm(x; w_post) before the add; needs the residual */ + { "scalar", RAD_OPD_WEIGHT, 1 }, /* [1], multiplies the sum; needs the residual */ +}; + +/* `qkv_norm_rope` is `qk_norm_rope` over SEPARATE q, k and v projections rather than one fused row: + * the per-head q and k norms, the weightless value norm and the rotary of q and k, in one + * dispatch -- Gemma 4's attention prologue, whose projections are three GEMMs. `v_from_k` 1 is its + * global class (k == v): v is the value norm of the RAW k, written before the k norm rewrites it. + * The rotary parameters are `rope`'s (`ladder` included), the norm parameters `rmsnorm`'s, and the + * op is byte-identical to rmsnorm_p + rmsnorm + rmsnorm + rope + rope. */ +static const RadParamSpec pQkvNormRope[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "head_dim", RAD_P_INT, RAD_REQUIRED }, + { "n_head", RAD_P_INT, RAD_REQUIRED }, + { "n_head_kv", RAD_P_INT, RAD_REQUIRED }, + P_F64("theta"), + P_F64("eps"), + P_F64O("scale"), + { "mode", RAD_P_STR, RAD_OPTIONAL }, + { "rotary_dim", RAD_P_INT, RAD_OPTIONAL }, + { "ladder", RAD_P_STR, RAD_OPTIONAL }, + P_F64O("wadd"), + { "v_from_k", RAD_P_INT, RAD_OPTIONAL }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadOperandSpec oQkvNormRope[] = { + { "q", RAD_OPD_INOUT, 0 }, + { "k", RAD_OPD_INOUT, 0 }, + { "v", RAD_OPD_INOUT, 0 }, /* written from the raw k under v_from_k */ + { "positions", RAD_OPD_IN, 0 }, + { "q_w", RAD_OPD_WEIGHT, 0 }, + { "k_w", RAD_OPD_WEIGHT, 0 }, +}; + +/* `gelu_mul_quant_i8` is `gelu_mul` with quant_act_i8's quantiser on its pass: the down projection + * input of a GELU-gated feed-forward on the w4a8 grid, byte-identical to the pair. */ +static const RadParamSpec pGeluMulQuantI8[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, +}; +static const RadOperandSpec oGeluMulQuantI8[] = { + { "gate_up", RAD_OPD_IN, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 }, +}; + +/* `ar_rmsnorm_quant_i8` is rmsnorm_quant_i8 with the two-rank exact all-reduce of `x` in front: + * same operands, `x` INOUT because the reduced sum lands back in it, plus `world_size`. */ +static const RadParamSpec pArRmsNormQuantI8[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + P_F64("eps"), + { "world_size", RAD_P_INT, RAD_REQUIRED }, + { "dtype", RAD_P_STR, RAD_REQUIRED }, + P_F64O("wadd"), +}; +static const RadOperandSpec oArRmsNormQuantI8[] = { + { "x", RAD_OPD_INOUT, 0 }, + { "residual", RAD_OPD_INOUT, 1 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "q", RAD_OPD_OUT, 0 }, + { "scale", RAD_OPD_OUT, 0 }, + { "out_bf16", RAD_OPD_OUT, 1 }, + { "w_post", RAD_OPD_WEIGHT, 1 }, + { "scalar", RAD_OPD_WEIGHT, 1 }, +}; + static const RadParamSpec pGatedQuantFp8[] = { { "M", RAD_P_INT, RAD_REQUIRED }, { "n", RAD_P_INT, RAD_REQUIRED }, @@ -1536,6 +1629,16 @@ static const RadParamSpec pMnDtype[] = { { "n", RAD_P_INT, RAD_REQUIRED }, { "dtype", RAD_P_STR, RAD_REQUIRED }, }; +/* `logit_softcap`'s, matched field for field to ref's `pMnCap` so the two plugins agree (spec + * §2.3). `cap` is required and must be > 0; a non-positive cap is a division by zero in every + * lane, so the op refuses it rather than answering with NaNs. */ +static const RadParamSpec pMnCap[] = { + { "M", RAD_P_INT, RAD_REQUIRED }, + { "n", RAD_P_INT, RAD_REQUIRED }, + P_F64("cap"), + { "dtype", RAD_P_STR, RAD_REQUIRED }, +}; + static const RadOperandSpec oBinary[] = { { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_IN, 0 }, @@ -1640,6 +1743,11 @@ static const RadParamSpec pFill[] = { static const RadOperandSpec oFill[] = { { "y", RAD_OPD_OUT, 0 }, }; +static const RadOperandSpec oScale[] = { + { "x", RAD_OPD_IN, 0 }, + { "s", RAD_OPD_WEIGHT, 0 }, + { "y", RAD_OPD_OUT, 0 }, +}; /* `cast`'s two dtype keys are STRINGS and not one `dtype`, because the whole point of the op is * that the two ends differ. ref's spelling, matched field for field so the two plugins agree. */ static const RadParamSpec pCast[] = { @@ -1674,6 +1782,7 @@ static const RadParamSpec pRope[] = { { "yarn_low", RAD_P_F64, RAD_OPTIONAL }, { "yarn_high", RAD_P_F64, RAD_OPTIONAL }, { "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL }, + { "ladder", RAD_P_STR, RAD_OPTIONAL }, /* the base ladder's width: rotary|head */ }; /* ---------------------------------------------------------------------- the vision tower */ @@ -1738,7 +1847,7 @@ static const RadParamSpec pEmbed[] = { { "dtype", RAD_P_STR, RAD_REQUIRED }, { "vocab_offset", RAD_P_INT, RAD_OPTIONAL }, /* first GLOBAL row; vocab-parallel embedding */ /* The scale embed_lookup_q's layout quantises with. That op shares this parameter list and - * libref fixes it for both, so it is spelled here to match; embed_lookup reads no scale. */ + * libref fixes it for both, so it is spelled here to match. */ { "wscale", RAD_P_F64, RAD_OPTIONAL }, }; /* embed_lookup's own: pEmbed and `mult`, the factor every gathered row is multiplied by (Gemma's @@ -1961,6 +2070,11 @@ static const RadOpSchema kSchemas[] = { SCHEMA("rmsnorm", pRmsNorm, oRmsNorm, "y = x * rsqrt(mean(x^2) + eps) * (w + wadd). `wadd` is GemmaRMSNorm's `1 +`, added in " "f32 after the load because forming it in bf16 first costs 0.3% per channel."), + SCHEMA("rmsnorm_p", pLayernorm, oUnary, + "y = x * rsqrt(mean(x^2) + eps); an rmsnorm with NO gain tensor at all. Gemma's " + "attention normalises the value with a bare RMS (a weightless ggml_rms_norm) and the " + "key with the k_norm gain in the same layer, which one op with a required gain cannot " + "express."), SCHEMA("add", pMnDtype, oBinary, "y = a + b. `b` carrying exactly n elements against an output of M rows broadcasts " "along rows, and nothing else broadcasts at all."), @@ -1970,7 +2084,12 @@ static const RadOpSchema kSchemas[] = { "(broadcast down the rows): a learned gain on an activation. f32 product, rounded once."), SCHEMA("silu_mul", pMnDtype, oGateUp, "y[.., i] = silu(gate_up[.., i]) * gate_up[.., n + i]. The GATE IS THE FIRST HALF, " - "which is the order rad-convert fuses gate_proj and up_proj in."), + "which is the order rad-convert fuses gate_proj and up_proj in."), + SCHEMA("gelu_mul", pMnDtype, oGateUp, + "y[.., i] = gelu_tanh(gate_up[.., i]) * gate_up[.., n + i], the tanh approximation " + "(gemma's gelu_pytorch_tanh), and the GATE IS THE FIRST HALF as in silu_mul. Its own " + "op, not gelu, because gated feed-forwards are trained with the tanh form and the " + "unary gelu is the exact erf one."), SCHEMA("act_mul", pActMul, oBinary, "y = act(a) * b, the activation (silu, gelu, gelu_tanh) rounded to y's dtype before " "the product: silu_mul with its two halves in two operands."), @@ -2008,6 +2127,12 @@ static const RadOpSchema kSchemas[] = { "y = value, every element of an [M, n] extent (default 0). The op a rank issues where " "it computes nothing and a reader downstream -- an all-reduce, a residual -- still " "expects a defined buffer: a wire shared across layers cannot be zeroed once a step."), + SCHEMA("logit_softcap", pMnCap, oUnary, + "y = cap * tanh(x / cap); the final-logit softcap. `cap` is required and > 0."), + SCHEMA("scale", pMnDtype, oScale, + "y = x * s, s a [1] weight broadcast over every element; the per-tensor scalar " + "(per-layer scalar). `mul` broadcasts a row, `scale_rows` a column-per-row."), + SCHEMA("cast", pCast, oUnary, "y = x, converted. `from` and `to` are for the selector; the bytes are described by the " "tensors' own dtypes and those are what the kernel reads."), @@ -2297,6 +2422,17 @@ static const RadOpSchema kSchemas[] = { SCHEMA("rmsnorm_quant_fp8", pRmsNormQuantFp8, oRmsNormQuantFp8, "RMS norm and the fp8 activation quantiser in one pass over the row. The bf16 norm " "output the unfused pair wrote is still written, and the codes are taken over it."), + SCHEMA("rmsnorm_quant_i8", pRmsNormQuantI8, oRmsNormQuantI8, + "RMS norm and the per-row int8 quantiser the w4a8 skinny GEMM reads, in one pass; with " + "a residual the norm is of residual + x (+ a post-norm of x, x a scalar), stored back."), + SCHEMA("qkv_norm_rope", pQkvNormRope, oQkvNormRope, + "per-head q and k RMS norms, the weightless v norm and the rotary of q and k over separate " + "q, k and v projections, in one dispatch; v from the raw k under v_from_k."), + SCHEMA("gelu_mul_quant_i8", pGeluMulQuantI8, oGeluMulQuantI8, + "gelu(gate) * up (tanh form) and the per-row int8 quantiser the w4a8 skinny GEMM reads, in " + "one pass."), + SCHEMA("ar_rmsnorm_quant_i8", pArRmsNormQuantI8, oArRmsNormQuantI8, + "the two-rank exact all-reduce of x and rmsnorm_quant_i8 after it, in one kernel."), SCHEMA("gated_quant_fp8", pGatedQuantFp8, oGatedQuantFp8, "silu(a)*b or sigmoid(a)*b, then the same quantiser, in one pass."), SCHEMA("gated_had_quant_fp8", pGatedQuantFp8, oGatedQuantFp8, @@ -2455,6 +2591,32 @@ static const RadConstraint cAttnDecodeH128Bf16[] = { C_GE("window", 0), C_EQ("head_dim", 128), C_EQ("gqa", 4), C_EQ("block_size", 16), C_GE("causal", 0), C_LE("q_len", 16), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; +/* Gemma 4 dense sliding window: head_dim 256, 2 queries per kv head, windowed decode + * (r4d_attn_paged_h256_gqa2.hip). window is a launch argument -- 1024 in the model, 0 = full + * attention -- so it is constrained on both sides like the drafter leg, not fixed. q_len <= 32 is + * the q_len*gqa <= 64 of the prose at gqa 2, and the bucket boundary that keeps prefill out. */ +static const RadConstraint cAttnDecodeH256Gqa2Fp8[] = { + C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnDecodeH256Gqa2Bf16[] = { + C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 32), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; +/* Gemma 4 dense sliding-window PREFILL (r4d_attn_paged_h256_gqa2.hip): the same geometry as the + * decode leg above, but no q_len bound -- it serves the prefill band (q_len > 32, the bucket the + * decode leg's C_LE leaves). window is a launch argument (1024 in the model) exactly as on the + * decode leg, so C_GE on both sides; the kernel's WIN bit masks the window and skips the below- + * window tiles. This was the band the decode-only leg left as a hole: a base-model prefill with no + * device kernel is fatal (spec §17 -- libref is an opt-in fallback the engine refuses by default). */ +static const RadConstraint cAttnPrefillH256Gqa2Fp8[] = { + C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnPrefillH256Gqa2Bf16[] = { + C_GE("window", 0), C_EQ("head_dim", 256), C_EQ("gqa", 2), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; /* EIGHT QUERIES PER KV HEAD, at both head widths (r4d_attn_paged_gqa8.hip). q_len <= 8 is the * `q_len * gqa <= 64` of the prose at gqa 8, and the difference from the gqa6 leg's 10 is the whole * of what the ratio changes: a decode workgroup holds 64 rows and the verify width is how many of @@ -2507,6 +2669,25 @@ static const RadConstraint cAttnPrefillH64G4Bf16[] = { C_EQ("window", 0), C_EQ("head_dim", 64), C_EQ("gqa", 4), C_EQ("block_size", 16), C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), }; +/* Gemma 4 dense GLOBAL layers: head_dim 512, 8 queries per KV head, full attention + * (r4d_attn_paged_h512_gqa8.hip). The `q_len <= 8` bound is the gqa verify width again; window + * stays 0, which is what separates this from the sliding leg and why it needs no windowed form. */ +static const RadConstraint cAttnPrefillH512G8Fp8[] = { + C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnPrefillH512G8Bf16[] = { + C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16), + C_EQ("causal", 1), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; +static const RadConstraint cAttnDecodeH512G8Fp8[] = { + C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "fp8_e4m3"), +}; +static const RadConstraint cAttnDecodeH512G8Bf16[] = { + C_EQ("window", 0), C_EQ("head_dim", 512), C_EQ("gqa", 8), C_EQ("block_size", 16), + C_GE("causal", 0), C_LE("q_len", 8), C_IN("q_dtype", "bf16"), C_IN("kv_dtype", "bf16"), +}; /* TWELVE QUERIES PER KV HEAD, head_dim 256 (r4d_attn_paged_h256_gqa12.hip) -- Qwen3.8-Flash-Next's * QSA layers, 24 query heads over 2. `q_len <= 5` is the same `q_len * gqa <= 64` bound the two * ratios above state, and it is TIGHTER than the legal speculation depths: a verify of depth 7 is @@ -2658,7 +2839,7 @@ static const RadConstraint cAttnDenseH512G4[] = { /* A head in a wave's registers with a rotary pair in one lane: head_dim a multiple of 32 up to * 1024. The shim refuses a rotary_dim whose half is not a multiple of 32 (neox) by name. */ static const RadConstraint cQkNormRope[] = { - C_LE("head_dim", 1024), C_DIV("head_dim", 32), + C_LE("head_dim", 1024), C_DIV("head_dim", 2), }; /* ---- gated delta net ----------------------------------------------------------------------- */ @@ -3117,6 +3298,24 @@ static const RadConstraint cSampleChain[] = { static const RadConstraint cQuantActI8[] = { C_DIV("n", 16), C_IN("dtype", "bf16"), }; +/* `n DIV 16`: a k step of the fragment order is sixteen bytes of one row. The row is staged in LDS + * as bf16 for the cross-thread fragment store: `n <= 30720` is the 60 KiB the shims bound it to, + * stated here so a wider row is refused at selection, where the caller can keep the unfused chain, + * and not at its first launch. */ +static const RadConstraint cRmsNormQuantI8[] = { + C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), +}; +/* head_dim 256 or 512: a workgroup is one head, a thread one channel. */ +static const RadConstraint cQkvNormRope[] = { + C_GE("head_dim", 256), C_LE("head_dim", 512), C_DIV("head_dim", 256), C_IN("dtype", "bf16"), +}; +static const RadConstraint cGeluMulQuantI8[] = { + C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), +}; +/* x is the message, pushed as 16B words, and the row is staged in LDS for the fragment store. */ +static const RadConstraint cArRmsNormQuantI8[] = { + C_DIV("n", 16), C_LE("n", 30720), C_IN("dtype", "bf16"), C_EQ("world_size", 2), C_P2P, +}; static const RadConstraint cHadQuantActI8[] = { C_DIV("n", 16), C_DIV("n", 128), C_LE("group", 512), C_IN("dtype", "bf16"), }; @@ -3419,6 +3618,7 @@ static const RadTunable tMv[] = { * cannot match a query that forgot to say what it wanted -- the same reasoning cSampleChain gives. * n_cand is bounded because the top-k's bitonic sort runs in LDS over a power-of-two padding. */ static const RadConstraint cBf16Row[] = { C_IN("dtype", "bf16") }; +static const RadConstraint cF32Row[] = { C_IN("dtype", "f32") }; /* bf16 rows over the byte copy, which moves four bytes a thread: an even width. */ static const RadConstraint cBf16Row2[] = { C_IN("dtype", "bf16"), C_DIV("n", 2) }; /* Opaque byte rows, four at a time. The width constraint is the vectorised copy's @@ -3630,9 +3830,10 @@ static const RadKernelInfo kKernels[] = { { "qk_norm_rope_bf16", "qk_norm_rope", "attn", "per-head RMS norm of q and k (and optionally v, unit gain) with rotary on q and k, in place", - "head_dim a multiple of 32 up to 1024, neox (rotary_dim / 2 a multiple of 32), gptj, or " - "blocks (sections of 16 or a multiple of 32 pairs, each starting on a 32-channel slice); one " - "workgroup a token and a wave a head, sin/cos computed once for all its heads", + "head_dim up to 1024, a multiple of 32 for neox (rotary_dim / 2 a multiple of 32) and gptj; " + "blocks at any even head_dim and section size (sections of 16 or a multiple of 32 pairs, each " + "on a 32-channel slice, in registers; others a lane a pair); one workgroup a token and a wave " + "a head, sin/cos computed once for all its heads", "bf16 qkv and gains, i32 positions, f32 arithmetic, the norm rounded before the rotation", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cQkNormRope), NOTUNE, @@ -3716,6 +3917,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_rmsnorm, nullptr, nullptr, nullptr, r4d_shape_rmsnorm }, +{ "rmsnorm_p_bf16", "rmsnorm_p", "norm", + "weightless root-mean-square norm (no gain), two passes over the row", + "any n; the sum of squares accumulates in f32 and only the store narrows", + "bf16 x / y, fp32 reduction", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_rmsnorm_p, nullptr, nullptr, nullptr, + r4d_shape_unary }, + { "layernorm_bf16", "layernorm", "norm", "layer norm with a gain and an optional bias, two passes over the row", "any n; mean and variance accumulate in f32 and only the store narrows", @@ -3798,6 +4008,33 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_sigmoid, nullptr, nullptr, nullptr, r4d_shape_unary }, +{ "logit_softcap_bf16", "logit_softcap", "elem", + "cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent", + "any extent; contiguous in and out", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_logit_softcap, nullptr, nullptr, nullptr, + r4d_shape_unary }, + +{ "logit_softcap_f32", "logit_softcap", "elem", + "cap * tanh(x / cap), the final-logit softcap, grid-strided over the whole extent", + "any extent; contiguous in and out", + "f32 in and out — the 1.3.0 sampling chain carries the logits as f32 from the gemm", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_logit_softcap, nullptr, nullptr, nullptr, + r4d_shape_unary }, + +{ "scale_bf16", "scale", "elem", + "x * s, s a [1] weight broadcast over the whole extent, grid-strided", + "any extent; contiguous in and out", + "bf16 in and out, fp32 arithmetic, s f32 or bf16", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr, + r4d_shape_scale }, + { "silu_mul_bf16", "silu_mul", "elem", "silu-gated product over a fused [M, 2n] gate_up", "any n; the gate is the first half", @@ -3807,6 +4044,15 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_silu_mul, nullptr, nullptr, nullptr, r4d_shape_silu_mul }, +{ "gelu_mul_bf16", "gelu_mul", "elem", + "gelu-gated product over a fused [M, 2n] gate_up", + "any n; the gate is the first half", + "bf16 in and out, fp32 arithmetic", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cBf16Row), NOTUNE, + nullptr, nullptr, r4d_rad_gelu_mul, nullptr, nullptr, nullptr, + r4d_shape_silu_mul }, + { "rope_bf16", "rope", "attn", "rotary embedding in place, one thread a rotated pair", "any head_dim; rotary_dim even and no wider than head_dim -- the frequency exponent divides by " @@ -4080,6 +4326,48 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_shape_attn_paged }, +{ "attn_prefill_h256_gqa2_fp8kv", "attn_paged", "attn", + "paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)", + "head_dim 256, 2 queries per kv head, paged block 16, varlen, " + "window taken from the launch argument (0 = full attention)", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH256Gqa2Fp8), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa2_fp8, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_prefill_h256_gqa2_bf16kv", "attn_paged", "attn", + "paged causal attention with a sliding window, query-tiled (prefill / chunked prefill)", + "head_dim 256, 2 queries per kv head, paged block 16, varlen, " + "window taken from the launch argument (0 = full attention)", + "bf16 query, bf16 kv cache, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH256Gqa2Bf16), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h256_gqa2_bf16, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h256_gqa2_fp8kv", "attn_paged", "attn", + "paged causal attention with a sliding window, split-KV (decode / verify)", + "head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, " + "window taken from the launch argument (0 = full attention)", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256Gqa2Fp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h256_gqa2_fp8, r4d_rad_attn_decode_h256_gqa2_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h256_gqa2_bf16kv", "attn_paged", "attn", + "paged causal attention with a sliding window, split-KV (decode / verify)", + "head_dim 256, 2 queries per kv head, paged block 16, q_len*gqa <= 64, " + "window taken from the launch argument (0 = full attention)", + "bf16 query, bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH256Gqa2Bf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h256_gqa2_bf16, r4d_rad_attn_decode_h256_gqa2_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + { "attn_prefill_h256_gqa8_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 256, 8 queries per kv head, paged block 16, varlen", @@ -4174,6 +4462,44 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_attn_prefill_h64_gqa4_bf16, nullptr, nullptr, nullptr, r4d_shape_attn_paged }, +{ "attn_prefill_h512_gqa8_fp8kv", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 512, 8 queries per kv head, paged block 16, varlen", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH512G8Fp8), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h512_gqa8_fp8, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_prefill_h512_gqa8_bf16kv", "attn_paged", "attn", + "paged causal attention, query-tiled (prefill / chunked prefill)", + "head_dim 512, 8 queries per kv head, paged block 16, varlen", + "bf16 query, bf16 kv cache, bf16 out", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_PREFILL, + ROW(cAttnPrefillH512G8Bf16), NOTUNE, + nullptr, nullptr, r4d_rad_attn_prefill_h512_gqa8_bf16, nullptr, nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h512_gqa8_fp8kv", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", + "head_dim 512, 8 queries per kv head, paged block 16, q_len*gqa <= 64, no window", + "bf16 query, fp8-e4m3 kv cache with per-(seq,head) descales, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH512G8Fp8), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h512_gqa8_fp8, r4d_rad_attn_decode_h512_gqa8_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + +{ "attn_decode_h512_gqa8_bf16kv", "attn_paged", "attn", + "paged attention, causal or not, split-KV (decode / speculative verify / draft block)", + "head_dim 512, 8 queries per kv head, paged block 16, q_len*gqa <= 64, no window", + "bf16 query, bf16 kv cache, bf16 out, f16 partials", + RAD_DOMAIN_DEVICE, R4D_PRIO_ATTN_DECODE, + ROW(cAttnDecodeH512G8Bf16), ROW(tAttnSplit), nullptr, + nullptr, nullptr, r4d_rad_attn_decode_h512_gqa8_bf16, r4d_rad_attn_decode_h512_gqa8_scratch, + nullptr, nullptr, + r4d_shape_attn_paged }, + { "attn_prefill_h256_gqa12_fp8kv", "attn_paged", "attn", "paged causal attention, query-tiled (prefill / chunked prefill)", "head_dim 256, 12 queries per kv head, paged block 4, varlen", @@ -5414,6 +5740,51 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_quant_act_i8, nullptr, nullptr, nullptr, r4d_shape_quant_act_i8 , nullptr, nullptr, r4d_rad_quant_act_i8_describe }, +{ "rmsnorm_quant_i8", "rmsnorm_quant_i8", "quant", + "RMS norm and quant_act_i8's quantiser in one pass over the row; optionally the residual " + "junction in front of it -- a post-norm on x, the add into the residual and a scalar on the sum", + "n a multiple of 16 and n*2 bytes within LDS; one workgroup per row at rmsnorm_bf16's width; " + "the gains f32 or bf16, read off the operand; w_post and scalar need the residual", + "bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale, optional bf16 " + "out; every stored intermediate rounded to bf16 as the unfused chain stores it", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cRmsNormQuantI8), NOTUNE, + nullptr, nullptr, r4d_rad_rmsnorm_quant_i8, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, r4d_rad_rmsnorm_quant_i8_describe }, + +{ "qkv_norm_rope_bf16", "qkv_norm_rope", "attn", + "per-head RMS norms of separate q and k projections, the weightless norm of v (or of the raw k), " + "and the rotary of q and k, in place, in one dispatch", + "head_dim 256 or 512; neox, `rotary` or `head` ladder, one position component, no YaRN; one " + "workgroup a (token, head), a thread a channel", + "bf16 q/k/v and gains (or f32 gains), i32 positions; byte-identical to rmsnorm_p + rmsnorm x2 + " + "rope x2, each norm taken by its standalone kernel's partition", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cQkvNormRope), NOTUNE, + nullptr, nullptr, r4d_rad_qkv_norm_rope, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, r4d_rad_qkv_norm_rope_describe }, + +{ "gelu_mul_quant_i8", "gelu_mul_quant_i8", "quant", + "gelu(gate) * up, the tanh form, and quant_act_i8's quantiser in one pass over the row", + "n a multiple of 16 and n*2 bytes within LDS; one workgroup per row", + "bf16 gate_up in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale, optional " + "bf16 out; the codes taken over the bf16-rounded product", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGeluMulQuantI8), NOTUNE, + nullptr, nullptr, r4d_rad_gelu_mul_quant_i8, nullptr, nullptr, nullptr, + nullptr, nullptr, nullptr, r4d_rad_gelu_mul_quant_i8_describe }, + +{ "ar_rmsnorm_quant_i8", "ar_rmsnorm_quant_i8", "quant", + "the two-rank exact all-reduce and the junction after it -- post-norm of the reduced sum, residual " + "add, scalar, RMS norm and quant_act_i8's quantiser -- in one kernel", + "exactly 2 ranks; n a multiple of 16, x unpitched (it is the message); one block a row; exact wire", + "bf16 in, int8 out in the w4a8 GEMM's fragment order with an f32 per-row scale; the reduced sum " + "rounded to bf16 as the standalone exact all-reduce stores it", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cArRmsNormQuantI8), ROW(tAr), nullptr, + r4d_rad_ar_ln_init, r4d_rad_ar_fini, r4d_rad_ar_rmsnorm_quant_i8, nullptr, nullptr, nullptr, + nullptr }, + { "had_quant_act_i8", "had_quant_act_i8", "quant", "block Hadamard along K then per-row symmetric int8 quantisation; the rotation is what makes " "int8 activations usable at all: unrotated, the per-row absmax is set by a few outlier channels " diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 8bfe30d7..1a6e93ff 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -771,7 +771,7 @@ static const RadKernelInfo* find(const Plugin& pl, const char* name) { /* ------------------------------------------------------------------ per-family smoke tests */ static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa, - int64_t q_len, const char* kv_dtype, int prefill) { + int64_t q_len, const char* kv_dtype, int prefill, int window = 0) { if (!sel(name)) return; const RadKernelInfo* r = find(pl, name); if (!r) { ok(name, false, "row absent"); return; } @@ -803,7 +803,7 @@ static void attn_case(const Plugin& pl, const char* name, int64_t head_dim, int6 absent(ts[6]); std::vector ps = { PI("q_len", q_len), PI("head_dim", head_dim), PI("gqa", gqa), PI("block_size", bs), - PI("causal", 1), PI("window", 0), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype), + PI("causal", 1), PI("window", window), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype), }; (void)prefill; run_case(r, ts, ps); @@ -884,6 +884,186 @@ static float h_e4m3(uint8_t b) { return sign * (1.0f + (float)mn / 8.0f) * std::ldexp(1.0f, (int)ex - 7); } +/* Two avalanche-random values for the numeric attention check: a bounded bf16 in [-1, 1] and an + * e4m3 code, each a function of its index so a wrong pitch or lane map reads unrelated numbers. */ +static uint16_t st_rand_bf16(uint32_t i) { + const uint32_t x = st_mix32(i); + const float f = ((x & 0x00ffffffu) / 16777215.0f) * 2.0f - 1.0f; + return h_to_bf16(f); +} +static uint8_t st_rand_e4m3(uint32_t i) { + const uint32_t x = st_mix32(i + 0x9e3779b9u); + /* Bounded to [-1, 1] (the positive magnitudes below), mirroring st_rand_bf16. The full e4m3 + * range (up to 448) makes the attention scores reach ~448*head_dim/sqrt(head_dim), so the + * softmax dominates by e^score and a 1-ulp difference between the device's v_cvt_f32_fp8 and + * this software h_e4m3 flips the max into a large output error; bounded, the scores stay ~22 + * (the passing bf16 path) and the comparison is stable. */ + static const uint8_t mag[] = { + 0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, /* subnormal, 0 .. 7/64 */ + 0x08, 0x09, 0x0A, 0x0B, 0x0C, 0x0D, 0x0E, 0x0F, /* exp 4, 0.125 .. 0.234375 */ + 0x18, 0x19, 0x1A, 0x1B, 0x1C, 0x1D, 0x1E, 0x1F, /* exp 5, 0.25 .. 0.46875 */ + 0x28, 0x29, 0x2A, 0x2B, 0x2C, 0x2D, 0x2E, 0x2F, /* exp 6, 0.5 .. 0.9375 */ + 0x38, /* exp 7, 1.0 */ + }; + const uint8_t m = mag[(x >> 1) % (sizeof mag / sizeof mag[0])]; + return (uint8_t)(m | (((x >> 8) & 1u) << 7)); +} + +/* The inline paged-attention oracle: a port of ref_attn_paged (libref/ref_attn.cpp) for the + * uniform batch, bf16 q, fp8-e4m3 or bf16 k/v, f32 descales. The selftest does not link libref, + * so the reference the kbench byte-equality uses is carried here; the mask, the two-pass softmax + * and the k/v dequant are the same, so a wrong kernel fails the comparison. One (row, head) at a + * time: `i` is the query's position within its sequence's query, and `pos = ctx - qlen + i`. */ +static void attn_oracle_one(const uint16_t* qh, const uint8_t* kv, int kv_is_fp8, + int64_t head_dim, int64_t kv_heads, int64_t block_size, int64_t kh, + const int* block_table, int64_t max_blocks, int ctx, + float kds, float vds, int causal, int window, float scale, + int64_t qlen, int64_t i, float* out) { + const int ew = kv_is_fp8 ? 1 : 2; + const int64_t pos = ctx - qlen + i; + const int64_t sb = kv_heads * block_size * 2 * head_dim; + const int64_t sh = block_size * 2 * head_dim; + const int64_t so = 2 * head_dim; + const auto kslot = [&](int64_t blk, int64_t slot, int64_t d) { + const uint8_t* p = kv + (blk * sb + kh * sh + slot * so + d) * ew; + return kv_is_fp8 ? h_e4m3(p[0]) : h_bf16(*(const uint16_t*)p); + }; + const auto vslot = [&](int64_t blk, int64_t slot, int64_t d) { + const uint8_t* p = kv + (blk * sb + kh * sh + slot * so + head_dim + d) * ew; + return kv_is_fp8 ? h_e4m3(p[0]) : h_bf16(*(const uint16_t*)p); + }; + const auto visible = [&](int64_t j) { + if (causal ? (j > pos) : (j >= ctx)) return false; + if (window > 0) { const int64_t d = pos - j; + if (causal ? (d >= window) : (d >= window || d <= -window)) return false; } + return true; + }; + float mx = -INFINITY; + for (int64_t j = 0; j < ctx; ++j) { + if (!visible(j)) continue; + if (j / block_size >= max_blocks) break; + int blk = block_table[j / block_size]; + if (blk < 0) continue; + float dot = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) dot += h_bf16(qh[d]) * (kslot(blk, j % block_size, d) * kds); + dot *= scale; + if (dot > mx) mx = dot; + } + if (mx == -INFINITY) { for (int64_t d = 0; d < head_dim; ++d) out[d] = 0.0f; return; } + float sum = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) out[d] = 0.0f; + for (int64_t j = 0; j < ctx; ++j) { + if (!visible(j)) continue; + if (j / block_size >= max_blocks) break; + int blk = block_table[j / block_size]; + if (blk < 0) continue; + float dot = 0.0f; + for (int64_t d = 0; d < head_dim; ++d) dot += h_bf16(qh[d]) * (kslot(blk, j % block_size, d) * kds); + const float w = std::exp(dot * scale - mx); + sum += w; + for (int64_t d = 0; d < head_dim; ++d) out[d] += w * (vslot(blk, j % block_size, d) * vds); + } + const float inv = sum > 0.0f ? 1.0f / sum : 0.0f; + for (int64_t d = 0; d < head_dim; ++d) out[d] *= inv; +} + +/* The numeric attention check: fill q and the paged k/v with avalanche-random data, run the row, + * and compare the bf16 output against the inline oracle above. The launch smoke (attn_case) proves + * the kernel starts; this proves it computes. A negative control corrupts a share of the reference + * and requires the comparison to FAIL -- the proof the check has teeth. */ +static void attn_numeric_case(const Plugin& pl, const char* name, int64_t head_dim, int64_t gqa, + int64_t q_len, const char* kv_dtype, int window, int64_t ctx = 64) { + if (!sel(name)) return; + const RadKernelInfo* r = find(pl, name); + if (!r) { ok(name, false, "row absent"); return; } + const int64_t seqs = 1, kv_heads = 2, bs = 16; + const int64_t q_heads = kv_heads * gqa; + const int64_t max_blocks = ctx / bs; + const int64_t total_q = seqs * q_len; + const int kv_is_fp8 = std::strcmp(kv_dtype, "bf16") != 0; + const uint32_t kvdt = kv_is_fp8 ? RAD_F8E4M3 : RAD_BF16; + const int ew = kv_is_fp8 ? 1 : 2; + const float scale = 1.0f / std::sqrt((float)head_dim); + + std::vector qh((size_t)total_q * q_heads * head_dim); + for (size_t i = 0; i < qh.size(); ++i) qh[i] = st_rand_bf16(i); + const int64_t nelem = max_blocks * kv_heads * bs * 2 * head_dim; + std::vector kv((size_t)nelem * ew); + for (int64_t e = 0; e < nelem; ++e) { + const size_t bo = (size_t)e * ew; + if (kv_is_fp8) kv[bo] = st_rand_e4m3(e); + else { const uint16_t h = st_rand_bf16(e); kv[bo] = (uint8_t)h; kv[bo + 1] = (uint8_t)(h >> 8); } + } + const std::vector bt = iota_i32(max_blocks); + + void* d_q = dalloc((size_t)total_q * q_heads * head_dim * 2); + st_memcpy(d_q, qh.data(), qh.size() * 2, hipMemcpyHostToDevice); + void* d_kv = dalloc(kv.size()); + st_memcpy(d_kv, kv.data(), kv.size(), hipMemcpyHostToDevice); + void* d_out = dalloc((size_t)total_q * q_heads * head_dim * 2); + + std::vector ts = { + T(d_q, RAD_BF16, { total_q, q_heads, head_dim }), + T(d_kv, kvdt, { max_blocks, kv_heads, bs, 2 * head_dim }), + TI32({ seqs, max_blocks }, bt), + TI32({ seqs }, rep_i32(seqs, (int32_t)ctx)), + TF32({ seqs, kv_heads }, 1.0f), + TF32({ seqs, kv_heads }, 1.0f), + T(nullptr, RAD_I32, { seqs + 1 }), + T(d_out, RAD_BF16, { total_q, q_heads, head_dim }), + }; + if (kvdt == RAD_BF16) { absent(ts[4]); absent(ts[5]); } + absent(ts[6]); + std::vector ps = { + PI("q_len", q_len), PI("head_dim", head_dim), PI("gqa", gqa), PI("block_size", bs), + PI("causal", 1), PI("window", window), PS("q_dtype", "bf16"), PS("kv_dtype", kv_dtype), + }; + run_case(r, ts, ps); + + std::vector oh((size_t)total_q * q_heads * head_dim); + st_memcpy(oh.data(), d_out, oh.size() * 2, hipMemcpyDeviceToHost); + + const float abs_tol = 1e-3f, rel_tol = 2e-2f; + std::vector oref((size_t)total_q * q_heads * head_dim); + float max_err = 0.0f; int nbad = 0; + for (int64_t tok = 0; tok < total_q; ++tok) + for (int64_t h = 0; h < q_heads; ++h) { + const int64_t kh = h / gqa; + float o[512]; + attn_oracle_one(&qh[(tok * q_heads + h) * head_dim], kv.data(), kv_is_fp8, + head_dim, kv_heads, bs, kh, bt.data(), max_blocks, ctx, + 1.0f, 1.0f, 1, window, scale, q_len, tok, o); + for (int64_t d = 0; d < head_dim; ++d) { + const size_t idx = (size_t)(tok * q_heads + h) * head_dim + d; + oref[idx] = o[d]; + const float got = h_bf16(oh[idx]); + const float diff = std::fabs(got - o[d]); + if (diff > abs_tol + rel_tol * std::fabs(o[d])) ++nbad; + if (diff > max_err) max_err = diff; + } + } + char nm[160]; + std::snprintf(nm, sizeof nm, "%s numeric", name); + ok(nm, nbad == 0, + fmt("max_err=%.5g bad=%d/%d", max_err, nbad, (int)oref.size())); + + /* Negative control: corrupt a share of the reference and require the comparison to FAIL -- the + * proof the check has teeth, since a broken (always-passing) comparison would flag nothing. */ + for (size_t idx = 0; idx < oref.size(); ++idx) + if ((idx & 7) == 0) oref[idx] += 0.5f; + float nmax = 0.0f; int nbadc = 0; + for (size_t idx = 0; idx < oref.size(); ++idx) { + const float got = h_bf16(oh[idx]); + const float diff = std::fabs(got - oref[idx]); + if (diff > abs_tol + rel_tol * std::fabs(oref[idx])) ++nbadc; + if (diff > nmax) nmax = diff; + } + std::snprintf(nm, sizeof nm, "%s numeric-negctl", name); + ok(nm, nbadc > 0, + fmt("corrupted ref must fail: max_err=%.5g bad=%d", nmax, nbadc)); +} + + /* ================================================================== a weight's canonical planes * * A container holds a weight as the planes of its encoding, row-major (spec §4.1), and a kernel's @@ -4167,6 +4347,376 @@ static void bf16_tiled_identity(const Plugin& pl, int64_t M, int64_t N, int64_t ok(nm, all, d); } +/* logit_softcap, against an f64 evaluation of the same formula. + * + * THE CAP IS THE PARAMETER THE MODEL LIVES IN (Gemma 4's graph issues it at 30.0), so the case + * runs at two values: the model's, and a smaller one that moves every answer -- a kernel that + * hard-wires 30.0, or one that swaps `cap` with its inverse, passes one cap and fails the other. + * + * The inputs are 0, half, one, two and five TIMES THE CAP, signed: x/cap is then an exact small + * half-integer, the f64 oracle cap * tanh(x/cap) is five constants deep, and the only room for an + * error in the comparison is the kernel's own f32 arithmetic and its bf16 store. The tolerance is + * this file's f32-against-f64 one (1% relative, 1e-3 absolute). */ +static void logit_softcap_case(const Plugin& pl) { + const char* what = "logit_softcap vs an f64 evaluation of the same formula"; + /* Both device legs run the case: bf16 (the gemm's own dtype) and f32 (the 1.3.0 sampling + * chain, where the logits reach the softcap as f32 rows). The f32 leg answers in the + * arithmetic dtype itself, so its oracle compare reads f32, not a bf16 round trip. */ + for (const uint32_t dt : { (uint32_t)RAD_BF16, (uint32_t)RAD_F32 }) { + const char* row = dt == RAD_BF16 ? "logit_softcap_bf16" : "logit_softcap_f32"; + const size_t es = dt == RAD_BF16 ? 2 : 4; + const RadKernelInfo* r = find(pl, row); + if (!r) { ok(what, false, std::string("row absent: ") + row); return; } + + const int64_t M = 7, n = 128; + for (const double capd : { 30.0, 10.0 }) { + std::vector xh((size_t)M * n); + std::vector xf((size_t)M * n); + std::vector want((size_t)M * n); + const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 }; + for (int64_t i = 0; i < M * n; ++i) { + const double mag = mags[(int)((i * 31) % 5)]; + const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0; + const double xv = sgn * mag * capd; + xh[(size_t)i] = h_to_bf16((float)xv); + xf[(size_t)i] = (float)xv; + want[(size_t)i] = capd * std::tanh(xv / capd); + } + + void* d_x = dalloc((size_t)(M * n) * es); + void* d_o = dalloc((size_t)(M * n) * es); + if (!d_x || !d_o) { ok(what, false, "hipMalloc failed"); return; } + st_memcpy(d_x, dt == RAD_BF16 ? (const void*)xh.data() : (const void*)xf.data(), + (size_t)(M * n) * es, hipMemcpyHostToDevice); + + std::vector ts = { + T(d_x, dt, { M, n }), + T(d_o, dt, { M, n }), + }; + std::vector ps = { PI("n", n), PF("cap", capd) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + + const int rc = r->launch(&a, nullptr); + st_stream_sync(nullptr); + if (rc != RAD_OK) { + ok(what, false, "launch rc=" + std::to_string(rc) + " cap=" + std::to_string(capd)); + return; + } + + std::vector got((size_t)(M * n)); + std::vector gotf((size_t)(M * n)); + st_memcpy(dt == RAD_BF16 ? (void*)got.data() : (void*)gotf.data(), d_o, + (size_t)(M * n) * es, hipMemcpyDeviceToHost); + double worst = 0.0; + int64_t bad = 0; + for (int64_t i = 0; i < M * n; ++i) { + const double v = dt == RAD_BF16 ? (double)h_bf16(got[(size_t)i]) + : (double)gotf[(size_t)i]; + const double e = v - want[(size_t)i]; + if (std::fabs(e) > worst) worst = std::fabs(e); + if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad; + } + ok(what, bad == 0, std::string(row) + " cap=" + std::to_string(capd) + + " worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad)); + } + } +} + +/* rmsnorm_p, against an f64 evaluation of the weightless normalisation. + * + * THE EPS IS THE PARAMETER THE MODEL LIVES IN (Gemma 4 issues it at 1e-6), so the case runs at + * two values: the model's, and a larger one (1e-2) that moves every answer -- a kernel that hard- + * wires 1e-6, or one that drops the +eps and answers a bare 1/rms, passes the small one and fails + * the large. + * + * The inputs are a fixed set of magnitudes, signed, so the f64 oracle x * rsqrt(mean(x^2) + eps) + * is exact and the only room for an error in the comparison is the kernel's own f32 accumulation + * and its bf16 store. The oracle is computed from the bf16 values the kernel actually reads. The + * tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). */ +static void rmsnorm_p_case(const Plugin& pl) { + const char* what = "rmsnorm_p vs an f64 evaluation of the weightless normalisation"; + const RadKernelInfo* r = find(pl, "rmsnorm_p_bf16"); + if (!r) { ok(what, false, "row absent"); return; } + + const int64_t M = 7, n = 640; + for (const double epsd : { 1e-6, 1e-2 }) { + std::vector xh((size_t)M * n); + const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 }; + for (int64_t i = 0; i < M * n; ++i) { + const double mag = mags[(int)((i * 31) % 5)]; + const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0; + xh[(size_t)i] = h_to_bf16((float)(sgn * mag)); + } + + // f64 oracle from the bf16 values the kernel reads: y = x * rsqrt(mean(x^2) + eps). + std::vector want((size_t)M * n); + for (int64_t m = 0; m < M; ++m) { + double ss = 0.0; + for (int64_t i = 0; i < n; ++i) { + const double v = (double)h_bf16(xh[(size_t)m * n + i]); + ss += v * v; + } + const double s = 1.0 / std::sqrt(ss / (double)n + epsd); + for (int64_t i = 0; i < n; ++i) + want[(size_t)m * n + i] = (double)h_bf16(xh[(size_t)m * n + i]) * s; + } + + void* d_x = dalloc(xh.size() * 2); + void* d_o = dalloc((size_t)(M * n) * 2); + if (!d_x || !d_o) { ok(what, false, "hipMalloc failed"); return; } + st_memcpy(d_x, xh.data(), xh.size() * 2, hipMemcpyHostToDevice); + + std::vector ts = { + T(d_x, RAD_BF16, { M, n }), + T(d_o, RAD_BF16, { M, n }), + }; + std::vector ps = { PI("n", n), PF("eps", epsd) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + + const int rc = r->launch(&a, nullptr); + st_stream_sync(nullptr); + if (rc != RAD_OK) { + ok(what, false, "launch rc=" + std::to_string(rc) + " eps=" + std::to_string(epsd)); + return; + } + + std::vector got((size_t)(M * n)); + st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost); + double worst = 0.0; + int64_t bad = 0; + for (int64_t i = 0; i < M * n; ++i) { + const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i]; + if (std::fabs(e) > worst) worst = std::fabs(e); + if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad; + } + ok(what, bad == 0, "eps=" + std::to_string(epsd) + + " worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad)); + } +} + +/* gelu_mul, against an f64 evaluation of the tanh-approximation GELU. + * + * The inputs are a fixed set of magnitudes, signed, for both the gate and the up half, so the f64 + * oracle 0.5*g*(1 + tanh(0.7978845608028654*(g + 0.044715*g^3))) * u is exact and the only room for + * an error in the comparison is the kernel's own f32 tanhf and its bf16 store. The oracle is computed + * from the bf16 values the kernel reads; the gate is the first half of the [M, 2n] row. The + * tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). */ +static void gelu_mul_case(const Plugin& pl) { + const char* what = "gelu_mul vs an f64 evaluation of the tanh GELU"; + const RadKernelInfo* r = find(pl, "gelu_mul_bf16"); + if (!r) { ok(what, false, "row absent"); return; } + + const int64_t M = 7, n = 640; + std::vector gh((size_t)M * 2 * n); + const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 5.0 }; + for (int64_t i = 0; i < M * 2 * n; ++i) { + const double mag = mags[(int)((i * 31) % 5)]; + const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0; + gh[(size_t)i] = h_to_bf16((float)(sgn * mag)); + } + + // f64 oracle from the bf16 values the kernel reads: y = gelu_tanh(gate) * up, gate the first half. + std::vector want((size_t)M * n); + const double k0 = 0.7978845608028654, k1 = 0.044715; + for (int64_t m = 0; m < M; ++m) { + for (int64_t i = 0; i < n; ++i) { + const double g = (double)h_bf16(gh[(size_t)m * 2 * n + i]); + const double u = (double)h_bf16(gh[(size_t)m * 2 * n + n + i]); + const double gelu = 0.5 * g * (1.0 + std::tanh(k0 * (g + k1 * g * g * g))); + want[(size_t)m * n + i] = gelu * u; + } + } + + void* d_g = dalloc(gh.size() * 2); + void* d_o = dalloc((size_t)(M * n) * 2); + if (!d_g || !d_o) { ok(what, false, "hipMalloc failed"); return; } + st_memcpy(d_g, gh.data(), gh.size() * 2, hipMemcpyHostToDevice); + + std::vector ts = { + T(d_g, RAD_BF16, { M, 2 * n }), + T(d_o, RAD_BF16, { M, n }), + }; + std::vector ps = { PI("n", n) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + + const int rc = r->launch(&a, nullptr); + st_stream_sync(nullptr); + if (rc != RAD_OK) { + ok(what, false, "launch rc=" + std::to_string(rc)); + return; + } + + std::vector got((size_t)(M * n)); + st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost); + double worst = 0.0; + int64_t bad = 0; + for (int64_t i = 0; i < M * n; ++i) { + const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i]; + if (std::fabs(e) > worst) worst = std::fabs(e); + if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad; + } + ok(what, bad == 0, "worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad)); +} + +/* scale, against an f64 evaluation of the same multiply. + * + * THE SCALAR IS THE [1] WEIGHT THE MODEL LIVES IN (Gemma 4's per-layer scalar, 0.03-0.99), so the + * case runs at three values: two positive of different magnitude (a kernel that hard-wires one of + * them, or one that squares the scalar, passes one and fails the other) and a negative (a kernel + * that drops the sign passes the positives and fails this). + * + * The inputs are a fixed set of magnitudes, signed, so the f64 oracle x * s is five constants deep + * and the only room for an error in the comparison is the kernel's own f32 arithmetic and its bf16 + * store. The tolerance is this file's f32-against-f64 one (1% relative, 1e-3 absolute). The scalar + * is stored as f32 (the kernel's branch reads it as such); a bf16 `s` takes the other branch and is + * not exercised here, which is fine -- the multiply is the same either way. */ +static void scale_case(const Plugin& pl) { + const char* what = "scale vs an f64 evaluation of the same multiply"; + const RadKernelInfo* r = find(pl, "scale_bf16"); + if (!r) { ok(what, false, "row absent"); return; } + + const int64_t M = 7, n = 128; + for (const double sv : { 2.0, 0.5, -1.5 }) { + std::vector xh((size_t)M * n); + std::vector want((size_t)M * n); + const double mags[5] = { 0.0, 0.5, 1.0, 2.0, 3.0 }; + for (int64_t i = 0; i < M * n; ++i) { + const double mag = mags[(int)((i * 31) % 5)]; + const double sgn = (mag == 0.0 || (i * 17) % 2 == 0) ? 1.0 : -1.0; + const double xv = sgn * mag; + xh[(size_t)i] = h_to_bf16((float)xv); + want[(size_t)i] = xv * sv; + } + + void* d_x = dalloc(xh.size() * 2); + void* d_s = dalloc(4); + void* d_o = dalloc((size_t)(M * n) * 2); + if (!d_x || !d_s || !d_o) { ok(what, false, "hipMalloc failed"); return; } + st_memcpy(d_x, xh.data(), xh.size() * 2, hipMemcpyHostToDevice); + const float sf = (float)sv; + st_memcpy(d_s, &sf, 4, hipMemcpyHostToDevice); + + std::vector ts = { + T(d_x, RAD_BF16, { M, n }), + T(d_s, RAD_F32, { 1 }), + T(d_o, RAD_BF16, { M, n }), + }; + std::vector ps = { PI("n", n) }; + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + + const int rc = r->launch(&a, nullptr); + st_stream_sync(nullptr); + if (rc != RAD_OK) { + ok(what, false, "launch rc=" + std::to_string(rc) + " s=" + std::to_string(sv)); + return; + } + + std::vector got((size_t)(M * n)); + st_memcpy(got.data(), d_o, got.size() * 2, hipMemcpyDeviceToHost); + double worst = 0.0; + int64_t bad = 0; + for (int64_t i = 0; i < M * n; ++i) { + const double e = (double)h_bf16(got[(size_t)i]) - want[(size_t)i]; + if (std::fabs(e) > worst) worst = std::fabs(e); + if (std::fabs(e) > 1e-2 * (std::fabs(want[(size_t)i]) + 1e-3)) ++bad; + } + ok(what, bad == 0, "s=" + std::to_string(sv) + + " worst_abs=" + std::to_string(worst) + " bad=" + std::to_string(bad)); + } +} + +/* rope_bf16, against an f32 mirror of rope_kernel at each ladder width. `den` is the ladder's + * width -- `rot` for `rotary`/absent and `head_dim` for `head` -- so the same kernel body is + * checked under both. The V head is untouched in every case; the absences there would be invisible + * in magnitude (the rotation preserves length) and rel_l2 is what sees the angle itself. */ +static void rope_ladder_case(const Plugin& pl) { + const char* what = "rope ladder vs an f32 mirror of rope_kernel at each width"; + const RadKernelInfo* r = find(pl, "rope_bf16"); + if (!r) { ok(what, false, "row absent"); return; } + + const int64_t M = 5, hd = 64, rot = 32, half = rot / 2; + const int64_t n_head = 2, nkv = 1, n_rope = n_head + nkv; /* 3 rotate, one V does not */ + const int64_t row = (n_head + 2 * nkv) * hd; + const float theta = 10000.0f; + const int32_t pos[5] = { 0, 1, 7, 128, 4096 }; + + for (const char* lad : std::initializer_list{ nullptr, "rotary", "head" }) { + const int64_t den = (lad && !std::strcmp(lad, "head")) ? hd : rot; + const char* tag = lad ? lad : "absent"; + + std::vector saved((size_t)M * row); + for (int64_t i = 0; i < M * row; ++i) { + float v = (float)(((i * 5) % 17) - 8) / 9.0f; + if (i % 13 == 0) v *= 4.0f; /* a few big channels */ + saved[(size_t)i] = h_to_bf16(v); + } + + void* d_qkv = dalloc(saved.size() * 2); + void* d_pos = dalloc(M * 4); + if (!d_qkv || !d_pos) { ok(what, false, "hipMalloc failed"); return; } + st_memcpy(d_qkv, saved.data(), saved.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_pos, pos, M * 4, hipMemcpyHostToDevice); + + std::vector ts = { T(d_qkv, RAD_BF16, { M, row }), T(d_pos, RAD_I32, { M }) }; + std::vector ps = { PI("M", M), PI("head_dim", hd), PI("n_head", n_head), + PI("n_head_kv", nkv), PF("theta", (double)theta), + PF("scale", 1.0), PS("mode", "neox"), + PI("rotary_dim", rot) }; + if (lad) ps.push_back(PS("ladder", lad)); + RadArgs a; + std::memset(&a, 0, sizeof(a)); + a.t = ts.data(); a.n_t = (int)ts.size(); + a.p = ps.data(); a.n_p = (int)ps.size(); + + const int rc = r->launch(&a, nullptr); + st_stream_sync(nullptr); + if (rc != RAD_OK) { ok(what, false, std::string("ladder=") + tag + " rc=" + std::to_string(rc)); return; } + + std::vector got((size_t)M * row); + st_memcpy(got.data(), d_qkv, got.size() * 2, hipMemcpyDeviceToHost); + + double num = 0.0, dnorm = 0.0; + int64_t untouched_bad = 0; + for (int64_t m = 0; m < M; ++m) { + const size_t base = (size_t)m * row; + for (int64_t h = 0; h < n_rope; ++h) { + for (int64_t i = 0; i < half; ++i) { + const size_t i0 = base + (size_t)h * hd + i; + /* `head` is HF's proportional RoPE: pair i is (i, i + head_dim/2). */ + const size_t i1 = i0 + ((lad && !std::strcmp(lad, "head")) ? hd / 2 : half); + const float x0 = h_bf16(saved[(size_t)i0]), x1 = h_bf16(saved[(size_t)i1]); + const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)den); + float s, c; + sincosf((float)pos[(size_t)m] * inv, &s, &c); + const float w0 = x0 * c - x1 * s, w1 = x0 * s + x1 * c; + const float g0 = h_bf16(got[(size_t)i0]), g1 = h_bf16(got[(size_t)i1]); + num += (double)(g0 - w0) * (double)(g0 - w0) + + (double)(g1 - w1) * (double)(g1 - w1); + dnorm += (double)w0 * w0 + (double)w1 * w1; + } + } + for (int64_t e = 0; e < hd; ++e) /* the V head is untouched, so exact */ + if (got[base + (size_t)n_rope * hd + e] != saved[base + (size_t)n_rope * hd + e]) + ++untouched_bad; + } + const double rel = dnorm > 0.0 ? std::sqrt(num / dnorm) : 0.0; + ok(what, rel < 2e-3 && untouched_bad == 0, std::string("ladder=") + tag + " rel_l2=" + + std::to_string(rel) + " vhead-moved=" + std::to_string(untouched_bad)); + } +} + /* ---- the two fp8 fusions, against the pair each one replaces -------------------------------- */ // // THE INVARIANT IS NOT "CLOSE", IT IS BYTE-IDENTICAL, which is why this compares against the @@ -4432,6 +4982,254 @@ static void fused_quant_fp8_numeric(const Plugin& pl) { } } +/* ---- gelu_mul_quant_i8, against gelu_mul + quant_act_i8 ------------------------------------- + * Gemma 4 31B's per-rank feed-forward width (10752 of 21504 at two ranks), both batch widths. */ +static void gelu_mul_quant_i8_numeric(const Plugin& pl) { + const RadKernelInfo* gm = find(pl, "gelu_mul_bf16"); + const RadKernelInfo* qz = find(pl, "quant_act_i8"); + const RadKernelInfo* fz = find(pl, "gelu_mul_quant_i8"); + if (!gm || !qz || !fz) { ok("gelu_mul_quant_i8 vs its pair", false, "rows absent"); return; } + for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)40 }) { + const int64_t n = 10752; + std::vector hgu((size_t)M * 2 * n); + for (size_t i = 0; i < hgu.size(); ++i) + hgu[i] = h_to_bf16(std::ldexp(1.0f, (int)((i / 512) % 5) - 2) * (0.029f * (float)((i * 41) % 103) - 1.5f)); + void* dgu = dalloc(hgu.size() * 2); + void* dy[2] = { dalloc((size_t)M * n * 2), dalloc((size_t)M * n * 2) }; + void* dq[2] = { dalloc((size_t)M * n), dalloc((size_t)M * n) }; + void* ds[2] = { dalloc((size_t)M * 4), dalloc((size_t)M * 4) }; + if (!dgu || !dy[1] || !dq[1] || !ds[1]) { ok("gelu_mul_quant_i8 alloc", false, "hipMalloc failed"); return; } + st_memcpy(dgu, hgu.data(), hgu.size() * 2, hipMemcpyHostToDevice); + int rc = launch_row(gm, { T(dgu, RAD_BF16, { M, 2 * n }), T(dy[0], RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(qz, { T(dy[0], RAD_BF16, { M, n }), T(dq[0], RAD_I8, { M, n }), T(ds[0], RAD_F32, { M }), + T(nullptr, RAD_F32, {}) }, + { PI("M", M), PI("n", n), PI("group", n), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(fz, { T(dgu, RAD_BF16, { M, 2 * n }), T(dq[1], RAD_I8, { M, n }), T(ds[1], RAD_F32, { M }), + T(dy[1], RAD_BF16, { M, n }) }, + { PI("M", M), PI("n", n), PS("dtype", "bf16") }); + const std::string what = "gelu_mul_quant_i8 M=" + std::to_string(M); + if (rc != RAD_OK) { ok((what + " vs gelu_mul + quant_act_i8").c_str(), false, "rc=" + std::to_string(rc)); continue; } + std::vector y0((size_t)M * n), y1((size_t)M * n); + std::vector q0((size_t)M * n), q1((size_t)M * n); + std::vector s0((size_t)M), s1((size_t)M); + st_memcpy(y0.data(), dy[0], y0.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(y1.data(), dy[1], y1.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(q0.data(), dq[0], q0.size(), hipMemcpyDeviceToHost); + st_memcpy(q1.data(), dq[1], q1.size(), hipMemcpyDeviceToHost); + st_memcpy(s0.data(), ds[0], s0.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(s1.data(), ds[1], s1.size() * 4, hipMemcpyDeviceToHost); + int ny = 0, nq = 0, ns = 0, nz = 0; + for (size_t i = 0; i < y0.size(); ++i) ny += y0[i] != y1[i]; + for (size_t i = 0; i < q0.size(); ++i) { nq += q0[i] != q1[i]; nz += q1[i] != 0; } + for (size_t i = 0; i < s0.size(); ++i) ns += std::memcmp(&s0[i], &s1[i], 4) != 0; + ok((what + " is byte-identical to gelu_mul + quant_act_i8").c_str(), ny == 0 && nq == 0 && ns == 0 && nz > (int)q1.size() / 2, + "bf16 differs " + std::to_string(ny) + ", codes " + std::to_string(nq) + ", scales " + std::to_string(ns) + + ", nonzero codes " + std::to_string(nz)); + } +} + +/* ---- qkv_norm_rope, against the five ops it replaces ------------------------------------------ + * + * rmsnorm_p (v, or the raw k under v_from_k), rmsnorm over the q heads and over the k heads, then + * rope over q and over k -- kernel by kernel, against the one dispatch. Both of Gemma 4 31B's + * classes at one rank of two: sliding (head_dim 256, 16 q over 8 kv heads, full rotary, separate v) + * and global (512, 16 over 2, the proportional `head` ladder over 128, k == v), at batch heights + * that put the q/k norms at every width r4d_act_threads answers -- including 256 at head_dim 512, + * where a thread of the standalone norm folds two channels. */ +static void qkv_norm_rope_numeric(const Plugin& pl) { + const RadKernelInfo* np = find(pl, "rmsnorm_p_bf16"); + const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); + const RadKernelInfo* rp = find(pl, "rope_bf16"); + const RadKernelInfo* fz = find(pl, "qkv_norm_rope_bf16"); + if (!np || !nrm || !rp || !fz) { ok("qkv_norm_rope vs its five", false, "rows absent"); return; } + struct Cls { int64_t hd, nq, nkv, rot; const char* ladder; double theta; bool vk; }; + for (const Cls& cl : { Cls{ 256, 16, 8, 256, "rotary", 10000.0, false }, + Cls{ 512, 16, 2, 128, "head", 1000000.0, true } }) { + for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)40 }) { + const int64_t QD = cl.nq * cl.hd, KD = cl.nkv * cl.hd; + std::vector hq((size_t)M * QD), hk((size_t)M * KD), hv((size_t)M * KD); + std::vector hqw((size_t)cl.hd), hkw((size_t)cl.hd); + std::vector hp((size_t)M); + for (size_t i = 0; i < hq.size(); ++i) hq[i] = h_to_bf16(0.031f * (float)((i * 37) % 97) - 1.4f); + for (size_t i = 0; i < hk.size(); ++i) hk[i] = h_to_bf16(0.027f * (float)((i * 53) % 89) - 1.1f); + for (size_t i = 0; i < hv.size(); ++i) hv[i] = h_to_bf16(0.023f * (float)((i * 29) % 83) - 0.9f); + for (int64_t c = 0; c < cl.hd; ++c) { + hqw[(size_t)c] = h_to_bf16(0.6f + 0.004f * (float)((c * 19) % 51)); + hkw[(size_t)c] = h_to_bf16(0.5f + 0.005f * (float)((c * 11) % 47)); + } + for (int64_t m = 0; m < M; ++m) hp[(size_t)m] = (int32_t)(1000 + 7 * m); + void* dq[2] = { dalloc(hq.size() * 2), dalloc(hq.size() * 2) }; + void* dk[2] = { dalloc(hk.size() * 2), dalloc(hk.size() * 2) }; + void* dv[2] = { dalloc(hv.size() * 2), dalloc(hv.size() * 2) }; + void* dqw = dalloc(hqw.size() * 2); + void* dkw = dalloc(hkw.size() * 2); + void* dp = dalloc(hp.size() * 4); + if (!dq[1] || !dk[1] || !dv[1] || !dqw || !dkw || !dp) { ok("qkv_norm_rope alloc", false, "hipMalloc failed"); return; } + for (int j = 0; j < 2; ++j) { + st_memcpy(dq[j], hq.data(), hq.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dk[j], hk.data(), hk.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dv[j], hv.data(), hv.size() * 2, hipMemcpyHostToDevice); + } + st_memcpy(dqw, hqw.data(), hqw.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dkw, hkw.data(), hkw.size() * 2, hipMemcpyHostToDevice); + st_memcpy(dp, hp.data(), hp.size() * 4, hipMemcpyHostToDevice); + const double eps = 1e-6, wadd = 0.0; + /* --- the five, in the order the unfused block issues them --- */ + int rc = launch_row(np, { T(cl.vk ? dk[0] : dv[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dv[0], RAD_BF16, { M * cl.nkv, cl.hd }) }, + { PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16") }); + if (rc == RAD_OK) + rc = launch_row(nrm, { T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }), T(dqw, RAD_BF16, { cl.hd }), T(dq[0], RAD_BF16, { M * cl.nq, cl.hd }) }, + { PI("M", M * cl.nq), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); + if (rc == RAD_OK) + rc = launch_row(nrm, { T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dkw, RAD_BF16, { cl.hd }), T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }) }, + { PI("M", M * cl.nkv), PI("n", cl.hd), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }); + for (int j = 0; j < 2 && rc == RAD_OK; ++j) + rc = launch_row(rp, { T(j ? dk[0] : dq[0], RAD_BF16, { M, (j ? cl.nkv : cl.nq) * cl.hd }), T(dp, RAD_I32, { M }) }, + { PI("M", M), PI("head_dim", cl.hd), PI("n_head", j ? cl.nkv : cl.nq), PI("n_head_kv", 0), + PF("theta", cl.theta), PF("scale", 1.0), PS("mode", "neox"), PI("rotary_dim", cl.rot), + PS("ladder", cl.ladder) }); + /* --- the one --- */ + if (rc == RAD_OK) + rc = launch_row(fz, { T(dq[1], RAD_BF16, { M, QD }), T(dk[1], RAD_BF16, { M, KD }), T(dv[1], RAD_BF16, { M, KD }), + T(dp, RAD_I32, { M }), T(dqw, RAD_BF16, { cl.hd }), T(dkw, RAD_BF16, { cl.hd }) }, + { PI("M", M), PI("head_dim", cl.hd), PI("n_head", cl.nq), PI("n_head_kv", cl.nkv), + PF("theta", cl.theta), PF("eps", eps), PF("scale", 1.0), PS("mode", "neox"), + PI("rotary_dim", cl.rot), PS("ladder", cl.ladder), PF("wadd", wadd), + PI("v_from_k", cl.vk ? 1 : 0), PS("dtype", "bf16") }); + const std::string what = std::string("qkv_norm_rope hd=") + std::to_string(cl.hd) + " M=" + std::to_string(M); + if (rc != RAD_OK) { ok((what + " vs its five").c_str(), false, "rc=" + std::to_string(rc)); continue; } + int nd = 0, moved = 0; + for (int t = 0; t < 3; ++t) { + void* const* d = t == 0 ? dq : (t == 1 ? dk : dv); + const size_t n = t == 0 ? hq.size() : hk.size(); + std::vector a(n), b(n); + st_memcpy(a.data(), d[0], n * 2, hipMemcpyDeviceToHost); + st_memcpy(b.data(), d[1], n * 2, hipMemcpyDeviceToHost); + const std::vector& h0 = t == 0 ? hq : (t == 1 ? hk : hv); + for (size_t i = 0; i < n; ++i) { nd += a[i] != b[i]; moved += b[i] != h0[i]; } + } + ok((what + " is byte-identical to rmsnorm_p + rmsnorm x2 + rope x2").c_str(), nd == 0 && moved > 0, + "differs " + std::to_string(nd) + ", changed from the input " + std::to_string(moved)); + } + } +} + +/* ---- rmsnorm_quant_i8, against the chain it replaces ------------------------------------------ + * + * Byte-identical, for the reason the fp8 fusions above give, in all three forms a sandwich-norm + * model issues: the plain norm + quantiser (a first block's entry), the junction without a scalar + * (attention -> feed-forward) and with one (feed-forward -> the next layer). The unfused chain is + * rmsnorm(x; w_post) -> add(residual) -> scale -> rmsnorm(residual; w) -> quant_act_i8, run here + * kernel by kernel. bf16 gains, which is what Gemma's checkpoint stores, and two batch heights so + * both of r4d_act_threads' widths a decode step meets are covered (1024 at M <= 32, 512 above). */ +static void rmsnorm_quant_i8_numeric(const Plugin& pl) { + const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); + const RadKernelInfo* ad = find(pl, "add_bf16"); + const RadKernelInfo* scl = find(pl, "scale_bf16"); + const RadKernelInfo* qz = find(pl, "quant_act_i8"); + const RadKernelInfo* rq = find(pl, "rmsnorm_quant_i8"); + if (!nrm || !ad || !scl || !qz || !rq) { ok("rmsnorm_quant_i8 vs its chain", false, "rows absent"); return; } + for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)40 }) { + const int64_t K = 5376; /* Gemma 4 31B's hidden width: 336 sixteen-byte k steps, not a power of two */ + std::vector hx((size_t)M * K), hr((size_t)M * K), hw((size_t)K), hp((size_t)K); + for (int64_t r = 0; r < M; ++r) + for (int64_t c = 0; c < K; ++c) { + const float m = std::ldexp(1.0f, (int)((c / 384) % 6) - 3); + const float v = m * (0.037f * (float)((r * 29 + c * 13) % 71) - 1.3f); + hx[(size_t)r * K + c] = h_to_bf16(c == (r * 37) % K ? v * 19.0f : v); + hr[(size_t)r * K + c] = h_to_bf16(0.019f * (float)((r * 13 + c * 29) % 67) - 0.6f); + } + for (int64_t c = 0; c < K; ++c) { + hw[(size_t)c] = h_to_bf16(0.004f * (float)((c * 19) % 51) - 0.1f); + hp[(size_t)c] = h_to_bf16(0.9f + 0.003f * (float)((c * 7) % 41)); + } + const uint16_t hs = h_to_bf16(0.373f); + void* d_x = dalloc((size_t)M * K * 2); + void* d_w = dalloc((size_t)K * 2); + void* d_p = dalloc((size_t)K * 2); + void* d_sc = dalloc(4); + void* d_t = dalloc((size_t)M * K * 2); + void* d_r[2] = { dalloc((size_t)M * K * 2), dalloc((size_t)M * K * 2) }; + void* d_y[2] = { dalloc((size_t)M * K * 2), dalloc((size_t)M * K * 2) }; + void* d_q[2] = { dalloc((size_t)M * K), dalloc((size_t)M * K) }; + void* d_s[2] = { dalloc((size_t)M * 4), dalloc((size_t)M * 4) }; + if (!d_x || !d_w || !d_p || !d_sc || !d_t || !d_r[1] || !d_y[1] || !d_q[1] || !d_s[1]) { + ok("rmsnorm_quant_i8 alloc", false, "hipMalloc failed"); + return; + } + st_memcpy(d_x, hx.data(), hx.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_w, hw.data(), hw.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_p, hp.data(), hp.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_sc, &hs, 2, hipMemcpyHostToDevice); + const double eps = 1e-6, wadd = 0.0; + const std::vector pn = { PI("M", M), PI("n", K), PF("eps", eps), PS("dtype", "bf16"), PF("wadd", wadd) }; + const std::vector pe = { PI("M", M), PI("n", K), PS("dtype", "bf16") }; + const std::vector pq = { PI("M", M), PI("n", K), PI("group", K), PS("dtype", "bf16") }; + + auto compare = [&](const std::string& what, bool res) { + std::vector y0((size_t)M * K), y1((size_t)M * K), r0((size_t)M * K), r1((size_t)M * K); + std::vector q0((size_t)M * K), q1((size_t)M * K); + std::vector s0((size_t)M), s1((size_t)M); + st_memcpy(y0.data(), d_y[0], y0.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(y1.data(), d_y[1], y1.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(q0.data(), d_q[0], q0.size(), hipMemcpyDeviceToHost); + st_memcpy(q1.data(), d_q[1], q1.size(), hipMemcpyDeviceToHost); + st_memcpy(s0.data(), d_s[0], s0.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(s1.data(), d_s[1], s1.size() * 4, hipMemcpyDeviceToHost); + st_memcpy(r0.data(), d_r[0], r0.size() * 2, hipMemcpyDeviceToHost); + st_memcpy(r1.data(), d_r[1], r1.size() * 2, hipMemcpyDeviceToHost); + int ny = 0, nq = 0, ns = 0, nr = 0, nz = 0; + for (size_t i = 0; i < y0.size(); ++i) ny += y0[i] != y1[i]; + for (size_t i = 0; i < q0.size(); ++i) nq += q0[i] != q1[i]; + for (size_t i = 0; i < s0.size(); ++i) ns += std::memcmp(&s0[i], &s1[i], 4) != 0; + if (res) for (size_t i = 0; i < r0.size(); ++i) nr += r0[i] != r1[i]; + for (size_t i = 0; i < q1.size(); ++i) nz += q1[i] != 0; + ok((what + " M=" + std::to_string(M)).c_str(), ny == 0 && nq == 0 && ns == 0 && nr == 0 && nz > (int)q1.size() / 2, + "bf16 differs " + std::to_string(ny) + ", codes " + std::to_string(nq) + ", scales " + + std::to_string(ns) + ", residual " + std::to_string(nr) + ", nonzero codes " + std::to_string(nz)); + }; + auto norm_quant = [&](void* src) { /* rmsnorm(src; w) -> quant_act_i8, into slot 0 */ + int rc = launch_row(nrm, { T(src, RAD_BF16, { M, K }), T(d_w, RAD_BF16, { K }), T(d_y[0], RAD_BF16, { M, K }) }, pn); + if (rc == RAD_OK) + rc = launch_row(qz, { T(d_y[0], RAD_BF16, { M, K }), T(d_q[0], RAD_I8, { M, K }), + T(d_s[0], RAD_F32, { M }), T(nullptr, RAD_F32, {}) }, pq); + return rc; + }; + + /* --- the plain form --- */ + int rc = norm_quant(d_x); + if (rc == RAD_OK) + rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }), T(nullptr, RAD_BF16, {}), T(d_w, RAD_BF16, { K }), + T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M }), T(d_y[1], RAD_BF16, { M, K }), + T(nullptr, RAD_BF16, {}), T(nullptr, RAD_BF16, {}) }, pn); + if (rc != RAD_OK) ok("rmsnorm_quant_i8 vs rmsnorm + quant_act_i8", false, "rc=" + std::to_string(rc)); + else compare("rmsnorm_quant_i8 is byte-identical to rmsnorm + quant_act_i8", false); + + /* --- the junction, without and with the scalar --- */ + for (const bool with_sc : { false, true }) { + st_memcpy(d_r[0], hr.data(), hr.size() * 2, hipMemcpyHostToDevice); + st_memcpy(d_r[1], hr.data(), hr.size() * 2, hipMemcpyHostToDevice); + rc = launch_row(nrm, { T(d_x, RAD_BF16, { M, K }), T(d_p, RAD_BF16, { K }), T(d_t, RAD_BF16, { M, K }) }, pn); + if (rc == RAD_OK) + rc = launch_row(ad, { T(d_r[0], RAD_BF16, { M, K }), T(d_t, RAD_BF16, { M, K }), T(d_r[0], RAD_BF16, { M, K }) }, pe); + if (rc == RAD_OK && with_sc) + rc = launch_row(scl, { T(d_r[0], RAD_BF16, { M, K }), T(d_sc, RAD_BF16, { 1 }), T(d_r[0], RAD_BF16, { M, K }) }, pe); + if (rc == RAD_OK) rc = norm_quant(d_r[0]); + if (rc == RAD_OK) + rc = launch_row(rq, { T(d_x, RAD_BF16, { M, K }), T(d_r[1], RAD_BF16, { M, K }), T(d_w, RAD_BF16, { K }), + T(d_q[1], RAD_I8, { M, K }), T(d_s[1], RAD_F32, { M }), T(d_y[1], RAD_BF16, { M, K }), + T(d_p, RAD_BF16, { K }), + with_sc ? T(d_sc, RAD_BF16, { 1 }) : T(nullptr, RAD_BF16, {}) }, pn); + const std::string what = with_sc ? "rmsnorm_quant_i8 junction with scalar" : "rmsnorm_quant_i8 junction"; + if (rc != RAD_OK) ok((what + " vs rmsnorm + add + scale + rmsnorm + quant_act_i8").c_str(), false, "rc=" + std::to_string(rc)); + else compare(what + " is byte-identical to its chain", true); + } + } +} + /* THE fp8 lm_head, end to end through its OWN hooks. * * The arrangement is the odd one in this library -- E4M3 codes with the row's own bf16 scales in @@ -11261,6 +12059,41 @@ static void device_phase(const Plugin& pl) { attn_case(pl, "attn_decode_h128_gqa4_bf16kv", 128, 4, 1, "bf16", 0); attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 32, "bf16", 1); attn_case(pl, "attn_prefill_h64_gqa4_bf16kv", 64, 4, 1, "bf16", 1); + /* Gemma 4 dense sliding window: decode only, so the window is threaded through -- 1024 is the + * model's window. It exercises the windowed split law and the WIN=1 template the way the + * drafter leg does; max_ctx here is smaller than the window, so the span clamps to the context. */ + attn_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 0, 1024); + attn_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 0, 1024); + /* Gemma 4 dense sliding window: the PREFILL leg, the band above q_len 32 that a trunk layer + * needs on the device (libref is an opt-in fallback the engine refuses by default, spec §17). + * The windowed query-tiled prefill kernel; window 1024 is the model's, threaded through to + * instantiate WIN=1 the way the decode leg does. max_ctx here (64) is smaller than the window, so the span clamps to the + * context and the launch is the full-attention form. */ + attn_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 32, "fp8_e4m3", 1, 1024); + attn_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 32, "bf16", 1, 1024); + /* Gemma 4 dense global: head_dim 512, full attention. Launch-only cases at prefill q_len 32 and + * decode 1, mirroring the gqa6 leg's pair; the numeric check of the same rows follows. */ + attn_case(pl, "attn_prefill_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 1); + attn_case(pl, "attn_prefill_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 1); + attn_case(pl, "attn_decode_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0); + attn_case(pl, "attn_decode_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0); + /* The numeric attention check: the same rows, but with random data and a comparison + * against the inline oracle, plus a negative control. h512 is prefill + decode; h256/gqa2 is + * decode-only (the windowed sliding-window leg, window 1024). */ + attn_numeric_case(pl, "attn_prefill_h512_gqa8_fp8kv", 512, 8, 32, "fp8_e4m3", 0); + attn_numeric_case(pl, "attn_prefill_h512_gqa8_bf16kv", 512, 8, 32, "bf16", 0); + attn_numeric_case(pl, "attn_decode_h512_gqa8_fp8kv", 512, 8, 1, "fp8_e4m3", 0); + attn_numeric_case(pl, "attn_decode_h512_gqa8_bf16kv", 512, 8, 1, "bf16", 0); + /* The h256/gqa2 PREFILL numeric check. Unlike the decode leg (ctx 64 < window, so the window + * clamps to the context), ctx here is 2048 > window 1024, so the window actually bites: for + * query row 0, pos = 2048-64 = 1984 and the visible keys are [961..1984], so the kernel's + * wlo0 = 961 and tstart = 961/48 = 20 -- exercising both the window mask (keys below 961 are + * masked) and the below-window tile skip (tiles 0..19 are never walked). The oracle's + * visible() is the same bound, so the two agree. */ + attn_numeric_case(pl, "attn_prefill_h256_gqa2_fp8kv", 256, 2, 64, "fp8_e4m3", 1024, 2048); + attn_numeric_case(pl, "attn_prefill_h256_gqa2_bf16kv", 256, 2, 64, "bf16", 1024, 2048); + attn_numeric_case(pl, "attn_decode_h256_gqa2_fp8kv", 256, 2, 1, "fp8_e4m3", 1024); + attn_numeric_case(pl, "attn_decode_h256_gqa2_bf16kv", 256, 2, 1, "bf16", 1024); attn_gq_fold_case(pl, 3, false); attn_gq_fold_case(pl, 24, false); attn_gq_fold_case(pl, 3, true); @@ -12544,6 +13377,31 @@ static void device_phase(const Plugin& pl) { qsa_block_key_yarn_case(pl); } + if (sel("logit_softcap_bf16")) { + if (!g_case) std::printf("\nthe final-logit softcap, against the formula it implements\n"); + logit_softcap_case(pl); + } + + if (sel("rmsnorm_p_bf16")) { + if (!g_case) std::printf("\nthe weightless RMS norm, against the formula it implements\n"); + rmsnorm_p_case(pl); + } + + if (sel("gelu_mul_bf16")) { + if (!g_case) std::printf("\nthe gelu-gated product, against the formula it implements\n"); + gelu_mul_case(pl); + } + + if (sel("scale_bf16")) { + if (!g_case) std::printf("\nthe per-tensor scalar scale, against the multiply it implements\n"); + scale_case(pl); + } + + if (sel("rope_bf16")) { + if (!g_case) std::printf("\nthe rotary ladder, against an f32 mirror of the kernel at each width\n"); + rope_ladder_case(pl); + } + if (sel("moe_gemm_w4a8")) { if (!g_case) std::printf("\nthe 4-bit grouped MoE GEMM, against a host decode\n"); /* One geometry; a gate/up pair whose odd experts are half as wide; a down projection @@ -12763,6 +13621,18 @@ static void device_phase(const Plugin& pl) { if (!g_case) std::printf("\nthe fp8 fusions, against the pair each one replaces\n"); fused_quant_fp8_numeric(pl); } + if (sel("gelu_mul_quant_i8")) { + if (!g_case) std::printf("\ngelu_mul_quant_i8, against the pair it replaces\n"); + gelu_mul_quant_i8_numeric(pl); + } + if (sel("qkv_norm_rope_bf16")) { + if (!g_case) std::printf("\nqkv_norm_rope, against the five ops it replaces\n"); + qkv_norm_rope_numeric(pl); + } + if (sel("rmsnorm_quant_i8")) { + if (!g_case) std::printf("\nrmsnorm_quant_i8, against the chain it replaces\n"); + rmsnorm_quant_i8_numeric(pl); + } /* The MTP head's fc is K=10240; the DFlash2 drafter's is 25600, the largest K any shape in * the tree asks these kernels for. @@ -12843,6 +13713,7 @@ static void device_phase(const Plugin& pl) { * at every one of the 128 sites, and the generated text is compared byte for byte against a * build that issues the pair instead. */ skip_pair("ar_rmsnorm_quant_fp8", "two-rank fusion: needs a peer rank"); + skip_pair("ar_rmsnorm_quant_i8", "two-rank fusion: needs a peer rank"); dfree_all(); } diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 6507cd34..9f5394d2 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -1272,6 +1272,17 @@ extern "C" int r4d_shape_scale_rows(const RadParam* p, int n_p, int operand, Rad R4D_PICK(l); } +/* The per-tensor scalar: one [1] weight broadcast over the whole [M, n] extent. `s` is the middle + * operand; its extent is 1, not M (that would be scale_rows) and not M*n (that would be a + * per-element mask). The scalar's dtype is the stream's, so a bf16 or f32 `s` both read. */ +extern "C" int r4d_shape_scale(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = pi(p, n_p, "M"), n = pi(p, n_p, "n"); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, n), opd(D, 1), opd(D, M, n) }; + R4D_PICK(l); +} + extern "C" int r4d_shape_router_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = pi(p, n_p, "M"); const int64_t ne = pi(p, n_p, "n_expert"); diff --git a/libref/ref_attn.cpp b/libref/ref_attn.cpp index 1d7ec165..1d59a547 100644 --- a/libref/ref_attn.cpp +++ b/libref/ref_attn.cpp @@ -395,8 +395,11 @@ struct RopeFreq { }; /* Which component and inverse frequency each of the rot/2 frequencies uses. */ -static int rope_freqs(int mode, int64_t rot, float theta, const int64_t* sec, int n_sec, - RopeFreq* f) { +/* `den` is the width the BASE ladder is measured in: `rot` for a `rotary` ladder (a partial rotary + * is a complete rotation of its own width) and `head_dim` for `head`, the proportional variant. The + * loop count and the NeoX/GPT-J pairing still come from `rot`; `axial` overrides `inv` below. */ +static int rope_freqs(int mode, int64_t rot, int64_t den, float theta, const int64_t* sec, + int n_sec, RopeFreq* f) { const int64_t half = rot / 2; if (half > REF_HD_MAX / 2) return RAD_E_UNSUPPORTED; int64_t start[8] = {}, total = 0; @@ -404,7 +407,7 @@ static int rope_freqs(int mode, int64_t rot, float theta, const int64_t* sec, in if ((mode == ROPE_MROPE || mode == ROPE_AXIAL) && n_sec > 0 && total != half) return RAD_E_SHAPE; for (int64_t i = 0; i < half; ++i) { int c = 0; - float inv = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot); + float inv = 1.0f / std::pow(theta, (float)(2 * i) / (float)den); if (n_sec > 0 && (mode == ROPE_MROPE || mode == ROPE_AXIAL)) { while (c + 1 < n_sec && i >= start[c + 1]) ++c; if (mode == ROPE_AXIAL) { @@ -450,6 +453,21 @@ static int rope_sections(const RadArgs* a, int64_t* sec) { return n; } +/* `ladder` names the width the base frequency ladder is measured in -- see rope_freqs. Absent and + * `rotary` divide by `rot` (every existing model); `head` divides by `head_dim`, which it needs. An + * unknown value is a schema error, not a silent default: a mistyped ladder is a silent wrong angle. */ +static int rope_ladder(const RadArgs* a, int64_t rot, int64_t head_dim, int64_t* den) { + const char* lad = p_str(a, "ladder", nullptr); + if (!lad) { *den = rot; return RAD_OK; } + if (!std::strcmp(lad, "rotary")) { *den = rot; return RAD_OK; } + if (!std::strcmp(lad, "head")) { + if (head_dim <= 0) return RAD_E_SHAPE; + *den = head_dim; + return RAD_OK; + } + return RAD_E_UNSUPPORTED; +} + } /* namespace */ int ref_rope(const RadArgs* a, RadStream) { @@ -466,6 +484,8 @@ int ref_rope(const RadArgs* a, RadStream) { if (mode < 0) return RAD_E_UNSUPPORTED; int64_t rot = p_int(a, "rotary_dim", head_dim); if (head_dim <= 0 || n_head <= 0 || rot <= 0 || rot > head_dim || (rot & 1)) return RAD_E_SHAPE; + int64_t den; + RAD_REF_TRY(rope_ladder(a, rot, head_dim, &den)); int64_t sec[8] = {}; const int n_sec = rope_sections(a, sec); @@ -479,14 +499,21 @@ int ref_rope(const RadArgs* a, RadStream) { const int64_t need = mode == ROPE_IMROPE ? 3 : n_sec; if (n_comp < need || n_comp > 8) return RAD_E_SHAPE; } + /* THE PROPORTIONAL LADDER (`head`) is HF's: the rotation spans the whole head -- pair i is + * (i, i + head_dim/2) -- and every frequency past rotary_dim/2 is zero, so those pairs turn by + * nothing. A rotary of rotary_dim's own width, pairing (i, i + rot/2), turns other channels. */ + const int64_t nfreq = rot / 2; + if (den == head_dim && rot < head_dim && !multi && mode == ROPE_NEOX) rot = head_dim; RopeFreq f; - RAD_REF_TRY(rope_freqs(mode, rot, theta, sec, multi ? n_sec : 0, &f)); + RAD_REF_TRY(rope_freqs(mode, rot, den, theta, sec, multi ? n_sec : 0, &f)); const RadYarn yarn = rad_yarn_args(a); if (!rad_yarn_valid(yarn)) return RAD_E_INVAL; if (yarn.factor != 0.0f) { if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED; for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i); } + for (int64_t i = nfreq; i < rot / 2; ++i) f.inv[i] = 0.0f; + const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim; if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE; @@ -582,7 +609,9 @@ int ref_qk_norm_rope(const RadArgs* a, RadStream) { const int64_t rs = qkv->rank >= 2 ? qkv->stride[qkv->rank - 2] : stride_row; const int64_t ds = laststride(qkv); RopeFreq f; - if (!blocks) RAD_REF_TRY(rope_freqs(mode, rot, theta, nullptr, 0, &f)); + /* No `ladder` on this row yet: the fused norm+rope measures by `rot`, as it always has. */ + RAD_REF_TRY(rope_freqs(mode, rot, rot, theta, nullptr, 0, &f)); + #pragma omp parallel for schedule(static) for (int64_t m = 0; m < M; ++m) { @@ -746,10 +775,13 @@ int ref_attn_local_rel(const RadArgs* a, RadStream) { int ref_rope_table(const RadArgs* a, RadStream) { if (!have(a, 2)) return RAD_E_INVAL; const RadTensor *pos = &a->t[0], *cs = &a->t[1]; - const int64_t rot = p_int(a, "rot", 0); + const int64_t rot = p_int(a, "rot", 0); + const int64_t head_dim = p_int(a, "head_dim", 0); const float theta = p_f32(a, "theta", 10000.0f); const float rscale = p_f32(a, "scale", 1.0f); if (rot < 2 || (rot & 1)) return RAD_E_SHAPE; + int64_t den; + RAD_REF_TRY(rope_ladder(a, rot, head_dim, &den)); const int64_t M = numel(pos); if (M <= 0 || numel(cs) % rot) return RAD_E_SHAPE; const int64_t rows = numel(cs) / rot; @@ -763,7 +795,7 @@ int ref_rope_table(const RadArgs* a, RadStream) { if (pp < 0 || pp >= rows) continue; const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f); for (int64_t i = 0; i < half; ++i) { - const float inv = yarn.frequency(1.0f / std::pow(theta, (float)(2 * i) / (float)rot), (int)i); + const float inv = yarn.frequency(1.0f / std::pow(theta, (float)(2 * i) / (float)den), (int)i); const float ang = p * inv; stt(cs, offlin(cs, pp * rot + i), std::cos(ang) * yarn.magnitude); stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang) * yarn.magnitude); @@ -820,7 +852,7 @@ int ref_qsa_block_key(const RadArgs* a, RadStream) { if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f))) return RAD_E_INVAL; RopeFreq f; - RAD_REF_TRY(rope_freqs(mc ? mode : ROPE_NEOX, rot, theta, sec, mc ? n_sec : 0, &f)); + RAD_REF_TRY(rope_freqs(mc ? mode : ROPE_NEOX, rot, rot, theta, sec, mc ? n_sec : 0, &f)); for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i); #pragma omp parallel for schedule(static) diff --git a/libref/ref_common.h b/libref/ref_common.h index 1885b7dd..4d80ea97 100644 --- a/libref/ref_common.h +++ b/libref/ref_common.h @@ -418,6 +418,17 @@ static inline float act_gelu(float x) { return 0.5f * x * (1.0f + std::erf(x * 0.70710678118654752f)); } +/* The tanh approximation (PyTorch's gelu_tanh / gemma's gelu_pytorch_tanh) -- the form gated + * feed-forwards are trained with. The constants are the standard fit and are the same two the + * gemm_nt_bias "gelu_tanh" epilogue uses (ref_gemm.cpp), which is a GEMM-local copy of this same + * formula; both compute the identical function, so a GELU-gated FFN and a tanh-gelu epilogue agree + * to the last bit. Kept here rather than `#include`d into ref_gemm.cpp so the elementwise header + * stays self-contained. */ +static inline float act_gelu_tanh(float x) { + const float k0 = 0.7978845608028654f, k1 = 0.044715f; + return 0.5f * x * (1.0f + std::tanh(k0 * (x + k1 * x * x * x))); +} + /* softplus in the two-sided form, with the large-x cutoff FLA and libr4d both use: above the * threshold log1p(e^x) IS x to every bit f32 holds, and evaluating it costs an overflow. */ static inline float act_softplus(float x, float thr) { diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index 4b5d2c3c..0a5e9d41 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -57,6 +57,37 @@ int ref_rmsnorm(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ rmsnorm_p */ +/* y = x * rsqrt(mean(x^2) + eps) -- the SAME normalisation as rmsnorm with NO gain at all. It is + * its own op rather than a zeroed gain on rmsnorm because the gain is a real, weightless thing: + * Gemma's attention normalises the VALUE with a bare RMS (llama.cpp's ggml_rms_norm(V, eps), no + * tensor) while normalising the KEY with the k_norm gain, and there is no checkpoint plane to feed + * a `wadd`/`w` through for the value -- so an rmsnorm call would need a phantom all-zero weight to + * express it, which is a name map to a tensor that does not exist. The mean is accumulated in f32 + * in ascending index order, exactly as rmsnorm does, so the two agree bit-for-bit where rmsnorm's + * gain happens to be one. */ +int ref_rmsnorm_p(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", 0); + const float eps = p_f32(a, "eps", 1e-6f); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(x, n); + if (rows <= 0 || numel(y) < rows * n) return RAD_E_SHAPE; + + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(x, r, n), yb = rowoff(y, r, n); + const int64_t xs = laststride(x), ys = laststride(y); + float ss = 0.0f; + for (int64_t i = 0; i < n; ++i) { float v = ldt(x, xb + i * xs); ss += v * v; } + const float s = 1.0f / std::sqrt(ss / (float)n + eps); + for (int64_t i = 0; i < n; ++i) + stt(y, yb + i * ys, ldt(x, xb + i * xs) * s); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ rmsnorm_add */ /* residual_out = x + residual; y = rmsnorm(residual_out) * (w + w_add) * @@ -657,6 +688,32 @@ int ref_rel_sinusoid(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ gelu_mul */ +/* y[.., i] = gelu_tanh(gate_up[.., i]) * gate_up[.., n + i] -- the tanh GELU, and the gate is the + * FIRST half, for the same order-locking reason as silu_mul. This is Gemma's gated FFN + * (down(gelu_tanh(gate(x)) * up(x)), activation gelu_pytorch_tanh in the checkpoint). It is not + * `gemm_nt`'s "gelu_tanh" EPLOGUE, which applies the activation to a whole GEMM's output and has no + * gate to multiply; gating needs the product of two halves of one fused plane, which is silu_mul's + * shape. The exact-erf form is the unary `gelu` op; a GELU-gated feed-forward in this family is + * trained with the tanh approximation, so this op is the tanh one on purpose and says so. */ +int ref_gelu_mul(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *gu = &a->t[0], *y = &a->t[1]; + const int64_t n = p_int(a, "n", numel(y)); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(y, n); + if (rows <= 0 || numel(gu) < rows * 2 * n) return RAD_E_SHAPE; + + #pragma omp parallel for schedule(static) + for (int64_t r = 0; r < rows; ++r) { + const int64_t gb = rowoff(gu, r, 2 * n), yb = rowoff(y, r, n); + const int64_t gs = laststride(gu), ys = laststride(y); + for (int64_t i = 0; i < n; ++i) + stt(y, yb + i * ys, act_gelu_tanh(ldt(gu, gb + i * gs)) * ldt(gu, gb + (n + i) * gs)); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ gelu / silu */ static int unary(const RadArgs* a, int which) { if (!have(a, 2)) return RAD_E_INVAL; @@ -700,6 +757,52 @@ int ref_fill(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ logit_softcap */ +/* y = cap * tanh(x / cap), Gemma's final-logit softcap: the logits_gemm's output is a nearly + * unbounded row and the sampler wants it bounded, so this is issued against the LOGITS, not the + * hidden stream. Its own op for the same reason sigmoid is -- the selector has to be able to name + * it -- and `cap` is a parameter of the call, which the which-switch above cannot carry. */ +int ref_logit_softcap(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + const int64_t nel = numel(y); + if (nel <= 0 || numel(x) < nel) return RAD_E_SHAPE; + const float cap = p_f32(a, "cap", 30.0f); + if (!(cap > 0.0f)) return RAD_E_INVAL; + + #pragma omp parallel for schedule(static) + for (int64_t i = 0; i < nel; ++i) { + const float v = ldt(x, offlin(x, i)); + stt(y, offlin(y, i), cap * std::tanhf(v / cap)); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ scale */ +/* y = x * s, where s is a [1] weight broadcast over every element of x. + * + * Gemma 4's per-layer scalar: the residual stream is scaled by a learned [1] value at the end of + * every layer (llama.cpp `out_scale`, `cur = cur * out_scale`). It is NOT `mul`, which broadcasts + * a single ROW down the rows (a bias's shape) -- this broadcasts a single SCALAR over the whole + * [M, n] tensor. `scale_rows` is the per-ROW version (one scalar a row); this is the per-TENSOR + * version (one scalar for all rows). Giving `mul` both rules would make them ambiguous exactly + * when rows == 1, so a silent choice between two broadcasts is how a shape bug becomes a + * plausible number -- the same reason `scale_rows` is its own op. + * + * `s` is a weight (a [1] tensor in the checkpoint), not a parameter: it varies per layer, so it + * is a declared weight the name map points at, not a call constant. Read once, outside the loop: + * a per-element reload of a [1] tensor is the same value every time and costs a load per element. */ +int ref_scale(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *s = &a->t[1], *y = &a->t[2]; + const int64_t nel = numel(y); + if (nel <= 0 || numel(x) < nel || numel(s) < 1) return RAD_E_SHAPE; + const float sv = ldt(s, 0); + #pragma omp parallel for schedule(static) + for (int64_t i = 0; i < nel; ++i) + stt(y, offlin(y, i), ldt(x, offlin(x, i)) * sv); + return RAD_OK; +} /* ------------------------------------------------------------------ gather_rows */ /* y[i, :] = x[idx[i], :]. The op that turns "correct" into "affordable": without it a plugin runs * the lm_head GEMM over every token of a prefill chunk when the sampler wants one row per diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 8e5398d3..0fc2066b 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -63,6 +63,7 @@ extern "C" { /* ---- elementwise and norms */ int ref_rmsnorm (const RadArgs*, RadStream); +int ref_rmsnorm_p (const RadArgs*, RadStream); int ref_rmsnorm_add (const RadArgs*, RadStream); int ref_hc_enter (const RadArgs*, RadStream); int ref_hc_read (const RadArgs*, RadStream); @@ -74,6 +75,7 @@ int ref_grid_embed_aa (const RadArgs*, RadStream); int ref_add (const RadArgs*, RadStream); int ref_mul (const RadArgs*, RadStream); int ref_silu_mul (const RadArgs*, RadStream); +int ref_gelu_mul (const RadArgs*, RadStream); int ref_act_mul (const RadArgs*, RadStream); int ref_mul_weight (const RadArgs*, RadStream); int ref_seg_mean (const RadArgs*, RadStream); @@ -87,6 +89,8 @@ int ref_attn_local_rel (const RadArgs*, RadStream); int ref_gelu (const RadArgs*, RadStream); int ref_silu (const RadArgs*, RadStream); int ref_sigmoid (const RadArgs*, RadStream); +int ref_logit_softcap (const RadArgs*, RadStream); +int ref_scale (const RadArgs*, RadStream); int ref_fill (const RadArgs*, RadStream); int ref_gather_rows (const RadArgs*, RadStream); int ref_scatter_rows (const RadArgs*, RadStream); @@ -194,6 +198,7 @@ int ref_sample_logprobs (const RadArgs*, RadStream); int fn##_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) REF_SHAPE_FN(ref_rmsnorm); +REF_SHAPE_FN(ref_rmsnorm_p); REF_SHAPE_FN(ref_rmsnorm_add); REF_SHAPE_FN(ref_hc_enter); REF_SHAPE_FN(ref_hc_read); @@ -205,6 +210,7 @@ REF_SHAPE_FN(ref_grid_embed_aa); REF_SHAPE_FN(ref_add); REF_SHAPE_FN(ref_mul); REF_SHAPE_FN(ref_silu_mul); +REF_SHAPE_FN(ref_gelu_mul); REF_SHAPE_FN(ref_act_mul); REF_SHAPE_FN(ref_mul_weight); REF_SHAPE_FN(ref_seg_mean); @@ -218,6 +224,8 @@ REF_SHAPE_FN(ref_attn_local_rel); REF_SHAPE_FN(ref_gelu); REF_SHAPE_FN(ref_silu); REF_SHAPE_FN(ref_sigmoid); +REF_SHAPE_FN(ref_logit_softcap); +REF_SHAPE_FN(ref_scale); REF_SHAPE_FN(ref_fill); REF_SHAPE_FN(ref_gather_rows); REF_SHAPE_FN(ref_scatter_rows); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index cafc9524..42dd25c3 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -155,6 +155,9 @@ static const RadParamSpec pMnD[] = { P_INT("M"), P_INT("n"), P_STR("dtype") }; /* `scalar` 1 says `w` is one element rather than one row: a kernel reads that off the operand, and * the parameter is what lets a shape description say which of the two geometries it is. */ static const RadParamSpec pMulWeight[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_INTO("scalar") }; +/* `cap` required and not optional: a softcap without a cap is a different op, and the one model in + * scope whose graph issues it (Gemma 4) has a value for it. */ +static const RadParamSpec pMnCap[] = { P_INT("M"), P_INT("n"), P_F64("cap"), P_STR("dtype") }; static const RadOperandSpec oBinary[] = { OPD("a"), OPD("b"), OUT("y") }; static const RadOperandSpec oGateUp[] = { OPD("gate_up"), OUT("y") }; static const RadOperandSpec oMulWeight[] = { OPD("x"), WGT("w"), OUT("y") }; @@ -190,6 +193,7 @@ static const RadOperandSpec oAttnLocalRel[] = { OPD("q"), OPD("k"), OPD("v"), OP /* `fill` has no input: `value` is the whole of what it writes. */ static const RadParamSpec pFill[] = { P_INT("M"), P_INT("n"), P_STR("dtype"), P_F64O("value") }; static const RadOperandSpec oFill[] = { OUT("y") }; +static const RadOperandSpec oScale[] = { OPD("x"), WGT("s"), OUT("y") }; static const RadOperandSpec oGather[] = { OPD("x"), OPD("idx"), OUT("y") }; static const RadOperandSpec oScatterRows[] = { OPD("v"), OPD("idx"), INOUT("x") }; @@ -323,7 +327,8 @@ static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_he P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"), P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"), P_F64O("yarn_factor"), P_F64O("yarn_low"), - P_F64O("yarn_high"), P_F64O("yarn_magnitude") }; + P_F64O("yarn_high"), P_F64O("yarn_magnitude"), + P_STRO("ladder") }; static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") }; /* The cos/sin plane a fused prologue reads instead of theta: written at each position's OWN row @@ -332,7 +337,8 @@ static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") }; static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"), P_F64("scale"), P_STR("dtype"), P_F64O("yarn_factor"), P_F64O("yarn_low"), - P_F64O("yarn_high"), P_F64O("yarn_magnitude") }; + P_F64O("yarn_high"), P_F64O("yarn_magnitude"), + P_INTO("head_dim"), P_STRO("ladder") }; static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") }; /* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio` @@ -628,6 +634,11 @@ static const RadOpSchema kSchemas[] = { "Spelled `wadd` and not `w_add` because that is what libr4d's fused norms call it and one " "vocabulary cannot have two spellings of one parameter. `mult` (default 1) scales the row " "before its one rounding." }, +{ "rmsnorm_p", ARR(pLayernorm), ARR(oUnary), + "y = x * rsqrt(mean(x^2) + eps); an rmsnorm with NO gain tensor at all. wadd is 1 so the result " + "is a plain normalisation. Gemma's attention normalises the value with a bare RMS (a weightless " + "ggml_rms_norm) and the key with the k_norm gain in the same layer, which one op with a required " + "gain cannot express." }, { "rmsnorm_add", ARR(pRmsnormAdd), ARR(oRmsnormAdd), "residual_out = x + residual, then y = rmsnorm(residual_out) * w. The variance is taken from " "the unrounded f32 sum; the multiply reads residual_out back AFTER it has been narrowed, which " @@ -704,6 +715,10 @@ static const RadOpSchema kSchemas[] = { { "silu_mul", ARR(pMnD), ARR(oGateUp), "y[i] = silu(gate_up[i]) * gate_up[n + i]. The GATE IS THE FIRST HALF, which is the order " "rad-convert fuses gate and up into one weight in." }, +{ "gelu_mul", ARR(pMnD), ARR(oGateUp), + "y[i] = gelu_tanh(gate_up[i]) * gate_up[n + i], the tanh approximation (gemma's " + "gelu_pytorch_tanh), and the GATE IS THE FIRST HALF as in silu_mul. Its own op, not gelu, because " + "gated feed-forwards are trained with the tanh form and the unary gelu is the exact erf one." }, { "gelu", ARR(pMnD), ARR(oUnary), "y = 0.5x(1 + erf(x/sqrt(2))). The exact erf form, not the tanh approximation." }, { "silu", ARR(pMnD), ARR(oUnary), "y = x * sigmoid(x)." }, @@ -712,6 +727,10 @@ static const RadOpSchema kSchemas[] = { "y = value, every element of an [M, n] extent (default 0), rounded once to y's dtype. The op a " "rank issues where it computes nothing and a reader downstream -- an all-reduce, a residual -- " "still expects a defined buffer." }, +{ "logit_softcap", ARR(pMnCap), ARR(oUnary), "y = cap * tanh(x / cap); the final-logit softcap." }, +{ "scale", ARR(pMnD), ARR(oScale), + "y = x * s, s a [1] weight broadcast over every element; the per-tensor scalar (per-layer scalar, " + "`mul` broadcasts a row, `scale_rows` a column-per-row)." }, { "ple_gate", ARR(pPleGate), ARR(oPleGate), "Per-Layer Embedding's gate. K = grouped_rmsnorm(k) * (w_key + wadd) and Q likewise over `q`, " "one rsqrt per `n`-wide stream and one gain across all hc*n; s[c] = sum_d K[c][d]*Q[c][d] / " @@ -1095,6 +1114,8 @@ static const RadOpSchema kSchemas[] = { static const RadKernelInfo kKernels[] = { SIMPLE("ref_rmsnorm", "rmsnorm", "norm", "root-mean-square norm with a gain", DT_FLOAT, ref_rmsnorm), +SIMPLE("ref_rmsnorm_p", "rmsnorm_p", "norm", "weightless RMS norm (no gain, plain x/rms)", DT_FLOAT, + ref_rmsnorm_p), SIMPLE("ref_rmsnorm_add", "rmsnorm_add", "norm", "residual add then RMS norm", DT_FLOAT, ref_rmsnorm_add), SIMPLE("ref_hc_enter", "hc_enter", "norm", "gated residual entry: hc copies of x", DT_FLOAT, @@ -1116,7 +1137,7 @@ SIMPLE("ref_grid_embed_aa", "grid_embed_aa", "elem", SIMPLE("ref_add", "add", "elem", "elementwise sum", DT_FLOAT, ref_add), SIMPLE("ref_mul", "mul", "elem", "elementwise product", DT_FLOAT, ref_mul), SIMPLE("ref_silu_mul", "silu_mul", "elem", "silu-gated product over a fused gate_up", DT_FLOAT, - ref_silu_mul), + ref_silu_mul), SIMPLE("ref_act_mul", "act_mul", "elem", "act(a) * b over two operands", DT_FLOAT, ref_act_mul), SIMPLE("ref_mul_weight", "mul_weight", "elem", "x * a scalar or one-row weight", DT_FLOAT, ref_mul_weight), @@ -1139,6 +1160,13 @@ SIMPLE("ref_gelu", "gelu", "elem", "exact erf gelu", DT_FLOAT, ref_gelu), SIMPLE("ref_silu", "silu", "elem", "silu", DT_FLOAT, ref_silu), SIMPLE("ref_sigmoid", "sigmoid", "elem", "logistic sigmoid", DT_FLOAT, ref_sigmoid), SIMPLE("ref_fill", "fill", "elem", "constant fill", DT_FLOAT, ref_fill), +SIMPLE("ref_gelu_mul", "gelu_mul", "elem", + "tanh-gelu-gated product over a fused gate_up (gemma's gelu_pytorch_tanh)", DT_FLOAT, + ref_gelu_mul), +SIMPLE("ref_logit_softcap", "logit_softcap", "elem", "final-logit softcap: cap * tanh(x / cap)", + DT_FLOAT, ref_logit_softcap), +SIMPLE("ref_scale", "scale", "elem", "per-tensor scalar scale: y = x * s (s a [1] weight)", + DT_FLOAT, ref_scale), SIMPLE("ref_ngram_ids", "ngram_ids", "vocab", "hashed n-gram row ids for PLE", DT_ANY, ref_ngram_ids), SIMPLE("ref_ple_gate", "ple_gate", "norm", "PLE gate: three grouped norms, a dot, a signed sqrt", diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index d84261cc..3c7d6ce2 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -331,6 +331,15 @@ int ref_rmsnorm_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("rmsnorm", operand, out); } +int ref_rmsnorm_p_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { M, n }); /* y */ + return o.finish("rmsnorm_p", operand, out); +} + int ref_rmsnorm_add_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -614,6 +623,15 @@ int ref_silu_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) return o.finish("silu_mul", operand, out); } +int ref_gelu_mul_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const uint32_t D = act_dt(p, n_p); + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + Opd o; + o.t(D, { M, 2 * n }); /* gate_up -- the gate is the FIRST half */ + o.t(D, { M, n }); /* y */ + return o.finish("gelu_mul", operand, out); +} + static int unary_shape(const RadParam* p, int n_p, int operand, const char* op, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); @@ -640,6 +658,20 @@ int ref_fill_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { o.t(D, { M, n }); /* y */ return o.finish("fill", operand, out); } + +int ref_logit_softcap_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + return unary_shape(p, n_p, operand, "logit_softcap", out); +} +int ref_scale_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0); + if (M <= 0 || n <= 0) return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + Opd o; + o.t(D, { M, n }); /* x */ + o.t(D, { 1 }); /* s -- one scalar, broadcast over everything */ + o.t(D, { M, n }); /* y */ + return o.finish("scale", operand, out); +} int ref_softmax_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { return unary_shape(p, n_p, operand, "softmax", out); } diff --git a/spec.md b/spec.md index 38bfaee8..7815552a 100644 --- a/spec.md +++ b/spec.md @@ -1472,6 +1472,12 @@ how a value is encoded — is plain data (`core/text/chatfmt.h`), and everything spelling is derived from it: the parser that reads the reply back, the lazy tool-call grammar and the literal words that trigger it, and the control tokens the decoder must render as text. +Two families of call syntax are described. In the tagged one each argument has its own tags +(Qwen's ``, MiniCPM's ``) and is typed by the tool's schema. In +the object one a call is its name and ONE object holding the arguments — JSON, or a dialect of +it with strings between declared delimiters and bare keys, as Gemma 4 writes +`call:NAME{path:<|"|>/a<|"|>,limit:3}` — and the values carry their own types. + There are two producers, in order of precedence. An architecture plugin may declare the format through the optional `rad_arch_chat_format` export (`abi/rad_builder.h`) — a new model whose template the analysis cannot read is supported by stating its format once. Otherwise the format diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index da6a14ed..3ee30c0a 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -41,7 +41,7 @@ add_library(rad_legacy_toolparse STATIC ${CMAKE_CURRENT_SOURCE_DIR}/legacy/toolp ${CMAKE_CURRENT_SOURCE_DIR}/legacy/chatdiff.cpp) target_link_libraries(rad_legacy_toolparse PUBLIC rad_core) target_include_directories(rad_legacy_toolparse PUBLIC ${CMAKE_CURRENT_SOURCE_DIR}/legacy) -set(RAD_TESTS_WITH_LEGACY chatparse_test) +set(RAD_TESTS_WITH_LEGACY chatparse_test chatparse_gemma4_test) # relayout_parity_test holds each kernel library's relayout of libquant's planes to the recorded # hash of the bytes that library stores. libr4d needs a HIP toolchain to build and its layouts do diff --git a/tests/arch_test.cpp b/tests/arch_test.cpp index 4c819cab..5c8dedd9 100644 --- a/tests/arch_test.cpp +++ b/tests/arch_test.cpp @@ -19,6 +19,7 @@ #include "rad_runtime.h" #include +#include #include #include #include @@ -90,6 +91,13 @@ struct RadBuilder { /* The buffer the plugin named as this step's logits (rad_declare_logits). */ rad_buf logits = 0; + /* The draft head's declaration (rad_declare_drafter), and whether it said it keeps no cache + * of its own (rad_drafter_shared_kv) and at which rotary offset. */ + RadDrafterDecl drafter{}; + std::string drafter_name; + bool drafter_shared = false; + int drafter_pos = -1; + /* The vision tower's declaration (rad_declare_encoder), when the plugin made one, and the * audio encoder's. */ RadEncoderDecl encoder{}; @@ -246,7 +254,16 @@ extern "C" int rad_kv_group_zero(RadBuilder* b, rad_kvgroup g) { return RAD_OK; } extern "C" int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d) { - (void)b; (void)d; + if (!b || !d) return RAD_E_INVAL; + b->drafter = *d; + b->drafter_name = d->name ? d->name : ""; + return RAD_OK; +} +extern "C" int rad_drafter_shared_kv(RadBuilder* b, int pos_offset) { + if (!b || b->drafter.kind != RAD_DRAFT_SERIAL || (pos_offset != 0 && pos_offset != 1)) + return RAD_E_STATE; + b->drafter_shared = true; + b->drafter_pos = pos_offset; return RAD_OK; } extern "C" int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { @@ -296,6 +313,7 @@ extern "C" const RadBatch* rad_batch(RadCtx* c) { return c->batch; } extern "C" int rad_rank(RadCtx* c) { return c->rank; } extern "C" int rad_world_size(RadCtx* c) { return c->world; } extern "C" RadStream rad_stream(RadCtx* c) { (void)c; return nullptr; } +extern "C" int rad_stream_sync(RadStream s) { (void)s; return RAD_OK; } extern "C" int rad_route_report(RadCtx* c, int layer, const RadRouting* r) { (void)r; c->routed_layers.push_back(layer); @@ -326,6 +344,8 @@ extern "C" void* rad_buf_ptr (RadCtx* c, rad_buf b) { (void)c; return (void #include "../arch/llama_fp8/llama_fp8.cpp" /* And LFM2, whose layer schedule and short convolution are its own. */ #include "../arch/lfm2_bf16/lfm2_bf16.cpp" +/* Gemma 4 dense: two attention classes (sliding-window + proportional-RoPE global) on one stream. */ +#include "../arch/gemma4_bf16/gemma4_bf16.cpp" /* The PLE block on its own: no architecture in this file declares it, and what its step() hands * the two windowed ops is a contract of its own (rad_block_ple.h). */ #include @@ -373,6 +393,87 @@ RadModelMeta qwen35_meta() { return m; } +/* Gemma 4 31B's text geometry, cut to TWELVE layers so a failure names a real shape. Twelve is the + * smallest count that lands two global layers at (l + 1) % 6 == 0 -- layers 5 and 11 -- over the ten + * sliding ones, the 5:1 ratio the model card carries. head_dim 256 here is the SLIDING width; the + * global class' 512 width and 4 heads are free-form header keys the plugin must read, not fields on + * RadModelMeta. */ +const char* k_gem4_keys[] = { + "sliding_window", + "global_head_dim", + "num_global_key_value_heads", + "rope_parameters.sliding_attention.rope_theta", + "rope_parameters.full_attention.rope_theta", + "rope_parameters.full_attention.partial_rotary_factor", + "num_kv_shared_layers", + "final_logit_softcapping", + "full_attention_interval", + "attention_k_eq_v", +}; +const char* k_gem4_vals[] = { "1024", "512", "4", "10000", "1000000", "0.25", "0", "30", "6", "1" }; + +RadModelMeta gemma4_meta() { + RadModelMeta m{}; + m.arch_id = "gemma4"; + m.name = "test-gemma4-31b"; + m.quant = "bf16"; + m.n_layers = 12; + m.n_embd = 5376; + m.n_head = 32; + m.n_head_kv = 16; + m.head_dim = 256; + m.n_ff = 21504; + m.n_vocab = 262144; + m.n_ctx_train = 262144; + m.rms_eps = 1e-6f; + m.rope_theta = 1e6f; + m.rope_scale = 1.0f; + m.n_kv = (int)(sizeof(k_gem4_keys) / sizeof(k_gem4_keys[0])); + m.kv_key = k_gem4_keys; + m.kv_val = k_gem4_vals; + return m; +} + +/* The same twelve layers with Gemma's assistant head merged under `draft.`, the way + * `rad-convert --draft-model` writes it: the head's own config flattened, its text config nested + * under `draft.text_config.`. The 31B's head: width 1024, four layers (three sliding, one full), + * the trunk's head geometry and window, its own 262144-row tied table. */ +const char* k_gem4d_keys[] = { + "sliding_window", "global_head_dim", "num_global_key_value_heads", + "rope_parameters.sliding_attention.rope_theta", "rope_parameters.full_attention.rope_theta", + "rope_parameters.full_attention.partial_rotary_factor", "num_kv_shared_layers", + "final_logit_softcapping", "full_attention_interval", "attention_k_eq_v", + "draft.architectures", "draft.backbone_hidden_size", "draft.use_ordered_embeddings", + "draft.text_config.hidden_size", "draft.text_config.num_hidden_layers", + "draft.text_config.layer_types", "draft.text_config.num_attention_heads", + "draft.text_config.num_key_value_heads", "draft.text_config.num_global_key_value_heads", + "draft.text_config.head_dim", "draft.text_config.global_head_dim", + "draft.text_config.intermediate_size", "draft.text_config.sliding_window", + "draft.text_config.vocab_size", "draft.text_config.rms_norm_eps", + "draft.text_config.rope_parameters.sliding_attention.rope_theta", + "draft.text_config.rope_parameters.full_attention.rope_theta", + "draft.text_config.rope_parameters.full_attention.partial_rotary_factor", +}; +const char* k_gem4d_vals[] = { + "1024", "512", "4", "10000", "1000000", "0.25", "0", "30", "6", "1", + "Gemma4AssistantForCausalLM", "5376", "0", + "1024", "4", + "sliding_attention sliding_attention sliding_attention full_attention", "32", + "16", "4", + "256", "512", + "8192", "1024", + "262144", "1e-06", + "10000", "1000000", "0.25", +}; + +RadModelMeta gemma4_draft_meta() { + RadModelMeta m = gemma4_meta(); + m.n_kv = (int)(sizeof(k_gem4d_keys) / sizeof(k_gem4d_keys[0])); + m.kv_key = k_gem4d_keys; + m.kv_val = k_gem4d_vals; + return m; +} + RadBuildCtx build_ctx(int rank = 0, int world = 1) { RadBuildCtx c{}; c.rank = rank; @@ -3439,3 +3540,595 @@ TEST(lfm2_vl_encoder_pass_and_the_rows_it_scatters) { CHECK_EQ(ops[0], std::string("embed_lookup")); CHECK_EQ(ops[1], std::string("scatter_rows")); } + +/* =============================== gemma4 dense: two attention classes =========================== */ + +TEST(declare_is_a_gemma4_trunk) { + RadBuilder b; + RadModelMeta meta = gemma4_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + /* 12 layers: 10 sliding + 2 global (layers 5 and 11). */ + CHECK_EQ(count_op(b, "attn_paged"), 12); + CHECK_EQ(count_op(b, "kv_store"), 12); + CHECK_EQ(count_op(b, "rmsnorm_p"), 12); /* the weightless value normalisation, one per layer */ + CHECK_EQ(count_op(b, "rope"), 24); /* q + k */ + CHECK_EQ(count_op(b, "gelu_mul"), 12); /* Gemma's FFN activation, not SwiGLU */ + CHECK_EQ(count_op(b, "silu_mul"), 0); + CHECK_EQ(count_op(b, "gemm_nt"), 70); /* 10x6 sliding (q,k,v,o,gu,down) + 2x5 global (no v) */ + CHECK_EQ(count_op(b, "rmsnorm"), 73); /* 4 attn + 2 ffn per layer, plus the final norm */ + CHECK_EQ(count_op(b, "add"), 24); /* the two GemmaRMSNorm residuals per layer */ + CHECK_EQ(count_op(b, "embed_lookup"), 1); + CHECK_EQ(count_op(b, "gather_rows"), 1); + CHECK_EQ(count_op(b, "logits_gemm"), 1); + CHECK_EQ(count_op(b, "logit_softcap"), 1); + CHECK_EQ(count_op(b, "all_reduce"), 0); /* world 1 */ +} + +/* The reply format is the plugin's to state: Gemma 4's template is one the template analysis + * cannot read. Its calls are the object family -- a name and one object in Gemma's dialect -- + * and its thought channel may open again after the answer. The parser's reading of it is + * chatparse_gemma4_test's; this holds the export to what the header declares. */ +TEST(gemma4_declares_its_reply_format) { + RadModelMeta meta = gemma4_meta(); + const RadChatFormat* f = gemma4_bf16::chat_format(&meta); + REQUIRE(f != nullptr); + CHECK_EQ(f->struct_size, (uint32_t)sizeof(RadChatFormat)); + CHECK_EQ(f->args_form, (uint32_t)RAD_CHAT_ARGS_OBJECT); + CHECK_EQ(std::string(f->call_open), std::string("<|tool_call>")); + CHECK_EQ(std::string(f->call_close), std::string("")); + CHECK_EQ(std::string(f->name_prefix), std::string("call:")); + CHECK_EQ(std::string(f->name_suffix), std::string("")); + CHECK_EQ(std::string(f->object_string_open), std::string("<|\"|>")); + CHECK_EQ(std::string(f->object_string_close), std::string("<|\"|>")); + CHECK(f->object_bare_keys != 0); + CHECK_EQ(std::string(f->reasoning_open), std::string("<|channel>thought\n")); + CHECK_EQ(std::string(f->reasoning_close), std::string("")); + CHECK(f->reasoning_anywhere != 0); + REQUIRE(f->n_triggers == 1); + CHECK_EQ(std::string(f->triggers[0]), std::string("<|tool_call>")); + CHECK(f->arg_prefix == nullptr && f->arg_value_suffix == nullptr); +} + +TEST(gemma4_declares_two_kv_groups_and_binds_the_schedule) { + RadBuilder b; + RadModelMeta meta = gemma4_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + CHECK_EQ((int)b.kv_groups.size(), 2); + CHECK_EQ((int)b.kv_groups[0].d.kind, RAD_KV_WINDOW); /* sliding, declared first */ + CHECK_EQ(b.kv_groups[0].d.window, 1024); + CHECK_EQ(b.kv_groups[0].d.n_head_kv, 16); + CHECK_EQ(b.kv_groups[0].d.head_dim, 256); + CHECK_EQ((int)b.kv_groups[1].d.kind, RAD_KV_FULL); /* global */ + CHECK_EQ(b.kv_groups[1].d.window, 0); + CHECK_EQ(b.kv_groups[1].d.n_head_kv, 4); + CHECK_EQ(b.kv_groups[1].d.head_dim, 512); + + /* (l + 1) % 6 == 0 -> global layers 5 and 11; the fake hands group #1 to sliding (declared + * first) and #2 to global. */ + CHECK_EQ((int)b.binds.size(), 12); + for (int l = 0; l < 12; ++l) { + const bool want_global = ((l + 1) % 6 == 0); + CHECK_EQ((int)b.binds[(size_t)l].first, l); + CHECK_EQ((int)b.binds[(size_t)l].second, want_global ? 2 : 1); + } +} + +TEST(gemma4_attention_shapes_for_both_classes) { + RadBuilder b; + RadModelMeta meta = gemma4_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + /* layer 0 (sliding): q 32x256, k/v 16x256, windowed. */ + { + const RecOp* at = find_op(b, "attn_paged", 0); + CHECK(at != nullptr); + CHECK_EQ(pint(at, "head_dim"), 256); + CHECK_EQ(pint(at, "gqa"), 2); + CHECK_EQ(pint(at, "window"), 1024); + CHECK_EQ(pint(at, "n_head"), 32); + CHECK_EQ(pint(at, "block_size"), 16); + CHECK_EQ(pstr(at, "q_dtype"), std::string("bf16")); + } + /* layer 5 (the first global, (5+1)%6==0): q 32x512, k 4x512, windowless. */ + { + const RecOp* at = find_op(b, "attn_paged", 5); + CHECK(at != nullptr); + CHECK_EQ(pint(at, "head_dim"), 512); + CHECK_EQ(pint(at, "gqa"), 8); + CHECK_EQ(pint(at, "window"), 0); + CHECK_EQ(pint(at, "n_head"), 32); + } + + /* rope: the sliding call is standard over the full 256 (theta 1e4); the global call is + * proportional over 128 of 512 (the "head" ladder, theta 1e6). rope ops are declared q, k per + * layer, so global index = 2*layer + (q ? 0 : 1). */ + { + const RecOp* r = find_op(b, "rope", 0); /* layer 0, q */ + CHECK(r != nullptr); + CHECK_EQ(pint(r, "head_dim"), 256); + CHECK_EQ(pint(r, "rotary_dim"), 256); + CHECK_NEAR(pflt(r, "theta"), 1e4, 1.0); + CHECK_EQ(pstr(r, "ladder"), std::string("rotary")); + CHECK_EQ(pint(r, "n_head"), 32); + + const RecOp* rg = find_op(b, "rope", 10); /* layer 5, q */ + CHECK(rg != nullptr); + CHECK_EQ(pint(rg, "head_dim"), 512); + CHECK_EQ(pint(rg, "rotary_dim"), 128); + CHECK_NEAR(pflt(rg, "theta"), 1e6, 1.0); + CHECK_EQ(pstr(rg, "ladder"), std::string("head")); + CHECK_EQ(pint(rg, "n_head"), 32); + + /* the k rope is a separate buffer, served by the fused-row kernel as a q-only form over + * the k heads: n_head is the head count to rotate (here n_head_kv = 4) and n_head_kv is 0. */ + const RecOp* rkg = find_op(b, "rope", 11); /* layer 5, k */ + CHECK(rkg != nullptr); + CHECK_EQ(pint(rkg, "n_head"), 4); + CHECK_EQ(pint(rkg, "n_head_kv"), 0); + } + + /* the weightless value normalisation reads 256 dims on a sliding layer, 512 on a global one; + * and the global layer has no v_proj weight at all -- v is k. */ + { + const RecOp* vn = find_op(b, "rmsnorm_p", 0); /* layer 0 */ + CHECK(vn != nullptr); + CHECK_EQ(pint(vn, "n"), 256); + const RecOp* vng = find_op(b, "rmsnorm_p", 5); /* layer 5 */ + CHECK(vng != nullptr); + CHECK_EQ(pint(vng, "n"), 512); + } + CHECK(find_w(b, "blk.0.attn_v.weight") != nullptr); /* sliding has a v projection */ + CHECK(find_w(b, "blk.5.attn_v.weight") == nullptr); /* global: k == v */ + CHECK(find_w(b, "blk.5.attn_q.weight") != nullptr); + CHECK(find_w(b, "blk.5.attn_o.weight") != nullptr); +} + +TEST(gemma4_final_norm_softcap_and_vocab) { + RadBuilder b; + RadModelMeta meta = gemma4_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + const RecOp* cap = find_op(b, "logit_softcap", 0); + CHECK(cap != nullptr); + CHECK_EQ(pint(cap, "n"), 262144); + CHECK_NEAR(pflt(cap, "cap"), 30.0, 1e-9); + CHECK_EQ(pstr(cap, "dtype"), std::string("f32")); + + const RecOp* lg = find_op(b, "logits_gemm", 0); + CHECK(lg != nullptr); + CHECK_EQ(pint(lg, "n_vocab"), 262144); + CHECK_EQ(pint(lg, "n_embd"), 5376); + + const RecWeight* emb = find_w(b, "token_embd.weight"); + CHECK(emb != nullptr); + CHECK_EQ(emb->d.shape[0], 262144); + CHECK_EQ(emb->d.shape[1], 5376); + CHECK_EQ(emb->d.shard, RAD_SHARD_ROW); + + /* lm_head is tied to the embedding. */ + CHECK(find_map(b, "output.weight") != nullptr); + + /* The embedding is scaled by sqrt(n_embd) at the LOOKUP, not baked into the table (the + * reference's build_inp_embd and HF's ScaledWordEmbedding both do it there), so the table + * stays tied to the head's. The scale rides the op. */ + const RecOp* el = find_op(b, "embed_lookup", 0); + CHECK(el != nullptr); + CHECK_NEAR(pflt(el, "mult"), std::sqrt(5376.0), 1e-9); +} + +TEST(gemma4_every_op_declares_the_buffers_it_touches) { + RadBuilder b; + RadModelMeta meta = gemma4_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + for (const auto& o : b.ops) + if (o.resolved) CHECK(o.uses_declared); +} + +/* attention_k_eq_v decides whether the global layers have a v_proj: 31B's read V from K and have + * none, a checkpoint that says 0 declares one, and one that says nothing is refused. */ +TEST(gemma4_global_v_follows_attention_k_eq_v) { + for (const char* v : { "1", "0", "" }) { + std::vector keys(std::begin(k_gem4_keys), std::end(k_gem4_keys)); + std::vector vals(std::begin(k_gem4_vals), std::end(k_gem4_vals)); + if (*v) vals.back() = v; + else { keys.pop_back(); vals.pop_back(); } + RadModelMeta meta = gemma4_meta(); + meta.n_kv = (int)keys.size(); meta.kv_key = keys.data(); meta.kv_val = vals.data(); + RadBuilder b; + RadBuildCtx ctx = build_ctx(); + const int rc = gemma4_bf16::declare(&b, &meta, &ctx); + if (!*v) { CHECK(rc != RAD_OK); continue; } + CHECK_OK(rc); + CHECK(find_w(b, "blk.0.attn_v.weight") != nullptr); /* sliding: always */ + CHECK_EQ(find_w(b, "blk.5.attn_v.weight") != nullptr, *v == '0'); /* global */ + } +} + +TEST(gemma4_every_weight_has_a_name_map) { + RadBuilder b; + RadModelMeta meta = gemma4_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + for (const auto& w : b.weights) + CHECK(find_map(b, w.name) != nullptr); +} + +TEST(a_gemma4_decode_step_runs_both_classes_in_order) { + RadBuilder b; + b.refuse.insert("qkv_norm_rope"); /* the unfused prologue; the fused one is checked below */ + RadModelMeta meta = gemma4_meta(); + RadBuildCtx ctx = build_ctx(); + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + + std::vector want = { "embed_lookup" }; + for (int l = 0; l < 12; ++l) { + if ((l + 1) % 6 == 0) { + /* global: k == v, so no v gemm -- the weightless v norm derives from k instead. */ + for (const char* s : { "rmsnorm", "gemm_nt", "gemm_nt", + "rmsnorm_p", "rmsnorm", "rmsnorm", "rope", "rope", + "kv_store", "attn_paged", "gemm_nt", "rmsnorm", "add" }) + want.push_back(s); + } else { + /* sliding: a v gemm feeds the weightless v norm. */ + for (const char* s : { "rmsnorm", "gemm_nt", "gemm_nt", "gemm_nt", + "rmsnorm_p", "rmsnorm", "rmsnorm", "rope", "rope", + "kv_store", "attn_paged", "gemm_nt", "rmsnorm", "add" }) + want.push_back(s); + } + for (const char* s : { "rmsnorm", "gemm_nt", "gelu_mul", "gemm_nt", "rmsnorm", "add" }) + want.push_back(s); + want.push_back("scale"); /* the per-layer scalar over the residual stream */ + } + for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) + want.push_back(s); + CHECK_EQ(join(issued_ops(b, c)), join(want)); + + /* The sampled-row ops band on n_out; the attention bands on q_len. */ + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (!o) continue; + if (o->op == "attn_paged") + CHECK_EQ(i.n, (int64_t)batch.max_q_len); + else if (o->op == "gather_rows" || o->op == "logits_gemm" || o->op == "logit_softcap") + CHECK_EQ(i.n, (int64_t)batch.n_out); + } +} + +/* THE w4a8 TRUNK FUSES ITS RESIDUAL JUNCTIONS: the first block's entry, every attention -> feed-forward + * and every feed-forward -> next attention is one `rmsnorm_quant_i8` (post-norm, add, layer scalar, + * norm and quantiser), and q, k and v read one quantised pair. The last layer's stream goes to the + * final norm unfused, and a kernel set that does not resolve the op keeps the whole unfused chain + * -- with the shared q/k/v pair, which needs nothing new. */ +static std::vector gemma4_w4_step(const std::set& refuse, int world = 1) { + RadBuilder b; + const RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_F16, 1, 128); + b.encs = { { "attn_q.", w4 }, { "attn_k.", w4 }, { "attn_v.", w4 }, { "attn_o.", w4 }, + { "ffn_gate_up.", w4 }, { "ffn_down.", w4 } }; + for (const auto& r : refuse) b.refuse.insert(r); + RadModelMeta meta = gemma4_meta(); + RadBuildCtx ctx = build_ctx(0, world); + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + RadCtx c; c.b = &b; c.rank = 0; c.world = world; + RadBatch batch = decode_batch(); + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + return issued_ops(b, c); +} + +/* At two ranks the all-reduce in front of every junction is folded into it: the only standalone + * collectives left are the embedding's and the last layer's feed-forward, whose stream goes to the + * final norm rather than a quantiser. Without the fused collective the junctions keep their + * all-reduces in front of them. */ +TEST(a_gemma4_w4a8_step_at_two_ranks_folds_the_all_reduce_into_the_junction) { + std::vector want = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" }; + for (int l = 0; l < 12; ++l) { + const bool global = (l + 1) % 6 == 0; + for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q"); + for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + "ar_rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) + want.push_back(s); + if (l < 11) want.push_back("ar_rmsnorm_quant_i8"); + else for (const char* s : { "all_reduce", "rmsnorm", "add", "scale" }) want.push_back(s); + } + for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) + want.push_back(s); + CHECK_EQ(join(gemma4_w4_step({}, 2)), join(want)); + + std::vector plain = { "embed_lookup", "all_reduce", "rmsnorm_quant_i8" }; + for (int l = 0; l < 12; ++l) { + const bool global = (l + 1) % 6 == 0; + for (int i = 0; i < (global ? 2 : 3); ++i) plain.push_back("gemm_nt_q"); + for (const char* s : { "qkv_norm_rope", "kv_store", "attn_paged", "quant_act_i8", "gemm_nt_q", + "all_reduce", "rmsnorm_quant_i8", "gemm_nt_q", "gelu_mul_quant_i8", + "gemm_nt_q", "all_reduce" }) + plain.push_back(s); + if (l < 11) plain.push_back("rmsnorm_quant_i8"); + else for (const char* s : { "rmsnorm", "add", "scale" }) plain.push_back(s); + } + for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) + plain.push_back(s); + CHECK_EQ(join(gemma4_w4_step({ "ar_rmsnorm_quant_i8" }, 2)), join(plain)); +} + +TEST(a_gemma4_w4a8_step_fuses_its_residual_junctions) { + std::vector want = { "embed_lookup", "rmsnorm_quant_i8" }; + for (int l = 0; l < 12; ++l) { + const bool global = (l + 1) % 6 == 0; + for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q"); + for (const char* s : { "qkv_norm_rope", "kv_store", + "attn_paged", "quant_act_i8", "gemm_nt_q", "rmsnorm_quant_i8", + "gemm_nt_q", "gelu_mul_quant_i8", "gemm_nt_q" }) + want.push_back(s); + if (l < 11) want.push_back("rmsnorm_quant_i8"); + else for (const char* s : { "rmsnorm", "add", "scale" }) want.push_back(s); + } + for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) + want.push_back(s); + CHECK_EQ(join(gemma4_w4_step({})), join(want)); +} + +TEST(a_gemma4_w4a8_step_without_the_fused_ops_keeps_the_chain_and_one_qkv_quantiser) { + std::vector want = { "embed_lookup" }; + for (int l = 0; l < 12; ++l) { + const bool global = (l + 1) % 6 == 0; + want.push_back("rmsnorm"); + want.push_back("quant_act_i8"); + for (int i = 0; i < (global ? 2 : 3); ++i) want.push_back("gemm_nt_q"); + for (const char* s : { "rmsnorm_p", "rmsnorm", "rmsnorm", "rope", "rope", "kv_store", + "attn_paged", "quant_act_i8", "gemm_nt_q", "rmsnorm", "add", + "rmsnorm", "quant_act_i8", "gemm_nt_q", "gelu_mul", "quant_act_i8", + "gemm_nt_q", "rmsnorm", "add", "scale" }) + want.push_back(s); + } + for (const char* s : { "rmsnorm", "gather_rows", "logits_gemm", "logit_softcap" }) + want.push_back(s); + CHECK_EQ(join(gemma4_w4_step({ "rmsnorm_quant_i8", "qkv_norm_rope", "gelu_mul_quant_i8" })), join(want)); +} + +/* =============================== gemma4: the assistant (MTP) head =============================== */ + +namespace { +/* The draft passes the core stages for a head with no cache of its own: one row a drafting + * sequence. Four sequences; the history pass names every row as a draft row. */ +static const int32_t kHeadRows[] = { 0, 1, 2, 3 }; +RadBatch head_batch(int pass) { + RadBatch b{}; + b.phase = RAD_PHASE_DECODE; + b.n_tok = 4; + b.n_seq = 4; + b.max_q_len = 1; + b.max_ctx_len = 100; + b.draft_pass = pass; + if (pass < 0) { + b.n_out = 4; + b.out_ids = kHeadRows; + b.n_draft_out = 4; + b.draft_out_ids = kHeadRows; + } + return b; +} +} /* namespace */ + +TEST(gemma4_declares_no_head_without_one_or_without_speculation) { + { + RadBuilder b; + RadModelMeta meta = gemma4_meta(); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 3; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_NONE); + CHECK(find_w(b, "mtp.pre_proj.weight") == nullptr); + } + { + RadBuilder b; + RadModelMeta meta = gemma4_draft_meta(); + RadBuildCtx ctx = build_ctx(); /* max_spec 0 */ + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_NONE); + CHECK(find_w(b, "mtp.pre_proj.weight") == nullptr); + CHECK_EQ(count_op(b, "attn_paged"), 12); + } +} + +TEST(gemma4_assistant_is_a_serial_head_with_no_cache_of_its_own) { + RadBuilder b; + RadModelMeta meta = gemma4_draft_meta(); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 3; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + CHECK_EQ((int)b.drafter.kind, (int)RAD_DRAFT_SERIAL); + CHECK_EQ(b.drafter.depth, 3); + CHECK_EQ(b.drafter_name, std::string("mtp")); + CHECK_EQ((int)b.drafter.proposal, 0); /* through the sampler chain */ + CHECK(b.drafter_shared); + CHECK_EQ(b.drafter_pos, gemma4_bf16::kHeadPosOffset); + + /* It binds no layer: it writes no K and V. The trunk's twelve bindings are all there are. */ + CHECK_EQ((int)b.binds.size(), 12); + CHECK_EQ((int)b.kv_groups.size(), 2); + + /* Four head layers' worth of attention beside the trunk's twelve, none of them storing. */ + CHECK_EQ(count_op(b, "attn_paged"), 16); + CHECK_EQ(count_op(b, "kv_store"), 12); + CHECK_EQ(count_op(b, "logit_softcap"), 1); /* the trunk's; the head's logits are not capped */ + CHECK_EQ(count_op(b, "logits_gemm"), 2); + + for (int l = 0; l < 4; ++l) { + const RecOp* at = find_op(b, "attn_paged", 12 + l); + REQUIRE(at != nullptr); + const bool full = (l == 3); + CHECK_EQ(pint(at, "head_dim"), full ? 512 : 256); + CHECK_EQ(pint(at, "gqa"), full ? 8 : 2); + CHECK_EQ(pint(at, "window"), full ? 0 : 1024); + CHECK_EQ(pint(at, "causal"), 1); + CHECK_NEAR(pflt(at, "scale"), 1.0, 1e-12); + const RecParam* ql = param(at, "q_len"); + REQUIRE(ql != nullptr); + CHECK_EQ(ql->ival, 1); /* one row a sequence, the decode band only */ + CHECK_EQ(ql->ihi, 1); + } + + /* The weights: q-only attention, the two projections and the head's own tied table. */ + const RecWeight* wq0 = find_w(b, "mtp.blk.0.attn_q.weight"); + const RecWeight* wq3 = find_w(b, "mtp.blk.3.attn_q.weight"); + REQUIRE(wq0 != nullptr); REQUIRE(wq3 != nullptr); + CHECK_EQ(wq0->d.shape[0], 32 * 256); CHECK_EQ(wq0->d.shape[1], 1024); + CHECK_EQ(wq3->d.shape[0], 32 * 512); CHECK_EQ(wq3->d.shape[1], 1024); + const RecWeight* wo3 = find_w(b, "mtp.blk.3.attn_o.weight"); + REQUIRE(wo3 != nullptr); + CHECK_EQ(wo3->d.shape[0], 1024); CHECK_EQ(wo3->d.shape[1], 32 * 512); + CHECK(find_w(b, "mtp.blk.0.attn_k.weight") == nullptr); + CHECK(find_w(b, "mtp.blk.0.attn_v.weight") == nullptr); + const RecWeight* gu = find_w(b, "mtp.blk.1.ffn_gate_up.weight"); + REQUIRE(gu != nullptr); + CHECK_EQ(gu->d.shape[0], 2 * 8192); CHECK_EQ(gu->d.shape[1], 1024); + const RecWeight* pre = find_w(b, "mtp.pre_proj.weight"); + const RecWeight* post = find_w(b, "mtp.post_proj.weight"); + REQUIRE(pre != nullptr); REQUIRE(post != nullptr); + CHECK_EQ(pre->d.shape[0], 1024); CHECK_EQ(pre->d.shape[1], 2 * 5376); + CHECK_EQ(post->d.shape[0], 5376); CHECK_EQ(post->d.shape[1], 1024); + CHECK_EQ(pre->d.shard, RAD_SHARD_NONE); + const RecWeight* lm = find_w(b, "mtp.output.weight"); + REQUIRE(lm != nullptr); + CHECK_EQ(lm->d.shape[0], 262144); CHECK_EQ(lm->d.shape[1], 1024); + CHECK_EQ(lm->d.shard, RAD_SHARD_ROW); + CHECK_EQ(lm->d.access, RAD_ACCESS_VOCAB); + + /* The checkpoint's names, merged under `draft.`: the head's table is its lm_head and nothing + * else, and gate and up are fused like the trunk's. */ + const RecMap* mlm = find_map(b, "mtp.output.weight"); + REQUIRE(mlm != nullptr); + CHECK_EQ(mlm->src[0], std::string("draft.model.embed_tokens.weight")); + const RecMap* mgu = find_map(b, "mtp.blk.1.ffn_gate_up.weight"); + REQUIRE(mgu != nullptr); + CHECK_EQ(mgu->mode, RAD_MAP_CONCAT); + CHECK_EQ(mgu->src[0], std::string("draft.model.layers.1.mlp.gate_proj.weight")); + CHECK_EQ(mgu->src[1], std::string("draft.model.layers.1.mlp.up_proj.weight")); + const RecMap* mpre = find_map(b, "mtp.pre_proj.weight"); + REQUIRE(mpre != nullptr); + CHECK_EQ(mpre->src[0], std::string("draft.pre_projection.weight")); + + /* The entry embeds through the TRUNK's table, scaled as the trunk scales it. */ + const RecOp* el = find_op(b, "embed_lookup", 1); + REQUIRE(el != nullptr); + CHECK_EQ(pint(el, "n_embd"), 5376); + CHECK_NEAR(pflt(el, "mult"), std::sqrt(5376.0), 1e-9); + CHECK(el->w.size() == 1 && find_op(b, "embed_lookup", 0)->w == el->w); + + for (const auto& o : b.ops) + if (o.resolved) CHECK(o.uses_declared); + for (const auto& w : b.weights) + CHECK(find_map(b, w.name) != nullptr); +} + +TEST(gemma4_head_passes_read_the_last_trunk_layer_of_their_class) { + RadBuilder b; + RadModelMeta meta = gemma4_draft_meta(); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 3; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + for (int pass : { -1, 2 }) { + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = head_batch(pass); + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + + std::vector want; + want.push_back(pass < 0 ? "gather_rows" : "cast"); /* the trunk's h, or the head's h' */ + for (const char* s : { "embed_lookup", "cast", "gemm_nt" }) want.push_back(s); + for (int l = 0; l < 4; ++l) + for (const char* s : { "rmsnorm", "gemm_nt", "rmsnorm", "rope", "attn_paged", "gemm_nt", + "rmsnorm", "add", "rmsnorm", "gemm_nt", "gelu_mul", "gemm_nt", + "rmsnorm", "add", "scale" }) + want.push_back(s); + for (const char* s : { "rmsnorm", "logits_gemm", "gemm_nt" }) want.push_back(s); + CHECK_EQ(join(issued_ops(b, c)), join(want)); + + /* The attention reads the trunk's cache: layers 0..2 the last sliding trunk layer (10 of + * the twelve), layer 3 the last full one (11). Groups by declaration: 1 sliding, 2 full. */ + int seen = 0; + for (const auto& i : c.issues) { + const RecOp* o = b.op_of(i.op); + if (!o || o->op != "attn_paged") continue; + REQUIRE(i.opd.size() > 1); + CHECK_EQ((int)i.opd[1].kind, (int)RAD_OPK_KV); + CHECK_EQ((int)i.opd[1].handle, seen < 3 ? 1 : 2); + CHECK_EQ((long long)i.opd[1].offset, seen < 3 ? 10LL : 11LL); + CHECK_EQ(i.n, 1); + ++seen; + } + CHECK_EQ(seen, 4); + } +} + +TEST(gemma4_head_at_two_ranks_reduces_before_each_post_norm) { + RadBuilder b; + RadModelMeta meta = gemma4_draft_meta(); + RadBuildCtx ctx = build_ctx(0, 2); + ctx.max_spec = 3; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + + const RecWeight* wq0 = find_w(b, "mtp.blk.0.attn_q.weight"); + REQUIRE(wq0 != nullptr); + CHECK_EQ(wq0->d.shape[0], 16 * 256); + const RecWeight* lm = find_w(b, "mtp.output.weight"); + REQUIRE(lm != nullptr); + CHECK_EQ(lm->d.shape[0], 131072); + + RadCtx c; c.b = &b; c.rank = 0; c.world = 2; + RadBatch batch = head_batch(-1); + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(c.step_fail.empty()); + const std::vector got = issued_ops(b, c); + std::vector want = { "gather_rows", "embed_lookup", "all_reduce", "cast", "gemm_nt" }; + for (int l = 0; l < 4; ++l) + for (const char* s : { "rmsnorm", "gemm_nt", "rmsnorm", "rope", "attn_paged", "gemm_nt", + "all_reduce", "rmsnorm", "add", "rmsnorm", "gemm_nt", "gelu_mul", + "gemm_nt", "all_reduce", "rmsnorm", "add", "scale" }) + want.push_back(s); + for (const char* s : { "rmsnorm", "logits_gemm", "gemm_nt" }) want.push_back(s); + CHECK_EQ(join(got), join(want)); +} + +TEST(gemma4_head_refuses_a_history_pass_shaped_for_a_cache_of_its_own) { + RadBuilder b; + RadModelMeta meta = gemma4_draft_meta(); + RadBuildCtx ctx = build_ctx(); + ctx.max_spec = 3; + CHECK_OK(gemma4_bf16::declare(&b, &meta, &ctx)); + RadCtx c; c.b = &b; c.rank = 0; c.world = 1; + RadBatch batch = head_batch(-1); + batch.n_draft_out = 1; /* a history run with rows that do not draft */ + c.batch = &batch; + gemma4_bf16::step(&c, &batch); + CHECK(!c.step_fail.empty()); + CHECK(c.issues.empty()); +} + +TEST(gemma4_probe_names_the_heads_operating_depth) { + RadArchProbe p{}; + RadModelMeta with = gemma4_draft_meta(); + CHECK_OK(gemma4_bf16::probe(&with, &p)); + CHECK_EQ(p.draft_depth, gemma4_bf16::kHeadDepth); + CHECK_EQ(p.draft_depth_fixed, 0); + RadArchProbe q{}; + RadModelMeta without = gemma4_meta(); + CHECK_OK(gemma4_bf16::probe(&without, &q)); + CHECK_EQ(q.draft_depth, 0); +} diff --git a/tests/build_test.cpp b/tests/build_test.cpp index 906eb51a..ad6a76ee 100644 --- a/tests/build_test.cpp +++ b/tests/build_test.cpp @@ -706,6 +706,38 @@ TEST(tune_requests_are_one_per_kernel_and_shape) { } /* ================================================================== KV groups */ +/* A HEAD THAT KEEPS NO CACHE OF ITS OWN BINDS NONE: it is given no history pass, so a group bound at + * one of its layers (meta.n_layers and above) would be read and never written. The same head + * borrowing only the trunk's layers finishes. */ +TEST(a_head_with_no_cache_of_its_own_binds_no_group_of_its_own) { + NEED_PLUGIN(reg) + for (bool own : { false, true }) { + Builder b(reg, make_meta(), make_ctx()); + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; kd.dtype = RAD_BF16; kd.n_head_kv = 8; kd.head_dim = 128; + const rad_kvgroup g = b.decl_kv_group("kv_full", &kd); + const RadParam p[] = { RAD_RANGE("q_len", 1, 16), RAD_INT("head_dim", 128), + RAD_INT("window", 0), RAD_INT("block_size", 16), + RAD_INT("causal", 1), RAD_INT("n_head", 8), + RAD_STR("kv_dtype", "bf16") }; + b.decl_op("t_attn", p, 7, nullptr, 0); + CHECK_OK(b.bind_layer_kv(0, g)); + CHECK_OK(b.bind_layer_kv(1, g)); + if (own) CHECK_OK(b.bind_layer_kv(2, g)); /* make_meta: two trunk layers, so 2 is the head's */ + RadDrafterDecl d{}; + d.kind = RAD_DRAFT_SERIAL; d.name = "mtp"; d.depth = 3; + CHECK_OK(rad_declare_drafter(&b, &d)); + CHECK_OK(rad_drafter_shared_kv(&b, 0)); + b.finish(); + if (own) { + CHECK_EQ(b.status(), RAD_E_STATE); + CHECK(has(b.errors().back(), "keeps no cache of its own")); + } else { + CHECK_OK(b.status()); + } + } +} + TEST(kv_block_size_comes_off_the_kernel) { NEED_PLUGIN(reg) Builder b(reg, make_meta(), make_ctx()); @@ -1005,6 +1037,49 @@ TEST(the_drafter_name_survives_the_program_leaving_the_builder) { CHECK_EQ(p.drafter.depth, 3); } +/* A HEAD THAT KEEPS NO CACHE OF ITS OWN (rad_drafter_shared_kv) is a property of a declared SERIAL + * drafter. With none declared, with a block drafter, or at a position no head sits at, the call is + * refused at declare -- a head staged the wrong way round costs acceptance and says nothing. */ +TEST(a_head_that_keeps_no_cache_of_its_own_is_a_serial_one) { + Registry reg; + { + Builder b(reg, make_meta(), make_ctx()); + CHECK_EQ(rad_drafter_shared_kv(&b, 0), RAD_E_STATE); /* nothing declared */ + } + { + Builder b(reg, make_meta(), make_ctx()); + RadBufDecl bd{}; + bd.dtype = RAD_I32; bd.rank = 2; bd.shape[0] = 256; bd.shape[1] = 4; + const rad_buf prop = rad_decl_buffer(&b, "prop", &bd); + RadDrafterDecl d{}; + d.kind = RAD_DRAFT_BLOCK; d.name = "df"; d.depth = 4; d.mask_token = 5; + d.proposal = prop; d.proposal_pitch = 4; + CHECK_OK(rad_declare_drafter(&b, &d)); + CHECK_EQ(rad_drafter_shared_kv(&b, 0), RAD_E_STATE); /* a block drafter */ + CHECK(!b.program().drafter_shared_kv); + } + { + Builder b(reg, make_meta(), make_ctx()); + RadDrafterDecl d{}; + d.kind = RAD_DRAFT_SERIAL; d.name = "mtp"; d.depth = 4; + CHECK_OK(rad_declare_drafter(&b, &d)); + CHECK_EQ(rad_drafter_shared_kv(&b, 2), RAD_E_INVAL); /* no position a head sits at */ + CHECK(!b.program().drafter_shared_kv); + CHECK_OK(rad_drafter_shared_kv(&b, 1)); + CHECK(b.program().drafter_shared_kv); + CHECK_EQ(b.program().drafter_pos_offset, 1); + } + { + /* Every drafter that does not ask keeps the old shape. */ + Builder b(reg, make_meta(), make_ctx()); + RadDrafterDecl d{}; + d.kind = RAD_DRAFT_SERIAL; d.name = "mtp"; d.depth = 4; + CHECK_OK(rad_declare_drafter(&b, &d)); + CHECK(!b.program().drafter_shared_kv); + CHECK_EQ(b.program().drafter_pos_offset, 0); + } +} + /* ================================================================== the enum name tables * diff --git a/tests/chatparse_gemma4_test.cpp b/tests/chatparse_gemma4_test.cpp new file mode 100644 index 00000000..2ffddb94 --- /dev/null +++ b/tests/chatparse_gemma4_test.cpp @@ -0,0 +1,897 @@ +/* chatparse_gemma4_test.cpp -- Gemma 4's reply format: a reasoning channel, and calls written as a + * name and ONE object in a dialect of JSON. + * + * Gemma 4's template is one llama.cpp reads with a hand-written handler, so the template analysis + * finds no format in it and the plugin declares one (arch/gemma4_bf16/gemma4_chat_format.h): + * + * <|channel>thought\n ... reasoning + * <|tool_call>call:NAME{key:<|"|>text<|"|>,n:3} a call, repeated for more + * + * Every case reads a reply under a request rendered through the model's REAL template + * (tests/data/chat/gemma4), and where the reply is within the format the answer is held, byte for + * byte, to llama.cpp's own Gemma 4 parser -- the PEG grammar and value mapper its handler builds + * (tests/legacy, the `old` side). Every reply is also streamed cut every way (chatdiff.h + * check_stream): each delta a prefix of the finished value, the deltas adding up to it, the bytes + * held under the format's bound, and a closed call's arguments JSON. + * + * The object family itself -- JSON behind a name tag or a function tag -- is chatparse_test's. + */ +#include "rad_test.h" + +#include "chatdiff.h" +#include "rad_builder.h" +#include "sample/gbnf.h" +#include "sample/vocab_view.h" +#include "server/adapters.h" +#include "text/chat.h" +#include "text/chatfmt.h" +#include "text/chatparse.h" +#include "text/tokenizer.h" + +#include "../arch/gemma4_bf16/gemma4_chat_format.h" + +#include + +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace rad; +using namespace rad::chatdiff; +using json = nlohmann::ordered_json; + +/* ================================================================== fixtures */ + +static std::string fixture() { + std::ifstream f(std::string(RAD_CHAT_FIXTURES) + "/gemma4/chat_template.jinja"); + std::ostringstream ss; + ss << f.rdbuf(); + return ss.str(); +} + +/* The vocabulary's spellings: generation_config.json ends a turn on , and + * <|tool_response>. */ +static const Model& gemma() { + static const Model m = { "gemma4", "gemma4", "", "", + { "", "", "<|tool_response>" }, + gemma4_bf16::chat_format_decl() }; + return m; +} + +static Bench* bench(const ChatRequest& rq, const json& tools = agent_tools()) { + static std::map> cache; + const std::string key = describe(rq) + "|" + tools.dump(); + auto it = cache.find(key); + if (it != cache.end()) return it->second.get(); + auto b = std::make_unique(); + std::string why; + if (b->load(gemma(), fixture(), &why) < 0 || b->bind(rq, tools, &why) < 0) { + ::radtest::fail(__FILE__, __LINE__, "gemma4 (" + describe(rq) + "): " + why); + return nullptr; + } + return (cache[key] = std::move(b)).get(); +} + +static ChatRequest thinking(bool on) { + ChatRequest r; + r.thinking = on; + return r; +} + +static std::string quote(const std::string& s) { + return json(s).dump(-1, ' ', false, json::error_handler_t::replace); +} + +/* One call as the model writes it. `args` is the object's inside. */ +static std::string G(const std::string& name, const std::string& args) { + return "<|tool_call>call:" + name + "{" + args + "}"; +} +static const std::string Q = "<|\"|>"; +static std::string S(const std::string& text) { return Q + text + Q; } + +/* ================================================================== the streaming checks */ + +static std::vector every(size_t n, size_t step) { + std::vector c; + for (size_t i = step; i < n; i += step) c.push_back(i); + return c; +} + +/* Every cut of the reply against its one-shot parse: one piece, byte by byte, token-sized pieces, + * and every two-way split. */ +static std::string stream_all(const ReplyParser& p, const std::string& text) { + const ReplyMessage expect = reply_parse(p, text); + std::string err = check_stream(p, text, {}, expect); + if (err.empty()) err = check_stream(p, text, every(text.size(), 1), expect); + std::mt19937 rng(11); + for (int k = 0; err.empty() && k < 3; ++k) { + std::vector c; + for (size_t at = 1 + rng() % 5; at < text.size(); at += 1 + rng() % 7) c.push_back(at); + err = check_stream(p, text, c, expect); + } + for (size_t k = 1; err.empty() && k < text.size() && text.size() <= 2048; ++k) + err = check_stream(p, text, { k }, expect); + return err; +} + +static void streams(const ReplyParser& p, const std::string& text, const std::string& what) { + const std::string err = stream_all(p, text); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, what + ": " + err + "\n reply: " + quote(text)); + ++::radtest::checks(); +} + +static ReplyMessage parse(const ReplyParser& p, const std::string& text, bool* strict = nullptr) { + return reply_parse(p, text, strict); +} + +static std::shared_ptr parser(const std::string& gp, bool tools = true, + bool reasoning = true, bool parallel = true) { + static std::shared_ptr rf = [] { + ChatFormat f; + std::string why; + std::shared_ptr r; + if (chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why) < 0 || + ReplyFormat::compile(f, &r, &why) < 0) + ::radtest::fail(__FILE__, __LINE__, "gemma4 format: " + why); + return r; + }(); + ReplyOptions ro; + ro.generation_prompt = gp; + ro.extract_reasoning = reasoning; + ro.tools = tools ? &agent_tools() : nullptr; + ro.parallel_tool_calls = parallel; + ro.terminators = gemma().terminators; + std::shared_ptr p; + std::string why; + if (ReplyParser::create(rf, ro, &p, &why) < 0) + ::radtest::fail(__FILE__, __LINE__, "gemma4 parser: " + why); + return p; +} + +/* The three generation prompts a reply follows: a turn with thinking off (the template closes an + * empty channel), a turn with thinking on (the model opens its own), and the continuation after a + * tool response with thinking on (the template has opened the channel). With thinking off a + * continuation has no generation prompt at all. */ +static const std::string kOff = "<|turn>model\n<|channel>thought\n"; +static const std::string kOn = "<|turn>model\n"; +static const std::string kAfter = "<|channel>thought\n"; + +/* ================================================================== the declaration */ + +TEST(the_declaration_is_a_format_the_parser_runs) { + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why)); + CHECK_OK(chat_format_check(f, &why)); + CHECK(f.object_args()); + CHECK(f.reasoning_anywhere); + CHECK_EQ(f.object_string_open, Q); + CHECK_EQ(chat_format_describe(f), + std::string("plugin:gemma4: reasoning \"<|channel>thought\\n\"..\"\" " + "anywhere; calls \"<|tool_call>\"\"call:\"NAME\"\" {OBJECT, strings " + "\"<|\\\"|>\"..\"<|\\\"|>\", bare keys} \"\"\"\"; grammar on " + "\"<|tool_call>\"")); + /* What the decoder must render as text: every delimiter, the string's included -- without it + * a string argument reaches the parser with its quotes gone. */ + const std::vector m = chat_format_markers(f); + for (const char* want : { "<|channel>thought", "", "<|tool_call>", "", + "call:", "<|\"|>" }) + CHECK(std::find(m.begin(), m.end(), std::string(want)) != m.end()); +} + +/* A plugin compiled against the header before the object family reads its new fields as zero: + * the tagged family, no dialect, reasoning at the start only -- and Gemma's declaration read that + * way is refused by name rather than run wrongly. */ +TEST(an_older_struct_reads_the_object_fields_as_zero) { + RadChatFormat c = *gemma4_bf16::chat_format_decl(); + c.struct_size = (uint32_t)offsetof(RadChatFormat, args_form); + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(&c, &f, &why)); + CHECK(!f.object_args()); + CHECK(f.object_string_open.empty()); + CHECK(!f.object_bare_keys); + CHECK(!f.reasoning_anywhere); + CHECK(chat_format_check(f, &why) == RAD_E_UNSUPPORTED); + CHECK(why.find("name_suffix") != std::string::npos); +} + +TEST(an_object_format_the_parser_cannot_read_is_refused_by_name) { + auto refused = [](void (*edit)(RadChatFormat&), const char* word) { + RadChatFormat c = *gemma4_bf16::chat_format_decl(); + edit(c); + ChatFormat f; + std::string why; + if (chat_format_from_abi(&c, &f, &why) < 0) return false; + const bool no = chat_format_check(f, &why) == RAD_E_UNSUPPORTED; + if (!no || why.find(word) == std::string::npos) + ::radtest::fail(__FILE__, __LINE__, std::string("expected a refusal naming '") + + word + "', got: " + (no ? why : "accepted")); + return no; + }; + CHECK(refused([](RadChatFormat& c) { c.arg_prefix = ""; }, "arg_*")); + CHECK(refused([](RadChatFormat& c) { c.object_string_close = nullptr; }, "together")); + CHECK(refused([](RadChatFormat& c) { c.object_string_open = c.object_string_close = " "; }, + "whitespace")); + CHECK(refused([](RadChatFormat& c) { c.object_string_open = "q"; }, "bare word")); + CHECK(refused([](RadChatFormat& c) { + c.object_string_open = c.object_string_close = ""; c.call_close = ""; }, "closes the call")); + CHECK(refused([](RadChatFormat& c) { c.call_close = ""; }, "punctuation")); + CHECK(refused([](RadChatFormat& c) { c.call_close = "<|"; }, "told apart")); + CHECK(refused([](RadChatFormat& c) { c.args_form = 7; }, "RAD_CHAT_ARGS")); + CHECK(refused([](RadChatFormat& c) { c.reasoning_open = ""; }, "reasoning_anywhere")); + CHECK(refused([](RadChatFormat& c) { c.call_open = "<|channel>thought"; c.reasoning_breaks = nullptr; + c.n_reasoning_breaks = 0; }, "content")); + /* The tagged family is untouched: a dialect field there is refused, not ignored. */ + CHECK(refused([](RadChatFormat& c) { + c.args_form = RAD_CHAT_ARGS_TAGGED; + c.name_suffix = ">"; c.call_end = ""; c.arg_prefix = "render_reply(msg); + REQUIRE(!reply.empty()); + bool strict = false; + const ReplyMessage m = b->new_parse(reply, &strict); + const legacy::Answer o = b->old_parse(reply); + + /* The calls come back as the message had them, arguments as JSON values. */ + const size_t ncalls = msg.contains("tool_calls") ? msg["tool_calls"].size() : 0; + REQUIRE_EQ(m.calls.size(), ncalls); + for (size_t i = 0; i < ncalls; ++i) { + const json& want = msg["tool_calls"][i]["function"]; + CHECK_EQ(m.calls[i].name, want["name"].get()); + CHECK(m.calls[i].closed); + /* Compared as values: the template writes keys in sorted order. */ + CHECK(nlohmann::json::parse(m.calls[i].arguments) == + nlohmann::json::parse(want["arguments"].get())); + } + const std::string r = msg.contains("reasoning_content") ? msg["reasoning_content"].get() : ""; + CHECK_EQ(m.reasoning, r.empty() ? r : r + "\n"); + CHECK_EQ(m.content, msg["content"].get()); + + /* llama.cpp's parser reads the same calls and reasoning, byte for byte. Where the template + * wrote content AFTER the calls -- its order for a past turn, not the model's -- the old + * parser drops that content and the new one keeps it, leniently. */ + CHECK_EQ(o.calls.size(), m.calls.size()); + for (size_t i = 0; i < std::min(o.calls.size(), m.calls.size()); ++i) { + CHECK_EQ(o.calls[i].name, m.calls[i].name); + CHECK_EQ(o.calls[i].arguments, m.calls[i].arguments); + } + CHECK_EQ(o.reasoning, m.reasoning); + const bool after = ncalls > 0 && !msg["content"].get().empty(); + CHECK_EQ(strict, !after); + if (!after) CHECK_EQ(o.content, m.content); + streams(b->parser(), reply, "rendered reply"); + ++read; + } + CHECK(read > 10); +} + +/* Every prefix of a rendered reply -- a reply the decoder stopped anywhere -- streams to its own + * one-shot parse, and a call the reply ended inside reads back as its text. */ +TEST(every_truncation_of_a_rendered_reply_keeps_the_contract) { + Bench* b = bench(thinking(true)); + REQUIRE(b != nullptr); + for (const json& msg : rendered_corpus()) { + const std::string reply = b->render_reply(msg); + for (size_t n = 1; n <= reply.size(); n += 1 + n / 64) { + const std::string cut = sanitize(reply.substr(0, n)); + const std::string err = check_stream(b->parser(), cut, every(cut.size(), 3), + reply_parse(b->parser(), cut)); + if (!err.empty()) + ::radtest::fail(__FILE__, __LINE__, err + "\n reply: " + quote(cut)); + std::unique_ptr s = b->parser().open(); + s->feed(cut, nullptr); + s->finish(nullptr); + const ReplyMessage& m = s->message(); + if (!m.calls.empty() && !m.calls.back().closed) { + const std::string text = s->content_with_open_call(cut); + CHECK(text.find("<|tool_call>call:") != std::string::npos); + } + } + ++::radtest::checks(); + } +} + +/* ================================================================== the decided shapes + * + * Replies written the way the model writes them, and the ways it leaves its format. Each reads as + * stated, streams under the contract, and -- where `oracle` says so -- agrees with llama.cpp's + * parser byte for byte. */ + +struct Call { std::string name, args; bool closed = true; }; +struct Shape { + const char* what; + std::string gp; + std::string reply; + std::string content, reasoning; + std::vector calls; + bool strict; + bool oracle; /* llama.cpp's parser reads it the same */ +}; + +static std::vector shapes() { + const std::string ls = G("bash", "command:" + S("ls")); + const std::string LS = "{\"command\":\"ls\"}"; + std::vector v = { + { "an answer", kOff, "The answer is 4.", "The answer is 4.", "", {}, true, true }, + { "a call", kOff, ls, "", "", { { "bash", LS } }, true, true }, + { "a sentence, then a call", kOff, "Let me look.\n" + ls, "Let me look.", "", + { { "bash", LS } }, true, true }, + { "two calls", kOff, ls + G("read", "limit:40,path:" + S("/a")), "", "", + { { "bash", LS }, { "read", "{\"limit\":40,\"path\":\"/a\"}" } }, true, true }, + { "two calls on two lines", kOff, ls + "\n" + G("read", "path:" + S("/a")), "", "", + { { "bash", LS }, { "read", "{\"path\":\"/a\"}" } }, true, false }, + { "every kind of value", kOff, + G("configure", "extra:{a:[1,2,[]],b:{c:null},d:{}},label:" + S("") + + ",level:-1.5e3,mode:" + S("fast") + ",tags:[" + S("x") + "," + S("y") + + "],verbose:false"), + "", "", { { "configure", "{\"extra\":{\"a\":[1,2,[]],\"b\":{\"c\":null},\"d\":{}}," + "\"label\":\"\",\"level\":-1.5e3,\"mode\":\"fast\"," + "\"tags\":[\"x\",\"y\"],\"verbose\":false}" } }, true, true }, + { "a call that takes no arguments", kOff, G("ping", ""), "", "", { { "ping", "{}" } }, + true, true }, + { "a string holding what JSON escapes", kOff, + G("write", "content:" + S("a \"q\" \\ b\n\tc\x01 é 🚀") + ",path:" + S("/x")), "", "", + { { "write", "{\"content\":\"a \\\"q\\\" \\\\ b\\n\\tc\\u0001 é 🚀\",\"path\":\"/x\"}" } }, + true, true }, + { "a string holding the format's own punctuation", kOff, + G("write", "content:" + S("{a:1,} [<|tool_call>call:x()] <|\" .") + + ",path:" + S("/x")), "", "", + { { "write", "{\"content\":\"{a:1,} [<|tool_call>call:x()] <|\\\" .\"," + "\"path\":\"/x\"}" } }, true, true }, + /* Text ending in the start of the delimiter reads as written. (No grammar of this shape + * can write it -- llama.cpp's cannot either.) */ + { "a string ending in the start of its own delimiter", kOff, + G("write", "content:" + S("a <|\"") + ",path:" + S("/x")), "", "", + { { "write", "{\"content\":\"a <|\\\"\",\"path\":\"/x\"}" } }, true, true }, + /* llama.cpp's key rule takes everything up to the colon, delimiters included, and + * hands the client a key `<|"|>path<|"|>`. */ + { "a key written as a string", kOff, G("read", S("path") + ":" + S("/a")), "", "", + { { "read", "{\"path\":\"/a\"}" } }, true, false }, + /* And keeps the blank after a number, `"limit":3 }`, which is no JSON. */ + { "whitespace inside the object", kOff, G("read", " path: " + S("/a") + ",\n limit: 3 "), + "", "", { { "read", "{\"path\":\"/a\",\"limit\":3}" } }, true, false }, + + /* reasoning */ + { "thinking on: a thought, then an answer", kOn, + "<|channel>thought\nIt is two plus two.\nThe answer is 4.", "The answer is 4.", + "It is two plus two.\n", {}, true, true }, + { "thinking on: no thought at all", kOn, "The answer is 4.", "The answer is 4.", "", {}, + true, true }, + { "thinking on: a thought, then a call", kOn, + "<|channel>thought\nList it.\n" + ls, "", "List it.\n", { { "bash", LS } }, true, + true }, + { "a thought never closed before a call", kOn, "<|channel>thought\nList it.\n" + ls, "", + "List it.\n", { { "bash", LS } }, true, false }, + { "after a tool response, thinking on", kAfter, + "The tool says 18.\nIt is 18 degrees.", "It is 18 degrees.", + "The tool says 18.\n", {}, true, false }, + { "after a tool response, thinking off", "", "It is 18 degrees.", "It is 18 degrees.", "", + {}, true, false }, + { "an empty thought after the answer", kOff, "The answer is 4.<|channel>thought\n", + "The answer is 4.", "", {}, true, true }, + { "a thought in the middle of the answer", kOff, + "First.\n<|channel>thought\nhm\nSecond.", "First.\nSecond.", "hm\n", {}, true, + true }, + { "a close with no thought open", kOff, "The answer is 4.", "The answer is 4.", "", + {}, false, false }, + { "the turn's terminator left on", kOff, "The answer is 4.", "The answer is 4.", "", + {}, true, false }, + + /* leaving the object */ + { "a JSON string", kOff, G("bash", "command:\"ls -la\""), "", "", + { { "bash", "{\"command\":\"ls -la\"}" } }, false, false }, + /* Gemma's plain-quoted values are its own strings with, at most, the quotes escaped + * (measured: `code: "const s = \"a\nb\";"` for the JS `const s = "a\nb";`): an + * escaped quote is a quote, every other backslash is text. */ + { "a plain-quoted value with its quotes escaped", kOff, + G("bash", "command:\"a\\\"b\\\\c\\u00e9\\n\\q\""), "", "", + { { "bash", "{\"command\":\"a\\\"b\\\\\\\\c\\\\u00e9\\\\n\\\\q\"}" } }, false, + false }, + { "a plain-quoted value written verbatim", kOff, + G("write", "content:\"const s = \"a\\nb\"; f(\"x\", {y: 1});\",path:" + S("/x")), "", "", + { { "write", "{\"content\":\"const s = \\\"a\\\\nb\\\"; f(\\\"x\\\", {y: 1});\",\"path\":\"/x\"}" } }, + false, false }, + /* Measured: asked for nested arguments, the model writes Python's quotes. */ + { "single-quoted values, as served", kOff, + G("configure", "label: 'prod \"eu\"', extra: {note: 'x: {y}', tags: ['a,b', 'c}']}, mode: 'it\\'s'"), + "", "", { { "configure", "{\"label\":\"prod \\\"eu\\\"\",\"extra\":{\"note\":\"x: {y}\",\"tags\":[\"a,b\",\"c}\"]}," + "\"mode\":\"it's\"}" } }, false, false }, + { "a plain quote closed by the dialect's delimiter", kOff, G("bash", "command:\"ls" + Q), "", + "", { { "bash", "{\"command\":\"ls\"}" } }, false, false }, + /* The model leaves a string unclosed and writes the object's `}` and the call's close + * (measured: the close delimiter at p=0.86, `}` at p=0.08). The close ends the string and + * the call; the closers before it are the object's. */ + { "a string the model left open, as served", kOff, + "<|tool_call>call:execute{code:" + Q + "const s = \"line1\\nline2\"; console.log(...);}" + "<|channel>thought\n" + "<|tool_call>call:execute{code:" + Q + "const s = \"line1\\nline2\"; console.log(...);" + Q + + "}", "", "", + { { "execute", "{\"code\":\"const s = \\\"line1\\\\nline2\\\"; console.log(...);\"}" }, + { "execute", "{\"code\":\"const s = \\\"line1\\\\nline2\\\"; console.log(...);\"}" } }, + false, false }, + { "a string left open whose code ends in a brace", kOff, + "<|tool_call>call:bash{command:" + Q + "f() { return 1; }}", "", "", + { { "bash", "{\"command\":\"f() { return 1; }\"}" } }, false, false }, + { "a nested string left open", kOff, + "<|tool_call>call:configure{extra:{a:[" + Q + "x]}\n}" + G("bash", "command:" + S("ls")), + "", "", { { "configure", "{\"extra\":{\"a\":[\"x\"]}}" }, { "bash", "{\"command\":\"ls\"}" } }, + false, false }, + /* Thinking on, measured: the close spelled as a plain quote, and text after the call. */ + { "a string closed by a stray quote, text after the call", kOn, + "<|tool_call>call:bash{command:" + Q + "f(\"a\");\n\"}end", "end", "", + { { "bash", "{\"command\":\"f(\\\"a\\\");\\n\"}" } }, false, false }, + { "a string left open that ends in its own quote", kOff, + "<|tool_call>call:bash{command:" + Q + "say \"hi\"}", "", "", + { { "bash", "{\"command\":\"say \\\"hi\\\"\"}" } }, false, false }, + { "a string left open at the end of the reply", kOff, + "<|tool_call>call:bash{command:" + Q + "ls}", "", "", + { { "bash", "{\"command\":\"ls\"}" } }, false, false }, + { "code with quotes, backticks, a regex and braces", kOff, + G("bash", "command:" + S("const r = /\\d+\"}/g; `${a}` '{'") + ",x:1"), "", "", + { { "bash", "{\"command\":\"const r = /\\\\d+\\\"}/g; `${a}` '{'\",\"x\":1}" } }, true, true }, + { "Python literals", kOff, G("configure", "verbose:True,nothing:None"), "", "", + { { "configure", "{\"verbose\":true,\"nothing\":null}" } }, false, false }, + { "a bare word", kOff, G("configure", "mode:fast,level:01"), "", "", + { { "configure", "{\"mode\":\"fast\",\"level\":\"01\"}" } }, false, false }, + { "a trailing comma", kOff, G("read", "path:" + S("/a") + ","), "", "", + { { "read", "{\"path\":\"/a\"}" } }, false, false }, + { "a missing comma", kOff, G("read", "path:" + S("/a") + " limit:3"), "", "", + { { "read", "{\"path\":\"/a\",\"limit\":3}" } }, false, false }, + { "a key with no value", kOff, G("read", "path:,limit"), "", "", + { { "read", "{\"path\":null,\"limit\":null}" } }, false, false }, + { "the wrong closing bracket", kOff, G("configure", "tags:[" + S("x") + "}"), "", "", + { { "configure", "{\"tags\":[\"x\"]}" } }, false, false }, + { "an object the call's close cuts off", kOff, + "<|tool_call>call:configure{extra:{a:[1,{b:" + S("c") + "" + ls, "", "", + { { "configure", "{\"extra\":{\"a\":[1,{\"b\":\"c\"}]}}" }, { "bash", LS } }, false, false }, + /* llama.cpp's grammar has no arm for it and reads no call at all. */ + { "a call to a function that is not a tool", kOff, G("frobnicate", "x:1"), "", "", + { { "frobnicate", "{\"x\":1}" } }, false, false }, + { "a call written without its wrapper", kOff, "call:bash{command:" + S("ls") + "}", "", "", + { { "bash", LS } }, false, false }, + { "the name prefix in prose", kOff, "This is what I call: a plan, and call:me{ maybe.", + "This is what I call: a plan, and call:me{ maybe.", "", {}, true, true }, + { "a reply that ends inside a call", kOff, + "<|tool_call>call:write{path:" + S("/a") + ",content:" + Q + "half", "", "", + { { "write", "{\"path\":\"/a\",\"content\":\"half", false } }, true, false }, + }; + return v; +} + +TEST(what_gemma_writes_reads_as_decided) { + for (const Shape& s : shapes()) { + std::shared_ptr p = parser(s.gp); + bool strict = false; + const ReplyMessage m = parse(*p, s.reply, &strict); + const std::string tag = std::string(s.what) + ": " + quote(s.reply) + "\n got " + show(m); + if (m.content != s.content || m.reasoning != s.reasoning || m.calls.size() != s.calls.size() || + strict != s.strict) + ::radtest::fail(__FILE__, __LINE__, tag + (strict ? " (strict)" : " (lenient)")); + for (size_t i = 0; i < std::min(m.calls.size(), s.calls.size()); ++i) + if (m.calls[i].name != s.calls[i].name || m.calls[i].arguments != s.calls[i].args || + m.calls[i].closed != s.calls[i].closed) + ::radtest::fail(__FILE__, __LINE__, tag); + for (const ReplyCall& c : m.calls) + if (c.closed && !json::accept(c.arguments)) + ::radtest::fail(__FILE__, __LINE__, tag + "\n arguments are no JSON"); + streams(*p, s.reply, s.what); + } +} + +/* Where the reply is within the format, llama.cpp's own Gemma 4 parser -- run on the generation + * prompt and the reply, as its handler runs it -- reads exactly what this one reads. */ +TEST(the_shapes_in_the_format_read_as_llama_cpp_reads_them) { + int compared = 0; + for (const Shape& s : shapes()) { + if (!s.oracle) continue; + const bool on = s.gp == kOn; + Bench* b = bench(thinking(on)); + REQUIRE(b != nullptr); + REQUIRE_EQ(b->prompt().generation_prompt, s.gp); + const legacy::Answer o = b->old_parse(s.reply); + const ReplyMessage m = b->new_parse(s.reply); + bool same = !o.strict_failed && o.content == m.content && o.reasoning == m.reasoning && + o.calls.size() == m.calls.size(); + for (size_t i = 0; same && i < o.calls.size(); ++i) + same = o.calls[i].name == m.calls[i].name && o.calls[i].arguments == m.calls[i].arguments; + if (!same) + ::radtest::fail(__FILE__, __LINE__, std::string(s.what) + ": " + quote(s.reply) + + "\n old: " + show(o) + "\n new: " + show(m)); + ++compared; + } + CHECK(compared >= 15); +} + +/* ================================================================== the request switches */ + +TEST(thinking_off_starts_the_reply_after_the_closed_channel) { + Bench* b = bench(thinking(false)); + REQUIRE(b != nullptr); + CHECK_EQ(b->prompt().generation_prompt, kOff); + const ReasoningMarkers rm = b->parser().reasoning(); + CHECK_EQ(rm.open, std::string("<|channel>thought")); + CHECK_EQ(rm.close, std::string("")); + CHECK(!rm.starts_open); + + Bench* on = bench(thinking(true)); + REQUIRE(on != nullptr); + CHECK_EQ(on->prompt().generation_prompt, kOn); + CHECK(!on->parser().reasoning().starts_open); + /* The system turn carries the thinking switch. */ + CHECK(on->prompt().prompt.find("<|turn>system\n<|think|>\n") != std::string::npos); + CHECK(b->prompt().prompt.find("<|think|>") == std::string::npos); + + CHECK(parser(kAfter)->reasoning().starts_open); + CHECK(!parser("")->reasoning().starts_open); +} + +/* reasoning_format "none": the channel stays in the content as the model wrote it, and with it + * the call grammar's break -- a call still ends the text before it. */ +TEST(reasoning_format_none_keeps_the_channel_in_the_content) { + std::shared_ptr p = parser(kOn, true, /*reasoning=*/false); + const std::string reply = "<|channel>thought\nhm\nYes." + + G("bash", "command:" + S("ls")); + const ReplyMessage m = parse(*p, reply); + CHECK_EQ(m.content, std::string("<|channel>thought\nhm\nYes.")); + CHECK(m.reasoning.empty()); + REQUIRE_EQ(m.calls.size(), (size_t)1); + streams(*p, reply, "reasoning none"); +} + +/* A request that sent no tools reads call syntax as the text it is -- but the thought channel is + * still the model's reasoning, wherever it opens. */ +TEST(without_tools_a_call_is_text_and_a_late_channel_is_still_reasoning) { + std::shared_ptr p = parser(kOff, /*tools=*/false); + const std::string reply = "Use <|tool_call>call:bash{} to run it.<|channel>thought\nx\n"; + const ReplyMessage m = parse(*p, reply); + CHECK_EQ(m.content, std::string("Use <|tool_call>call:bash{} to run it.")); + CHECK_EQ(m.reasoning, std::string("x\n")); + CHECK(m.calls.empty()); + streams(*p, reply, "no tools"); +} + +TEST(parallel_tool_calls_false_still_reads_a_second_call) { + std::shared_ptr p = parser(kOff, true, true, /*parallel=*/false); + bool strict = true; + const ReplyMessage m = parse(*p, G("bash", "command:" + S("ls")) + G("bash", "command:" + S("pwd")), &strict); + CHECK_EQ(m.calls.size(), (size_t)2); + CHECK(!strict); +} + +/* ================================================================== a conversation + * + * The turn after a call: the assistant message carries the call, a `role: tool` message its + * result, and the template writes both into the model's own turn -- the call in the model's + * spelling, the result as a response block -- and leaves the turn open for the model to go on. */ +static json conversation(bool two_calls) { + json calls = json::array(); + calls.push_back({ { "id", "c1" }, { "type", "function" }, + { "function", { { "name", "read" }, { "arguments", "{\"path\":\"/a\",\"limit\":3}" } } } }); + if (two_calls) + calls.push_back({ { "id", "c2" }, { "type", "function" }, + { "function", { { "name", "bash" }, { "arguments", "{\"command\":\"ls\"}" } } } }); + json msgs = json::array({ { { "role", "user" }, { "content", "Read /a." } }, + { { "role", "assistant" }, { "content", "" }, { "tool_calls", calls } }, + { { "role", "tool" }, { "tool_call_id", "c1" }, { "content", "line one" } } }); + if (two_calls) + msgs.push_back({ { "role", "tool" }, { "tool_call_id", "c2" }, { "content", "a.txt" } }); + return msgs; +} + +TEST(a_tool_result_renders_into_the_open_turn_and_the_reply_goes_on) { + for (bool on : { false, true }) { + for (bool two : { false, true }) { + ChatTemplate t; + CHECK_OK(t.load(fixture(), "", "")); + ChatOptions opt; + opt.enable_thinking = on; + ChatPrompt p; + REQUIRE_EQ(t.apply(conversation(two), agent_tools(), opt, &p), RAD_OK); + const std::string want = + "<|turn>model\n<|tool_call>call:read{limit:3,path:<|\"|>/a<|\"|>}" + + std::string(two ? "<|tool_call>call:bash{command:<|\"|>ls<|\"|>}" : "") + + "<|tool_response>response:read{value:<|\"|>line one<|\"|>}" + + std::string(two ? "<|tool_response>response:bash{value:<|\"|>a.txt<|\"|>}" + : ""); + if (p.prompt.find(want) == std::string::npos) + ::radtest::fail(__FILE__, __LINE__, "the turn is not rendered as " + quote(want) + + "\n prompt: " + quote(p.prompt)); + /* The model goes on in the same turn: thinking off with nothing written for it, + * thinking on inside a channel the template opened. */ + CHECK_EQ(p.generation_prompt, std::string(on ? kAfter : "")); + CHECK(p.prompt.size() >= want.size() && + p.prompt.compare(p.prompt.size() - p.generation_prompt.size() - 0, + p.generation_prompt.size(), p.generation_prompt) == 0); + + std::shared_ptr rp = parser(p.generation_prompt); + const std::string reply = on ? "The file has one line.\nIt reads \"line one\"." + : "It reads \"line one\"."; + const ReplyMessage m = parse(*rp, reply); + CHECK_EQ(m.content, std::string("It reads \"line one\".")); + CHECK_EQ(m.reasoning, std::string(on ? "The file has one line.\n" : "")); + streams(*rp, reply, "after a tool result"); + } + } +} + +/* ================================================================== fuzz */ + +static std::vector fragments() { + return { "<|tool_call>", "", "call:", "call:bash", "call:read", "{", "}", "[", "]", + ",", ":", Q, "<|\"", "<|", "|>", "<|channel>thought\n", "", "<|channel>", + "\"", "\\", "\\u", "\\ud83d", "true", "None", "-1.5e3", "path", "command", "x", "\n", + " ", "中", "🚀", "", "", "<|tool_response>" }; +} + +TEST(fuzzed_replies_keep_the_contract) { + std::mt19937 rng(3); + const std::vector frag = fragments(); + const std::vector seeds = { + G("configure", "extra:{a:[1,{b:" + S("c") + "}]},tags:[" + S("x") + "]"), + "Sure.\n" + G("bash", "command:" + S("ls -la")) + G("read", "path:" + S("/a") + ",limit:3"), + "<|channel>thought\nPlan.\nDone.<|channel>thought\n", + G("write", "content:\"a\\nb\\u00e9\",path:" + S("/x")), + }; + int n = 0; + for (const std::string& gp : { kOff, kOn, kAfter }) { + std::shared_ptr p = parser(gp); + for (const std::string& seed : seeds) + for (int k = 0; k < 60; ++k) { + const std::string text = sanitize(mutate(rng, seed, frag)); + const std::string err = check_stream(*p, text, every(text.size(), 1), + reply_parse(*p, text)); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err + "\n reply: " + quote(text)); + ++n; + } + } + CHECK(n > 0); +} + +/* A long reply holds a bounded number of bytes, whatever it holds: a file written into a string + * streams as it arrives. */ +TEST(a_long_string_streams_and_holds_a_bounded_number_of_bytes) { + std::string file; + while (file.size() < 200000) file += " x = compute(a, b) # & \"quoted\" <| ]] \\n\n"; + const std::string reply = "<|channel>thought\nWriting it.\n" + + G("write", "content:" + S(file) + ",path:" + S("/big.py")); + std::shared_ptr p = parser(kOn); + const std::string err = check_stream(*p, reply, every(reply.size(), 7), reply_parse(*p, reply)); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err); + const ReplyMessage m = parse(*p, reply); + REQUIRE_EQ(m.calls.size(), (size_t)1); + CHECK(json::parse(m.calls[0].arguments)["content"] == file); +} + +/* ================================================================== the grammar */ + +static const SimpleVocab& printable() { + static const SimpleVocab v = [] { + SimpleVocab s; + for (int c = 32; c < 127; ++c) s.add(std::string(1, (char)c)); + s.add("\n"); + s.add("\t"); + return s; + }(); + return v; +} + +/* 1 complete, 0 admitted but unfinished or refused, -1 does not compile. */ +static int admits(const std::string& gbnf, const std::string& prefix, const std::string& text) { + std::unique_ptr gr; + std::string err; + if (GbnfGrammar::create(gbnf, "root", &printable(), false, {}, {}, &gr, &err) < 0) return -1; + if (gr->accept_str(prefix) < 0 || gr->accept_str(text) < 0) return 0; + return gr->complete() ? 1 : 0; +} + +static std::string grammar_for(const ChatGrammarRequest& gq) { + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why)); + ChatGrammar g; + CHECK_OK(chat_format_grammar(f, gq, &g, &why)); + return g.text; +} + +/* The lazy call grammar admits every call the template writes and every strict call above, as + * llama.cpp's own Gemma 4 grammar does; it refuses what leaves the dialect. */ +TEST(the_call_grammar_admits_what_the_model_writes_and_refuses_the_rest) { + Bench* b = bench(thinking(true)); + REQUIRE(b != nullptr); + ChatGrammarRequest gq; + gq.tools = &agent_tools(); + gq.generation_prompt = b->prompt().generation_prompt; + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(gemma4_bf16::chat_format_decl(), &f, &why)); + ChatGrammar g; + CHECK_OK(chat_format_grammar(f, gq, &g, &why)); + CHECK(g.lazy); + CHECK(g.trigger_words == std::vector{ "<|tool_call>" }); + const std::string& vendored = b->prompt().grammar; + + int seen = 0; + for (const json& msg : rendered_corpus()) { + std::string reply = b->render_reply(msg); + const size_t at = reply.find("<|tool_call>"); + if (at == std::string::npos) continue; + reply = reply.substr(at, reply.rfind("") + 12 - at); + if (reply.find_first_of("\x01") != std::string::npos) continue; + CHECK_EQ(admits(g.text, "", reply), 1); + CHECK_EQ(admits(vendored, "", reply), 1); + ++seen; + } + CHECK(seen > 8); + for (const Shape& s : shapes()) { + if (!s.strict || s.calls.empty() || s.reply.find("\x01") != std::string::npos) continue; + const size_t at = s.reply.find("<|tool_call>"); + if (at == std::string::npos || !s.calls.back().closed) continue; + const std::string calls = s.reply.substr(at, s.reply.rfind("") + 12 - at); + if (s.reply.find("\n<|tool_call>") != std::string::npos) continue; /* a line between calls */ + if (std::string(s.what) == "whitespace inside the object" || + std::string(s.what) == "a string ending in the start of its own delimiter") + continue; + if (admits(g.text, "", calls) != 1) + ::radtest::fail(__FILE__, __LINE__, std::string("refused: ") + s.what + " " + quote(calls)); + } + /* Python's quotes, as the model writes arguments it was handed as JSON. */ + CHECK_EQ(admits(g.text, "", G("bash", "command:'echo \"hi\" \\' {x}'")), 1); + CHECK_EQ(admits(g.text, "", G("configure", "extra:{tags:['a,b', 'c}']}")), 1); + for (const std::string& bad : { + G("bash", "command:ls"), /* a bare word */ + G("bash", "command:\"ls\""), /* a JSON string */ + G("bash", "command:" + S("ls") + ","), /* a trailing comma */ + "<|tool_call>call:bash{command:" + S("ls") + "", /* the object unclosed */ + G("frobnicate", "x:1"), /* not a tool */ + "<|tool_call>call:bash {command:" + S("ls") + "}", /* a space after the name */ + G("bash", "command:True"), + }) + CHECK_EQ(admits(g.text, "", bad), 0); +} + +/* tool_choice "required" makes the grammar the whole reply: from the generation prompt, an + * optional thought, then the calls and nothing after them; a named function admits that one, and + * parallel_tool_calls false one call. */ +TEST(a_required_call_is_the_whole_reply) { + for (const std::string& gp : { kOff, kOn }) { + ChatGrammarRequest gq; + gq.tools = &agent_tools(); + gq.generation_prompt = gp; + gq.require_call = true; + const std::string any = grammar_for(gq); + gq.parallel_tool_calls = false; + const std::string one = grammar_for(gq); + gq.parallel_tool_calls = true; + gq.only_tool = "read"; + const std::string rd = grammar_for(gq); + const std::string ls = G("bash", "command:" + S("ls")), ra = G("read", "path:" + S("/a")); + const std::string T = gp == kOn ? "<|channel>thought\nPlan.\n" : ""; + CHECK_EQ(admits(any, gp, T + ls), 1); + CHECK_EQ(admits(any, gp, T + ls + ra), 1); + CHECK_EQ(admits(any, gp, T + "The answer."), 0); + CHECK_EQ(admits(any, gp, T + ls + "Done."), 0); + CHECK_EQ(admits(one, gp, T + ls), 1); + CHECK_EQ(admits(one, gp, T + ls + ra), 0); + CHECK_EQ(admits(rd, gp, T + ra), 1); + CHECK_EQ(admits(rd, gp, T + ls), 0); + } +} + +TEST(a_response_format_is_the_whole_reply) { + const json schema = json::parse(R"({"type":"object","properties":{"n":{"type":"integer"}},"required":["n"]})"); + ChatGrammarRequest gq; + gq.json_schema = &schema; + gq.generation_prompt = kOff; + const std::string g = grammar_for(gq); + CHECK_EQ(admits(g, kOff, "{\"n\": 3}"), 1); + CHECK_EQ(admits(g, kOff, "```json\n{\"n\": 3}\n```"), 1); + CHECK_EQ(admits(g, kOff, "{\"n\": \"x\"}"), 0); +} + +/* ================================================================== the server's view + * + * The chat bridge serves the model from the plugin's declaration: tool requests are no longer + * refused, the grammar comes from the format, and the decoder renders the dialect's string + * delimiter -- a control token like the format's tags -- so the parser sees it. */ +static std::shared_ptr gemma_vocab() { + VocabBuild vb; + vb.tokens = { "", "", "", "a", "<|tool_call>", "", "<|tool_response>", + "", "<|\"|>", "<|channel>", "", "<|turn>", "", + "thought", "call:" }; + vb.types.assign(vb.tokens.size(), RAD_TT_CONTROL); + vb.types[3] = vb.types[13] = vb.types[14] = RAD_TT_NORMAL; + /* The letters the markers' text is spelled with, so a marker tokenises whole. */ + for (const char* c : { "t", "h", "o", "u", "g", "c", "l", ":" }) { + vb.tokens.push_back(c); + vb.types.push_back(RAD_TT_NORMAL); + } + vb.bos = 2; + vb.eos = 1; + vb.chat_template = fixture(); + /* generation_config.json: eos_token_id [1, 106, 50] -- here , , <|tool_response>. */ + vb.eos_ids = { 1, 12, 6 }; + auto v = std::make_shared(); + return v->load(std::move(vb)) >= 0 ? v : nullptr; +} + +TEST(the_chat_bridge_serves_gemma_from_its_declaration) { + std::shared_ptr v = gemma_vocab(); + REQUIRE(v != nullptr); + CHECK(v->is_eog(6)); /* <|tool_response>: after its calls the model stops there */ + server::ChatTemplateBridge br; + CHECK_OK(br.init(*v, gemma4_bf16::chat_format_decl(), "gemma4_bf16")); + CHECK(br.supports_tools()); + CHECK(br.tool_refusal().empty()); + + server::ChatRenderOptions opt; + opt.enable_thinking = false; + server::ChatRender r; + std::string why; + const json msgs = json::array({ { { "role", "user" }, { "content", "List /work." } } }); + REQUIRE_EQ(br.apply(msgs, agent_tools(), opt, &r, &why), RAD_OK); + CHECK_EQ(r.generation_prompt, kOff); + CHECK(r.grammar_lazy); + REQUIRE_EQ(r.grammar_triggers.size(), (size_t)1); + CHECK_EQ(r.grammar_triggers[0].value, std::string("<|tool_call>")); + CHECK(std::find(r.preserved_tokens.begin(), r.preserved_tokens.end(), Q) != r.preserved_tokens.end()); + CHECK(!r.think_starts_open); + REQUIRE(r.parser != nullptr); + + /* The decoder renders every control token the markers are made of, the string's among them; + * the turn's terminators it does not. */ + Detokenizer d(v, {}, false, r.preserved_tokens); + std::string text; + for (int32_t id : { 9, 13, 3, 10, 4, 14, 3, 8, 3, 8, 5 }) text += d.push(id); + text += d.flush(); + CHECK_EQ(text, std::string("<|channel>thoughta<|tool_call>call:a<|\"|>a<|\"|>")); + + std::unique_ptr rd = r.parser->open(); + std::vector deltas; + const std::string reply = "On it." + G("bash", "command:" + S("ls")); + for (char c : reply) rd->feed(std::string(1, c), &deltas); + rd->finish(&deltas); + const server::ParsedMessage pm = rd->message(); + CHECK_EQ(pm.content, std::string("On it.")); + REQUIRE_EQ(pm.tool_calls.size(), (size_t)1); + CHECK_EQ(pm.tool_calls[0].name, std::string("bash")); + CHECK_EQ(pm.tool_calls[0].arguments, std::string("{\"command\":\"ls\"}")); + CHECK(!pm.open_call); + std::string args; + int begins = 0, ends = 0; + for (const server::ReplyDelta& dl : deltas) { + if (dl.kind == server::ReplyDelta::CallBegin) ++begins; + if (dl.kind == server::ReplyDelta::CallArgs) args += dl.text; + if (dl.kind == server::ReplyDelta::CallEnd) ++ends; + } + CHECK_EQ(begins, 1); + CHECK_EQ(ends, 1); + CHECK_EQ(args, pm.tool_calls[0].arguments); + + /* A tool whose name the object's opening would end is refused at admission, by name. */ + const json bad = json::parse(R"([{"type":"function","function":{"name":"a{b"}}])"); + server::ChatRender rb; + CHECK(br.apply(msgs, bad, opt, &rb, &why) < 0); + CHECK(why.find("a{b") != std::string::npos); +} + +RAD_TEST_MAIN() diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index 33a8d075..6ebaa30a 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -1492,6 +1492,187 @@ TEST(a_template_whose_calls_cannot_be_described_refuses_tools_and_still_chats) { CHECK(!why.empty()); } +/* ================================================================== the object family + * + * A call written as its name and ONE object holding the arguments (ChatArgs::Object): JSON behind + * a name tag with neither an end nor a wrapper -- Mistral's `[TOOL_CALLS]NAME[ARGS]{...}` -- and + * behind a function tag that has its own close. The dialect fields (Gemma 4's strings and bare + * keys) are held in chatparse_gemma4_test, against the model's own template and llama.cpp's + * parser for it. */ + +static std::shared_ptr object_format(bool tagged_end, ChatFormat* out = nullptr) { + static const char* const kT1[] = { "[TOOL_CALLS]" }; + static const char* const kT2[] = { "" }; + RadChatFormat c{}; + c.struct_size = sizeof(RadChatFormat); + c.args_form = RAD_CHAT_ARGS_OBJECT; + if (!tagged_end) { + c.name = "test:name-tag"; + c.name_prefix = "[TOOL_CALLS]"; + c.name_suffix = "[ARGS]"; + c.triggers = kT1; + } else { + c.name = "test:function-tag"; + c.call_open = "\n"; + c.call_close = ""; + c.name_prefix = " rf; + std::shared_ptr p; + if (chat_format_from_abi(&c, &f, &why) < 0 || ReplyFormat::compile(f, &rf, &why) < 0) { + ::radtest::fail(__FILE__, __LINE__, why); + return nullptr; + } + if (out) *out = f; + ReplyOptions ro; + ro.tools = &agent_tools(); + if (ReplyParser::create(rf, ro, &p, &why) < 0) ::radtest::fail(__FILE__, __LINE__, why); + return p; +} + +static int object_admits(const std::string& gbnf, const std::string& text) { + static const SimpleVocab vocab = [] { + SimpleVocab v; + for (int c = 32; c < 127; ++c) v.add(std::string(1, (char)c)); + v.add("\n"); + return v; + }(); + std::unique_ptr gr; + std::string err; + if (GbnfGrammar::create(gbnf, "root", &vocab, false, {}, {}, &gr, &err) < 0) return -1; + if (gr->accept_str(text) < 0) return 0; + return gr->complete() ? 1 : 0; +} + +TEST(json_arguments_behind_a_name_tag_read_as_one_object) { + std::shared_ptr p = object_format(false); + REQUIRE(p != nullptr); + bool strict = false; + const std::string reply = "Sure.[TOOL_CALLS]bash[ARGS]{\"command\": \"ls -la\", \"timeout\": 30}" + "[TOOL_CALLS]read[ARGS]{\"path\": \"/a\", \"limit\": [1, {\"x\": null}]}"; + const ReplyMessage m = reply_parse(*p, reply, &strict); + CHECK(strict); + CHECK_EQ(m.content, std::string("Sure.")); + REQUIRE(m.calls.size() == 2); + CHECK_EQ(m.calls[0].arguments, std::string("{\"command\":\"ls -la\",\"timeout\":30}")); + CHECK_EQ(m.calls[1].arguments, std::string("{\"path\":\"/a\",\"limit\":[1,{\"x\":null}]}")); + const std::string err = stream_all(*p, reply); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err); + /* A bare key is outside JSON: read, and said so. */ + const ReplyMessage b = reply_parse(*p, "[TOOL_CALLS]read[ARGS]{path: \"/a\"}", &strict); + CHECK(!strict); + REQUIRE(b.calls.size() == 1); + CHECK_EQ(b.calls[0].arguments, std::string("{\"path\":\"/a\"}")); + /* No object after the tag: a call with none, and what stood there is content. */ + const ReplyMessage n = reply_parse(*p, "[TOOL_CALLS]ping[ARGS] and then", &strict); + CHECK(!strict); + REQUIRE(n.calls.size() == 1); + CHECK_EQ(n.calls[0].arguments, std::string("{}")); + CHECK_EQ(n.content, std::string("and then")); +} + +TEST(json_arguments_behind_a_function_tag_end_at_its_close) { + ChatFormat f; + std::shared_ptr p = object_format(true, &f); + REQUIRE(p != nullptr); + bool strict = false; + const std::string reply = "\n{\"command\": \"ls\"}\n" + "\n{\"path\": \"/a\"}\n\n"; + const ReplyMessage m = reply_parse(*p, reply, &strict); + CHECK(strict); + REQUIRE(m.calls.size() == 2); + CHECK_EQ(m.calls[0].arguments, std::string("{\"command\":\"ls\"}")); + CHECK_EQ(m.calls[1].arguments, std::string("{\"path\":\"/a\"}")); + const std::string err = stream_all(*p, reply); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err); + /* The function's close where the object was still open closes it. */ + const ReplyMessage c = reply_parse( + *p, "\n{\"path\": \"/a\"\n", &strict); + CHECK(!strict); + REQUIRE(c.calls.size() == 1); + CHECK(c.calls[0].closed); + CHECK_EQ(c.calls[0].arguments, std::string("{\"path\":\"/a\"}")); + + /* The grammar: a JSON object between the tags, and the tags as written. */ + ChatGrammarRequest gq; + gq.tools = &agent_tools(); + ChatGrammar g; + std::string why; + CHECK_OK(chat_format_grammar(f, gq, &g, &why)); + CHECK(g.lazy); + log_set_level(Log::Error); + CHECK_EQ(object_admits(g.text, "\n{\"command\": \"ls\", \"n\": [1, {\"a\": null}]}" + "\n"), 1); + CHECK_EQ(object_admits(g.text, "\n{command: \"ls\"}\n"), 0); + CHECK_EQ(object_admits(g.text, "\n{}\n"), 0); + log_set_level(Log::Warn); +} + +/* reasoning_anywhere: a block that opens after the answer is reasoning there too, and a close + * with no block open is not part of the answer. Without it, both are content. */ +TEST(a_reasoning_block_may_open_again_later_when_the_format_says_so) { + for (bool anywhere : { false, true }) { + RadChatFormat c = qwen_abi(); + c.reasoning_anywhere = anywhere ? 1 : 0; + ChatFormat f; + std::string why; + std::shared_ptr rf; + std::shared_ptr p; + CHECK_OK(chat_format_from_abi(&c, &f, &why)); + CHECK_OK(ReplyFormat::compile(f, &rf, &why)); + ReplyOptions ro; + ro.generation_prompt = "<|im_start|>assistant\n\n"; + ro.tools = &agent_tools(); + CHECK_OK(ReplyParser::create(rf, ro, &p, &why)); + const std::string reply = "Plan.\n\n\nAnswer.\nmore\n\n\nTail."; + bool strict = false; + const ReplyMessage m = reply_parse(*p, reply, &strict); + if (anywhere) { + CHECK_EQ(m.reasoning, std::string("Plan.\nmore\n")); + CHECK_EQ(m.content, std::string("Answer.Tail.")); + CHECK(!strict); /* the last closed nothing */ + } else { + CHECK_EQ(m.reasoning, std::string("Plan.\n")); + CHECK_EQ(m.content, std::string("Answer.\nmore\n\n\nTail.")); + } + const std::string err = stream_all(*p, reply); + if (!err.empty()) ::radtest::fail(__FILE__, __LINE__, err); + } +} + +TEST(an_object_format_the_parser_cannot_read_is_refused) { + auto refused = [](void (*edit)(RadChatFormat&), const char* word) { + static const char* const kT[] = { "[TOOL_CALLS]" }; + RadChatFormat c{}; + c.struct_size = sizeof(RadChatFormat); + c.args_form = RAD_CHAT_ARGS_OBJECT; + c.name_prefix = "[TOOL_CALLS]"; + c.name_suffix = "[ARGS]"; + c.triggers = kT; + c.n_triggers = 1; + edit(c); + ChatFormat f; + std::string why; + if (chat_format_from_abi(&c, &f, &why) < 0) return false; + return chat_format_check(f, &why) == RAD_E_UNSUPPORTED && why.find(word) != std::string::npos; + }; + CHECK(refused([](RadChatFormat&) {}, "") == false); /* the base is a format */ + CHECK(refused([](RadChatFormat& c) { c.arg_value_suffix = ""; }, "arg_*")); + CHECK(refused([](RadChatFormat& c) { c.object_string_open = ""; }, "together")); + CHECK(refused([](RadChatFormat& c) { c.object_string_open = c.object_string_close = "'"; }, + "bare word")); + CHECK(refused([](RadChatFormat& c) { c.call_end = "<,>"; }, "punctuation")); + CHECK(refused([](RadChatFormat& c) { c.call_end = " \n"; }, "only whitespace")); + CHECK(refused([](RadChatFormat& c) { c.name_prefix = ""; c.triggers = nullptr; c.n_triggers = 0; }, + "name_prefix is empty")); +} + /* ================================================================== cost * * The legacy path re-parses the whole reply on every chunk, so a reply of n bytes costs O(n^2). The diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index 0711eec5..aeec27c5 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -684,3 +684,164 @@ TEST(the_index_decides_which_shard_a_tensor_is_read_from) { std::remove((dir + "/" + f).c_str()); ::rmdir(dir.c_str()); } + +/* ================================================================== CT-INT4 */ +namespace { + +/* A compressed-tensors pack-quantized int4 weight as llm-compressor writes it: code (row n, column + * k) is the signed value q[n][k], stored unsigned about 8 as nibble k % 8 of int32 word [n, k / 8]; + * `X.weight_scale` is bf16 [N, K / group]. */ +struct Ct { + std::vector> q; /* [N][K] signed codes, -8..7 */ + std::vector scale; /* [N * K / group] */ + int64_t N = 0, K = 0, group = 0; +}; + +Ct make_ct(int64_t N, int64_t K, int64_t group, int seed) { + Ct c; + c.N = N; c.K = K; c.group = group; + c.q.assign((size_t)N, std::vector((size_t)K)); + for (int64_t n = 0; n < N; ++n) + for (int64_t k = 0; k < K; ++k) + c.q[(size_t)n][(size_t)k] = (int)((n * 7 + k * 3 + seed * 5 + (k * k) % 11) % 16) - 8; + for (int64_t i = 0; i < N * (K / group); ++i) + c.scale.push_back(rad_load_f32(std::vector{ rad_f32_to_bf16( + 0.01f * (float)(1 + (i * 13 + seed) % 29)) }.data(), RAD_BF16, 0)); + return c; +} + +void add_ct(std::vector* ts, const std::string& base, const Ct& c) { + T p{ base + ".weight_packed", "I32", { c.N, c.K / 8 }, {} }; + p.bytes.assign((size_t)(c.N * c.K / 2), 0); + for (int64_t n = 0; n < c.N; ++n) + for (int64_t k = 0; k < c.K; ++k) { + const uint32_t u = (uint32_t)(c.q[(size_t)n][(size_t)k] + 8); + uint32_t w; + std::memcpy(&w, p.bytes.data() + (n * (c.K / 8) + k / 8) * 4, 4); + w |= u << (4 * (k % 8)); + std::memcpy(p.bytes.data() + (n * (c.K / 8) + k / 8) * 4, &w, 4); + } + T s{ base + ".weight_scale", "BF16", { c.N, c.K / c.group }, {} }; + s.bytes.resize((size_t)(c.N * (c.K / c.group) * 2)); + for (size_t i = 0; i < c.scale.size(); ++i) rad_store_f32(s.bytes.data(), RAD_BF16, (int64_t)i, c.scale[i]); + ts->push_back(p); + ts->push_back(s); +} + +std::string ct_config(const char* symmetric, int group) { + return std::string("{\"model_type\":\"qwen4_exp\",\"quantization_config\":{\"quant_method\":" + "\"compressed-tensors\",\"format\":\"pack-quantized\",\"config_groups\":" + "{\"group_0\":{\"format\":\"pack-quantized\",\"targets\":[\"Linear\"]," + "\"weights\":{\"num_bits\":4,\"type\":\"int\",\"symmetric\":") + symmetric + + ",\"strategy\":\"group\",\"group_size\":" + std::to_string(group) + + ",\"dynamic\":false,\"actorder\":null}}}}}"; +} + +} /* namespace */ + +/* CT-INT4 IS IMPORTED: gate and up, each its own packed weight, become one `i4*bf16[1x32]` weight + * whose codes are the shipped ones made signed and whose scales are the shipped ones. Read as f32 + * it is the shipped value, the code less eight times its group's scale -- a code below eight is a + * negative weight, which an unsigned `code - 8` once turned into four billion. */ +TEST(a_ct_int4_weight_is_imported_as_its_signed_codes_and_scales) { + const Ct gate = make_ct(4, 64, 32, 1), up = make_ct(6, 64, 32, 2); + std::vector ts; + add_ct(&ts, "e.0.gate_proj", gate); + add_ct(&ts, "e.0.up_proj", up); + T plain = bf16("e.0.norm.weight", { 64 }, 1.0f); /* an ignored layer is an ordinary tensor */ + ts.push_back(plain); + const std::string dir = write_checkpoint(ts, ct_config("true", 32).c_str()); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK(ck.imports() == Checkpoint::Import::CtInt4); + CHECK(ck.import_refusal().empty()); + Program prog; + prog.name_map.push_back(map("gu", RAD_MAP_CONCAT, { "e.0.gate_proj.weight", "e.0.up_proj.weight" })); + prog.name_map.push_back(map("norm", RAD_MAP_COPY, { "e.0.norm.weight" })); + CkptWeight w; + std::string why; + REQUIRE_EQ(ckpt_resolve(ck, prog, "gu", false, &w, &why), RAD_OK); + REQUIRE(w.imported); + CHECK_EQ(w.rows, (int64_t)10); + CHECK_EQ(w.cols, (int64_t)64); + REQUIRE_EQ(w.enc.n_planes, 2); + CHECK_EQ(w.enc.plane[0].dtype, (uint32_t)RAD_I4); + CHECK_EQ(w.enc.plane[0].block[1], (int64_t)1); + CHECK_EQ(w.enc.plane[1].dtype, (uint32_t)RAD_BF16); + CHECK_EQ(w.enc.plane[1].block[1], (int64_t)32); + CHECK(rad_enc_valid(&w.enc)); + + std::vector codes((size_t)(10 * 32)), scales((size_t)(10 * 2 * 2)); + REQUIRE_EQ(ckpt_plane_rows(w, 0, 0, 10, codes.data(), &why), RAD_OK); + REQUIRE_EQ(ckpt_plane_rows(w, 1, 0, 10, scales.data(), &why), RAD_OK); + std::vector f((size_t)(10 * 64)); + REQUIRE_EQ(ckpt_rows_f32(w, 0, 10, f.data(), &why), RAD_OK); + int bad_code = 0, bad_scale = 0, bad_f = 0, negative = 0; + for (int64_t r = 0; r < 10; ++r) { + const Ct& c = r < 4 ? gate : up; + const int64_t n = r < 4 ? r : r - 4; + for (int64_t k = 0; k < 64; ++k) { + const int q = c.q[(size_t)n][(size_t)k]; + negative += q < 0; + if ((int)rad_load_f32(codes.data(), RAD_I4, r * 64 + k) != q) ++bad_code; + if (f[(size_t)(r * 64 + k)] != (float)q * c.scale[(size_t)(n * 2 + k / 32)]) ++bad_f; + } + for (int64_t g = 0; g < 2; ++g) + if (rad_load_f32(scales.data(), RAD_BF16, r * 2 + g) != c.scale[(size_t)(n * 2 + g)]) + ++bad_scale; + } + CHECK(negative > 0); + CHECK_EQ(bad_code, 0); + CHECK_EQ(bad_scale, 0); + CHECK_EQ(bad_f, 0); + + REQUIRE_EQ(ckpt_resolve(ck, prog, "norm", false, &w, &why), RAD_OK); + CHECK(w.trivial); + CHECK(!w.imported); + remove_checkpoint(dir); +} + +/* WHAT IS NOT READ IS REFUSED, NOT MISREAD: an asymmetric config, a zero point beside a weight a + * symmetric config describes, and a scale plane that is not one a group. */ +TEST(a_ct_int4_checkpoint_this_does_not_read_is_refused) { + const Ct c = make_ct(4, 64, 32, 3); + { + std::vector ts; + add_ct(&ts, "p", c); + const std::string dir = write_checkpoint(ts, ct_config("false", 32).c_str()); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + CHECK(ck.imports() == Checkpoint::Import::None); + CHECK(ck.import_refusal().find("symmetric") != std::string::npos); + remove_checkpoint(dir); + } + { + std::vector ts; + add_ct(&ts, "p", c); + ts.push_back(T{ "p.weight_zero_point", "I32", { 4, 1 }, std::vector(16, 0) }); + const std::string dir = write_checkpoint(ts, ct_config("true", 32).c_str()); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + Program prog; + prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" })); + CkptWeight w; + std::string why; + CHECK(ckpt_resolve(ck, prog, "p", false, &w, &why) != RAD_OK); + CHECK(why.find("zero point") != std::string::npos); + remove_checkpoint(dir); + } + { + std::vector ts; + add_ct(&ts, "p", c); /* scales a 32, the config says 16 */ + const std::string dir = write_checkpoint(ts, ct_config("true", 16).c_str()); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + Program prog; + prog.name_map.push_back(map("p", RAD_MAP_COPY, { "p.weight" })); + CkptWeight w; + std::string why; + CHECK(ckpt_resolve(ck, prog, "p", false, &w, &why) != RAD_OK); + CHECK(why.find("weight_scale") != std::string::npos); + remove_checkpoint(dir); + } +} diff --git a/tests/data/chat/gemma4/chat_template.jinja b/tests/data/chat/gemma4/chat_template.jinja new file mode 100644 index 00000000..4741bf6e --- /dev/null +++ b/tests/data/chat/gemma4/chat_template.jinja @@ -0,0 +1,390 @@ +{# + Template: Google Gemma 4 Canonical Chat Template + Author: Google Gemma Engineering Team + Published: 2026-07-09 + Context: Fixed tool-calling loops, turn closures, and thinking content-ordering. +#} +{%- macro format_parameters(properties, required, filter_keys=false) -%} + {%- set standard_keys = ['description', 'type', 'properties', 'required', 'nullable'] -%} + {%- set ns = namespace(found_first=false) -%} + {%- for key, value in properties | dictsort -%} + {%- set add_comma = false -%} + {%- if not filter_keys or key not in standard_keys -%} + {%- if ns.found_first %},{% endif -%} + {%- set ns.found_first = true -%} + {{ key }}:{ + {%- if value['description'] -%} + description:<|"|>{{ value['description'] }}<|"|> + {%- set add_comma = true -%} + {%- endif -%} + {%- if value['type'] | upper == 'STRING' -%} + {%- if value['enum'] -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + enum:{{ format_argument(value['enum']) }} + {%- endif -%} + {%- elif value['type'] | upper == 'ARRAY' -%} + {%- if value['items'] is mapping and value['items'] -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + items:{ + {%- set ns_items = namespace(found_first=false) -%} + {%- for item_key, item_value in value['items'] | dictsort -%} + {%- if item_value is not none -%} + {%- if ns_items.found_first %},{% endif -%} + {%- set ns_items.found_first = true -%} + {%- if item_key == 'properties' -%} + properties:{ + {%- if item_value is mapping -%} + {{- format_parameters(item_value, value['items']['required'] | default([])) -}} + {%- endif -%} + } + {%- elif item_key == 'required' -%} + required:[ + {%- for req_item in item_value -%} + <|"|>{{- req_item -}}<|"|> + {%- if not loop.last %},{% endif -%} + {%- endfor -%} + ] + {%- elif item_key == 'type' -%} + {%- if item_value is string -%} + type:{{ format_argument(item_value | upper) }} + {%- else -%} + type:{{ format_argument(item_value | map('upper') | list) }} + {%- endif -%} + {%- else -%} + {{ item_key }}:{{ format_argument(item_value) }} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + } + {%- endif -%} + {%- endif -%} + {%- if value['nullable'] %} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + nullable:true + {%- endif -%} + {%- if value['type'] | upper == 'OBJECT' -%} + {%- if value['properties'] is defined and value['properties'] is mapping -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + properties:{ + {{- format_parameters(value['properties'], value['required'] | default([])) -}} + } + {%- elif value is mapping -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + properties:{ + {{- format_parameters(value, value['required'] | default([]), filter_keys=true) -}} + } + {%- endif -%} + {%- if value['required'] -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + required:[ + {%- for item in value['required'] | default([]) -%} + <|"|>{{- item -}}<|"|> + {%- if not loop.last %},{% endif -%} + {%- endfor -%} + ] + {%- endif -%} + {%- endif -%} + {%- if add_comma %},{%- else -%} {%- set add_comma = true -%} {% endif -%} + type:<|"|>{{ value['type'] | upper }}<|"|>} + {%- endif -%} + {%- endfor -%} +{%- endmacro -%} +{%- macro format_function_declaration(tool_data) -%} + declaration:{{- tool_data['function']['name'] -}}{description:<|"|>{{- tool_data['function']['description'] -}}<|"|> + {%- set params = tool_data['function']['parameters'] -%} + {%- if params -%} + ,parameters:{ + {%- if params['properties'] -%} + properties:{ {{- format_parameters(params['properties'], params['required']) -}} }, + {%- endif -%} + {%- if params['required'] -%} + required:[ + {%- for item in params['required'] -%} + <|"|>{{- item -}}<|"|> + {{- ',' if not loop.last -}} + {%- endfor -%} + ], + {%- endif -%} + {%- if params['type'] -%} + type:<|"|>{{- params['type'] | upper -}}<|"|>} + {%- endif -%} + {%- endif -%} + {%- if 'response' in tool_data['function'] -%} + {%- set response_declaration = tool_data['function']['response'] -%} + ,response:{ + {%- if response_declaration['description'] -%} + description:<|"|>{{- response_declaration['description'] -}}<|"|>, + {%- endif -%} + {%- if response_declaration['type'] | upper == 'OBJECT' -%} + type:<|"|>{{- response_declaration['type'] | upper -}}<|"|>} + {%- endif -%} + {%- endif -%} + } +{%- endmacro -%} +{%- macro format_argument(argument, escape_keys=True) -%} + {%- if argument is none -%} + {{- 'null' -}} + {%- elif argument is string -%} + {{- '<|"|>' + argument + '<|"|>' -}} + {%- elif argument is boolean -%} + {{- 'true' if argument else 'false' -}} + {%- elif argument is mapping -%} + {{- '{' -}} + {%- set ns = namespace(found_first=false) -%} + {%- for key, value in argument | dictsort -%} + {%- if ns.found_first %},{% endif -%} + {%- set ns.found_first = true -%} + {%- if escape_keys -%} + {{- '<|"|>' + key + '<|"|>' -}} + {%- else -%} + {{- key -}} + {%- endif -%} + :{{- format_argument(value, escape_keys=escape_keys) -}} + {%- endfor -%} + {{- '}' -}} + {%- elif argument is sequence -%} + {{- '[' -}} + {%- for item in argument -%} + {{- format_argument(item, escape_keys=escape_keys) -}} + {%- if not loop.last %},{% endif -%} + {%- endfor -%} + {{- ']' -}} + {%- else -%} + {{- argument -}} + {%- endif -%} +{%- endmacro -%} +{%- macro strip_thinking(text) -%} + {%- set ns = namespace(result='') -%} + {%- for part in text.split('') -%} + {%- if '<|channel>' in part -%} + {%- set ns.result = ns.result + part.split('<|channel>')[0] -%} + {%- else -%} + {%- set ns.result = ns.result + part -%} + {%- endif -%} + {%- endfor -%} + {{- ns.result | trim -}} +{%- endmacro -%} + +{%- macro format_tool_response_block(tool_name, response) -%} + {{- '<|tool_response>' -}} + {%- if response is mapping -%} + {{- 'response:' + tool_name + '{' -}} + {%- for key, value in response | dictsort -%} + {{- key -}}:{{- format_argument(value, escape_keys=False) -}} + {%- if not loop.last %},{% endif -%} + {%- endfor -%} + {{- '}' -}} + {%- else -%} + {{- 'response:' + tool_name + '{value:' + format_argument(response, escape_keys=False) + '}' -}} + {%- endif -%} + {{- '' -}} +{%- endmacro -%} + +{#- ===== SETUP ===== -#} +{%- set ns = namespace(prev_message_type=None, prev_non_tool_role=None) -%} +{%- set loop_messages = messages -%} +{%- set enable_thinking = enable_thinking | default(false) -%} +{%- set preserve_thinking = preserve_thinking | default(false) -%} +{{- bos_token -}} +{#- Handle System/Tool Definitions Block -#} +{%- if enable_thinking or tools or (messages and messages[0]['role'] in ['system', 'developer']) -%} + {{- '<|turn>system\n' -}} + {#- Inject Thinking token at the very top of the FIRST system turn -#} + {%- if enable_thinking -%} + {{- '<|think|>\n' -}} + {%- set ns.prev_message_type = 'think' -%} + {%- endif -%} + {%- if messages and messages[0]['role'] in ['system', 'developer'] -%} + {%- if messages[0]['content'] is string -%} + {{- messages[0]['content'] | trim -}} + {%- elif messages[0]['content'] is sequence -%} + {%- for item in messages[0]['content'] -%} + {{- item['text'] | trim + ' '-}} + {%- endfor -%} + {%- endif -%} + {%- set loop_messages = messages[1:] -%} + {%- endif -%} + {%- if tools -%} + {%- for tool in tools %} + {{- '<|tool>' -}} + {{- format_function_declaration(tool) | trim -}} + {{- '' -}} + {%- endfor %} + {%- set ns.prev_message_type = 'tool' -%} + {%- endif -%} + {{- '\n' -}} +{%- endif %} + +{#- Pre-scan: find last user message index for reasoning guard -#} +{%- set ns_turn = namespace(last_user_idx=-1) -%} +{%- for i in range(loop_messages | length) -%} + {%- if loop_messages[i]['role'] == 'user' -%} + {%- set ns_turn.last_user_idx = i -%} + {%- endif -%} +{%- endfor -%} + +{#- Loop through messages -#} +{%- for message in loop_messages -%} + {%- if message['role'] != 'tool' -%} + {%- set ns.prev_message_type = None -%} + {%- set role = 'model' if message['role'] == 'assistant' else message['role'] -%} + {#- Detect continuation using tracked state — O(1) instead of O(n) backward scan -#} + {%- set continue_same_model_turn = (role == 'model' and ns.prev_non_tool_role == 'assistant') -%} + {%- if not continue_same_model_turn -%} + {{- '<|turn>' + role + '\n' }} + + {%- endif -%} + + {#- Render reasoning/reasoning_content as thinking channel -#} + {%- set thinking_text = message.get('reasoning') or message.get('reasoning_content') -%} + {%- set thinking_gate = (loop.index0 > ns_turn.last_user_idx) or (preserve_thinking and message.get('tool_calls')) -%} + {%- if thinking_text and thinking_gate -%} + {{- '<|channel>thought\n' + thinking_text + '\n' -}} + {%- endif -%} + + {%- if message.get('tool_calls') -%} + {%- for tool_call in message.get('tool_calls') -%} + {%- set function = tool_call['function'] -%} + {{- '<|tool_call>call:' + function['name'] + '{' -}} + {%- if function['arguments'] is mapping -%} + {%- set ns_args = namespace(found_first=false) -%} + {%- for key, value in function['arguments'] | dictsort -%} + {%- if ns_args.found_first %},{% endif -%} + {%- set ns_args.found_first = true -%} + {{- key -}}:{{- format_argument(value, escape_keys=False) -}} + {%- endfor -%} + {%- elif function['arguments'] is none -%} + {%- else -%} + {{- raise_exception( + "chat_template: tool_calls[].function.arguments must be a " + "JSON object (mapping), not a string. Deserialize arguments " + "before passing to the template." + ) -}} + {%- endif -%} + {{- '}' -}} + {%- endfor -%} + {%- set ns.prev_message_type = 'tool_call' -%} + {%- endif -%} + + {%- set ns_tr_out = namespace(flag=false) -%} + {%- if message.get('tool_responses') -%} + {#- Legacy: tool_responses embedded on the assistant message (Google/Gemma native) -#} + {%- for tool_response in message.get('tool_responses') -%} + {{- format_tool_response_block(tool_response['name'] | default('unknown', true), tool_response['response']) -}} + {%- set ns_tr_out.flag = true -%} + {%- set ns.prev_message_type = 'tool_response' -%} + {%- endfor -%} + {%- elif message.get('tool_calls') -%} + {#- OpenAI Chat Completions: forward-scan consecutive role:tool messages -#} + {%- set ns_tool_scan = namespace(stopped=false) -%} + {%- for k in range(loop.index0 + 1, loop_messages | length) -%} + {%- if ns_tool_scan.stopped -%} + {%- elif loop_messages[k]['role'] != 'tool' -%} + {%- set ns_tool_scan.stopped = true -%} + {%- else -%} + {%- set follow = loop_messages[k] -%} + {#- Resolve tool_call_id to function name -#} + {%- set ns_tname = namespace(name=follow.get('name') or 'unknown') -%} + {%- for tc in message.get('tool_calls') -%} + {%- if tc.get('id') == follow.get('tool_call_id') -%} + {%- set ns_tname.name = tc['function']['name'] -%} + {%- endif -%} + {%- endfor -%} + {#- Handle content as string or content-parts array -#} + {%- set tool_body = follow.get('content') -%} + {%- if tool_body is string -%} + {{- format_tool_response_block(ns_tname.name, tool_body) -}} + {%- elif tool_body is sequence and tool_body is not string -%} + {%- set ns_txt = namespace(s='') -%} + {%- for part in tool_body -%} + {%- if part.get('type') == 'text' -%} + {%- set ns_txt.s = ns_txt.s + (part.get('text') | default('')) -%} + {%- endif -%} + {%- endfor -%} + {{- format_tool_response_block(ns_tname.name, ns_txt.s) -}} + {%- for part in tool_body -%} + {%- if part.get('type') in ['image', 'image_url'] -%} + {{- '<|image|>' -}} + {%- elif part.get('type') in ['audio', 'input_audio'] -%} + {{- '<|audio|>' -}} + {%- elif part.get('type') == 'video' -%} + {{- '<|video|>' -}} + {%- endif -%} + {%- endfor -%} + {%- else -%} + {{- format_tool_response_block(ns_tname.name, tool_body) -}} + {%- endif -%} + {%- set ns_tr_out.flag = true -%} + {%- set ns.prev_message_type = 'tool_response' -%} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + + {%- set captured_content -%} + {%- if message.get('content') is string -%} + {%- if role == 'model' -%} + {{- strip_thinking(message['content']) -}} + {%- else -%} + {{- message['content'] | trim -}} + {%- endif -%} + {%- elif message.get('content') is sequence -%} + {%- for item in message['content'] -%} + {%- if item.get('type') == 'text' -%} + {%- if role == 'model' -%} + {{- strip_thinking(item['text']) -}} + {%- else -%} + {{- item['text'] | trim -}} + {%- endif -%} + {%- elif item.get('type') in ['image', 'image_url'] -%} + {{- '<|image|>' -}} + {%- elif item.get('type') in ['audio', 'input_audio'] -%} + {{- '<|audio|>' -}} + {%- elif item.get('type') == 'video' -%} + {{- '<|video|>' -}} + {%- endif -%} + {%- endfor -%} + {%- endif -%} + {%- endset -%} + + {{- captured_content -}} + {%- set has_content = captured_content | trim | length > 0 -%} + + {#- Forward-scan: find next non-tool message role for continuation detection -#} + {%- set next_nt = namespace(role=None, found=false) -%} + {%- for j in range(loop.index0 + 1, loop_messages | length) -%} + {%- if not next_nt.found -%} + {%- if loop_messages[j]['role'] != 'tool' -%} + {%- set next_nt.role = loop_messages[j]['role'] -%} + {%- set next_nt.found = true -%} + {%- endif -%} + {%- endif -%} + {%- endfor -%} + + {%- set continues_into_next = ( + role == 'model' + and next_nt.role == 'assistant' + and (not message.get('tool_calls') or ns_tr_out.flag) + ) -%} + + {%- if ns.prev_message_type == 'tool_call' and not ns_tr_out.flag -%} + {{- '<|tool_response>' -}} + {%- elif continues_into_next -%} + {%- elif not (ns_tr_out.flag and not has_content and not next_nt.found) -%} + {{- '\n' -}} + {%- endif -%} + + {#- Track previous non-tool role for next iteration (avoids O(n) backward scan) -#} + {%- set ns.prev_non_tool_role = message['role'] -%} + {%- endif -%} +{%- endfor -%} + +{%- if add_generation_prompt -%} + {%- if ns.prev_message_type != 'tool_response' and ns.prev_message_type != 'tool_call' -%} + {{- '<|turn>model\n' -}} + {%- if not enable_thinking -%} + {{- '<|channel>thought\n' -}} + {%- endif -%} + {%- elif ns.prev_message_type == 'tool_response' and enable_thinking -%} + {{- '<|channel>thought\n' -}} + {%- endif -%} +{%- endif -%} diff --git a/tests/legacy/chatdiff.cpp b/tests/legacy/chatdiff.cpp index c86fda88..6b820bc2 100644 --- a/tests/legacy/chatdiff.cpp +++ b/tests/legacy/chatdiff.cpp @@ -65,6 +65,11 @@ int Bench::load(const Model& m, const std::string& jinja, std::string* why) { *why = "the template did not compile"; return RAD_E_FORMAT; } + if (m.declared) { + const int st = chat_format_from_abi(m.declared, &fmt_, why); + if (st < 0) return st; + return ReplyFormat::compile(fmt_, &rf_, why); + } std::string refused; int st = chat_format_from_template(jinja, m.bos, m.eos, &fmt_, &refused, why); if (st < 0) return st; diff --git a/tests/legacy/chatdiff.h b/tests/legacy/chatdiff.h index 8a146d91..39654d4a 100644 --- a/tests/legacy/chatdiff.h +++ b/tests/legacy/chatdiff.h @@ -13,6 +13,8 @@ #include "text/chatparse.h" #include "toolparse_legacy.h" +struct RadChatFormat; + #include #include @@ -31,6 +33,9 @@ struct Model { std::string dir; /* under the fixture root */ std::string bos, eos; std::vector terminators; /* its end-of-generation spellings */ + /* The architecture plugin's reply format, when it declares one; null derives the format from + * the template, as the engine does. */ + const RadChatFormat* declared = nullptr; }; const std::vector& models(); diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index cfc9a324..53f458b0 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -943,6 +943,106 @@ TEST(kv_preemption_by_recompute_and_the_undeadlockable_request) { CHECK_OK(f.kv.ensure(newcomer, per)); } +/* THE WINDOW BEHIND A PREFIX HIT: a checkpoint slot carries window_blocks pages a WINDOW group, + * window_rows() names the pages a query at P reads from the table that wrote them, seed_window() + * gives a resumed sequence fresh pages at the same floor -- and a table whose floor moved past it + * answers false, which is the fallback (no snapshot, a full re-prefill). */ +TEST(kv_window_snapshot_rows_and_seed) { + std::vector g; + g.push_back(null_group()); + KVGroupInfo k; + k.name = "swa"; + k.decl.kind = RAD_KV_WINDOW; + k.decl.dtype = RAD_BF16; + k.decl.n_head_kv = 2; + k.decl.head_dim = 8; + k.decl.window = 64; + k.block_size = 16; + k.layers = { 0 }; + g.push_back(k); + Config cfg = small_config(); + Pools p; + CHECK_OK(p.configure(cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator())); + KVManager kv; + CHECK_OK(kv.configure(g, cfg, p.kv())); + CHECK(kv.has_window_snapshot()); + CHECK_EQ(kv.checkpoint_bytes(), 5 * kv.plan(G_FULL)->bytes_per_block); + + CHECK_OK(kv.add_sequence(1)); + CHECK_OK(kv.ensure(1, 400)); /* a prompt of 400 in one chunk */ + std::vector rows; + CHECK(kv.window_rows(1, 400, &rows)); + CHECK_EQ((long long)rows.size(), 5ll); /* padded to window_blocks */ + /* A query at 400 reads back to 337: blocks 21..24, the floor recycle_window keeps. */ + for (int j = 0; j < 4; ++j) CHECK_EQ(rows[(size_t)j], kv.block_table(1, G_FULL)[(size_t)(21 + j)]); + CHECK_EQ(rows[4], -1); + /* A short prefix: the window starts at zero and the rest is padding. */ + CHECK(kv.window_rows(1, 32, &rows)); + CHECK_EQ(rows[0], kv.block_table(1, G_FULL)[0]); + CHECK_EQ(rows[2], -1); + /* Not on a block: no rows. */ + CHECK(!kv.window_rows(1, 40, &rows)); + /* The floor moved past it (a decode step slid the window): the fallback. */ + CHECK_OK(kv.ensure(1, 401)); + CHECK(!kv.window_rows(1, 64, &rows)); + CHECK(kv.window_rows(1, 400, &rows)); + + /* A resumed sequence: seeded at the floor, extended from there, and its rows are its own. */ + CHECK_OK(kv.add_sequence(2)); + CHECK_OK(kv.seed_window(2, 400)); + CHECK_EQ(kv.first_block_pos(2, G_FULL), 336ll); + CHECK_EQ((long long)kv.block_table(2, G_FULL).size(), 4ll); + CHECK_EQ(kv.seq_tokens(2), 400ll); + CHECK_OK(kv.ensure(2, 432, 400)); + CHECK_EQ(kv.first_block_pos(2, G_FULL), 336ll); + CHECK_EQ((long long)kv.block_table(2, G_FULL).size(), 6ll); + std::vector rows2; + CHECK(kv.window_rows(2, 400, &rows2)); + for (int j = 0; j < 4; ++j) CHECK_EQ(rows2[(size_t)j], kv.block_table(2, G_FULL)[(size_t)j]); + /* A table already holding window pages is not seeded twice. */ + CHECK_EQ(kv.seed_window(2, 400), RAD_E_STATE); + kv.free_sequence(1); + kv.free_sequence(2); +} + +/* A SNAPSHOT ONLY WHERE A HIT RESUMES FROM IT: the trunk's window in a model with no linear state. + * A model with linear state re-prefills a hit on a windowed trunk, and a drafter's window is + * recomputed by draft refill, so a window section in either slot would be copied at every + * checkpoint and never read. */ +TEST(kv_window_snapshot_only_where_a_hit_resumes_from_it) { + KVGroupInfo w; + w.name = "swa"; + w.decl.kind = RAD_KV_WINDOW; + w.decl.dtype = RAD_BF16; + w.decl.n_head_kv = 2; + w.decl.head_dim = 8; + w.decl.window = 64; + w.block_size = 16; + w.layers = { 6 }; + const Config cfg = small_config(); + { /* beside linear state: the slot holds the state and nothing more */ + std::vector g = hybrid_groups(); + g.push_back(w); + Pools p; + CHECK_OK(p.configure(cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator())); + KVManager kv; + CHECK_OK(kv.configure(g, cfg, p.kv())); + CHECK(!kv.has_window_snapshot()); + CHECK_EQ(kv.checkpoint_bytes(), 16384ll); + } + { /* a drafter's own window over a full-attention trunk */ + std::vector g = hybrid_groups(/*with_linear=*/false); + w.drafter = true; + g.push_back(w); + Pools p; + CHECK_OK(p.configure(cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator())); + KVManager kv; + CHECK_OK(kv.configure(g, cfg, p.kv())); + CHECK(!kv.has_window_snapshot()); + CHECK_EQ(kv.checkpoint_bytes(), 0ll); + } +} + TEST(kv_window_group_recycles_below_the_window) { std::vector g; g.push_back(null_group()); @@ -965,19 +1065,60 @@ TEST(kv_window_group_recycles_below_the_window) { CHECK_OK(kv.configure(g, cfg, p.kv())); /* window 64 at block 16 is 4 blocks plus one for the straddle. */ CHECK_EQ(kv.plan(G_FULL)->window_blocks, 5ll); - /* Sized against the cap, not against the whole budget: blocks past the window are memory - * nobody will ever address. */ - CHECK_EQ(kv.total_blocks(G_FULL), cfg.max_seqs * 5); + /* Sized against the cap, not against the whole budget: a window a sequence plus one step's + * worth of tokens (max_tok) and a straddle block a sequence -- a chunk's own blocks are held + * beside the window behind its first query. Past that is memory nobody will ever address. */ + CHECK_EQ(kv.total_blocks(G_FULL), cfg.max_seqs * 5 + (cfg.max_tok + 15) / 16 + cfg.max_seqs); const int64_t n0 = kv.free_blocks(G_FULL); CHECK_OK(kv.add_sequence(1)); - CHECK_OK(kv.ensure(1, 80)); + CHECK_OK(kv.ensure(1, 80)); /* a chunk from 0: all of it held */ + CHECK_EQ(kv.first_block_pos(1, G_FULL), 0ll); CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 5ll); + /* A chunk from 80 to 400: its first query (80) reads back to 17, so block 1 stays and only + * block 0 goes -- NOT the window behind 400, which left rows 80..335 with no keys. */ CHECK_OK(kv.ensure(1, 400)); - CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 5ll); /* recycled, not grown */ + CHECK_EQ(kv.first_block_pos(1, G_FULL), 16ll); + CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 24ll); + /* A decode step from 400: back to the window, recycled rather than grown. */ + CHECK_OK(kv.ensure(1, 401)); + CHECK_EQ(kv.first_block_pos(1, G_FULL), 336ll); + CHECK_EQ((long long)kv.block_table(1, G_FULL).size(), 5ll); CHECK_EQ(kv.free_blocks(G_FULL), n0 - 5); kv.free_sequence(1); CHECK_EQ(kv.free_blocks(G_FULL), n0); + + /* THE PROMPT LONGER THAN THE WINDOW, in one chunk from 0: every position keeps its slot. The + * old rule rebased this table at ceil(400/16) - 5 = 20 blocks, and a sliding layer read no + * keys at all for positions 0..319. */ + CHECK_OK(kv.add_sequence(2)); + CHECK_OK(kv.ensure(2, 400)); + CHECK_EQ(kv.first_block_pos(2, G_FULL), 0ll); + CHECK_EQ((long long)kv.block_table(2, G_FULL).size(), 25ll); + /* And the scheduler's form names the step's first query itself: a chunk grown in the same + * step (ensure called twice) keeps what the first call's first query reads. */ + CHECK_OK(kv.ensure(2, 432, 400)); + CHECK_EQ(kv.first_block_pos(2, G_FULL), 336ll); + CHECK_OK(kv.ensure(2, 464, 400)); + CHECK_EQ(kv.first_block_pos(2, G_FULL), 336ll); + CHECK_EQ((long long)kv.block_table(2, G_FULL).size(), 8ll); + kv.free_sequence(2); + CHECK_EQ(kv.free_blocks(G_FULL), n0); + + /* A COMMITTED CHUNK GIVES ITS BLOCKS BACK at once: trim_window to the new end keeps the window + * behind it and nothing else, so a prefill that waits a step for its next chunk holds a window + * and not a chunk. */ + CHECK_OK(kv.add_sequence(3)); + CHECK_OK(kv.ensure(3, 400)); + CHECK_EQ((long long)kv.block_table(3, G_FULL).size(), 25ll); + kv.trim_window(3, 400); + CHECK_EQ(kv.first_block_pos(3, G_FULL), 336ll); + CHECK_EQ((long long)kv.block_table(3, G_FULL).size(), 4ll); + CHECK_EQ(kv.free_blocks(G_FULL), n0 - 4); + CHECK_OK(kv.ensure(3, 401)); + CHECK_EQ((long long)kv.block_table(3, G_FULL).size(), 5ll); + kv.free_sequence(3); + CHECK_EQ(kv.free_blocks(G_FULL), n0); } TEST(kv_conv_slot_is_a_rolling_window) { diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index c55b4cca..9fabb089 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -254,11 +254,11 @@ TEST(plugin_surface) { * which is a decision and not an oversight (docs/OPS.md). */ TEST(op_vocabulary) { static const char* kOps[] = { - "rmsnorm", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter", - "layernorm", "add", "mul", "mul_weight", "silu_mul", "act_mul", "seg_mean", "pool_rows", - "relu", "clamp", "conv2d", "conv1d_dw", "rel_sinusoid", "attn_local_rel", "gelu", "silu", - "sigmoid", "fill", "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv", - "causal_conv1d", + "rmsnorm", "rmsnorm_p", "rmsnorm_add", "hc_enter", "hc_read", "hc_write", "mtp_enter", + "layernorm", "add", "mul", "mul_weight", "silu_mul", "gelu_mul", "act_mul", "seg_mean", + "pool_rows", "relu", "clamp", "conv2d", "conv1d_dw", "rel_sinusoid", "attn_local_rel", + "gelu", "silu", "sigmoid", "logit_softcap", "scale", "fill", + "gather_rows", "scatter_rows", "ngram_ids", "ple_gate", "ple_conv", "causal_conv1d", "embed_lookup_q", "cast", "scale_rows", "softmax", @@ -450,6 +450,24 @@ TEST(op_rmsnorm) { CHECK_NEAR(y2.at(3), 4 * s, 1e-6); } +/* The weightless rmsnorm: same normalisation as rmsnorm with no gain, so the row divides by its + * rms and stops. The literals are exactly op_rmsnorm's, because a plain norm IS rmsnorm whose gain + * is one. */ +TEST(op_rmsnorm_p) { + T x(RAD_F32, {1, 4}); x.f({1, 2, 3, 4}); + T y(RAD_F32, {1, 4}); + A a; a.t(x).t(y).i("M", 1).i("n", 4).d("eps", 0).s("dtype", "f32"); + CHECK_OK(run("rmsnorm_p", a)); + /* rms = sqrt((1+4+9+16)/4) = sqrt(7.5) = 2.7386128 */ + const float s = 1.0f / 2.7386128f; + CHECK_NEAR(y.at(0), 1 * s, 1e-6); + CHECK_NEAR(y.at(3), 4 * s, 1e-6); + + /* A non-positive n is not a normalisation, so it is refused rather than answered. */ + A bb; bb.t(x).t(y).i("M", 1).i("n", 0).d("eps", 0).s("dtype", "f32"); + CHECK(run("rmsnorm_p", bb) != RAD_OK); +} + TEST(op_rmsnorm_add) { T x(RAD_F32, {1, 2}); x.f({1, 3}); T res(RAD_F32, {1, 2}); res.f({1, 1}); @@ -523,6 +541,70 @@ TEST(op_silu_mul_and_unary) { CHECK_NEAR(s.at(1), 0.73105858f, 1e-6); } +/* Gemma's gated FFN, on paper: same fused layout as silu_mul (gate the first half, up the second) + * but the gate runs the tanh GELU, not silu. gelu_tanh matches the gemm_nt_bias tanh epilogue and + * differs from the unary `gelu` (exact erf) -- the check at 1.0 pins that difference: erf gelu(1) is + * 0.84134..., the tanh form is 0.84119.... */ +TEST(op_gelu_mul) { + T gu(RAD_F32, {1, 4}); gu.f({1, 2, 3, 4}); /* gate [1,2], up [3,4] */ + T y(RAD_F32, {1, 2}); + A a; a.t(gu).t(y).i("M", 1).i("n", 2).s("dtype", "f32"); + CHECK_OK(run("gelu_mul", a)); + CHECK_NEAR(y.at(0), 0.84119199f * 3.0f, 1e-6); /* gelu_tanh(1) * up */ + CHECK_NEAR(y.at(1), 1.95459769f * 4.0f, 1e-6); /* gelu_tanh(2) * up */ + /* And the negative side, where tanh gelu and erf gelu drift furthest. */ + T gx(RAD_F32, {1, 4}); gx.f({-2, -1, 3, 4}); /* gate [-2,-1], up [3,4] */ + T gy(RAD_F32, {1, 2}); + A b; b.t(gx).t(gy).i("M", 1).i("n", 2).s("dtype", "f32"); + CHECK_OK(run("gelu_mul", b)); + CHECK_NEAR(gy.at(0), -0.04540231f * 3.0f, 1e-6); /* gelu_tanh(-2) * up */ + CHECK_NEAR(gy.at(1), -0.15880801f * 4.0f, 1e-6); /* gelu_tanh(-1) * up */ +} + +/* The final-logit softcap, on paper. `cap` at 30 -- Gemma's value -- and the input the kernel + * actually sees after a logits_gemm, reduced to the five ratios the formula can take: 0, cap/2, + * both signs of cap, and 2 cap. Every ratio is exact in f32, so the literals below are tanh of a + * small integer, and the check is the f32 rounding of the product and nothing else. */ +TEST(op_logit_softcap) { + T x(RAD_F32, {5}); x.f({ 0.0f, 15.0f, 30.0f, -30.0f, 60.0f }); + T y(RAD_F32, {5}); + A a; a.t(x).t(y).i("M", 1).i("n", 5).d("cap", 30.0).s("dtype", "f32"); + CHECK_OK(run("logit_softcap", a)); + CHECK_EQ(y.at(0), 0.0f); + CHECK_NEAR(y.at(1), 30.0f * 0.4621171573f, 1e-5); /* tanh(1/2) */ + CHECK_NEAR(y.at(2), 30.0f * 0.7615941560f, 1e-5); /* tanh(1) */ + CHECK_NEAR(y.at(3), -30.0f * 0.7615941560f, 1e-5); /* tanh(-1) */ + CHECK_NEAR(y.at(4), 30.0f * 0.9640275801f, 1e-5); /* tanh(2) */ + + /* A non-positive cap is a division by zero in every lane, so it is refused, not answered. */ + T y2(RAD_F32, {5}); + A b; b.t(x).t(y2).i("M", 1).i("n", 5).d("cap", 0.0).s("dtype", "f32"); + CHECK(run("logit_softcap", b) != RAD_OK); +} + +/* The per-tensor scalar scale. `s` is a [1] weight broadcast over every element, so the answer is + * a literal times the literal -- not a second call into the same multiply. The negative case is a + * scalar with no element: that is a shape error, not a broadcast of zero (a zero scalar would be a + * plausible number, which is the thing this file's rule exists to rule out). */ +TEST(op_scale) { + T x(RAD_F32, {5}); x.f({ 0.0f, 2.0f, 4.0f, -6.0f, 8.0f }); + T s(RAD_F32, {1}); s.f({ 3.0f }); + T y(RAD_F32, {5}); + A a; a.t(x).t(s).t(y).i("M", 1).i("n", 5).s("dtype", "f32"); + CHECK_OK(run("scale", a)); + CHECK_EQ(y.at(0), 0.0f); + CHECK_EQ(y.at(1), 6.0f); + CHECK_EQ(y.at(2), 12.0f); + CHECK_EQ(y.at(3), -18.0f); + CHECK_EQ(y.at(4), 24.0f); + + /* A scalar with no element is a shape error, not a broadcast of zero. */ + T s0(RAD_F32, {0}); + T y2(RAD_F32, {5}); + A b; b.t(x).t(s0).t(y2).i("M", 1).i("n", 5).s("dtype", "f32"); + CHECK(run("scale", b) != RAD_OK); +} + /* The quantised gather. Three things, and the scale is the least interesting of them. * * The E4M3 codes are chosen so their VALUES are exact and writable as literals: 0x38 is 1.0, @@ -1704,6 +1786,16 @@ TEST(op_vocab_edges) { CHECK_EQ(x.at(2), 1.0f); CHECK_EQ(x.at(3), 2.0f); CHECK_EQ(x.at(4), 0.0f); CHECK_EQ(x.at(5), 0.0f); /* a negative id is padding */ + /* A runtime gather scale multiplies the rows that are found; a missed row stays zero, not + * zero times the scale. Absent it, the lookup is the plain gather (the first block). */ + T xs(RAD_F32, {3, 2}); + A as; as.t(tok).t(wte).t(xs).i("M", 3).i("n_embd", 2).i("n_vocab", 3) + .s("dtype", "f32").d("mult", 2.0); + CHECK_OK(run("embed_lookup", as)); + CHECK_EQ(xs.at(0), 10.0f); CHECK_EQ(xs.at(1), 12.0f); + CHECK_EQ(xs.at(2), 2.0f); CHECK_EQ(xs.at(3), 4.0f); + CHECK_EQ(xs.at(4), 0.0f); CHECK_EQ(xs.at(5), 0.0f); + /* An id at or above n_vocab fails the launch rather than returning a plausible row. */ T bad(RAD_I32, {1}); bad.n({7}); T x2(RAD_F32, {1, 2}); @@ -2453,6 +2545,51 @@ TEST(op_rope_multi_component) { } } +/* THE PROPORTIONAL LADDER. With head_dim wider than rotary_dim, the two ladders give frequency 1 a + * different angle: `rotary` divides by rotary_dim, `head` by head_dim. And they pair different + * channels: `rotary` is a complete rotary of rotary_dim's own width, pair i = (i, i + rot/2) with + * the tail past rot untouched, while `head` is HF's proportional RoPE + * (_compute_proportional_rope_parameters + rotate_half over the WHOLE head): pair i is + * (i, i + head_dim/2) and every frequency past rot/2 is zero, so only those rot/2 pairs turn. + * Frequency 0 is theta^0 under both; frequency 1 pins the ladder, the partner index the pairing. */ +TEST(op_rope_ladder) { + const int64_t hd = 8, rot = 4; /* two frequencies, a partial rotary (hd > rot) */ + const float pos = 7.0f; + for (const char* lad : { "rotary", "head" }) { + const bool head = lad[0] == 'h'; + const int64_t den = head ? hd : rot; + const int64_t poff = head ? hd / 2 : rot / 2; /* where pair i's partner sits */ + T got(RAD_F32, { 1, hd }); + got.f(std::vector(hd, 1.0f)); + T p1(RAD_I32, { 1 }); p1.n({ 7 }); + A a; a.t(got).t(p1).i("M", 1).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 0) + .d("theta", 100).d("scale", 1).s("mode", "neox").i("rotary_dim", rot) + .s("ladder", lad); + CHECK_OK(run("rope", a)); + std::vector turned(hd, false); + for (int i = 0; i < rot / 2; ++i) { + const float inv = 1.0f / std::pow(100.0f, (float)(2 * i) / (float)den); + const float ang = pos * inv; + CHECK_NEAR(got.at(i), std::cos(ang) - std::sin(ang), 1e-5); + CHECK_NEAR(got.at(i + poff), std::sin(ang) + std::cos(ang), 1e-5); + turned[i] = turned[i + poff] = true; + } + for (int d = 0; d < hd; ++d) + if (!turned[d]) CHECK_EQ(got.at(d), 1.0f); /* every other channel untouched */ + } + /* absent ladder == rotary: the models that never set it keep the old angles bit-for-bit */ + { + T got(RAD_F32, { 1, hd }); + got.f(std::vector(hd, 1.0f)); + T p1(RAD_I32, { 1 }); p1.n({ 7 }); + A a; a.t(got).t(p1).i("M", 1).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 0) + .d("theta", 100).d("scale", 1).s("mode", "neox").i("rotary_dim", rot); + CHECK_OK(run("rope", a)); + const float ang = pos * (1.0f / std::pow(100.0f, (float)(2 * 1) / (float)rot)); + CHECK_NEAR(got.at(1), std::cos(ang) - std::sin(ang), 1e-5); + } +} + /* ALIGNED CORNERS: a grid's first and last rows and columns sit exactly on the table's, so a * corner patch reads one table row whole; an interior one blends four. */ TEST(op_grid_embed) { diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index eaf869fb..51898143 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -9,6 +9,7 @@ #include "rad_test.h" #include "sched/scheduler.h" +#include "sched/advance_impl.h" #include "sched/derive.h" #include "server/sink.h" @@ -499,7 +500,7 @@ struct Fixture { ~Fixture() { sch.fini(); for (void* p : owned) std::free(p); } void build(int64_t blocks = 4096, int64_t states = 64, int64_t max_tok = 512, - int64_t max_ctx = 4096) { + int64_t max_ctx = 4096, bool windowed = false) { g_gdn_ki = RadKernelInfo{}; g_gdn_ki.name = "gdn_fake"; g_gdn_ki.op = "gdn_chunked"; @@ -532,6 +533,25 @@ struct Fixture { conv.decl.conv_width = 4; prog.kv_groups.push_back(conv); + /* A WINDOWED paged group — the second half of the pair a sliding-window model declares + * (windowed layers + a full group; qwen35/llama windowed checkpoints declare these). + * Paged, block-aligned, and deliberately NOT prefix-cached: prefix.cpp indexes only the + * groups whose blocks below the window stay put. Tests that want a prefix cache over a + * WINDOW+FULL pair trim pc.groups to the cached ones. */ + if (windowed) { + KVGroupInfo win; + win.name = "swa"; + win.decl.kind = RAD_KV_WINDOW; + win.decl.window = 64; + win.block_size = 16; + win.layers = { 2 }; /* bound to a TRUNK layer — the group a trunk attention reads; + * a drafter's own group is bound at the trunk's layer count and + * above (rad_bind_layer_kv at the drafter declare) */ + prog.kv_groups.push_back(win); + prog.meta.n_layers = 16; /* trunk layers 0..15; the drafter tests' appended group + * stays unbound, and unbound is not trunk-owned */ + } + OpInfo op; op.op = "gdn_chunk_scan"; op.schema = &g_gdn_schema; @@ -659,6 +679,39 @@ TEST(chunk_geometry_rounds_the_checkpoint_interval_up_to_a_legal_chunk) { CHECK_EQ(f.sch.geometry().checkpoint_interval, 256); } +/* A MODEL WITH NO LINEAR STATE CHECKPOINTS ONLY FOR A TRUNK WINDOW: the snapshot of the window + * behind a prompt's tail is what a prefix hit resumes from. A drafter's own window is recomputed + * by draft refill, so it takes no checkpoint and leaves the hit at any block. */ +TEST(chunk_geometry_snapshots_a_trunk_window_and_not_a_drafters) { + for (int drafter = 0; drafter < 2; ++drafter) { + Program prog; + prog.meta.n_layers = 16; + prog.kv_groups.emplace_back(); + KVGroupInfo attn; + attn.name = "attn"; + attn.decl.kind = RAD_KV_FULL; + attn.block_size = 16; + attn.layers = { 0 }; + prog.kv_groups.push_back(attn); + KVGroupInfo win; + win.name = "swa"; + win.decl.kind = RAD_KV_WINDOW; + win.decl.window = 64; + win.block_size = 16; + win.layers = { drafter ? 16 : 1 }; + win.drafter = drafter != 0; + prog.kv_groups.push_back(win); + Config cfg; + cfg.max_tok = 512; + cfg.checkpoint_interval = 256; + cfg.prefix_cache = true; + ChunkGeometry g; + CHECK_OK(chunk_geometry_resolve(prog, cfg, &g)); + CHECK_EQ(g.checkpoint_interval, drafter ? 0ll : 256ll); + CHECK(g.window_ckpt == !drafter); + } +} + TEST(chunk_geometry_refuses_a_budget_it_cannot_serve) { Fixture f; f.build(); @@ -993,6 +1046,50 @@ TEST(a_hit_that_no_checkpoint_covers_replays_from_zero) { CHECK_EQ(f.sch.metrics().linear_cached_tokens, 0); } +/* THE PREFIX CACHE CANNOT COVER A MODEL WITH A PAGED GROUP IT DOES NOT INDEX. The fixture's + * groups are FULL, LINEAR, CONV, WINDOW — the windowed group is paged, bound to a trunk layer, + * and a real cache skips it (prefix.cpp: its blocks below the window are recycled, so no block + * list describes them), which is what pc.groups = {0} reproduces: three paged groups, one + * cached. The cache below is seeded to a DEEP, checkpoint-covered hit — 304 attention blocks, + * the linear state at 256, a slot to restore from — the most legitimate hit there is: every + * clamp above the trunk one lets it through untouched. The adopted blocks cover group 0 ONLY, + * while used = ctx_len + n_tok makes the windowed trunk layers read the positions below ctx_len + * this sequence never wrote — and the pool hands out the most recently freed blocks, i.e. the + * previous tenant's. That is reading ANOTHER REQUEST'S KV AS YOUR OWN PREFIX: fluent text + * carrying the last request's content. No tail-recompute repairs a trunk hole (a drafter's own + * hole is another matter, and the refill tests above keep theirs); the hit is refused. */ +TEST(a_hit_on_a_model_with_a_windowed_group_reuses_nothing) { + Fixture f; + f.build(4096, 64, 512, 4096, /*windowed=*/true); + f.pc.groups = {0}; /* a cache that indexes the FULL group only — windowed groups are not + * prefix-cacheable; must precede start(), which reads it once */ + CHECK_OK(f.start()); + f.pc.seed(304); /* a deep, block-aligned attention hit: 19 blocks */ + f.pc.lin = 256; /* its linear state checkpoints at 256 — the resume point exists */ + f.pc.src = 3; /* and names a snapshot, so no checkpoint clamp applies */ + + uint64_t a = f.submit(300, 8); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + + /* The whole hit is refused, not trimmed: the request runs from zero. */ + CHECK_EQ(f.sch.find(a)->n_computed, 0); + CHECK_EQ(f.sch.find(a)->n_cached, 0); + CHECK_EQ(b->ctx_lens[0], 0); + CHECK_EQ(f.sch.plan().e[0].ckpt_restore, -1); + + /* NOTHING IS ADOPTED — the 16 blocks covering the 256-token chunk are all freshly grabbed. */ + CHECK_EQ((int)f.kv.block_table(a, 0).size(), 16); + CHECK(std::find(f.pc.seeded[0].begin(), f.pc.seeded[0].end(), + f.kv.block_table(a, 0)[0]) == f.pc.seeded[0].end()); + + /* THE CACHE STILL REPORTED THE MATCH, and the metrics say so: this is a real hit the + * scheduler refused, not a lookup that found nothing. */ + SchedMetrics m = f.sch.metrics(); + CHECK_EQ(m.attn_cached_tokens, 304); + CHECK_EQ(m.linear_cached_tokens, 0); +} + /* ================================================================== preemption */ /* A REQUEST WHOSE CONTEXT IS STILL BEING READ OFF DISK WAITS, AND ONLY IT DOES. It is not admitted * short -- the hit length is what its prefill is shaped by -- and it does not hold up the queue: @@ -1358,7 +1455,11 @@ RefillRun refill_run(int n_prompt, int32_t seeded, int64_t ckpt_lo = 0) { f.cfg.n_spec = 7; f.prog.drafter.kind = RAD_DRAFT_BLOCK; f.prog.drafter.window = 512; - KVGroupInfo w; /* the drafter's own group: paged, windowed, not prefix-cached */ + KVGroupInfo w; /* the drafter's own group: paged, windowed, not prefix-cached. + * UNBOUND, and a drafter group bound at the trunk's layer count + * and above is the same — the trunk clamp reads bound TRUNK + * layers (scheduler.h, hit_holes_trunk_) and does not fire on a + * drafter hole: the refill below is exactly its repair. */ w.name = "draft"; w.decl.kind = RAD_KV_WINDOW; w.decl.window = 512; @@ -3014,6 +3115,202 @@ TEST(the_history_pass_carries_draft_round_one) { f.sch.serial_end(2); } +/* THE SERIAL DRIVER'S TWO SHAPES, side by side over one verify step. A head with a cache of its own + * (every drafter but one) owes the history of every verified position and steps one position a + * round; a head that reads the trunk's cache and keeps none (rad_drafter_shared_kv) owes nothing, + * runs one row a drafting sequence, and does not step. The first half of this is the old path and + * must not move: it is what Qwen's MTP head is staged with. */ +namespace { +struct SerialShape { + int hist_tok = 0, hist_out = 0, hist_dout = 0; + int32_t hist_ctx = 0, hist_row = 0; + int32_t round_ctx[4] = {0, 0, 0, 0}; +}; + +void serial_shape(bool shared, SerialShape& r) { + Fixture f; + f.build(/*blocks=*/4096, /*states=*/64); + f.cfg.n_spec = 4; + f.prog.drafter.kind = RAD_DRAFT_SERIAL; + f.prog.drafter.depth = 4; + f.prog.drafter_shared_kv = shared; + CHECK_OK(f.start()); + + const uint64_t a = f.submit(160, 64); + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + int32_t draft[4] = { 21, 22, 23, 24 }; + CHECK_OK(f.sch.set_draft(a, draft, 4)); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + CHECK_EQ(b->n_spec, 4); + + int rounds = 4; + Scheduler::SerialRow rows[4]; + CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 1); + const RadBatch* hb = f.sch.serial_batch(0, 1); + REQUIRE(hb != nullptr); + CHECK(hb->draft_pass < 0); + r.hist_tok = (int)hb->n_tok; + r.hist_out = (int)hb->n_out; + r.hist_dout = (int)hb->n_draft_out; + r.hist_ctx = hb->ctx_lens[0]; + r.hist_row = hb->out_ids[0]; + for (int rd = 2; rd <= 3; ++rd) { + const RadBatch* rb = f.sch.serial_batch(rd, 1); + REQUIRE(rb != nullptr); + CHECK_EQ(rb->n_tok, 1); + r.round_ctx[rd] = rb->ctx_lens[0]; + } + f.sch.serial_end(3); +} +} /* namespace */ + +TEST(a_head_with_a_cache_of_its_own_is_staged_as_it_always_was) { + SerialShape o; + serial_shape(false, o); + CHECK_EQ(o.hist_tok, 5); /* every verified position */ + CHECK_EQ(o.hist_out, 5); /* one trunk row each */ + CHECK_EQ(o.hist_dout, 1); + CHECK_EQ(o.hist_ctx, 160); /* the history starts at the first verified one */ + CHECK_EQ(o.hist_row, 0); /* the verify step's first row */ + CHECK_EQ(o.round_ctx[2], 165); /* the furthest round 2 can sit: one past the last */ + CHECK_EQ(o.round_ctx[3], 166); /* ...and the head steps one position a round */ +} + +TEST(a_head_with_no_cache_of_its_own_runs_one_row_and_stays_put) { + SerialShape s; + serial_shape(true, s); + CHECK_EQ(s.hist_tok, 1); /* round 1 alone */ + CHECK_EQ(s.hist_out, 1); + CHECK_EQ(s.hist_dout, 1); + CHECK_EQ(s.hist_ctx, 164); /* the furthest the committed position can be */ + CHECK_EQ(s.hist_row, 0); /* the run's first trunk row; the card adds acc */ + CHECK_EQ(s.round_ctx[2], 164); /* and every round stays there */ + CHECK_EQ(s.round_ctx[3], 164); +} + +/* A HEAD WITH NO CACHE OF ITS OWN IS OWED NO HISTORY: a prefill chunk that drafts nothing runs no + * pass for it at all, where a head with its own cache is given the whole chunk. */ +TEST(a_head_with_no_cache_of_its_own_runs_no_pass_when_nothing_drafts) { + for (int shared = 0; shared < 2; ++shared) { + Fixture f; + f.build(/*blocks=*/10, /*states=*/64); /* exactly the prompt: nothing to look ahead into */ + f.cfg.n_spec = 4; + f.prog.drafter.kind = RAD_DRAFT_SERIAL; + f.prog.drafter.depth = 4; + f.prog.drafter_shared_kv = shared != 0; + CHECK_OK(f.start()); + f.submit(160, 64); + CHECK(f.sch.step() != nullptr); + f.commit_plain(); + int rounds = 4; + Scheduler::SerialRow rows[4]; + CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 0); + const RadBatch* hb = f.sch.serial_batch(0, 1); + if (shared) { + CHECK(hb == nullptr); + } else { + REQUIRE(hb != nullptr); + CHECK_EQ(hb->n_tok, 160); + } + f.sch.serial_end(0); + } +} + +/* WHAT THE CARD WRITES INTO A DRAFT PASS, row by row (advance_impl.h), for both shapes. One verify + * step at positions 101..105 accepted two drafts, so the committed position is 103 and the trunk + * chose token 7003 there; the block table maps position p to slot p. A head with a cache of its own + * gets the verified run with its tail repeated and a context that runs to its end; a head with no + * cache of its own gets the committed position and a context that ends there, in every round. */ +namespace { +struct AdvSlab { + alignas(16) int32_t w[512] = {}; + rad::StepSlot st{}; + int32_t src[8] = { 7001, 7002, 7003, 7004, 7005, 0, 0, 0 }; + rad::AdvanceArgs a; + + /* word offsets */ + enum { ROWS = 0, TOK = 8, POS = 16, CTX = 24, ACC = 28, OUT = 32, SID = 40, CU = 44, Q = 48, + GRP = 64, SLOT = 96, USED = 104, BT = 112, FIRST = 128 }; + + AdvSlab(int mode, int n_rows, int round, bool shared, int shift) { + a.mode = mode; + a.round = round; + a.n_seq = 1; + a.n_groups = 1; + a.slab = reinterpret_cast(w); + a.row_off = ROWS * 4; a.row_pitch = 1; + a.tok_off = TOK * 4; a.pos_off = POS * 4; a.ctx_off = CTX * 4; a.acc_off = ACC * 4; + a.out_off = OUT * 4; a.sid_off = SID * 4; a.cu_off = CU * 4; a.q_off = Q * 4; + a.grp_off = GRP * 4; + a.st = &st; + a.src = src; + a.shared_kv = shared ? 1 : 0; + a.rot_shift = shift; + w[ROWS + 0] = 1; /* a device row */ + w[ROWS + 1] = 0; /* its first verified token row */ + w[ROWS + 2] = 0; /* its first sampled row */ + w[ROWS + 3] = 0; /* no history before the verified positions */ + w[SID] = 0; w[CU] = 0; w[Q] = n_rows; + w[OUT] = 40; /* the host staged the run's first trunk row */ + rad::AdvGroup g{}; + g.block_size = 16; g.paged = 1; g.pitch = 16; + g.slot_off = SLOT * 4; g.used_off = USED * 4; g.bt_off = BT * 4; g.first_off = FIRST * 4; + std::memcpy(&w[GRP], &g, sizeof g); + for (int i = 0; i < 16; ++i) w[BT + i] = i; /* block i holds positions 16i.. */ + w[FIRST] = 0; + st.head = 103; st.acc = 2; st.ctx = 104; st.n_acc = 3; st.tok[0] = 7003; + } +}; +} /* namespace */ + +TEST(the_card_stages_a_cacheless_head_at_the_committed_position) { + /* The history pass. */ + { + AdvSlab o(rad::ADV_HIST, 5, 0, false, 0); + rad::adv_row(o.a, 0); + const int32_t pos[5] = { 101, 102, 103, 103, 103 }, tok[5] = { 7001, 7002, 7003, 7003, 7003 }; + for (int j = 0; j < 5; ++j) { + CHECK_EQ(o.w[AdvSlab::POS + j], pos[j]); + CHECK_EQ(o.w[AdvSlab::TOK + j], tok[j]); + CHECK_EQ(o.w[AdvSlab::OUT + j], 40 + (j < 2 ? j : 2)); + CHECK_EQ(o.w[AdvSlab::SLOT + j], pos[j]); + } + CHECK_EQ(o.w[AdvSlab::USED], 106); /* the verify step's whole run */ + CHECK_EQ(o.w[AdvSlab::CTX], 101); + } + for (int shift = 0; shift < 2; ++shift) { + AdvSlab s(rad::ADV_HIST, 1, 0, true, shift); + rad::adv_row(s.a, 0); + CHECK_EQ(s.w[AdvSlab::POS], 103 + shift); + CHECK_EQ(s.w[AdvSlab::TOK], 7003); + CHECK_EQ(s.w[AdvSlab::OUT], 42); + CHECK_EQ(s.w[AdvSlab::USED], 104); /* the committed positions and no more */ + CHECK_EQ(s.w[AdvSlab::CTX], 103); + } + /* Round 3: the old head two positions on, the cacheless one where it was. */ + { + AdvSlab o(rad::ADV_ROUND, 1, 3, false, 0); + o.src[0] = 9001; + rad::adv_row(o.a, 0); + CHECK_EQ(o.w[AdvSlab::POS], 105); + CHECK_EQ(o.w[AdvSlab::USED], 106); + CHECK_EQ(o.w[AdvSlab::TOK], 9001); + CHECK_EQ(o.st.tok[2], 9001); + } + for (int shift = 0; shift < 2; ++shift) { + AdvSlab s(rad::ADV_ROUND, 1, 3, true, shift); + s.src[0] = 9001; + rad::adv_row(s.a, 0); + CHECK_EQ(s.w[AdvSlab::POS], 103 + shift); + CHECK_EQ(s.w[AdvSlab::USED], 104); + CHECK_EQ(s.w[AdvSlab::CTX], 103); + CHECK_EQ(s.w[AdvSlab::TOK], 9001); + CHECK_EQ(s.st.tok[2], 9001); + } +} + /* A STEP IS ISSUED AHEAD OF A COMMIT ONLY FOR A REQUEST WHOSE SPECULATION THAT COMMIT CANNOT * CHANGE. The ahead step is sized before the commit in front of it, so a request the sampler has * not started yet -- whose grammar, if any, nobody has asked -- is not issued ahead; one whose diff --git a/tests/text_test.cpp b/tests/text_test.cpp index 4ce1292d..2a309a43 100644 --- a/tests/text_test.cpp +++ b/tests/text_test.cpp @@ -957,6 +957,26 @@ TEST(vocab_treats_an_out_of_range_special_id_as_absent) { CHECK_EQ(v->pad(), -1); } +/* The checkpoint's own end-of-generation list -- generation_config.json's eos_token_id, which the + * container carries as `generation.eos_token_id` -- ends a generation on every id it names: Gemma 4 + * names <|tool_response> there, where the model stops after its calls. An id naming no token is + * no id. */ +TEST(vocab_ends_a_generation_on_every_id_the_checkpoint_names) { + VocabBuild vb; + vb.kind = RAD_TOK_BPE; + vb.tokens = { "a", "", "<|tool_response>", "<|tool_call>" }; + vb.types = { RAD_TT_NORMAL, RAD_TT_CONTROL, RAD_TT_CONTROL, RAD_TT_CONTROL }; + vb.eos = 1; + vb.eos_ids = { 1, 2, 99, -3 }; + auto v = std::make_shared(); + CHECK_OK(v->load(std::move(vb))); + CHECK(v->is_eog(1)); + CHECK(v->is_eog(2)); + CHECK(!v->is_eog(3)); + CHECK(!v->is_eog(0)); + CHECK_EQ(v->eog().size(), (size_t)2); +} + /* ================================================================== chain steps */ TEST(step_chain_units) {