diff --git a/CMakeLists.txt b/CMakeLists.txt index ea870066..e550ffe8 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is the server release that /version reports. The plugin ABI version is separate and is # read from abi/rad_abi.h below. -project(radiance VERSION 2.0.0 LANGUAGES C CXX) +project(radiance VERSION 2.1.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) diff --git a/NOTICE b/NOTICE index fd98dfa7..3c508b5f 100644 --- a/NOTICE +++ b/NOTICE @@ -42,7 +42,8 @@ Written by Deadcode, with contributions from: routed reads with their own router's counts and its deposit wait, the stop-string hold-back, and the sampler's planes by the step's token bound, its n-gram ban beside a drafter and no candidate cut over a top-1 row, and --prefill-interleave auto[:SHARE], sized from measured step times and - served by default + served by default, and the diagnose mode, in which the engine measures itself, with its token + parity and reproducibility checks - 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 @@ -55,11 +56,11 @@ Written by Deadcode, with contributions from: host) and decode-hot residency (--expert-profile, --expert-pin-top), prefix hits over KV groups of different block sizes and a hybrid's window in the checkpoint slot, --prefix-resume exact, DeepSeek-V4.1-Flash's conversion from its release (the Engram tables, the fused imatrix, the - UD-IQ1_S recipe and rad-convert --chat-template), a preempted prefill admitted only with its - whole recompute and the running sequences' next blocks free and the bound on its wait - (--preempt-wait-ms), prompt lookup alone (--spec-ngram) with each sequence's n-gram index and - the gate that verifies a proposal only when it pays, and DeepSeek-V4.1's reply format with its - DSML tool calls, and expert_stats_report.py + UD-IQ1_S recipe and rad-convert --chat-template), a preempted prefill admitted only with its whole + recompute and the running sequences' next blocks free and the bound on its wait + (--preempt-wait-ms), prompt lookup alone (--spec-ngram) with each sequence's n-gram index and the + gate that verifies a proposal only when it pays, and DeepSeek-V4.1's reply format with its DSML + tool calls, and expert_stats_report.py, and the KL mode's own line in the VRAM shortfall report - hazyumps: static YaRN for the Qwen rotary paths - malic: ParoQuant, with its MXFP4, int5 and int4 checkpoints imported and served, the Givens rotation as stages and as dense per-group matrices on the matrix cores, and the 5- and 4-bit @@ -130,13 +131,17 @@ Written by Deadcode, with contributions from: JSON export, with the page's JavaScript driven by tests/js - C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual projection, KV streaming for a context bigger than VRAM (--kv-resident), and the dashboard's - request history, KV streaming traffic and one-unit KV meter + request history, KV streaming traffic and one-unit KV meter, and the mapped tier kept in the page + cache across a load - J-Nova: Unlimited-OCR, and Sage-A1.5 with its vision tower and its DFlash2 drafter -- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8) +- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8), and the + diagnosis of the expert loan held at zero by leftover cache blocks - lortht: Krea 2's rebalance of the text taps and its presets, MiniMax-H3's modulation rows, and keyframes carried through a latent upscale - Quackster: cards with a small PCI BAR, their kernel arguments kept in host memory -- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix +- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix, and + Breeze-TTS-2's native voice cloning with its delivery direction (the Qwen3-TTS reference encoder, + vq_euclidean and elu) - gostar: snapshot-backed prefix KV kept across recomputes, and Tencent's Hy-Memory (HYV3) -- its BF16, FP8 and GGUF adapters, its KV scales, its native sectioned tool calls, and its W4 decode (the per-128 I4 expert packing, the one-row W4/W5 epilogue and the fused prologue and folds), @@ -145,7 +150,9 @@ Written by Deadcode, with contributions from: tool calls) with its DSpark drafter (exact attention and Markov walk ops), the prefill split keyed by live KV bounds, and --gpu-memory-mib - launch80_assets: tuning collectives as the exchange they serve at the served configuration, the - per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch + per-layer embeddings' read-ahead queue and gather regimes, and the step loop's stall watch, and + Meta Muse Glimmer 30B -- the museglimmer plugins, its windowed vision tower, its DFlash drafter, + the ATEM tool dialect and its context extension - hugypufy: M2XFP4 -- its quantiser, its GEMMs and its linears in the Qwen3.8 trunk and the DFlash2 drafter -- and the ParoQuant M2XFP4 import - steki: Gemma 4 E2B's per-layer MLP width and the bf16 descriptor for Google's E2B/E4B @@ -161,8 +168,10 @@ Written by Deadcode, with contributions from: and its gated three-tile form at 8 waves - RikshaDriver: libr3d, the RDNA3 (gfx11) kernel library, and its wave-matrix rewrite: the GEMMs retiled to 16x128 blocks, the grouped MoE GEMMs, the norms and quantisers, and the QSA and MoE - router rows, its MoE GEMMs at w4a8 and w4a4 with dequant_w4, row_topk_merge, ngram_ids and - the biased and short GEMMs, and w4a4's reference implementation + router rows, its MoE GEMMs at w4a8 and w4a4 with dequant_w4, row_topk_merge, ngram_ids and the + biased and short GEMMs, and w4a4's reference implementation, and Ling-3.0-tiny on bailing_hybrid + from its GGUF releases (the K-quant and IQ4_NL imports, the MLA query LoRA) with libr3d's + gemm_nt_f32, ple_conv, grouped router, kda_update, mla_project and mla_attn_paged - fl0l0u: every request entry point bounded, gated and sanitised (JSON parses bounded in depth, errors safe on invalid UTF-8, control bytes kept off the log, the dashboard's CSP, cross-origin browsers refused on the loopback-only routes, method-scoped API-key exemptions), prompt ids that @@ -185,10 +194,16 @@ Written by Deadcode, with contributions from: rows), and the DMA lane's room check over a reused fence slot - neuromanMD: libr3d's MXFP4 GEMM leaving VRAM exponent planes unscanned from the host, and its branch-free e4m3_to_f32 -- everplays: the paged attention at seven queries a KV head, head_dim 128 (Nanbeige4.3-33B) +- everplays: the paged attention at seven queries a KV head, head_dim 128 (Nanbeige4.3-33B), and + Recursive Flint -- its plugin, the sink-aware WMMA prefill attention and the fused prologue at + rotary_dim 0 - Kezi: the decode tile arms of the int4 and int5 x int8 GEMM -- dschmitz: the two-rank fused writes' host-mailbox twins taking their chained forms +- dschmitz: the two-rank fused writes' host-mailbox twins taking their chained forms, the card + telemetry's junction temperature, and a replayed tool call's blank arguments read as the empty + object with arguments that are not JSON refused naming the call - eniga: the diagnosis of GLM-5.3-Flash's template refused for tools (jinja's unique filter) +- tnhnyzc: the mixed-step service-time target (mixed-step-target-ms) +- aelfwyne: the diagnosis of draft trees refusing the int8 KV cache's rows 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 b4d45983..8afd67aa 100644 --- a/README.md +++ b/README.md @@ -54,6 +54,11 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Stable Diffusion XL bf16 and its finetunes (Illustrious, NoobAI, Pony): text to image, one card | `illustrious-xl-v2.0-bf16.rad` (6.4 GiB), from any single-file SDXL checkpoint | [convert](#convert-a-checkpoint) | — | | EmbeddingGemma 2 bf16: text, image, video and audio embeddings, one card | `embeddinggemma2-bf16.rad` (1.4 GiB) | [convert](#convert-a-checkpoint) | `tp1.yaml`, `tp2.yaml` | | nomic-embed-text-v2-moe bf16: text embeddings, one card | `nomic-embed-v2-moe-bf16.rad` (959 MB) | [convert](#convert-a-checkpoint) | — | +| Meta Muse Glimmer 30B bf16: text, images and video; sliding-window rotary layers between NoPE full ones, a windowed ViT | `muse-glimmer-30b-bf16.rad` (56 GiB) | [convert](#convert-a-checkpoint) | — | +| Meta Muse Glimmer 30B w4a8: int4 trunk, images and video, one card | `muse-glimmer-30b-w4a8.rad` (16 GiB) | [convert](#convert-a-checkpoint) | — | +| Meta Muse Glimmer 30B IQ8R: rotated int8 trunk, int8 head, DFlash drafter, images and video | `muse-glimmer-30b-iq8r-dflash.rad` (36 GiB) | [download](https://huggingface.co/StillDeadcode/muse-glimmer-30b-iq8r-dflash) | — | +| Recursive Flint (39.8B, about 2.5B active) IQ8R: rotated int8 trunk and experts, two cards | `flint-iq8r.rad` (38 GiB) | [download](https://huggingface.co/StillDeadcode/flint-iq8r) | — | +| Ling-3.0-tiny IQ8R: rotated int8 trunk and experts, one card | `ling-3.0-tiny-iq8r.rad` (7.9 GiB) | [download](https://huggingface.co/StillDeadcode/ling-3.0-tiny-iq8r) | — | | Nemotron 3.5 Embed 1B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-1B-BF16) | — | | Nemotron 3.5 Embed 8B BF16: text and image embeddings, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Embed-8B-BF16) | — | | Nemotron 3.5 Rerank 8B BF16: text/image document relevance, one card | the checkpoint as it ships | [NVIDIA checkpoint](https://huggingface.co/nvidia/Nemotron-3.5-Rerank-8B-BF16) | `tp1.yaml`, `tp2.yaml` | @@ -351,6 +356,17 @@ build/bin/rad-convert /srv/models/hf/google/gemma-4-31B-it -o gemma4-31b-dense-q --recipe data/recipes/gemma4-31b-dense-bf16-q8-df.recipe \ --set quantization_config.quant_method=compressed-tensors \ --draft-model /srv/models/hf/z-lab/gemma-4-31B-it-DFlash +# Meta's Muse Glimmer 30B, as it ships (bf16), with an int4 trunk and int8 attention values, or +# with an IQ8R trunk and an int8 head +build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-bf16.rad \ + --recipe data/recipes/museglimmer-30b-bf16.recipe +build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-w4a8.rad \ + --recipe data/recipes/museglimmer-30b-w4a8.recipe \ + --set quantization_config.quant_method=compressed-tensors +build/bin/rad-convert /srv/models/hf/meta-models/Muse-Glimmer-30B -o muse-glimmer-30b-iq8r-dflash.rad \ + --draft-model /srv/models/hf/meta-models/Muse-Glimmer-30B-assistant \ + --recipe data/recipes/museglimmer-30b-iq8r.recipe \ + --set quantization_config.quant_method=compressed-tensors build/bin/rad-convert /srv/models/hf/ukisai/Swift-1.5-Qwen3.8-27b-W4A16-AWQ -o swift15-27b-w4a16.rad \ --recipe data/recipes/q38-27b-w4a16.recipe # Any single-file SDXL checkpoint (SDXL 1.0, Illustrious, NoobAI, Pony, a civitai finetune), with @@ -394,6 +410,7 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out o |---|---| | [`docs/GUIDE.md`](docs/GUIDE.md) | installing, converting, serving, the HTTP API, operating a server | | [`docs/TOOLS.md`](docs/TOOLS.md) | every flag of every tool, and the recipe syntax | +| [`docs/DIAGNOSE.md`](docs/DIAGNOSE.md) | `diagnose`: the engine measures itself, and what makes a run a measurement | | [`docs/DOCKER.md`](docs/DOCKER.md) | the image and the compose files | | [`docs/PREPARING_YOUR_RIG.md`](docs/PREPARING_YOUR_RIG.md) | a two-R9700 machine from firmware setup to a serving model | | [`docs/PLUGIN.md`](docs/PLUGIN.md) | writing a kernel library, architecture or quantiser plugin, including one for another AMD card | diff --git a/abi/rad_abi.h b/abi/rad_abi.h index 2c003373..254977ab 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -19,7 +19,7 @@ extern "C" { * version is refused at load with both versions printed. Each also exports the layout's fingerprint * (rad_abi_layout.h), so two layouts given one number are refused as well. A new optional export * (e.g. rad_plugin_reference) is not a change of shape: a plugin without it gets the default. */ -#define RAD_ABI_VERSION 39u +#define RAD_ABI_VERSION 40u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: diff --git a/abi/rad_abi_layout_rows.h b/abi/rad_abi_layout_rows.h index a8a373e0..701ccebf 100644 --- a/abi/rad_abi_layout_rows.h +++ b/abi/rad_abi_layout_rows.h @@ -192,6 +192,7 @@ ABI_FIELD(RadAudioGenBatch, ref_cu) ABI_FIELD(RadAudioGenBatch, ref_cu_h) ABI_FIELD(RadAudioGenBatch, ref_frame) ABI_FIELD(RadAudioGenBatch, ref_frame_h) +ABI_FIELD(RadAudioGenBatch, prompt_cu_h) ABI_STRUCT(RadAudioGenDecl) ABI_FIELD(RadAudioGenDecl, name) ABI_FIELD(RadAudioGenDecl, tmpl) @@ -232,6 +233,8 @@ ABI_FIELD(RadAudioGenDecl, ref_rate) ABI_FIELD(RadAudioGenDecl, ref_hop) ABI_FIELD(RadAudioGenDecl, ref_max_samples) ABI_FIELD(RadAudioGenDecl, ref_max) +ABI_FIELD(RadAudioGenDecl, tmpl_ref_instruct) +ABI_FIELD(RadAudioGenDecl, neg_tmpl_ref) ABI_STRUCT(RadControlVector) ABI_FIELD(RadControlVector, dir) ABI_FIELD(RadControlVector, scales) @@ -278,6 +281,7 @@ ABI_FIELD(RadChatFormat, object_string_close) ABI_FIELD(RadChatFormat, object_bare_keys) ABI_FIELD(RadChatFormat, reasoning_anywhere) ABI_FIELD(RadChatFormat, arg_json_value_prefix) +ABI_FIELD(RadChatFormat, content_open) ABI_STRUCT(RadConstraint) ABI_FIELD(RadConstraint, key) ABI_FIELD(RadConstraint, op) diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 354e451e..03e351b2 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -1264,13 +1264,22 @@ typedef struct RadAudioGenDecl { * prepare() has limited to those a caller may write), and so is the text after it. A clip is * mono f32 in [-1, 1] at `ref_rate`, right-padded with zeros to a whole number of `ref_hop` * samples, each `ref_hop` samples one frame; a request's clips hold at most `ref_max_samples` - * samples together. NULL `tmpl_ref`: references are refused. */ + * samples together. With two branches, references require default_cfg 1 and a plain + * neg_tmpl: guidance 1 repeats the conditional prompt and frame map in both branches. + * Reference direction is opt-in through the templates appended below. NULL `tmpl_ref`: + * references are refused. */ const char* tmpl_ref; const char* ref_item; int64_t ref_rate; int64_t ref_hop; int64_t ref_max_samples; int32_t ref_max; + /* ABI 40: reference-plus-instructions uses tmpl_ref_instruct ({references}, + * {instructions}, {input} once each). Its guidance baseline is neg_tmpl_ref + * ({references}, {input}, no instructions). Both branches retain the same clips; + * their text lengths and reference-frame maps may differ. NULL: direction refused. */ + const char* tmpl_ref_instruct; + const char* neg_tmpl_ref; } RadAudioGenDecl; int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d); @@ -1847,6 +1856,13 @@ typedef struct RadChatFormat { * decides how its value is read, whatever the schema says; the grammar writes the one the * schema calls for. NULL: the schema alone types a value. */ const char* arg_json_value_prefix; + + /* A header the model writes first when it answers without reasoning, in place of + * reasoning_open: the reply then starts with this literal, which is dropped, and the rest is + * content. A reply that starts with anything else, or with only part of it, is read as + * written. When the model does reason, its header after the block is reasoning_close's. + * NULL or "": the reply starts with its content. */ + const char* content_open; } RadChatFormat; /* Return the format, or NULL for "derive it from the chat template". Called once at startup. */ diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index 09fb4b83..158fe68d 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -625,6 +625,9 @@ typedef struct RadAudioGenBatch { const int32_t* ref_cu_h; const int32_t* ref_frame; const int32_t* ref_frame_h; + /* ABI 40: PROMPT branch boundaries on the host, [n_seq + 1], including unequal + * reference-direction branches. Same rows as RadBatch::cu_seqlens on device. */ + const int32_t* prompt_cu_h; } RadAudioGenBatch; /* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear diff --git a/arch/bailing_hybrid/bailing_hybrid.cpp b/arch/bailing_hybrid/bailing_hybrid.cpp index cf89e05f..324e7c98 100644 --- a/arch/bailing_hybrid/bailing_hybrid.cpp +++ b/arch/bailing_hybrid/bailing_hybrid.cpp @@ -1,25 +1,52 @@ -/* bailing_hybrid -- Ling-3.0-flash and its fine-tunes (`model_type: bailing_hybrid`, - * BailingMoeV3ForCausalLM), from the bf16 checkpoint, the routed experts as a recipe stores them - * (data/recipes/ling3-w4a8-rtn.recipe, ling3-w4a8-gptq.recipe). +/* bailing_hybrid -- Ling-3.0-flash, Ling-3.0-tiny and their fine-tunes (`model_type: + * bailing_hybrid`, BailingMoeV3ForCausalLM), from the bf16 checkpoint, the routed experts as a + * recipe stores them (data/recipes/ling3-w4a8-rtn.recipe, ling3-w4a8-gptq.recipe), an IQ8R trunk + * with rotated int8 experts (data/recipes/ling-3.0-tiny-iq8r.recipe; below), and the tiny + * family's GGUF releases (arch/bailing_hybrid_gguf and kin: IQ4_NL, Q8_0, Q4_K_M, Q5_K_M, Q6_K, + * the iq4 release's codes through data/recipes/ling-3.0-tiny-iq4.recipe). * * ============================== WHAT IT SERVES ============================== * - * layers 42 in groups of six: five Kimi delta attention (KDA) layers, then one dense - * latent attention (MLA) layer, so layers 5, 11, ..., 41 are MLA - * KDA 32 heads of 128, separate q/k/v projections each with its own causal - * convolution, a full-rank per-channel forget gate (`f_proj`) and output gate - * (`g_proj`), lower bound -5 - * MLA no query LoRA, a 512-wide latent and a 64-wide rotary part (interleaved pairs), - * heads of 128 + 64, values of 128, a sigmoid gate per head - * feed-forward layers 0-1 dense (6144); from layer 2, 512 experts of 768 at top-8 under - * group-limited sigmoid routing (8 groups, 4 kept, a correction bias, x2.5), an - * ungated shared expert, and a SwiGLU clipped after the SiLU in the last layers - * (`expert_swiglu_limit_list`, `share_expert_swiglu_limit_list`, as vLLM and - * SGLang serve it; HF's reference ignores it) + * layers flash: 42 in groups of six -- five Kimi delta attention (KDA) layers, then one + * dense latent attention (MLA) layer, so layers 5, 11, ..., 41 are MLA. + * tiny: 24 in groups of four, MLA at 3, 7, ..., 23. + * KDA flash: 32 heads of 128; tiny: 16. Separate q/k/v projections each with its own + * causal convolution, a full-rank per-channel forget gate (`f_proj`) and output + * gate (`g_proj`), lower bound -5 + * MLA a 512-wide latent and a 64-wide rotary part (interleaved pairs), heads of + * 128 + 64, values of 128, a sigmoid gate per head. flash has no query LoRA; + * tiny projects through one: q_a and its norm feed q_b, whose rows serve the + * two query parts. + * feed-forward flash: layers 0-1 dense (6144); from layer 2, 512 experts of 768 at top-8. + * tiny: layer 0 dense (4608); from layer 1, 128 experts of 512 at top-8. Both + * under group-limited sigmoid routing (8 groups, 4 kept, a correction bias, + * x2.5), an ungated shared expert, and a SwiGLU clipped after the SiLU in the + * last layers (`expert_swiglu_limit_list`, `share_expert_swiglu_limit_list`, as + * vLLM and SGLang serve it; HF's reference ignores it) * * The KDA core is GLM-5.3's (KdaState), the router GLM-5.3's with groups (GlmRouter), the * feed-forward MoeFP8. The KDA and MLA blocks around them are in this file. * + * ============================== THE TRUNK'S FORM ============================== + * + * Read from layer 0's fused q|k|v before any activation buffer is declared. Two forms: + * + * - a rotated int8 trunk (data/recipes/ling-3.0-tiny-iq8r.recipe: IQ8R, int8 codes rotated by + * a 128-wide Hadamard under a u8 scale a (row, 256 of K) and a bf16 one a row): the block + * norms write rmsnorm_had_quant_i8g's codes at the trunk's group, read by every KDA + * projection, the shared expert's gate/up and the routed gate/up; the KDA core's gated norm + * and the MLA's expanded values are quantised by had_quant_act_i8g for their out projections; + * the dense and shared gated products write gated_had_quant_i8g's codes (the shared one at + * the group its own down weight is stored at), and the routed arm is int8 at one scale a 128 + * (MoeFP8::a8), so the rotated int8 experts read those codes at i8a8h. Where no loaded + * library serves the rotating norm, each linear quantises the norm's bf16 output itself and + * the routed experts read a rotated copy written once a layer. The linears the recipe keeps + * bf16 (the KDA beta, the MLA's low-rank q and kv and its head gate) read the norm's bf16 + * output in either case. Unclamped SwiGLU only: the int8 gated products have no clamped form. + * - any other (bf16, the four-bit experts of ling3-w4a8-rtn and ling-3.0-tiny-iq4, the GGUF + * releases): the norms write E4M3 codes, each linear reads the bf16 plane or quantises it + * itself, and four-bit experts read the E4M3 pair (rotated ones a rotated copy of it). + * * ============================== THE LATENT ATTENTION ============================== * * The MLA attends in the latent. The query projection is served as two, its heads' rotary rows and @@ -55,11 +82,20 @@ using namespace rad::arch; struct Shape { int64_t n_embd = 0, n_layer = 0, heads = 0, head_dim = 0, nope = 0, rope = 0, v_dim = 0, latent = 0, experts = 0, top_k = 0, groups = 0, topk_groups = 0, ff_exp = 0, - ff_shared = 0, ff_dense = 0, dense_layers = 0, group_size = 0, conv = 0; + ff_shared = 0, ff_dense = 0, dense_layers = 0, group_size = 0, conv = 0, q_lora = 0; double lower = -5, route_scale = 1; + bool gguf = false; /* the checkpoint spells its tensors blk. and ssm. names (the release GGUF) */ std::vector lim_exp, lim_shared; }; +/* A projection's checkpoint name: config.json's spelling under the layer prefix `pre` + * (`model.layers.%d.attention`) for the safetensors, the blk./ssm. spelling with the layer as %d + * for the release GGUF. */ +static const char* ck_name(Names& nm, const Shape& sh, int l, const char* pre, const char* hf, + const char* gg) { + return sh.gguf ? nm.ckpt(gg, l) : nm.ckpt(hf, pre); +} + /* A KDA layer: the q/k/v, beta, forget and output-gate projections into KdaState, then o_proj and * its all-reduce. */ struct LingKda { @@ -76,40 +112,63 @@ struct LingKda { QuantFP8 out_quant{}; rad_op op_ar = 0; + /* Maps layer l's fused q|k|v and reads its stored form (LinearFP8::probe); declare() then does + * not map it again. The model learns from it whether the trunk is rotated int8 before it + * declares any activation buffer. */ + int probe_qkv(RadBuilder* b, Names& nm, const Geom& geom, const Shape& sh, int l, + const char* pre) { + return qkv.probe(b, nm, geom, nm.f("blk.%d.attn_qkv", l), + { ck_name(nm, sh, l, pre, "%s.q_proj.weight", "blk.%d.attn_q.weight"), + ck_name(nm, sh, l, pre, "%s.k_proj.weight", "blk.%d.attn_k.weight"), + ck_name(nm, sh, l, pre, "%s.v_proj.weight", "blk.%d.attn_v.weight") }); + } + int declare(RadBuilder* b, Names& nm, const Geom& geom, const Shape& sh, int l, const Wire& wire, const char* pre, rad_kvgroup state, rad_kvgroup history) { g = geom; w = wire; const int64_t heads = sh.heads / g.world, width = heads * sh.head_dim; const auto grp = grp_layer(l); + /* One name a projection, the checkpoint's spelling (ck_name). */ + auto ck = [&](const char* hf, const char* gg) -> const char* { + return ck_name(nm, sh, l, pre, hf, gg); + }; RAD_ARCH_TRY(qkv.declare(b, nm, g, nm.f("blk.%d.attn_qkv", l), 3 * width, g.n_embd, RAD_SHARD_ROW, grp, - { nm.ckpt("%s.q_proj.weight", pre), nm.ckpt("%s.k_proj.weight", pre), - nm.ckpt("%s.v_proj.weight", pre) }, + { ck("%s.q_proj.weight", "blk.%d.attn_q.weight"), + ck("%s.k_proj.weight", "blk.%d.attn_k.weight"), + ck("%s.v_proj.weight", "blk.%d.attn_v.weight") }, w.input, w.core.qkv, 0, { width, width, width })); RAD_ARCH_TRY(beta.declare(b, nm, g, nm.f("blk.%d.attn_beta", l), heads, g.n_embd, - RAD_SHARD_ROW, grp, { nm.ckpt("%s.b_proj.weight", pre) }, + RAD_SHARD_ROW, grp, { ck("%s.b_proj.weight", "blk.%d.ssm_beta.weight") }, w.input, w.core.beta)); RAD_ARCH_TRY(forget.declare(b, nm, g, nm.f("blk.%d.attn_forget", l), width, g.n_embd, - RAD_SHARD_ROW, grp, { nm.ckpt("%s.f_proj.weight", pre) }, + RAD_SHARD_ROW, grp, { ck("%s.f_proj.weight", "blk.%d.ssm_f_a.weight") }, w.input, w.core.a)); RAD_ARCH_TRY(gate.declare(b, nm, g, nm.f("blk.%d.attn_gate", l), width, g.n_embd, - RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) }, + RAD_SHARD_ROW, grp, { ck("%s.g_proj.weight", "blk.%d.ssm_g_a.weight") }, w.input, w.core.gate)); KdaState::Config kc; kc.heads = heads; kc.dim = sh.head_dim; kc.width = sh.conv; kc.lower = sh.lower; - KdaState::Src ks{ nm.ckpt("%s.q_conv1d.weight", pre), nm.ckpt("%s.k_conv1d.weight", pre), - nm.ckpt("%s.v_conv1d.weight", pre), nm.ckpt("%s.A_log", pre), - nm.ckpt("%s.dt_bias", pre), nm.ckpt("%s.o_norm.weight", pre) }; + KdaState::Src ks{ ck("%s.q_conv1d.weight", "blk.%d.ssm_conv1d_q.weight"), + ck("%s.k_conv1d.weight", "blk.%d.ssm_conv1d_k.weight"), + ck("%s.v_conv1d.weight", "blk.%d.ssm_conv1d_v.weight"), + ck("%s.A_log", "blk.%d.ssm_a_raw"), + ck("%s.dt_bias", "blk.%d.ssm_dt.bias"), + ck("%s.o_norm.weight", "blk.%d.ssm_norm.weight") }; RAD_ARCH_TRY(core.declare(b, nm, g, l, state, history, kc, w.core, ks)); const char* on = nm.f("blk.%d.attn_output", l); - RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.o_proj.weight", pre) })); - if (!output.reads_x) RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, width)); + RAD_ARCH_TRY(output.probe(b, nm, g, on, { ck("%s.o_proj.weight", "blk.%d.attn_output.weight") })); + /* The out projection's input codes: on a rotated int8 trunk (ActFP8::q8_fed) an int8 out + * projection reads had_quant_act_i8g's, written here; otherwise a quantiser runs only for + * a weight that does not read the bf16 plane. */ + if (w.core_out.q8_fed ? output.probed_i8 : !output.reads_x) + RAD_ARCH_TRY(out_quant.declare(b, g, w.core_out, width)); RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, width, RAD_SHARD_COL, grp, - { nm.ckpt("%s.o_proj.weight", pre) }, w.core_out, w.out)); + { ck("%s.o_proj.weight", "blk.%d.attn_output.weight") }, w.core_out, w.out)); op_ar = GlmTp::reduce(b, g, w.out); return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK; } @@ -131,6 +190,8 @@ struct LingKda { struct LingMla { struct Wire { ActFP8 input{}; + ActFP8 qa{}; /* [T, q_lora], the tiny query LoRA's normed latent (the trunk's, + projected through q_a, for the parts' GEMMs) */ rad_buf q_rope = 0; /* [T, heads * rope] */ rad_buf q_nope = 0; /* [T, heads * nope] */ rad_buf row = 0; /* [T, latent + rope], the cache row */ @@ -146,11 +207,11 @@ struct LingMla { int layer = 0; int64_t heads = 0, qw = 0, cw = 0; rad_kvgroup kv = 0; - LinearFP8 q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{}; - QuantFP8 value_quant{}; - rad_weight kv_gain = 0, kv_b = 0; - rad_op op_kv_norm = 0, op_q_rope = 0, op_k_rope = 0, op_store = 0, op_absorb = 0, op_attn = 0, - op_expand = 0, op_ar = 0; + LinearFP8 q_a_proj{}, q_rope_proj{}, q_nope_proj{}, kv_a{}, g_proj{}, output{}; + QuantFP8 value_quant{}, qa_quant{}; + rad_weight kv_gain = 0, qa_gain = 0, kv_b = 0; + rad_op op_qa_norm = 0, op_kv_norm = 0, op_q_rope = 0, op_k_rope = 0, op_store = 0, + op_absorb = 0, op_attn = 0, op_expand = 0, op_ar = 0; int64_t block = 0; static constexpr int64_t kBlock = 16; @@ -169,7 +230,17 @@ struct LingMla { RAD_ARCH_TRY(rad_bind_layer_kv(b, l, kv)); /* One row map a part, a piece a head: [h * (nope + rope) + off, + width). Successive ROWS * maps for one name extend it in call order (rad_builder.h), eight pieces a map. */ - const char* qsrc = nm.ckpt("%s.q_proj.weight", pre); + /* flash projects the query from the trunk; tiny runs it through a LoRA first (q_a, its + * norm, then q_b), and the parts' rows come off q_b against the normed latent. */ + const int64_t qk = s.q_lora ? s.q_lora : g.n_embd; + const ActFP8& qin = s.q_lora ? w.qa : w.input; + auto ck = [&](const char* hf, const char* gg) -> const char* { + /* The safetensors names are the layer prefix plus the projection (`pre`, `model.layers.%d`); + * the release GGUF spells them blk./ssm. with the layer as %d. */ + return s.gguf ? nm.ckpt(gg, l) : nm.ckpt(hf, pre); + }; + const char* qsrc = s.q_lora ? ck("%s.q_b_proj.weight", "blk.%d.attn_q_b.weight") + : ck("%s.q_proj.weight", "blk.%d.attn_q.weight"); auto part = [&](const char* name, int64_t off, int64_t width) -> int { for (int64_t h0 = 0; h0 < s.heads; h0 += 8) { RadNameMap m = map_base(name, RAD_MAP_ROWS); @@ -183,18 +254,49 @@ struct LingMla { } return RAD_OK; }; - RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_rope.weight", l), s.nope, s.rope)); - RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_nope.weight", l), 0, s.nope)); + if (s.gguf) { + /* The reader split the quantised q_b into plain blocks a row map cannot see. */ + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_rope.weight", l), + nm.ckpt("blk.%d.attn_q_b_rope.weight", l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_nope.weight", l), + nm.ckpt("blk.%d.attn_q_b_nope.weight", l))); + } else { + RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_rope.weight", l), s.nope, s.rope)); + RAD_ARCH_TRY(part(nm.f("blk.%d.attn_q_nope.weight", l), 0, s.nope)); + } + if (s.q_lora) { + RAD_ARCH_TRY(q_a_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_a", l), s.q_lora, g.n_embd, + RAD_SHARD_NONE, grp, + { ck("%s.q_a_proj.weight", "blk.%d.attn_q_a.weight") }, w.input, w.qa.x)); + const char* an = nm.f("blk.%d.attn_q_a_norm.weight", l); + RAD_ARCH_TRY(map_copy(b, an, ck("%s.q_a_layernorm.weight", "blk.%d.attn_q_a_norm.weight"))); + qa_gain = decl_w(b, an, RAD_F32, { s.q_lora }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp); + if (!qa_gain) return RAD_E_INVAL; + op_qa_norm = rw(b, + RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", s.q_lora), + RAD_F64("eps", g.eps), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(qa_gain)), + { w.qa.x }, { w.qa.x }); + if (!op_qa_norm) return RAD_E_INVAL; + } q_rope_proj.mapped = q_nope_proj.mapped = true; RAD_ARCH_TRY(q_rope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_rope", l), heads * s.rope, - g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_rope)); + qk, RAD_SHARD_ROW, grp, { qsrc }, qin, w.q_rope)); RAD_ARCH_TRY(q_nope_proj.declare(b, nm, g, nm.f("blk.%d.attn_q_nope", l), heads * s.nope, - g.n_embd, RAD_SHARD_ROW, grp, { qsrc }, w.input, w.q_nope)); + qk, RAD_SHARD_ROW, grp, { qsrc }, qin, w.q_nope)); + /* On a rotated int8 trunk the LoRA's latent carries an int8 pair that a part stored int8 + * quantises itself (LinearFP8's own had_quant_act_i8g) and no E4M3 pair, so no quantiser + * runs here. */ + if (s.q_lora && !q_nope_proj.reads_x && !w.qa.q8) + RAD_ARCH_TRY(qa_quant.declare(b, g, w.qa, s.q_lora)); RAD_ARCH_TRY(kv_a.declare(b, nm, g, nm.f("blk.%d.attn_kv_a", l), cw, g.n_embd, - RAD_SHARD_NONE, grp, { nm.ckpt("%s.kv_a_proj_with_mqa.weight", pre) }, + RAD_SHARD_NONE, grp, + { ck("%s.kv_a_proj_with_mqa.weight", "blk.%d.attn_kv_a_mqa.weight") }, w.input, w.row)); const char* kn = nm.f("blk.%d.attn_kv_a_norm.weight", l); - RAD_ARCH_TRY(map_copy(b, kn, nm.ckpt("%s.kv_a_layernorm.weight", pre))); + RAD_ARCH_TRY(map_copy(b, kn, ck("%s.kv_a_layernorm.weight", "blk.%d.attn_kv_a_norm.weight"))); kv_gain = decl_w(b, kn, RAD_F32, { s.latent }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); if (!kv_gain) return RAD_E_INVAL; op_kv_norm = rw(b, @@ -217,7 +319,8 @@ struct LingMla { RAD_NOWEIGHTS), { w.row }, {}); const char* bn = nm.f("blk.%d.attn_kv_b.weight", l); - RAD_ARCH_TRY(map_copy(b, bn, nm.ckpt("%s.kv_b_proj.weight", pre))); + /* The GGUF keeps k_b and v_b head-last; the reader fuses them into this name. */ + RAD_ARCH_TRY(map_copy(b, bn, ck("%s.kv_b_proj.weight", "blk.%d.attn_kv_b.weight"))); kv_b = decl_w(b, bn, RAD_BF16, { heads * (s.nope + s.v_dim), s.latent }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp); if (!op_kv_norm || !op_q_rope || !op_k_rope || !op_store || !kv_b) return RAD_E_INVAL; @@ -229,7 +332,8 @@ struct LingMla { RAD_WEIGHTS(kv_b)), { w.q_nope }, { w.q_lat }); RAD_ARCH_TRY(g_proj.declare(b, nm, g, nm.f("blk.%d.attn_head_gate", l), heads, g.n_embd, - RAD_SHARD_ROW, grp, { nm.ckpt("%s.g_proj.weight", pre) }, + RAD_SHARD_ROW, grp, + { ck("%s.g_proj.weight", "blk.%d.attn_gate.weight") }, w.input, w.gate)); op_attn = rw(b, RAD_OP(b, "mla_attn_paged", @@ -255,10 +359,12 @@ struct LingMla { return RAD_E_INVAL; } const char* on = nm.f("blk.%d.attn_output", l); - RAD_ARCH_TRY(output.probe(b, nm, g, on, { nm.ckpt("%s.dense.weight", pre) })); - if (!output.reads_x) RAD_ARCH_TRY(value_quant.declare(b, g, w.value, heads * s.v_dim)); + RAD_ARCH_TRY(output.probe(b, nm, g, on, { ck("%s.dense.weight", "blk.%d.attn_output.weight") })); + /* As the KDA out projection's input (LingKda::declare). */ + if (w.value.q8_fed ? output.probed_i8 : !output.reads_x) + RAD_ARCH_TRY(value_quant.declare(b, g, w.value, heads * s.v_dim)); RAD_ARCH_TRY(output.declare(b, nm, g, on, g.n_embd, heads * s.v_dim, RAD_SHARD_COL, grp, - { nm.ckpt("%s.dense.weight", pre) }, w.value, w.out)); + { ck("%s.dense.weight", "blk.%d.attn_output.weight") }, w.value, w.out)); op_ar = GlmTp::reduce(b, g, w.out); return g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK; } @@ -271,8 +377,14 @@ struct LingMla { } const int64_t T = batch->n_tok, S = batch->n_seq; const RadOperand pos = praw(batch->positions, RAD_I32, T); - q_rope_proj.step(c, w.input, w.q_rope, T); - q_nope_proj.step(c, w.input, w.q_nope, T); + const ActFP8& qin = s.q_lora ? w.qa : w.input; + if (s.q_lora) { + q_a_proj.step(c, w.input, w.qa.x, T); + RAD_ISSUE_N(c, op_qa_norm, T, brows(w.qa.x, T), RAD_W(qa_gain), brows(w.qa.x, T)); + qa_quant.step(c, T); + } + q_rope_proj.step(c, qin, w.q_rope, T); + q_nope_proj.step(c, qin, w.q_nope, T); kv_a.step(c, w.input, w.row, T); g_proj.step(c, w.input, w.gate, T); RAD_ISSUE_N(c, op_kv_norm, T, bcol(w.row, 0, s.latent, T), RAD_W(kv_gain), @@ -308,6 +420,11 @@ struct Model { Names nm{}; Geom g{}; Shape s{}; + /* The trunk is rotated int8 (rad_fp8.h's linear_is_w8h or linear_is_wnh), its activation codes + * one scale a `trunk_g8` columns: 256 for IQ8R, 128 for the other rotated forms. `norm_fed`: + * the block norms write those codes themselves (rmsnorm_had_quant_i8g is served). */ + bool trunk_rot = false, norm_fed = false; + int64_t trunk_g8 = RAD_FP8_BLOCK; std::vector layers; rad_kvgroup latent = 0, state = 0, conv = 0; rad_buf x = 0, y = 0, final_hidden = 0, logit_input = 0, logits = 0; @@ -370,6 +487,8 @@ static int read_shape(const RadModelMeta* meta, Shape& s) { s.dense_layers = cfg(meta, "first_k_dense_replace", 0); s.group_size = cfg(meta, "layer_group_size", 0); s.conv = cfg(meta, "short_conv_kernel_size", 0); + s.q_lora = cfg(meta, "q_lora_rank", 0); + s.gguf = cfg(meta, "gguf_source", 0) != 0; s.lower = rad_meta_getf(meta, "kda_lower_bound", 0.0); s.route_scale = rad_meta_getf(meta, "routed_scaling_factor", 0.0); s.lim_exp = cfg_list(meta, "expert_swiglu_limit_list"); @@ -382,7 +501,11 @@ static int read_shape(const RadModelMeta* meta, Shape& s) { { "qk_nope_head_dim == v_head_dim (mla_project's head)", s.nope > 0 && s.nope == s.v_dim }, { "an even qk_rope_head_dim", s.rope > 0 && !(s.rope & 1) }, { "an even kv_lora_rank + qk_rope_head_dim", s.latent > 0 && !((s.latent + s.rope) & 1) }, - { "q_lora_rank null", cfg(meta, "q_lora_rank", 0) == 0 }, + { "q_lora_rank null, or 256 for the tiny family's query LoRA", + s.q_lora == 0 || s.q_lora == 256 }, + { "the tiny family's query LoRA in a GGUF release (the reader splits its quantised q_b; " + "a full-rank attn_q has no GGUF path)", + !s.gguf || s.q_lora != 0 }, { "no_kda_lora", cfg(meta, "no_kda_lora", 0) != 0 }, { "kda_safe_gate", cfg(meta, "kda_safe_gate", 1) != 0 }, { "a negative kda_lower_bound", s.lower < 0 && std::isfinite(s.lower) }, @@ -423,18 +546,38 @@ static void slice_of(int64_t blocks, int world, int rank, int first, int64_t* lo /* ============================== The trunk's buffers ============================== */ +/* The activation code pairs follow the trunk's form (the file's head comment). On a rotated int8 + * trunk every pair is int8 at the trunk's group and is declared before the wires are copied, so + * each block sees whether its producer writes the codes (ActFP8::q8_fed): the norms where + * `norm_fed`, the out projections' quantisers always, the gated products where gated_had_quant_i8g + * is served (ActFP8::declare_pair). A producer whose rotating form is not served keeps an E4M3 pair + * that no linear reads, and each int8 linear then quantises the bf16 plane itself. */ static int buffers(RadBuilder* b, Model& m) { auto& g = m.g; auto& s = m.s; auto& nm = m.nm; const int64_t T = g.max_tok, E = g.n_embd, H = s.heads / g.world, W = H * s.head_dim; + const bool rot = m.trunk_rot; + const int64_t g8 = m.trunk_g8; auto bf = [&](const char* n, std::initializer_list shape) { return decl_b(b, nm.f("%s", n), RAD_BF16, shape); }; + /* A rotated int8 trunk's pair on `a`, written by its producer (`fed`) or by each int8 linear + * reading it. */ + auto i8_pair = [&](ActFP8& a, const char* n, int64_t width, bool fed) -> int { + RAD_ARCH_TRY(a.declare_qs(b, nm, g, n, width, 0, true, false, g8)); + a.q8_fed = a.q8_rot = fed; + return RAD_OK; + }; m.x = bf("residual", { T, E }); m.y = bf("attn_delta", { T, E }); m.act.x = bf("normed", { T, E }); - RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E)); + if (rot) { + RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E, 0, true, !m.norm_fed, g8)); + m.act.q8_fed = m.act.q8_rot = m.norm_fed; + } else { + RAD_ARCH_TRY(m.act.declare_qs(b, nm, g, "normed", E)); + } m.final_hidden = decl_b(b, nm.f("final_hidden"), RAD_BF16, { T, E }, RAD_BUF_PERSIST); m.logit_input = bf("logit_input", { g.max_logit_rows, E }); m.logits = decl_b(b, nm.f("logits"), RAD_F32, { g.max_logit_rows, g.n_vocab }); @@ -450,7 +593,10 @@ static int buffers(RadBuilder* b, Model& m) { kw.core.gate = bf("kda_gate", { T, W }); kw.core.out = bf("kda_out", { T, W }); kw.core_out.x = kw.core.out; - RAD_ARCH_TRY(kw.core_out.declare_qs(b, nm, g, "kda_out", W)); + if (rot) + RAD_ARCH_TRY(i8_pair(kw.core_out, "kda_out", W, true)); + else + RAD_ARCH_TRY(kw.core_out.declare_qs(b, nm, g, "kda_out", W)); auto& aw = m.aw; aw.input = m.act; @@ -461,19 +607,35 @@ static int buffers(RadBuilder* b, Model& m) { aw.q_lat = bf("mla_q_latent", { T, H * s.latent }); aw.gate = bf("mla_gate", { T, H }); aw.attn = bf("mla_attn_latent", { T, H * s.latent }); + if (s.q_lora) { + aw.qa.x = bf("mla_q_a", { T, s.q_lora }); + if (rot) + RAD_ARCH_TRY(i8_pair(aw.qa, "mla_q_a", s.q_lora, false)); + else + RAD_ARCH_TRY(aw.qa.declare_qs(b, nm, g, "mla_q_a", s.q_lora)); + } aw.value.x = bf("mla_value", { T, H * s.v_dim }); - RAD_ARCH_TRY(aw.value.declare_qs(b, nm, g, "mla_value", H * s.v_dim)); + if (rot) + RAD_ARCH_TRY(i8_pair(aw.value, "mla_value", H * s.v_dim, true)); + else + RAD_ARCH_TRY(aw.value.declare_qs(b, nm, g, "mla_value", H * s.v_dim)); auto& dw = m.dw; dw.x = m.x; dw.h = m.act; dw.gate_up = bf("dense_gate_up", { T, 2 * g.n_ff }); dw.ffn.x = bf("dense_ff", { T, g.n_ff }); - RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff)); + if (rot) + RAD_ARCH_TRY(dw.ffn.declare_pair(b, nm, g, "dense_ff", g.n_ff, 0, true, g8, + "gated_had_quant_i8g")); + else + RAD_ARCH_TRY(dw.ffn.declare_qs(b, nm, g, "dense_ff", g.n_ff)); return RAD_OK; } -static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) { +/* `shared_g8`: on a rotated int8 trunk, the scale group of the shared expert's stored down weight, + * which its input codes take. */ +static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc, int64_t shared_g8) { auto& g = m.g; auto& nm = m.nm; const int64_t T = g.max_tok, E = g.n_embd, F = mc.n_ff_exp, k = mc.top_k; @@ -491,9 +653,25 @@ static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) { mw.sorted = decl_b(b, nm.f("expert_sorted"), RAD_I32, { T * k }); mw.egu = bf("expert_gate_up", { T * k, 2 * F }); mw.eff.x = bf("expert_ff", { T * k, F }); - RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k)); + if (m.trunk_rot) { + /* The routed arm of a rotated trunk is int8 throughout: the gated product's rotated codes + * at one scale a 128 of K, which the grouped GEMM's int8 rows read (MoeFP8::a8). */ + RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k, true, false, + RAD_FP8_BLOCK)); + mw.eff.q8_fed = mw.eff.q8_rot = true; + } else { + RAD_ARCH_TRY(mw.eff.declare_qs(b, nm, g, "expert_ff", F, T * k)); + } mw.edn = bf("expert_down", { T * k, E }); - if (mc.expert_rot) { + if (m.trunk_rot) { + /* The routed gate_up reads the norm's own codes where it writes them, else a rotated int8 + * copy of the block input that MoeFP8 writes once a layer (Wire::hr). */ + if (!m.norm_fed) { + RAD_ARCH_TRY(mw.hr.declare_qs(b, nm, g, "normed_rot", E, 0, true, false, + RAD_FP8_BLOCK)); + mw.hr.q8_fed = mw.hr.q8_rot = true; + } + } else if (mc.expert_rot) { mw.hr.q = decl_b(b, nm.f("normed_rot.q"), RAD_F8E4M3, { T, E }); mw.hr.s = decl_b(b, nm.f("normed_rot.s"), RAD_F32, { T, E / RAD_FP8_BLOCK }); if (!mw.hr.q || !mw.hr.s) return RAD_E_INVAL; @@ -501,7 +679,11 @@ static int moe_buffers(RadBuilder* b, Model& m, const MoeFP8::Config& mc) { if (mc.n_ff_shared > 0) { mw.sgu = bf("shared_gate_up", { T, 2 * mc.n_ff_shared }); mw.sff.x = bf("shared_ff", { T, mc.n_ff_shared }); - RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", mc.n_ff_shared)); + if (m.trunk_rot) + RAD_ARCH_TRY(mw.sff.declare_pair(b, nm, g, "shared_ff", mc.n_ff_shared, 0, true, + shared_g8, "gated_had_quant_i8g")); + else + RAD_ARCH_TRY(mw.sff.declare_qs(b, nm, g, "shared_ff", mc.n_ff_shared)); mw.sout = bf("shared_out", { T, E }); mw.sgate = bf("shared_one", { T, 1 }); } @@ -614,11 +796,23 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c ms.cfg = mc; ms.cfg.swiglu_limit = limit_at(s.lim_exp, l); ms.cfg.shared_swiglu_limit = limit_at(s.lim_shared, l); - ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre); - ms.router = nm.ckpt("%s.mlp.gate.weight", pre); - ms.router_bias = nm.ckpt("%s.mlp.gate.expert_bias", pre); - ms.experts = nm.ckpt("%s.mlp.experts", pre); - ms.shared = nm.ckpt("%s.mlp.shared_experts", pre); + ms.norm = s.gguf ? nm.ckpt("blk.%d.ffn_norm.weight", l) + : nm.ckpt("%s.post_attention_layernorm.weight", pre); + ms.router = s.gguf ? nm.ckpt("blk.%d.ffn_gate_inp.weight", l) + : nm.ckpt("%s.mlp.gate.weight", pre); + ms.router_bias = s.gguf ? nm.ckpt("blk.%d.exp_probs_b.bias", l) + : nm.ckpt("%s.mlp.gate.expert_bias", pre); + if (s.gguf) { + /* The release GGUF stacks the experts expert-last, the block's split-stacked + * source slicing one expert off each: [E, ff, emb] gate and up, [E, emb, ff] down. */ + ms.experts_gate = nm.ckpt("blk.%d.ffn_gate_exps.weight", l); + ms.experts_up = nm.ckpt("blk.%d.ffn_up_exps.weight", l); + ms.experts_down = nm.ckpt("blk.%d.ffn_down_exps.weight", l); + } else { + ms.experts = nm.ckpt("%s.mlp.experts", pre); + } + ms.shared = s.gguf ? nm.ckpt("blk.%d.mlp.shared_experts", l) + : nm.ckpt("%s.mlp.shared_experts", pre); RAD_ARCH_TRY(MoeFP8::probe(b, nm, l, ms, &ms.cfg)); if (ms.cfg.expert_rot) mc.expert_rot = 1; if (ms.cfg.expert_bf16) mc.expert_bf16 = 1; @@ -645,8 +839,66 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c g.rank, (long long)mc.expert_base, (long long)(mc.expert_base + per), (long long)s.experts); } + + /* ---- the trunk's stored form, read from layer 0's fused q|k|v through that layer's own + * LinearFP8 (layer 0 is KDA: the last of each group of `layer_group_size` > 1 is MLA). The + * activations below carry rotated int8 codes only for a rotated trunk. */ + m.layers.resize((size_t)s.n_layer); + RAD_ARCH_TRY(m.layers[0].kda.probe_qkv(b, nm, g, s, 0, + nm.ckpt("%s.attention", nm.ckpt("model.layers.%d", 0)))); + { + RadEncoding enc{}; + m.trunk_rot = weight_enc(b, nm.f("blk.0.attn_qkv.weight"), &enc) && + (linear_is_w8h(enc) || linear_is_wnh(enc)); + if (m.trunk_rot) m.trunk_g8 = linear_w8h_group(enc); + } + int64_t shared_g8 = m.trunk_g8; + if (m.trunk_rot) { + /* The routed experts read the trunk's rotated int8 codes (MoeFP8::a8), which only a + * rotated expert meets; and the int8 gated products have no clamped form. */ + for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) { + const MoeFP8::Config& c = msrc[(size_t)l].cfg; + if (c.expert_bf16 || !c.expert_rot) { + fprintf(stderr, "radiance: bailing_hybrid: the trunk is rotated int8 and layer %d's " + "routed experts are %s; a rotated trunk's experts read its int8 codes " + "and are stored rotated (data/recipes/ling-3.0-tiny-iq8r.recipe)\n", + l, c.expert_bf16 ? "plain bf16" : "unrotated"); + return RAD_E_UNSUPPORTED; + } + if (c.swiglu_limit > 0 || c.shared_swiglu_limit > 0) { + fprintf(stderr, "radiance: bailing_hybrid: layer %d clamps its SwiGLU (routed %g, " + "shared %g) and the trunk is rotated int8, whose gated products " + "write int8 codes with no clamped form; this checkpoint is served " + "with a bf16 or four-bit trunk\n", + l, c.swiglu_limit, c.shared_swiglu_limit); + return RAD_E_UNSUPPORTED; + } + } + m.norm_fed = rad_op_declared(b, "rmsnorm_had_quant_i8g") != 0; + /* The shared expert's down projection is a trunk linear whose input codes take the group + * its own weight is stored at, read from the first routed layer's through that layer's + * own LinearFP8 (which MoeFP8 then does not map again). */ + const int lm = (int)s.dense_layers; + if (lm < (int)s.n_layer && mc.n_ff_shared > 0) { + LinearFP8& sd = m.layers[(size_t)lm].moe.sh_down; + RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.%d.ffn_down_shexp", lm), + { nm.ckpt("%s.down_proj.weight", msrc[(size_t)lm].shared) })); + if (sd.probed_i8) shared_g8 = sd.probed_g8; + } + } else { + for (int l = (int)s.dense_layers; l < (int)s.n_layer + (mtp ? 1 : 0); ++l) { + const MoeFP8::Config& c = msrc[(size_t)l].cfg; + if (c.expert_i8 || c.expert_iqr) { + fprintf(stderr, "radiance: bailing_hybrid: layer %d's routed experts are rotated " + "int8 and the trunk is not; they read the trunk's rotated int8 codes, " + "so convert the trunk with them " + "(data/recipes/ling-3.0-tiny-iq8r.recipe)\n", l); + return RAD_E_UNSUPPORTED; + } + } + } RAD_ARCH_TRY(buffers(b, m)); - RAD_ARCH_TRY(moe_buffers(b, m, mc)); + RAD_ARCH_TRY(moe_buffers(b, m, mc, shared_g8)); /* ---- the caches: the MLA layers' latent rows, the KDA layers' state and convolution * history. */ @@ -674,9 +926,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } /* ---- the embedding, the layers, the final norm and the head. */ - RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.word_embeddings.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"))); - RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"))); + /* The release GGUF already spells the head tensors under the container's names; the first + * source the container holds wins. */ + RAD_ARCH_TRY(map_copy_alt(b, nm.f("token_embd.weight"), nm.ckpt("model.word_embeddings.weight"), + nm.ckpt("token_embd.weight"))); + RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"), + nm.ckpt("output.weight"))); + RAD_ARCH_TRY(map_copy_alt(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"), + nm.ckpt("output_norm.weight"))); m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, { g.n_vocab, g.n_embd }, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); m.head = decl_w(b, nm.f("output.weight"), RAD_BF16, { g.n_vocab, g.n_embd }, RAD_ACCESS_VOCAB, @@ -699,7 +956,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c lay.dense = l < s.dense_layers; const char* pre = nm.ckpt("model.layers.%d", l); const char* nn = nm.f("blk.%d.attn_norm.weight", l); - RAD_ARCH_TRY(map_copy(b, nn, nm.ckpt("%s.input_layernorm.weight", pre))); + RAD_ARCH_TRY(map_copy(b, nn, s.gguf ? nm.ckpt("blk.%d.attn_norm.weight", l) + : nm.ckpt("%s.input_layernorm.weight", pre))); lay.gain = decl_w(b, nn, RAD_F32, { g.n_embd }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); RAD_ARCH_TRY(lay.norm.declare(b, g, lay.gain, m.x, m.act, g.n_embd)); @@ -719,10 +977,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c { m.x, m.y }, { m.x }); if (!lay.op_add) return RAD_E_INVAL; if (lay.dense) { - MlpFP8::Src ds{ nm.ckpt("%s.post_attention_layernorm.weight", pre), - nm.ckpt("%s.mlp.gate_proj.weight", pre), - nm.ckpt("%s.mlp.up_proj.weight", pre), - nm.ckpt("%s.mlp.down_proj.weight", pre) }; + MlpFP8::Src ds{ s.gguf ? nm.ckpt("blk.%d.ffn_norm.weight", l) + : nm.ckpt("%s.post_attention_layernorm.weight", pre), + s.gguf ? nm.ckpt("blk.%d.ffn_gate.weight", l) + : nm.ckpt("%s.mlp.gate_proj.weight", pre), + s.gguf ? nm.ckpt("blk.%d.ffn_up.weight", l) + : nm.ckpt("%s.mlp.up_proj.weight", pre), + s.gguf ? nm.ckpt("blk.%d.ffn_down.weight", l) + : nm.ckpt("%s.mlp.down_proj.weight", pre) }; RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, l, m.dw, ds)); } else { RAD_ARCH_TRY(lay.moe.declare(b, nm, g, l, m.mw, msrc[(size_t)l])); @@ -780,10 +1042,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } rad_note(b, "Ling-3.0 (bailing_hybrid): TP%d, %lld layers, %lld KDA + %lld dense MLA, %lld experts " - "top-%lld in %lld groups (%lld kept), MTP %s", + "top-%lld in %lld groups (%lld kept), MTP %s, %s trunk", world, (long long)s.n_layer, (long long)(s.n_layer - s.n_layer / s.group_size), (long long)(s.n_layer / s.group_size), (long long)s.experts, (long long)s.top_k, - (long long)s.groups, (long long)s.topk_groups, m.have_mtp ? "enabled" : "not declared"); + (long long)s.groups, (long long)s.topk_groups, m.have_mtp ? "enabled" : "not declared", + !m.trunk_rot ? "unrotated" + : m.trunk_g8 == RAD_I8_GROUP_WIDE ? "IQ8R (rotated int8)" : "rotated int8"); return RAD_OK; } @@ -879,10 +1143,36 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { } /* namespace bailing_hybrid */ +/* The GGUF release wrappers (arch/bailing_hybrid_gguf* and kin) define these to their file's + * `general.file_type` and plugin name and include the file; the base plugin keeps the empty + * quant. The name is spelled by a macro, not by RAD_ARCH_PLUGIN's stringifier: a macro argument + * that reaches `#` expands as written, and a wrapper that only renames the namespace would ship + * five plugins all called "bailing_hybrid". */ +#ifndef BAILING_HYBRID_QUANT +#define BAILING_HYBRID_QUANT "" +#endif +#ifndef BAILING_HYBRID_PLUGIN +#define BAILING_HYBRID_PLUGIN "bailing_hybrid" +#endif + #ifndef RAD_ARCH_NO_EXPORTS RAD_ARCH_PROBE(bailing_hybrid) /* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */ RAD_ARCH_MULTI_INSTANCE() -RAD_ARCH_PLUGIN(bailing_hybrid, "bailinghybrid", "", "0.1.0", - "Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts") +extern "C" const char* rad_arch_id(void) { return "bailinghybrid"; } +extern "C" const char* rad_arch_quant(void) { return BAILING_HYBRID_QUANT; } +extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) { + return bailing_hybrid::declare(b, m, c); +} +extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) { + bailing_hybrid::step(c, batch); +} +extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } +extern "C" uint64_t rad_plugin_abi_layout(void) { return rad_abi_layout(); } +extern "C" const RadPluginInfo* rad_plugin_info(void) { + static const RadPluginInfo info = { + RAD_PLUGIN_ARCH, BAILING_HYBRID_PLUGIN, "0.1.0", + "Ling-3.0 (bailing_hybrid): KDA and dense latent attention, group-routed experts", "" }; + return &info; +} #endif diff --git a/arch/bailing_hybrid_gguf/CMakeLists.txt b/arch/bailing_hybrid_gguf/CMakeLists.txt new file mode 100644 index 00000000..d91dbee6 --- /dev/null +++ b/arch/bailing_hybrid_gguf/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/bailing_hybrid_gguf -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(bailing_hybrid_gguf LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(bailing_hybrid_gguf architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf.cpp) diff --git a/arch/bailing_hybrid_gguf/bailing_hybrid_gguf.cpp b/arch/bailing_hybrid_gguf/bailing_hybrid_gguf.cpp new file mode 100644 index 00000000..712a8104 --- /dev/null +++ b/arch/bailing_hybrid_gguf/bailing_hybrid_gguf.cpp @@ -0,0 +1,12 @@ +/* bailing_hybrid_gguf -- the GGUF variant of bailing_hybrid for the tiny family's IQ4_NL release: the same + * declaration and step, claiming the ftype-25 descriptor so the quantised GGUF converts + * and serves. As in hyv3_gguf, a thin include over the family's implementation with the + * namespace, the plugin name and the quant redefined. */ +#define bailing_hybrid bailing_hybrid_gguf +#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf" +#define BAILING_HYBRID_QUANT "gguf_ftype_25" +#include "../bailing_hybrid/bailing_hybrid.cpp" + +/* GGUF file_type names the quant, never an imported tool descriptor: imports stay + * with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */ +RAD_ARCH_SERVES_IMPORTS(0) diff --git a/arch/bailing_hybrid_gguf_q4km/CMakeLists.txt b/arch/bailing_hybrid_gguf_q4km/CMakeLists.txt new file mode 100644 index 00000000..a3b8e5a8 --- /dev/null +++ b/arch/bailing_hybrid_gguf_q4km/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/bailing_hybrid_gguf_q4km -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(bailing_hybrid_gguf_q4km LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(bailing_hybrid_gguf_q4km architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q4km.cpp) diff --git a/arch/bailing_hybrid_gguf_q4km/bailing_hybrid_gguf_q4km.cpp b/arch/bailing_hybrid_gguf_q4km/bailing_hybrid_gguf_q4km.cpp new file mode 100644 index 00000000..b92a8964 --- /dev/null +++ b/arch/bailing_hybrid_gguf_q4km/bailing_hybrid_gguf_q4km.cpp @@ -0,0 +1,12 @@ +/* bailing_hybrid_gguf_q4km -- the GGUF variant of bailing_hybrid for the tiny family's Q4_K_M release: the same + * declaration and step, claiming the ftype-15 descriptor so the quantised GGUF converts + * and serves. As in hyv3_gguf, a thin include over the family's implementation with the + * namespace, the plugin name and the quant redefined. */ +#define bailing_hybrid bailing_hybrid_gguf_q4km +#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q4km" +#define BAILING_HYBRID_QUANT "gguf_ftype_15" +#include "../bailing_hybrid/bailing_hybrid.cpp" + +/* GGUF file_type names the quant, never an imported tool descriptor: imports stay + * with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */ +RAD_ARCH_SERVES_IMPORTS(0) diff --git a/arch/bailing_hybrid_gguf_q5km/CMakeLists.txt b/arch/bailing_hybrid_gguf_q5km/CMakeLists.txt new file mode 100644 index 00000000..5c2f503e --- /dev/null +++ b/arch/bailing_hybrid_gguf_q5km/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/bailing_hybrid_gguf_q5km -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(bailing_hybrid_gguf_q5km LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(bailing_hybrid_gguf_q5km architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q5km.cpp) diff --git a/arch/bailing_hybrid_gguf_q5km/bailing_hybrid_gguf_q5km.cpp b/arch/bailing_hybrid_gguf_q5km/bailing_hybrid_gguf_q5km.cpp new file mode 100644 index 00000000..d0504a0d --- /dev/null +++ b/arch/bailing_hybrid_gguf_q5km/bailing_hybrid_gguf_q5km.cpp @@ -0,0 +1,12 @@ +/* bailing_hybrid_gguf_q5km -- the GGUF variant of bailing_hybrid for the tiny family's Q5_K_M release: the same + * declaration and step, claiming the ftype-17 descriptor so the quantised GGUF converts + * and serves. As in hyv3_gguf, a thin include over the family's implementation with the + * namespace, the plugin name and the quant redefined. */ +#define bailing_hybrid bailing_hybrid_gguf_q5km +#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q5km" +#define BAILING_HYBRID_QUANT "gguf_ftype_17" +#include "../bailing_hybrid/bailing_hybrid.cpp" + +/* GGUF file_type names the quant, never an imported tool descriptor: imports stay + * with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */ +RAD_ARCH_SERVES_IMPORTS(0) diff --git a/arch/bailing_hybrid_gguf_q6k/CMakeLists.txt b/arch/bailing_hybrid_gguf_q6k/CMakeLists.txt new file mode 100644 index 00000000..6c59fdd5 --- /dev/null +++ b/arch/bailing_hybrid_gguf_q6k/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/bailing_hybrid_gguf_q6k -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(bailing_hybrid_gguf_q6k LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(bailing_hybrid_gguf_q6k architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q6k.cpp) diff --git a/arch/bailing_hybrid_gguf_q6k/bailing_hybrid_gguf_q6k.cpp b/arch/bailing_hybrid_gguf_q6k/bailing_hybrid_gguf_q6k.cpp new file mode 100644 index 00000000..677c92c2 --- /dev/null +++ b/arch/bailing_hybrid_gguf_q6k/bailing_hybrid_gguf_q6k.cpp @@ -0,0 +1,12 @@ +/* bailing_hybrid_gguf_q6k -- the GGUF variant of bailing_hybrid for the tiny family's Q6_K release: the same + * declaration and step, claiming the ftype-18 descriptor so the quantised GGUF converts + * and serves. As in hyv3_gguf, a thin include over the family's implementation with the + * namespace, the plugin name and the quant redefined. */ +#define bailing_hybrid bailing_hybrid_gguf_q6k +#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q6k" +#define BAILING_HYBRID_QUANT "gguf_ftype_18" +#include "../bailing_hybrid/bailing_hybrid.cpp" + +/* GGUF file_type names the quant, never an imported tool descriptor: imports stay + * with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */ +RAD_ARCH_SERVES_IMPORTS(0) diff --git a/arch/bailing_hybrid_gguf_q80/CMakeLists.txt b/arch/bailing_hybrid_gguf_q80/CMakeLists.txt new file mode 100644 index 00000000..418ed7ed --- /dev/null +++ b/arch/bailing_hybrid_gguf_q80/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/bailing_hybrid_gguf_q80 -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(bailing_hybrid_gguf_q80 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(bailing_hybrid_gguf_q80 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/bailing_hybrid_gguf_q80.cpp) diff --git a/arch/bailing_hybrid_gguf_q80/bailing_hybrid_gguf_q80.cpp b/arch/bailing_hybrid_gguf_q80/bailing_hybrid_gguf_q80.cpp new file mode 100644 index 00000000..d616925c --- /dev/null +++ b/arch/bailing_hybrid_gguf_q80/bailing_hybrid_gguf_q80.cpp @@ -0,0 +1,12 @@ +/* bailing_hybrid_gguf_q80 -- the GGUF variant of bailing_hybrid for the tiny family's Q8_0 release: the same + * declaration and step, claiming the ftype-7 descriptor so the quantised GGUF converts + * and serves. As in hyv3_gguf, a thin include over the family's implementation with the + * namespace, the plugin name and the quant redefined. */ +#define bailing_hybrid bailing_hybrid_gguf_q80 +#define BAILING_HYBRID_PLUGIN "bailing_hybrid_gguf_q80" +#define BAILING_HYBRID_QUANT "gguf_ftype_7" +#include "../bailing_hybrid/bailing_hybrid.cpp" + +/* GGUF file_type names the quant, never an imported tool descriptor: imports stay + * with the family's bf16 plugin (rad_builder.h, rad_arch_serves_imports). */ +RAD_ARCH_SERVES_IMPORTS(0) diff --git a/arch/breeze/breeze.cpp b/arch/breeze/breeze.cpp index e2002d66..6662eb66 100644 --- a/arch/breeze/breeze.cpp +++ b/arch/breeze/breeze.cpp @@ -1,8 +1,9 @@ -/* breeze -- Breeze-TTS-2: speech from text, with an optional description of the voice; 24 kHz mono. +/* breeze -- Breeze-TTS-2: speech from text, voice design or a reference recording; 24 kHz mono. * * ============================== THE MODEL ============================== * - * Four networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer): + * Four generation networks (BreezeBlue's BreezeForConditionalGeneration and its audio tokenizer), + * plus the reference-audio encoder in reference.h for voice cloning: * * Text encoder: T5Gemma 2's text encoder, Gemma 3 1B's shape (26 layers of 1152, 4 query heads * over one KV head of 256, gelu-tanh GLU 6912, sandwich RMS norms with a (1 + w) gain), read @@ -85,6 +86,8 @@ constexpr int64_t kVocChunk = 4, kConvCtx = 12, kAttnWin = 72; constexpr int64_t kVocContext = 2 + (kAttnWin - 1) + kConvCtx; constexpr int64_t kConvFrames = kConvCtx + kVocChunk; constexpr int64_t kCbBins = 2048, kCbDim = 256; +/* One clean reference of at most ten seconds (rounded to complete codec frames). */ +constexpr int64_t kMaxRefFrames = 125, kMaxRefSamples = kMaxRefFrames * kSamplesPerFrame; /* The codec's sequence rates, rows a frame: the transformer's frames, the convolutions' frames, * the two upsamplings', and each decoder block's output (8, 5, 4, 3 times). */ constexpr int kRates = 8; @@ -160,7 +163,34 @@ struct Llama3 { double factor = 0, low = 0, high = 0, orig = 0; }; +struct RefConv { + rad_weight w = 0, b = 0; + rad_op op = 0; +}; +struct RefLayer { + rad_weight n1 = 0, b1 = 0, n2 = 0, b2 = 0, qkv = 0, o = 0, fc1 = 0, fc2 = 0; + rad_weight ls1 = 0, ls2 = 0; + rad_op norm1 = 0, norm2 = 0, proj = 0, rope = 0, attn = 0, out = 0; + rad_op f1 = 0, act = 0, f2 = 0, scale1 = 0, scale2 = 0, add1 = 0, add2 = 0; +}; +struct Reference { + RefConv first{}, res1[4]{}, res2[4]{}, down[4]{}, last{}, sample{}; + rad_buf x[5]{}, a[5]{}, h[4]{}, z = 0, pad = 0, sampled = 0; + rad_op elu[5]{}, elu_h[4]{}; + rad_buf th = 0, qkv = 0, attn = 0, o = 0, ff = 0, act = 0; + RefLayer layer[8]{}; + rad_buf index = 0, cu = 0, text_pos = 0, text_cu = 0; + rad_op indices = 0, copy_i = 0, copy_f = 0, text_indices = 0; + rad_buf q[2]{}, codes = 0, eos_codes = 0; + rad_weight qi[2]{}, cb[16]{}; + rad_op project[2]{}, quant[16]{}, embed = 0, eos = 0; +}; + struct Model { + Reference ref{}; + /* The model holds the reference encoder (reference_stored), whose first weight is then already + * in the name map. */ + bool ref_stored = false; Names nm{""}; Llama3 l3{}; Geom ge{}, gl{}, gd{}; /* the text encoder's, the backbone's, the depth decoder's */ @@ -1183,6 +1213,8 @@ static int check_format(const RadModelMeta* meta) { return RAD_OK; } +#include "reference.h" + 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 || rad_build_slot(ctx) >= MAX_SLOTS) @@ -1214,6 +1246,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_ARCH_TRY(declare_encoder(b, meta, m)); RAD_ARCH_TRY(declare_frame(b, meta, m)); RAD_ARCH_TRY(declare_codec(b, meta, m)); + /* A container converted before the reference encoder was in the recipe holds the generator + * alone: it serves speech as before, and with no reference templates declared below the + * server refuses a request that brings references, saying the model clones no voice. */ + m.ref_stored = reference_stored(b, m); + if (m.ref_stored) RAD_ARCH_TRY(declare_reference(b, meta, m)); if (!ctx->shape_probe) { RadAudioGenDecl d{}; @@ -1221,6 +1258,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c d.tmpl = kTemplate; d.tmpl_plain = kPlain; d.neg_tmpl = kPlain; + d.branches = 2; + if (m.ref_stored) { + d.tmpl_ref = "{references}[S0]{input}"; + d.tmpl_ref_instruct = "{references}[S0]{instructions}{input}"; + d.neg_tmpl_ref = d.tmpl_ref; + d.ref_item = "[S0]{text}{audio}<|audio_eos|>"; + d.ref_rate = kSampleRate; + d.ref_hop = kSamplesPerFrame; + d.ref_max_samples = kMaxRefSamples; + d.ref_max = 1; + } d.prompt_whole = 1; d.first_frame = 0; d.max_prompt = kMaxPrompt; @@ -1267,34 +1315,91 @@ static void step_backbone(RadCtx* c, const RadBatch* batch, const Model& m) { m.b_h2, m.b_gu, m.b_ff, pos, cu, layer++); } +static void step_text(RadCtx* c, const Model& m, int64_t T, RadOperand tokens, + RadOperand pos, RadOperand cu, RadOperand output) { + const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim; + /* The encoder over each branch's prompt, bidirectional within it; its projection is the + * backbone's input. */ + RAD_ISSUE_N(c, m.op_eembed, T, tokens, RAD_W(m.w_etok), + brows(m.b_ex, T)); + for (const EncLayer& L : m.enc) { + RAD_ISSUE_N(c, L.op_n1, T, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T)); + RAD_ISSUE_N(c, L.op_qkv, T, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T)); + RAD_ISSUE_N(c, L.op_qknr, T, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); + RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T), + bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T)); + RAD_ISSUE_N(c, L.op_o, T, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T)); + RAD_ISSUE_N(c, L.op_n2, T, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T)); + RAD_ISSUE_N(c, L.op_add1, T, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T)); + RAD_ISSUE_N(c, L.op_n3, T, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T)); + RAD_ISSUE_N(c, L.op_gu, T, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T)); + RAD_ISSUE_N(c, L.op_act, T, brows(m.b_egu, T), brows(m.b_eff, T)); + RAD_ISSUE_N(c, L.op_down, T, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T)); + RAD_ISSUE_N(c, L.op_n4, T, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T)); + RAD_ISSUE_N(c, L.op_add2, T, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T)); + } + RAD_ISSUE_N(c, m.op_enorm, T, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T)); + RAD_ISSUE_N(c, m.op_eproj, T, brows(m.b_eh, T), RAD_W(m.w_eproj), output); +} + +/* rvq_embed reads codebook 0 from its first table and codebooks 1..15 from its + * second table, whose row zero must therefore be the start of codebook 1. */ +static RadOperand residual_codebooks(const Model& m) { + RadOperand t = RAD_W(m.w_cb); + t.offset = (int64_t)kVocab * m.gl.n_embd; + t.rows = (int64_t)(kCodes - 1) * kVocab; + return t; +} + static void step_prompt(RadCtx* c, const RadBatch* batch, const Model& m) { const RadAudioGenBatch* A = batch->agen_b; const int64_t T = batch->n_tok; - const int64_t qd = m.ge.n_head * m.ge.head_dim, kd = m.ge.n_head_kv * m.ge.head_dim; - const RadOperand cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); - const RadOperand pos = praw(batch->positions, RAD_I32, T); - /* The encoder over each branch's prompt, bidirectional within it; its projection is the - * backbone's input. */ - RAD_ISSUE(c, m.op_eembed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_etok), - brows(m.b_ex, T)); - for (const EncLayer& L : m.enc) { - RAD_ISSUE(c, L.op_n1, brows(m.b_ex, T), RAD_W(L.w_n1), brows(m.b_eh, T)); - RAD_ISSUE(c, L.op_qkv, brows(m.b_eh, T), RAD_W(L.w_qkv), brows(m.b_eqkv, T)); - RAD_ISSUE(c, L.op_qknr, brows(m.b_eqkv, T), pos, RAD_W(L.w_qn), RAD_W(L.w_kn)); - RAD_ISSUE_N(c, L.op_attn, T, bcol(m.b_eqkv, 0, qd, T), bcol(m.b_eqkv, qd, kd, T), - bcol(m.b_eqkv, qd + kd, kd, T), cu, brows(m.b_eattn, T)); - RAD_ISSUE(c, L.op_o, brows(m.b_eattn, T), RAD_W(L.w_o), brows(m.b_eo, T)); - RAD_ISSUE(c, L.op_n2, brows(m.b_eo, T), RAD_W(L.w_n2), brows(m.b_eh, T)); - RAD_ISSUE(c, L.op_add1, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T)); - RAD_ISSUE(c, L.op_n3, brows(m.b_ex, T), RAD_W(L.w_n3), brows(m.b_eh, T)); - RAD_ISSUE(c, L.op_gu, brows(m.b_eh, T), RAD_W(L.w_gu), brows(m.b_egu, T)); - RAD_ISSUE(c, L.op_act, brows(m.b_egu, T), brows(m.b_eff, T)); - RAD_ISSUE(c, L.op_down, brows(m.b_eff, T), RAD_W(L.w_down), brows(m.b_eo, T)); - RAD_ISSUE(c, L.op_n4, brows(m.b_eo, T), RAD_W(L.w_n4), brows(m.b_eh, T)); - RAD_ISSUE(c, L.op_add2, brows(m.b_ex, T), brows(m.b_eh, T), brows(m.b_ex, T)); + if (A->n_ref) { + if (!A->prompt_cu_h || A->prompt_cu_h[0] != 0 || + A->prompt_cu_h[batch->n_seq] != T) { + rad_step_fail(c, "breeze: reference prompt needs its host branch boundaries"); + return; + } + step_reference(c, batch, m); + const Reference& E = m.ref; + RAD_ISSUE_N(c, E.text_indices, kMaxPrompt, brows(E.text_pos, kMaxPrompt)); + RAD_ISSUE_N(c, E.eos, 16, brows(E.eos_codes, 16)); + /* Each branch has two independent text-encoder segments around its audio. The + * backbone alone attends across the concatenation. Never encode audio placeholders + * or the audio EOS as text, and reset rotary positions for each text segment. */ + for (int64_t branch = 0; branch < batch->n_seq; ++branch) { + const int64_t end = A->prompt_cu_h[branch + 1]; + for (int64_t t = A->prompt_cu_h[branch]; t < end;) { + const int32_t f = A->ref_frame_h[t]; + if (f >= 0) { + int64_t n = 1; + while (t + n < end && A->ref_frame_h[t + n] == f + n) ++n; + if (t + n >= end) { + rad_step_fail(c, "breeze: reference frames need their audio EOS row"); + return; + } + RAD_ISSUE_N(c, E.embed, n, bcol(E.codes, f, n, 16), RAD_W(m.w_cb), + residual_codebooks(m), brow_slice(m.b_x, t, n, m.gl.n_embd)); + t += n; + RAD_ISSUE_N(c, E.embed, 1, brows(E.eos_codes, 16), RAD_W(m.w_cb), + residual_codebooks(m), brow_slice(m.b_x, t, 1, m.gl.n_embd)); + ++t; + } else { + int64_t n = 1; + while (t + n < end && A->ref_frame_h[t + n] < 0) ++n; + ref_bounds(c, E, E.text_cu, n); + step_text(c, m, n, praw(batch->token_ids + t, RAD_I32, n), + brows(E.text_pos, n), brows(E.text_cu, 2), + brow_slice(m.b_x, t, n, m.gl.n_embd)); + t += n; + } + } + } + } else { + step_text(c, m, T, praw(batch->token_ids, RAD_I32, T), + praw(batch->positions, RAD_I32, T), + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(m.b_x, T)); } - RAD_ISSUE(c, m.op_enorm, brows(m.b_ex, T), RAD_W(m.w_enorm), brows(m.b_eh, T)); - RAD_ISSUE(c, m.op_eproj, brows(m.b_eh, T), RAD_W(m.w_eproj), brows(m.b_x, T)); step_backbone(c, batch, m); bool any_last = false; for (int64_t i = 0; i < A->n_lane; ++i) any_last = any_last || A->last_h[i]; @@ -1358,10 +1463,8 @@ static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) { /* 3. the frame into its lane's history, and the backbone over the frame's embedding */ RAD_ISSUE_N(c, m.op_store, n, brows(m.b_codes, kCodes), lanes, frame, brows(m.b_status, m.lanes), brows(m.b_codes_all, m.lanes * kCodes)); - RadOperand t1 = RAD_W(m.w_cb); - t1.offset = (int64_t)kVocab * D; - t1.rows = (int64_t)(kCodes - 1) * kVocab; - RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), t1, brows(m.b_x, S)); + RAD_ISSUE_N(c, m.op_fb, S, brows(m.b_codes, kCodes), RAD_W(m.w_cb), residual_codebooks(m), + brows(m.b_x, S)); step_backbone(c, batch, m); store_hidden(c, m, A, S, A->last_row, S); } @@ -1504,6 +1607,11 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { static int64_t text_prepare(int field, const char* in, char* out, int64_t cap) { if (!in) return RAD_E_INVAL; std::string r = in; + if (field == RAD_TEXT_REFERENCE) { + for (const char* marker : {"", "", "<|AUDIO|>", "<|audio_eos|>", + "", ""}) + if (r.find(marker) != std::string::npos) return RAD_E_INVAL; + } if (field == RAD_TEXT_INSTRUCTIONS) { const size_t a = r.find_first_not_of(" \t\r\n"), z = r.find_last_not_of(" \t\r\n"); r = a == std::string::npos ? std::string() : r.substr(a, z - a + 1); diff --git a/arch/breeze/reference.h b/arch/breeze/reference.h new file mode 100644 index 00000000..c74e4e03 --- /dev/null +++ b/arch/breeze/reference.h @@ -0,0 +1,281 @@ +/* Breeze's Qwen3-TTS/Mimi reference encoder. Included inside namespace breeze after the + * ordinary networks. Kept in f32, as the released audio tokenizer encodes references. */ +static rad_op ref_rows(RadBuilder* b, const char* op, int64_t rows, int64_t n, + std::initializer_list in, std::initializer_list out, + const char* dtype = "f32") { + return rw(b, RAD_OP(b, op, RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", dtype)), RAD_NOWEIGHTS), in, out); +} + +static rad_op ref_gemm(RadBuilder* b, int64_t rows, int64_t n, int64_t k, rad_weight w, + rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n), + RAD_INT("K", k), RAD_STR("dtype", "f32")), RAD_WEIGHTS(w)), {x}, {y}); +} + +static int ref_conv(RadBuilder* b, Model& m, RefConv& C, const char* name, const char* src, + int64_t ci, int64_t co, int64_t k, int64_t st, int64_t rate, int64_t rows, + rad_buf x, rad_buf res, rad_buf y, bool bias = true) { + /* The first convolution's weight is mapped by reference_stored when that ran. */ + C.w = (m.ref_stored && &C == &m.ref.first) + ? decl_w(b, m.nm.f("ref.%s.weight", name), RAD_F32, {co, ci, k}, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(kGrpCodec + 1)) + : wcopy(b, m.nm, m.nm.f("ref.%s.weight", name), m.nm.ckpt("%s.weight", src), + RAD_F32, {co, ci, k}, kGrpCodec + 1); + if (bias) C.b = wcopy(b, m.nm, m.nm.f("ref.%s.bias", name), m.nm.ckpt("%s.bias", src), + RAD_F32, {co}, kGrpCodec + 1); + const rad_weight weights[] = {C.w, C.b}; + C.op = rw(b, RAD_OP(b, "conv1d", RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("cin", ci), + RAD_INT("cout", co), RAD_INT("k", k), RAD_INT("dil", 1), + RAD_INT("causal", 1), RAD_INT("stride", st), RAD_INT("cu_div", rate), + RAD_STR("dtype", "f32")), weights, bias ? 2 : 1), + {x, m.ref.cu, res}, {y}); + return C.w && (!bias || C.b) && C.op ? RAD_OK : RAD_E_INVAL; +} + +/* Whether the model holds the reference encoder, asked of its first convolution through the name + * map entry declared here (the one ref_conv would declare). A builder with no model behind it + * answers no. */ +static bool reference_stored(RadBuilder* b, Model& m) { + const std::string dn = m.nm.f("ref.first.weight"); + if (map_copy(b, dn.c_str(), + m.nm.ckpt("%s.weight", "audio_tokenizer.encoder.encoder.layers.0.conv")) < 0) + return false; + RadEncoding enc{}; + return weight_enc(b, dn.c_str(), &enc); +} + +static int declare_reference(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Reference& E = m.ref; + Names& nm = m.nm; + const char* ec = "audio_tokenizer.encoder_config"; + if (rad_meta_geti(meta, nm.f("%s.hidden_size", ec), 0) != 512 || + rad_meta_geti(meta, nm.f("%s.num_hidden_layers", ec), 0) != 8 || + rad_meta_geti(meta, nm.f("%s.num_filters", ec), 0) != 64 || + rad_meta_geti(meta, nm.f("%s.use_causal_conv", ec), 1) != 1 || + rad_meta_geti(meta, nm.f("%s.use_conv_shortcut", ec), 0) != 0) { + fprintf(stderr, "radiance: breeze: reference encoder is not the released Qwen3-TTS encoder\n"); + return RAD_E_UNSUPPORTED; + } + constexpr int64_t R = kMaxRefSamples / 960; /* SEANet's 25 Hz output */ + constexpr int64_t NI = 2 * kMaxPrompt + 3; + E.index = decl_b(b, nm.f("ref.index"), RAD_I32, {NI}, RAD_BUF_PERSIST); + E.indices = iota_op(b, NI, 0, 1, E.index); + E.cu = decl_b(b, nm.f("ref.cu"), RAD_I32, {2}, RAD_BUF_PERSIST); + E.text_pos = decl_b(b, nm.f("ref.text_pos"), RAD_I32, {kMaxPrompt}, RAD_BUF_PERSIST); + E.text_cu = decl_b(b, nm.f("ref.text_cu"), RAD_I32, {2}, RAD_BUF_PERSIST); + E.text_indices = iota_op(b, kMaxPrompt, 0, 1, E.text_pos); + E.copy_i = rw(b, RAD_OP(b, "int_affine", RAD_PARAMS(RAD_INT("M", 1), RAD_STR("src", "0"), + RAD_STR("mul", "1"), RAD_STR("add", "0")), RAD_NOWEIGHTS), + {E.index}, {E.cu, E.text_cu}); + E.copy_f = rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 512), + RAD_STR("from", "f32"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {}, {}); + int64_t rows = kMaxRefSamples, ch = 64, rate = 1; + static const int64_t stride[] = {4, 5, 6, 8}; + for (int i = 0; i < 5; ++i) { + E.x[i] = decl_b(b, nm.f("ref.x%d", i), RAD_F32, {rows, ch}); + E.a[i] = decl_b(b, nm.f("ref.a%d", i), RAD_F32, {rows, ch}); + E.elu[i] = ref_rows(b, "elu", rows, ch, {E.x[i]}, {E.a[i]}); + if (i < 4) { + E.h[i] = decl_b(b, nm.f("ref.h%d", i), RAD_F32, {rows, ch / 2}); + E.elu_h[i] = ref_rows(b, "elu", rows, ch / 2, {E.h[i]}, {E.h[i]}); + rows /= stride[i]; ch *= 2; + } + } + RAD_ARCH_TRY(ref_conv(b, m, E.first, "first", "audio_tokenizer.encoder.encoder.layers.0.conv", + 1, 64, 7, 1, 1, kMaxRefSamples, 0, 0, E.x[0])); + rows = kMaxRefSamples; ch = 64; rate = 1; + for (int i = 0; i < 4; ++i) { + const int li = 1 + 3 * i; + RAD_ARCH_TRY(ref_conv(b, m, E.res1[i], nm.f("res%d.1", i), + nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.block.1.conv", li), + ch, ch / 2, 3, 1, rate, rows, E.a[i], 0, E.h[i])); + RAD_ARCH_TRY(ref_conv(b, m, E.res2[i], nm.f("res%d.2", i), + nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.block.3.conv", li), + ch / 2, ch, 1, 1, rate, rows, E.h[i], E.x[i], E.x[i])); + RAD_ARCH_TRY(ref_conv(b, m, E.down[i], nm.f("down%d", i), + nm.ckpt("audio_tokenizer.encoder.encoder.layers.%d.conv", li + 2), + ch, 2 * ch, 2 * stride[i], stride[i], rate, rows, + E.a[i], 0, E.x[i + 1])); + rows /= stride[i]; rate *= stride[i]; ch *= 2; + } + E.z = decl_b(b, nm.f("ref.z"), RAD_F32, {R, 512}); + RAD_ARCH_TRY(ref_conv(b, m, E.last, "last", "audio_tokenizer.encoder.encoder.layers.14.conv", + 1024, 512, 3, 1, 960, R, E.a[4], 0, E.z)); + E.th = decl_b(b, nm.f("ref.th"), RAD_F32, {R, 512}); + E.qkv = decl_b(b, nm.f("ref.qkv"), RAD_F32, {R, 1536}); + E.attn = decl_b(b, nm.f("ref.attn"), RAD_F32, {R, 512}); + E.o = decl_b(b, nm.f("ref.o"), RAD_F32, {R, 512}); + E.ff = decl_b(b, nm.f("ref.ff"), RAD_F32, {R, 2048}); + E.act = decl_b(b, nm.f("ref.act"), RAD_F32, {R, 2048}); + for (int i = 0; i < 8; ++i) { + RefLayer& L = E.layer[i]; + auto w = [&](const char* dn, const char* sn, std::initializer_list sh) { + return wcopy(b, nm, nm.f("ref.t%d.%s", i, dn), + nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.%s", i, sn), + RAD_F32, sh, kGrpCodec + 1); + }; + L.n1 = w("n1", "input_layernorm.weight", {512}); + L.b1 = w("b1", "input_layernorm.bias", {512}); + L.n2 = w("n2", "post_attention_layernorm.weight", {512}); + L.b2 = w("b2", "post_attention_layernorm.bias", {512}); + L.ls1 = w("ls1", "self_attn_layer_scale.scale", {512}); + L.ls2 = w("ls2", "mlp_layer_scale.scale", {512}); + const char* qn = nm.f("ref.t%d.qkv", i); + RAD_ARCH_TRY(map_concat(b, qn, { + nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.q_proj.weight", i), + nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.k_proj.weight", i), + nm.ckpt("audio_tokenizer.encoder.encoder_transformer.layers.%d.self_attn.v_proj.weight", i)})); + L.qkv = decl_w(b, qn, RAD_F32, {1536, 512}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec + 1)); + L.o = w("out", "self_attn.o_proj.weight", {512, 512}); + L.fc1 = w("fc1", "mlp.fc1.weight", {2048, 512}); + L.fc2 = w("fc2", "mlp.fc2.weight", {512, 2048}); + auto ln = [&](rad_weight nw, rad_weight nb) { + return rw(b, RAD_OP(b, "layernorm", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", 512), + RAD_F64("eps", 1e-5), RAD_STR("dtype", "f32")), RAD_WEIGHTS(nw, nb)), + {E.z}, {E.th}); + }; + L.norm1 = ln(L.n1, L.b1); L.norm2 = ln(L.n2, L.b2); + L.proj = ref_gemm(b, R, 1536, 512, L.qkv, E.th, E.qkv); + L.rope = rw(b, RAD_OP(b, "rope", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("head_dim", 64), + RAD_INT("n_head", 8), RAD_INT("n_head_kv", 8), RAD_F64("theta", 10000), + RAD_F64("scale", 1), RAD_STR("mode", "neox")), RAD_NOWEIGHTS), + {E.qkv, E.index}, {E.qkv}); + L.attn = rw(b, RAD_OP(b, "attn_dense", RAD_PARAMS(RAD_RANGE("M", 1, R), + RAD_INT("head_dim", 64), RAD_INT("gqa", 1), RAD_INT("causal", 1), + RAD_F64("scale", 0.125), RAD_INT("window", 250), RAD_INT("max_seqlen", R), + RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {E.qkv, E.cu}, {E.attn}); + L.out = ref_gemm(b, R, 512, 512, L.o, E.attn, E.o); + L.f1 = ref_gemm(b, R, 2048, 512, L.fc1, E.th, E.ff); + L.act = ref_rows(b, "gelu", R, 2048, {E.ff}, {E.act}); + L.f2 = ref_gemm(b, R, 512, 2048, L.fc2, E.act, E.o); + auto scale = [&](rad_weight sw) { + return rw(b, RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), + RAD_INT("n", 512), RAD_STR("dtype", "f32")), RAD_WEIGHTS(sw)), {E.o}, {E.o}); + }; + L.scale1 = scale(L.ls1); L.scale2 = scale(L.ls2); + L.add1 = ref_rows(b, "add", R, 512, {E.z, E.o}, {E.z}); + L.add2 = ref_rows(b, "add", R, 512, {E.z, E.o}, {E.z}); + if (!L.n1 || !L.b1 || !L.n2 || !L.b2 || !L.qkv || !L.o || !L.fc1 || !L.fc2 || + !L.ls1 || !L.ls2 || !L.norm1 || !L.norm2 || !L.proj || !L.rope || !L.attn || + !L.out || !L.f1 || !L.act || !L.f2 || !L.scale1 || !L.scale2 || !L.add1 || !L.add2) + return RAD_E_INVAL; + } + /* The last downsample uses replicate padding. Prepending two copies of the first row, + * using the ordinary causal conv, then dropping its first output is exactly that pad. */ + E.pad = decl_b(b, nm.f("ref.pad"), RAD_F32, {R + 2, 512}); + E.sampled = decl_b(b, nm.f("ref.sampled"), RAD_F32, {kMaxRefFrames + 1, 512}); + RAD_ARCH_TRY(rad_op_reads(b, E.copy_f, &E.z, 1)); + RAD_ARCH_TRY(rad_op_writes(b, E.copy_f, &E.pad, 1)); + RAD_ARCH_TRY(ref_conv(b, m, E.sample, "sample", "audio_tokenizer.encoder.downsample.conv", + 512, 512, 4, 2, 1, R + 2, E.pad, 0, E.sampled, false)); + E.codes = decl_b(b, nm.f("ref.codes"), RAD_I32, {16, kMaxRefFrames}, RAD_BUF_PERSIST); + E.eos_codes = decl_b(b, nm.f("ref.eos_codes"), RAD_I32, {16, 1}, RAD_BUF_PERSIST); + for (int part = 0; part < 2; ++part) { + const char* qs = part ? "acoustic_residual_vector_quantizer" : "semantic_residual_vector_quantizer"; + E.q[part] = decl_b(b, nm.f("ref.q%d", part), RAD_F32, {kMaxRefFrames, 256}); + E.qi[part] = wcopy(b, nm, nm.f("ref.q%d.in", part), + nm.ckpt("audio_tokenizer.encoder.quantizer.%s.input_proj.weight", qs), + RAD_F32, {256, 512}, kGrpCodec + 1); + /* A 1x1 Conv1d weight's trailing singleton is immaterial to GEMM's matrix view. */ + E.project[part] = ref_gemm(b, kMaxRefFrames, 256, 512, E.qi[part], E.sampled, E.q[part]); + const int first = part ? 1 : 0, count = part ? 15 : 1; + for (int j = 0; j < count; ++j) { + const int k = first + j; + const char* dn = nm.f("ref.cb%d", k); + RAD_ARCH_TRY(map_ema(b, dn, + nm.ckpt("audio_tokenizer.encoder.quantizer.%s.layers.%d.codebook.embed_sum", qs, j), + nm.ckpt("audio_tokenizer.encoder.quantizer.%s.layers.%d.codebook.cluster_usage", qs, j))); + E.cb[k] = decl_w(b, dn, RAD_F32, {2048, 256}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec + 1)); + E.quant[k] = rw(b, RAD_OP(b, "vq_euclidean", RAD_PARAMS(RAD_RANGE("M", 1, kMaxRefFrames), + RAD_INT("n", 256), RAD_INT("bins", 2048), RAD_STR("dtype", "f32")), + RAD_WEIGHTS(E.cb[k])), {E.q[part]}, {E.q[part], E.codes}); + if (!E.cb[k] || !E.quant[k]) return RAD_E_INVAL; + } + if (!E.qi[part] || !E.project[part]) return RAD_E_INVAL; + } + E.embed = rw(b, RAD_OP(b, "rvq_embed", RAD_PARAMS(RAD_RANGE("M", 1, kMaxRefFrames), + RAD_INT("n_embd", m.gl.n_embd), RAD_INT("n_codes", 16), RAD_INT("vocab", kVocab), + RAD_INT("off0", 0), RAD_F64("scale", 1), RAD_INT("round", 1), + RAD_STR("dtype", "bf16")), RAD_WEIGHTS(m.w_cb, m.w_cb)), {E.codes}, {m.b_x}); + E.eos = iota_op(b, 16, 0, 0, E.eos_codes); + RAD_ARCH_TRY(rad_op_reads(b, E.embed, &E.eos_codes, 1)); + /* Both branches' text segments are encoded separately at position zero. These buffers must + * remain live through each segment's encoder, projection and the backbone prefill. */ + for (const EncLayer& L : m.enc) { + RAD_ARCH_TRY(rad_op_reads(b, L.op_qknr, &E.text_pos, 1)); + RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &E.text_cu, 1)); + } + return E.indices && E.copy_i && E.copy_f && E.text_indices && E.embed && E.eos ? RAD_OK : RAD_E_INVAL; +} + +/* Copy the endpoints of an iota into a two-entry cu, without a host upload or ABI change. */ +static void ref_bounds(RadCtx* c, const Reference& E, rad_buf cu, int64_t len) { + RAD_ISSUE_N(c, E.copy_i, 1, brow_slice(E.index, 0, 1, 1), brow_slice(cu, 0, 1, 1)); + RAD_ISSUE_N(c, E.copy_i, 1, brow_slice(E.index, len, 1, 1), brow_slice(cu, 1, 1, 1)); +} + +static void step_reference(RadCtx* c, const RadBatch* batch, const Model& m) { + const Reference& E = m.ref; + const auto* A = batch->agen_b; + const int64_t L = A->ref_samples, R = L / 960, F = R / 2; + RAD_ISSUE_N(c, E.indices, 2 * kMaxPrompt + 3, brows(E.index, 2 * kMaxPrompt + 3)); + const RadOperand raw_cu = praw(A->ref_cu, RAD_I32, 2); + auto conv = [&](const RefConv& C, RadOperand x, RadOperand res, RadOperand y, + int64_t rows, RadOperand cu) { + RAD_ISSUE_N(c, C.op, rows, x, RAD_W(C.w), cu, res, y, C.b ? RAD_W(C.b) : RAD_NONE); + }; + conv(E.first, praw(A->ref_audio, RAD_F32, L), RAD_NONE, brows(E.x[0], L), L, raw_cu); + static const int64_t stride[] = {4, 5, 6, 8}; + int64_t rows = L; + for (int i = 0; i < 4; ++i) { + RAD_ISSUE_N(c, E.elu[i], rows, brows(E.x[i], rows), brows(E.a[i], rows)); + conv(E.res1[i], brows(E.a[i], rows), RAD_NONE, brows(E.h[i], rows), rows, raw_cu); + RAD_ISSUE_N(c, E.elu_h[i], rows, brows(E.h[i], rows), brows(E.h[i], rows)); + conv(E.res2[i], brows(E.h[i], rows), brows(E.x[i], rows), brows(E.x[i], rows), rows, raw_cu); + RAD_ISSUE_N(c, E.elu[i], rows, brows(E.x[i], rows), brows(E.a[i], rows)); + conv(E.down[i], brows(E.a[i], rows), RAD_NONE, brows(E.x[i + 1], rows / stride[i]), rows, raw_cu); + rows /= stride[i]; + } + RAD_ISSUE_N(c, E.elu[4], R, brows(E.x[4], R), brows(E.a[4], R)); + conv(E.last, brows(E.a[4], R), RAD_NONE, brows(E.z, R), R, raw_cu); + ref_bounds(c, E, E.cu, R); + const RadOperand cu = brows(E.cu, 2), pos = brows(E.index, R); + for (const RefLayer& T : E.layer) { + auto norm = [&](rad_op op, rad_weight w, rad_weight bias) { + RAD_ISSUE_N(c, op, R, brows(E.z, R), RAD_W(w), RAD_W(bias), brows(E.th, R)); + }; + auto gemm = [&](rad_op op, rad_buf x, rad_weight w, rad_buf y) { + RAD_ISSUE_N(c, op, R, brows(x, R), RAD_W(w), brows(y, R)); + }; + norm(T.norm1, T.n1, T.b1); + gemm(T.proj, E.th, T.qkv, E.qkv); + RAD_ISSUE_N(c, T.rope, R, brows(E.qkv, R), pos); + RAD_ISSUE_N(c, T.attn, R, bcol(E.qkv, 0, 512, R), bcol(E.qkv, 512, 512, R), + bcol(E.qkv, 1024, 512, R), cu, brows(E.attn, R)); + gemm(T.out, E.attn, T.o, E.o); + RAD_ISSUE_N(c, T.scale1, R, brows(E.o, R), RAD_W(T.ls1), brows(E.o, R)); + RAD_ISSUE_N(c, T.add1, R, brows(E.z, R), brows(E.o, R), brows(E.z, R)); + norm(T.norm2, T.n2, T.b2); + gemm(T.f1, E.th, T.fc1, E.ff); + RAD_ISSUE_N(c, T.act, R, brows(E.ff, R), brows(E.act, R)); + gemm(T.f2, E.act, T.fc2, E.o); + RAD_ISSUE_N(c, T.scale2, R, brows(E.o, R), RAD_W(T.ls2), brows(E.o, R)); + RAD_ISSUE_N(c, T.add2, R, brows(E.z, R), brows(E.o, R), brows(E.z, R)); + } + RAD_ISSUE_N(c, E.copy_f, 1, brow_slice(E.z, 0, 1, 512), brow_slice(E.pad, 0, 1, 512)); + RAD_ISSUE_N(c, E.copy_f, 1, brow_slice(E.z, 0, 1, 512), brow_slice(E.pad, 1, 1, 512)); + RAD_ISSUE_N(c, E.copy_f, R, brows(E.z, R), brow_slice(E.pad, 2, R, 512)); + ref_bounds(c, E, E.cu, R + 2); + conv(E.sample, brows(E.pad, R + 2), RAD_NONE, brows(E.sampled, F + 1), R + 2, cu); + for (int p = 0; p < 2; ++p) { + RAD_ISSUE_N(c, E.project[p], F, brow_slice(E.sampled, 1, F, 512), RAD_W(E.qi[p]), brows(E.q[p], F)); + for (int k = p ? 1 : 0; k < (p ? 16 : 1); ++k) { + RadOperand codes = brow_slice(E.codes, k, 1, kMaxRefFrames); + codes.cols = F; + RAD_ISSUE_N(c, E.quant[k], F, brows(E.q[p], F), RAD_W(E.cb[k]), codes); + } + } +} diff --git a/arch/common/rad_block_muse_dflash.h b/arch/common/rad_block_muse_dflash.h new file mode 100644 index 00000000..03c2b7ed --- /dev/null +++ b/arch/common/rad_block_muse_dflash.h @@ -0,0 +1,1321 @@ +/* rad_block_muse_dflash.h -- Meta Muse Glimmer's DFlash block-diffusion drafter, bf16 weights. + * + * ============================== WHAT IT IS ============================== + * + * `meta-models/Muse-Glimmer-30B-assistant`: five plain attention layers that denoise a whole + * block of masked positions in one forward pass, conditioned on the target trunk's residual + * stream at layers 1, 13, 25, 37 and 49. The target then verifies the block in one parallel + * pass, so every proposal is checked and a bad draft costs speed, never text. + * + * Structurally it is the DSpark drafter (rad_block_dspark_bf16.h) exactly -- fc over the + * concatenated taps, one hidden norm, q from the noise rows and k/v projected from the shared + * context, plain q/k gains, SwiGLU, the target's own output table -- with three differences this + * block exists to state: + * + * * **No Markov head.** DSpark adds markov_w2 @ markov_w1[prev] to the draft logits; the Muse + * drafter has no such tensors, so its head is the plain full-vocabulary argmax of + * target.lm_head(output_norm(h)). `cfg.rank == 0` is the honest spelling of that. + * * **The anchor row does not predict.** The block is [the last accepted token, MASK x 15] and + * the reference takes logits from rows 1..15 (`last_hidden_state[:, 1:]`), so `steps()` is + * `block - 1`, as in Dflash2 rather than Dspark. + * * **No per-tap norm and no output gate** (`tap_norm = 0`, `gate = 0`): the reference has one + * RMS norm over the fused 5 x n_embd context, and no gate on the attention output. + * + * ============================== THE REFERENCE ============================== + * + * transformers' `MuseGlimmerAssistantModel.forward` plus the `DFlashTokenCandidateGenerator` that + * drives it: + * + * ctx = rmsnorm(fc(concat of the trunk's residual stream after layers 1,13,25,37,49)) + * h = target.embed_tokens([anchor, MASK x (block-1)]) the raw table, the trunk's + * embedding norm BYPASSED + * per layer (x5): + * h_n = input_layernorm(h) + * q = q_norm(q_proj(h_n)) + * k,v = k_norm(k_proj(concat(ctx, h))), v_proj(concat(ctx, h)) + * rope(q,k, theta 500000); attention is bidirectional over the block and causal to the + * context, inside a sliding window of 2048 + * h += o_proj(attn); h += down(act(gate(h_n2)) * up(h_n2)), act = silu + * logits = target.lm_head(norm(h))[1:] 15 drafts + * + * Two passes, as in Dflash2: the context pass projects and stores K/V for every committed token + * once per step; the query pass runs the 16 block rows through the five layers. The context K/V + * lives in the drafter's own paged group, written past `seqused` for the block rows so every row + * sees its siblings, and overwritten by the next context pass (the reference's cache.crop). + * + * ============================== PRECISION ============================== + * + * Block fp8 or OCP-MXFP4 weights (`DenseFP8`, whichever the recipe wrote), read against an E4M3 + * activation quantised per row and 128 of K; the residual stream stays f32, which is what the + * reference's autocast does and what keeps five stacked layers of 6656-wide adds from drifting. + * The per-head q/k gains and both norms stay bf16. + * + * ============================== SHARDING AND BATCHES ============================== + * + * The five layers split like the trunk's: q/k/v and gate_up by output rows, o and down by input + * columns, with an all_reduce after each of those two branches (a partial sum without it drafts + * nonsense -- measured as position-0 acceptance collapsing from 61% to 5%). The block embeds + * from the trunk's vocab-sharded table, so its lookup is partial too: an exact all_reduce sums + * the ranks' rows after `embed_lookup`, as the trunk's own embedding does. The head is the + * trunk's vocab-sharded table, so the draft argmax is distributed too: `row_topk` over this + * rank's slice reports global ids into a pair plane, `all_gather` moves the pairs and + * `pair_argmax` picks the winner, which is exactly `rad_gemma4_dflash.h`'s walk. kTopR is 2 + * because the gather moves 16-byte rows. + * + * Every buffer is sized [max_seqs * steps, ...] and the predicting rows are gathered by + * `RadBatch::out_ids`, so a batch of sequences drafts side by side; the proposal plane is + * sequence-major and the engine reads it with `proposal_pitch = steps`. + */ +#ifndef RAD_BLOCK_MUSE_DFLASH_H +#define RAD_BLOCK_MUSE_DFLASH_H + +#include "rad_arch.h" +#include "rad_fp8.h" /* DenseFP8: the block fp8 / MXFP4 linear */ + +namespace rad { +namespace arch { + +/* The builder refuses a declaration it cannot serve and says why in its own words; this names which + * handle did not come back, so that message reads against a line of this file. An op that resolves + * to no kernel is recorded and handed back null -- it is only an error if the block issues it -- so + * without this a missing kernel surfaces as a bare "invalid argument" at startup. */ +#define MD_REFUSED(...) ::rad::arch::muse_drafter_refused({ __VA_ARGS__ }) +inline int muse_drafter_refused(std::initializer_list what) { + std::string list; + for (const char* w : what) { if (!list.empty()) list += ", "; list += w; } + std::fprintf(stderr, "Muse Glimmer drafter: the builder gave no handle for %s\n", list.c_str()); + return RAD_E_INVAL; +} + +struct MuseDflash { + enum { MAX_LAYERS = 8 }; + + /* The drafter's config beyond its geometry. Everything here comes from the container's + * `draft.` keys; nothing is defaulted quietly, because a silently ignored gate or window only + * moves acceptance, which is the one number the user cannot see. */ + struct Config { + int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */ + int64_t block = 0; /* noise rows a sequence, and drafts (one per row) */ + int64_t rank = 0; /* markov_rank: the codebooks' width */ + int64_t window = 0; /* reference's anchor-aligned n_swa (configured history + 1) */ + int64_t rot = 0; /* rotary dimensions a head; 0 for all of head_dim */ + int causal = 0; + int tap_norm = 0; /* `fc_norm`: one RMS gain a tap before the concatenation */ + int qk_norm = 0; /* per-head q/k gains, and no output gate */ + int gate = 0; /* one sigmoid gate a head on the attention output */ + const char* act = "gelu"; /* the feed-forward's activation */ + int64_t steps() const { return block - 1; } /* the anchor row does not predict */ + }; + + struct Wire { + /* ---- the context pass, one row per committed token */ + rad_buf src = 0; /* [max_tok, n_taps * n_embd] the trunk's taps, read only */ + rad_buf srcn = 0; /* [max_tok, n_taps * n_embd] each tap normed, same layout */ + rad_buf c = 0, cn = 0; /* [max_tok, n_embd] fc output and separately normed context */ + rad_buf ck = 0, ckn = 0; /* [max_tok, kv_dim] projected and optionally normed K */ + rad_buf cv = 0; /* [max_tok, kv_dim] and its V */ + + /* ---- the query pass, `block` rows per sequence */ + rad_buf x = 0; /* [qrows, n_embd] f32 the drafter's residual stream */ + rad_buf delta = 0; /* [qrows, n_embd] f32 the block a projection just wrote */ + rad_buf h = 0; /* [qrows, n_embd] bf16 the normed stream, and every linear's output */ + rad_buf q = 0, k = 0, v = 0, qn = 0, kn = 0; + rad_buf gate = 0, gaten = 0; /* [qrows, n_head] projection and sigmoid */ + rad_buf attn = 0, attng = 0; /* [qrows, q_dim] attention and gated attention */ + rad_buf gate_up = 0; rad_buf ff = 0; + + /* ---- fp8 codes and scales of the activations the linears read (`quant_act_fp8`), one + * pair per activation rather than per linear: q, k and v all read the same `h`. The + * scale plane is one f32 a 128-value block (`fp8_blocks`), which is the grid a + * block-scaled fp8 GEMM reads (`DenseFP8`). */ + rad_buf srcq = 0, srcs = 0; /* [max_tok, n_taps * n_embd] e4m3 | [.., /128] f32 */ + rad_buf cnq = 0, cns = 0; /* [max_tok, n_embd] the normed context, k/v's input */ + rad_buf hq = 0, hs = 0; /* [qrows, n_embd] the normed stream */ + rad_buf atq = 0, ats = 0; /* [qrows, q_dim] the attention output, o's input */ + rad_buf ffq = 0, ffs = 0; /* [qrows, n_ff] the SwiGLU output, down's input */ + + /* ---- the head and the walk, one row per draft position */ + rad_buf hg = 0; /* [max_seqs*depth, n_embd] the predicting rows, gathered by out_ids */ + rad_buf cand = 0; /* [srows, kTopR] i32 this rank's candidate ids, when sharded */ + rad_buf unary = 0; /* [srows, kTopR] f32 their values */ + rad_buf dpair = 0; /* [srows, kTopR, 2] f32 the gather's pair plane */ + rad_buf dgath = 0; /* [srows, world * kTopR, 2] f32 */ + rad_buf dlog = 0; /* [srows, n_vocab] f32 full-vocabulary draft logits */ + rad_buf dlog_all = 0; /* [srows, n_vocab_all] bf16, the ranks' logits gathered */ + rad_buf dlog_bf = 0; /* [srows, n_vocab] bf16, row_topk's operand */ + rad_buf best_score = 0; /* [max_seqs, ceil(n_vocab/64)] f32 partial argmax scores */ + rad_buf best_token = 0; /* [max_seqs, ceil(n_vocab/64)] i32 partial argmax ids */ + rad_buf tokens = 0; /* [max_seqs, steps] i32 the draft; the engine reads it by name */ + }; + + Geom g{}; /* the drafter's geometry, not the trunk's */ + Config cfg{}; + Wire w{}; + int first_layer = 0; /* absolute, for the KV group's layer_slot lookup */ + /* The short block this drafter also serves (rad_drafter_short_block): 4 rows, 3 drafts. The + * whole block is staged and verified per sequence, so at several sequences its 13 extra rows + * cost more than the drafts they add. */ + int64_t block_lo = 0; + int64_t long_steps() const { return cfg.steps(); } + int64_t qrows = 0, crows = 0, srows = 0; + rad_kvgroup kv = 0; + + /* ---- model-scope weights */ + DenseFP8 w_fc{}; /* block fp8 or MXFP4, per the recipe */ + rad_weight b_fc = 0; /* the same linear in bf16, when nothing quantised it */ + bool quant = false; /* the container's linears are quantised */ + /* Test switch: declare the column-split linears (o, down) replicated instead of split plus an + * all_reduce, to tell a wrong reduce from a wrong split. */ + static constexpr bool kRepOut = false; + /* Test switch: at a vocab-sharded head, all-gather the draft logits and take a plain argmax + * instead of the top-2 pair walk. Same answer by construction, so a difference is the walk's. */ + static constexpr bool kGatherLogits = true; + rad_weight w_hnorm = 0, w_norm = 0; + rad_weight w_fcnorm[MAX_LAYERS] = {}; /* one row of `fc_norm` a tap */ + rad_weight w_mk1 = 0, w_mk2 = 0; /* markov_w1 (pred), markov_w2 (succ) */ + rad_weight w_tok = 0; /* the target's embedding table */ + rad_weight w_head = 0; /* the target's output table */ + + /* ---- per-layer weights */ + rad_weight w_anorm[MAX_LAYERS] = {}, w_fnorm[MAX_LAYERS] = {}; + DenseFP8 w_q[MAX_LAYERS]{}, w_k[MAX_LAYERS]{}, w_v[MAX_LAYERS]{}, w_o[MAX_LAYERS]{}; + rad_weight b_q[MAX_LAYERS] = {}, b_k[MAX_LAYERS] = {}, b_v[MAX_LAYERS] = {}, b_o[MAX_LAYERS] = {}; + rad_weight w_qn[MAX_LAYERS] = {}, w_kn[MAX_LAYERS] = {}, w_gate[MAX_LAYERS] = {}; + DenseFP8 w_gu[MAX_LAYERS]{}, w_dn[MAX_LAYERS]{}; + rad_weight b_gu[MAX_LAYERS] = {}, b_dn[MAX_LAYERS] = {}; + + /* ---- the context pass */ + rad_op op_tapn[MAX_LAYERS] = {}; /* one per tap, not per layer */ + rad_op op_cfc = 0, op_cnorm = 0; + rad_op op_ck[MAX_LAYERS] = {}, op_cv[MAX_LAYERS] = {}, op_cknorm[MAX_LAYERS] = {}; + rad_op op_crope = 0, op_cstore = 0; + + /* ---- the query pass. The weightless ops are declared once and issued per layer; the ones + * with weights are per layer, since a weight's prefetch interval and residency class come + * from the op that declares it. */ + rad_op op_embed = 0, op_embed_ar = 0, op_widen = 0, op_add = 0; + rad_op op_anorm[MAX_LAYERS] = {}, op_fnorm[MAX_LAYERS] = {}, op_outnorm = 0; + rad_op op_qp[MAX_LAYERS] = {}, op_kp[MAX_LAYERS] = {}, op_vp[MAX_LAYERS] = {}; + rad_op op_qn[MAX_LAYERS] = {}, op_kn[MAX_LAYERS] = {}, op_gp[MAX_LAYERS] = {}; + rad_op op_op[MAX_LAYERS] = {}, op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; + rad_op op_widen2 = 0, op_widen3 = 0; + rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0; + /* one activation quantiser an input */ + rad_op op_qsrc = 0, op_qcn = 0, op_qh = 0, op_qat = 0, op_qff = 0; + /* The fused forms, where a kernel serves them: norm+quantise in one launch, and the + * gate_up|silu|quantise fold. 0 falls back to the pair/triple. */ + /* Bisect switches: which of the two fusions this build takes. */ + rad_op op_gug[MAX_LAYERS] = {}; + int64_t gated_rows = 0; + rad_op op_sig = 0, op_gate_heads = 0, op_act = 0; + + /* ---- the head and the walk */ + rad_op op_dgather_rows = 0, op_dlogits = 0, op_markov = 0, op_dlogbf = 0; + rad_op op_dgather = 0, op_pick = 0; + rad_op op_dgath_lg = 0, op_tok_all = 0; /* the gathered-logits path, when declared */ + /* The column-split output projections leave each rank a partial sum, which the whole world + * must add: the same all_reduce the trunk runs after its own attention and MLP branches. */ + rad_op op_ar = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer, + rad_kvgroup group, rad_weight tok_embd, const char* ck, rad_weight head_w, + const Wire& wire); + /* The context pass, one row per committed token. */ + void context(RadCtx* c, const RadBatch* batch) const; + /* The query pass, the head and the Markov walk, `block` rows per sequence. */ + void step(RadCtx* c, const RadBatch* batch) const; + +private: + int64_t q_dim() const { return g.n_head * g.head_dim; } + int64_t kv_dim() const { return g.n_head_kv * g.head_dim; } +}; + +/* ------------------------------------------------------------------------------ declare */ + +inline int MuseDflash::declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, + int base_layer, rad_kvgroup group, rad_weight tok_embd, + const char* ck, rad_weight head_w, const Wire& wire) { + g = geom; cfg = c; w = wire; first_layer = base_layer; kv = group; w_tok = tok_embd; + w_head = head_w; + if (!ck || !w_head || !w_tok) return MD_REFUSED("ck", "w_head", "w_tok"); + if (g.n_layer <= 0 || g.n_layer > MAX_LAYERS) { + fprintf(stderr, "radiance: the bf16 Muse Glimmer drafter has %lld layers; this block carries at " + "most %d\n", (long long)g.n_layer, MAX_LAYERS); + return RAD_E_UNSUPPORTED; + } + if (cfg.n_taps <= 0 || cfg.n_taps > MAX_LAYERS || cfg.block < 2 || cfg.rank < 0) + return RAD_E_INVAL; + if (cfg.qk_norm && cfg.gate) { + fprintf(stderr, "radiance: the drafter declares both per-head q/k norms and a per-head " + "output gate; no published drafter ships both, and this block would have " + "to guess which one the checkpoint trained with\n"); + return RAD_E_UNSUPPORTED; + } + /* At tp > 1 the head is vocab-sharded and the draft argmax runs over the ranks' slices + * (row_topk with vocab_off -> all_gather -> pair_argmax): every rank holds the same global + * top-1, so the proposal matches the replicated one. */ + + const int64_t qd = q_dim(), kvd = kv_dim(), E = g.n_embd; + crows = g.max_tok; + qrows = g.max_seqs * cfg.block; + if (qrows > g.max_tok) qrows = g.max_tok; + srows = g.max_seqs * cfg.steps(); /* every row predicts */ + if (qrows <= 0 || srows <= 0 || cfg.rot < 0 || cfg.rot > g.head_dim || cfg.rot % 2) + return RAD_E_INVAL; + const int64_t rot = cfg.rot ? cfg.rot : g.head_dim; + + /* Vocab-sharded, the head's rows are this rank's slice and the top-1 must be taken over + * every rank's slice. kTopR = 2 because the gather moves 16-byte rows. */ + const bool sharded = vocab_head_sharded(g); + const int64_t kTopR = sharded ? 2 : 1; + + /* One op declaration per kernel shape, shared by the layers: `rmsnorm`'s and `gemm_nt`'s + * parameters are geometry, and only the weights differ per layer. */ + auto gemm = [&](int64_t rows, int64_t n, int64_t k, rad_weight wt, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", n), + RAD_INT("K", k), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(wt)), + {x}, {y}); + }; + /* A linear over a quantised weight: DenseFP8 picks `fp8a8` or `mxfp4a8` from the container's + * encoding of that weight, and both read the same E4M3 activation pair. */ + auto qgemm = [&](int64_t rows, int64_t n, int64_t k, DenseFP8& wt, + rad_buf xq, rad_buf xs, rad_buf y) { + return wt.gemm(b, rows, n, k, {xq, xs}, {y}); + }; + /* One quantiser per linear input. `h` takes two a layer, because the attention and + * feed-forward norms each rewrite it. */ + auto qact = [&](rad_buf x, rad_buf xq, rad_buf xs, int64_t rows, int64_t n) { + return rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {x}, {xq, xs}); + }; + + /* ---------------------------------------------------------------- model-scope weights */ + { + const char* wn = nm.f("dspark.fc.weight"); + RAD_ARCH_TRY(map_linear(b, wn, { nm.ckpt("%s.encoder.fc.weight", ck) })); + RadEncoding enc{}; + /* `weight_enc` is true for a plain bf16 plane too, so ask which encoding: block fp8 + * (e4m3 codes, bf16 scale per 128x128), OCP-MXFP4 or M2XFP4 are what `DenseFP8` reads. */ + const RadEncPlane* sc = nullptr; + const bool known = weight_enc(b, wn, &enc); + const bool blk_fp8 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 2 && + !enc.transform[0] && enc.plane[0].dtype == RAD_F8E4M3 && + (sc = rad_enc_plane(&enc, "scale")) && + sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK; + quant = blk_fp8 || (known && (linear_is_mxfp4(enc) || linear_is_m2xfp4(enc))); + if (quant) { + RAD_ARCH_TRY(w_fc.declare(b, nm, nm.f("dspark.fc"), E, cfg.n_taps * E, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model(), + { nm.ckpt("%s.encoder.fc.weight", ck) }, {}, true)); + } else { + b_fc = decl_w(b, wn, RAD_BF16, {E, cfg.n_taps * E}, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_model()); + } + } + RAD_ARCH_TRY(map_copy(b, nm.f("dspark.hidden_norm.weight"), + nm.ckpt("%s.encoder.output_norm_enc.weight", ck))); + w_hnorm = decl_w(b, nm.f("dspark.hidden_norm.weight"), RAD_BF16, {E}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + RAD_ARCH_TRY(map_copy(b, nm.f("dspark.norm.weight"), nm.ckpt("%s.norm.weight", ck))); + w_norm = decl_w(b, nm.f("dspark.norm.weight"), RAD_BF16, {E}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + if (!(quant ? (w_fc.w && w_fc.s) : b_fc) || !w_hnorm || !w_norm) + return MD_REFUSED("w_fc", "w_hnorm", "w_norm"); + fprintf(stderr, "I speculation: 'muse_dflash' reads %s linears\n", + quant ? "quantised (block fp8 / MXFP4)" : "bf16"); + + /* `fc_norm` is [n_taps, n_embd]: one gain row a tap, read as that tap's slice. */ + if (cfg.tap_norm) { + const char* src = nm.ckpt("%s.fc_norm.weight", ck); + for (int64_t t = 0; t < cfg.n_taps; ++t) { + const int i = (int)t; + RAD_ARCH_TRY(map_rows(b, nm.f("dspark.fc_norm.%d.weight", i), + { { src, (int)t, 1 } })); + w_fcnorm[i] = decl_w(b, nm.f("dspark.fc_norm.%d.weight", i), RAD_BF16, {E}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + if (!w_fcnorm[i]) return MD_REFUSED("w_fcnorm[i]"); + } + } + + /* The Markov codebooks, bf16, replicated over the whole vocabulary: both are [vocab, rank], so + * `w2 @ w1[prev]` is ``. RAD_ACCESS_VOCAB: each walk position reads one + * predecessor row and scans every successor row. */ + /* The Markov codebooks exist only in drafters that were trained with one; the Muse assistant + * has none, and `rank == 0` leaves the head a plain full-vocabulary argmax below. */ + if (cfg.rank > 0) { + RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w1"), + nm.ckpt("%s.markov_head.markov_w1.weight", ck))); + RAD_ARCH_TRY(map_copy(b, nm.f("dspark.markov_w2"), + nm.ckpt("%s.markov_head.markov_w2.weight", ck))); + w_mk1 = decl_w(b, nm.f("dspark.markov_w1"), RAD_BF16, {g.n_vocab_all, cfg.rank}, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + w_mk2 = decl_w(b, nm.f("dspark.markov_w2"), RAD_BF16, {g.n_vocab_all, cfg.rank}, + RAD_ACCESS_VOCAB, RAD_SHARD_NONE, grp_model()); + if (!w_mk1 || !w_mk2) return MD_REFUSED("w_mk1", "w_mk2"); + } + + /* The target's output table under the drafter's own name: one stored tensor, two arch weights, + * as rad_block_dspark.h does for its 2-bit copy. bf16 and replicated here, since the drafter + * reads it as the head its full-vocabulary walk scores (see NOT DONE for sharding). */ + /* One stored tensor, two arch weights: the trunk's output table under the drafter's own name. + * The encoding is whatever the recipe planned for the trunk's head (`output.weight`), so an + * int8 or MXFP4 head is read by the same `logits_gemm` the trunk uses and nothing is stored + * twice. */ + /* The head is the trunk's own declared output table, passed in: one stored tensor, read by the + * same `logits_gemm` the trunk uses, so an int8 or MXFP4 head costs the drafter nothing and the + * draft logits match the trunk's scale exactly. */ + + /* ---------------------------------------------------------------- per-layer weights + * + * One name map and one declaration a weight, spelled out: the list is the readable form of + * which checkpoint tensor feeds which matmul, and a drafter has few enough of them that a + * table would only hide it. */ + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + const RadWeightGroup grp = grp_layer(first_layer + i); + + /* A norm gain: f32, read whole, never sharded. */ + auto norm_w = [&](rad_weight* out, const char* suffix, const char* from, + std::initializer_list shape) -> int { + const char* name = nm.f("dspark.blk.%d.%s", i, suffix); + RAD_ARCH_TRY(map_copy(b, name, nm.ckpt("%s.layers.%d.%s", ck, i, from))); + *out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + return *out ? RAD_OK : RAD_E_INVAL; + }; + /* A linear, block fp8 or MXFP4 as the recipe wrote it (`DenseFP8::declare` reads which + * from the container's encoding and maps the name itself). More than one source is a + * concatenation, whose row parts say where each piece begins, so `act_mul` reads + * [gate | up] as one weight. */ + auto lin_w = [&](DenseFP8* out, rad_weight* bout, const char* suffix, + std::initializer_list srcs, + std::initializer_list shape, + std::initializer_list parts = {}, + int shard = RAD_SHARD_NONE) -> int { + int64_t N = 0, K = 0; + auto it = shape.begin(); + if (it != shape.end()) N = *it++; + if (it != shape.end()) K = *it; + const char* base = nm.f("dspark.blk.%d.%s", i, suffix); + const char* wn = nm.f("%s.weight", base); + RAD_ARCH_TRY(map_linear(b, wn, srcs)); + if (quant) + return out->declare(b, nm, base, N, K, RAD_ACCESS_PER_TOKEN, shard, grp, srcs, + parts, true); + *bout = decl_w(b, wn, RAD_BF16, {N, K}, RAD_ACCESS_PER_TOKEN, shard, grp, 0, parts); + return *bout ? RAD_OK : RAD_E_INVAL; + }; + /* The output gate, when a drafter ships one, stays bf16: it is [n_head, n_embd] and no + * recipe quantises it. */ + auto lin_b = [&](rad_weight* out, const char* suffix, + std::initializer_list srcs, + std::initializer_list shape) -> int { + const char* name = nm.f("dspark.blk.%d.%s", i, suffix); + RAD_ARCH_TRY(map_copy(b, name, *srcs.begin())); + *out = decl_w(b, name, RAD_BF16, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp); + return *out ? RAD_OK : RAD_E_INVAL; + }; + +#define SRC(path) nm.ckpt("%s.layers.%d." path, ck, i) + RAD_ARCH_TRY(norm_w(&w_anorm[i], "attn_norm.weight", "input_layernorm.weight", {E})); + RAD_ARCH_TRY(norm_w(&w_fnorm[i], "ffn_norm.weight", "post_attention_layernorm.weight", {E})); + /* Row-split outputs shard by head; column-split inputs shard the residual axis. The + * attention kernel reads a per-rank head slice, so q/k/v split rows and o splits its + * input columns, which is the same plan the trunk's own layers take. */ + RAD_ARCH_TRY(lin_w(&w_q[i], &b_q[i], "attn_q", { SRC("self_attn.q_proj.weight") }, {qd, E}, {}, + RAD_SHARD_ROW)); + RAD_ARCH_TRY(lin_w(&w_k[i], &b_k[i], "attn_k", { SRC("self_attn.k_proj.weight") }, {kvd, E}, {}, + RAD_SHARD_ROW)); + RAD_ARCH_TRY(lin_w(&w_v[i], &b_v[i], "attn_v", { SRC("self_attn.v_proj.weight") }, {kvd, E}, {}, + RAD_SHARD_ROW)); + RAD_ARCH_TRY(lin_w(&w_o[i], &b_o[i], "attn_output", { SRC("self_attn.o_proj.weight") }, {E, qd}, {}, + kRepOut ? RAD_SHARD_NONE : RAD_SHARD_COL)); + RAD_ARCH_TRY(lin_w(&w_gu[i], &b_gu[i], "ffn_gate_up", + { SRC("mlp.gate_proj.weight"), SRC("mlp.up_proj.weight") }, + {2 * g.n_ff, E}, { g.n_ff, g.n_ff }, RAD_SHARD_ROW)); + RAD_ARCH_TRY(lin_w(&w_dn[i], &b_dn[i], "ffn_down", { SRC("mlp.down_proj.weight") }, + {E, g.n_ff}, {}, kRepOut ? RAD_SHARD_NONE : RAD_SHARD_COL)); + if (cfg.gate) + RAD_ARCH_TRY(lin_b(&w_gate[i], "attn_gate", { SRC("self_attn.g_proj.weight") }, + {g.n_head, E})); + if (cfg.qk_norm) { + RAD_ARCH_TRY(norm_w(&w_qn[i], "attn_q_norm.weight", "self_attn.q_norm.weight", + {g.head_dim})); + RAD_ARCH_TRY(norm_w(&w_kn[i], "attn_k_norm.weight", "self_attn.k_norm.weight", + {g.head_dim})); + } +#undef SRC + } + + /* Non-causal: every query row sees its whole block and the context the trunk committed + * (`causal` comes from `draft.is_causal`). Declared before both kv_stores, which read the + * resolved `block_size` back with rad_kv_block_size(); before it, that returns zero. */ + /* `attn_paged` at causal=0 is the bidirectional block over a windowed key plane. The + * anchor-window variant has no gqa 4 band at head_dim 128 (Muse's 32/8 split), and its + * mask is anchor-aligned where the reference's is distance-aligned. */ + op_attn = rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, cfg.block), RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", cfg.causal), + RAD_INT("window", cfg.window), RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {cfg.qk_norm ? w.qn : w.q}, {w.attn}); + if (!op_attn) return MD_REFUSED("op_attn"); + + /* ---------------------------------------------------------------- the context pass + * + * One row per committed token, run once per trunk step: the taps become the drafter's own K + * and V. Nothing here is per query row, so its cost follows the trunk's token count, not the + * block's. */ + /* `fc_norm` exists only in drafters that norm each tap on its own; without it `fc` reads the + * trunk's stream directly, so neither the per-tap norm nor its output buffer is declared. */ + if (cfg.tap_norm) + for (int64_t t = 0; t < cfg.n_taps; ++t) { + const int i = (int)t; + op_tapn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_fcnorm[i])), + {w.src}, {w.srcn}); + if (!op_tapn[i]) return MD_REFUSED("op_tapn[i]"); + } + /* The query pass quantises `h` after each norm and `ff` before down; `attn`'s quantiser is + * declared in the query pass below, where step() issues it. */ + op_qh = qact(w.h, w.hq, w.hs, qrows, E); + op_qff = qact(w.ff, w.ffq, w.ffs, qrows, g.n_ff); + op_qsrc = qact(cfg.tap_norm ? w.srcn : w.src, w.srcq, w.srcs, crows, cfg.n_taps * E); + op_cfc = quant ? qgemm(crows, E, cfg.n_taps * E, w_fc, w.srcq, w.srcs, w.c) + : gemm(crows, E, cfg.n_taps * E, b_fc, cfg.tap_norm ? w.srcn : w.src, w.c); + op_cnorm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("n", E), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_hnorm)), + {w.c}, {w.cn}); + op_qcn = qact(w.cn, w.cnq, w.cns, crows, E); + if (!op_qsrc || !op_qcn || !op_cfc || !op_cnorm) + return MD_REFUSED("op_qsrc", "op_qcn", "op_cfc", "op_cnorm"); + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + /* One op per weight: an op's declared weight list gives each weight its prefetch interval + * and residency class. */ + op_ck[i] = quant ? qgemm(crows, kvd, E, w_k[i], w.cnq, w.cns, w.ck) + : gemm(crows, kvd, E, b_k[i], w.cn, w.ck); + op_cv[i] = quant ? qgemm(crows, kvd, E, w_v[i], w.cnq, w.cns, w.cv) + : gemm(crows, kvd, E, b_v[i], w.cn, w.cv); + if (!op_ck[i] || !op_cv[i]) return MD_REFUSED("op_ck[i]", "op_cv[i]"); + if (cfg.qk_norm) { + op_cknorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, crows * g.n_head_kv), + RAD_INT("n", g.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_kn[i])), + {w.ck}, {w.ckn}); + if (!op_cknorm[i]) return MD_REFUSED("op_cknorm[i]"); + } + } + + /* K-only rope: `rope` rotates the first n_head + n_head_kv heads, so a K-only tensor is + * n_head = n_head_kv, n_head_kv = 0. Weightless, so one op serves every layer. Each context + * row is rotated by its own absolute position, as the reference's single concatenated rope + * does. */ + op_crope = rw(b, decl_rope(b, g, crows, g.head_dim, g.n_head_kv, 0, rot, "neox"), + {cfg.qk_norm ? w.ckn : w.ck}, {cfg.qk_norm ? w.ckn : w.ck}); + op_cstore = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {cfg.qk_norm ? w.ckn : w.ck, w.cv}, {}); + if (!op_crope || !op_cstore) return MD_REFUSED("op_crope", "op_cstore"); + + /* ---------------------------------------------------------------- the query pass + * + * `block` rows per sequence, through the drafter's layers. The residual stream is f32 and the + * linears read bf16, exactly as the trunk keeps them: `rmsnorm` reads the stream and writes the + * activations, `cast` widens a projection's output, and `add` keeps the sum in f32. */ + op_embed = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n_embd", E), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"), + RAD_INT("vocab_offset", g.vocab_off)), + RAD_WEIGHTS(w_tok)), + {}, {w.h}); + /* The target's embedding table is vocab-sharded, so the lookup is partial: this rank's slice + * writes its rows, `embed_lookup` writes zero rows for the rest, and the exact all-reduce + * below sums the ranks into h -- the same reduce the trunk's own embedding runs, and dflash2's + * and dspark's. Exact, because a lossy wire would move the one embedded anchor row the whole + * block conditions on. */ + 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", E, qrows * E), + RAD_STR("dtype", "bf16"), RAD_INT("exact", 1)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + op_widen = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + {w.h}, {w.x}); + /* One widen and one add serve both residual sites a layer: same shapes, same buffers. */ + op_widen2 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E), + RAD_STR("from", "bf16"), RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + {w.h}, {w.delta}); + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {w.x, w.delta}, {w.x}); + /* `attn`'s quantiser, declared here rather than with the others so the attention buffer's + * declared life reaches into the query pass: declared with them, it ends before the stream's + * begins, and the planner could lay `attn` over the residual the adds still read (the same + * liveness rule the norms below follow). */ + op_qat = qact(cfg.gate ? w.attng : w.attn, w.atq, w.ats, qrows, qd); + if (!op_embed || !op_widen || !op_widen2 || !op_add || !op_qat) + return MD_REFUSED("op_embed", "op_widen", "op_widen2", "op_add", "op_qat"); + if (g.world > 1 && !op_embed_ar) return MD_REFUSED("op_embed_ar"); + + /* Invariant: the norms are declared where step() issues them. Declaration order is the buffer + * planner's liveness (core/build/rad_bufplan.cpp), and the stream `x` lives over the ops that + * touch it: each layer's two norms in the loop, the final one after everything the layers + * issue. Declared up front, the stream's lifetime would end before the layers and the planner + * could overlay a feed-forward temporary on it. */ + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + op_anorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_anorm[i])), + {w.x}, {w.h}); + op_qp[i] = quant ? qgemm(qrows, qd, E, w_q[i], w.hq, w.hs, w.q) + : gemm(qrows, qd, E, b_q[i], w.h, w.q); + op_kp[i] = quant ? qgemm(qrows, kvd, E, w_k[i], w.hq, w.hs, w.k) + : gemm(qrows, kvd, E, b_k[i], w.h, w.k); + op_vp[i] = quant ? qgemm(qrows, kvd, E, w_v[i], w.hq, w.hs, w.v) + : gemm(qrows, kvd, E, b_v[i], w.h, w.v); + op_op[i] = quant ? qgemm(qrows, E, qd, w_o[i], w.atq, w.ats, w.h) + : gemm(qrows, E, qd, b_o[i], cfg.gate ? w.attng : w.attn, w.h); + op_fnorm[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_fnorm[i])), + {w.x}, {w.h}); + op_gu[i] = quant ? qgemm(qrows, 2 * g.n_ff, E, w_gu[i], w.hq, w.hs, w.gate_up) + : gemm(qrows, 2 * g.n_ff, E, b_gu[i], w.h, w.gate_up); + /* One launch for gate_up, silu and the E4M3 quantise (`gemm_nt_q_gated` / + * `gemm_nt_q_gated_mx`): it writes the quantised SwiGLU output down reads, so `w.ff` + * stays for the fallback. */ + if (quant) + op_gug[i] = (w_gu[i].mx || w_gu[i].m2x) + ? decl_gated_fold_mx(b, qrows, 2 * g.n_ff, E, w_gu[i].w, w_gu[i].s, + w_gu[i].ref, {w.hq, w.hs}, {w.ffq, w.ffs}, + &gated_rows) + : decl_gated_fold(b, qrows, 2 * g.n_ff, E, w_gu[i].w, w_gu[i].s, + {w.hq, w.hs}, {w.ffq, w.ffs}, &gated_rows, true); + op_dn[i] = quant ? qgemm(qrows, E, g.n_ff, w_dn[i], w.ffq, w.ffs, w.h) + : gemm(qrows, E, g.n_ff, b_dn[i], w.ff, w.h); + if (!op_anorm[i] || !op_qp[i] || !op_kp[i] || !op_vp[i] || !op_op[i] || !op_fnorm[i] || + !op_gu[i] || !op_dn[i]) + return RAD_E_INVAL; + if (cfg.qk_norm) { + op_qn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_qn[i])), + {w.q}, {w.qn}); + op_kn[i] = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_kn[i])), + {w.k}, {w.kn}); + if (!op_qn[i] || !op_kn[i]) return MD_REFUSED("op_qn[i]", "op_kn[i]"); + } + if (cfg.gate) { + op_gp[i] = gemm(qrows, g.n_head, E, w_gate[i], w.h, w.gate); + if (!op_gp[i]) return MD_REFUSED("op_gp[i]"); + } + } + + op_qrope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head, 0, rot, "neox"), + {cfg.qk_norm ? w.qn : w.q}, {cfg.qk_norm ? w.qn : w.q}); + op_krope = rw(b, decl_rope(b, g, qrows, g.head_dim, g.n_head_kv, 0, rot, "neox"), + {cfg.qk_norm ? w.kn : w.k}, {cfg.qk_norm ? w.kn : w.k}); + op_store = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {cfg.qk_norm ? w.kn : w.k, w.v}, {}); + /* The gate the trunk uses too: one sigmoid a head, then one scale a head's whole row. */ + if (cfg.gate) { + op_sig = rw(b, RAD_OP(b, "sigmoid", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_head), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {w.gate}, {w.gaten}); + op_gate_heads = rw(b, RAD_OP(b, "scale_rows", + RAD_PARAMS(RAD_RANGE("M", 1, qrows * g.n_head), + RAD_INT("n", g.head_dim), RAD_STR("act", "none"), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {w.attn, w.gaten}, {w.attng}); + if (!op_sig || !op_gate_heads) return MD_REFUSED("op_sig", "op_gate_heads"); + } + /* `act_mul` with the activation the drafter was trained with: exact-erf gelu for the Spark + * drafts (`hidden_activation: gelu`), silu for a Qwen3-shaped one. `gelu_mul` is the tanh + * approximation and is not what the reference runs. */ + op_act = rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", g.n_ff), + RAD_STR("act", cfg.act), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {w.gate_up}, {w.ff}); + 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", "bf16"), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + op_outnorm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("n", E), + RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + if (!op_qrope || !op_krope || !op_store || !op_act || !op_outnorm) + return MD_REFUSED("op_qrope", "op_krope", "op_store", "op_act", "op_outnorm"); + + /* ---------------------------------------------------------------- the head and full-vocabulary walk + * + * Every row predicts, so the head scores all `steps` rows, anchor included. The row order is + * sequence-major, which is the selector's [sequence, position, vocabulary] contract. The + * greedy Markov op scans all vocabulary entries at every position and feeds each winning id + * into the next position's bigram bias. + */ + /* The block's 16 rows are [anchor, MASK x 15] and the anchor row predicts nothing: the engine + * names the predicting rows in RadBatch::out_ids -- one entry per drafting sequence, `block` + * staged rows, `out_ids` each entry's last `steps` rows (the scheduler's block_query) -- and + * the gather below picks them out of the staged block. "The last S rows" of the block is only + * the same list when EVERY staged sequence drafts; with several, it drops each sequence's + * first mask row and reads its neighbour's anchor, whose logits then pose as that + * sequence's first draft. */ + op_dgather_rows = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", E), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {w.h}, {w.hg}); + op_dlogits = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n_vocab", g.n_vocab), + RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_head)), + {w.hg}, {w.dlog}); + if (cfg.rank > 0) { + op_markov = rw(b, RAD_OP(b, "dflash_markov_greedy_f32", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), + RAD_INT("steps", cfg.steps()), RAD_INT("rank", cfg.rank), + RAD_INT("n_vocab", g.n_vocab_all), + RAD_INT("anchor_stride", cfg.block), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_mk1, w_mk2)), + {w.dlog}, {w.best_score, w.best_token, w.tokens}); + } else { + /* No bigram bias: the draft is the argmax of the target's own head over the predicting + * rows, exactly `main_model_output_embeddings(...).argmax(-1)` in the reference. R = 1 + * writes one id a row, which is the [sequences, steps] proposal plane. */ + op_dlogbf = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.n_vocab), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {w.dlog}, {w.dlog_bf}); + if (sharded && kGatherLogits) { + op_dgath_lg = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_INT("numel", srows * g.n_vocab), + RAD_STR("dtype", "bf16"), RAD_INT("row", g.n_vocab)), + RAD_NOWEIGHTS), + {w.dlog_bf}, {w.dlog_all}); + if (op_dgath_lg) + op_tok_all = rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab_all), + RAD_INT("R", 1), RAD_INT("vocab_off", 0), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {w.dlog_all}, {w.tokens, w.best_score}); + } + op_markov = sharded + ? rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("R", kTopR), RAD_INT("vocab_off", g.vocab_off), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {w.dlog_bf}, {w.cand, w.unary, w.dpair}) + : rw(b, RAD_OP(b, "row_topk", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("N", g.n_vocab), + RAD_INT("R", 1), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {w.dlog_bf}, {w.tokens, w.best_score}); + } + if (sharded) { + /* Row-interleaved, so one draft position's pairs from every rank are adjacent. */ + op_dgather = rw(b, RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_INT("numel", srows * kTopR * 2), RAD_STR("dtype", "f32"), + RAD_INT("row", kTopR * 2)), + RAD_NOWEIGHTS), + {w.dpair}, {w.dgath}); + op_pick = rw(b, RAD_OP(b, "pair_argmax", + RAD_PARAMS(RAD_RANGE("M", 1, srows), RAD_INT("n", g.world * kTopR), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {w.dgath}, {w.tokens}); + } + if (!op_dgather_rows || !op_dlogits || !op_markov || (c.rank <= 0 && !op_dlogbf) || + (sharded && (!op_dgather || !op_pick))) + return MD_REFUSED("op_dgather_rows", "op_dlogits", "op_markov"); + + return RAD_OK; +} + +/* ------------------------------------------------------------------------------ the context pass */ + +inline void MuseDflash::context(RadCtx* c, const RadBatch* batch) const { + const int64_t T = batch->n_tok; + if (T <= 0) return; + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + const int32_t* slot = kvb ? kvb->slot_mapping : nullptr; + const int64_t E = g.n_embd; + + /* Each tap's slice of the residual the trunk just tapped, normed with its own gain into the + * same slice layout of one row-per-token buffer. */ + for (int64_t t = 0; t < cfg.n_taps; ++t) { + const int i = (int)t; + if (!cfg.tap_norm) continue; + RAD_ISSUE_N(c, op_tapn[i], T, bcol(w.src, t * E, E, T), RAD_W(w_fcnorm[i]), + bcol(w.srcn, t * E, E, T)); + } + if (quant) { + RAD_ISSUE_N(c, op_qsrc, T, brows(cfg.tap_norm ? w.srcn : w.src, T), brows(w.srcq, T), + brows(w.srcs, T)); + RAD_ISSUE_N(c, op_cfc, T, brows(w.srcq, T), brows(w.srcs, T), RAD_W(w_fc.w), + RAD_W(w_fc.s), brows(w.c, T), RAD_NONE, w_fc.bref()); + } else { + RAD_ISSUE_N(c, op_cfc, T, brows(cfg.tap_norm ? w.srcn : w.src, T), RAD_W(b_fc), + brows(w.c, T)); + } + RAD_ISSUE_N(c, op_cnorm, T, brows(w.c, T), RAD_W(w_hnorm), brows(w.cn, T)); + if (quant) + RAD_ISSUE_N(c, op_qcn, T, brows(w.cn, T), brows(w.cnq, T), brows(w.cns, T)); + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + if (quant) { + RAD_ISSUE_N(c, op_ck[i], T, brows(w.cnq, T), brows(w.cns, T), RAD_W(w_k[i].w), + RAD_W(w_k[i].s), brows(w.ck, T), RAD_NONE, w_k[i].bref()); + RAD_ISSUE_N(c, op_cv[i], T, brows(w.cnq, T), brows(w.cns, T), RAD_W(w_v[i].w), + RAD_W(w_v[i].s), brows(w.cv, T), RAD_NONE, w_v[i].bref()); + } else { + RAD_ISSUE_N(c, op_ck[i], T, brows(w.cn, T), RAD_W(b_k[i]), brows(w.ck, T)); + RAD_ISSUE_N(c, op_cv[i], T, brows(w.cn, T), RAD_W(b_v[i]), brows(w.cv, T)); + } + if (cfg.qk_norm) + RAD_ISSUE_N(c, op_cknorm[i], T * g.n_head_kv, brows(w.ck, T), RAD_W(w_kn[i]), + brows(w.ckn, T)); + RAD_ISSUE_N(c, op_crope, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), praw(batch->positions, RAD_I32, T)); + RAD_ISSUE_N(c, op_cstore, T, brows(cfg.qk_norm ? w.ckn : w.ck, T), brows(w.cv, T), + praw(slot, RAD_I32, T), kv_cache(kv, first_layer + i)); + } +} + +/* ------------------------------------------------------------------------------ the query pass */ + +inline void MuseDflash::step(RadCtx* c, const RadBatch* batch) const { + const bool sharded = vocab_head_sharded(g); + const int64_t T = batch->n_tok; + if (T <= 0) return; + 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 RadOperand pos = praw(batch->positions, RAD_I32, T); + + /* The block the core staged: the token the sampler just chose, then the mask token in every + * unfilled slot. */ + RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.h, T)); + if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + RAD_ISSUE_N(c, op_widen, T, brows(w.h, T), brows(w.x, T)); + + for (int64_t l = 0; l < g.n_layer; ++l) { + const int i = (int)l; + + RAD_ISSUE_N(c, op_anorm[i], T, brows(w.x, T), RAD_W(w_anorm[i]), brows(w.h, T)); + if (quant) { + RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); + RAD_ISSUE_N(c, op_qp[i], T, brows(w.hq, T), brows(w.hs, T), RAD_W(w_q[i].w), + RAD_W(w_q[i].s), brows(w.q, T), RAD_NONE, w_q[i].bref()); + RAD_ISSUE_N(c, op_kp[i], T, brows(w.hq, T), brows(w.hs, T), RAD_W(w_k[i].w), + RAD_W(w_k[i].s), brows(w.k, T), RAD_NONE, w_k[i].bref()); + RAD_ISSUE_N(c, op_vp[i], T, brows(w.hq, T), brows(w.hs, T), RAD_W(w_v[i].w), + RAD_W(w_v[i].s), brows(w.v, T), RAD_NONE, w_v[i].bref()); + } else { + RAD_ISSUE_N(c, op_qp[i], T, brows(w.h, T), RAD_W(b_q[i]), brows(w.q, T)); + RAD_ISSUE_N(c, op_kp[i], T, brows(w.h, T), RAD_W(b_k[i]), brows(w.k, T)); + RAD_ISSUE_N(c, op_vp[i], T, brows(w.h, T), RAD_W(b_v[i]), brows(w.v, T)); + } + if (cfg.qk_norm) { + RAD_ISSUE_N(c, op_qn[i], T * g.n_head, brows(w.q, T), RAD_W(w_qn[i]), brows(w.qn, T)); + RAD_ISSUE_N(c, op_kn[i], T * g.n_head_kv, brows(w.k, T), RAD_W(w_kn[i]), + brows(w.kn, T)); + } + RAD_ISSUE_N(c, op_qrope, T, brows(cfg.qk_norm ? w.qn : w.q, T), pos); + RAD_ISSUE_N(c, op_krope, T, brows(cfg.qk_norm ? w.kn : w.k, T), pos); + /* The block's own K and V go into the cache past `seqused`, which is how every row of the + * block attends to every other; the next context pass overwrites them, which is the + * reference's `crop(start)`. */ + RAD_ISSUE_N(c, op_store, T, brows(cfg.qk_norm ? w.kn : w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), + kv_cache(kv, first_layer + i)); + RAD_ISSUE_N(c, op_attn, batch->max_q_len, brows(cfg.qk_norm ? w.qn : w.q, T), kv_cache(kv, first_layer + i), + 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)); + if (cfg.gate) { + /* One gate a head, applied to that head's whole row of the attention output, before + * o_proj. View [rows, heads * dim] and [rows, heads] as one row a head. */ + RAD_ISSUE_N(c, op_gp[i], T, brows(w.h, T), RAD_W(w_gate[i]), brows(w.gate, T)); + RAD_ISSUE_N(c, op_sig, T, brows(w.gate, T), brows(w.gaten, T)); + const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, w.attn), RAD_BF16, T * g.n_head, + g.head_dim); + const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, w.gaten), RAD_BF16, T * g.n_head, 1); + const RadOperand gated = RAD_P_T2(rad_buf_ptr(c, w.attng), RAD_BF16, T * g.n_head, + g.head_dim); + RAD_ISSUE_N(c, op_gate_heads, T * g.n_head, heads, gates, RAD_NONE, gated); + } + if (quant) { + RAD_ISSUE_N(c, op_qat, T, brows(cfg.gate ? w.attng : w.attn, T), brows(w.atq, T), + brows(w.ats, T)); + RAD_ISSUE_N(c, op_op[i], T, brows(w.atq, T), brows(w.ats, T), RAD_W(w_o[i].w), + RAD_W(w_o[i].s), brows(w.h, T), RAD_NONE, w_o[i].bref()); + } else { + RAD_ISSUE_N(c, op_op[i], T, brows(cfg.gate ? w.attng : w.attn, T), RAD_W(b_o[i]), + brows(w.h, T)); + } + if (op_ar && !kRepOut) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T)); + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T)); + + RAD_ISSUE_N(c, op_fnorm[i], T, brows(w.x, T), RAD_W(w_fnorm[i]), brows(w.h, T)); + if (quant) + RAD_ISSUE_N(c, op_qh, T, brows(w.h, T), brows(w.hq, T), brows(w.hs, T)); + if (op_gug[i] && T <= gated_rows) { + /* The MXFP4 fold takes the reference plane as a third weight; the fp8 tile does + * not, and its schema is one operand shorter. */ + if (w_gu[i].mx || w_gu[i].m2x) + RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T), RAD_W(w_gu[i].w), + RAD_W(w_gu[i].s), RAD_W(w_gu[i].ref), brows(w.ffq, T), + brows(w.ffs, T), RAD_NONE); + else + RAD_ISSUE_N(c, op_gug[i], T, brows(w.hq, T), brows(w.hs, T), RAD_W(w_gu[i].w), + RAD_W(w_gu[i].s), brows(w.ffq, T), brows(w.ffs, T), RAD_NONE); + } else if (quant) { + RAD_ISSUE_N(c, op_gu[i], T, brows(w.hq, T), brows(w.hs, T), RAD_W(w_gu[i].w), + RAD_W(w_gu[i].s), brows(w.gate_up, T), RAD_NONE, w_gu[i].bref()); + RAD_ISSUE_N(c, op_act, T, bcol(w.gate_up, 0, g.n_ff, T), + bcol(w.gate_up, g.n_ff, g.n_ff, T), brows(w.ff, T)); + RAD_ISSUE_N(c, op_qff, T, brows(w.ff, T), brows(w.ffq, T), brows(w.ffs, T)); + } else { + RAD_ISSUE_N(c, op_gu[i], T, brows(w.h, T), RAD_W(b_gu[i]), brows(w.gate_up, T)); + RAD_ISSUE_N(c, op_act, T, bcol(w.gate_up, 0, g.n_ff, T), + bcol(w.gate_up, g.n_ff, g.n_ff, T), brows(w.ff, T)); + } + if (quant) + RAD_ISSUE_N(c, op_dn[i], T, brows(w.ffq, T), brows(w.ffs, T), RAD_W(w_dn[i].w), + RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref()); + else + RAD_ISSUE_N(c, op_dn[i], T, brows(w.ff, T), RAD_W(b_dn[i]), brows(w.h, T)); + if (op_ar && !kRepOut) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + RAD_ISSUE_N(c, op_widen2, T, brows(w.h, T), brows(w.delta, T)); + RAD_ISSUE_N(c, op_add, T, brows(w.x, T), brows(w.delta, T), brows(w.x, T)); + } + + RAD_ISSUE_N(c, op_outnorm, T, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + + /* The predicting rows are the engine's `out_ids`: one entry per drafting sequence, `block` + * staged rows, `out_ids` its last `steps` rows (the scheduler's block_query; the gather reads + * them into `hg` and the head scores the gathered rows). Not "the last S rows" of the staged + * block: that list coincides with out_ids only while EVERY staged sequence drafts -- with + * several, it drops each sequence's first mask row and reads its neighbour's anchor, whose + * logits then pose as that sequence's first draft and collapse a batch's acceptance (measured + * at two sequences: the drafts came out shifted by one, the anchor's posing as draft 0). */ + const int64_t S = batch->n_out; + if (S <= 0) return; + RAD_ISSUE_N(c, op_dgather_rows, S, brows(w.h, T), praw(batch->out_ids, RAD_I32, S), + brows(w.hg, S)); + RAD_ISSUE_N(c, op_dlogits, S, brows(w.hg, S), RAD_W(w_head), brows(w.dlog, S)); + if (cfg.rank > 0) + RAD_ISSUE_N(c, op_markov, batch->n_seq, brows(w.dlog, S), + praw(batch->token_ids, RAD_I32, T), RAD_W(w_mk1), RAD_W(w_mk2), + brows(w.best_score, batch->n_seq), brows(w.best_token, batch->n_seq), + brows(w.tokens, batch->n_seq)); + else if (sharded) { + RAD_ISSUE_N(c, op_dlogbf, S, brows(w.dlog, S), brows(w.dlog_bf, S)); + if (op_tok_all) { + RAD_ISSUE_N(c, op_dgath_lg, S * g.n_vocab, brows(w.dlog_bf, S), brows(w.dlog_all, S)); + RAD_ISSUE_N(c, op_tok_all, S, brows(w.dlog_all, S), brows(w.tokens, S), + brows(w.best_score, S)); + return; + } + RAD_ISSUE_N(c, op_markov, S, brows(w.dlog_bf, S), brows(w.cand, S), brows(w.unary, S), + brows(w.dpair, S)); + RAD_ISSUE(c, op_dgather, brows(w.dpair, S), brows(w.dgath, S)); + RAD_ISSUE_N(c, op_pick, S, brows(w.dgath, S), brows(w.tokens, S)); + } else { + RAD_ISSUE_N(c, op_dlogbf, S, brows(w.dlog, S), brows(w.dlog_bf, S)); + RAD_ISSUE_N(c, op_markov, S, brows(w.dlog_bf, S), brows(w.tokens, S), + brows(w.best_score, S)); + } +} + +/* ================================================================== the trunk's side of it + * + * The taps, and one call a target plugin makes to put a drafter on. Both live here because both + * are the drafter's contract with the trunk: which residual streams it reads, where its blocks + * live, and how deep a proposal it makes. */ + +/* The residual streams a drafter reads, captured as the trunk passes them. */ +struct MuseTaps { + enum { MAX_TAPS = MuseDflash::MAX_LAYERS }; + + int n = 0; + int layer[MAX_TAPS] = {}; /* the trunk layer whose OUTPUT is tapped */ + rad_buf src = 0; /* [rows, n * n_embd] bf16, one column slice a tap */ + rad_op op = 0; /* the residual stream, copied into that slice */ + + /* Read `draft.target_layer_ids`, which names the layers whose output is tapped. Zero taps when + * the container carries no drafter, or one that reads no trunk stream. Out-of-range ids are + * dropped, not clamped: a drafter naming a layer this model lacks belongs to another target. */ + int read(const RadModelMeta* meta, int64_t n_layer) { + n = 0; + const char* ids = rad_meta_gets(meta, "draft.target_layer_ids", nullptr); + if (!ids) ids = rad_meta_gets(meta, "draft.dflash_config.target_layer_ids", nullptr); + if (!ids) ids = rad_meta_gets(meta, "draft.gguf_target_layers", nullptr); + n = parse_layer_ids(ids, n_layer, layer, MAX_TAPS); + return n; + } + + /* The copy that saves a tap. The residual's dtype is the plugin's (`g.act_dtype`), so it is + * passed in: a bf16 trunk copies bf16 to bf16 (the strided row copy), and an f32 one narrows. */ + int declare(RadBuilder* b, Names& nm, const Geom& g, int64_t rows, rad_buf residual, + uint32_t res_dtype) { + if (n <= 0) return RAD_OK; + /* bf16, not the trunk's f32: `fc` is a bf16 GEMM, and the reference runs the drafter under + * bf16 autocast, so the narrower tap is both the operand the GEMM reads and half the + * memory (5 x 6656 x max_tok values are not cheap). */ + src = decl_b(b, nm.f("draft_src"), RAD_BF16, {rows, (int64_t)n * g.n_embd}); + if (!src) return MD_REFUSED("src"); + /* Declared over the trunk's own residual buffer: the op's operand pair is the stream and a + * tap's slice, and every issue site passes the slice it is writing. */ + op = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", g.n_embd), + RAD_STR("from", rad_dtype_name(res_dtype)), + RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {residual}, {src}); + return op ? RAD_OK : RAD_E_INVAL; + } + + /* The tap that follows trunk layer `l`, if any. Issued on prefill and decode alike: the + * drafter conditions on every committed token's residual stream. */ + void step(RadCtx* c, rad_buf residual, int64_t rows, int64_t l, int64_t n_embd) const { + if (!op) return; + for (int t = 0; t < n; ++t) + if (layer[t] == l) + RAD_ISSUE(c, op, brows(residual, rows), + bcol(src, (int64_t)t * n_embd, n_embd, rows)); + } +}; + +/* Put a Muse Glimmer drafter on a trunk: its config from the container's `draft.` keys, its own KV + * group, its graph, and the drafter declaration the core drives. `base_layer` is the absolute + * layer its first block takes, one past the trunk's last. + * + * Nothing is defaulted quietly. A `draft.` key that describes a drafter this file does not + * implement is refused by name, because a silently ignored gate, window or block length only moves + * acceptance -- the one number a user cannot see in the output. + * + * The plugin calls it last, after its own head and logits: a drafter's passes run after the whole + * trunk, and the buffer planner lays an op's lifetimes out in declaration order, so declaring it + * earlier would let a trunk temporary land on the stream the drafter is still reading. */ +inline int declare_muse_dflash(MuseDflash* ds, MuseDflash::Wire* w, rad_kvgroup* kv, RadBuilder* b, + Names& nm, const RadModelMeta* meta, const RadBuildCtx* ctx, + const Geom& target, const MuseTaps& taps, int base_layer, + rad_weight tok_embd, rad_weight head_w) { + Geom dg{}; + RAD_ARCH_TRY(drafter_geom(dg, target, meta, "DFlash")); + /* The width the drafter concatenates and projects is the trunk's, and `drafter_geom` keeps the + * target's -- so a draft that disagrees is a draft for another model, and its `fc` would be + * read at a shape it was not trained at. */ + const int64_t want_embd = rad_meta_geti(meta, "draft.hidden_size", + rad_meta_geti(meta, "draft.dflash_config.hidden_size", + dg.n_embd)); + if (want_embd != dg.n_embd) { + fprintf(stderr, "radiance: the drafter reads a %lld-wide trunk and this target is %lld " + "wide; they are not the same model\n", (long long)want_embd, + (long long)dg.n_embd); + return RAD_E_UNSUPPORTED; + } + + MuseDflash::Config c{}; + c.n_taps = taps.n; + c.rank = rad_meta_geti(meta, "draft.markov_rank", 0); + c.causal = rad_meta_geti(meta, "draft.is_causal", 0) ? 1 : 0; + c.tap_norm = rad_meta_geti(meta, "draft.fc_norm", 0) ? 1 : 0; + /* The Muse assistant always carries per-head q/k gains (its checkpoint has + * `layers.N.self_attn.{q,k}_norm.weight` in every layer), and its config has no key to say so: + * default them on rather than silently run a different attention. */ + c.qk_norm = rad_meta_geti(meta, "draft.qk_norm", 1) ? 1 : 0; + c.gate = rad_meta_geti(meta, "draft.headwise_attn_output_gate", 0) ? 1 : 0; + const char* act = rad_meta_gets(meta, "draft.hidden_act", "silu"); + c.act = (!std::strcmp(act, "gelu") || !std::strcmp(act, "none")) ? "gelu" + : (!std::strcmp(act, "silu")) ? "silu" : nullptr; + if (!c.act) { + fprintf(stderr, "radiance: the drafter's feed-forward is '%s'; this block runs exact-erf " + "gelu (what the Spark drafts train with) or silu, and the two are not the " + "same function\n", act); + return RAD_E_UNSUPPORTED; + } + const char* gate_mode = rad_meta_gets(meta, "draft.gate_attn_act_mode", "sigmoid"); + if (c.gate && std::strcmp(gate_mode, "sigmoid")) { + fprintf(stderr, "radiance: the drafter gates its attention output with '%s'; this block " + "applies a sigmoid\n", gate_mode); + return RAD_E_UNSUPPORTED; + } + /* Every row predicts, the anchor included. Without it a block row's worth of proposals is + * missing and the head reads rows the drafter never filled. */ + if (!rad_meta_geti(meta, "draft.sample_from_anchor", 1)) { + fprintf(stderr, "radiance: the drafter declares sample_from_anchor false, whose bonus " + "anchor slot this block has no rows for\n"); + return RAD_E_UNSUPPORTED; + } + /* The reference applies the bigram bias to the full vocabulary before each greedy choice. */ + if (c.rank < 0 || c.rank > 512 || (c.rank > 0 && c.rank % 32)) { + fprintf(stderr, "radiance: the drafter's Markov head has rank %lld; a bigram walk takes a " + "multiple of 32 up to 512, and 0 means the checkpoint has none (the Muse " + "Glimmer assistant does not)\n", (long long)c.rank); + return RAD_E_UNSUPPORTED; + } + + /* The block is both the number of noise rows and the number of drafts: every row, the anchor + * included, predicts the token after it, so the depth is `block_size` rather than the + * `block_size - 1` a DFlash2 container's is. A block-diffusion drafter is trained for one + * block length and has no partial block, so any other depth is refused. */ + const int64_t trained = rad_meta_geti(meta, "draft.block_size", 0); + if (trained < 2) { + fprintf(stderr, "radiance: this drafter declares no draft.block_size; the number of masked " + "positions it denoises is not a number this engine may choose.\n"); + return RAD_E_FORMAT; + } + if ((long long)ctx->max_spec != trained - 1) { + fprintf(stderr, "radiance: the drafter denoises a block of %lld positions, of which %lld " + "predict, and this serve asks for %d. A block-diffusion drafter has a fixed " + "block; run it at %lld.\n", + (long long)trained, (long long)trained - 1, ctx->max_spec, + (long long)trained - 1); + return RAD_E_UNSUPPORTED; + } + c.block = trained; + + /* The reference gives every row of the block the anchor's history. `window` is the configured + * number of preceding positions; llama.cpp sets n_swa to window + 1 and masks when + * anchor - key >= n_swa. Keep that exact width in attention, the KV group and scheduler. */ + int64_t window = 0; + /* Its config names `layer_types: sliding_attention` and a `sliding_window`, but no + * `use_sliding_window` flag: take the window whenever the drafter states one. */ + const int64_t sw = rad_meta_geti(meta, "draft.sliding_window", + rad_meta_geti(meta, "draft.dflash_config.swa_window_size", 0)); + if (rad_meta_geti(meta, "draft.use_sliding_window", sw > 0 ? 1 : 0)) + window = sw; + if (window < 0 || (window && window < c.block)) { + fprintf(stderr, "radiance: the drafter's %lld-token window does not cover the %lld-token " + "block it denoises\n", (long long)window, (long long)c.block); + return RAD_E_UNSUPPORTED; + } + if (window > 0 && window == INT64_MAX) return RAD_E_INVAL; + /* The reference masks with |q - k| <= sliding_window, with no anchor-aligned +1. */ + c.window = window; + const double prf = rad_meta_getf(meta, "draft.partial_rotary_factor", + rad_meta_getf(meta, + "draft.rope_parameters.partial_rotary_factor", 1.0)); + const double rot = (double)dg.head_dim * prf; + if (!(prf > 0.0) && prf != 0.0) { + fprintf(stderr, "radiance: the drafter's partial_rotary_factor is %g\n", prf); + return RAD_E_INVAL; + } + if (std::floor(rot) != rot || (int64_t)rot % 2 || rot > (double)dg.head_dim) { + fprintf(stderr, "radiance: the drafter rotates %g of %lld head dimensions\n", rot, + (long long)dg.head_dim); + return RAD_E_INVAL; + } + c.rot = (int64_t)rot ? (int64_t)rot : dg.head_dim; + + RAD_ARCH_TRY(drafter_kv_group(b, nm, ctx, dg, c.window, base_layer, kv)); + + /* Activations: one row per committed token for the context pass, one row per block position + * for the query pass. Both are small; the drafter's cost is its weights. */ + const int64_t qd = dg.n_head * dg.head_dim, kvd = dg.n_head_kv * dg.head_dim; + int64_t qr = dg.max_seqs * c.block; + if (qr > dg.max_tok) qr = dg.max_tok; + const int64_t sr = dg.max_seqs * c.steps(); + MuseDflash::Wire& dw = *w; + dw.src = taps.src; + if (c.tap_norm) + dw.srcn = decl_b(b, nm.f("ds_srcn"), RAD_BF16, {dg.max_tok, c.n_taps * dg.n_embd}); + dw.c = decl_b(b, nm.f("ds_c"), RAD_BF16, {dg.max_tok, dg.n_embd}); + dw.cn = decl_b(b, nm.f("ds_cn"), RAD_BF16, {dg.max_tok, dg.n_embd}); + dw.ck = decl_b(b, nm.f("ds_ck"), RAD_BF16, {dg.max_tok, kvd}); + dw.cv = decl_b(b, nm.f("ds_cv"), RAD_BF16, {dg.max_tok, kvd}); + if (c.qk_norm) dw.ckn = decl_b(b, nm.f("ds_ckn"), RAD_BF16, {dg.max_tok, kvd}); + dw.x = decl_b(b, nm.f("ds_x"), RAD_F32, {qr, dg.n_embd}); + dw.delta = decl_b(b, nm.f("ds_delta"), RAD_F32, {qr, dg.n_embd}); + dw.h = decl_b(b, nm.f("ds_h"), RAD_BF16, {qr, dg.n_embd}); + dw.q = decl_b(b, nm.f("ds_q"), RAD_BF16, {qr, qd}); + dw.k = decl_b(b, nm.f("ds_k"), RAD_BF16, {qr, kvd}); + dw.v = decl_b(b, nm.f("ds_v"), RAD_BF16, {qr, kvd}); + if (c.qk_norm) { + dw.qn = decl_b(b, nm.f("ds_qn"), RAD_BF16, {qr, qd}); + dw.kn = decl_b(b, nm.f("ds_kn"), RAD_BF16, {qr, kvd}); + } + dw.gate = decl_b(b, nm.f("ds_gate"), RAD_BF16, {qr, dg.n_head}); + dw.attn = decl_b(b, nm.f("ds_attn"), RAD_BF16, {qr, qd}); + if (c.gate) { + dw.gaten = decl_b(b, nm.f("ds_gaten"), RAD_BF16, {qr, dg.n_head}); + dw.attng = decl_b(b, nm.f("ds_attng"), RAD_BF16, {qr, qd}); + } + dw.gate_up = decl_b(b, nm.f("ds_gate_up"), RAD_BF16, {qr, 2 * dg.n_ff}); + dw.ff = decl_b(b, nm.f("ds_ff"), RAD_BF16, {qr, dg.n_ff}); + /* The linears are block fp8 or MXFP4, so every activation feeding one has an E4M3 plane and + * an f32 scale a 128 values. */ + dw.srcq = decl_b(b, nm.f("ds_srcq"), RAD_F8E4M3, {dg.max_tok, c.n_taps * dg.n_embd}); + dw.srcs = decl_b(b, nm.f("ds_srcs"), RAD_F32, {dg.max_tok, fp8_blocks(c.n_taps * dg.n_embd)}); + dw.cnq = decl_b(b, nm.f("ds_cnq"), RAD_F8E4M3, {dg.max_tok, dg.n_embd}); + dw.cns = decl_b(b, nm.f("ds_cns"), RAD_F32, {dg.max_tok, fp8_blocks(dg.n_embd)}); + dw.hq = decl_b(b, nm.f("ds_hq"), RAD_F8E4M3, {qr, dg.n_embd}); + dw.hs = decl_b(b, nm.f("ds_hs"), RAD_F32, {qr, fp8_blocks(dg.n_embd)}); + dw.atq = decl_b(b, nm.f("ds_atq"), RAD_F8E4M3, {qr, qd}); + dw.ats = decl_b(b, nm.f("ds_ats"), RAD_F32, {qr, fp8_blocks(qd)}); + dw.ffq = decl_b(b, nm.f("ds_ffq"), RAD_F8E4M3, {qr, dg.n_ff}); + dw.ffs = decl_b(b, nm.f("ds_ffs"), RAD_F32, {qr, fp8_blocks(dg.n_ff)}); + dw.hg = decl_b(b, nm.f("ds_hg"), RAD_BF16, {sr, dg.n_embd}); + dw.dlog = decl_b(b, nm.f("ds_dlog"), RAD_F32, {sr, dg.n_vocab}); + /* Vocab-sharded, the head's rows are this rank's slice and the top-1 must be taken over every + * rank's slice: row_topk reports global ids into a pair plane, all_gather moves the pairs, and + * pair_argmax picks the winner -- the same walk rad_gemma4_dflash.h runs. kTopR = 2 because the + * gather moves 16-byte rows. */ + const bool sharded = vocab_head_sharded(dg); + const int64_t kTopR = sharded ? 2 : 1; + if (sharded) { + dw.cand = decl_b(b, nm.f("ds_cand"), RAD_I32, {sr, kTopR}); + dw.unary = decl_b(b, nm.f("ds_unary"), RAD_F32, {sr, kTopR}); + dw.dpair = decl_b(b, nm.f("ds_dpair"), RAD_F32, {sr, kTopR, 2}); + dw.dgath = decl_b(b, nm.f("ds_dgath"), RAD_F32, {sr, (int64_t)dg.world * kTopR, 2}); + } + /* row_topk serves bf16 only (its band list), and logits_gemm writes f32: the draft's argmax + * reads this narrower copy. One row's scores are 202048 values, so the pair costs 18 MB a + * draft step against the ~50 MB of head GEMM the same step runs. */ + if (c.rank <= 0) { + dw.dlog_bf = decl_b(b, nm.f("ds_dlog_bf"), RAD_BF16, {sr, dg.n_vocab}); + if (vocab_head_sharded(dg)) + dw.dlog_all = decl_b(b, nm.f("ds_dlog_all"), RAD_BF16, {sr, dg.n_vocab_all}); + } + const int64_t n_markov_tiles = (dg.n_vocab_all + 63) / 64; + /* row_topk's outputs are [M, R]: one row a predicting row, so the no-markov path lays the + * proposal and its score out as [rows, 1], which is the same bytes as [max_seqs, steps] in + * sequence-major order and what RadDrafterDecl::proposal_pitch reads. */ + dw.best_score = c.rank > 0 + ? decl_b(b, nm.f("ds_markov_score"), RAD_F32, {dg.max_seqs, n_markov_tiles}) + : decl_b(b, nm.f("ds_markov_score"), RAD_F32, {sr, 1}); + dw.best_token = decl_b(b, nm.f("ds_markov_token"), RAD_I32, + {dg.max_seqs, n_markov_tiles}); + /* The proposal buffer (RadDrafterDecl::proposal): a block pass proposes through the drafter's + * own walk, never through the sampler's token buffer. */ + dw.tokens = c.rank > 0 + ? decl_b(b, nm.f("ds_tokens"), RAD_I32, {dg.max_seqs, c.steps()}) + : decl_b(b, nm.f("ds_tokens"), RAD_I32, {sr, 1}); + if ((c.tap_norm && !dw.srcn) || !dw.c || !dw.cn || !dw.ck || !dw.cv || + (c.qk_norm && (!dw.ckn || !dw.qn || !dw.kn)) || + (c.gate && (!dw.gaten || !dw.attng)) || !dw.x || !dw.delta || !dw.h || !dw.q || !dw.k || + !dw.v || !dw.gate || !dw.attn || !dw.gate_up || !dw.ff || !dw.hg || !dw.dlog || + !dw.best_score || !dw.best_token || !dw.tokens || !dw.srcq || !dw.srcs || !dw.cnq || + !dw.cns || !dw.hq || !dw.hs || !dw.atq || !dw.ats || !dw.ffq || !dw.ffs) + return RAD_E_INVAL; + + RAD_ARCH_TRY(ds->declare(b, nm, dg, c, base_layer, *kv, tok_embd, "draft", head_w, dw)); + fprintf(stderr, "I speculation: 'muse_dflash' %s its gate_up|silu|quant fold (%lld row(s))\n", + ds->gated_rows ? "fuses" : "does not fuse", (long long)ds->gated_rows); + + RadDrafterDecl drf{}; + drf.name = "muse_dflash"; + drf.kind = RAD_DRAFT_BLOCK; + drf.depth = ctx->max_spec; + drf.block = c.block; + drf.proposal = dw.tokens; + drf.proposal_pitch = c.steps(); + drf.window = c.window; + drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.mask_token_id", -1); + if (drf.mask_token < 0) + drf.mask_token = (int32_t)rad_meta_geti(meta, "draft.dflash_config.mask_token_id", -1); + if (drf.mask_token < 0) { + fprintf(stderr, "radiance: this drafter declares no mask_token_id, which every unfilled " + "block position embeds\n"); + return RAD_E_FORMAT; + } + RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + /* A short block, so the core can drop from 16 rows to 4 once several sequences decode: every op + * above is ranged by rows, so the same graph serves both. Declared after the drafter, as the + * ABI requires. */ + if (c.block > 4) { + ds->block_lo = 4; + RAD_ARCH_TRY(rad_drafter_short_block(b, ds->block_lo)); + } + + rad_note(b, "Muse Glimmer drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, " + "ffn %lld, %s attention with a %lld-token anchor-aligned window (%lld configured " + "history + 1), %lld of %lld rotary dimensions, %s, %s a head, %d trunk tap(s); one " + "forward over %lld noise row(s), the anchor included, proposes %lld tokens", + (long long)dg.n_layer, base_layer, base_layer + (int)dg.n_layer - 1, + (long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim, + (long long)dg.n_ff, c.causal ? "causal" : "non-causal", (long long)c.window, + (long long)window, (long long)c.rot, (long long)dg.head_dim, c.act, + c.gate ? "sigmoid gate" : "no gate", (int)c.n_taps, (long long)c.block, + (long long)c.steps()); + rad_note(b, "the rank-%lld Markov bigram head greedily scans all %lld vocabulary tokens at " + "each draft position; confidence is not applied to logits%s", + (long long)c.rank, (long long)dg.n_vocab_all, + rad_meta_geti(meta, "draft.has_confidence_head", 0) + ? " (its reference role is adaptive depth, which this fixed-depth graph does not use)" + : ""); + return RAD_OK; +} + + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* RAD_BLOCK_MUSE_DFLASH_H */ \ No newline at end of file diff --git a/arch/common/rad_block_museglimmer_vision.h b/arch/common/rad_block_museglimmer_vision.h new file mode 100644 index 00000000..cb175fda --- /dev/null +++ b/arch/common/rad_block_museglimmer_vision.h @@ -0,0 +1,571 @@ +/* rad_block_museglimmer_vision.h -- Muse Glimmer's vision tower (transformers' + * MuseGlimmerVisionModel, an InternVit-shaped stack), its adapter and the perception norm, served + * by museglimmer. + * + * What it computes, per encoder pass (RadBatch::enc), in the reference's order: + * + * x = patches @ Wp^T the patch embedding as a linear layer, bias-less; + * a patch row is (temporal, channel, y, x) + * x += position table resampled to the grid `grid_embed_pad`, bilinear at half-pixel + * centres, align_corners=False, out-of-range taps + * zero-weighted (grid_sample padding zeros) + * x = LN_pre(x) LayerNorm, eps `layer_norm_eps` + * x = x[window order] `window_order`: the 32x32-patch window permutation + * (per frame, ragged edges smaller windows), its + * inverse, per-slot rotary positions and the + * per-window cumulative boundaries + * depth times: + * h = LN1(x) LayerNorm, eps 1e-5 (the blocks hard-code it) + * q|k|v = qkv(h) the reference's three biased projections, joined + * q first into one GEMM as the reference's fused + * tensors would read + * rope(q, k) `rope` axial, the whole head, sections + * head_dim/4 a side on theta^(-j/(head_dim/4)), + * positions (column + 1, row + 1) -- HF's + * position_ids.flip(-1) + 1 + * x += proj(attn(q, k, v)) non-causal, scale 1/sqrt(head_dim). A + * window_attention layer attends within one window + * (cu = the per-window boundaries in permuted + * order); a full_attention layer attends within + * its frame (cu = the frame boundaries). The + * window permutation never moves a patch across + * frames, so the frame boundaries among permuted + * rows are the boundaries among natural rows: + * `enc_cu` is passed unchanged, exactly what the + * reference passes (modeling_muse_glimmer.py maps + * full_attention to the frame cu_seqlens while the + * rows stay permuted). + * x += fc2(gelu(fc1(LN2(x)))) both biased; `gelu` the exact erf form the + * config's hidden_act names, in gemm_nt_bias's + * epilogue + * x = x[inv] the window order undone (gather_rows) + * x = LN_post(x) LayerNorm, eps `layer_norm_eps` + * y = pixel_shuffle(x) the merge (`pixtral_merge`): each 2x2 block's + * four patches fold into one row of merge^2 * + * width, channels interleaved -- the reference's + * [block, merge^2, dim].permute(0, 2, 1) + * y = gelu(fc2(gelu(fc1(y)))) the adapter: both linears bias-less, TWO + * activations (projector_hidden_act) + * y = y @ Wproj^T the projection, bias-less, the model's width + * out = rms(y) `perception_emb_norm`, a weightless RMS norm at + * the TEXT model's rms_norm_eps + * + * The reference permutes AFTER ln_pre, so the tower works in window order and un-permutes before + * ln_post, exactly as above. The processor stages patches in the reference's raster order; the + * merge is a real fold (not a view: the reference interleaves the four patches' channels, which + * four consecutive rows do not spell), and its output is what the adapter reads. + * + * Every rank runs the whole tower with replicated weights, as rad_block_vit.h's does, and the + * weights are RAD_ACCESS_PER_REQUEST. Activations are sized by the pass (RadBuildCtx:: + * max_enc_patches rows), except in a sizing declare (shape_probe), where rows follow the probe's + * step; the attention's longest segment stays at the real pass so the kernel rows do not move. + */ +#ifndef RAD_BLOCK_MUSEGLIMMER_VISION_H +#define RAD_BLOCK_MUSEGLIMMER_VISION_H + +#include "rad_arch.h" + +#include +#include +#include +#include + +namespace rad { +namespace arch { + +struct MuseTower { + /* Geometry, from the container's vision_config (never aliased: only the full prefix). The + * adapter's widths are top-level keys of the family config. */ + int64_t depth = 0, width = 0, heads = 0, head_dim = 0, ff = 0, patch = 0, temporal = 0; + int64_t merge = 0, side = 0, npos = 0, proj_ff = 0, out_hidden = 0, n_embd = 0; + int64_t patch_dim = 0, P = 0; + double eps = 1e-5; /* ln_pre / ln_post; the blocks hard-code 1e-5 */ + float theta = 10000.0f; + bool on = false; + + struct Layer { + bool full = false; /* full_attention: frame-wide attention, NoPE-free (rotary runs + * on every layer of this tower, full or window) */ + rad_weight n1w = 0, n1b = 0, qkv_w = 0, qkv_b = 0, out_w = 0, out_b = 0; + rad_weight n2w = 0, n2b = 0, up_w = 0, up_b = 0, down_w = 0, down_b = 0; + rad_op ln1 = 0, qkv = 0, rope = 0, attn = 0, proj = 0, ln2 = 0, up = 0, down = 0; + int64_t max_seg = 0; /* the kernel band's longest segment */ + }; + std::vector L; + rad_weight w_patch = 0, w_pos = 0, lw_pre = 0, lb_pre = 0, lw_post = 0, lb_post = 0; + rad_weight w_a1 = 0, w_a2 = 0, w_proj = 0; + rad_op op_patch = 0, op_pos = 0, op_lpre = 0, op_wo = 0, op_gidx = 0, op_ginv = 0; + rad_op op_lpost = 0, op_merge = 0, op_m1 = 0, op_g1 = 0, op_m2 = 0, op_g2 = 0, op_proj = 0, + op_perc = 0; + rad_buf b_x = 0, b_h = 0, b_p = 0, b_qkv = 0, b_att = 0, b_ff = 0; + rad_buf b_idx = 0, b_inv = 0, b_pos = 0, b_cuw = 0; + rad_buf b_mh = 0, b_m1 = 0, b_m2 = 0, b_out = 0; + char sec[48] = {}; + + /* Whether the container carries this family's tower. */ + static bool present(const RadModelMeta* m) { + return rad_meta_geti(m, "vision_config.num_hidden_layers", 0) > 0; + } + + int declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* ctx, Names& nm, + int64_t model_embd, int first_group); + void step(RadCtx* c, const RadBatch* batch) const; +}; + +inline int MuseTower::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; + + depth = rad_meta_geti(m, "vision_config.num_hidden_layers", 0); + width = rad_meta_geti(m, "vision_config.hidden_size", 0); + heads = rad_meta_geti(m, "vision_config.num_attention_heads", 0); + ff = rad_meta_geti(m, "vision_config.intermediate_size", 0); + patch = rad_meta_geti(m, "vision_config.patch_size", 0); + temporal = rad_meta_geti(m, "vision_config.patch_temporal", 2); + merge = rad_meta_geti(m, "vision_config.merge_size", 2); + side = rad_meta_geti(m, "vision_config.pos_emb_height", 0); + npos = rad_meta_geti(m, "vision_config.pos_emb_height", 0) * + rad_meta_geti(m, "vision_config.pos_emb_width", 0); + eps = rad_meta_getf(m, "vision_config.layer_norm_eps", 1e-5); + theta = (float)rad_meta_getf(m, "vision_config.rope_parameters.rope_theta", 10000.0); + proj_ff = rad_meta_geti(m, "projector_hidden_size", 4096); + out_hidden = rad_meta_geti(m, "out_hidden_size", 6144); + n_embd = model_embd; + if (depth <= 0 || width <= 0 || heads <= 0 || ff <= 0 || patch <= 0 || temporal <= 0 || + merge <= 0 || side <= 0 || proj_ff <= 0 || out_hidden <= 0 || width % heads || + rad_meta_geti(m, "vision_config.pos_emb_width", 0) != side) { + fprintf(stderr, "radiance: museglimmer: the container's vision_config is incomplete or " + "inconsistent (depth %lld, hidden %lld, heads %lld, ff %lld, patch %lld, " + "temporal %lld, merge %lld, position grid %lld x %lld, projector %lld, " + "merged %lld)\n", (long long)depth, (long long)width, (long long)heads, + (long long)ff, (long long)patch, (long long)temporal, (long long)merge, + (long long)side, (long long)rad_meta_geti(m, "vision_config.pos_emb_width", 0), + (long long)proj_ff, (long long)out_hidden); + return RAD_E_INVAL; + } + /* The merge is `pixtral_merge`, whose kernels fold a 2x2 block: the only factor Muse Glimmer + * ships and the only one the op serves. */ + if (merge != 2) { + fprintf(stderr, "radiance: museglimmer: this vision tower states merge_size %lld; the " + "merge op folds a 2x2 block\n", (long long)merge); + return RAD_E_UNSUPPORTED; + } + /* The exact-erf GELU is what this tower and its adapter state; another activation is another + * tower (the reference would compute a different function). */ + const char* act = rad_meta_gets(m, "vision_config.hidden_act", "gelu"); + const char* pact = rad_meta_gets(m, "projector_hidden_act", "gelu"); + const char* rt = rad_meta_gets(m, "vision_config.rope_parameters.rope_type", "axial"); + if (std::strcmp(act, "gelu") || std::strcmp(pact, "gelu")) { + fprintf(stderr, "radiance: museglimmer: this vision tower has hidden_act '%s' and " + "projector_hidden_act '%s'; it serves the exact gelu both call for\n", + act, pact); + return RAD_E_UNSUPPORTED; + } + /* `axial` is Meta's spelling and `default` NVIDIA's ModelOpt export of the same tower: the + * reference's vision embedder has one rotary (axial), so both name it. Anything else is + * another tower. */ + if (std::strcmp(rt, "axial") && std::strcmp(rt, "default")) { + fprintf(stderr, "radiance: museglimmer: this vision tower states rope_type '%s'; it " + "serves the axial 2-D rotary the tower's rotary embedder raises on " + "leaving\n", rt); + return RAD_E_UNSUPPORTED; + } + /* The tower's full layers: every fourth, counted from the start, plus the last (the config's + * own rule, MuseGlimmerVisionConfig.__post_init__). The shipped array must say the same + * thing; a window layer where the rule puts a full one changes what the model saw. */ + std::vector full; + const char* kinds = rad_meta_gets(m, "vision_config.layer_types", ""); + if (kinds && *kinds) { + RAD_ARCH_TRY(parse_layer_kinds("museglimmer vision", kinds, {"full_attention"}, + "window_attention", &full)); + if ((int64_t)full.size() != depth) { + fprintf(stderr, "radiance: museglimmer: vision_config.layer_types names %zu layers " + "and the tower has %lld\n", full.size(), (long long)depth); + return RAD_E_INVAL; + } + for (int64_t l = 0; l < depth; ++l) { + const bool rule = is_full_attention(l, 4) || l == depth - 1; + if ((full[(size_t)l] != 0) != rule) { + fprintf(stderr, "radiance: museglimmer: vision_config.layer_types makes tower " + "layer %lld %s and the family rule (every fourth from the first, " + "plus the last) makes it %s\n", (long long)l, + full[(size_t)l] ? "full" : "window", rule ? "full" : "window"); + return RAD_E_UNSUPPORTED; + } + } + } else { + full.assign((size_t)depth, 0); + for (int64_t l = 0; l < depth; ++l) + full[(size_t)l] = is_full_attention(l, 4) || l == depth - 1; + } + + head_dim = width / heads; + patch_dim = 3 * temporal * patch * patch; + /* The 2-D rotary: half the head a side, each on its own ladder (arange(0, head_dim/2, 2) + * frequencies, sections head_dim/4 a side). */ + if (head_dim % 4) return RAD_E_SHAPE; + std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(head_dim / 4), + (long long)(head_dim / 4)); + /* The merger's rows replace token embeddings, so they must be the model's width. */ + if (out_hidden != merge * merge * width) { + fprintf(stderr, "radiance: museglimmer: out_hidden_size %lld is not merge %lld squared " + "times the tower's width %lld, whose view the adapter's first layer " + "reads\n", (long long)out_hidden, (long long)merge, (long long)width); + return RAD_E_INVAL; + } + /* The tower emits merged rows the width of the model's tokens: the caller passes the model's + * width and the projection is declared at it, so no separate check exists. */ + + const int64_t mm = merge * merge; + P = ctx->max_enc_patches; + if (ctx->shape_probe) { + /* A sizing declare: rows follow the probe's step (rounded to whole merged rows), keeping + * the activations out of the levels a decode step runs at. The kernel bands stay at the + * real pass: the engine runs the real declare's kernels at every level. */ + const int64_t r = std::min(P, ctx->max_tok); + P = std::max(mm, r / mm * mm); + } + if (P % mm) return RAD_E_SHAPE; + const int64_t R = P / mm; + const int64_t ACC = RAD_ACCESS_PER_REQUEST; + /* The window side in patches (the reference states it in pixels and divides by patch_size). + * A window_attention layer's longest segment is one window. */ + const int64_t win_seg = side * side; + + /* ---- weights, replicated. Model-level groups for the stem and the adapter; one group per + * block from `first_group` on, so a tower block is its own movement unit. */ + auto bw = [&](const char* dn, const char* src, std::initializer_list shp, + RadWeightGroup g) -> rad_weight { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, RAD_BF16, shp, ACC, RAD_SHARD_NONE, g); + }; + w_patch = bw(nm.f("v.patch.weight"), + nm.ckpt("model.vision_tower.patch_embedder.patch_embedding.weight"), + { width, patch_dim }, grp_model()); + w_pos = bw(nm.f("v.pos.weight"), + nm.ckpt("model.vision_tower.patch_embedder.position_embedding_table.weight"), + { npos, width }, grp_model()); + lw_pre = bw(nm.f("v.lnpre.weight"), nm.ckpt("model.vision_tower.ln_pre.weight"), { width }, + grp_model()); + lb_pre = bw(nm.f("v.lnpre.bias"), nm.ckpt("model.vision_tower.ln_pre.bias"), { width }, + grp_model()); + L.assign((size_t)depth, Layer{}); + for (int64_t i = 0; i < depth; ++i) { + Layer& l = L[(size_t)i]; + const RadWeightGroup g = grp_layer(first_group + (int)i); + const int li = (int)i; + auto src = [&](const char* s) { return nm.ckpt("model.vision_tower.layers.%d.%s", li, s); }; + auto dn = [&](const char* s) { return nm.f("v.blk.%d.%s", li, s); }; + l.n1w = bw(dn("norm1.weight"), src("norm1.weight"), { width }, g); + l.n1b = bw(dn("norm1.bias"), src("norm1.bias"), { width }, g); + /* The reference's three biased projections, joined q | k | v into one GEMM. */ + if (map_concat(b, dn("qkv.weight"), + { src("attn.q_proj.weight"), src("attn.k_proj.weight"), + src("attn.v_proj.weight") }) < 0) + return RAD_E_INVAL; + l.qkv_w = decl_w(b, dn("qkv.weight"), RAD_BF16, { 3 * width, width }, ACC, + RAD_SHARD_NONE, g, 0, { width, width, width }); + if (map_concat(b, dn("qkv.bias"), + { src("attn.q_proj.bias"), src("attn.k_proj.bias"), + src("attn.v_proj.bias") }) < 0) + return RAD_E_INVAL; + l.qkv_b = decl_w(b, dn("qkv.bias"), RAD_BF16, { 3 * width }, ACC, RAD_SHARD_NONE, g, 0, + { width, width, width }); + l.out_w = bw(dn("proj.weight"), src("attn.proj.weight"), { width, width }, g); + l.out_b = bw(dn("proj.bias"), src("attn.proj.bias"), { width }, g); + l.n2w = bw(dn("norm2.weight"), src("norm2.weight"), { width }, g); + l.n2b = bw(dn("norm2.bias"), src("norm2.bias"), { width }, g); + l.up_w = bw(dn("fc1.weight"), src("mlp.fc1.weight"), { ff, width }, g); + l.up_b = bw(dn("fc1.bias"), src("mlp.fc1.bias"), { ff }, g); + l.down_w= bw(dn("fc2.weight"), src("mlp.fc2.weight"), { width, ff }, g); + l.down_b= bw(dn("fc2.bias"), src("mlp.fc2.bias"), { width }, g); + if (!l.n1w || !l.n1b || !l.qkv_w || !l.qkv_b || !l.out_w || !l.out_b || !l.n2w || !l.n2b || + !l.up_w || !l.up_b || !l.down_w || !l.down_b) + return RAD_E_INVAL; + l.full = full[(size_t)i] != 0; + l.max_seg = l.full ? ctx->max_enc_patches : win_seg; + } + lw_post = bw(nm.f("v.lnpost.weight"), nm.ckpt("model.vision_tower.ln_post.weight"), { width }, + grp_model()); + lb_post = bw(nm.f("v.lnpost.bias"), nm.ckpt("model.vision_tower.ln_post.bias"), { width }, + grp_model()); + w_a1 = bw(nm.f("v.mlp.fc1.weight"), nm.ckpt("model.vision_adapter.fc1.weight"), + { proj_ff, out_hidden }, grp_model()); + w_a2 = bw(nm.f("v.mlp.fc2.weight"), nm.ckpt("model.vision_adapter.fc2.weight"), + { proj_ff, proj_ff }, grp_model()); + w_proj = bw(nm.f("v.proj.weight"), nm.ckpt("model.vision_projection.weight"), + { n_embd, proj_ff }, grp_model()); + if (!w_patch || !w_pos || !lw_pre || !lb_pre || !lw_post || !lb_post || !w_a1 || !w_a2 || + !w_proj) + return RAD_E_INVAL; + + /* ---- activations. `mh` holds the merged rows: `pixtral_merge` folds each 2x2 block's four + * patch rows into one row of mm * width in the reference's pixel_shuffle layout, and the + * adapter's first layer reads it. */ + 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_p = decl_b(b, nm.f("v.p"), 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_ff = decl_b(b, nm.f("v.ff"), RAD_BF16, { P, ff }); + b_idx = decl_b(b, nm.f("v.idx"), RAD_I32, { P }); + b_inv = decl_b(b, nm.f("v.inv"), RAD_I32, { P }); + b_pos = decl_b(b, nm.f("v.pos"), RAD_I32, { 2, P }); + b_cuw = decl_b(b, nm.f("v.cuw"), RAD_I32, { P + 1 }); + b_mh = decl_b(b, nm.f("v.mh"), RAD_BF16, { R, mm * width }); + b_m1 = decl_b(b, nm.f("v.m1"), RAD_BF16, { R, proj_ff }); + b_m2 = decl_b(b, nm.f("v.m2"), RAD_BF16, { R, proj_ff }); + b_out = decl_b(b, nm.f("v.out"), RAD_BF16, { R, n_embd }); + if (!b_x || !b_h || !b_p || !b_qkv || !b_att || !b_ff || !b_idx || !b_inv || !b_pos || !b_cuw || + !b_mh || !b_m1 || !b_m2 || !b_out) + return RAD_E_INVAL; + + auto gemm_b = [&](int64_t rows, int64_t N, int64_t K, const char* a, rad_weight w, + rad_weight bias) -> rad_op { + return RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16"), RAD_STR("act", a)), + RAD_WEIGHTS(w, bias)); + }; + auto gemm = [&](int64_t rows, int64_t N, int64_t K, rad_weight w) -> rad_op { + return RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + }; + auto lnorm = [&](int64_t rows, int64_t n, double e, rad_weight w, rad_weight bias) -> rad_op { + return RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", e), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + }; + auto attn_op = [&](int64_t max_seg) -> rad_op { + return RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)head_dim)), + RAD_INT("max_seqlen", max_seg)), + RAD_NOWEIGHTS); + }; + + /* The stem is bias-less (the reference's patch_embedding states no bias). */ + op_patch = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("N", width), + RAD_INT("K", patch_dim), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_patch)), + {}, { b_x }); + op_pos = rw(b, RAD_OP(b, "grid_embed_pad", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), + RAD_INT("side", side), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w_pos)), + { b_x }, { b_x }); + op_lpre = rw(b, lnorm(P, width, eps, lw_pre, lb_pre), { b_x }, { b_h }); + op_wo = rw(b, RAD_OP(b, "window_order", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("window", side)), + RAD_NOWEIGHTS), + {}, { b_idx, b_inv, b_pos, b_cuw }); + op_gidx = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { b_h, b_idx }, { b_p }); + for (Layer& l : L) { + l.ln1 = rw(b, lnorm(P, width, 1e-5, l.n1w, l.n1b), { b_p }, { b_h }); + l.qkv = rw(b, gemm_b(P, 3 * width, width, "none", l.qkv_w, l.qkv_b), { b_h }, { b_qkv }); + l.rope = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("head_dim", head_dim), + RAD_INT("n_head", heads), RAD_INT("n_head_kv", heads), + RAD_F64("theta", theta), RAD_F64("scale", 1.0), + RAD_STR("mode", "axial"), + RAD_INT("rotary_dim", head_dim), + RAD_STR("sections", sec)), + RAD_NOWEIGHTS), + { b_qkv, b_pos }, { b_qkv }); + /* A window layer's segment bounds are the order op's per-window cu; a full layer's are + * the pass's frame bounds, raw (the permutation is within frames, so they read the same + * values in permuted order). */ + l.attn = rw(b, attn_op(l.max_seg), + l.full ? std::initializer_list{ b_qkv } + : std::initializer_list{ b_qkv, b_cuw }, + { b_att }); + l.proj = rw(b, gemm_b(P, width, width, "none", l.out_w, l.out_b), { b_att, b_p }, { b_p }); + l.ln2 = rw(b, lnorm(P, width, 1e-5, l.n2w, l.n2b), { b_p }, { b_h }); + l.up = rw(b, gemm_b(P, ff, width, "gelu", l.up_w, l.up_b), { b_h }, { b_ff }); + l.down = rw(b, gemm_b(P, width, ff, "none", l.down_w, l.down_b), { b_ff, b_p }, { b_p }); + } + op_ginv = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { b_p, b_inv }, { b_x }); + op_lpost = rw(b, lnorm(P, width, eps, lw_post, lb_post), { b_x }, { b_x }); + /* The reference's pixel_shuffle: each 2x2 block's four patches fold into one row with the + * channels interleaved (block, channel, sub-patch), which is `pixtral_merge`'s layout. A view + * over four consecutive rows cannot produce it: the concatenated form is a different tensor. */ + op_merge = rw(b, RAD_OP(b, "pixtral_merge", + RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", width), + RAD_INT("merge", merge), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { b_x }, { b_mh }); + /* The adapter: both linears bias-less, gelu between and after (the reference's + * act(fc2(act(fc1(x))))). */ + op_m1 = rw(b, gemm(R, proj_ff, mm * width, w_a1), { b_mh }, { b_m1 }); + op_g1 = rw(b, RAD_OP(b, "gelu", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { b_m1 }, { b_m2 }); + op_m2 = rw(b, gemm(R, proj_ff, proj_ff, w_a2), { b_m2 }, { b_m1 }); + op_g2 = rw(b, RAD_OP(b, "gelu", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", proj_ff), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { b_m1 }, { b_m2 }); + op_proj = rw(b, gemm(R, n_embd, proj_ff, w_proj), { b_m2 }, { b_out }); + /* perception_emb_norm: MuseGlimmerRMSNorm(eps = the TEXT model's rms_norm_eps, with_scale + * False) -- no gain operand, no centered 1+. */ + op_perc = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", n_embd), + RAD_F64("eps", m->rms_eps), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { b_out }, { b_out }); + + if (!ctx->shape_probe) { + RadEncoderDecl e{}; + e.name = "vision"; + e.modalities = RAD_MM_IMAGE | RAD_MM_VIDEO; + e.patch_dim = patch_dim; + e.merge = mm; + e.max_patches = ctx->max_enc_patches; + e.n_embd = n_embd; + e.out = b_out; + RAD_ARCH_TRY(rad_declare_encoder(b, &e)); + int64_t nfull = 0; + for (int64_t l = 0; l < depth; ++l) nfull += full[(size_t)l]; + rad_note(b, "vision tower: %lld blocks of %lld (%lld heads x %lld), ff %lld, patch %lld x " + "%lld x %lld, merge %lld, windows of %lld patches (%lld full attention); " + "%lld patches a pass -> %lld rows of %lld", + (long long)depth, (long long)width, (long long)heads, (long long)head_dim, + (long long)ff, (long long)temporal, (long long)patch, (long long)patch, + (long long)merge, (long long)side, (long long)nfull, (long long)P, (long long)R, + (long long)n_embd); + } + on = true; + return RAD_OK; +} + +/* Stage taps, the same protocol as rad_block_sam.h's: RADIANCE_DEBUG_MM_BUFFERS names stages + * (comma separated, matched as substrings) and RADIANCE_DEBUG_MM_DUMP's directory receives + * tap..bf16 -- raw bf16 rows, one file a stage. The copy is issued on the pass's stream + * behind the producing op and synced, so it reads that op's output rather than whatever writes + * the buffer later (the after-pass dump in core/engine_mm.cpp cannot see intermediates). */ +inline void muse_tap(RadCtx* c, const char* tag, rad_buf b, int64_t rows, int64_t cols) { + static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP"); + static const char* const env = std::getenv("RADIANCE_DEBUG_MM_BUFFERS"); + if (!dir || !*dir || !env || !*env || rows <= 0 || cols <= 0 || rad_rank(c) != 0) return; + bool want = false; + const size_t tl = std::strlen(tag); + for (const char* s = env; *s && !want;) { + const char* e = s; + while (*e && *e != ',') ++e; + const size_t l = (size_t)(e - s); + for (size_t i = 0; l && i + l <= tl && !want; ++i) + want = std::strncmp(tag + i, s, l) == 0; + s = *e ? e + 1 : e; + } + if (!want) return; + void* p = rad_buf_ptr(c, b); + if (!p) return; + std::vector h((size_t)(rows * cols)); + if (rad_memcpy_async(h.data(), p, (size_t)(rows * cols * 2), rad_stream(c)) < 0) return; + rad_stream_sync(rad_stream(c)); + char path[512]; + std::snprintf(path, sizeof path, "%s/tap.%s.bf16", dir, tag); + if (FILE* f = std::fopen(path, "wb")) { + std::fwrite(h.data(), sizeof(uint16_t), h.size(), f); + std::fclose(f); + } +} + +inline void MuseTower::step(RadCtx* c, const RadBatch* batch) const { + const int64_t Pn = batch->enc_n_patch, S = batch->enc_n_seg; + const int64_t mm = merge * merge, Rn = Pn / mm; + if (!on || Pn <= 0 || Pn > P || Pn % mm || S <= 0 || !batch->enc_coord || !batch->enc_cu || + !batch->enc_seg_h || !batch->enc_seg_w || !batch->enc_pixels) { + rad_step_fail(c, "an encoder pass this program's vision tower cannot serve: no tower, or " + "more patches than it was declared for, or not whole merged rows"); + return; + } + /* Windows per frame, from the pass's host grids: the window layers' cu is the per-window + * boundaries among permuted rows, `n_win + 1` entries of the order op's output. */ + int64_t n_win = 0; + for (int64_t s = 0; s < S; ++s) + n_win += (batch->enc_seg_h[s] + side - 1) / side * ((batch->enc_seg_w[s] + side - 1) / side); + if (n_win > P) { + rad_step_fail(c, "an encoder pass whose window count exceeds the tower's declared rows"); + return; + } + /* Patches, coordinates (planes 0-3: row, column, segment height, segment width, in patches) + * and the frame boundaries, staged by the core. The full layers read the frame boundaries + * unchanged: the window permutation is within frames, so the boundaries among permuted rows + * are these values (the reference passes its cu_seqlens the same way). */ + const RadOperand pix = praw2(batch->enc_pixels, RAD_BF16, Pn, patch_dim); + const RadOperand crd = praw2(batch->enc_coord, RAD_I32, 4, Pn); + const RadOperand cu = praw(batch->enc_cu, RAD_I32, S + 1); + RadOperand cuw = RAD_B(b_cuw); + cuw.rows = n_win + 1; + RadOperand pos = RAD_B(b_pos); + pos.rows = 2; + pos.cols = Pn; + + RAD_ISSUE_N(c, op_patch, Pn, pix, RAD_W(w_patch), brows(b_x, Pn)); + RAD_ISSUE_N(c, op_pos, Pn, brows(b_x, Pn), RAD_W(w_pos), crd); + muse_tap(c, "v.patchpos", b_x, Pn, width); + RAD_ISSUE_N(c, op_lpre, Pn, brows(b_x, Pn), RAD_W(lw_pre), RAD_W(lb_pre), brows(b_h, Pn)); + muse_tap(c, "v.lnpre", b_h, Pn, width); + RAD_ISSUE_N(c, op_wo, Pn, crd, cu, brows(b_idx, Pn), brows(b_inv, Pn), pos, cuw); + RAD_ISSUE_N(c, op_gidx, Pn, brows(b_h, Pn), brows(b_idx, Pn), brows(b_p, Pn)); + for (size_t li = 0; li < L.size(); ++li) { + const Layer& l = L[li]; + RAD_ISSUE_N(c, l.ln1, Pn, brows(b_p, Pn), RAD_W(l.n1w), RAD_W(l.n1b), brows(b_h, Pn)); + RAD_ISSUE_N(c, l.qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv_w), RAD_W(l.qkv_b), RAD_NONE, + brows(b_qkv, Pn)); + RAD_ISSUE_N(c, l.rope, Pn, brows(b_qkv, Pn), pos); + RAD_ISSUE_N(c, l.attn, Pn, + bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn), + bcol(b_qkv, 2 * width, width, Pn), + l.full ? cu : cuw, brows(b_att, Pn)); + RAD_ISSUE_N(c, l.proj, Pn, brows(b_att, Pn), RAD_W(l.out_w), RAD_W(l.out_b), + brows(b_p, Pn), brows(b_p, Pn)); + RAD_ISSUE_N(c, l.ln2, Pn, brows(b_p, Pn), RAD_W(l.n2w), RAD_W(l.n2b), brows(b_h, Pn)); + RAD_ISSUE_N(c, l.up, Pn, brows(b_h, Pn), RAD_W(l.up_w), RAD_W(l.up_b), RAD_NONE, + brows(b_ff, Pn)); + RAD_ISSUE_N(c, l.down, Pn, brows(b_ff, Pn), RAD_W(l.down_w), RAD_W(l.down_b), + brows(b_p, Pn), brows(b_p, Pn)); + if (li == 0) muse_tap(c, "v.blk0", b_p, Pn, width); + if (li + 1 == L.size()) muse_tap(c, "v.blkL", b_p, Pn, width); + } + RAD_ISSUE_N(c, op_ginv, Pn, brows(b_p, Pn), brows(b_inv, Pn), brows(b_x, Pn)); + muse_tap(c, "v.ginv", b_x, Pn, width); + /* ln_post over the P patches, then the reference's pixel_shuffle into merged rows. */ + RAD_ISSUE_N(c, op_lpost, Pn, brows(b_x, Pn), RAD_W(lw_post), RAD_W(lb_post), brows(b_x, Pn)); + muse_tap(c, "v.lnpost", b_x, Pn, width); + RAD_ISSUE_N(c, op_merge, Pn, brows(b_x, Pn), crd, brows(b_mh, Rn)); + muse_tap(c, "v.merge", b_mh, Rn, mm * width); + RAD_ISSUE_N(c, op_m1, Rn, brows(b_mh, Rn), RAD_W(w_a1), brows(b_m1, Rn)); + muse_tap(c, "v.fc1", b_m1, Rn, proj_ff); + RAD_ISSUE_N(c, op_g1, Rn, brows(b_m1, Rn), brows(b_m2, Rn)); + RAD_ISSUE_N(c, op_m2, Rn, brows(b_m2, Rn), RAD_W(w_a2), brows(b_m1, Rn)); + RAD_ISSUE_N(c, op_g2, Rn, brows(b_m1, Rn), brows(b_m2, Rn)); + RAD_ISSUE_N(c, op_proj, Rn, brows(b_m2, Rn), RAD_W(w_proj), brows(b_out, Rn)); + muse_tap(c, "v.proj", b_out, Rn, n_embd); + RAD_ISSUE_N(c, op_perc, Rn, brows(b_out, Rn), RAD_NONE, brows(b_out, Rn)); + muse_tap(c, "v.out", b_out, Rn, n_embd); +} + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* RAD_BLOCK_MUSEGLIMMER_VISION_H */ diff --git a/arch/flint/CMakeLists.txt b/arch/flint/CMakeLists.txt new file mode 100644 index 00000000..ed33a1e6 --- /dev/null +++ b/arch/flint/CMakeLists.txt @@ -0,0 +1,9 @@ +# Built in radiance's tree, or standalone against an installed radiance. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(flint LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(flint architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/flint.cpp) diff --git a/arch/flint/flint.cpp b/arch/flint/flint.cpp new file mode 100644 index 00000000..ee046510 --- /dev/null +++ b/arch/flint/flint.cpp @@ -0,0 +1,544 @@ +/* flint -- Recursive Flint (39.8B-A2.5B): two dense layers then 47 sigmoid-routed MoE layers, + * grouped-query attention with per-head Q/K RMSNorm, a learned per-head softmax sink, and a + * 513-token sliding window on 35 of the 49 layers (the other 14 are full attention and NoPE). + * + * 2 dense layers: rmsnorm -> q/k/v -> qk-norm -> [rope] -> paged attention + sink -> o + * rmsnorm -> gate_up -> silu_mul -> down + * 47 MoE layers: same attention; rmsnorm -> router -> top-6 of 256 (sigmoid) + * -> grouped gate_up -> silu_mul -> down -> gather + * + ungated shared expert (2 x 512) + * + * Weights come from a BF16 or recipe-quantized Flint checkpoint; the blocks probe the stored + * encoding. Two trunk forms, read from layer 0's q projection: + * + * - a rotated int8 trunk (data/recipes/flint-iq8r.recipe: IQ8R linears, i8 codes rotated by a + * 128-wide Hadamard): the norms, the gated products and the attention output write + * had_quant_act_i8g's codes themselves, every linear reads them at i8a8h, and the routed + * experts are rotated int8 (or another form with an int8 row) read by the grouped GEMM's int8 + * rows from the same codes (MoeFP8::a8), as qwen35moe_w8a8 serves Qwen3.6-35B-A3B; + * - any other (bf16, the four-bit attention of data/recipes/flint-bf16-q4.recipe, plain int8 + * linears): each linear reads the bf16 plane or quantises it itself, and four-bit experts read + * the block input's E4M3 pair, as hyv3_bf16 serves its W4 and W8 recipes. + * + * No MTP head. + */ +#include +#include "flint_attention.h" +#include +#include +#include "rad_abi_layout.h" + +#include +#include +#include +#include +#include +#include +#include +#include + +namespace flint { +using namespace rad::arch; + +struct Layer { + bool dense = false; + bool sliding = false; + FlintAttn attn{}; + MlpFP8 dense_mlp{}; + MoeFP8 moe{}; +}; + +struct Model { + Names nm{}; + Geom g{}; + int64_t n_ff_expert = 0, n_ff_shared = 0; + rad_kvgroup kv_full = 0, kv_win = 0; + /* The trunk is rotated int8 (rad_fp8.h's linear_is_w8h or linear_is_wnh), its activation codes + * one scale a `trunk_g8` columns: 256 for IQ8R, 128 for the other rotated forms. */ + bool trunk_rot = false; + int64_t trunk_g8 = RAD_FP8_BLOCK; + + rad_buf x = 0, h_out = 0, logits = 0; + ActFP8 h{}; + /* The routed experts' rotated int8 copy of the block input, where a rotated trunk's norms do + * not write the codes themselves (MoeFP8::Wire::hr). */ + ActFP8 hr{}; + rad_buf q = 0, k = 0, v = 0; + ActFP8 attn{}; + rad_buf dense_gate_up = 0; + ActFP8 dense_ffn{}; + MoeFP8::Wire mw{}; + + rad_weight token = 0, final_norm = 0, lm_head = 0; + rad_op embed = 0, embed_ar = 0, shared_one = 0, final_rms = 0, gather = 0, logits_op = 0; + std::vector layers; +}; + +/* Every per-instance state is indexed by slot (rad_build_slot at declare, rad_slot in step). */ +static Model g_model[MAX_SLOTS]; + +/* Flint's layer schedule: full attention (and NoPE) at 0, 1, 5, 9, ..., 45, 48; the other 35 + * layers are sliding (window 513) and carry RoPE. */ +static bool is_full(int64_t l) { + return l == 0 || l == 1 || l == 48 || (l >= 5 && l <= 45 && (l - 5) % 4 == 0); +} + +static int64_t meta_i(const RadModelMeta* meta, const char* a, const char* b, int64_t def) { + int64_t v = meta_text_geti(meta, a, INT64_MIN); + if (v == INT64_MIN && b) v = meta_text_geti(meta, b, INT64_MIN); + return v == INT64_MIN ? def : v; +} + +static int check_model(const RadModelMeta* meta, const Geom& g, Model& m) { + const int64_t sliding = meta_i(meta, "sliding_window", "flint.attention.sliding_window", 513); + const int64_t n_expert = meta_text_geti(meta, "num_experts", meta->n_expert); + const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used); + const int64_t moe_ff = meta_i(meta, "moe_intermediate_size", + "flint.expert_feed_forward_length", 512); + const int64_t shared = meta_i(meta, "shared_expert_intermediate_size", + "flint.expert_shared_feed_forward_length", 1024); + const int64_t dense_ff = meta_i(meta, "intermediate_size", + "flint.feed_forward_length", 6144); + + if (g.n_layer != 49 || g.n_embd != 2048 || g.n_head_all != 32 || g.n_head_kv_all != 4 || + g.head_dim != 128 || g.n_vocab_all != 150144 || dense_ff != 6144 || + sliding != 513 || n_expert != 256 || top_k != 6 || moe_ff != 512 || shared != 1024) { + fprintf(stderr, "radiance: flint: unsupported geometry (49 layers, 2048-wide, 32/4 " + "heads x 128, vocab 150144, 256 experts top-6, expert width 512, shared " + "1024, sliding 513); got %lld layers, %lld-wide, %lld/%lld heads, " + "vocab %lld, %lld experts top-%lld, expert %lld, shared %lld, " + "sliding %lld, dense %lld\n", + (long long)g.n_layer, (long long)g.n_embd, (long long)g.n_head_all, + (long long)g.n_head_kv_all, (long long)g.n_vocab_all, (long long)n_expert, + (long long)top_k, (long long)moe_ff, (long long)shared, (long long)sliding, + (long long)dense_ff); + return RAD_E_UNSUPPORTED; + } + if (g.world != 1 && g.world != 2) { + fprintf(stderr, "radiance: flint supports tensor-parallel world sizes 1 and 2\n"); + return RAD_E_UNSUPPORTED; + } + m.n_ff_expert = moe_ff; + m.n_ff_shared = shared; + return RAD_OK; +} + +static void block_slice_128(int64_t width, int world, int rank, int64_t* lo, int64_t* hi) { + const int64_t blocks = width / RAD_FP8_BLOCK; + const int64_t base = blocks / world, rem = blocks % world; + const int64_t first = rank * base + std::min(rank, rem); + const int64_t count = base + (rank < rem ? 1 : 0); + *lo = first * RAD_FP8_BLOCK; + *hi = (first + count) * RAD_FP8_BLOCK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS || + rad_build_slot(ctx) >= MAX_SLOTS) + return RAD_E_INVAL; + Model& m = g_model[rad_build_slot(ctx)]; + m = Model{}; + m.nm = Names(ctx->scope); + + int status = geom_from(m.g, meta, ctx, "bf16", RAD_BF16); + if (status < 0) return status; + Geom& g = m.g; + Names& nm = m.nm; + + status = check_model(meta, g, m); + if (status < 0) return status; + + if (ctx->kv_dtype != RAD_DT_INVALID && ctx->kv_dtype != RAD_BF16 && ctx->kv_dtype != RAD_I8) { + fprintf(stderr, "radiance: flint serves a bf16 or an int8 KV cache, not %s\n", + rad_dtype_name((uint32_t)ctx->kv_dtype)); + return RAD_E_UNSUPPORTED; + } + status = yarn_from(g, meta, "", g.head_dim); + if (status < 0) return status; + + const int64_t sliding = meta_i(meta, "sliding_window", "flint.attention.sliding_window", 513); + const int64_t n_expert_all = meta_text_geti(meta, "num_experts", meta->n_expert); + const int64_t top_k = meta_text_geti(meta, "num_experts_per_tok", meta->n_expert_used); + if (n_expert_all % g.world != 0) return RAD_E_SHAPE; + const int64_t n_expert_local = n_expert_all / g.world; + + /* Two paged groups: the 14 full layers grow with the context, the 35 sliding layers keep + * only 513 tokens. That is what makes 262K affordable. Both take the deployment's cache + * dtype: bf16, or with --kv-cache-dtype i8 the int8 cache (abi/rad_builder.h), K and V as + * int8 codes with one f16 scale each per token and head. */ + RadKVGroupDecl kd{}; + kd.kind = RAD_KV_FULL; + kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + kd.n_head_kv = g.n_head_kv; + kd.head_dim = g.head_dim; + m.kv_full = rad_decl_kv_group(b, nm.f("kv_full"), &kd); + if (!m.kv_full) return RAD_E_INVAL; + + RadKVGroupDecl kw = kd; + kw.kind = RAD_KV_WINDOW; + kw.window = sliding; + m.kv_win = rad_decl_kv_group(b, nm.f("kv_win"), &kw); + if (!m.kv_win) return RAD_E_INVAL; + g.kv_dtype = rad_dtype_name(kd.dtype); + + const int64_t T = g.max_tok, qd = g.q_dim(), kvd = g.kv_dim(); + + /* ---- the trunk's stored form, read from layer 0's q projection through that layer's own + * LinearFP8, which then does not map it again; the activations below carry rotated int8 + * codes only for a rotated trunk. */ + m.layers.resize((size_t)g.n_layer); + RAD_ARCH_TRY(m.layers[0].attn.q.probe(b, nm, g, nm.f("blk.0.attn_q"), + { nm.ckpt("model.layers.0.self_attn.q_proj.weight") })); + { + RadEncoding enc{}; + m.trunk_rot = weight_enc(b, nm.f("blk.0.attn_q.weight"), &enc) && + (linear_is_w8h(enc) || linear_is_wnh(enc)); + if (m.trunk_rot) m.trunk_g8 = linear_w8h_group(enc); + } + + MoeFP8::Config mc{}; + mc.n_expert_all = n_expert_all; + mc.n_expert = n_expert_local; + mc.expert_base = n_expert_local * g.rank; + mc.probed_expert = mc.expert_base; + mc.top_k = top_k; + mc.n_ff_exp = m.n_ff_expert; + mc.norm_topk = 1; + mc.sigmoid_router = 1; + mc.route_scale = meta_text_getf(meta, "router_scaling_factor", 1.0); + mc.shared_ungated = 1; + /* One combine at the gather, not two separately reduced arms: TP2 then matches the TP1 + * arithmetic (the local routed+shared sum is rounded to bf16 once and the closing + * all-reduce reduces it), and that single collective folds into the next block's norm. */ + mc.shared_fp32_combine = 0; + mc.shared_one_external = g.world == 1; + mc.router_fuse = 1; + mc.rows = T < 2048 ? T : 2048; + block_slice_128(m.n_ff_shared, g.world, g.rank, &mc.shared_lo, &mc.shared_hi); + mc.n_ff_shared = mc.shared_hi - mc.shared_lo; + + /* ---- the routed experts' stored form, read from the first routed layer's first owned + * expert; every layer is declared with it (MoeFP8::declare checks each layer's own). */ + const int64_t l_moe = 2; + MoeFP8::Src probe_src{}; + probe_src.experts = nm.ckpt("model.layers.%lld.mlp.experts", (long long)l_moe); + RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)l_moe, probe_src, &mc)); + if (m.trunk_rot && (mc.expert_bf16 || !mc.expert_rot)) { + fprintf(stderr, "radiance: flint: the trunk is rotated int8 and the routed experts are " + "%s; a rotated trunk's experts read its int8 codes and are stored rotated " + "(data/recipes/flint-iq8r.recipe)\n", + mc.expert_bf16 ? "plain bf16" : "unrotated"); + return RAD_E_UNSUPPORTED; + } + if (!m.trunk_rot && (mc.expert_i8 || mc.expert_iqr)) { + fprintf(stderr, "radiance: flint: the routed experts are rotated int8 and the trunk is " + "not; they read the trunk's rotated int8 codes, so convert the trunk with " + "them (data/recipes/flint-iq8r.recipe)\n"); + return RAD_E_UNSUPPORTED; + } + + /* ---- activation buffers. A rotated trunk's producers write had_quant_act_i8g's codes and + * its linears declare no quantiser: the norms (rmsnorm_had_quant_i8g and, at two ranks, its + * all-reduce form) where a loaded library serves them, the attention output (q_attn), and the + * gated products (gated_had_quant_i8g). Where the norms are not served, each linear + * quantises `h` itself and the experts read `hr`, written once a layer. Any other trunk keeps + * both code pairs on `h`: E4M3 for four-bit experts, int8 for a plain int8 linear's own + * quantiser. */ + const bool rot = m.trunk_rot; + const int64_t g8 = m.trunk_g8; + const bool h_fed = rot && rad_op_declared(b, "rmsnorm_had_quant_i8g") && + (g.world != 2 || rad_op_declared(b, "ar_rmsnorm_had_quant_i8g")); + m.x = decl_b(b, nm.f("x"), RAD_BF16, {T, g.n_embd}); + m.h.x = decl_b(b, nm.f("h"), RAD_BF16, {T, g.n_embd}); + RAD_ARCH_TRY(m.h.declare_qs(b, nm, g, "h", g.n_embd, 0, true, !h_fed, + rot ? g8 : (int64_t)RAD_FP8_BLOCK)); + m.h.q8_fed = m.h.q8_rot = h_fed; + if (rot && !h_fed) { + RAD_ARCH_TRY(m.hr.declare_qs(b, nm, g, "moe_hr", g.n_embd, 0, true, false, + RAD_FP8_BLOCK)); + m.hr.q8_fed = m.hr.q8_rot = true; + } + m.q = decl_b(b, nm.f("attn_q"), RAD_BF16, {T, qd}); + m.k = decl_b(b, nm.f("attn_k"), RAD_BF16, {T, kvd}); + m.v = decl_b(b, nm.f("attn_v"), RAD_BF16, {T, kvd}); + m.attn.x = decl_b(b, nm.f("attn_out"), RAD_BF16, {T, qd}); + RAD_ARCH_TRY(m.attn.declare_qs(b, nm, g, "attn_out", qd, 0, true, false, + rot ? g8 : (int64_t)RAD_FP8_BLOCK)); + m.attn.q8_fed = m.attn.q8_rot = rot; + m.dense_gate_up = decl_b(b, nm.f("dense_gate_up"), RAD_BF16, {T, 2 * g.n_ff}); + m.dense_ffn.x = decl_b(b, nm.f("dense_ffn"), RAD_BF16, {T, g.n_ff}); + if (rot) + RAD_ARCH_TRY(m.dense_ffn.declare_pair(b, nm, g, "dense_ffn", g.n_ff, 0, true, g8, + "gated_had_quant_i8g")); + else + RAD_ARCH_TRY(m.dense_ffn.declare_qs(b, nm, g, "dense_ffn", g.n_ff, 0, true)); + m.h_out = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, g.n_embd}); + m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab}); + RAD_ARCH_TRY(rad_declare_logits(b, m.logits)); + + const int64_t R = T, S = mc.rows * top_k; + m.mw.x = m.x; + m.mw.h = m.h; + m.mw.hr = m.hr; + m.mw.logits = decl_b(b, nm.f("moe_logits"), RAD_F32, {R, n_expert_all}); + m.mw.ids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, top_k}); + m.mw.ew = decl_b(b, nm.f("moe_weights"), RAD_F32, {R, top_k}); + m.mw.eoff = decl_b(b, nm.f("moe_offsets"), RAD_I32, {n_expert_local + 1}); + m.mw.ecnt = decl_b(b, nm.f("moe_counts"), RAD_I32, {n_expert_local}, RAD_BUF_PERSIST); + m.mw.sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {S}); + m.mw.egu = decl_b(b, nm.f("moe_gate_up"), RAD_BF16, {S, 2 * mc.n_ff_exp}); + m.mw.eff.x = decl_b(b, nm.f("moe_ffn"), RAD_BF16, {S, mc.n_ff_exp}); + if (rot) { + /* The routed arm of a rotated trunk is int8 throughout: the gated product's rotated codes + * at one scale a 128 of K, which the grouped GEMM's int8 rows read (MoeFP8::a8). */ + RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, true, false, + RAD_FP8_BLOCK)); + m.mw.eff.q8_fed = m.mw.eff.q8_rot = true; + } else { + RAD_ARCH_TRY(m.mw.eff.declare_qs(b, nm, g, "moe_ffn", mc.n_ff_exp, S, true)); + } + m.mw.edn = decl_b(b, nm.f("moe_down"), RAD_BF16, {S, g.n_embd}); + m.mw.sgu = decl_b(b, nm.f("shared_gate_up"), RAD_BF16, {T, 2 * mc.n_ff_shared}); + m.mw.sff.x = decl_b(b, nm.f("shared_ffn"), RAD_BF16, {T, mc.n_ff_shared}); + if (rot) { + /* The shared expert's down projection is a trunk linear whose input codes take the group + * its own weight is stored at, read from the first routed layer's through that layer's + * own LinearFP8 (which then maps it once). */ + LinearFP8& sd = m.layers[(size_t)l_moe].moe.sh_down; + RAD_ARCH_TRY(sd.probe(b, nm, g, nm.f("blk.%lld.ffn_down_shexp", (long long)l_moe), + { nm.ckpt("model.layers.%lld.mlp.shared_expert.down_proj.weight", + (long long)l_moe) })); + const int64_t sg = sd.probed_i8 ? sd.probed_g8 : g8; + RAD_ARCH_TRY(m.mw.sff.declare_pair(b, nm, g, "shared_ffn", mc.n_ff_shared, 0, true, sg, + "gated_had_quant_i8g")); + } else { + RAD_ARCH_TRY(m.mw.sff.declare_qs(b, nm, g, "shared_ffn", mc.n_ff_shared, 0, true)); + } + m.mw.sout = decl_b(b, nm.f("shared_out"), RAD_BF16, {T, g.n_embd}); + m.mw.sgate = decl_b(b, nm.f("shared_one"), RAD_BF16, {T, 1}); + if (mc.shared_one_external) { + m.shared_one = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", 1), + RAD_STR("dtype", g.dtype), RAD_F64("value", 1.0)), + RAD_NOWEIGHTS), {}, {m.mw.sgate}); + if (!m.shared_one) return RAD_E_INVAL; + } + + RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"))); + RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"), + nm.ckpt("model.embed_tokens.weight"))); + m.token = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd}, + RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); + m.final_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + m.lm_head = 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()); + m.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_WEIGHTS(m.token)), + {}, {m.x}); + if (g.world > 1) + m.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.x}, {m.x}); + + FlintAttn::Wire aw{}; + aw.x = m.x; aw.h = m.h; aw.q = m.q; aw.k = m.k; aw.v = m.v; aw.attn = m.attn; + MlpFP8::Wire dw{}; + dw.x = m.x; dw.h = m.h; dw.gate_up = m.dense_gate_up; dw.ffn = m.dense_ffn; + + for (int64_t l = 0; l < g.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.dense = (l < 2); + lay.sliding = !is_full(l); + const char* pre = nm.ckpt("model.layers.%lld", (long long)l); + + FlintAttn::Src as{}; + as.norm = nm.ckpt("%s.input_layernorm.weight", pre); + as.q = nm.ckpt("%s.self_attn.q_proj.weight", pre); + as.k = nm.ckpt("%s.self_attn.k_proj.weight", pre); + as.v = nm.ckpt("%s.self_attn.v_proj.weight", pre); + as.q_norm = nm.ckpt("%s.self_attn.q_norm.weight", pre); + as.k_norm = nm.ckpt("%s.self_attn.k_norm.weight", pre); + as.o = nm.ckpt("%s.self_attn.o_proj.weight", pre); + as.sink = nm.ckpt("%s.self_attn.softmax_offset", pre); + as.use_rope = lay.sliding; + as.window = lay.sliding ? sliding : 0; + + const rad_kvgroup grp = lay.sliding ? m.kv_win : m.kv_full; + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, grp)); + /* Every block after the first folds the previous block's delta and, at two ranks, + * absorbs its all-reduce into its own norm; the last block keeps its add for the plain + * final norm and issues its own collective. */ + const LayerFold f = layer_fold(g, l, g.n_layer, nullptr, 0, false); + status = lay.attn.declare(b, nm, g, (int)l, grp, aw, as, f.mix_fold, false, f.mix_ar_in, + f.mix_ar_out); + if (status < 0) { + fprintf(stderr, "radiance: flint: attention layer %lld declaration failed (%d)\n", + (long long)l, status); + return status; + } + + if (lay.dense) { + MlpFP8::Src ds{}; + const char* mlp = nm.ckpt("%s.mlp", pre); + ds.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre); + ds.gate = nm.ckpt("%s.gate_proj.weight", mlp); + ds.up = nm.ckpt("%s.up_proj.weight", mlp); + ds.down = nm.ckpt("%s.down_proj.weight", mlp); + status = lay.dense_mlp.declare(b, nm, g, (int)l, dw, ds, true, f.mlp_add, + f.mlp_ar_in, f.mlp_ar_out); + if (status < 0) { + fprintf(stderr, "radiance: flint: dense layer %lld declaration failed (%d)\n", + (long long)l, status); + return status; + } + } else { + MoeFP8::Src ms{}; + ms.cfg = mc; + const char* mlp = nm.ckpt("%s.mlp", pre); + ms.norm = nm.ckpt("%s.post_attention_layernorm.weight", pre); + ms.router = nm.ckpt("%s.gate.weight", mlp); + /* Flint has no router correction bias. The sigmoid router's bias is + * selection-only, so the converter merges a zero [n_expert] tensor under this + * name (data/flint-zero-bias.safetensors, `rad-convert --add`). */ + ms.router_bias = nm.ckpt("%s.expert_bias", mlp); + ms.experts = nm.ckpt("%s.experts", mlp); + ms.shared = nm.ckpt("%s.shared_expert", mlp); + status = lay.moe.declare(b, nm, g, (int)l, m.mw, ms, true, f.mlp_add, f.mlp_ar_in, + f.mlp_ar_out); + if (status < 0) { + fprintf(stderr, "radiance: flint: MoE layer %lld declaration failed (%d)\n", + (long long)l, status); + return status; + } + } + } + + m.final_rms = 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", 0.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.final_norm)), + {m.x}, {m.h.x}); + m.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.h.x}, {m.h_out}); + m.logits_op = 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.lm_head)), + {m.h_out}, {m.logits}); + + rad_note(b, "Flint: %lld layers (2 dense, 47 top-%lld/%lld sigmoid MoE), %lld/%lld " + "attention/KV heads x %lld; expert width %lld, shared %lld, window %lld on %s; " + "per-head sink on every layer; %s trunk, %s KV cache", + (long long)g.n_layer, (long long)top_k, (long long)n_expert_all, + (long long)g.n_head_all, (long long)g.n_head_kv_all, (long long)g.head_dim, + (long long)m.n_ff_expert, (long long)mc.n_ff_shared, (long long)sliding, + g.world == 2 ? "both cards" : "one card", + rot ? (g8 == RAD_I8_GROUP_WIDE ? "IQ8R (rotated int8)" : "rotated int8") : "unrotated", + g.kv_dtype); + return RAD_OK; +} + +static void step(RadCtx* c, const RadBatch* batch) { + Model& m = g_model[rad_slot(c)]; + RAD_ISSUE(c, m.embed, + praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.token), + brows(m.x, batch->n_tok)); + if (m.embed_ar) + RAD_ISSUE_N(c, m.embed_ar, (int64_t)batch->n_tok * m.g.n_embd, + brows(m.x, batch->n_tok), RAD_NONE); + + if (m.shared_one) + RAD_ISSUE_N(c, m.shared_one, batch->n_tok, brows(m.mw.sgate, batch->n_tok)); + for (Layer& layer : m.layers) { + layer.attn.step(c, batch); + if (layer.dense) layer.dense_mlp.step(c, batch); + else layer.moe.step(c, batch); + } + + RAD_ISSUE(c, m.final_rms, brows(m.x, batch->n_tok), RAD_W(m.final_norm), + brows(m.h.x, batch->n_tok)); + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.gather, batch->n_out, + brows(m.h.x, batch->n_tok), praw(batch->out_ids, RAD_I32, batch->n_out), + brows(m.h_out, batch->n_out)); + RAD_ISSUE_N(c, m.logits_op, batch->n_out, + brows(m.h_out, batch->n_out), RAD_W(m.lm_head), + brows(m.logits, batch->n_out)); + } +} + +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->draft_depth = 0; + return RAD_OK; +} + +} // namespace flint + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(flint) +static const char* const kFlintTriggers[] = { "" }; +static const RadChatFormat kFlintChatFormat = { + .struct_size = sizeof(RadChatFormat), + .name = "flint", + .reasoning_open = "", + .reasoning_close = "", + .reasoning_breaks = kFlintTriggers, + .n_reasoning_breaks = 1, + .reasoning_in_prompt = RAD_CHAT_THINK_FROM_PROMPT, + .section_open = nullptr, + .section_close = nullptr, + .call_separator = nullptr, + .call_open = nullptr, + .call_close = nullptr, + .name_prefix = "", + .name_suffix = "", + .call_end = "", + .arg_prefix = "", + .arg_name_suffix = "", + .arg_value_prefix = "", + .arg_value_suffix = "", + .string_value = RAD_CHAT_VALUE_RAW, + .other_value = RAD_CHAT_VALUE_JSON, + .value_newlines = 1, + .triggers = kFlintTriggers, + .n_triggers = 1, + .args_form = RAD_CHAT_ARGS_TAGGED, +}; +extern "C" const RadChatFormat* rad_arch_chat_format(const RadModelMeta*) { + return &kFlintChatFormat; +} +extern "C" const char* rad_arch_id(void) { return "flint"; } +/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */ +RAD_ARCH_MULTI_INSTANCE() +extern "C" const char* rad_arch_quant(void) { return ""; } +extern "C" int rad_arch_declare(RadBuilder* b, const RadModelMeta* m, const RadBuildCtx* c) { + return flint::declare(b, m, c); +} +extern "C" void rad_arch_step(struct RadCtx* c, const struct RadBatch* batch) { + flint::step(c, batch); +} +extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; } +RAD_PLUGIN_ABI_LAYOUT_EXPORT +extern "C" const RadPluginInfo* rad_plugin_info(void) { + static const RadPluginInfo info = { + RAD_PLUGIN_ARCH, "flint", "0.1.0", + "Recursive Flint: 2 dense + 47 sigmoid MoE layers, sink attention, 513 window", "" + }; + return &info; +} +#endif diff --git a/arch/flint/flint_attention.h b/arch/flint/flint_attention.h new file mode 100644 index 00000000..2926dbe6 --- /dev/null +++ b/arch/flint/flint_attention.h @@ -0,0 +1,272 @@ +/* flint_attention.h -- Flint's grouped-query attention: per-head Q/K RMSNorm, optional NeoX + * RoPE (sliding layers) or no positional encoding (full layers), a learned per-head softmax + * sink, a paged bf16 or int8 KV cache, and an optional sliding window. + * + * Derived from arch/hyv3_common/hyv3_attention.h (the same linears and activation plumbing); the + * differences are Flint's: + * + * - every layer has `self_attn.softmax_offset` (GGUF `attn_sinks`), one learned logit a query + * head added to the scaled scores before the softmax; + * - the full-attention layers are NoPE, the sliding layers carry NeoX RoPE; + * - the sliding layers bound the paged attention with `window` (513). + * + * The sink and the window ride in attn_paged_sink, which libr4d serves at h128/gqa8 on both + * caches. The block's closing all-reduce may be taken by the next block's norm (ar_out). + */ +#ifndef FLINT_ATTENTION_H +#define FLINT_ATTENTION_H + +#include + +#include +#include +#include +#include + +namespace rad { +namespace arch { + +struct FlintAttn { + struct Wire { + rad_buf x = 0; /* [max_tok, n_embd] residual stream */ + ActFP8 h{}; /* [max_tok, n_embd] normed input, then o output */ + rad_buf q = 0; /* [max_tok, q_dim], projected, normed and rotated */ + rad_buf k = 0; /* [max_tok, kv_dim] */ + rad_buf v = 0; /* [max_tok, kv_dim] */ + ActFP8 attn{}; /* [max_tok, q_dim] attention output */ + }; + + struct Src { + const char* norm = nullptr; + const char* q = nullptr; + const char* k = nullptr; + const char* v = nullptr; + const char* q_norm = nullptr; + const char* k_norm = nullptr; + const char* o = nullptr; + /* `self_attn.softmax_offset` (no `.weight` suffix). Null declares no sink. */ + const char* sink = nullptr; + bool use_rope = true; + int64_t window = 0; /* 0: full attention */ + }; + + Geom g{}; + Wire w{}; + int layer = 0; + rad_kvgroup kv = 0; + + rad_weight w_norm = 0, w_q_norm = 0, w_k_norm = 0, w_sink = 0; + LinearFP8 q{}, k{}, v{}, o{}; + NormQuantFP8 nq_h{}; + QuantFP8 q_attn{}; + rad_op op_q_norm = 0, op_k_norm = 0; + rad_op op_rope_q = 0, op_rope_k = 0, op_attn = 0, op_kv_store = 0; + rad_op op_qkr_store = 0; /* Q/K norms, NeoX rotary (or none) and cache store, decode band */ + int64_t qkr_rows = 0; + rad_op op_ar = 0, op_add = 0; + /* The next block's norm absorbs this block's closing all-reduce (NormQuantFP8::fuse_ar), so + * this one must not issue it. Counterpart of `ar_in`; both sides ask ar_taken(g, T, ...) on + * the same facts, so they agree. */ + bool ar_out = false; + int ar_out_take = kArOutNorm; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group, + const Wire& wire, const Src& src, bool fold = false, bool add_out = true, + int ar_in = kArNone, bool ar_out_ = false); + bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); } + void step(RadCtx* c, const RadBatch* batch) const; +}; + +inline int FlintAttn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, + rad_kvgroup group, const Wire& wire, const Src& src, + bool fold, bool add_out, int ar_in, bool ar_out_) { + g = geom; + w = wire; + layer = l; + kv = group; + ar_out = ar_out_; + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + + if (g.world > g.n_head_kv_all) { + fprintf(stderr, "radiance: flint declares no KV row span and cannot serve world_size = %d " + "with n_head_kv = %lld\n", g.world, (long long)g.n_head_kv_all); + return RAD_E_UNSUPPORTED; + } + + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), src.q_norm)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k_norm.weight", l), src.k_norm)); + w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_q_norm = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_F32, {g.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_k_norm = decl_w(b, nm.f("blk.%d.attn_k_norm.weight", l), RAD_F32, {g.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + if (!w_norm || !w_q_norm || !w_k_norm) return RAD_E_INVAL; + + /* The learned softmax offset, one f32 a query head, sharded with the heads. */ + if (src.sink) { + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_sinks", l), src.sink)); + w_sink = decl_w(b, nm.f("blk.%d.attn_sinks", l), RAD_F32, {g.n_head}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + if (!w_sink) return RAD_E_INVAL; + } + + // As in the other pre-norm blocks, absorb a preceding delta into the residual stream. + // The fused kernel normalizes the BF16-rounded sum, not an unrounded FP32 substitute. + RAD_ARCH_TRY(nq_h.declare(b, g, w_norm, fold ? w.h.x : w.x, w.h, g.n_embd, + fold ? w.x : 0, 0, ar_in)); + RAD_ARCH_TRY(q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), q_dim, g.n_embd, + RAD_SHARD_ROW, grp_layer(l), {src.q}, w.h, w.q)); + RAD_ARCH_TRY(k.declare(b, nm, g, nm.f("blk.%d.attn_k", l), kv_dim, g.n_embd, + RAD_SHARD_ROW, grp_layer(l), {src.k}, w.h, w.k)); + RAD_ARCH_TRY(v.declare(b, nm, g, nm.f("blk.%d.attn_v", l), kv_dim, g.n_embd, + RAD_SHARD_ROW, grp_layer(l), {src.v}, w.h, w.v)); + + auto head_norm = [&](int64_t heads, rad_weight wt) { + return RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * heads), RAD_INT("n", g.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(wt)); + }; + op_q_norm = rw(b, head_norm(g.n_head, w_q_norm), {w.q}, {w.q}); + op_k_norm = rw(b, head_norm(g.n_head_kv, w_k_norm), {w.k}, {w.k}); + if (src.use_rope) { + op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, g.head_dim, "neox"), + {w.q}, {w.q}); + op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, g.head_dim, + "neox"), + {w.k}, {w.k}); + } + + const rad_op attn = w_sink + ? rw(b, RAD_OP(b, "attn_paged_sink", + RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), + RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_INT("window", src.window), RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_WEIGHTS(w_sink)), + {w.q}, {w.attn.x}) + : rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), + RAD_INT("head_dim", g.head_dim), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_INT("window", src.window), RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.q}, {w.attn.x}); + op_attn = attn; + op_kv_store = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.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}, {}); + + /* The fused prologue serves the rope layers and, with `rotary_dim` 0, the NoPE ones: the + * kernel then only copies the normed head through the rotary stage. Rows exist for the bf16 + * and the int8 cache (qkv_norm_rope_kv_store_h128_bf16, _i8); prefill heights and libraries + * without the fold take the standalone norms, ropes and kv_store. */ + if (g.head_dim == 128 && !std::strcmp(g.dtype, "bf16") && + (!std::strcmp(g.kv_dtype, "bf16") || !std::strcmp(g.kv_dtype, "i8")) && + !g.rope_mc && g.yarn.factor == 0.0f && + rad_op_declared(b, "qkv_norm_rope_kv_store")) { + qkr_rows = qk_fuse_rows(g); + op_qkr_store = RAD_OP(b, "qkv_norm_rope_kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, qkr_rows), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv), + RAD_F64("theta", g.theta), RAD_F64("eps", g.eps), + RAD_F64("scale", g.rope_scale), RAD_STR("mode", "neox"), + RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype), + RAD_INT("v_norm", 0), + RAD_INT("rotary_dim", src.use_rope ? g.head_dim : 0), + RAD_INT("block_size", rad_kv_block_size(b, kv)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_WEIGHTS(w_q_norm, w_k_norm)); + if (!op_qkr_store || !rad_op_resolved(b, op_qkr_store)) op_qkr_store = 0; + if (op_qkr_store) + op_qkr_store = rw(b, op_qkr_store, {w.q, w.k, w.v}, {w.q, w.k, w.v}); + } + + /* The out projection's input codes: where the model feeds them (a rotated int8 trunk, + * ActFP8::q8_fed), q_attn writes had_quant_act_i8g's pair and the projection declares no + * quantiser. Otherwise every form the out projection can take reads the bf16 plane or + * quantises it itself (LinearFP8 refuses the E4M3-pair formats), so no quantiser runs here. */ + if (w.attn.q8_fed) RAD_ARCH_TRY(q_attn.declare(b, g, w.attn, q_dim)); + RAD_ARCH_TRY(o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), g.n_embd, q_dim, + RAD_SHARD_COL, grp_layer(l), {src.o}, w.attn, w.h.x)); + 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.x}, {w.h.x}); + if (add_out) 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.x}, {w.x}); + /* A rope layer needs either the fused prologue or both standalone rope ops; without this, + * step() would silently skip the rotation. */ + const bool rope_ok = !src.use_rope || op_qkr_store || (op_rope_q && op_rope_k); + return op_attn && op_kv_store && rope_ok && (!add_out || op_add) && + (op_qkr_store || (op_q_norm && op_k_norm)) + ? RAD_OK : RAD_E_INVAL; +} + +inline void FlintAttn::step(RadCtx* c, const RadBatch* batch) 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; + + nq_h.step(c, T); + q.step(c, w.h, w.q, T); + k.step(c, w.h, w.k, T); + v.step(c, w.h, w.v, T); + if (op_qkr_store && T <= qkr_rows) { + RAD_ISSUE_N(c, op_qkr_store, T, brows(w.q, T), brows(w.k, T), brows(w.v, T), + rope_posmc(g, batch, T), RAD_W(w_q_norm), RAD_W(w_k_norm), + praw(slot, RAD_I32, T), kv_cache(kv, layer)); + } else { + RAD_ISSUE_N(c, op_q_norm, T * g.n_head, brows(w.q, T), RAD_W(w_q_norm), brows(w.q, T)); + RAD_ISSUE_N(c, op_k_norm, T * g.n_head_kv, brows(w.k, T), RAD_W(w_k_norm), brows(w.k, T)); + if (op_rope_q) { + RAD_ISSUE(c, op_rope_q, brows(w.q, T), rope_posmc(g, batch, T)); + RAD_ISSUE(c, op_rope_k, brows(w.k, T), rope_posmc(g, batch, T)); + } + RAD_ISSUE(c, op_kv_store, brows(w.k, T), brows(w.v, T), praw(slot, RAD_I32, T), + kv_cache(kv, layer)); + } + if (w_sink) + 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), + RAD_W(w_sink), brows(w.attn.x, T)); + else + 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.x, T)); + q_attn.step(c, T); + o.step(c, w.attn, w.h.x, T); + if (issues_ar(T)) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h.x, T), RAD_NONE); + if (op_add) RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h.x, T), brows(w.x, T)); +} + +} // namespace arch +} // namespace rad + +#endif /* FLINT_ATTENTION_H */ diff --git a/arch/museglimmer/CMakeLists.txt b/arch/museglimmer/CMakeLists.txt new file mode 100644 index 00000000..6024ba23 --- /dev/null +++ b/arch/museglimmer/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/museglimmer -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(museglimmer LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(museglimmer architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/museglimmer.cpp) diff --git a/arch/museglimmer/chat.h b/arch/museglimmer/chat.h new file mode 100644 index 00000000..b190828c --- /dev/null +++ b/arch/museglimmer/chat.h @@ -0,0 +1,71 @@ +/* Muse Glimmer's reply format: the ATEM channel protocol its chat template renders. + * + * The template's generation prompt ends at `<|start|>assistant`, so the model opens its own + * channels: `` reasoning first, then the answer: + * + * to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=user<|message|> ...answer... + * + * `reasoning_close` carries the whole channel transition, so the answer's own header is consumed + * with the reasoning block's close and the content begins at the answer's first byte. A reply + * that skips the reasoning opens on the answer's channel directly (`to=user<|message|> ...`); + * `content_open` names that header so it is dropped there too. + * + * Tool calls are the template's ATEM dialect, emitted as their own assistant turn whose channel + * names the tool (chat_template.jinja, render_atem): + * + * to=self<|message|> ...reasoning... <|eom|><|start|>assistant to=NAME<|message|> + * + * + * value + * + * + * + * String parameters are written raw, everything else as JSON (the template's `tojson`); the + * section opener is the constrained-decoding trigger, and it is also the reasoning break: a call + * turn's channel header names the tool rather than `user`, so the answer's `reasoning_close` + * does not match there and the reasoning block runs to the section, swallowing the `<|eom|>` and + * the header. + */ +#pragma once +#include "rad_builder.h" + +namespace museglimmer { + +inline const RadChatFormat* muse_chat_format() { + static const RadChatFormat f = [] { + RadChatFormat x{}; + x.struct_size = sizeof(x); + x.name = "plugin:museglimmer"; + x.reasoning_open = "to=self<|message|>"; + x.reasoning_close = "<|eom|><|start|>assistant to=user<|message|>"; + static const char* const kBreaks[] = {""}; + x.reasoning_breaks = kBreaks; + x.n_reasoning_breaks = 1; + /* The model opens its own channel; the prompt carries none. */ + x.reasoning_in_prompt = RAD_CHAT_THINK_NEVER; + x.content_open = "to=user<|message|>"; + x.section_open = ""; + x.section_close = ""; + x.call_open = ""; + x.call_end = ""; + x.arg_prefix = ""; + x.arg_value_suffix = ""; + x.string_value = RAD_CHAT_VALUE_RAW; /* the template writes string arguments raw */ + x.other_value = RAD_CHAT_VALUE_JSON; /* booleans, numbers, arrays, objects as tojson */ + x.value_newlines = 1; + /* No grammar triggers: the reference deployment (vLLM's --tool-call-parser muse) runs + * unconstrained and parses whatever the model writes. A trigger arms the lazy tool-call + * grammar, and with the DFlash drafter the trigger fires mid-verify -- inside drafted + * text -- at the reasoning-to-call boundary, which spins the sampler and loops the + * channel header (measured: drafter on = the header repeats 3-4x and the reply stalls; + * drafter off = one header, clean call). The streaming parser reads natural ATEM as + * it is. */ + return x; + }(); + return &f; +} + +} /* namespace museglimmer */ \ No newline at end of file diff --git a/arch/museglimmer/museglimmer.cpp b/arch/museglimmer/museglimmer.cpp new file mode 100644 index 00000000..b9d7513b --- /dev/null +++ b/arch/museglimmer/museglimmer.cpp @@ -0,0 +1,847 @@ +/* museglimmer.cpp -- Meta's Muse Glimmer 30B, bf16 weights and bf16 activations. + * + * Muse Glimmer (HF `meta-models/Muse-Glimmer-30B`, model_type `muse_glimmer`) is a dense text + * model with a separate vision tower. The text trunk here is served by this plugin; the tower and + * its projector are declared at the bottom of declare() when the deployment asked for media. + * + * ============================== WHAT IT SERVES ============================== + * + * The unquantised release (quantisation descriptor ""), every projection a bf16 GEMM. The lm_head + * is declared at whatever the model holds, so a recipe-made block-fp8 head uses the fp8 logits + * kernel. + * + * ============================== THE SHAPE, AT 30B ============================== + * + * 52 layers, `layer_types` full_attention on every 4th layer counted back from the last + * (3, 7, ..., 51; the shipped config states the array, and this plugin checks + * it against full_attention_interval 4 rather than trusting either alone) + * hidden 6656 ffn 19968 vocab 202048 (lm_head not tied) + * 32 heads / 2 kv heads / head_dim 128 -> GQA 16 + * sliding_window 2048: the sliding layers own a RAD_KV_WINDOW pool, the full layers a + * RAD_KV_FULL pool; a sequence holds one state per bound layer of each group + * q and output gate are SEPARATE checkpoint tensors (`q_proj`, `gate_proj`), unlike Qwen3.5's + * interleaved q_proj -- two GEMMs, two buffers, no fused q|gate row + * `layer_rope_theta`: 500000 on the sliding layers, 0 on the full ones. A 0 layer is NoPE: no + * rotary is declared or issued there (the reference passes + * position_embeddings=None). max_position_embeddings 131072, rope_type default + * + * ============================== WHAT DIFFERS FROM A LLAMA-LIKE ============================== + * + * Every deviation from the Qwen/Llama shape below is load-bearing; getting one wrong yields + * fluent wrong text (spec §17 refuses instead). + * + * * Four norms a layer, all Gemma-2 style "centered" norms, x_hat * (1 + w): the attention's + * input (rms_norm_eps 1e-5) and its output (post_norm_eps 1e-8), then the feed-forward's input + * (1e-5) and output (1e-8). The residual adds the *normed* branch, not the raw one. + * * The q/k "norm" is weightless: MuseGlimmerRMSNorm(with_scale=False), a plain RMS norm over + * head_dim at rms_norm_eps. The query is then multiplied by `qk_scale_factor` (3.87); the key + * is not. The attention scale stays 1/sqrt(head_dim). `rmsnorm` serves both: no gain operand, + * `mult` on the query. + * * The embedding is normed after the lookup: a weightless RMS norm at rms_norm_eps on the + * gathered rows (MuseGlimmerTextNormedEmbedding). It cannot be folded into the table because + * a drafter embeds without it, so it is an op. + * * The final norm (`model.language_model.norm.weight`) is a plain RMSNorm WITH a gain and + * without the centered 1+: wadd 0, unlike every layer norm. + * * The logits are pre-scaled by `output_multiplier` (1/sqrt(26)) before the Gemma-style tanh + * softcap: 20 * tanh(logits * mult / 20). The multiplier is carried on the final norm's + * `mult` (its output feeds only the head), the cap on `logit_softcap` over the f32 logits. + * + * ============================== WHAT THIS PLUGIN DOES NOT DECLARE ============================== + * + * The speculative drafter Meta ships beside the model (a DFlash block stack over layers + * 1, 13, 25, 37, 49) is not declared: it lives in its own checkpoint with its own `draft.` + * config, which this tree has no fixture for. Serving the trunk alone is a complete model. + */ +#include +#include +#include +#include +#include "chat.h" + +#include +#include +#include + +namespace museglimmer { + +using namespace rad::arch; + +/* ---- the checkpoint's config. A multimodal model keeps the trunk under `text_config.`; accept + * the bare spelling too, so a text-only GGUF container of the same family reads the same way. */ +namespace { + +double cfg_f(const RadModelMeta* m, const char* key, double dflt) { + return rad_meta_getf(m, (std::string("text_config.") + key).c_str(), + rad_meta_getf(m, key, dflt)); +} +long long cfg_i(const RadModelMeta* m, const char* key, long long dflt) { + return rad_meta_geti(m, (std::string("text_config.") + key).c_str(), + rad_meta_geti(m, key, dflt)); +} +const char* cfg_s(const RadModelMeta* m, const char* key, const char* dflt) { + return rad_meta_gets(m, (std::string("text_config.") + key).c_str(), + rad_meta_gets(m, key, dflt)); +} + +} // namespace + +/* One trunk layer. The rope ops exist only where layer_rope_theta says so; the branch is fixed + * per layer by the model. */ +struct Layer { + int full = 0; /* full attention (no window, no rope in this family) */ + int rope = 0; /* carries a rotary (the sliding layers) */ + + rad_weight w_norm = 0, w_post = 0, w_q = 0, w_gate = 0, w_k = 0, w_v = 0, w_o = 0; + rad_weight w_fnorm = 0, w_fpost = 0, w_gate_up = 0, w_down = 0; + + rad_op op_norm = 0, op_q = 0, op_gate = 0, op_k = 0, op_v = 0; + rad_op op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0; + rad_op op_kv = 0, op_attn = 0, op_sig = 0, op_mul = 0, op_o = 0, op_ar = 0; + rad_op op_post = 0, op_add = 0; + rad_op op_fnorm = 0, op_gu = 0, op_act = 0, op_down = 0, op_far = 0, op_fpost = 0, op_fadd = 0; + + /* The layer's calibration inputs (rad_calib_full.h): -1 where the run does not record it. */ + int cs_in = -1, cs_o = -1, cs_mlp = -1, cs_down = -1; +}; + +struct Model { + Names nm{""}; + Geom g{}; /* the trunk geometry, the rank's shard of it */ + Geom g_rope{}; /* the same, with the sliding layers' rotary base (decl_rope reads theta) */ + float qk_mult = 0; /* qk_scale_factor */ + float post_eps = 0; /* post_norm_eps */ + float out_mult = 0; /* output_multiplier */ + float softcap = 0; /* final_logit_softcapping; 0: none */ + int64_t window = 0; /* sliding_window */ + + rad_kvgroup kv_win = 0, kv_full = 0; + + /* the residual stream and the two vocabulary edges */ + rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0; + rad_buf b_q = 0, b_gate = 0, b_k = 0, b_v = 0, b_attn = 0; + rad_buf b_gu = 0, b_ffn = 0; + + rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_embed_norm = 0; + rad_op op_final_norm = 0, op_gather = 0, op_logits = 0, op_cap = 0; + + /* ---- media (arch/common/rad_block_museglimmer_vision.h): the vision tower and the scatter of + * its rows, declared only when the container carries a tower and the deployment asked for + * media. The tower is declared last, so its activations share the arena with every buffer + * above. */ + bool media = false; + rad_op op_media_rows = 0; + MuseTower vit{}; + + /* ---- the DFlash drafter (arch/common/rad_block_muse_dflash.h): declared last, only when the + * container carries one and the serve asks for drafts. It reads the trunk's residual stream at + * `draft.target_layer_ids`, keeps its own KV group, and proposes `block_size - 1` tokens a + * pass for the trunk to verify. */ + bool have_df = false; + MuseDflash df{}; + MuseDflash::Wire dfw{}; + MuseTaps taps{}; + rad_kvgroup kv_draft = 0; + + std::vector layers; + + /* --calib-dir: the whole Hessian of every linear's input over a --calib-corpus run. */ + CalibFull calib; + int cs_head = -1; +}; + +/* Declare runs once per rank of an instance, on the rank's own thread (spec §1, §9); every + * instance's state is its slot's (rad_build_slot / rad_slot). */ +static Model g_model[MAX_SLOTS]; + +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 || rad_build_slot(ctx) >= MAX_SLOTS) + return RAD_E_INVAL; + + Model& m = g_model[rad_build_slot(ctx)]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + + /* A routed model is not this family. */ + if (meta->n_expert > 0) { + fprintf(stderr, "radiance: museglimmer refuses a checkpoint with %lld experts\n", + (long long)meta->n_expert); + return RAD_E_UNSUPPORTED; + } + + Geom& g = m.g; + Names& nm = m.nm; + + /* ---- the family's own config. Everything that changes the mathematics is required or read + * from the family defaults the reference config class states; a wrong default yields fluent + * wrong text, so nothing here falls back to a "reasonable" value silently. */ + m.qk_mult = (float)cfg_f(meta, "qk_scale_factor", 3.87); + m.post_eps = (float)cfg_f(meta, "post_norm_eps", 1e-8); + m.out_mult = (float)cfg_f(meta, "output_multiplier", 0.19611613513818404); + m.softcap = (float)cfg_f(meta, "final_logit_softcapping", 20.0); + m.window = cfg_i(meta, "sliding_window", 2048); + const double theta_rope = cfg_f(meta, "rope_parameters.rope_theta", + cfg_f(meta, "rope_theta", 0.0)); + if (!(m.qk_mult > 0.0f) || !(m.out_mult > 0.0f) || !(m.post_eps > 0.0f) || m.window <= 0 || + !(theta_rope > 0.0)) { + fprintf(stderr, "radiance: museglimmer: qk_scale_factor %g output_multiplier %g " + "post_norm_eps %g sliding_window %lld rope theta %g are all required\n", + (double)m.qk_mult, (double)m.out_mult, (double)m.post_eps, + (long long)m.window, theta_rope); + return RAD_E_INVAL; + } + if (g.rope_mc) { + fprintf(stderr, "radiance: museglimmer: the trunk has one-component rotary; a container " + "with mrope_section is not this family\n"); + return RAD_E_UNSUPPORTED; + } + + /* The rotary width is the full head: rope_parameters has no partial_rotary_factor and the + * reference rotates all of head_dim. */ + const int64_t n_rot = g.head_dim; + + /* ---- layer kinds. The config ships `layer_types`; where it does not (a GGUF container), the + * interval rule stands in. The two must agree where both exist: the schedule decides which + * layers keep a long context, and a wrong layer still generates fluent text. */ + std::vector full; + const char* kinds = cfg_s(meta, "layer_types", nullptr); + if (kinds && *kinds) + RAD_ARCH_TRY(parse_layer_kinds("museglimmer", kinds, {"full_attention"}, + "sliding_attention", &full)); + const int64_t interval = 4; + if ((int64_t)full.size() < g.n_layer) { + full.assign((size_t)g.n_layer, 0); + for (int64_t l = 0; l < g.n_layer; ++l) full[(size_t)l] = is_full_attention(l, interval); + if (kinds && *kinds) + rad_note(b, "the container's layer_types named %zu layers and the model has %lld; " + "building the full-attention layers by the interval %lld", + full.size() - (size_t)g.n_layer + (size_t)g.n_layer, (long long)g.n_layer, + (long long)interval); + } else { + for (int64_t l = 0; l < g.n_layer; ++l) { + if ((full[(size_t)l] != 0) != is_full_attention(l, interval)) { + fprintf(stderr, "radiance: museglimmer: layer_types makes layer %lld %s and " + "full_attention_interval %lld makes it %s\n", + (long long)l, full[(size_t)l] ? "full" : "sliding", (long long)interval, + is_full_attention(l, interval) ? "full" : "sliding"); + return RAD_E_UNSUPPORTED; + } + } + } + + /* Per-layer rotary: the shipped `layer_rope_theta`, else the family pattern (theta on the + * sliding layers, 0 -- NoPE -- on the full ones). */ + std::vector theta((size_t)g.n_layer, 0.0f); + const char* thetas = cfg_s(meta, "layer_rope_theta", nullptr); + if (thetas && *thetas) { + size_t i = 0; + for_each_token(thetas, [&](const char* t, size_t n) { + if (i >= theta.size()) return false; + char* e = nullptr; + const double v = std::strtod(std::string(t, n).c_str(), &e); + theta[i++] = e == t ? -1.0f : (float)v; + return true; + }); + if (i < theta.size()) { + fprintf(stderr, "radiance: museglimmer: layer_rope_theta names %zu layers and the " + "model has %lld\n", i, (long long)g.n_layer); + return RAD_E_INVAL; + } + } else { + for (int64_t l = 0; l < g.n_layer; ++l) + theta[(size_t)l] = full[(size_t)l] ? 0.0f : (float)theta_rope; + } + for (int64_t l = 0; l < g.n_layer; ++l) { + if (!(theta[(size_t)l] >= 0.0f)) { + fprintf(stderr, "radiance: museglimmer: layer_rope_theta[%lld] is not a number\n", + (long long)l); + return RAD_E_INVAL; + } + } + + /* Two Geoms: the trunk's for the buffers and shards, one with the sliding layers' rotary base + * for the rope ops (decl_rope takes theta from the Geom it is given). The rotary scaling is + * read into the rope Geom, against the sliding layers' own base: the extension reaches their + * rope and leaves the NoPE full layers untouched (they have no rotary to scale), and the + * mechanical extension past the trained 131072 positions -- which this family takes well, the + * full layers carrying no positions and the sliding ones reading only in-window relative + * offsets -- is the no-keys default this call returns. */ + m.g_rope = g; + m.g_rope.theta = (float)theta_rope; + RAD_ARCH_TRY(yarn_from(m.g_rope, meta, "", g.head_dim)); + + const int64_t q_dim = g.q_dim(); + const int64_t kv_dim = g.kv_dim(); + + /* ---- two KV groups (spec §7.2): the sliding layers' pool recycles blocks below the window, + * the full layers' does not. A group with no bound layers is a declare error. */ + const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16); + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_WINDOW; + sd.dtype = kvdt; + sd.window = m.window; + sd.n_head_kv = g.n_head_kv; + sd.head_dim = g.head_dim; + m.kv_win = rad_decl_kv_group(b, nm.f("kv_sliding"), &sd); + RadKVGroupDecl gd{}; + gd.kind = RAD_KV_FULL; + gd.dtype = kvdt; + gd.n_head_kv = g.n_head_kv; + gd.head_dim = g.head_dim; + m.kv_full = rad_decl_kv_group(b, nm.f("kv_full"), &gd); + g.kv_dtype = rad_dtype_name(kvdt); + if (m.kv_win == 0 || m.kv_full == 0) { + fprintf(stderr, "radiance: museglimmer: a KV group failed to declare\n"); + return RAD_E_INVAL; + } + + /* ---- activation buffers, sized at max_tok and shared by every layer; liveness over the + * declared read and write sets fits them in one arena (spec §3.1). */ + 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_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim}); + m.b_gate = decl_b(b, nm.f("attn_gate"),g.act_dtype, {g.max_tok, q_dim}); + m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim}); + m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, kv_dim}); + m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, 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}); + /* The lm_head runs over the sampled rows only (RadBatch::out_ids), not the whole step. */ + 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 drafter's taps. Declared before the trunk's layers: the buffer planner takes + * lifetimes in declaration order, so a tap buffer declared after them could share bytes a + * layer temporary lands on, and acceptance would collapse with no other symptom. */ + if (ctx->max_spec > 0 && m.taps.read(meta, g.n_layer) > 0) { + RAD_ARCH_TRY(m.taps.declare(b, nm, g, g.max_tok, m.b_x, g.act_dtype)); + if (m.taps.n <= 0) { + fprintf(stderr, "radiance: museglimmer: the container carries a drafter whose " + "draft.target_layer_ids name no layer of this %lld-layer trunk\n", + (long long)g.n_layer); + return RAD_E_INVAL; + } + } + + + /* ---- vocabulary edges, both row-sharded. The 30B does not tie its head; the second source + * serves family members that do, first present wins. */ + 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()); + /* A plain RMSNorm with a gain: declared at f32, cast at load, read with wadd 0. */ + m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + m.w_lm_head = 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()); + + 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_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}); + /* The embedding norm, after the vocabulary shard's reduction: a weightless RMS norm at + * rms_norm_eps, in place. Weightless because MuseGlimmerTextNormedEmbedding has no gain. */ + m.op_embed_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_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + + /* The encoder's rows overwrite the lookup before its reduction (as rad_block_vit.h's + * MediaRows): declared only when the tower is served, issued on the passes that carry rows, + * so the reduction counts each row once. */ + m.media = MuseTower::present(meta) && ctx->max_enc_patches > 0; + if (m.media) + m.op_media_rows = 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", g.dtype)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + + /* ---- calibration: the widest split input bounds the Hessian's width. */ + RAD_ARCH_TRY(m.calib.begin(b, nm, g, ctx, g.n_layer, + std::max({g.n_embd, q_dim * g.world, g.n_ff * g.world}), + std::max({g.n_embd, q_dim * g.world, g.n_ff * g.world}))); + + /* ---- the layers. */ + const int64_t attn_scale_num = 1; /* attention scale stays 1/sqrt(head_dim): the query's + * qk_scale_factor rides the q norm's `mult`. */ + (void)attn_scale_num; + m.layers.resize((size_t)g.n_layer); + for (int64_t l = 0; l < g.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.full = full[(size_t)l]; + lay.rope = theta[(size_t)l] > 0.0f; + const bool glob = lay.full; + rad_kvgroup kg = glob ? m.kv_full : m.kv_win; + const char* pre = "model.language_model.layers"; + const Geom& gr = lay.rope ? m.g_rope : m.g; + + /* -- weights. Shapes are [out, in]; gemm_nt reads B transposed. */ + 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_post.weight", l), + nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q.weight", l), + nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_gate.weight", l), + nm.ckpt("%s.%lld.self_attn.gate_proj.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_k.weight", l), + nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_v.weight", l), + nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), + nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l))); + 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.weight", l), + nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ffn_gate_up.weight", 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)}, + 0)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_down.weight", l), + nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l))); + + lay.w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + lay.w_post = decl_w(b, nm.f("blk.%d.attn_post.weight", l), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + lay.w_q = decl_w(b, nm.f("blk.%d.attn_q.weight", l), RAD_BF16, {q_dim, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + lay.w_gate = decl_w(b, nm.f("blk.%d.attn_gate.weight", l), RAD_BF16, {q_dim, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + lay.w_k = decl_w(b, nm.f("blk.%d.attn_k.weight", l), RAD_BF16, {kv_dim, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + lay.w_v = decl_w(b, nm.f("blk.%d.attn_v.weight", l), RAD_BF16, {kv_dim, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l)); + lay.w_o = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l)); + lay.w_fnorm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + lay.w_fpost = decl_w(b, nm.f("blk.%d.ffn_post.weight", l), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + lay.w_gate_up= decl_w(b, nm.f("blk.%d.ffn_gate_up.weight", l), RAD_BF16, + {2 * g.n_ff, g.n_embd}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, + grp_layer(l), 0, {g.n_ff, g.n_ff}); + lay.w_down = decl_w(b, nm.f("blk.%d.ffn_down.weight", l), RAD_BF16, {g.n_embd, g.n_ff}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l)); + + /* -- ops, in run order except attn_paged, declared before kv_store like every family: the + * two touch disjoint buffers and the block size comes from the resolved kernel. */ + lay.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", 1.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_norm)), + {m.b_x}, {m.b_h}); + lay.op_q = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_q)), + {m.b_h}, {m.b_q}); + lay.op_gate = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_gate)), + {m.b_h}, {m.b_gate}); + lay.op_k = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_k)), + {m.b_h}, {m.b_k}); + lay.op_v = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", kv_dim), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_v)), + {m.b_h}, {m.b_v}); + + /* The q/k norms are weightless (no gain operand), the query carrying qk_scale_factor on + * `mult`. Both run in place: a row's scale is computed before the row is written. */ + lay.op_qn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("mult", (double)m.qk_mult), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_q}, {m.b_q}); + lay.op_kn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_k}, {m.b_k}); + + if (lay.rope) { + lay.op_rq = rw(b, decl_rope(b, gr, g.max_tok, g.head_dim, g.n_head, 0, n_rot, "neox"), + {m.b_q}, {m.b_q}); + lay.op_rk = rw(b, decl_rope(b, gr, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, "neox"), + {m.b_k}, {m.b_k}); + } + + lay.op_attn = rw(b, rad_decl_op(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), + RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa()), + RAD_INT("causal", 1), + RAD_INT("window", glob ? 0 : m.window), + RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), + RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {m.b_q}, {m.b_attn}); + + lay.op_kv = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kg)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {m.b_k, m.b_v}, {}); + + /* out = attn * sigmoid(gate): two ops, as in the gated-attention block. */ + lay.op_sig = rw(b, RAD_OP(b, "sigmoid", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head), + RAD_INT("n", g.head_dim), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_gate}, {m.b_gate}); + lay.op_mul = rw(b, RAD_OP(b, "mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_attn, m.b_gate}, {m.b_attn}); + + lay.op_o = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd), + RAD_INT("K", q_dim), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_o)), + {m.b_attn}, {m.b_h}); + if (g.world > 1) + lay.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), + {m.b_h}, {m.b_h}); + /* The branch's own norm, at post_norm_eps, before the residual add. */ + lay.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", m.post_eps), RAD_F64("wadd", 1.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_post)), + {m.b_h}, {m.b_h}); + lay.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), + {m.b_x, m.b_h}, {m.b_x}); + + /* ---- the feed-forward, the same double norm. */ + lay.op_fnorm = 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", 1.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_fnorm)), + {m.b_x}, {m.b_h}); + lay.op_gu = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 2 * g.n_ff), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_gate_up)), + {m.b_h}, {m.b_gu}); + lay.op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_gu}, {m.b_ffn}); + lay.op_down = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd), + RAD_INT("K", g.n_ff), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_down)), + {m.b_ffn}, {m.b_h}); + if (g.world > 1) + lay.op_far = 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), + {m.b_h}, {m.b_h}); + lay.op_fpost = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", m.post_eps), RAD_F64("wadd", 1.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_fpost)), + {m.b_h}, {m.b_h}); + lay.op_fadd = 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), + {m.b_x, m.b_h}, {m.b_x}); + + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg)); + + /* -- calibration taps, the same four a dense family records. */ + if (m.calib.records(l)) { + const std::string L = std::string(pre) + "." + std::to_string(l); + lay.cs_in = (int)m.calib.sites.size(); + RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".input", + L + ".self_attn.q_proj," + L + ".self_attn.k_proj," + + L + ".self_attn.v_proj," + L + ".self_attn.gate_proj", + m.b_h, g.n_embd, g.n_embd)); + lay.cs_o = (int)m.calib.sites.size(); + RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".self_attn.o_proj.input", L + ".self_attn.o_proj", + m.b_attn, q_dim, q_dim * g.world)); + lay.cs_mlp = (int)m.calib.sites.size(); + RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".pre_feedforward.input", + L + ".mlp.gate_proj," + L + ".mlp.up_proj", + m.b_h, g.n_embd, g.n_embd)); + lay.cs_down = (int)m.calib.sites.size(); + RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".mlp.down_proj.input", L + ".mlp.down_proj", + m.b_ffn, g.n_ff, g.n_ff * g.world)); + } + } + + /* ---- the head. The final norm is a plain RMSNorm (wadd 0) that also carries the logits' + * pre-scale: its output feeds only the head, so mult here is logits * output_multiplier + * exactly. */ + m.op_final_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", 0.0), + RAD_F64("mult", (double)m.out_mult), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_out_norm)), + {m.b_x}, {m.b_h}); + if (m.calib.on && m.calib.hi == g.n_layer) { + m.cs_head = (int)m.calib.sites.size(); + RAD_ARCH_TRY(m.calib.site(b, g, -1, "lm_head.input", "lm_head", m.b_h, g.n_embd, g.n_embd)); + } + + 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_head)), + {m.b_hout}, {m.b_logits}); + /* cap * tanh(x / cap) over the f32 logits, after the pre-scale. */ + if (m.softcap > 0.0f) { + 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", (double)m.softcap), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {m.b_logits}, {m.b_logits}); + if (!m.op_cap) + rad_note(b, "warning: no kernel serves `logit_softcap` (load libr4d or libavx), so " + "the logits skip %g * tanh(x / %g): greedy output is unchanged, sampled " + "output draws from a sharper distribution", (double)m.softcap, + (double)m.softcap); + } + + /* ---- media: the vision tower, declared last so its activations share the arena with every + * buffer above (the trunk's weights were mapped and declared first). */ + if (m.media) + RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer)); + + /* ---- the DFlash drafter, declared last: its passes run after the whole trunk's, and the + * planner lays lifetimes out in declaration order. */ + if (m.taps.n > 0) { + RAD_ARCH_TRY(declare_muse_dflash(&m.df, &m.dfw, &m.kv_draft, b, nm, meta, ctx, g, m.taps, + (int)g.n_layer, m.w_tok, m.w_lm_head)); + m.have_df = true; + } + + /* ---- notes for --debug-graph. */ + int64_t nfull = 0, nrope = 0; + for (int64_t l = 0; l < g.n_layer; ++l) { + nfull += full[(size_t)l]; + nrope += theta[(size_t)l] > 0.0f; + } + rad_note(b, "rank %d/%d: %lld layers (%lld full attention, %lld sliding over a %lld-token " + "window; %lld with rotary at theta %g), n_head=%lld n_head_kv=%lld head_dim=%lld " + "n_ff=%lld vocab=[%lld,%lld)", + g.rank, g.world, (long long)g.n_layer, (long long)nfull, + (long long)(g.n_layer - nfull), (long long)m.window, (long long)nrope, + theta_rope, (long long)g.n_head, (long long)g.n_head_kv, (long long)g.head_dim, + (long long)g.n_ff, (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab)); + rad_note(b, "centered norms (1 + w): input/pre at eps %g, post at eps %g; the final norm is a " + "plain gain; the embedding and the q/k norms are weightless", (double)g.eps, + (double)m.post_eps); + rad_note(b, "attention scale 1/sqrt(%lld) with the query pre-scaled by qk_scale_factor %g; " + "logits pre-scaled by output_multiplier %g%s%g", + (long long)g.head_dim, (double)m.qk_mult, (double)m.out_mult, + m.softcap > 0.0f ? " and soft-capped at " : "", (double)m.softcap); + if (m.g_rope.theta != g.theta) + rad_note(b, "rotary runs on the sliding layers only (theta %g); the full-attention layers " + "are NoPE", (double)m.g_rope.theta); + rad_note(b, "logits for at most %lld sampled rows a step (of %lld tokens): gather_rows " + "selects RadBatch::out_ids before the lm_head", (long long)g.max_logit_rows, + (long long)g.max_tok); + + return RAD_OK; +} + +static void step(RadCtx* c, const RadBatch* batch) { + Model& m = g_model[rad_slot(c)]; + + /* An encoder pass runs only the vision tower (RadBatch::enc). */ + if (batch->enc) { + m.vit.step(c, batch); + return; + } + + /* A draft pass runs only the drafter: >0 the query pass on the staged block, <0 the context + * pass that projects and stores K/V for the tokens the trunk just committed. */ + if (batch->draft_pass != 0) { + if (!m.have_df) { + rad_step_fail(c, "this serve stages a draft pass but the container carries no drafter"); + return; + } + if (batch->draft_pass > 0) m.df.step(c, batch); + else m.df.context(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)); + /* The encoder's rows overwrite the lookup before the vocabulary shard's reduction, so the + * reduction counts each row once. */ + if (m.op_media_rows && batch->n_mm_rows > 0) + RAD_ISSUE_N(c, m.op_media_rows, 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)); + /* The vocab shard's reduction; declared only when world > 1, so tp1 is unchanged. */ + 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); + /* The embedding norm, after the reduction: it normalises whole rows. */ + RAD_ISSUE(c, m.op_embed_norm, brows(m.b_x, batch->n_tok), RAD_NONE, brows(m.b_x, batch->n_tok)); + + const int64_t T = batch->n_tok; + for (size_t li = 0; li < m.layers.size(); ++li) { + const Layer& l = m.layers[li]; + const rad_kvgroup kg = l.full ? m.kv_full : m.kv_win; + const RadKVGroupBatch* kvb = kv_batch(batch, kg); + 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; + + /* -- attention. */ + RAD_ISSUE(c, l.op_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T)); + RAD_ISSUE(c, l.op_q, brows(m.b_h, T), RAD_W(l.w_q), brows(m.b_q, T)); + RAD_ISSUE(c, l.op_gate, brows(m.b_h, T), RAD_W(l.w_gate), brows(m.b_gate, T)); + RAD_ISSUE(c, l.op_k, brows(m.b_h, T), RAD_W(l.w_k), brows(m.b_k, T)); + RAD_ISSUE(c, l.op_v, brows(m.b_h, T), RAD_W(l.w_v), brows(m.b_v, T)); + RAD_ISSUE_N(c, l.op_qn, T * m.g.n_head, brows(m.b_q, T), RAD_NONE, brows(m.b_q, T)); + RAD_ISSUE_N(c, l.op_kn, T * m.g.n_head_kv, brows(m.b_k, T), RAD_NONE, brows(m.b_k, T)); + if (l.rope) { + RAD_ISSUE(c, l.op_rq, brows(m.b_q, T), rope_posmc(m.g, batch, T)); + RAD_ISSUE(c, l.op_rk, brows(m.b_k, T), rope_posmc(m.g, batch, T)); + } + RAD_ISSUE(c, l.op_kv, + brows(m.b_k, T), brows(m.b_v, T), praw(slot, RAD_I32, T), + kv_cache(kg, (int)li)); + /* The longest query length, not the token count, selects the attention band. */ + RAD_ISSUE_N(c, l.op_attn, batch->max_q_len, + brows(m.b_q, T), kv_cache(kg, (int)li), + 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(m.b_attn, T)); + RAD_ISSUE_N(c, l.op_sig, T * m.g.n_head, brows(m.b_gate, T), brows(m.b_gate, T)); + RAD_ISSUE(c, l.op_mul, brows(m.b_attn, T), brows(m.b_gate, T), brows(m.b_attn, T)); + RAD_ISSUE(c, l.op_o, brows(m.b_attn, T), RAD_W(l.w_o), brows(m.b_h, T)); + if (l.op_ar) RAD_ISSUE_N(c, l.op_ar, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE); + RAD_ISSUE(c, l.op_post, brows(m.b_h, T), RAD_W(l.w_post), brows(m.b_h, T)); + RAD_ISSUE(c, l.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T)); + + /* -- feed-forward. */ + RAD_ISSUE(c, l.op_fnorm, brows(m.b_x, T), RAD_W(l.w_fnorm), brows(m.b_h, T)); + RAD_ISSUE(c, l.op_gu, brows(m.b_h, T), RAD_W(l.w_gate_up), brows(m.b_gu, T)); + RAD_ISSUE(c, l.op_act, brows(m.b_gu, T), brows(m.b_ffn, T)); + RAD_ISSUE(c, l.op_down, brows(m.b_ffn, T), RAD_W(l.w_down), brows(m.b_h, T)); + if (l.op_far) RAD_ISSUE_N(c, l.op_far, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE); + RAD_ISSUE(c, l.op_fpost, brows(m.b_h, T), RAD_W(l.w_fpost), brows(m.b_h, T)); + RAD_ISSUE(c, l.op_fadd, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T)); + + /* The drafter reads this layer's completed residual, if it taps it. */ + m.taps.step(c, m.b_x, T, (int64_t)li, m.g.n_embd); + } + + RAD_ISSUE(c, m.op_final_norm, + brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok)); + m.calib.after_step(c, T); + + /* The lm_head runs only on the rows the sampler asked for; a mid-prompt prefill chunk has + * n_out zero and skips it. */ + 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_head), + brows(m.b_logits, batch->n_out)); + if (m.op_cap) + RAD_ISSUE_N(c, m.op_cap, batch->n_out, brows(m.b_logits, batch->n_out), + brows(m.b_logits, batch->n_out)); + } +} + +/* What the plugin says before it declares anything: this family's tower merges 4 patches into a + * row, so an automatic --mm-max-patches rounds to whole merged rows. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + if (MuseTower::present(meta)) out->enc_merge = 4; + /* The drafter denoises `block_size` positions and the anchor row proposes nothing, so the + * draft width is block_size - 1. It is trained for that one block, hence fixed. */ + const long long bs = rad_meta_geti(meta, "draft.block_size", 0); + if (bs > 1) { + out->draft_depth = (int)(bs - 1); + out->draft_depth_fixed = 1; + } + return RAD_OK; +} + +static const RadChatFormat* chat_format(const RadModelMeta*) { + return muse_chat_format(); +} + +} /* namespace museglimmer */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(museglimmer) +/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */ +RAD_ARCH_MULTI_INSTANCE() +RAD_ARCH_PLUGIN(museglimmer, "museglimmer", "", "0.1.0", + "Meta Muse Glimmer 30B dense, bf16 weights and activations, gated attention " + "alternating sliding-window (rotary) and NoPE full-attention layers, Gemma-2 " + "style double norms") +RAD_ARCH_CHAT_FORMAT(museglimmer) +#endif diff --git a/arch/museglimmer_ct/CMakeLists.txt b/arch/museglimmer_ct/CMakeLists.txt new file mode 100644 index 00000000..9c1f3973 --- /dev/null +++ b/arch/museglimmer_ct/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/museglimmer_ct -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(museglimmer_ct LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(museglimmer_ct architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/museglimmer_ct.cpp) diff --git a/arch/museglimmer_ct/museglimmer_ct.cpp b/arch/museglimmer_ct/museglimmer_ct.cpp new file mode 100644 index 00000000..7e7cd981 --- /dev/null +++ b/arch/museglimmer_ct/museglimmer_ct.cpp @@ -0,0 +1,1295 @@ +/* museglimmer_ct.cpp -- Meta's Muse Glimmer 30B under compressed-tensors quantisation. + * + * The same graph arch/museglimmer.cpp declares at the unquantised release, with every trunk + * linear encoding-aware (arch/gemma3's G3Linear shape, gemma4_bf16's G4Linear grids): the weight's + * container encoding picks the op. Plain bf16 rides `gemm_nt`; the symmetric int4/int8 grid the + * museglimmer-30b-w4a8 recipe writes (`codes=i4/i8 group=128 scale=f16`) rides quant_act_i8 + + * gemm_nt_q at w4a8 / w8a8; asymmetric int4/int5 affine per + * [1 x 128] (`codes=u4/u5 zero=u8 group=128 scale=f16`) rides quant_act_i8g + gemm_nt_q at + * w4a8i8_asym / w5a8i8, with the a16 low-latency decode form w4a16_asym / w5a16 under 64 rows; + * int8 a 128 (i8g) rides gemm_nt_q at i8a8. Anything else is refused by name. The tower and its + * adapter stay bf16 whatever the trunk does: the recipes never touch them, and a container that + * quantised tower weights is refused naming the weight. + * + * An IQ8R trunk (data/recipes/museglimmer-30b-iq8r.recipe: int8 codes rotated 128 wide by the + * unnormalised Hadamard, a u8 scale per [1 x 256] under a bf16 scale a row) is a whole-trunk form, + * read from layer 0's q projection before any activation is declared. Its linears are rad_fp8.h's + * LinearFP8 at gemm_nt_q i8a8h, group 256, against int8 activations quantised under the same + * rotation: the two pre-norms write them (rmsnorm_had_quant_i8g), the gated product writes the + * down projection's (gated_had_quant_i8g), and the out projection quantises the gated attention + * output itself (had_quant_act_i8g). q, gate, k and v read one pair. Every trunk linear of such a + * container must be IQ8R; anything else in it is refused naming the weight. + * + * The lm_head is declared at whatever the model holds (weight_codes_dtype): bf16, or a recipe-made + * int8 head (`codes=i8 group=128 scale=bf16`), which `logits_gemm` then reads with the int8 head + * kernel. The drafter reads the same declared head. + */ +#include +#include +#include +#include +#include +#include "../museglimmer/chat.h" + +#include +#include +#include + +namespace museglimmer_ct { + +using namespace rad::arch; + +/* The family's shape, as the bf16 plugin states it: 52 layers, hidden 6656, ffn 19968, vocab + * 202048; sliding_window 2048 with the sliding layers owning the rotary; q and the output gate + * separate checkpoint tensors; four centered norms a layer; a weightless q/k RMS norm with + * qk_scale_factor on the query; a weightless embedding norm; a plain-gain final norm carrying + * output_multiplier before the tanh softcap. + */ + +/* ---- the checkpoint's config. A multimodal model keeps the trunk under `text_config.`; accept + * the bare spelling too, so a text-only GGUF container of the same family reads the same way. */ +namespace { + +double cfg_f(const RadModelMeta* m, const char* key, double dflt) { + return rad_meta_getf(m, (std::string("text_config.") + key).c_str(), + rad_meta_getf(m, key, dflt)); +} +long long cfg_i(const RadModelMeta* m, const char* key, long long dflt) { + return rad_meta_geti(m, (std::string("text_config.") + key).c_str(), + rad_meta_geti(m, key, dflt)); +} +const char* cfg_s(const RadModelMeta* m, const char* key, const char* dflt) { + return rad_meta_gets(m, (std::string("text_config.") + key).c_str(), + rad_meta_gets(m, key, dflt)); +} + +} // namespace + +/* ---- one trunk linear, encoding-aware. The gemma3 G3Linear shape with gemma4_bf16's grids: the + * weight's container encoding picks the op. + * + * plain bf16 -> decl_w + gemm_nt + * symmetric affine -> decl_view codes i4/i8 + scale f16 per [1 x 128] (the + * museglimmer-30b-w4a8 recipe's grid), quant_act_i8 over the bf16 + * activation, gemm_nt_q at w4a8 / w8a8 + * asymmetric affine -> decl_view codes u4/u5 + scale,zero f16 per [1 x 128], quant_act_i8g + * over the bf16 activation, gemm_nt_q at w4a8i8_asym / w5a8i8; up to + * kA4Split rows the input is cast to f16 for w4a16_asym / w5a16 (the + * decode band: w4a8i8_asym has only a prefill kernel, which at one row + * does 16 times the matrix work and reads its weight a quarter as fast) + * int8 a 128 (i8g) -> decl_view codes i8 + scale bf16 per [1 x 128], quant_act_i8g, + * gemm_nt_q at i8a8 + * anything else -> refused by name (RAD_E_DTYPE, the formatted encoding) + * + * The name map is made before the weight is queried (Builder::finish() needs the map entry before + * the declaration). A builder with no model behind it (a test, a synthetic tool) answers + * RAD_E_NOTFOUND from rad_weight_encoding, and the weight is read as plain bf16. + * q, gate, k and v quantise the same norm output on the same per-row grid, so with `in_from` set + * the later linear reads that linear's int8 pair and declares no quantiser of its own: one + * dispatch instead of four. An a4 linear writes no pair below its decode band, so an a4 q + * provides none and each of the four keeps its own quantiser. */ +struct MlLinear { + rad_weight w = 0, ws = 0; /* the codes + scale (quantised), or the single bf16 weight */ + rad_op op = 0, op_q = 0; /* the GEMM and, for a quantised form, its activation quantiser */ + rad_buf q8 = 0, s8 = 0; /* the int8 pair (i8 codes + a scale row) the quantiser writes */ + int64_t N = 0, K = 0; + /* true: symmetric i4/i8 codes with an f16 scale per [1 x 128] (the museglimmer-30b-w4a8 + * recipe's grid), gemm_nt_q at w4a8 / w8a8 over a per-row int8 activation. */ + bool quant = false; + bool i8g = false; /* true: int8 codes, bf16 scale per [1 x 128], gemm_nt_q at i8a8 */ + /* true: asymmetric int4/int5 (libquant `codes=u4/u5 zero=u8 group=128 scale=f16`), gemm_nt_q + * at w4a8i8_asym / w5a8i8 over the same per-(row, 128) int8 activation as i8g. */ + bool a4 = false; + bool w5 = false; /* true with a4: the same grid at five bits */ + bool grouped() const { return i8g || a4; } + /* Block-scaled fp8 (fp8_e4m3 codes, a bf16 scale per [128 x 128]) or OCP-MXFP4 (e2m1 codes, an + * e8m0 exponent per [1 x 32]), read by gemm_nt_q at fp8a8 / mxfp4a8 over an E4M3 activation + * pair. These are what NVIDIA's ModelOpt NVFP4 release leaves behind once the recipe imports + * its FP8 projections and makes its NVFP4 MLPs MXFP4. */ + bool fp8b = false; + bool mx = false; + bool fp8_f32 = false; /* block fp8 with an f32 rather than a bf16 weight scale */ + rad_weight wref = 0; /* mx: the e8m0 plane again as the per-row reference operand */ + rad_buf fq = 0, fs = 0; /* the E4M3 activation pair the quantiser writes */ + /* the pair's scales a row: one, or one per 128 columns */ + int64_t scale_w() const { return grouped() ? K / RAD_FP8_BLOCK : 1; } + rad_buf in = 0; /* the bf16 input row `a` given at declare */ + static constexpr int64_t kA4Split = 64; + int64_t a4_split = 0; /* rows up to which op_dec serves; 0: no decode band */ + rad_buf a16 = 0; + rad_op op_a16 = 0, op_dec = 0; + 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 MlLinear* 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 MlLinear::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 MlLinear* in_from) { + N = n_out; K = n_in; in = a; + if (N <= 0 || K <= 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 if (src.size() > 1) RAD_ARCH_TRY(map_concat(b, wn, src, 0)); + RadEncoding enc{}; + const bool known = weight_enc(b, wn, &enc); + 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; + } + + const RadEncPlane* sc = rad_enc_plane(&enc, "scale"); + const RadEncPlane* zp = rad_enc_plane(&enc, "zero"); + const uint32_t cdt = known && enc.n_planes > 0 ? enc.plane[0].dtype : 0; + quant = 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; + i8g = known && linear_is_w8(enc); + a4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 3 && !enc.transform[0] && + (cdt == RAD_U4 || cdt == RAD_U5) && enc.plane[0].block[1] == 1 && + sc && sc->dtype == RAD_F16 && sc->block[0] == 1 && sc->block[1] == RAD_FP8_BLOCK && zp && + zp->dtype == RAD_U8 && zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK; + w5 = a4 && cdt == RAD_U5; + fp8b = known && rad_enc_is(&enc, "affine") && enc.n_planes == 2 && !enc.transform[0] && + cdt == RAD_F8E4M3 && enc.plane[0].block[1] == 1 && + sc && (sc->dtype == RAD_BF16 || sc->dtype == RAD_F32) && + sc->block[0] == RAD_FP8_BLOCK && sc->block[1] == RAD_FP8_BLOCK; + fp8_f32 = fp8b && sc && sc->dtype == RAD_F32; + mx = known && linear_is_mxfp4(enc); + /* Block fp8 and MXFP4 are forms this build does not serve, in any plugin. */ + if (known) + if (const char* gone = linear_retired(enc)) return linear_refuse_retired(base, gone); + + if (fp8b || mx) { + if (N % 16 || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a %s weight takes rows in 16s " + "and K in whole %d-column activation scale groups\n", base, + (long long)N, (long long)K, mx ? "MXFP4" : "block fp8", RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + const char* sn = nm.f("%s.scale", base); + if (mx) { + w = decl_view(b, wn, nullptr, "codes", RAD_FP4E2M1, { N, K }, RAD_ACCESS_PER_TOKEN, + shard, grp, parts, np); + ws = decl_view(b, sn, wn, "scale", RAD_E8M0, { N, K / RAD_MX_GROUP }, + RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + wref = decl_view(b, nm.f("%s.ref", base), wn, "scale", RAD_E8M0, + { N, K / RAD_MX_GROUP }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + if (!w || !ws || !wref) return RAD_E_INVAL; + } else { + w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, RAD_ACCESS_PER_TOKEN, + shard, grp, parts, np); + ws = decl_view(b, sn, wn, "scale", fp8_f32 ? RAD_F32 : RAD_BF16, + { fp8_blocks(N), fp8_blocks(K) }, + RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + if (!w || !ws) return RAD_E_INVAL; + } + if (in_from && in_from->fp8b == fp8b && in_from->mx == mx && in_from->fq && + in_from->K == K) { + fq = in_from->fq; + fs = in_from->fs; + shared_in = true; + } else { + fq = decl_b(b, nm.f("%s.q8", base), RAD_F8E4M3, { g.max_tok, K }); + fs = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK }); + if (!fq || !fs) return RAD_E_INVAL; + /* quant_act_fp8: the E4M3 codes and an f32 scale per (row, 128), which the fp8a8 and + * mxfp4a8 GEMMs read. */ + op_q = rw(b, RAD_OP(b, "quant_act_fp8", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a }, { fq, fs }); + if (!op_q) return RAD_E_INVAL; + } + op = mx ? 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", RAD_MX_GROUP), RAD_STR("dtype", "mxfp4a8")), + RAD_WEIGHTS(w, ws, wref)), + { fq, fs }, { y }) + : 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", RAD_FP8_BLOCK), + RAD_STR("dtype", fp8_f32 ? "fp8a8f32" : "fp8a8")), + RAD_WEIGHTS(w, ws)), + { fq, fs }, { y }); + return op ? RAD_OK : RAD_E_INVAL; + } + + if (quant || i8g || a4) { + if (N % 16 || K % (quant ? 128 : RAD_FP8_BLOCK)) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; it takes rows in 16s and K in " + "whole %d-column activation scale groups\n", base, (long long)N, + (long long)K, quant ? 128 : RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + if (quant) { + w = decl_view(b, wn, nullptr, "codes", cdt, { N, K }, RAD_ACCESS_PER_TOKEN, shard, + grp, parts, np); + ws = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_F16, { N, K / 128 }, + RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + } else if (a4) { + w = decl_view(b, wn, nullptr, "codes", w5 ? RAD_U5 : RAD_U4, { N, K }, + RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, + RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + } else { + w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, RAD_ACCESS_PER_TOKEN, shard, + grp, parts, np); + ws = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, + RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + } + if (!w || !ws) return RAD_E_INVAL; + if (in_from && ((quant && in_from->quant) || + (!quant && in_from->grouped() && !in_from->a4 && !a4 && + in_from->i8g == i8g)) && + 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, quant ? 1 : K / RAD_FP8_BLOCK }); + if (!q8 || !s8) return RAD_E_INVAL; + /* quant_act_i8 for the symmetric grid: row-major codes with ONE f32 scale a row, + * which the w4a8 / w8a8 GEMMs read (docs/OPS.md). quant_act_i8g for the grouped + * grids (a scale per (row, 128)); paired the other way round they produce NaN + * logits. `group` only sizes the optional code sums, which the symmetric grid does + * not take. */ + op_q = rw(b, RAD_OP(b, quant ? "quant_act_i8" : "quant_act_i8g", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K), + RAD_INT("group", quant ? 128 : RAD_FP8_BLOCK), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a }, { q8, s8 }); + if (!op_q) return RAD_E_INVAL; + } + 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", quant ? 128 : RAD_FP8_BLOCK), + RAD_STR("dtype", quant ? (cdt == RAD_I8 ? "w8a8" : "w4a8") + : w5 ? "w5a8i8" : a4 ? "w4a8i8_asym" : "i8a8")), + RAD_WEIGHTS(w, ws)), + { q8, s8 }, { y }); + if (!op) return RAD_E_INVAL; + if (a4) { + a4_split = std::min(kA4Split, g.max_tok); + a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { a4_split, K }); + if (!a16) return RAD_E_INVAL; + op_a16 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("n", K), + RAD_STR("from", g.dtype), RAD_STR("to", "f16")), + RAD_NOWEIGHTS), + { a }, { a16 }); + op_dec = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", w5 ? "w5a16" : "w4a16_asym")), + RAD_WEIGHTS(w, ws)), + { a16 }, { y }); + if (!op_a16 || !op_dec) return RAD_E_INVAL; + } + return RAD_OK; + } + + char en[256]; + rad_enc_format(&enc, en, sizeof en); + /* IQ8R is served only as a whole trunk, decided by layer 0's q projection (declare()). */ + if (known && linear_is_iq8r(enc)) { + fprintf(stderr, "radiance: '%s' is IQ8R (%s) and layer 0's attn_q is not; an IQ8R " + "container stores every trunk linear in it " + "(data/recipes/museglimmer-30b-iq8r.recipe)\n", wn, en); + return RAD_E_DTYPE; + } + fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16, symmetric " + "int4 or int8 a 128 (w4a8 / w8a8), asymmetric int4 or int5 a 128 " + "(w4a8i8_asym / w5a8i8), int8 a 128 (i8a8), block fp8 e4m3 with a bf16 " + "scale a 128x128 (fp8a8) or MXFP4 e2m1 with an e8m0 exponent a 32 " + "(mxfp4a8) -- none matches\n", wn, en); + return RAD_E_DTYPE; +} + +inline void MlLinear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const { + if (quant) { + /* quant_act_i8 takes x, q, scale, asum; `asum` (the per-group row sums asymmetric grids + * subtract) is absent on this symmetric grid and passed as a null tensor, since operands + * are positional. */ + 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 if (fp8b || mx) { + /* quant_act_fp8 takes x, q, scale: an E4M3 pair at group 128. The mx form reads the e8m0 + * plane again as its per-row reference, so the GEMM carries a third weight operand. */ + if (!shared_in) + RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(fq, T), brows(fs, T)); + gemm(c, y, T); + } else if (a4 && T <= a4_split) { + /* the decode band: f16 copy of the input, the skinny kernel; operands as LinearFP8's w4 */ + RAD_ISSUE_N(c, op_a16, T, brows(a, T), brows(a16, T)); + RAD_ISSUE_N(c, op_dec, T, brows(a16, T), RAD_NONE, RAD_W(w), RAD_W(ws), brows(y, T), + RAD_NONE, RAD_NONE); + } else if (grouped()) { + /* quant_act_i8g takes x, q, scale: no optional `asum`. */ + if (!shared_in) + RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T)); + gemm(c, y, T); + } else + RAD_ISSUE(c, op, brows(a, T), RAD_W(w), brows(y, T)); +} + +inline void MlLinear::gemm(RadCtx* c, rad_buf y, int64_t T) const { + if (fp8b || mx) { + /* the caller wrote the E4M3 pair itself (a fused norm + quantiser): issue the GEMM only */ + if (mx) + RAD_ISSUE_N(c, op, T, brows(fq, T), brows(fs, T), RAD_W(w), RAD_W(ws), brows(y, T), + RAD_NONE, RAD_W(wref)); + else + RAD_ISSUE_N(c, op, T, brows(fq, T), brows(fs, T), RAD_W(w), RAD_W(ws), brows(y, T), + RAD_NONE, RAD_NONE); + return; + } + if (a4 && T <= a4_split) { + RAD_ISSUE_N(c, op_a16, T, brows(in, T), brows(a16, T)); + RAD_ISSUE_N(c, op_dec, T, brows(a16, T), RAD_NONE, RAD_W(w), RAD_W(ws), brows(y, T), + RAD_NONE, RAD_NONE); + return; + } + 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 trunk layer. The rope ops exist only where layer_rope_theta says so; the branch is fixed + * per layer by the model. */ +struct Layer { + int full = 0; /* full attention (no window, no rope in this family) */ + int rope = 0; /* carries a rotary (the sliding layers) */ + + rad_weight w_norm = 0, w_post = 0; + rad_weight w_fnorm = 0, w_fpost = 0; + MlLinear lq, lgate, lk, lv, lo, lgu, ldown; + + /* The same seven linears in an IQ8R trunk (Model::iq8r), at gemm_nt_q i8a8h. The pre-norms + * write their int8 pair as rmsnorm_had_quant_i8g where a loaded library declares it (nq_attn, + * nq_ffn; op_norm / op_fnorm stay 0 then), and the gated product writes the down projection's + * as gated_had_quant_i8g (gq_ffn; op_act stays 0). Where they are not declared, the plain norm + * and silu_mul run and the first linear reading each input quantises it (had_quant_act_i8g). */ + LinearFP8 rq, rgate, rk, rv, ro, rgu, rdown; + NormQuantFP8 nq_attn, nq_ffn; + GateQuantFP8 gq_ffn; + + rad_op op_norm = 0, op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0; + rad_op op_kv = 0, op_attn = 0, op_sig = 0, op_mul = 0, op_ar = 0; + rad_op op_post = 0, op_add = 0; + rad_op op_fnorm = 0, op_act = 0, op_far = 0, op_fpost = 0, op_fadd = 0; + + /* The layer's calibration inputs (rad_calib_full.h): -1 where the run does not record it. */ + int cs_in = -1, cs_o = -1, cs_mlp = -1, cs_down = -1; +}; + +struct Model { + Names nm{""}; + Geom g{}; /* the trunk geometry, the rank's shard of it */ + Geom g_rope{}; /* the same, with the sliding layers' rotary base (decl_rope reads theta) */ + float qk_mult = 0; /* qk_scale_factor */ + float post_eps = 0; /* post_norm_eps */ + float out_mult = 0; /* output_multiplier */ + float softcap = 0; /* final_logit_softcapping; 0: none */ + int64_t window = 0; /* sliding_window */ + + rad_kvgroup kv_win = 0, kv_full = 0; + + /* the residual stream and the two vocabulary edges */ + rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0; + rad_buf b_q = 0, b_gate = 0, b_k = 0, b_v = 0, b_attn = 0; + rad_buf b_gu = 0, b_ffn = 0; + + /* An IQ8R trunk: every trunk linear is IQ8R (layer 0's q projection decides), and the three + * linear inputs carry an int8 code pair at one f32 scale per (row, 256) under the 128-wide + * rotation beside their bf16 plane: `a_h` over `b_h` (both pre-norms' output; q, gate, k, v and + * gate/up read it), `a_attn` over `b_attn` (the gated attention output; o_proj), `a_ffn` over + * `b_ffn` (the gated product; down_proj). */ + bool iq8r = false; + ActFP8 a_h{}, a_attn{}, a_ffn{}; + + rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_embed_norm = 0; + rad_op op_final_norm = 0, op_gather = 0, op_logits = 0, op_cap = 0; + + /* ---- media (arch/common/rad_block_museglimmer_vision.h): the vision tower and the scatter of + * its rows, declared only when the container carries a tower and the deployment asked for + * media. The tower is declared last, so its activations share the arena with every buffer + * above. */ + bool media = false; + rad_op op_media_rows = 0; + MuseTower vit{}; + + /* ---- the DFlash drafter (arch/common/rad_block_muse_dflash.h): same wiring as the bf16 + * plugin declares, so a compressed-tensors container carries the drafter the same way. */ + bool have_df = false; + MuseDflash df{}; + MuseDflash::Wire dfw{}; + MuseTaps taps{}; + rad_kvgroup kv_draft = 0; + + std::vector layers; + + /* --calib-dir: the whole Hessian of every linear's input over a --calib-corpus run. */ + CalibFull calib; + int cs_head = -1; +}; + +/* Declare runs once per rank of an instance, on the rank's own thread (spec §1, §9); every + * instance's state is its slot's (rad_build_slot / rad_slot). */ +static Model g_model[MAX_SLOTS]; + +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 || rad_build_slot(ctx) >= MAX_SLOTS) + return RAD_E_INVAL; + + Model& m = g_model[rad_build_slot(ctx)]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + + /* A routed model is not this family. */ + if (meta->n_expert > 0) { + fprintf(stderr, "radiance: museglimmer refuses a checkpoint with %lld experts\n", + (long long)meta->n_expert); + return RAD_E_UNSUPPORTED; + } + + Geom& g = m.g; + Names& nm = m.nm; + + /* ---- the family's own config. Everything that changes the mathematics is required or read + * from the family defaults the reference config class states; a wrong default yields fluent + * wrong text, so nothing here falls back to a "reasonable" value silently. */ + m.qk_mult = (float)cfg_f(meta, "qk_scale_factor", 3.87); + m.post_eps = (float)cfg_f(meta, "post_norm_eps", 1e-8); + m.out_mult = (float)cfg_f(meta, "output_multiplier", 0.19611613513818404); + m.softcap = (float)cfg_f(meta, "final_logit_softcapping", 20.0); + m.window = cfg_i(meta, "sliding_window", 2048); + const double theta_rope = cfg_f(meta, "rope_parameters.rope_theta", + cfg_f(meta, "rope_theta", 0.0)); + if (!(m.qk_mult > 0.0f) || !(m.out_mult > 0.0f) || !(m.post_eps > 0.0f) || m.window <= 0 || + !(theta_rope > 0.0)) { + fprintf(stderr, "radiance: museglimmer: qk_scale_factor %g output_multiplier %g " + "post_norm_eps %g sliding_window %lld rope theta %g are all required\n", + (double)m.qk_mult, (double)m.out_mult, (double)m.post_eps, + (long long)m.window, theta_rope); + return RAD_E_INVAL; + } + if (g.rope_mc) { + fprintf(stderr, "radiance: museglimmer: the trunk has one-component rotary; a container " + "with mrope_section is not this family\n"); + return RAD_E_UNSUPPORTED; + } + + /* The rotary width is the full head: rope_parameters has no partial_rotary_factor and the + * reference rotates all of head_dim. */ + const int64_t n_rot = g.head_dim; + + /* ---- layer kinds. The config ships `layer_types`; where it does not (a GGUF container), the + * interval rule stands in. The two must agree where both exist: the schedule decides which + * layers keep a long context, and a wrong layer still generates fluent text. */ + std::vector full; + const char* kinds = cfg_s(meta, "layer_types", nullptr); + if (kinds && *kinds) + RAD_ARCH_TRY(parse_layer_kinds("museglimmer", kinds, {"full_attention"}, + "sliding_attention", &full)); + const int64_t interval = 4; + if ((int64_t)full.size() < g.n_layer) { + full.assign((size_t)g.n_layer, 0); + for (int64_t l = 0; l < g.n_layer; ++l) full[(size_t)l] = is_full_attention(l, interval); + if (kinds && *kinds) + rad_note(b, "the container's layer_types named %zu layers and the model has %lld; " + "building the full-attention layers by the interval %lld", + full.size() - (size_t)g.n_layer + (size_t)g.n_layer, (long long)g.n_layer, + (long long)interval); + } else { + for (int64_t l = 0; l < g.n_layer; ++l) { + if ((full[(size_t)l] != 0) != is_full_attention(l, interval)) { + fprintf(stderr, "radiance: museglimmer: layer_types makes layer %lld %s and " + "full_attention_interval %lld makes it %s\n", + (long long)l, full[(size_t)l] ? "full" : "sliding", (long long)interval, + is_full_attention(l, interval) ? "full" : "sliding"); + return RAD_E_UNSUPPORTED; + } + } + } + + /* Per-layer rotary: the shipped `layer_rope_theta`, else the family pattern (theta on the + * sliding layers, 0 -- NoPE -- on the full ones). */ + std::vector theta((size_t)g.n_layer, 0.0f); + const char* thetas = cfg_s(meta, "layer_rope_theta", nullptr); + if (thetas && *thetas) { + size_t i = 0; + for_each_token(thetas, [&](const char* t, size_t n) { + if (i >= theta.size()) return false; + char* e = nullptr; + const double v = std::strtod(std::string(t, n).c_str(), &e); + theta[i++] = e == t ? -1.0f : (float)v; + return true; + }); + if (i < theta.size()) { + fprintf(stderr, "radiance: museglimmer: layer_rope_theta names %zu layers and the " + "model has %lld\n", i, (long long)g.n_layer); + return RAD_E_INVAL; + } + } else { + for (int64_t l = 0; l < g.n_layer; ++l) + theta[(size_t)l] = full[(size_t)l] ? 0.0f : (float)theta_rope; + } + for (int64_t l = 0; l < g.n_layer; ++l) { + if (!(theta[(size_t)l] >= 0.0f)) { + fprintf(stderr, "radiance: museglimmer: layer_rope_theta[%lld] is not a number\n", + (long long)l); + return RAD_E_INVAL; + } + } + + /* The rotary scaling is read into the rope Geom, against the sliding layers' own base: the + * extension reaches their rope and leaves the NoPE full layers untouched (they have no rotary + * to scale); the mechanical extension past the trained positions is the no-keys default. */ + m.g_rope = g; + m.g_rope.theta = (float)theta_rope; + RAD_ARCH_TRY(yarn_from(m.g_rope, meta, "", g.head_dim)); + + const int64_t q_dim = g.q_dim(); + const int64_t kv_dim = g.kv_dim(); + + /* ---- two KV groups (spec §7.2): the sliding layers' pool recycles blocks below the window, + * the full layers' does not. A group with no bound layers is a declare error. */ + const uint32_t kvdt = rad_kv_cache_dtype(ctx, RAD_BF16); + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_WINDOW; + sd.dtype = kvdt; + sd.window = m.window; + sd.n_head_kv = g.n_head_kv; + sd.head_dim = g.head_dim; + m.kv_win = rad_decl_kv_group(b, nm.f("kv_sliding"), &sd); + RadKVGroupDecl gd{}; + gd.kind = RAD_KV_FULL; + gd.dtype = kvdt; + gd.n_head_kv = g.n_head_kv; + gd.head_dim = g.head_dim; + m.kv_full = rad_decl_kv_group(b, nm.f("kv_full"), &gd); + g.kv_dtype = rad_dtype_name(kvdt); + if (m.kv_win == 0 || m.kv_full == 0) { + fprintf(stderr, "radiance: museglimmer: a KV group failed to declare\n"); + return RAD_E_INVAL; + } + + /* ---- the trunk's form, read from layer 0's q projection before any activation is declared: + * only an IQ8R trunk's activations carry an int8 code pair. The probe makes the weight's name + * map through that layer's own LinearFP8, so neither linear of layer 0 maps it again. */ + const char* const pre = "model.language_model.layers"; + m.layers.resize((size_t)g.n_layer); + RAD_ARCH_TRY(m.layers[0].rq.probe(b, nm, g, nm.f("blk.0.attn_q"), + { nm.ckpt("%s.0.self_attn.q_proj.weight", pre) })); + { + RadEncoding e0{}; + m.iq8r = weight_enc(b, nm.f("blk.0.attn_q.weight"), &e0) && linear_is_iq8r(e0); + } + if (m.iq8r && (g.n_embd % RAD_I8_GROUP_WIDE || q_dim % RAD_I8_GROUP_WIDE || + g.n_ff % RAD_I8_GROUP_WIDE)) { + fprintf(stderr, "radiance: museglimmer: the IQ8R trunk keeps one scale a %d of K, which " + "does not divide this rank's widths (hidden %lld, attention %lld, " + "feed-forward %lld)\n", RAD_I8_GROUP_WIDE, (long long)g.n_embd, + (long long)q_dim, (long long)g.n_ff); + return RAD_E_UNSUPPORTED; + } + + /* ---- activation buffers, sized at max_tok and shared by every layer; liveness over the + * declared read and write sets fits them in one arena (spec §3.1). */ + 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_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim}); + m.b_gate = decl_b(b, nm.f("attn_gate"),g.act_dtype, {g.max_tok, q_dim}); + m.b_k = decl_b(b, nm.f("attn_k"), g.act_dtype, {g.max_tok, kv_dim}); + m.b_v = decl_b(b, nm.f("attn_v"), g.act_dtype, {g.max_tok, kv_dim}); + m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, 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}); + /* An IQ8R trunk's int8 pairs, one scale per (row, 256). `a_h` is fed by the pre-norms where + * rmsnorm_had_quant_i8g is declared; neither norm absorbs a collective (the all-reduce sits + * before the post norm, and the embedding's before the weightless embedding norm), so the + * all-reduce form is not needed at two ranks. `a_ffn` is fed by gated_had_quant_i8g where it + * is declared. `a_attn` is never fed: the attention output is a sigmoid gate and a multiply + * over separate buffers, and o_proj's own had_quant_act_i8g quantises the product (the gated + * quantiser's per-head rows are head_dim wide, narrower than the 256-column group). No E4M3 + * pair: nothing here reads one. */ + if (m.iq8r) { + m.a_h.x = m.b_h; + RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd, 0, true, false, RAD_I8_GROUP_WIDE)); + m.a_h.q8_fed = m.a_h.q8_rot = rad_op_declared(b, "rmsnorm_had_quant_i8g") != 0; + m.a_attn.x = m.b_attn; + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim, 0, true, false, + RAD_I8_GROUP_WIDE)); + m.a_ffn.x = m.b_ffn; + RAD_ARCH_TRY(m.a_ffn.declare_qs(b, nm, g, "ffn", g.n_ff, 0, true, false, + RAD_I8_GROUP_WIDE)); + m.a_ffn.q8_fed = m.a_ffn.q8_rot = rad_op_declared(b, "gated_had_quant_i8g") != 0; + } + /* The lm_head runs over the sampled rows only (RadBatch::out_ids), not the whole step. */ + 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 drafter's taps, declared before the trunk's layers: the buffer planner takes + * lifetimes in declaration order (see the bf16 plugin's note). */ + if (ctx->max_spec > 0 && m.taps.read(meta, g.n_layer) > 0) { + RAD_ARCH_TRY(m.taps.declare(b, nm, g, g.max_tok, m.b_x, g.act_dtype)); + if (m.taps.n <= 0) { + fprintf(stderr, "radiance: museglimmer: the container carries a drafter whose " + "draft.target_layer_ids name no layer of this %lld-layer trunk\n", + (long long)g.n_layer); + return RAD_E_INVAL; + } + } + + + /* ---- vocabulary edges, both row-sharded. The 30B does not tie its head; the second source + * serves family members that do, first present wins. */ + 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()); + /* A plain RMSNorm with a gain: declared at f32, cast at load, read with wadd 0. */ + m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + m.w_lm_head = 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()); + + 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_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}); + /* The embedding norm, after the vocabulary shard's reduction: a weightless RMS norm at + * rms_norm_eps, in place. Weightless because MuseGlimmerTextNormedEmbedding has no gain. */ + m.op_embed_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_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + + /* The encoder's rows overwrite the lookup before its reduction (as rad_block_vit.h's + * MediaRows): declared only when the tower is served, issued on the passes that carry rows, + * so the reduction counts each row once. */ + m.media = MuseTower::present(meta) && ctx->max_enc_patches > 0; + if (m.media) + m.op_media_rows = 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", g.dtype)), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + + /* ---- calibration: the widest split input bounds the Hessian's width. */ + RAD_ARCH_TRY(m.calib.begin(b, nm, g, ctx, g.n_layer, + std::max({g.n_embd, q_dim * g.world, g.n_ff * g.world}), + std::max({g.n_embd, q_dim * g.world, g.n_ff * g.world}))); + + /* ---- the layers. */ + const int64_t attn_scale_num = 1; /* attention scale stays 1/sqrt(head_dim): the query's + * qk_scale_factor rides the q norm's `mult`. */ + (void)attn_scale_num; + + /* One linear of an IQ8R trunk: its name map (layer 0's q has it from the probe), its encoding + * checked to be IQ8R, then LinearFP8's declaration (codes view i8 [N, K], one "scale,scale.1" + * u8 view at the logical [N, K], gemm_nt_q at i8a8h, group 256, over `a`'s int8 pair; and + * had_quant_act_i8g over `a.x` unless `a` is fed). */ + auto rot_linear = [&](int64_t l, LinearFP8& L, const char* base, + std::initializer_list src, int64_t n_out, int64_t n_in, + int shard, const ActFP8& a, rad_buf y, + std::initializer_list parts) -> int { + if (!L.mapped) RAD_ARCH_TRY(L.probe(b, nm, g, base, src)); + const char* wn = nm.f("%s.weight", base); + RadEncoding e{}; + const bool known = weight_enc(b, wn, &e); + if (!known || !linear_is_iq8r(e)) { + char en[256] = "plain bf16"; + if (known) rad_enc_format(&e, en, sizeof en); + fprintf(stderr, "radiance: '%s' is %s, and this container's trunk is IQ8R (layer 0's " + "attn_q): every trunk linear of an IQ8R container is IQ8R " + "(data/recipes/museglimmer-30b-iq8r.recipe)\n", wn, en); + return RAD_E_DTYPE; + } + return L.declare(b, nm, g, base, n_out, n_in, shard, grp_layer((int)l), src, a, y, 0, + parts); + }; + /* The pre-norms' geometry for NormQuantFP8, which reads `wadd` from it: this family's input + * and pre-feed-forward norms are centered, x_hat * (1 + w), at rms_norm_eps. */ + Geom gn = g; + gn.wadd = 1.0f; + + for (int64_t l = 0; l < g.n_layer; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.full = full[(size_t)l]; + lay.rope = theta[(size_t)l] > 0.0f; + const bool glob = lay.full; + rad_kvgroup kg = glob ? m.kv_full : m.kv_win; + const Geom& gr = lay.rope ? m.g_rope : m.g; + + /* -- weights. Shapes are [out, in]; gemm_nt reads B transposed. The linears are declared + * encoding-aware; the norm gains stay f32 whatever the trunk quantises. q is declared + * first: gate, k and v quantise its same norm output and, on the grouped grids, read its + * int8 pair (MlLinear::in_from). */ + 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_post.weight", l), + nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l))); + 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.weight", l), + nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l))); + + lay.w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + lay.w_post = decl_w(b, nm.f("blk.%d.attn_post.weight", l), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + lay.w_fnorm = decl_w(b, nm.f("blk.%d.ffn_norm.weight", l), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + lay.w_fpost = decl_w(b, nm.f("blk.%d.ffn_post.weight", l), RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + + /* -- ops, in run order except attn_paged, declared before kv_store like every family: the + * two touch disjoint buffers and the block size comes from the resolved kernel. */ + /* The input norm: with an IQ8R trunk fed by its norms, rmsnorm_had_quant_i8g writes the + * bf16 output and its rotated int8 pair in one pass (no residual operand: the residual add + * is the post-normed branch's, not this norm's). */ + if (m.iq8r && m.a_h.q8_fed) + RAD_ARCH_TRY(lay.nq_attn.declare(b, gn, lay.w_norm, m.b_x, m.a_h, g.n_embd)); + else + lay.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", 1.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_norm)), + {m.b_x}, {m.b_h}); + const char* const src_q = nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l); + const char* const src_gate = + nm.ckpt("%s.%lld.self_attn.gate_proj.weight", pre, (long long)l); + const char* const src_k = nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l); + const char* const src_v = nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l); + if (m.iq8r) { + /* q, gate, k and v read one int8 pair of the norm output: the norm's, or q's own + * quantiser's where the norm writes none. The three after q read it as fed. */ + ActFP8 h_shared = m.a_h; + h_shared.q8_fed = h_shared.q8_rot = true; + RAD_ARCH_TRY(rot_linear(l, lay.rq, nm.f("blk.%d.attn_q", (int)l), {src_q}, q_dim, + g.n_embd, RAD_SHARD_ROW, m.a_h, m.b_q, {})); + RAD_ARCH_TRY(rot_linear(l, lay.rgate, nm.f("blk.%d.attn_gate", (int)l), {src_gate}, + q_dim, g.n_embd, RAD_SHARD_ROW, h_shared, m.b_gate, {})); + RAD_ARCH_TRY(rot_linear(l, lay.rk, nm.f("blk.%d.attn_k", (int)l), {src_k}, kv_dim, + g.n_embd, RAD_SHARD_ROW, h_shared, m.b_k, {})); + RAD_ARCH_TRY(rot_linear(l, lay.rv, nm.f("blk.%d.attn_v", (int)l), {src_v}, kv_dim, + g.n_embd, RAD_SHARD_ROW, h_shared, m.b_v, {})); + } else { + /* The linears, declared in run order after the norm that feeds them: q first, so + * gate, k and v quantise its same norm output and, on the grouped grids, read its + * int8 pair (MlLinear::in_from). o and down are cut along K, in whole scale groups. + * Layer 0's q was mapped by the trunk probe. */ + if (l == 0) + RAD_ARCH_TRY(lay.lq.declare(b, nm, g, nm.f("blk.%d.attn_q", (int)l), {}, q_dim, + g.n_embd, RAD_SHARD_ROW, grp_layer((int)l), m.b_h, + m.b_q)); + else + RAD_ARCH_TRY(lay.lq.declare(b, nm, g, nm.f("blk.%d.attn_q", (int)l), {src_q}, + q_dim, g.n_embd, RAD_SHARD_ROW, grp_layer((int)l), + m.b_h, m.b_q)); + RAD_ARCH_TRY(lay.lgate.declare(b, nm, g, nm.f("blk.%d.attn_gate", (int)l), {src_gate}, + q_dim, g.n_embd, RAD_SHARD_ROW, grp_layer((int)l), m.b_h, m.b_gate, + {}, &lay.lq)); + RAD_ARCH_TRY(lay.lk.declare(b, nm, g, nm.f("blk.%d.attn_k", (int)l), {src_k}, + kv_dim, g.n_embd, RAD_SHARD_ROW, grp_layer((int)l), m.b_h, m.b_k, + {}, &lay.lq)); + RAD_ARCH_TRY(lay.lv.declare(b, nm, g, nm.f("blk.%d.attn_v", (int)l), {src_v}, + kv_dim, g.n_embd, RAD_SHARD_ROW, grp_layer((int)l), m.b_h, m.b_v, + {}, &lay.lq)); + } + /* the q/k norms are weightless (no gain operand), the query carrying qk_scale_factor on + * `mult`. Both run in place: a row's scale is computed before the row is written. */ + lay.op_qn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_F64("mult", (double)m.qk_mult), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_q}, {m.b_q}); + lay.op_kn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head_kv), + RAD_INT("n", g.head_dim), RAD_F64("eps", g.eps), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_k}, {m.b_k}); + + if (lay.rope) { + lay.op_rq = rw(b, decl_rope(b, gr, g.max_tok, g.head_dim, g.n_head, 0, n_rot, "neox"), + {m.b_q}, {m.b_q}); + lay.op_rk = rw(b, decl_rope(b, gr, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, "neox"), + {m.b_k}, {m.b_k}); + } + + lay.op_attn = rw(b, rad_decl_op(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), + RAD_INT("head_dim", g.head_dim), RAD_INT("gqa", g.gqa()), + RAD_INT("causal", 1), + RAD_INT("window", glob ? 0 : m.window), + RAD_INT("n_head", g.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), + RAD_INT("max_ctx", g.max_ctx), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {m.b_q}, {m.b_attn}); + + lay.op_kv = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, kg)), + RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {m.b_k, m.b_v}, {}); + + /* out = attn * sigmoid(gate): two ops, as in the gated-attention block. */ + lay.op_sig = rw(b, RAD_OP(b, "sigmoid", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_head), + RAD_INT("n", g.head_dim), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_gate}, {m.b_gate}); + lay.op_mul = rw(b, RAD_OP(b, "mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_attn, m.b_gate}, {m.b_attn}); + const char* const src_o = nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l); + /* IQ8R: o_proj quantises the gated product itself (had_quant_act_i8g into `a_attn`). */ + if (m.iq8r) + RAD_ARCH_TRY(rot_linear(l, lay.ro, nm.f("blk.%d.attn_output", (int)l), {src_o}, + g.n_embd, q_dim, RAD_SHARD_COL, m.a_attn, m.b_h, {})); + else + RAD_ARCH_TRY(lay.lo.declare(b, nm, g, nm.f("blk.%d.attn_output", l), {src_o}, + g.n_embd, q_dim, RAD_SHARD_COL, grp_layer(l), m.b_attn, m.b_h)); + + if (g.world > 1) + lay.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), + {m.b_h}, {m.b_h}); + /* The branch's own norm, at post_norm_eps, before the residual add. */ + lay.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", m.post_eps), RAD_F64("wadd", 1.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_post)), + {m.b_h}, {m.b_h}); + lay.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), + {m.b_x, m.b_h}, {m.b_x}); + + /* ---- the feed-forward, the same double norm. With an IQ8R trunk fed by its norms the + * pre-feed-forward norm writes the int8 pair too, as the input norm does. */ + if (m.iq8r && m.a_h.q8_fed) + RAD_ARCH_TRY(lay.nq_ffn.declare(b, gn, lay.w_fnorm, m.b_x, m.a_h, g.n_embd)); + else + lay.op_fnorm = 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", 1.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_fnorm)), + {m.b_x}, {m.b_h}); + const char* const src_gate_ff = nm.ckpt("%s.%lld.mlp.gate_proj.weight", pre, (long long)l); + const char* const src_up = nm.ckpt("%s.%lld.mlp.up_proj.weight", pre, (long long)l); + const char* const src_down = nm.ckpt("%s.%lld.mlp.down_proj.weight", pre, (long long)l); + if (m.iq8r) { + /* gate|up in the checkpoint's row order, two row parts; then silu(gate) * up. Where + * `a_ffn` is fed, gated_had_quant_i8g writes down_proj's int8 pair, and the bf16 + * product only when the calibration taps read it (down_proj reads codes alone). + * Where it is not, silu_mul writes the product and down_proj quantises it. */ + RAD_ARCH_TRY(rot_linear(l, lay.rgu, nm.f("blk.%d.ffn_gate_up", (int)l), + {src_gate_ff, src_up}, 2 * g.n_ff, g.n_embd, RAD_SHARD_ROW, + m.a_h, m.b_gu, {g.n_ff, g.n_ff})); + if (m.a_ffn.q8_fed) + RAD_ARCH_TRY(lay.gq_ffn.declare(b, g, m.b_gu, m.a_ffn, g.n_ff, "silu", 0, + m.calib.records(l))); + else + lay.op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_gu}, {m.b_ffn}); + RAD_ARCH_TRY(rot_linear(l, lay.rdown, nm.f("blk.%d.ffn_down", (int)l), {src_down}, + g.n_embd, g.n_ff, RAD_SHARD_COL, m.a_ffn, m.b_h, {})); + } else { + RAD_ARCH_TRY(lay.lgu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), + {src_gate_ff, src_up}, + 2 * g.n_ff, g.n_embd, RAD_SHARD_ROW, grp_layer(l), m.b_h, m.b_gu, + {g.n_ff, g.n_ff})); + lay.op_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_ff), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_gu}, {m.b_ffn}); + RAD_ARCH_TRY(lay.ldown.declare(b, nm, g, nm.f("blk.%d.ffn_down", l), {src_down}, + g.n_embd, g.n_ff, RAD_SHARD_COL, grp_layer(l), m.b_ffn, m.b_h)); + } + if (g.world > 1) + lay.op_far = 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), + {m.b_h}, {m.b_h}); + lay.op_fpost = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", m.post_eps), RAD_F64("wadd", 1.0), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_fpost)), + {m.b_h}, {m.b_h}); + lay.op_fadd = 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), + {m.b_x, m.b_h}, {m.b_x}); + + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg)); + + /* -- calibration taps, the same four a dense family records. */ + if (m.calib.records(l)) { + const std::string L = std::string(pre) + "." + std::to_string(l); + lay.cs_in = (int)m.calib.sites.size(); + RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".input", + L + ".self_attn.q_proj," + L + ".self_attn.k_proj," + + L + ".self_attn.v_proj," + L + ".self_attn.gate_proj", + m.b_h, g.n_embd, g.n_embd)); + lay.cs_o = (int)m.calib.sites.size(); + RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".self_attn.o_proj.input", L + ".self_attn.o_proj", + m.b_attn, q_dim, q_dim * g.world)); + lay.cs_mlp = (int)m.calib.sites.size(); + RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".pre_feedforward.input", + L + ".mlp.gate_proj," + L + ".mlp.up_proj", + m.b_h, g.n_embd, g.n_embd)); + lay.cs_down = (int)m.calib.sites.size(); + RAD_ARCH_TRY(m.calib.site(b, g, l, L + ".mlp.down_proj.input", L + ".mlp.down_proj", + m.b_ffn, g.n_ff, g.n_ff * g.world)); + } + } + + /* ---- the head. The final norm is a plain RMSNorm (wadd 0) that also carries the logits' + * pre-scale: its output feeds only the head, so mult here is logits * output_multiplier + * exactly. */ + m.op_final_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", 0.0), + RAD_F64("mult", (double)m.out_mult), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_out_norm)), + {m.b_x}, {m.b_h}); + if (m.calib.on && m.calib.hi == g.n_layer) { + m.cs_head = (int)m.calib.sites.size(); + RAD_ARCH_TRY(m.calib.site(b, g, -1, "lm_head.input", "lm_head", m.b_h, g.n_embd, g.n_embd)); + } + + 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_head)), + {m.b_hout}, {m.b_logits}); + /* cap * tanh(x / cap) over the f32 logits, after the pre-scale. */ + if (m.softcap > 0.0f) { + 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", (double)m.softcap), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {m.b_logits}, {m.b_logits}); + if (!m.op_cap) + rad_note(b, "warning: no kernel serves `logit_softcap` (load libr4d or libavx), so " + "the logits skip %g * tanh(x / %g): greedy output is unchanged, sampled " + "output draws from a sharper distribution", (double)m.softcap, + (double)m.softcap); + } + + /* ---- media: the vision tower, declared last so its activations share the arena with every + * buffer above (the trunk's weights were mapped and declared first). The tower stays bf16 + * whatever the trunk does -- the recipes never touch it -- so a container that quantised a + * tower weight is refused naming the weight. */ + if (m.media) { + const char* tower_srcs[] = { + nm.ckpt("model.vision_tower.patch_embedder.patch_embedding.weight"), + nm.ckpt("model.vision_tower.layers.0.attn.q_proj.weight"), + nm.ckpt("model.vision_tower.layers.0.mlp.fc1.weight"), + nm.ckpt("model.vision_adapter.fc1.weight"), + nm.ckpt("model.vision_projection.weight"), + }; + for (const char* src : tower_srcs) { + RadEncoding te{}; + if (weight_enc(b, src, &te) && + !(rad_enc_is(&te, "plain") && te.n_planes == 1 && te.plane[0].dtype == RAD_BF16)) { + char ten[256]; + rad_enc_format(&te, ten, sizeof ten); + fprintf(stderr, "radiance: '%s' is %s; museglimmer_ct serves the vision tower in " + "bf16 only, like every recipe for this family\n", src, ten); + return RAD_E_DTYPE; + } + } + RAD_ARCH_TRY(m.vit.declare(b, meta, ctx, nm, g.n_embd, (int)g.n_layer)); + } + + /* ---- the DFlash drafter, declared last: its passes run after the whole trunk's, and the + * planner lays lifetimes out in declaration order. */ + if (m.taps.n > 0) { + RAD_ARCH_TRY(declare_muse_dflash(&m.df, &m.dfw, &m.kv_draft, b, nm, meta, ctx, g, m.taps, + (int)g.n_layer, m.w_tok, m.w_lm_head)); + m.have_df = true; + } + + /* ---- notes for --debug-graph. */ + int64_t nfull = 0, nrope = 0; + for (int64_t l = 0; l < g.n_layer; ++l) { + nfull += full[(size_t)l]; + nrope += theta[(size_t)l] > 0.0f; + } + rad_note(b, "rank %d/%d: %lld layers (%lld full attention, %lld sliding over a %lld-token " + "window; %lld with rotary at theta %g), n_head=%lld n_head_kv=%lld head_dim=%lld " + "n_ff=%lld vocab=[%lld,%lld)", + g.rank, g.world, (long long)g.n_layer, (long long)nfull, + (long long)(g.n_layer - nfull), (long long)m.window, (long long)nrope, + theta_rope, (long long)g.n_head, (long long)g.n_head_kv, (long long)g.head_dim, + (long long)g.n_ff, (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab)); + rad_note(b, "centered norms (1 + w): input/pre at eps %g, post at eps %g; the final norm is a " + "plain gain; the embedding and the q/k norms are weightless", (double)g.eps, + (double)m.post_eps); + rad_note(b, "attention scale 1/sqrt(%lld) with the query pre-scaled by qk_scale_factor %g; " + "logits pre-scaled by output_multiplier %g%s%g", + (long long)g.head_dim, (double)m.qk_mult, (double)m.out_mult, + m.softcap > 0.0f ? " and soft-capped at " : "", (double)m.softcap); + if (m.g_rope.theta != g.theta) + rad_note(b, "rotary runs on the sliding layers only (theta %g); the full-attention layers " + "are NoPE", (double)m.g_rope.theta); + if (m.iq8r) + rad_note(b, "IQ8R trunk: every linear gemm_nt_q i8a8h over int8 codes rotated 128 wide, " + "one scale a (row, %d) on both sides; the pre-norms %s, the gated product %s, " + "o_proj quantises its own input; q, gate, k and v read one pair", + RAD_I8_GROUP_WIDE, + m.a_h.q8_fed ? "write the codes (rmsnorm_had_quant_i8g)" + : "are plain (q and gate/up quantise)", + m.a_ffn.q8_fed ? "writes down_proj's codes (gated_had_quant_i8g)" + : "is plain (down_proj quantises)"); + rad_note(b, "logits for at most %lld sampled rows a step (of %lld tokens): gather_rows " + "selects RadBatch::out_ids before the lm_head", (long long)g.max_logit_rows, + (long long)g.max_tok); + + return RAD_OK; +} + +static void step(RadCtx* c, const RadBatch* batch) { + Model& m = g_model[rad_slot(c)]; + + /* An encoder pass runs only the vision tower (RadBatch::enc). */ + if (batch->enc) { + m.vit.step(c, batch); + return; + } + + /* A draft pass runs only the drafter: >0 the query pass on the staged block, <0 the context + * pass that projects and stores K/V for the tokens the trunk just committed. */ + if (batch->draft_pass != 0) { + if (!m.have_df) { + rad_step_fail(c, "this serve stages a draft pass but the container carries no drafter"); + return; + } + if (batch->draft_pass > 0) m.df.step(c, batch); + else m.df.context(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)); + /* The encoder's rows overwrite the lookup before the vocabulary shard's reduction, so the + * reduction counts each row once. */ + if (m.op_media_rows && batch->n_mm_rows > 0) + RAD_ISSUE_N(c, m.op_media_rows, 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)); + /* The vocab shard's reduction; declared only when world > 1, so tp1 is unchanged. */ + 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); + /* The embedding norm, after the reduction: it normalises whole rows. */ + RAD_ISSUE(c, m.op_embed_norm, brows(m.b_x, batch->n_tok), RAD_NONE, brows(m.b_x, batch->n_tok)); + + const int64_t T = batch->n_tok; + for (size_t li = 0; li < m.layers.size(); ++li) { + const Layer& l = m.layers[li]; + const rad_kvgroup kg = l.full ? m.kv_full : m.kv_win; + const RadKVGroupBatch* kvb = kv_batch(batch, kg); + 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; + + /* -- attention. An IQ8R layer issues LinearFP8's ops over the int8 pairs; a linear that + * declared a quantiser (op_q) issues it first, over the pair's bf16 plane. */ + if (l.nq_attn.op) l.nq_attn.step(c, T); + else RAD_ISSUE(c, l.op_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T)); + if (m.iq8r) { + l.rq.step(c, m.a_h, m.b_q, T); + l.rgate.step(c, m.a_h, m.b_gate, T); + l.rk.step(c, m.a_h, m.b_k, T); + l.rv.step(c, m.a_h, m.b_v, T); + } else { + l.lq.step(c, m.b_h, m.b_q, T); + l.lgate.step(c, m.b_h, m.b_gate, T); + l.lk.step(c, m.b_h, m.b_k, T); + l.lv.step(c, m.b_h, m.b_v, T); + } + RAD_ISSUE_N(c, l.op_qn, T * m.g.n_head, brows(m.b_q, T), RAD_NONE, brows(m.b_q, T)); + RAD_ISSUE_N(c, l.op_kn, T * m.g.n_head_kv, brows(m.b_k, T), RAD_NONE, brows(m.b_k, T)); + if (l.rope) { + RAD_ISSUE(c, l.op_rq, brows(m.b_q, T), rope_posmc(m.g, batch, T)); + RAD_ISSUE(c, l.op_rk, brows(m.b_k, T), rope_posmc(m.g, batch, T)); + } + RAD_ISSUE(c, l.op_kv, + brows(m.b_k, T), brows(m.b_v, T), praw(slot, RAD_I32, T), + kv_cache(kg, (int)li)); + /* The longest query length, not the token count, selects the attention band. */ + RAD_ISSUE_N(c, l.op_attn, batch->max_q_len, + brows(m.b_q, T), kv_cache(kg, (int)li), + 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(m.b_attn, T)); + RAD_ISSUE_N(c, l.op_sig, T * m.g.n_head, brows(m.b_gate, T), brows(m.b_gate, T)); + RAD_ISSUE(c, l.op_mul, brows(m.b_attn, T), brows(m.b_gate, T), brows(m.b_attn, T)); + if (m.iq8r) l.ro.step(c, m.a_attn, m.b_h, T); + else l.lo.step(c, m.b_attn, m.b_h, T); + if (l.op_ar) RAD_ISSUE_N(c, l.op_ar, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE); + RAD_ISSUE(c, l.op_post, brows(m.b_h, T), RAD_W(l.w_post), brows(m.b_h, T)); + RAD_ISSUE(c, l.op_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T)); + + /* -- feed-forward. */ + if (l.nq_ffn.op) l.nq_ffn.step(c, T); + else RAD_ISSUE(c, l.op_fnorm, brows(m.b_x, T), RAD_W(l.w_fnorm), brows(m.b_h, T)); + if (m.iq8r) { + l.rgu.step(c, m.a_h, m.b_gu, T); + if (l.gq_ffn.op) l.gq_ffn.step(c, m.b_gu, T); + else RAD_ISSUE(c, l.op_act, brows(m.b_gu, T), brows(m.b_ffn, T)); + l.rdown.step(c, m.a_ffn, m.b_h, T); + } else { + l.lgu.step(c, m.b_h, m.b_gu, T); + RAD_ISSUE(c, l.op_act, brows(m.b_gu, T), brows(m.b_ffn, T)); + l.ldown.step(c, m.b_ffn, m.b_h, T); + } + if (l.op_far) RAD_ISSUE_N(c, l.op_far, T * m.g.n_embd, brows(m.b_h, T), RAD_NONE); + RAD_ISSUE(c, l.op_fpost, brows(m.b_h, T), RAD_W(l.w_fpost), brows(m.b_h, T)); + RAD_ISSUE(c, l.op_fadd, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T)); + + /* The drafter reads this layer's completed residual, if it taps it. */ + m.taps.step(c, m.b_x, T, (int64_t)li, m.g.n_embd); + } + + RAD_ISSUE(c, m.op_final_norm, + brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok)); + m.calib.after_step(c, T); + + /* The lm_head runs only on the rows the sampler asked for; a mid-prompt prefill chunk has + * n_out zero and skips it. */ + 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_head), + brows(m.b_logits, batch->n_out)); + if (m.op_cap) + RAD_ISSUE_N(c, m.op_cap, batch->n_out, brows(m.b_logits, batch->n_out), + brows(m.b_logits, batch->n_out)); + } +} + +/* What the plugin says before it declares anything: this family's tower merges 4 patches into a + * row, so an automatic --mm-max-patches rounds to whole merged rows. */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + if (MuseTower::present(meta)) out->enc_merge = 4; + /* The drafter denoises `block_size` positions, the anchor row proposes nothing. */ + const long long bs = rad_meta_geti(meta, "draft.block_size", 0); + if (bs > 1) { + out->draft_depth = (int)(bs - 1); + out->draft_depth_fixed = 1; + } + return RAD_OK; +} + +static const RadChatFormat* chat_format(const RadModelMeta*) { + return museglimmer::muse_chat_format(); +} + +} /* namespace museglimmer_ct */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(museglimmer_ct) +/* Every per-instance state above is indexed by slot (rad_build_slot / rad_slot). */ +RAD_ARCH_MULTI_INSTANCE() +RAD_ARCH_PLUGIN(museglimmer_ct, "museglimmer", "compressed-tensors", "0.1.0", + "Meta Muse Glimmer 30B dense under compressed-tensors: encoding-aware trunk " + "linears (plain bf16, asymmetric int4/int5 a 128, int8 a 128, or an IQ8R trunk: " + "rotated int8 a 256), gated attention " + "alternating sliding-window (rotary) and NoPE full-attention layers, Gemma-2 " + "style double norms, a bf16 vision tower") +RAD_ARCH_CHAT_FORMAT(museglimmer_ct) +#endif diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 0e8790c3..3eddc797 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1550,8 +1550,8 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { return RAD_E_INVAL; } /* References: a template with both of its slots, an item with one transcript before its one - * clip, and the clips' geometry; read whole by one branch's prompt (an unconditional branch - * would need references of its own). */ + * clip, and the clips' geometry. Two branches may repeat the same reference prompt at + * guidance 1; reference CFG would need a separate unconditional frame map and is refused. */ if (d->tmpl_ref) { auto once = [](const char* t, const char* k) { const char* a = t ? std::strstr(t, k) : nullptr; @@ -1566,16 +1566,36 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { "{input} once each, and ref_item {text} before its one {audio}", nm); return RAD_E_INVAL; } - if (d->branches != 1 || !d->prompt_whole || d->ref_rate <= 0 || d->ref_hop <= 0 || - d->ref_max <= 0 || d->ref_max_samples < d->ref_hop) { - err(RAD_E_INVAL, "declare_audio_generator '%s': references are read by a model of one " - "branch from whole prompts, clips at a rate (%lld Hz) in frames of " + if (!d->prompt_whole || d->ref_rate <= 0 || d->ref_hop <= 0 || + d->ref_max <= 0 || d->ref_max_samples < d->ref_hop || + (d->branches != 1 && (!d->neg_tmpl || d->default_cfg != 1.0 || + std::strstr(d->neg_tmpl, "{references}")))) { + err(RAD_E_INVAL, "declare_audio_generator '%s': references need whole prompts and " + "guidance 1 (two branches need a plain negative template); clips at " + "a rate (%lld Hz) in frames of " "%lld samples, at most %d of them and %lld samples a request", nm, (long long)d->ref_rate, (long long)d->ref_hop, (int)d->ref_max, (long long)d->ref_max_samples); return RAD_E_INVAL; } } + if (d->tmpl_ref_instruct || d->neg_tmpl_ref) { + auto once = [](const char* t, const char* key) { + const char* p = t ? std::strstr(t, key) : nullptr; + return p && !std::strstr(p + 1, key); + }; + if (!d->tmpl_ref || !d->tmpl_ref_instruct || !d->neg_tmpl_ref || d->branches == 1 || + !once(d->tmpl_ref_instruct, "{references}") || + !once(d->tmpl_ref_instruct, "{input}") || + !once(d->tmpl_ref_instruct, "{instructions}") || + !once(d->neg_tmpl_ref, "{references}") || !once(d->neg_tmpl_ref, "{input}") || + std::strstr(d->neg_tmpl_ref, "{instructions}")) { + err(RAD_E_INVAL, "declare_audio_generator '%s': reference direction needs paired " + "conditional/reference-only templates with one references/input " + "slot each and instructions only in the conditional template", nm); + return RAD_E_INVAL; + } + } if (d->branches != 0 && d->branches != 1 && d->branches != 2) { err(RAD_E_INVAL, "declare_audio_generator '%s': branches is %d; a request runs 1 sequence " "or 2 (0 means 2)", nm, (int)d->branches); @@ -1669,6 +1689,8 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { prog_.agen_str.tmpl_plain = d->tmpl_plain ? d->tmpl_plain : ""; prog_.agen_str.neg_tmpl = d->neg_tmpl ? d->neg_tmpl : ""; prog_.agen_str.tmpl_ref = d->tmpl_ref ? d->tmpl_ref : ""; + prog_.agen_str.tmpl_ref_instruct = d->tmpl_ref_instruct ? d->tmpl_ref_instruct : ""; + prog_.agen_str.neg_tmpl_ref = d->neg_tmpl_ref ? d->neg_tmpl_ref : ""; prog_.agen_str.ref_item = d->tmpl_ref && d->ref_item ? d->ref_item : ""; prog_.audio_gen = *d; /* As for the image generator: the Program is moved after declare; strings live in agen_str. */ @@ -1677,6 +1699,8 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { prog_.audio_gen.tmpl_plain = nullptr; prog_.audio_gen.neg_tmpl = nullptr; prog_.audio_gen.tmpl_ref = nullptr; + prog_.audio_gen.tmpl_ref_instruct = nullptr; + prog_.audio_gen.neg_tmpl_ref = nullptr; prog_.audio_gen.ref_item = nullptr; /* Without references the clips' geometry is nothing: the driver stages none. */ if (!d->tmpl_ref) { diff --git a/core/config.cpp b/core/config.cpp index 8f609d7a..55ce8c58 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -76,6 +76,9 @@ static const Flag g_flags[] = { "of the chunk step's time, auto:SHARE in SHARE of it (0-4];\n" "0 lets every step carry a chunk; served default auto:1\n" "(0 under --deterministic, KL mode, generators)" }, + { "--mixed-step-target-ms", "N", "soft duration target in milliseconds for a mixed prefill/decode\n" + "step. The scheduler learns an aggregate prefill cap from\n" + "completed mixed steps; 0 (default) is off" }, { "--preempt-wait-ms", "N", "how long a preempted prefill may wait for the whole-\n" "recompute gate before reclaiming cache blocks and\n" "preempting the lowest-priority running request; 0\n" @@ -336,6 +339,25 @@ static const Flag g_flags[] = { { "--kld-lora-sources", "PREFIX", "--kld-lora only for documents whose source starts with PREFIX; the\n" " rest run as the base, in the same steps (a mixed batch)" }, + { "--diagnose", "DIR", "instead of serving, run a fixed workload on this engine and write\n" + " diagnose.json and diagnose.md to DIR: decode by prompt category,\n" + " a concurrency sweep, a prefill sweep with decode at each depth and\n" + " a prompt arriving into running streams -- step times, tokens a\n" + " step, draft acceptance, TTFT, emission intervals, jitter. Prompts\n" + " are salted so the prefix cache serves none of them" }, + { "--diagnose-tokens", "N", "tokens a --diagnose decode stream generates (default 256)" }, + { "--diagnose-runs", "N", "measured runs of every --diagnose point, after one unmeasured (default 3)" }, + { "--diagnose-concurrency", "LIST", "stream counts of the concurrency sweep, comma-separated (default\n" + " 1,2,4,8; counts above --max-num-seqs are skipped and reported)" }, + { "--diagnose-prefill", "LIST", "prompt lengths of the prefill sweep in tokens, comma-separated\n" + " (default 1024,4096,16384,65536; lengths the context cannot hold\n" + " are skipped and reported)" }, + { "--diagnose-corpus", "FILE", "JSONL of category prompts, one {\"category\", \"messages\" or \"prompt\",\n" + " \"max_tokens\"?} a line; default: a built-in set of code, reasoning,\n" + " prose, json, file_edit and summarization prompts" }, + { "--diagnose-baseline", "FILE", "an earlier diagnose.json of the same workload: compare every request's\n" + " tokens with it and fail the run on any difference (parity)" }, + { "--debug-graph", nullptr, "print the entire declared graph and exit-quality detail" }, { "--debug-selection", nullptr, "print the selection table" }, { "--debug-placement", nullptr, "print the placement plan" }, @@ -443,6 +465,25 @@ static bool parse_int(const char* flag, const char* v, int64_t lo, int64_t hi, i return true; } +/* A comma-separated list of whole numbers (--diagnose-concurrency, --diagnose-prefill). An empty + * element, a trailing comma or a value out of range refuses the list rather than dropping it. */ +static bool parse_int_list(const char* flag, const char* v, int64_t lo, int64_t hi, + std::vector* out) { + std::vector got; + const char* p = v; + for (;;) { + const char* comma = std::strchr(p, ','); + const std::string one(p, comma ? (size_t)(comma - p) : std::strlen(p)); + int64_t n = 0; + if (!parse_int(flag, one.c_str(), lo, hi, &n)) return false; + got.push_back((int)n); + if (!comma) break; + p = comma + 1; + } + *out = std::move(got); + return true; +} + /* Sampler defaults are checked against the request range (server::sampler_value_ok) at startup; * an out-of-range default would 400 every request that omits the field. */ static bool sampler_num(const char* flag, const char* field, const char* v, double* out) { @@ -589,6 +630,7 @@ int config_parse(int argc, char** argv, Config* c) { } else if (!parse_int(a.c_str(), v, 0, 64, &c->prefill_interleave)) return RAD_E_INVAL; } + else if (S("--mixed-step-target-ms")) { if (!num(0, 60000, &c->mixed_step_target_ms)) return RAD_E_INVAL; } else if (S("--preempt-wait-ms")) { if (!num(0, INT64_MAX, &c->preempt_wait_ms)) return RAD_E_INVAL; } else if (S("--max-num-seqs")) { if (!num(1, INT64_MAX, &c->max_seqs)) return RAD_E_INVAL; } else if (S("--max-model-len")) { if (!num(0, INT64_MAX, &c->max_ctx)) return RAD_E_INVAL; } @@ -1090,6 +1132,29 @@ int config_parse(int argc, char** argv, Config* c) { c->calib_layer_hi = hi; } else if (S("--kld-out")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_out = v; } + else if (S("--diagnose")) { if (!(v = need(i))) return RAD_E_INVAL; c->diagnose = v; } + else if (S("--diagnose-tokens")) { + if (!(v = need(i))) return RAD_E_INVAL; + int64_t n = 0; + if (!parse_int(a.c_str(), v, 2, 1 << 20, &n)) return RAD_E_INVAL; + c->diagnose_tokens = (int)n; + } + else if (S("--diagnose-runs")) { + if (!(v = need(i))) return RAD_E_INVAL; + int64_t n = 0; + if (!parse_int(a.c_str(), v, 1, 100, &n)) return RAD_E_INVAL; + c->diagnose_runs = (int)n; + } + else if (S("--diagnose-concurrency")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!parse_int_list(a.c_str(), v, 1, 4096, &c->diagnose_concurrency)) return RAD_E_INVAL; + } + else if (S("--diagnose-prefill")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!parse_int_list(a.c_str(), v, 16, 1 << 24, &c->diagnose_prefill)) return RAD_E_INVAL; + } + else if (S("--diagnose-corpus")) { if (!(v = need(i))) return RAD_E_INVAL; c->diagnose_corpus = v; } + else if (S("--diagnose-baseline")) { if (!(v = need(i))) return RAD_E_INVAL; c->diagnose_baseline = v; } else if (S("--kld-lora")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_lora = v; } else if (S("--kld-lora-sources")) { if (!(v = need(i))) return RAD_E_INVAL; c->kld_lora_sources = v; } else if (S("--debug-graph")) { c->debug_graph = true; c->debug_selection = true; } @@ -1219,6 +1284,19 @@ int config_parse(int argc, char** argv, Config* c) { return RAD_E_INVAL; } + /* ONE MODE A RUN. Each replaces serving with its own driver, so two given together would have + * to pick one silently; --debug-graph returns before either runs. */ + if (!c->diagnose_mode() && (!c->diagnose_corpus.empty() || !c->diagnose_baseline.empty())) { + RAD_ERR("--diagnose-corpus and --diagnose-baseline belong to the --diagnose workload; give " + "--diagnose DIR as well"); + return RAD_E_INVAL; + } + if (c->diagnose_mode() && (c->kld() || c->calib() || c->debug_graph)) { + RAD_ERR("--diagnose runs its own workload; it cannot be combined with --kld-record, --kld-ref, " + "--calib-corpus or --debug-graph"); + return RAD_E_INVAL; + } + /* Runtime LoRA: the slot flags need slots, the named adapters must fit them, and KL mode's * adapter is one of them. */ { @@ -1352,6 +1430,8 @@ const ShowRow kShow[] = { return c.prefill_interleave > 0 ? num(c.prefill_interleave) : c.prefill_interleave < 0 ? "auto:" + std::to_string(c.prefill_interleave_share) : std::string("off"); } }, + { "--mixed-step-target-ms", [](const Config& c) { + return c.mixed_step_target_ms > 0 ? num(c.mixed_step_target_ms) : std::string("off"); } }, { "--preempt-wait-ms", [](const Config& c) { return num(c.preempt_wait_ms); } }, { "--max-num-seqs", [](const Config& c) { return num(c.max_seqs); } }, { "--max-model-len", [](const Config& c) { @@ -1502,6 +1582,19 @@ const ShowRow kShow[] = { { "--kld-out", [](const Config& c) { return or_none(c.kld_out, "none"); } }, { "--kld-lora", [](const Config& c) { return or_none(c.kld_lora, "none (the base)"); } }, { "--kld-lora-sources", [](const Config& c) { return or_none(c.kld_lora_sources, "every document"); } }, + { "--diagnose", [](const Config& c) { return or_none(c.diagnose, "off (serve)"); } }, + { "--diagnose-tokens", [](const Config& c) { return num(c.diagnose_tokens); } }, + { "--diagnose-runs", [](const Config& c) { return num(c.diagnose_runs); } }, + { "--diagnose-concurrency", [](const Config& c) { + std::string s; + for (int n : c.diagnose_concurrency) s += (s.empty() ? "" : ",") + num(n); + return s; } }, + { "--diagnose-prefill", [](const Config& c) { + std::string s; + for (int n : c.diagnose_prefill) s += (s.empty() ? "" : ",") + num(n); + return s; } }, + { "--diagnose-corpus", [](const Config& c) { return or_none(c.diagnose_corpus, "the built-in set"); } }, + { "--diagnose-baseline", [](const Config& c) { return or_none(c.diagnose_baseline, "none"); } }, { "--debug-graph", [](const Config& c) { return onoff(c.debug_graph); } }, { "--debug-selection", [](const Config& c) { return onoff(c.debug_selection); } }, { "--debug-placement", [](const Config& c) { return onoff(c.debug_placement); } }, diff --git a/core/device/aql.cpp b/core/device/aql.cpp index 6cda9261..dba45d63 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -943,6 +943,36 @@ void report_running(int card) { } } +int64_t stuck_ms(); + +std::atomic g_stuck_watch{false}; + +/* Started by a stall verdict, at most one at a time: ends the process once the verdict has stood + * for dev_stuck_exit_ms (`scheduler.stuck-exit`; 0 never), and ends itself when the queues move + * again. Its own thread, because the threads that noticed the stall are the ones parked in the + * wait. Without the exit a hung device left the process up for good: /health answered 503, a + * SIGTERM could not drain a thread blocked in the driver, and a restart policy had nothing to + * act on. */ +void stuck_watch() { + for (;;) { + std::this_thread::sleep_for(std::chrono::seconds(1)); + const int64_t ms = stuck_ms(); + const int64_t limit = rad::dev_stuck_exit_ms.load(std::memory_order_relaxed); + if (limit > 0 && ms >= limit) { + dump_queues("the device"); + fatal("the device has advanced nothing for %lld s (the queue dumps above name the " + "packets it is stuck on); exiting so a restart can bring the server back", + (long long)(ms / 1000)); + } + if (ms > 0) continue; + g_stuck_watch.store(false, std::memory_order_release); + /* A verdict that landed between the read above and the store has no watcher yet. */ + if (!g_stuck_at.load(std::memory_order_acquire) || + g_stuck_watch.exchange(true, std::memory_order_acq_rel)) + return; + } +} + /* Stall detector for a spin loop. tick() reads the clock every 64k iterations, a few thousand * times a second at most. * @@ -980,7 +1010,11 @@ struct Stall { dump_queues(where); RAD_ERR("device: nothing has advanced in the %u s since: the GPU is not running the " "packet named above -- a hung kernel, or a queue the driver evicted and could " - "not restore (amdgpu cwsr_enable=0 is one cause)", kStallMs / 1000); + "not restore (amdgpu cwsr_enable=0 is one cause). The process exits once this " + "has stood for scheduler.stuck-exit (%lld s; 0 never)", kStallMs / 1000, + (long long)(rad::dev_stuck_exit_ms.load(std::memory_order_relaxed) / 1000)); + if (!g_stuck_watch.exchange(true, std::memory_order_acq_rel)) + std::thread(stuck_watch).detach(); return; } sampled = true; diff --git a/core/device/device.h b/core/device/device.h index 1bf5d770..0d9f9108 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -12,6 +12,7 @@ #include "rad_abi.h" #include "rad_device.h" +#include #include #include #include @@ -447,6 +448,12 @@ std::string dev_dma_lane(int device); * tell. */ int64_t dev_stuck_ms(); +/* How long the device may be stuck (dev_stuck_ms) before the backend ends the process, in ms; 0 + * never. Set from `scheduler.stuck-exit` before serving; a backend that can tell reads it when a + * stall is standing. A device that has advanced nothing for a minute is not coming back: the + * reported hangs stood for hours, and a stall that clears does so within seconds. */ +extern std::atomic dev_stuck_exit_ms; + /* Longest run of dispatches a played tape leaves unordered. Of any kTapeOverlapRun + 1 * consecutive packets on a queue one carries the barrier bit, so a launched packet still proves * that everything more than that many packets earlier has completed. Argument slots and tape diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index 5941bc63..396e4de0 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -874,6 +874,7 @@ std::string dev_pci_address(int device) { if (!dev()->pci_address) return std::string(); return dev_string(64, [&](char* b, int n) { return dev()->pci_address(device, b, n); }); } +std::atomic dev_stuck_exit_ms{60000}; int64_t dev_stuck_ms() { const auto f = dev()->stuck_ms; return f ? f() : 0; diff --git a/core/diag/diag.h b/core/diag/diag.h index 922a4228..c6c34881 100644 --- a/core/diag/diag.h +++ b/core/diag/diag.h @@ -126,6 +126,22 @@ struct Facts { * process reads them only for its own cards. Null reads them for every card. */ Facts collect(const std::string& root, const std::vector* managed = nullptr); +/* A CARD'S STATE AT ONE MOMENT, for --diagnose to read before and after each run: a run that + * starts hotter, or under a different performance level, than the one it is compared with is + * measuring a different card. Read under the same root as collect(); unreadable fields stay unknown. + * The power-management files are answered by the SMU under its lock, so this is read between + * runs, never during one. */ +struct CardSample { + std::string bdf; + int64_t edge_mc = -1, junction_mc = -1, mem_mc = -1; /* hwmon temperatures, millidegrees C */ + int64_t power_uw = -1; /* power1_average, else power1_input */ + std::string perf_level; /* power_dpm_force_performance_level: auto, high, profile_peak, ... */ + std::string sclk_cur, mclk_cur; /* the DPM level marked current, as the driver lists it */ + int busy_percent = -1; +}; + +std::vector sample_cards(const std::string& root, const std::vector& bdfs); + /* Fills what only a system call answers for the live process: the memlock limit and whether * io_uring is allowed (a container's seccomp profile may refuse it). */ void probe_process(HostFacts* h); diff --git a/core/diag/diagnose.cpp b/core/diag/diagnose.cpp new file mode 100644 index 00000000..6ce6c7cc --- /dev/null +++ b/core/diag/diagnose.cpp @@ -0,0 +1,1265 @@ +/* diagnose.cpp -- see diag/diagnose.h. */ +#include "diagnose.h" + +#include "diag/diag.h" + +#include "rad_runtime.h" + +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace diag { + +/* ================================================================== the ring */ + +void StepRing::reset(size_t capacity) { + buf_.assign(capacity, StepRecord{}); + n_ = 0; +} + +void StepRing::push(const StepRecord& r) noexcept { + if (buf_.empty()) return; + buf_[(size_t)(n_ % buf_.size())] = r; + ++n_; +} + +uint64_t StepRing::copy_since(uint64_t from, std::vector* out) const { + if (buf_.empty() || from >= n_) return 0; + const uint64_t oldest = n_ > buf_.size() ? n_ - buf_.size() : 0; + const uint64_t lost = from < oldest ? oldest - from : 0; + for (uint64_t s = std::max(from, oldest); s < n_; ++s) out->push_back(buf_[(size_t)(s % buf_.size())]); + return lost; +} + +/* ================================================================== statistics */ + +/* Nearest rank: the smallest sample with at least p of the samples at or below it. No + * interpolation, so every reported value is one that was measured. */ +static size_t nearest_rank(size_t n, double p) { + const size_t k = (size_t)std::ceil(p * (double)n); + return k == 0 ? 0 : std::min(k - 1, n - 1); +} + +Quantiles quantiles(std::vector v) { + Quantiles q; + q.n = (int64_t)v.size(); + if (v.empty()) return q; + std::sort(v.begin(), v.end()); + auto at = [&](double p) { return v[nearest_rank(v.size(), p)]; }; + q.min = v.front(); + q.max = v.back(); + q.p50 = at(0.50); + q.p90 = at(0.90); + q.p99 = at(0.99); + q.mean = std::accumulate(v.begin(), v.end(), 0.0) / (double)v.size(); + return q; +} + +json to_json(const Quantiles& q) { + json j; + j["n"] = q.n; + if (q.n == 0) { + for (const char* k : { "min", "p50", "p90", "p99", "max", "mean" }) j[k] = nullptr; + return j; + } + auto r = [](double x) { return std::round(x * 1000.0) / 1000.0; }; + j["min"] = r(q.min); + j["p50"] = r(q.p50); + j["p90"] = r(q.p90); + j["p99"] = r(q.p99); + j["max"] = r(q.max); + j["mean"] = r(q.mean); + return j; +} + +namespace { + +double round3(double x) { return std::round(x * 1000.0) / 1000.0; } + +/* A ratio that has no denominator is not a number to report. */ +json ratio(double num, double den) { + if (den <= 0) return nullptr; + return round3(num / den); +} + +/* The spread of a set of durations, as a coefficient of variation: the standard deviation over + * the mean. Unitless, so a step that got faster and steadier and one that got faster and as + * uneven can be told apart. */ +json coeff_var(const std::vector& v) { + if (v.size() < 2) return nullptr; + const double m = std::accumulate(v.begin(), v.end(), 0.0) / (double)v.size(); + if (m <= 0) return nullptr; + double ss = 0; + for (double x : v) ss += (x - m) * (x - m); + return round3(std::sqrt(ss / (double)(v.size() - 1)) / m); +} + +std::string num(const json& v, const char* unit = "") { + if (v.is_null()) return "–"; + if (v.is_string()) return v.get() + unit; + if (v.is_boolean()) return v.get() ? "yes" : "no"; + char b[64]; + if (v.is_number_integer()) std::snprintf(b, sizeof b, "%lld%s", (long long)v.get(), unit); + else std::snprintf(b, sizeof b, "%.3g%s", v.get(), unit); + return b; +} + +/* Two-proportion z for k1/n1 against k0/n0, negative when the first is lower; NaN without data. */ +double drop_z(int64_t n1, int64_t k1, int64_t n0, int64_t k0) { + if (n1 <= 0 || n0 <= 0) return std::nan(""); + const double p1 = (double)k1 / (double)n1, p0 = (double)k0 / (double)n0; + const double p = (double)(k1 + k0) / (double)(n1 + n0); + const double se = std::sqrt(p * (1.0 - p) * (1.0 / (double)n1 + 1.0 / (double)n0)); + if (se <= 0) return p1 == p0 ? 0.0 : (p1 < p0 ? -INFINITY : INFINITY); + return (p1 - p0) / se; +} + +/* The regularised incomplete beta function I_x(a, b), by its continued fraction (Lentz). */ +double inc_beta(double x, double a, double b) { + if (x <= 0) return 0; + if (x >= 1) return 1; + if (x > (a + 1) / (a + b + 2)) return 1.0 - inc_beta(1.0 - x, b, a); + const double lbeta = std::lgamma(a + b) - std::lgamma(a) - std::lgamma(b); + const double front = std::exp(std::log(x) * a + std::log(1.0 - x) * b + lbeta) / a; + const double tiny = 1e-300; + double f = 1, c = 1, d = 1 - (a + b) * x / (a + 1); + if (std::fabs(d) < tiny) d = tiny; + d = 1 / d; + f = d; + for (int m = 1; m <= 300; ++m) { + for (int odd = 0; odd < 2; ++odd) { + const double num = odd ? -(a + m) * (a + b + m) * x / ((a + 2 * m) * (a + 2 * m + 1)) + : m * (b - m) * x / ((a + 2 * m - 1) * (a + 2 * m)); + d = 1 + num * d; + if (std::fabs(d) < tiny) d = tiny; + c = 1 + num / c; + if (std::fabs(c) < tiny) c = tiny; + d = 1 / d; + f *= c * d; + } + if (std::fabs(c * d - 1) < 1e-12) break; + } + return front * f; +} + +/* P(T <= t) for Student's t with `df` degrees of freedom. */ +double t_cdf(double t, double df) { + if (std::isinf(t)) return t < 0 ? 0.0 : 1.0; + const double tail = 0.5 * inc_beta(df / (df + t * t), df / 2, 0.5); + return t < 0 ? tail : 1.0 - tail; +} + +/* The one-sided probability of z = -3: the threshold every acceptance test below uses, so a + * request-level t test and a pooled z test call the same thing a drop. */ +constexpr double kDropP = 0.0013498980316301; + +const char* phase_name(int p) { + return p == RAD_PHASE_DECODE ? "decode" : p == RAD_PHASE_PREFILL ? "prefill" : "mixed"; +} + +} /* namespace */ + +json slow_steps(const std::vector& steps, int phase) { + std::vector s; + for (const StepRecord& r : steps) + if (r.phase == phase) s.push_back(&r); + json j; + j["phase"] = phase_name(phase); + j["steps"] = (int64_t)s.size(); + if (s.empty()) { + j["typical"] = nullptr; + j["slowest"] = json::array(); + return j; + } + std::sort(s.begin(), s.end(), [](const StepRecord* a, const StepRecord* b) { return a->ns < b->ns; }); + auto row = [](const StepRecord& r) { + json x; + x["step"] = r.step; + x["ms"] = round3((double)r.ns / 1e6); + x["n_seq"] = r.n_seq; + x["prefill_tok"] = r.prefill_tok; + x["decode_tok"] = r.decode_tok; + return x; + }; + j["typical"] = row(*s[(s.size() - 1) / 2]); + const size_t k = std::min(s.size(), std::max(3, s.size() / 100)); + json slow = json::array(); + for (size_t i = 0; i < k; ++i) slow.push_back(row(*s[s.size() - 1 - i])); + j["slowest"] = slow; + return j; +} + +json pool_draft_positions(const std::vector& runs) { + std::vector reached, taken; + for (const json& r : runs) { + if (!r.contains("counters") || !r["counters"].contains("draft_by_position")) continue; + for (const json& x : r["counters"]["draft_by_position"]) { + const size_t p = (size_t)x.value("position", 0); + if (p < 1) continue; + if (reached.size() < p) { + reached.resize(p, 0); + taken.resize(p, 0); + } + reached[p - 1] += x.value("reached", (int64_t)0); + taken[p - 1] += x.value("accepted_n", (int64_t)0); + } + } + json out = json::array(); + for (size_t p = 0; p < reached.size(); ++p) + out.push_back({ { "position", (int64_t)p + 1 }, { "reached", reached[p] }, { "accepted_n", taken[p] }, + { "accepted", ratio((double)taken[p], (double)reached[p]) } }); + return out; +} + +json phase_report(const PhaseInput& in) { + json j; + j["name"] = in.name; + j["kind"] = in.kind == PhaseKind::Decode ? "decode" : "prefill"; + j["streams"] = in.streams; + j["wall_s"] = round3((double)in.wall_ns / 1e9); + + /* ---- requests: what a client of this phase saw ---- */ + int ok = 0, stopped = 0; + int64_t tokens = 0, drafted = 0, accepted = 0, cached = 0; + std::vector ttft_ms, queue_ms, stream_tps, prefill_tps; + int64_t first_min = INT64_MAX, last_max = INT64_MIN, first_max = INT64_MIN; + for (const RequestTiming& r : in.requests) { + ok += r.ok; + stopped += r.stopped; + cached += r.cached; + tokens += r.tokens; + drafted += r.drafted; + accepted += r.accepted; + if (r.admitted_ns >= 0 && r.first_ns >= 0) { + ttft_ms.push_back((double)(r.first_ns - r.admitted_ns) / 1e6); + if (r.start_ns >= 0) queue_ms.push_back((double)(r.admitted_ns - r.start_ns) / 1e6); + const int32_t computed = r.prompt - r.cached; + if (computed > 0 && r.first_ns > r.admitted_ns) + prefill_tps.push_back((double)computed * 1e9 / (double)(r.first_ns - r.admitted_ns)); + } + if (r.first_ns >= 0 && r.last_ns > r.first_ns && r.tokens > 1) + stream_tps.push_back((double)(r.tokens - 1) * 1e9 / (double)(r.last_ns - r.first_ns)); + if (r.first_ns >= 0) { + first_min = std::min(first_min, r.first_ns); + first_max = std::max(first_max, r.first_ns); + } + if (r.last_ns >= 0) last_max = std::max(last_max, r.last_ns); + } + json req; + req["count"] = (int64_t)in.requests.size(); + req["ok"] = ok; + req["stopped_on_eos"] = stopped; + req["tokens"] = tokens; + /* Prompt tokens the prefix cache served. The workload is salted so this is 0; anything else + * means the phase measured a cache hit, and the driver says so. */ + req["cached_prompt_tokens"] = cached; + { + json outs = json::array(), drafts = json::array(), prompts = json::array(); + for (const RequestTiming& r : in.requests) { + outs.push_back(r.output); + drafts.push_back(json::array({ r.drafted, r.accepted })); + prompts.push_back(r.prompt); + } + req["outputs"] = outs; + /* Prompt tokens a request, so a difference can be read against what its prefill took: + * a path that only long prompts take shows only in long prompts. */ + req["prompt_tokens"] = prompts; + /* [proposed, accepted] a request: the unit the acceptance comparison pairs on. */ + req["drafts"] = drafts; + } + /* TTFT FROM ADMISSION, and the queue wait beside it: the first is the engine's latency, the + * second is how long the scheduler kept the request waiting, and a client sees their sum. */ + req["ttft_ms"] = to_json(quantiles(ttft_ms)); + req["queue_ms"] = to_json(quantiles(queue_ms)); + req["stream_tok_s"] = to_json(quantiles(stream_tps)); + if (in.kind == PhaseKind::Prefill) req["prefill_tok_s"] = to_json(quantiles(prefill_tps)); + /* THE AGGREGATE DECODE RATE: every token after each stream's own first, over the span from the + * earliest first token to the last token. The first tokens are left out because they are the + * prefill's; a stream whose first token came late lowers the rate, as it would for a client. */ + if (in.kind == PhaseKind::Decode && first_max > INT64_MIN && last_max > first_max) { + int64_t after_first = 0; + for (const RequestTiming& r : in.requests) after_first += std::max(r.tokens - 1, 0); + req["aggregate_tok_s"] = round3((double)after_first * 1e9 / (double)(last_max - first_min)); + } else { + req["aggregate_tok_s"] = nullptr; + } + j["requests"] = req; + + /* ---- the engine's own counters over the phase ---- */ + const SchedMetrics& a = in.before; + const SchedMetrics& b = in.after; + const int64_t d_steps = b.steps - a.steps; + const int64_t d_dec = b.steps_decode - a.steps_decode; + json c; + c["steps"] = d_steps; + c["steps_decode"] = d_dec; + c["steps_prefill"] = b.steps_prefill - a.steps_prefill; + c["steps_mixed"] = b.steps_mixed - a.steps_mixed; + c["steps_ahead"] = b.steps_ahead - a.steps_ahead; + c["decode_rows_unspeculated"] = b.decode_rows_unspeculated - a.decode_rows_unspeculated; + c["preemptions"] = b.preemptions - a.preemptions; + c["prefill_tokens"] = b.prefill_tokens - a.prefill_tokens; + c["decode_tokens"] = b.decode_tokens - a.decode_tokens; + c["ms_per_decode_step"] = ratio((double)(b.step_ns_decode - a.step_ns_decode) / 1e6, (double)d_dec); + c["draft_tokens"] = b.draft_tokens - a.draft_tokens; + c["draft_accepted"] = b.draft_accepted - a.draft_accepted; + c["draft_acceptance"] = ratio((double)(b.draft_accepted - a.draft_accepted), + (double)(b.draft_tokens - a.draft_tokens)); + /* The conditional rate at each draft position: of the verifies that reached j, the share that + * took j as well. The pooled rate above hides a single collapsed position. */ + json pos = json::array(); + const int depth = std::min(std::max(a.draft_depth_seen, b.draft_depth_seen), (int)SchedMetrics::RAD_METRICS_MAX_SPEC); + for (int p = 0; p < depth; ++p) { + const int64_t reached = b.draft_pos_reached[p] - a.draft_pos_reached[p]; + json x; + x["position"] = p + 1; + x["reached"] = reached; + x["accepted_n"] = b.draft_pos_accepted[p] - a.draft_pos_accepted[p]; + x["accepted"] = ratio((double)(b.draft_pos_accepted[p] - a.draft_pos_accepted[p]), (double)reached); + pos.push_back(x); + } + c["draft_by_position"] = pos; + j["counters"] = c; + + /* ---- the steps themselves ---- */ + json st; + st["recorded"] = (int64_t)in.steps.size(); + st["lost"] = (int64_t)in.steps_lost; + std::vector dec_ms, gaps_ms, rate; + int64_t dec_tok = 0; + int64_t prev_end = -1; + for (const StepRecord& r : in.steps) { + if (r.phase == RAD_PHASE_DECODE) { + dec_ms.push_back((double)r.ns / 1e6); + dec_tok += r.decode_tok; + } + /* EMISSIONS: a step that committed decode tokens is one burst a stream receives. The + * interval between two is what a client measures as a token gap, plus delivery; it + * includes the host's planning and commit between steps, which step_ns does not. */ + if (r.decode_tok > 0) { + if (prev_end >= 0 && r.end_ns > prev_end) { + const double g = (double)(r.end_ns - prev_end) / 1e6; + gaps_ms.push_back(g); + rate.push_back((double)r.decode_tok / (g / 1e3)); + } + prev_end = r.end_ns; + } + } + st["decode_step_ms"] = to_json(quantiles(dec_ms)); + st["decode_tok_per_step"] = ratio((double)dec_tok, (double)dec_ms.size()); + st["emission_interval_ms"] = to_json(quantiles(gaps_ms)); + /* JITTER, two ways: how uneven the steps are (coefficient of variation of decode step time), + * and how far the slow tail of emission gaps sits from the typical one (p99 over p50). */ + st["jitter_step_cv"] = coeff_var(dec_ms); + { + const Quantiles q = quantiles(gaps_ms); + st["jitter_emission_p99_over_p50"] = q.n && q.p50 > 0 ? json(round3(q.p99 / q.p50)) : json(nullptr); + } + /* THE 1% LOW TOKEN RATE: committed tokens over the emission interval, the slowest 1% of + * emissions. With speculation a burst carries several tokens, so this is a rate per burst, + * not one token's latency. Nearest rank, as quantiles(): floor(p*n) would take the second + * slowest sample at exactly 100 intervals and flatter the slow edge. */ + { + json low; + if (!rate.empty()) { + std::sort(rate.begin(), rate.end()); + low = round3(rate[nearest_rank(rate.size(), 0.01)]); + } + st["tok_s_1pct_low"] = low; + } + st["slow_decode_steps"] = slow_steps(in.steps, RAD_PHASE_DECODE); + if (in.kind == PhaseKind::Prefill) { + std::vector pf; + for (const StepRecord& r : in.steps) + if (r.prefill_tok > 0) pf.push_back((double)r.ns / 1e6); + st["prefill_chunk_ms"] = to_json(quantiles(pf)); + } + j["steps"] = st; + if (!in.cards.is_null()) j["cards"] = in.cards; + return j; +} + +json summarize_runs(const std::vector& runs) { + static const std::vector kPaths = { + "/requests/aggregate_tok_s", "/requests/stream_tok_s/p50", "/requests/ttft_ms/p50", + "/requests/prefill_tok_s/p50", "/counters/ms_per_decode_step", + "/steps/decode_tok_per_step", "/counters/draft_acceptance", + "/steps/emission_interval_ms/p50", "/steps/emission_interval_ms/max", + "/steps/jitter_emission_p99_over_p50", "/steps/jitter_step_cv", "/steps/tok_s_1pct_low", + "/steps/prefill_chunk_ms/p50", + }; + return summarize_paths(runs, kPaths); +} + +json summarize_paths(const std::vector& runs, const std::vector& paths) { + json j; + j["runs"] = (int64_t)runs.size(); + for (const std::string& path : paths) { + const json::json_pointer ptr(path); + std::vector v; + for (const json& r : runs) + if (r.contains(ptr) && r.at(ptr).is_number()) v.push_back(r.at(ptr).get()); + std::string key = path.substr(1); + std::replace(key.begin(), key.end(), '/', '.'); + if (v.empty()) { + j[key] = nullptr; + continue; + } + const Quantiles q = quantiles(v); + /* How far the runs disagree, against the median: null for one run, or a median of 0. */ + const json spread = v.size() >= 2 && q.p50 != 0.0 + ? json(round3((q.max - q.min) / std::fabs(q.p50) * 100.0)) + : json(nullptr); + j[key] = { { "median", round3(q.p50) }, { "min", round3(q.min) }, { "max", round3(q.max) }, + { "spread_pct", spread } }; + } + return j; +} + +json interference_report(const std::vector& steps, int64_t from_ns, int64_t to_ns) { + json j; + j["window_ms"] = to_ns > from_ns ? json(round3((double)(to_ns - from_ns) / 1e6)) : json(nullptr); + std::vector before; + double worst = -1; + int64_t in_window = 0, prev = -1; + for (const StepRecord& r : steps) { + if (r.decode_tok <= 0) continue; + if (prev >= 0 && r.end_ns > prev) { + const double g = (double)(r.end_ns - prev) / 1e6; + if (r.end_ns <= from_ns) before.push_back(g); + else if (prev < to_ns) worst = std::max(worst, g); /* the gap overlaps the window */ + } + if (r.end_ns > from_ns && r.end_ns <= to_ns) ++in_window; + prev = r.end_ns; + } + const Quantiles b = quantiles(before); + j["emissions_in_window"] = in_window; + j["typical_gap_ms"] = b.n ? json(round3(b.p50)) : json(nullptr); + j["longest_gap_ms"] = worst >= 0 ? json(round3(worst)) : json(nullptr); + j["stall_ratio"] = b.n && b.p50 > 0 && worst >= 0 ? json(round3(worst / b.p50)) : json(nullptr); + return j; +} + +/* ================================================================== parity */ + +std::string workload_fingerprint(const json& p) { + /* FNV-1a over the canonical dump: stable across builds, and the parameters are few. */ + const std::string d = p.dump(); + uint64_t h = 1469598103934665603ull; + for (unsigned char c : d) { h ^= c; h *= 1099511628211ull; } + char b[24]; + std::snprintf(b, sizeof b, "%016llx", (unsigned long long)h); + return b; +} + +/* ================================================================== reproducibility */ + +json card_samples_json(const std::vector& samples) { + auto deg = [](int64_t mc) { return mc >= 0 ? json(round3((double)mc / 1000.0)) : json(nullptr); }; + auto str = [](const std::string& v) { return v.empty() ? json(nullptr) : json(v); }; + json a = json::array(); + for (const CardSample& c : samples) + a.push_back({ { "bdf", c.bdf }, { "edge_c", deg(c.edge_mc) }, { "junction_c", deg(c.junction_mc) }, + { "mem_c", deg(c.mem_mc) }, + { "power_w", c.power_uw >= 0 ? json(round3((double)c.power_uw / 1e6)) : json(nullptr) }, + { "perf_level", str(c.perf_level) }, { "sclk", str(c.sclk_cur) }, { "mclk", str(c.mclk_cur) }, + { "busy_percent", c.busy_percent >= 0 ? json(c.busy_percent) : json(nullptr) } }); + return a; +} + +json conditions_report(const Facts& f, const RunFacts& r, const std::vector& findings) { + auto str = [](const std::string& v) { return v.empty() ? json(nullptr) : json(v); }; + auto n = [](int64_t v) { return v >= 0 ? json(v) : json(nullptr); }; + auto watts = [](int64_t uw) { return uw > 0 ? json(round3((double)uw / 1e6)) : json(nullptr); }; + json c; + c["engine"] = { { "version", r.version }, { "device_build", r.device_build }, { "host_backend", r.host_backend }, + { "tp", r.tp }, { "deterministic", r.deterministic }, { "profile_ops", r.profile_ops }, + { "reference_kernels", r.reference_kernels }, { "prefix_cache", r.prefix_cache } }; + const HostFacts& h = f.host; + c["host"] = { { "cpu_model", str(h.cpu_model) }, { "cores", n(h.cores) }, { "threads", n(h.threads) }, + { "kernel", str(h.kernel) }, { "runtime", str(h.runtime) }, + { "cpu_governor", str(h.cpu_governor) }, { "cpu_epp", str(h.cpu_epp) }, + { "cpu_driver", str(h.cpu_driver) }, { "thp_enabled", str(h.thp_enabled) }, + { "iommu", str(h.iommu) }, { "container", str(h.container) } }; + std::vector serving; + for (const CardFacts& k : f.cards) + if (k.rank >= 0) serving.push_back(&k); + std::sort(serving.begin(), serving.end(), [](const CardFacts* a, const CardFacts* b) { return a->rank < b->rank; }); + json cards = json::array(); + for (const CardFacts* k : serving) { + json link = nullptr; + if (!k->chain.empty()) link = link_text(k->chain.back().max_speed, k->chain.back().max_width); + cards.push_back({ { "rank", k->rank }, { "name", str(k->name) }, { "gfx", str(k->gfx) }, + { "pci_device", str(k->pci_device) }, { "sclk", str(k->sclk) }, { "mclk", str(k->mclk) }, + { "power_cap_w", watts(k->power_cap_uw) }, + { "power_cap_default_w", watts(k->power_cap_default_uw) }, + { "voltage_offset", str(k->vddgfx_offset) }, + { "runtime_pm", str(k->runtime_control) }, { "link_max", link } }); + } + c["cards"] = cards; + /* The fingerprint before the findings go in: their text carries numbers read under load. */ + c["fingerprint"] = workload_fingerprint(c); + json fs = json::array(); + for (const Finding& x : findings) { + const char* lv = x.level == Finding::Incompatible ? "incompatible" : x.level == Finding::Warn ? "warn" : "note"; + fs.push_back(json{ { "level", lv }, { "id", x.id }, { "what", x.what }, { "fix", x.fix } }); + } + c["findings"] = fs; + return c; +} + +/* A tree's leaves keyed by their JSON Pointer ("/cards/0/power_cap_w"); an empty array or object + * is a leaf of its own, so a field that became empty still differs. */ +static void flatten_into(const json& v, const std::string& at, json* out) { + if (v.is_object() && !v.empty()) { + for (auto it = v.begin(); it != v.end(); ++it) flatten_into(it.value(), at + "/" + it.key(), out); + } else if (v.is_array() && !v.empty()) { + for (size_t i = 0; i < v.size(); ++i) flatten_into(v[i], at + "/" + std::to_string(i), out); + } else { + (*out)[at] = v; + } +} + +json conditions_differences(const json& now, const json& base) { + json out = json::array(); + auto flat = [](const json& c) { + json k = c; + if (k.is_object()) { + k.erase("findings"); + k.erase("fingerprint"); + } + json leaves = json::object(); + flatten_into(k, "", &leaves); + return leaves; + }; + const json a = flat(now), b = flat(base); + for (auto it = a.begin(); it != a.end(); ++it) { + const json other = b.contains(it.key()) ? b[it.key()] : json(nullptr); + if (other != it.value()) + out.push_back(json{ { "field", it.key() }, { "now", it.value() }, { "baseline", other } }); + } + for (auto it = b.begin(); it != b.end(); ++it) + if (!a.contains(it.key())) + out.push_back(json{ { "field", it.key() }, { "now", nullptr }, { "baseline", it.value() } }); + return out; +} + +json stability_report(const json& rep, double max_spread_pct) { + struct Point { const char* section; const char* key; std::vector metrics; }; + /* A decode point is judged by its step time alone. Its token rate also moves with what was + * written: every run of a point samples its own text, from its own seed behind its own salt, + * so drafts land differently from run to run on a machine that repeats to the microsecond. */ + static const std::vector kDecode = { "counters.ms_per_decode_step" }; + /* A category's own summary pools different prompts, whose rates differ by what they ask for: + * it is judged prompt by prompt (prompts_summary), never as a whole. */ + static const std::vector kPoints = { + { "concurrency", "streams", kDecode }, + { "prefill", "requested_tokens", { "requests.ttft_ms.p50", "requests.prefill_tok_s.p50" } }, + }; + json unstable = json::array(); + int64_t judged = 0; + auto look = [&](const std::string& point, const json& sum, const char* metric) { + if (!sum.is_object() || !sum.contains(metric) || !sum[metric].is_object()) return; + const json& m = sum[metric]; + if (!m.contains("spread_pct") || !m["spread_pct"].is_number()) return; + ++judged; + const double sp = m["spread_pct"].get(); + if (sp > max_spread_pct) + unstable.push_back({ { "point", point }, { "metric", metric }, { "spread_pct", sp }, + { "median", m["median"] }, { "min", m["min"] }, { "max", m["max"] }, + { "runs", sum.value("runs", json()) } }); + }; + if (rep.contains("categories") && rep["categories"].is_array()) + for (const json& c : rep["categories"]) + for (const json& p : c.value("prompts_summary", json::array())) + for (const char* m : kDecode) + look("categories " + c.value("category", std::string("?")) + " #" + p["prompt"].dump(), + p.value("summary", json()), m); + for (const Point& p : kPoints) { + if (!rep.contains(p.section) || !rep[p.section].is_array()) continue; + for (const json& x : rep[p.section]) { + const std::string point = std::string(p.section) + " " + + (x[p.key].is_string() ? x[p.key].get() : x[p.key].dump()); + for (const char* m : p.metrics) look(point, x.value("summary", json()), m); + } + } + if (rep.contains("interference") && rep["interference"].is_object()) + look("interference", rep["interference"].value("summary", json()), "arrival_ttft_ms"); + json j; + j["threshold_pct"] = max_spread_pct; + j["judged"] = judged; + j["unstable"] = unstable; + j["verdict"] = judged == 0 ? "not judged" : unstable.empty() ? "stable" : "UNSTABLE"; + return j; +} + +json thermal_report(const json& rep) { + struct Card { + std::vector start, end; + std::vector levels; + int64_t runs = 0; + }; + std::map cards; + auto temp = [](const json& c) -> double { + for (const char* k : { "junction_c", "edge_c" }) + if (c.contains(k) && c[k].is_number()) return c[k].get(); + return NAN; + }; + auto take = [&](const json& run) { + if (!run.is_object() || !run.contains("cards") || !run["cards"].is_object()) return; + const json& cs = run["cards"]; + for (const char* side : { "start", "end" }) + for (const json& c : cs.value(side, json::array())) { + Card& k = cards[c.value("bdf", std::string("?"))]; + const double t = temp(c); + if (std::isfinite(t)) (std::strcmp(side, "start") == 0 ? k.start : k.end).push_back(t); + if (c.contains("perf_level") && c["perf_level"].is_string()) { + const std::string l = c["perf_level"].get(); + if (std::find(k.levels.begin(), k.levels.end(), l) == k.levels.end()) k.levels.push_back(l); + } + if (std::strcmp(side, "start") == 0) ++k.runs; + } + }; + for (const char* sec : { "categories", "concurrency", "prefill" }) + if (rep.contains(sec) && rep[sec].is_array()) + for (const json& p : rep[sec]) + for (const json& r : p.value("runs", json::array())) take(r); + if (rep.contains("interference") && rep["interference"].is_object()) + for (const json& r : rep["interference"].value("runs", json::array())) take(r.value("phase", json())); + + auto range = [](const std::vector& v) -> json { + if (v.empty()) return nullptr; + const auto mm = std::minmax_element(v.begin(), v.end()); + return { { "min", round3(*mm.first) }, { "max", round3(*mm.second) } }; + }; + json out = json::array(), warnings = json::array(); + for (const auto& [bdf, k] : cards) { + out.push_back({ { "bdf", bdf }, { "runs", k.runs }, { "start_c", range(k.start) }, { "end_c", range(k.end) }, + { "perf_levels", k.levels } }); + if (k.start.size() >= 2) { + const auto mm = std::minmax_element(k.start.begin(), k.start.end()); + if (*mm.second - *mm.first > kMaxStartTempSpreadC) { + char b[256]; + std::snprintf(b, sizeof b, + "card %s started its runs between %.0f and %.0f C: runs began in different thermal " + "states, so their clocks under load may differ", + bdf.c_str(), *mm.first, *mm.second); + warnings.push_back(b); + } + } + if (k.levels.size() > 1) { + std::string l; + for (const auto& x : k.levels) l += (l.empty() ? "" : ", ") + x; + warnings.push_back("card " + bdf + " changed its performance level during the report (" + l + + "): the runs were measured under different clock policies"); + } + } + return { { "cards", out }, { "warnings", warnings } }; +} + +int compare_outputs(const json& now, const json& base, json* out, std::string* why) { + auto fp = [](const json& r) { + return r.contains("workload") ? r["workload"].value("fingerprint", std::string()) : std::string(); + }; + if (fp(now).empty() || fp(now) != fp(base)) { + *why = "the two reports ran different workloads (workload.fingerprint " + fp(now) + " against " + + fp(base) + "), so their prompts differ and their outputs cannot be compared"; + return RAD_E_INVAL; + } + struct Section { const char* name; const char* key; }; + static const Section kSections[] = { { "categories", "category" }, { "concurrency", "streams" }, + { "prefill", "requested_tokens" } }; + int64_t compared = 0, identical = 0; + json differing = json::array(), missing = json::array(), acceptance = json::array(), dropped = json::array(); + for (const Section& sec : kSections) { + const json empty = json::array(); + const json& a = now.contains(sec.name) ? now[sec.name] : empty; + const json& b = base.contains(sec.name) ? base[sec.name] : empty; + auto find = [&](const json& list, const json& key) -> const json* { + for (const json& p : list) + if (p.contains(sec.key) && p[sec.key] == key) return &p; + return nullptr; + }; + auto label = [&](const json& p) { + const json& key = p[sec.key]; + return std::string(sec.name) + " " + (key.is_string() ? key.get() : key.dump()); + }; + for (const json& pa : a) { + const json& key = pa[sec.key]; + const std::string point = label(pa); + const json* pb = find(b, key); + if (!pb) { + missing.push_back(point + ": not in the baseline"); + continue; + } + /* DRAFT ACCEPTANCE BESIDE THE TOKENS. Bit-identical builds accept identically; a build + * that is not shows here first, because the draft head reads the trunk's hidden state + * and an inaccuracy there costs acceptance before it changes an answer. + * + * THE UNIT IS THE REQUEST, NOT THE DRAFT. Drafts within one text are not independent -- + * a stretch of boilerplate is accepted wholesale -- so a test that counts every draft as + * a coin flip takes two texts that differ for any reason for a drop: two runs of the + * same build that diverged a few tokens in did exactly that. The overall rate is tested + * on the requests, paired (the same prompt and seed on both sides), by a one-sided t + * test; a drop is p below that of z = -3. The positions have only pooled counts, so + * their two-proportion z is divided by the square root of the dispersion the requests + * show beyond a binomial one, and a drop is that z below -3. */ + auto pooled = [](const json& p) { + int64_t n = 0, k = 0; + for (const json& r : p.value("runs", json::array())) + if (r.contains("counters")) { + n += r["counters"].value("draft_tokens", (int64_t)0); + k += r["counters"].value("draft_accepted", (int64_t)0); + } + return std::make_pair(n, k); + }; + std::vector diffs; + { + const json& ra = pa.value("runs", json::array()); + const json& rb = (*pb).value("runs", json::array()); + for (size_t r = 0; r < std::min(ra.size(), rb.size()); ++r) { + const json da = ra[r].contains("requests") ? ra[r]["requests"].value("drafts", json::array()) : json::array(); + const json db = rb[r].contains("requests") ? rb[r]["requests"].value("drafts", json::array()) : json::array(); + for (size_t k = 0; k < std::min(da.size(), db.size()); ++k) { + const double n1 = da[k][0].get(), k1 = da[k][1].get(); + const double n0 = db[k][0].get(), k0 = db[k][1].get(); + if (n1 > 0 && n0 > 0) diffs.push_back(k1 / n1 - k0 / n0); + } + } + } + const auto [n1, k1] = pooled(pa); + const auto [n0, k0] = pooled(*pb); + double phi = 1.0; + if (n1 > 0 || n0 > 0) { + json x = { { "point", point }, { "what", "overall" }, + { "now", ratio((double)k1, (double)n1) }, { "baseline", ratio((double)k0, (double)n0) }, + { "n_now", n1 }, { "n_baseline", n0 }, { "requests", (int64_t)diffs.size() } }; + bool drop = false; + if (diffs.size() >= 2) { + const double m = (double)diffs.size(); + const double mean = std::accumulate(diffs.begin(), diffs.end(), 0.0) / m; + double ss = 0; + for (double d : diffs) ss += (d - mean) * (d - mean); + const double se = std::sqrt(ss / (m - 1) / m); + const double t = se > 0 ? mean / se : (mean == 0 ? 0.0 : (mean < 0 ? -INFINITY : INFINITY)); + const double p = t_cdf(t, m - 1); + x["test"] = "paired t over requests"; + x["t"] = std::isfinite(t) ? json(round3(t)) : json(nullptr); + x["p"] = p; + drop = p < kDropP; + /* The requests' spread against a binomial one, for the positions below. */ + if (n1 > 0 && n0 > 0) { + const double pp = (double)(k1 + k0) / (double)(n1 + n0); + const double se_bin = std::sqrt(pp * (1 - pp) * (1.0 / (double)n1 + 1.0 / (double)n0)); + if (se_bin > 0) phi = std::max(1.0, (se / se_bin) * (se / se_bin)); + } + } else { + const double z = drop_z(n1, k1, n0, k0); + x["test"] = "pooled z (fewer than two requests to pair)"; + x["z"] = std::isfinite(z) ? json(round3(z)) : json(nullptr); + drop = std::isfinite(z) && z < -3.0; + } + acceptance.push_back(x); + if (drop) dropped.push_back(x); + } + { + const json pn = pa.value("draft_by_position", json::array()); + const json pbp = (*pb).value("draft_by_position", json::array()); + for (size_t q = 0; q < std::min(pn.size(), pbp.size()); ++q) { + const int64_t a1 = pn[q].value("reached", (int64_t)0), b1 = pn[q].value("accepted_n", (int64_t)0); + const int64_t a0 = pbp[q].value("reached", (int64_t)0), b0 = pbp[q].value("accepted_n", (int64_t)0); + const double z = drop_z(a1, b1, a0, b0) / std::sqrt(phi); + json x = { { "point", point }, { "what", "position " + std::to_string(q + 1) }, + { "now", ratio((double)b1, (double)a1) }, { "baseline", ratio((double)b0, (double)a0) }, + { "n_now", a1 }, { "n_baseline", a0 }, { "test", "pooled z / sqrt(dispersion)" }, + { "dispersion", round3(phi) }, + { "z", std::isfinite(z) ? json(round3(z)) : json(nullptr) } }; + acceptance.push_back(x); + if (std::isfinite(z) && z < -3.0) dropped.push_back(x); + } + } + const json& ra = pa.value("runs", json::array()); + const json& rb = (*pb).value("runs", json::array()); + for (size_t r = 0; r < std::max(ra.size(), rb.size()); ++r) { + if (r >= ra.size() || r >= rb.size()) { + missing.push_back(point + " run " + std::to_string(r + 1) + ": only one side has it"); + continue; + } + const json& oa = ra[r]["requests"].value("outputs", json::array()); + const json& ob = rb[r]["requests"].value("outputs", json::array()); + for (size_t k = 0; k < std::max(oa.size(), ob.size()); ++k) { + if (k >= oa.size() || k >= ob.size()) { + missing.push_back(point + " run " + std::to_string(r + 1) + " request " + + std::to_string(k + 1) + ": only one side has it"); + continue; + } + ++compared; + const json& ta = oa[k]; + const json& tb = ob[k]; + if (ta == tb) { + ++identical; + continue; + } + size_t i = 0; + while (i < ta.size() && i < tb.size() && ta[i] == tb[i]) ++i; + const json pt = ra[r]["requests"].value("prompt_tokens", json::array()); + differing.push_back({ { "point", point }, { "run", (int64_t)r + 1 }, { "request", (int64_t)k + 1 }, + { "prompt_tokens", k < pt.size() ? pt[k] : json(nullptr) }, + { "first_different_token", (int64_t)i }, + { "tokens", (int64_t)ta.size() }, { "tokens_baseline", (int64_t)tb.size() } }); + } + } + } + for (const json& pb : b) + if (!find(a, pb[sec.key])) missing.push_back(label(pb) + ": only in the baseline"); + } + json j; + j["compared"] = compared; + j["identical"] = identical; + j["differing"] = differing; + j["missing"] = missing; + j["acceptance"] = acceptance; + j["acceptance_dropped"] = dropped; + j["verdict"] = compared == 0 ? "nothing compared" + : !differing.empty() ? "DIFFERS" + : !missing.empty() ? "identical where both ran; points missing" + : "identical"; + j["acceptance_verdict"] = dropped.empty() ? "no drop" : "DROPPED"; + /* Not part of either verdict: tokens do not depend on the clocks. It says whether the two + * reports' timings were taken under the same conditions. */ + if (now.contains("conditions") && base.contains("conditions")) + j["conditions"] = conditions_differences(now["conditions"], base["conditions"]); + else + j["conditions"] = "not recorded on both sides"; + *out = j; + return RAD_OK; +} + +/* ================================================================== workload */ + +std::string synthetic_document(int64_t chars, uint32_t salt) { + static const char* const kPara[] = { + "The survey covers the history of the measurement of time, from water clocks and candle " + "marks to escapements, pendulums and the quartz oscillator. Each section names the " + "instrument, the error it removed and the error it introduced in its place.", + "Records from the observatory list the transit of each reference star, the clock reading " + "at the transit, the correction applied and the observer. A missing reading is entered as " + "missing; an interpolated one is marked, because a later reader cannot tell otherwise.", + "The comparison table gives, for every pair of clocks, the drift over a week, the largest " + "single-day deviation and the temperature at which it was observed, so that a drift caused " + "by the room can be separated from one caused by the mechanism.", + "In the appendix the same procedure is repeated with a different reference, and the two " + "series are compared line by line. Where they disagree by more than the stated tolerance " + "the entry is kept, flagged and discussed rather than averaged away.", + }; + std::string s; + s.reserve((size_t)chars + 512); + uint32_t x = salt * 2654435761u + 12345u; + for (int sec = 1; (int64_t)s.size() < chars; ++sec) { + x = x * 1664525u + 1013904223u; + char head[96]; + std::snprintf(head, sizeof head, "\n\nSection %d (series %u, run %u).\n", sec, salt, x % 100000u); + s += head; + s += kPara[(size_t)(sec + salt) % (sizeof kPara / sizeof kPara[0])]; + } + s.resize((size_t)std::max(chars, 0)); + return s; +} + +std::string decode_prompt(int stream) { + static const char* const kTopics[] = { + "the history of printing", "how bridges are inspected", "the water cycle of a river basin", + "the design of a railway timetable", "how a compiler allocates registers", + "the economics of a small harbour", "how glaciers record climate", "the logistics of a city library", + }; + const size_t n = sizeof kTopics / sizeof kTopics[0]; + return std::string("Write a long, detailed essay about ") + kTopics[(size_t)stream % n] + + ". Use several sections with headings, and keep writing until you are asked to stop."; +} + +std::vector builtin_corpus() { + struct P { const char* cat; const char* text; }; + static const P kPrompts[] = { + { "code", "Write a Python module that parses a CSV file of bank transactions, groups them by " + "month and category, and prints a summary table. Include type hints, docstrings and " + "unit tests using the standard library only." }, + { "code", "Implement a thread-safe LRU cache in C++17 with a fixed capacity, O(1) get and put, " + "and an eviction callback. Explain the locking strategy, then give the full code." }, + { "reasoning", "A train leaves city A at 08:00 at 80 km/h towards city B, 300 km away. Another " + "leaves B at 09:00 at 100 km/h towards A. Where and when do they meet? Then " + "generalise: derive the meeting point for arbitrary departure times and speeds, " + "and check the edge cases step by step." }, + { "reasoning", "Five people sit in a row. Anna is not at either end, Ben sits directly left of " + "Carla, Dora is not next to Ben, and Emil sits at the right end. List every " + "arrangement that satisfies all conditions and prove that there are no others." }, + { "prose", "Write a long short story about a lighthouse keeper on a remote island who receives a " + "letter that was posted forty years ago. Use vivid description and dialogue." }, + { "prose", "Write an essay on how public libraries have changed over the last century, with " + "sections on architecture, technology, funding and their role in communities." }, + { "json", "Return a JSON array of 25 fictional employees. Each object has: id (integer), name, " + "email, department (one of engineering, sales, support, finance), start_date " + "(YYYY-MM-DD), salary (integer), skills (array of strings) and manager_id (integer " + "or null). Output only the JSON." }, + { "json", "Produce a JSON Schema (draft 2020-12) for an online shop order: customer, shipping " + "address, line items with product id, quantity and price, payment details, status " + "history. Then give three example orders that validate against it, as JSON." }, + { "file_edit", "Here is a file:\n\n```python\nimport os\n\ndef load(path):\n f = open(path)\n" + " data = f.read()\n return data\n\ndef save(path, data):\n f = open(path, 'w')\n" + " f.write(data)\n\ndef main():\n d = load(os.environ['IN'])\n save(os.environ['OUT'], " + "d.upper())\n\nmain()\n```\n\nRewrite it so files are closed with context managers, " + "errors are reported with clear messages, paths come from argparse instead of the " + "environment, and main only runs under `if __name__ == '__main__'`. Give the whole " + "new file, then a unified diff against the original." }, + { "file_edit", "Rename the function `calc` to `compute_total` everywhere in the following " + "JavaScript, add JSDoc comments to every function, and convert it to ES modules. " + "Output the complete updated file.\n\n```js\nconst tax = 0.2;\nfunction calc(items) " + "{\n let t = 0;\n for (const i of items) t += i.price * i.qty;\n return t * (1 + tax);\n}" + "\nfunction fmt(v) { return v.toFixed(2) + ' EUR'; }\nmodule.exports = { calc, fmt };\n```" }, + { "summarization", nullptr }, + { "summarization", nullptr }, + }; + std::vector out; + uint32_t doc = 0; + for (const P& p : kPrompts) { + CorpusEntry e; + e.category = p.cat; + std::string text; + if (p.text) { + text = p.text; + } else { + /* A document to summarise: long enough that the answer is a summary and not a copy. */ + text = "Summarise the following report in about 300 words, then list its five most " + "important findings as bullet points.\n\n" + synthetic_document(6000, 1000u + doc++); + } + e.messages = json::array({ json{ { "role", "user" }, { "content", text } } }); + out.push_back(std::move(e)); + } + return out; +} + +int load_corpus(const std::string& path, std::vector* out, std::string* why) { + FILE* f = std::fopen(path.c_str(), "rb"); + if (!f) { + *why = "cannot open " + path; + return RAD_E_IO; + } + std::string text; + char b[65536]; + for (size_t n; (n = std::fread(b, 1, sizeof b, f)) > 0;) text.append(b, n); + std::fclose(f); + std::vector got; + size_t line_no = 0; + for (size_t pos = 0; pos <= text.size();) { + size_t nl = text.find('\n', pos); + if (nl == std::string::npos) nl = text.size(); + std::string line = text.substr(pos, nl - pos); + pos = nl + 1; + ++line_no; + const size_t a = line.find_first_not_of(" \t\r"); + if (a == std::string::npos || line[a] == '#') continue; + const json j = json::parse(line, nullptr, /*allow_exceptions=*/false); + auto bad = [&](const char* what) { + *why = path + ":" + std::to_string(line_no) + ": " + what; + return RAD_E_INVAL; + }; + if (j.is_discarded() || !j.is_object()) return bad("not a JSON object"); + if (!j.contains("category") || !j["category"].is_string() || j["category"].get().empty()) + return bad("needs a non-empty string \"category\""); + CorpusEntry e; + e.category = j["category"].get(); + if (j.contains("messages")) { + if (!j["messages"].is_array() || j["messages"].empty()) return bad("\"messages\" must be a non-empty array"); + for (const json& m : j["messages"]) + if (!m.is_object() || !m.contains("role") || !m.contains("content")) + return bad("every message needs \"role\" and \"content\""); + e.messages = j["messages"]; + } else if (j.contains("prompt") && j["prompt"].is_string()) { + e.messages = json::array({ json{ { "role", "user" }, { "content", j["prompt"] } } }); + } else { + return bad("needs \"messages\" or a string \"prompt\""); + } + if (j.contains("max_tokens")) { + if (!j["max_tokens"].is_number_integer() || j["max_tokens"].get() < 1 || + j["max_tokens"].get() > (1 << 20)) + return bad("\"max_tokens\" must be an integer from 1 to 1048576"); + e.max_tokens = j["max_tokens"].get(); + } + got.push_back(std::move(e)); + } + if (got.empty()) { + *why = path + ": no prompts in it"; + return RAD_E_INVAL; + } + *out = std::move(got); + return RAD_OK; +} + +json salt_messages(const json& messages, const std::string& tag) { + json m = messages; + if (!m.is_array() || m.empty()) return m; + json& c = m[0]["content"]; + const std::string head = "[" + tag + "]\n"; + if (c.is_string()) { + c = head + c.get(); + } else if (c.is_array()) { + c.insert(c.begin(), json{ { "type", "text" }, { "text", head } }); + } else { + c = head; + } + return m; +} + +/* ================================================================== report */ + +namespace { + + +/* "12.3 (11.9–12.8)": the median of a summarised number with its range, or the median alone. */ +std::string cell(const json& summary, const char* key) { + if (!summary.contains(key) || summary[key].is_null()) return "–"; + const json& v = summary[key]; + std::string out = num(v["median"]); + if (v["min"] != v["max"]) out += " (" + num(v["min"]) + "–" + num(v["max"]) + ")"; + return out; +} + +} /* namespace */ + +std::vector env_allowlist(char* const* env) { + /* A fixed list of the engine's configuration knobs, not a prefix: a prefix takes every suffix + * with it, so `RADIANCE_API_KEY_` would be reported by name. Nothing outside the + * list is, and no value is ever read. */ + static const char* const kNames[] = { + "HIP_VISIBLE_DEVICES", "OMP_NUM_THREADS", "OMP_WAIT_POLICY", + "RADIANCE_CALIB_DIR", "RADIANCE_CALIB_TOKENS", "RADIANCE_HOME", + "RADIANCE_HOST_DEVICES", "RADIANCE_HOST_VRAM_MIB", "RADIANCE_KERNELS", + "RADIANCE_LOG", "RADIANCE_LOG_STEPS", "RADIANCE_PROFILE_EVERY", + "RADIANCE_TUNE", "ROCR_VISIBLE_DEVICES", + }; + std::vector out; + for (char* const* e = env; e && *e; ++e) { + const char* eq = std::strchr(*e, '='); + const size_t n = eq ? (size_t)(eq - *e) : std::strlen(*e); + for (const char* name : kNames) + if (std::strlen(name) == n && std::strncmp(*e, name, n) == 0) { + out.emplace_back(*e, n); + break; + } + } + std::sort(out.begin(), out.end()); + return out; +} + +json engine_report(const json& server_info) { + /* Only the model's identity and the cards: /server_info's `container` is the model's path and + * its control vector carries a file, and neither belongs in a report pasted into an issue. The + * card's own handle is left out too: it names a resource in this process, not a card. */ + json out = json::object(); + if (!server_info.is_object()) return out; + for (const char* k : { "arch", "quant", "n_layers", "n_embd", "n_vocab", "n_ctx_train" }) + if (server_info.contains(k)) out[k] = server_info[k]; + if (server_info.contains("devices") && server_info["devices"].is_array()) { + json kept = json::array(); + for (const json& d : server_info["devices"]) { + json k = json::object(); + for (const char* f : { "rank", "name", "arch", "vram_bytes" }) + if (d.is_object() && d.contains(f)) k[f] = d[f]; + kept.push_back(std::move(k)); + } + out["devices"] = std::move(kept); + } + return out; +} + +std::string render_markdown(const json& rep) { + std::string m = "# Diagnosis\n\n"; + if (rep.contains("engine")) { + const json& e = rep["engine"]; + const std::string quant = e.value("quant", std::string()); + m += "Model `" + e.value("arch", std::string("?")) + "`" + + (quant.empty() ? std::string() : " (" + quant + ")") + ", TP " + + num(e.value("tp", json())) + ", backend `" + e.value("backend", std::string()) + + "`, " + e.value("plan", std::string("plan not stated")) + ".\n\n"; + } + if (rep.contains("workload")) m += "Workload: " + rep["workload"].value("description", std::string()) + "\n\n"; + if (rep.contains("verdict")) m += "**Verdict: " + rep["verdict"].get() + "**\n\n"; + if (rep.contains("stability") && rep["stability"].is_object()) + m += "**Run-to-run: " + rep["stability"].value("verdict", std::string()) + "** (headline numbers whose runs " + "spread more than " + num(rep["stability"].value("threshold_pct", json())) + "% of their median are " + "listed under Reproducibility)\n\n"; + if (rep.contains("warnings") && !rep["warnings"].empty()) { + m += "**Warnings**\n\n"; + for (const auto& w : rep["warnings"]) m += "- " + w.get() + "\n"; + m += "\n"; + } + m += "Each cell is the median over the runs of a point, with the smallest and largest run in " + "brackets where they differ. A dash is a number the run could not measure, not a zero.\n\n"; + + if (rep.contains("categories") && !rep["categories"].empty()) { + m += "## Decode by category (1 stream)\n\n" + "| Category | Runs | Stream tok/s | ms/step | Tok/step | Draft acceptance | TTFT ms | 1% low tok/s | Ended on EOS |\n" + "|---|---|---|---|---|---|---|---|---|\n"; + for (const auto& c : rep["categories"]) { + const json s = c.value("summary", json::object()); + m += "| " + c.value("category", std::string("?")) + " | " + num(s.value("runs", json())) + " | " + + cell(s, "requests.stream_tok_s.p50") + " | " + cell(s, "counters.ms_per_decode_step") + " | " + + cell(s, "steps.decode_tok_per_step") + " | " + cell(s, "counters.draft_acceptance") + " | " + + cell(s, "requests.ttft_ms.p50") + " | " + cell(s, "steps.tok_s_1pct_low") + " | " + + num(c.value("stopped_on_eos", json())) + " of " + num(c.value("requests", json())) + " |\n"; + } + m += "\nDraft acceptance by position (conditional, pooled over the runs):\n\n"; + for (const auto& c : rep["categories"]) { + const json pos = c.value("draft_by_position", json::array()); + if (pos.empty()) continue; + m += "- " + c.value("category", std::string("?")) + ":"; + for (const auto& p : pos) + m += " " + num(p["position"]) + ": " + num(p["accepted"]) + " (" + num(p["reached"]) + ");"; + m += "\n"; + } + m += "\n"; + } + if (rep.contains("concurrency") && !rep["concurrency"].empty()) { + m += "## Concurrency sweep (streams submitted together)\n\n" + "| Streams | Runs | Aggregate tok/s | Per stream tok/s | ms/step | Tok/step | Draft acceptance | " + "Emission p50 ms | Emission p99/p50 | 1% low tok/s |\n|---|---|---|---|---|---|---|---|---|---|\n"; + for (const auto& c : rep["concurrency"]) { + const json s = c.value("summary", json::object()); + m += "| " + num(c.value("streams", json())) + " | " + num(s.value("runs", json())) + " | " + cell(s, "requests.aggregate_tok_s") + + " | " + cell(s, "requests.stream_tok_s.p50") + " | " + cell(s, "counters.ms_per_decode_step") + + " | " + cell(s, "steps.decode_tok_per_step") + " | " + cell(s, "counters.draft_acceptance") + + " | " + cell(s, "steps.emission_interval_ms.p50") + " | " + + cell(s, "steps.jitter_emission_p99_over_p50") + " | " + cell(s, "steps.tok_s_1pct_low") + " |\n"; + } + m += "\n"; + } + if (rep.contains("prefill") && !rep["prefill"].empty()) { + m += "## Prefill sweep (1 stream, then decode at that depth)\n\n" + "| Prompt tokens | Runs | TTFT ms | Prefill tok/s | Chunk ms p50 | Decode ms/step at depth | " + "Decode tok/s at depth |\n|---|---|---|---|---|---|---|\n"; + for (const auto& c : rep["prefill"]) { + const json s = c.value("summary", json::object()); + m += "| " + num(c.value("prompt_tokens", json())) + " | " + num(s.value("runs", json())) + " | " + cell(s, "requests.ttft_ms.p50") + + " | " + cell(s, "requests.prefill_tok_s.p50") + " | " + cell(s, "steps.prefill_chunk_ms.p50") + + " | " + cell(s, "counters.ms_per_decode_step") + " | " + cell(s, "requests.stream_tok_s.p50") + " |\n"; + } + m += "\n"; + } + if (rep.contains("interference") && rep["interference"].is_object()) { + const json& i = rep["interference"]; + const json s = i.value("summary", json::object()); + m += "## A prompt arriving into running streams\n\n" + num(i.value("streams", json())) + " streams decoding, then one prompt of " + + num(i.value("prompt_tokens", json())) + " tokens.\n\n| Measure | Value |\n|---|---|\n"; + m += "| TTFT of the arriving prompt | " + cell(s, "arrival_ttft_ms") + " ms |\n"; + m += "| Its TTFT on an idle engine (prefill sweep) | " + num(i.value("idle_ttft_ms", json())) + " ms |\n"; + m += "| Typical emission gap before it | " + cell(s, "interference.typical_gap_ms") + " ms |\n"; + m += "| Longest emission gap while it prefilled | " + cell(s, "interference.longest_gap_ms") + " ms |\n"; + m += "| Stall ratio (longest / typical) | " + cell(s, "interference.stall_ratio") + " |\n\n"; + } + if (rep.contains("parity") && rep["parity"].is_object()) { + const json& p = rep["parity"]; + m += "## Parity against " + p.value("baseline", std::string("the baseline")) + "\n\n**" + + p.value("verdict", std::string()) + "**: " + num(p.value("identical", json())) + " of " + + num(p.value("compared", json())) + " requests produced identical tokens.\n\n"; + const json& d = p.value("differing", json::array()); + if (!d.empty()) { + m += "| Point | Run | Request | Prompt tokens | First different token | Tokens (now / baseline) |\n|---|---|---|---|---|---|\n"; + for (const auto& x : d) + m += "| " + x["point"].get() + " | " + num(x["run"]) + " | " + num(x["request"]) + " | " + + num(x.value("prompt_tokens", json())) + " | " + num(x["first_different_token"]) + " | " + + num(x["tokens"]) + " / " + num(x["tokens_baseline"]) + " |\n"; + m += "\n"; + } + const json acc = p.value("acceptance", json::array()); + if (!acc.empty()) { + m += "Draft acceptance against the baseline (**" + p.value("acceptance_verdict", std::string()) + + "**): overall by a paired t test over the requests, positions by the pooled z corrected for " + "the requests' dispersion; a drop is as unlikely as z below -3:\n\n" + "| Point | | Now | Baseline | Drafts now / baseline | Test |\n|---|---|---|---|---|---|\n"; + for (const auto& x : acc) { + std::string test; + if (x.contains("t")) { + char b[64]; + std::snprintf(b, sizeof b, "t %s, p %.2g, %lld requests", num(x["t"]).c_str(), + x.value("p", 1.0), (long long)x.value("requests", (int64_t)0)); + test = b; + } else { + test = "z " + num(x.value("z", json())); + if (x.contains("dispersion")) test += ", dispersion " + num(x["dispersion"]); + } + m += "| " + x.value("point", std::string()) + " | " + x.value("what", std::string()) + " | " + + num(x.value("now", json())) + " | " + num(x.value("baseline", json())) + " | " + + num(x.value("n_now", json())) + " / " + num(x.value("n_baseline", json())) + " | " + test + " |\n"; + } + m += "\n"; + } + for (const auto& x : p.value("missing", json::array())) m += "- missing: " + x.get() + "\n"; + if (!p.value("missing", json::array()).empty()) m += "\n"; + } + { + const bool any = (rep.contains("conditions") && rep["conditions"].is_object()) || + (rep.contains("stability") && rep["stability"].is_object()); + if (any) m += "## Reproducibility\n\n"; + if (rep.contains("stability") && rep["stability"].is_object()) { + const json& u = rep["stability"].value("unstable", json::array()); + if (!u.empty()) { + m += "| Point | Number | Spread | Median | Runs |\n|---|---|---|---|---|\n"; + for (const json& x : u) + m += "| " + x.value("point", std::string()) + " | " + x.value("metric", std::string()) + " | " + + num(x["spread_pct"]) + "% | " + num(x["median"]) + " | " + num(x.value("runs", json())) + " |\n"; + m += "\n"; + } + } + if (rep.contains("conditions") && rep["conditions"].is_object()) { + const json& c = rep["conditions"]; + const json h = c.value("host", json::object()); + const json e = c.value("engine", json::object()); + m += "Conditions `" + c.value("fingerprint", std::string()) + "`: radiance " + num(e.value("version", json())) + + ", CPU governor " + num(h.value("cpu_governor", json())) + " (energy preference " + + num(h.value("cpu_epp", json())) + "), kernel " + num(h.value("kernel", json())) + ", runtime " + + num(h.value("runtime", json())) + ".\n\n"; + const json& cards = c.value("cards", json::array()); + if (!cards.empty()) { + m += "| Rank | Card | sclk | mclk | Power cap (default) | Voltage offset | Runtime PM |\n" + "|---|---|---|---|---|---|---|\n"; + for (const json& k : cards) + m += "| " + num(k["rank"]) + " | " + num(k["name"]) + " " + num(k["gfx"]) + " | " + num(k["sclk"]) + + " | " + num(k["mclk"]) + " | " + num(k["power_cap_w"], " W") + " (" + + num(k["power_cap_default_w"], " W") + ") | " + num(k["voltage_offset"]) + " | " + + num(k["runtime_pm"]) + " |\n"; + m += "\n"; + } + } + if (rep.contains("thermal") && rep["thermal"].is_object()) { + const json& t = rep["thermal"].value("cards", json::array()); + if (!t.empty()) { + m += "| Card | Runs | Start temperature | End temperature | Performance level |\n|---|---|---|---|---|\n"; + auto rg = [](const json& r) { + return r.is_object() ? num(r["min"]) + "–" + num(r["max"]) + " C" : std::string("–"); + }; + for (const json& k : t) { + std::string lv; + for (const json& l : k.value("perf_levels", json::array())) + lv += (lv.empty() ? "" : ", ") + l.get(); + m += "| " + k.value("bdf", std::string()) + " | " + num(k["runs"]) + " | " + rg(k["start_c"]) + " | " + + rg(k["end_c"]) + " | " + (lv.empty() ? std::string("–") : lv) + " |\n"; + } + m += "\n"; + } + } + for (const json& n : rep.value("reproducibility", json::array())) m += "- " + n.get() + "\n"; + if (!rep.value("reproducibility", json::array()).empty()) m += "\n"; + } + if (rep.contains("not_measured")) { + m += "## Not measured\n\n"; + for (const auto& w : rep["not_measured"]) m += "- " + w.get() + "\n"; + } + return m; +} + +} /* namespace diag */ +} /* namespace rad */ diff --git a/core/diag/diagnose.h b/core/diag/diagnose.h new file mode 100644 index 00000000..a95361ce --- /dev/null +++ b/core/diag/diagnose.h @@ -0,0 +1,279 @@ +/* diagnose.h -- the --diagnose mode's arithmetic and its report. + * + * `radiance --diagnose DIR` starts the engine as it would to serve, then runs a fixed workload on + * itself instead of listening (core/engine_diagnose.cpp) and writes DIR/diagnose.json and + * DIR/diagnose.md. This file is the part with no device and no scheduler in it: the step record + * the scheduler keeps, the statistics a phase reduces to, and the report. The driver feeds it; + * tests/diagnose_test.cpp holds it to hand-computed numbers. + * + * WHY THE ENGINE MEASURES ITSELF. The numbers an operator wants -- milliseconds a decode step, + * tokens a step, how often a draft is taken, how long a prefill takes, how uneven the steps are -- + * are all known inside the engine exactly, and outside it only through a client's clock and a + * stream that delivers a speculative step's tokens in one burst. A client measuring inter-token + * latency on a speculating engine is measuring the burst pattern; the engine knows the steps. + * + * WHAT A PHASE REPORTS, AND FROM WHERE. + * - SchedMetrics deltas taken while the engine is idle at the phase's edges: exact counts of + * steps by shape, tokens, drafts proposed and accepted, per draft position. + * - One StepRecord per step, written by the scheduler (Scheduler::step_finished): what the step + * carried and how long it took. From these: the distribution of decode step times, the + * interval between consecutive emissions (what a stream sees between token bursts), and the + * slowest steps against typical ones. + * - Each request's sink: admitted, first token, last token, tokens -- TTFT and stream rate. + * A quantity the run cannot measure is reported as absent with the reason, never as 0. + */ +#pragma once + +#include "sched/metrics.h" + +#include "util/json.h" + +#include +#include +#include +#include + +namespace rad { +namespace diag { + +struct Facts; +struct RunFacts; +struct Finding; +struct CardSample; + +using json = Json; + +/* ONE ENGINE STEP, as the scheduler commits it. Plain data, fixed size: the scheduler writes one + * per step under its own lock into a ring sized at init, so recording costs a store and no + * allocation on the step path. */ +struct StepRecord { + int64_t step = 0; /* SchedMetrics::steps after this step: a run-wide ordinal */ + int32_t phase = 0; /* RAD_PHASE_PREFILL / DECODE / MIXED of the step's plan */ + int32_t n_seq = 0; /* sequences the step carried */ + int32_t prefill_tok = 0; /* prompt tokens it computed */ + int32_t decode_tok = 0; /* tokens it committed to decoding sequences, accepted drafts included */ + int64_t ns = 0; /* inside the step, the clock SchedMetrics::step_ns charges */ + int64_t end_ns = 0; /* steady clock when it was committed: emissions are spaced by these */ +}; + +/* A FIXED-CAPACITY RING OF STEP RECORDS with a run-wide sequence number. The writer and every + * reader hold the scheduler's lock, so it needs no atomics of its own. A reader asks for what + * came after a sequence number it saved; if the ring has lapped since, the records it lost are + * counted, not invented. */ +class StepRing { +public: + explicit StepRing(size_t capacity = 0) { reset(capacity); } + void reset(size_t capacity); + + void push(const StepRecord& r) noexcept; + uint64_t count() const { return n_; } /* records ever pushed */ + size_t capacity() const { return buf_.size(); } + + /* Appends every record with sequence number >= `from` still in the ring to `out`; returns how + * many after `from` were overwritten before they could be read. */ + uint64_t copy_since(uint64_t from, std::vector* out) const; + +private: + std::vector buf_; + uint64_t n_ = 0; +}; + +/* ------------------------------------------------------------------ statistics */ + +/* Quantiles by nearest rank over a copy of the samples. `n == 0` means there were none, and every + * other field is then meaningless; the JSON form says null rather than 0. */ +struct Quantiles { + int64_t n = 0; + double min = 0, p50 = 0, p90 = 0, p99 = 0, max = 0, mean = 0; +}; +Quantiles quantiles(std::vector v); +json to_json(const Quantiles& q); + +/* What a request's sink recorded, on one steady-clock axis (Sink::t_start_ns + its offsets). -1 + * where the sink never saw the event. */ +struct RequestTiming { + int64_t start_ns = -1; /* the sink's construction: before submission */ + int64_t admitted_ns = -1; /* the scheduler first gave it a step */ + int64_t first_ns = -1; /* first token */ + int64_t last_ns = -1; /* last token */ + int64_t tokens = 0; /* produced */ + int32_t prompt = 0; /* prompt tokens */ + int32_t cached = 0; /* of those, served from the prefix cache */ + int64_t drafted = 0; + int64_t accepted = 0; + bool ok = false; /* finished on length or stop, not on an error or a cancel */ + bool stopped = false; /* finished on the model's own end of sequence, not on length */ + std::vector output; /* the tokens it produced, for the parity comparison */ +}; + +enum class PhaseKind { Decode, Prefill }; + +struct PhaseInput { + std::string name; + PhaseKind kind = PhaseKind::Decode; + int streams = 1; + int64_t wall_ns = 0; + SchedMetrics before, after; + std::vector steps; /* the steps the phase ran, in order */ + uint64_t steps_lost = 0; /* records the ring overwrote before they were read */ + std::vector requests; + /* The serving cards' state before and after the run ({"start": [...], "end": [...]}, each + * card_samples_json), null when the driver read none. */ + json cards; +}; + +/* The phase's section of the report. Every derived number names what it was derived from. */ +json phase_report(const PhaseInput& in); + +/* The slowest steps of one shape against the typical ones: the slowest `max(3, 1%)` decode steps + * with what they carried, and the median step beside them, so a reader can tell a step that was + * slow because it carried more from one that was slow carrying the same. */ +json slow_steps(const std::vector& steps, int phase); + +/* DRAFT ACCEPTANCE BY POSITION, POOLED OVER A POINT'S RUNS: at each position the verifies that + * reached it and the share of those that took it, summed over the runs rather than a median of + * per-run rates, because a run reaches the deep positions only a few times. This is the curve an + * adaptive draft depth is tuned against. */ +json pool_draft_positions(const std::vector& runs); + +/* THE RUNS OF ONE MEASUREMENT POINT, reduced to what a reader compares: for each headline number + * of phase_report, the median over the runs and the smallest and largest run. A run that has no + * value for a number does not count toward it; a number no run had is null. */ +json summarize_runs(const std::vector& runs); +/* The same over the numbers at the given JSON pointers, keyed by the pointer with '/' as '.'. */ +json summarize_paths(const std::vector& runs, const std::vector& paths); + +/* ------------------------------------------------------------------ reproducibility */ + +/* A headline number whose runs spread wider than this, as (max - min) / median, makes the point + * UNSTABLE in the report's stability section: the runs disagree by more than most changes a + * comparison is run to find. */ +constexpr double kMaxSpreadPct = 5.0; +/* Runs of one report that start this many degrees apart (junction, else edge) began on cards in + * different thermal states. */ +constexpr double kMaxStartTempSpreadC = 10.0; + +/* The cards' samples as JSON: temperatures in degrees C, power in W, the performance level and the + * current DPM levels; an unknown field is null. */ +json card_samples_json(const std::vector& samples); + +/* WHAT THE RUN RAN ON, so two reports can be told comparable or not: the engine build, the host + * settings that move a step's time (CPU governor and energy preference, kernel, device runtime, + * THP, IOMMU mode) and the serving cards (rank >= 0) with their DPM ranges, power cap against its + * default, voltage offset, runtime power management and link. No path and no command line: the + * report is pasted into issues. `findings` are the startup report's (diag::check) and are listed + * with their fix. `fingerprint` hashes everything but the findings, whose text carries load- + * dependent numbers. */ +json conditions_report(const Facts& f, const RunFacts& r, const std::vector& findings); + +/* The fields of two reports' `conditions` that differ, as {"field", "now", "baseline"} with the + * field as a JSON pointer; empty when they ran under the same conditions. */ +json conditions_differences(const json& now, const json& base); + +/* RUN-TO-RUN AGREEMENT. For each measured point the headline numbers -- aggregate and per-step + * decode rate for each category prompt (its `prompts_summary`; the category's own summary pools + * prompts that differ by design) and each concurrency point, TTFT and prefill rate for the prefill sweep, the arriving + * prompt's TTFT for interference -- whose spread_pct exceeds `max_spread_pct`. `verdict` is + * "stable", "UNSTABLE" or "not judged" (no point has two runs). */ +json stability_report(const json& report, double max_spread_pct = kMaxSpreadPct); + +/* THE CARDS ACROSS THE MEASURED RUNS: per card the start and end temperatures' range and the + * performance levels seen, from each run's `cards`. `warnings` names a start-temperature spread + * above kMaxStartTempSpreadC and a performance level that changed during the report. */ +json thermal_report(const json& report); + +/* A DECODE STALL: what a prompt arriving into running streams costs them. `from`..`to` is the + * window from the new request's admission to its first token; the report gives the longest gap + * between two emissions that overlaps it, against the median gap of the emissions before it. */ +json interference_report(const std::vector& steps, int64_t from_ns, int64_t to_ns); + +/* ------------------------------------------------------------------ parity */ + +/* WHAT TWO RUNS OF THE SAME WORKLOAD PRODUCED, COMPARED TOKEN FOR TOKEN. With the same prompts and + * the same seed per request, a build whose logits are bit-identical samples identical tokens, at + * any temperature -- so every request of the categories, the concurrency sweep and the prefill + * sweep is a parity check of the paths it ran: long prefills, attention at depth, batched decode. + * The interference point is left out: when its running streams are cancelled depends on timing. + * + * `now` and `base` are whole reports. Points are matched by their key (category, streams, + * requested tokens), runs and requests by position. The result counts identical and differing + * requests and names, for each difference, the first token where they part; a point or run that + * only one side has is listed as missing rather than counted as either. Two reports of different + * workloads (workload.fingerprint) are refused with RAD_E_INVAL: their prompts differ. */ +/* Beside the tokens it compares each matched point's draft acceptance: identical for + * bit-identical builds, and the first number to move when a build computes less accurately. The + * overall rate by a one-sided paired t test over the requests (same prompt and seed on both + * sides), the positions by the pooled two-proportion z divided by the square root of the + * dispersion the requests show; either as unlikely as z below -3 is a drop, listed in + * `acceptance_dropped`, and makes `acceptance_verdict` "DROPPED". */ +int compare_outputs(const json& now, const json& base, json* out, std::string* why); + +/* The part of a report's workload that decides which prompts and seeds it ran: equal fingerprints + * mean comparable outputs. */ +std::string workload_fingerprint(const json& workload_params); + +/* ------------------------------------------------------------------ workload */ + +/* ONE PROMPT OF THE CATEGORY WORKLOAD: OpenAI-style chat messages and the category they are + * reported under. `max_tokens` 0 means the run's --diagnose-tokens. */ +struct CorpusEntry { + std::string category; + json messages; + int max_tokens = 0; +}; + +/* A small built-in corpus, a few prompts in each of the categories a chat deployment typically + * serves (code, reasoning, prose, json, file_edit, summarization), so a run without a corpus file + * still reports by category. Speculative decoding accepts very differently across these, which is + * why one decode number is not enough. */ +std::vector builtin_corpus(); + +/* Reads a corpus file: one JSON object a line, `{"category": "...", "messages": [...]}` or + * `{"category": "...", "prompt": "..."}`, optionally with "max_tokens". Blank lines and lines + * starting with '#' are skipped. Any other malformed line refuses the file, naming the line. */ +int load_corpus(const std::string& path, std::vector* out, std::string* why); + +/* THE SAME MESSAGES MADE UNIQUE FROM THEIR FIRST CHARACTER. `tag` is put at the head of the first + * message's content, so no two requests of a run share a prefix longer than the chat template's + * own opening -- less than one cache block -- and the prefix cache cannot serve one from another. + * The tag is deterministic (a request counter), so two builds see the same prompts; a hit from a + * cache tier that outlived the process is caught by the driver's check of RequestTiming::cached. */ +json salt_messages(const json& messages, const std::string& tag); + + +/* A deterministic document of about `chars` characters: numbered sections of fixed prose, every + * section different in its numbers, so a prefix cache cannot serve one run's text to the next + * when `salt` differs. Language-neutral enough to tokenise under any vocabulary. */ +std::string synthetic_document(int64_t chars, uint32_t salt); + +/* The decode prompts, one per stream: fixed instructions that ask for long prose, distinct per + * stream so eight streams are eight conversations and not one prompt eight times. */ +std::string decode_prompt(int stream); + +/* ------------------------------------------------------------------ report */ + +/* The environment the workload ran under: the NAMES of the variables in `env` (environ-shaped, + * null-terminated) that are on a fixed list of the engine's configuration knobs, sorted. Names + * only, never values: a value may be a path, a host name or a token, and the report is pasted into + * issues and committed beside a baseline (diag/diag.h's env_names states the same rule for the + * startup report). + * + * A fixed list, not a prefix: a prefix admits every suffix, so `RADIANCE_API_KEY_` is a + * name the report would print. A name the engine does not read as configuration is not reported. */ +std::vector env_allowlist(char* const* env); + +/* The engine section of a report, built from the engine's /server_info object: the model's + * architecture, quantisation and shapes, and the cards it ran on. The object itself is not copied, + * because its `container` is the model's path and its control vector carries a file, and the report + * is pasted into issues: a path names a person's home directory and nothing a reader needs. */ +json engine_report(const json& server_info); + +/* The Markdown view of a report: one table each for the categories, the concurrency sweep, the + * prefill sweep and the interference point, from their `summary` sections plus the driver's + * header. It reads only the JSON, so it can be regenerated from a saved diagnose.json; the + * per-run detail stays in the JSON. It carries no path either: the header names the model by its + * architecture and quantisation (engine_report), never by where it is stored. */ +std::string render_markdown(const json& report); + +} /* namespace diag */ +} /* namespace rad */ diff --git a/core/diag/sysinfo.cpp b/core/diag/sysinfo.cpp index e63035f5..eb439f10 100644 --- a/core/diag/sysinfo.cpp +++ b/core/diag/sysinfo.cpp @@ -423,6 +423,48 @@ Facts collect(const std::string& root, const std::vector* managed) return f; } +std::vector sample_cards(const std::string& root, const std::vector& bdfs) { + /* The line the driver marks with '*', without the mark and the level's index: "2350Mhz". */ + auto current = [](const std::string& path) { + std::istringstream in(slurp(path)); + std::string l; + while (std::getline(in, l)) { + if (l.find('*') == std::string::npos) continue; + l.erase(std::remove(l.begin(), l.end(), '*'), l.end()); + const size_t colon = l.find(':'); + return trim(colon == std::string::npos ? l : l.substr(colon + 1)); + } + return std::string(); + }; + std::vector out; + for (const std::string& bdf : bdfs) { + const std::string dev = root + "/sys/bus/pci/devices/" + bdf; + CardSample c; + c.bdf = bdf; + c.perf_level = line(dev + "/power_dpm_force_performance_level"); + c.sclk_cur = current(dev + "/pp_dpm_sclk"); + c.mclk_cur = current(dev + "/pp_dpm_mclk"); + c.busy_percent = (int)num(dev + "/gpu_busy_percent", -1); + for (const std::string& h : list(dev + "/hwmon")) { + const std::string hp = dev + "/hwmon/" + h; + /* amdgpu labels its sensors; an unlabelled temp1 is the edge sensor. */ + for (int t = 1; t <= 8; ++t) { + const std::string base = hp + "/temp" + std::to_string(t); + const int64_t v = num(base + "_input", -1); + if (v < 0) continue; + const std::string label = line(base + "_label"); + if (label == "edge" || (label.empty() && t == 1)) c.edge_mc = v; + else if (label == "junction") c.junction_mc = v; + else if (label == "mem") c.mem_mc = v; + } + if (c.power_uw < 0) c.power_uw = num(hp + "/power1_average", -1); + if (c.power_uw < 0) c.power_uw = num(hp + "/power1_input", -1); + } + out.push_back(std::move(c)); + } + return out; +} + void probe_process(HostFacts* h) { struct rlimit rl{}; if (getrlimit(RLIMIT_MEMLOCK, &rl) == 0) diff --git a/core/engine.cpp b/core/engine.cpp index e4e69e6d..e2b4d23c 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -2457,12 +2457,14 @@ void Engine::tier_tick() { /* Release an entry once its host copy has landed, if the expert slab can use the blocks; a * later turn restores it with a copy. Otherwise (no lending, or the loan already covers every * slab slot) it stays in VRAM, and a request needing room takes it through trim. Snapshots - * are already in host memory. */ + * are already in host memory. Stragglers with no host copy coming go too (PrefixCache:: + * drop_clean): a few thousand such tokens near the top of the pool would otherwise hold the + * whole loan at zero until the server restarts. */ if (lending_) { int64_t ceiling = 0; for (auto& r : ranks_) ceiling = std::max(ceiling, r->mover.loan_ceiling(Mover::kLendKV)); const auto lk = sched_.hold(); - if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean(); + if (lead.kv.loan_tokens() < ceiling) (void)lead.prefix.drop_clean(ceiling); } /* ---- capacity ---------------------------------------------------------------------------- */ @@ -2840,11 +2842,14 @@ int Engine::serve(std::unique_ptr watch) { stepped.store(true, std::memory_order_release); }); - if (cfg_.kld() || cfg_.calib()) { + if (cfg_.kld() || cfg_.calib() || cfg_.diagnose_mode()) { print_startup_report(RAD_OK); startup_watch_.reset(); } - int s = cfg_.kld() ? run_kld() : cfg_.calib() ? run_calib() : run_server(); + int s = cfg_.diagnose_mode() ? run_diagnose() + : cfg_.kld() ? run_kld() + : cfg_.calib() ? run_calib() + : run_server(); startup_watch_.reset(); /* Stop the step loop before the server's storage is destroyed: Request::sink points into it, @@ -3120,6 +3125,11 @@ std::string request_overrides(const Config& c) { return out; } } /* namespace */ + +SamplingParams Engine::sampling_defaults() const { + return resolve_sampling_defaults(meta_, file_ != nullptr, cfg_); +} + /* The HTTP server over the engine. `/v1/completions`, `/v1/chat/completions`, `/v1/models`, * `/metrics` and `/health` are live. `/v1/embeddings` answers 501 unless the program is an * embedding program, and so do image, video and audio content parts unless the program declared an @@ -3951,6 +3961,8 @@ int Engine::run_server() { in.branches = ad.branches == 1 ? 1 : 2; in.input_special = ad.input_special != 0; in.tmpl_ref = pg.agen_str.tmpl_ref; + in.tmpl_ref_instruct = pg.agen_str.tmpl_ref_instruct; + in.neg_tmpl_ref = pg.agen_str.neg_tmpl_ref; in.ref_item = pg.agen_str.ref_item; in.ref_rate = ad.ref_rate; in.ref_hop = ad.ref_hop; diff --git a/core/engine.h b/core/engine.h index 4b15970e..e93ebb83 100644 --- a/core/engine.h +++ b/core/engine.h @@ -788,6 +788,10 @@ private: std::vector>& sinks, bool fit_pool, const char* tag, int every_s, const std::function& progress, int* bad); + /* --diagnose (core/engine_diagnose.cpp), replacing run_server: runs a fixed workload on this + * engine -- decode by prompt category, a concurrency sweep, a prefill sweep, interference -- + * and writes DIR/diagnose.json and DIR/diagnose.md instead of listening. */ + int run_diagnose(); int score_rows(const RadBatch* b, const StepOut& so); std::unique_ptr kld_; std::vector kld_host_; @@ -800,6 +804,10 @@ private: long long calib_tokens_ = 0; /* The engine half of /server_info, as a JSON object. See the definition in engine.cpp. */ std::string engine_info() const; + /* The sampler a request that sends no settings runs with: the container's generation defaults + * with the operator's flags over them (resolve_sampling_defaults, engine.cpp). A mode that + * builds requests with no client -- --diagnose -- samples with what the server would. */ + SamplingParams sampling_defaults() const; /* ---- startup report inputs (engine_diag.cpp). `decisions_` holds each value startup resolved * and why, recorded where it was resolved; the rest are facts only startup saw. */ diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index fcc097a1..58f49200 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -3551,8 +3551,11 @@ static int sweep_container(RadFile* file, std::vector& runs, return RAD_OK; }(); - /* Release the page cache of weights never read from the file again, leaving it to the mapped - * tier (e.g. a mapped n-gram table, read from its mapping for the process lifetime). */ + /* Release the page cache of weights never read from the file again. The mapped tier's pages + * stay (RadFile::keep_cached, named where load_weights publishes a mapped weight): an n-gram + * table is gathered from its mapping on every step, and with its pages dropped the first long + * prefill after each load or restore faults them back from the drive (a 103 GiB table: 1460 + * against 1998 tok/s on a 24k prompt). */ file->drop_blob_cache(); /* Drain before freeing: a sweep that failed part-way may have copies outstanding. */ for (int b = 0; b < kWin; ++b) pool->drain(b); @@ -3683,6 +3686,8 @@ int Engine::load_weights() { int64_t total = 0, n_loaded = 0, n_missing = 0; /* Counted apart from `n_loaded`: mapped weights are published in place, not loaded. */ int64_t n_mapped = 0, mapped_bytes = 0; + /* Of the container's own bytes, what the mapped tier reads: left in the page cache. */ + int64_t mapped_kept = 0; /* Two phases. The walk decides which rank wants which bytes, where they land, and what is * refused, without touching the disk; sweep_container then reads the container once in file @@ -3870,6 +3875,7 @@ int Engine::load_weights() { * for a row of a few hundred bytes. MADV_RANDOM is per range, so the rest of the * container keeps sequential readahead. The effect shows only with a cold cache. */ posix_madvise(w.ptr, (size_t)n, POSIX_MADV_RANDOM); + if (file_) mapped_kept = file_->keep_cached(w.host_ptr, n); r->mover.publish_mapped((rad_weight)i, w.ptr); ++n_mapped; mapped_bytes += n; @@ -4000,10 +4006,11 @@ int Engine::load_weights() { /* Summed over ranks, which map the same file, so under TP the resident bytes are this * divided by --tp; the message says so. */ RAD_INFO("load: %lld weight(s), %s, read in place from the container's mapping -- not " - "copied and charged to no pool%s", (long long)n_mapped, - humanb(mapped_bytes).c_str(), + "copied and charged to no pool%s; %s of the container stays page-cached for them", + (long long)n_mapped, humanb(mapped_bytes).c_str(), cfg_.tp > 1 ? " (summed over ranks, which map the same file: the resident bytes " - "are that divided by --tp)" : ""); + "are that divided by --tp)" : "", + humanb(mapped_kept).c_str()); return RAD_OK; } diff --git a/core/engine_diagnose.cpp b/core/engine_diagnose.cpp new file mode 100644 index 00000000..6d310686 --- /dev/null +++ b/core/engine_diagnose.cpp @@ -0,0 +1,698 @@ +/* engine_diagnose.cpp -- the --diagnose driver: a fixed workload the engine runs on itself in + * place of the HTTP server, and the report it writes. The arithmetic and the report format are + * core/diag/diagnose.h's; this file only drives the scheduler and collects what it needs. + * + * THE WORKLOAD IS A SERVING WORKLOAD. Prompts go through the model's chat template with the + * deployment's reasoning default, sampling is the server's default (the same resolve the HTTP + * path uses) with a fixed seed per request, and pipelining and drafting stay as configured -- so + * what is measured is the engine that serves, not a benchmark mode of it. No HTTP, no stop + * strings. + * + * NOTHING IS SERVED FROM THE PREFIX CACHE. Every prompt is salted at its head with a tag unique to + * the request (diag::salt_messages), the cache is emptied before every run, and every request's + * cached-token count is checked afterwards: a run the cache served any of is reported, and the + * report's verdict says the run is not a measurement. The cache itself stays on, so what it costs + * a request that misses -- lookups, publishing, checkpoints -- is measured as a server pays it. + * + * PARITY. The tag is a counter, not a clock, so two builds run the same workload on the same + * prompts with the same seeds, and every request's tokens are in the report. With + * --diagnose-baseline the run compares them with an earlier report token for token + * (diag::compare_outputs) and fails on any difference. + * + * Points, each run once unmeasured (first launches of a shape record passes and load code) and + * then --diagnose-runs times, every run from an idle engine: + * categories one stream a prompt of the corpus, ending on the model's EOS or max tokens + * concurrency N streams submitted together, for each N of --diagnose-concurrency; + * ignore_eos, so all N decode for the whole run + * prefill one prompt of each length of --diagnose-prefill, then a short decode at that + * depth + * interference streams decoding, then one prompt arriving: its TTFT under load and the gap it + * puts into the running streams + */ +#include "engine_priv.h" +#include "diag/diagnose.h" + +#include "build/startup.h" +#include "device/device.h" +#include "server/adapters.h" +#include "server/sink.h" + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + + +extern char** environ; + +namespace rad { + +namespace { + +using json = diag::json; + +int64_t steady_ns() { + return std::chrono::duration_cast( + std::chrono::steady_clock::now().time_since_epoch()).count(); +} + +/* The environment knobs that change what is measured, so a report says what it was measured + * under: several are read once into statics and cannot be seen any other way. Names only, from the + * allowlist in diag/diagnose.cpp; a value may be a path, a host name or a token, and the report is + * pasted into issues and committed beside a baseline. */ +json env_snapshot() { return diag::env_allowlist(environ); } + +/* One request of a run. */ +struct Job { + std::vector prompt; + int max_tokens = 0; + bool ignore_eos = true; + float temp = -1.0f; /* < 0: the server's default */ +}; + +double loadavg1() { + FILE* f = std::fopen("/proc/loadavg", "r"); + if (!f) return -1; + double v = -1; + if (std::fscanf(f, "%lf", &v) != 1) v = -1; + std::fclose(f); + return v; +} + +} /* namespace */ + +int Engine::run_diagnose() { + namespace fs = std::filesystem; + std::error_code ec; + fs::create_directories(cfg_.diagnose, ec); + if (ec) { + RAD_ERR("diagnose: cannot create '%s': %s", cfg_.diagnose.c_str(), ec.message().c_str()); + return RAD_E_IO; + } + + json warnings = json::array(); + json problems = json::array(); /* what makes the run not a measurement: the verdict */ + auto warn = [&](const std::string& w) { + RAD_WARN("diagnose: %s", w.c_str()); + warnings.push_back(w); + }; + json not_measured = json::array({ + "per-kernel device time, launch gaps and host joins: needs dispatch timestamps inside the " + "engine (docs/DIAGNOSE.md, step 3); rocprofv3 is not a substitute here", + "placement, expert streaming and link counters per phase (docs/DIAGNOSE.md, step 1b)", + "op correctness (repeat, oracle) over a step window (docs/DIAGNOSE.md, step 4)", + "the HTTP path, detokenisation and streaming to a client: a client-side benchmark measures " + "those, and the difference to these numbers is their cost", + }); + + /* ---- the conditions: what the run ran on, and the serving cards to sample between runs ---- + * The startup report's machine reading and its findings, taken once before the workload; the + * cards' temperatures and performance level again around every run (diag::sample_cards), so a + * report shows when two runs, or two reports, were taken on cards in different states. */ + const diag::Facts facts0 = hardware_facts(/*serving=*/true); + const diag::RunFacts rfacts = run_facts(false); + const std::vector findings = diag::check(facts0, rfacts); + std::vector serving_bdfs; + for (const diag::CardFacts& c : facts0.cards) + if (c.rank >= 0) serving_bdfs.push_back(c.bdf); + for (const diag::Finding& x : findings) + if (x.level >= diag::Finding::Warn && x.id != "profile-ops" && x.id != "prefix-cache-off") + warn("machine: " + x.what + " (" + x.fix + ")"); /* those two the mode says below, in its terms */ + + /* What makes the numbers depend on more than the build and the machine. Notes, not problems: + * each is how the engine serves, and the fix makes it a different engine. */ + json repro = json::array(); + { + bool heat = false; + for (const auto& r : ranks_) heat = heat || r->heat.enabled(); + if (heat) + repro.push_back("placement is dynamic: the heat engine moves experts as it sees routing, so the " + "resident set a run starts with depends on the runs before it; --deterministic " + "pins the loader's plan for an A/B comparison"); + if (cfg_.prefill_interleave < 0) + repro.push_back("--prefill-interleave auto sizes the decode-only steps between prefill chunks by " + "how long a chunk step took, so a long prompt's step sequence depends on timing; " + "--prefill-interleave 0 or N fixes it"); + const std::vector s0 = diag::sample_cards("", serving_bdfs); + for (const diag::CardSample& c : s0) + if (c.perf_level == "auto") + repro.push_back("card " + c.bdf + ": performance level auto, so the firmware picks clocks by " + "load, temperature and power; a fixed level (profile_standard in " + "power_dpm_force_performance_level) holds them for a comparison, below " + "serving clocks"); + if (cfg_.diagnose_runs < 5) + repro.push_back(std::to_string(cfg_.diagnose_runs) + " measured run(s) a point: a spread of so " + "few samples says little; --diagnose-runs 5 or more for a comparison"); + } + + /* ---- prompts: the chat template where the container has one, as the server renders it ---- */ + server::TokenizerBridge tok(vocab_); + server::ChatTemplateBridge chat; + const RadChatFormat* fmt = rad_tools_chat_format(plugins_, meta_); + const bool use_chat = vocab_ && !vocab_->chat_template().empty() && + chat.init(*vocab_, fmt, plugins_.arch_plugin) >= 0 && chat.ready(); + if (!use_chat) + warn("no usable chat template: prompts are raw text, so draft acceptance and tokens a step " + "are not those of chat traffic"); + + /* A counter, the same in every process, so a baseline and a candidate see the same prompts. + * What the salt cannot cover is the tiers that outlive the process; the cached-token check + * after every run catches a hit and refuses the run (below). */ + uint64_t salt_n = 0; + auto render = [&](const json& messages, std::vector* out) -> int { + char tag[64]; + std::snprintf(tag, sizeof tag, "diagnose request %llu", (unsigned long long)++salt_n); + const json msgs = diag::salt_messages(messages, tag); + if (use_chat) { + server::ChatRenderOptions o; + const std::string& def = cfg_.reasoning_effort; + if (def == "none" || def == "minimal") o.enable_thinking = false; + else if (!def.empty()) o.template_kwargs.emplace("reasoning_effort", json(def).dump()); + server::ChatRender r; + std::string why; + const int st = chat.apply(msgs, json::array(), o, &r, &why); + if (st < 0) { + RAD_ERR("diagnose: the chat template refused a workload prompt: %s", why.c_str()); + return st; + } + *out = tok.encode(r.prompt, false, /*parse_special=*/true); + } else { + std::string text; + for (const json& m : msgs) + if (m["content"].is_string()) text += m["content"].get() + "\n\n"; + *out = tok.encode(text, true, /*parse_special=*/false); + } + if (out->empty()) { + RAD_ERR("diagnose: a workload prompt tokenised to nothing"); + return RAD_E_STATE; + } + return RAD_OK; + }; + auto user = [](const std::string& text) { + return json::array({ json{ { "role", "user" }, { "content", text } } }); + }; + + const int64_t ctx_limit = cfg_.max_ctx > 0 ? (int64_t)cfg_.max_ctx : (int64_t)meta_.n_ctx_train; + const int dec_tokens = cfg_.diagnose_tokens; + const int runs = cfg_.diagnose_runs; + if (cfg_.profile_ops) + warn("--profile-ops is on: it turns recorded passes off and adds barriers, so every step time " + "here is of a different engine than the one that serves"); + if (!cfg_.prefix_cache) + warn("--no-prefix-cache: requests do not pay the cache's lookups and publishing, which a " + "server with the cache on does"); + const double load0 = loadavg1(); + const unsigned ncpu = std::max(1u, std::thread::hardware_concurrency()); + if (load0 > (double)ncpu / 4) + warn("the host is busy (load average " + std::to_string(load0) + " on " + std::to_string(ncpu) + + " CPUs): the scheduler's planning between steps competes with it, and emission gaps show that"); + + /* A prompt of about `want` tokens: a document to summarise, sized by a first render and + * scaled, because the template adds tokens of its own and a vocabulary's characters a token is + * not known in advance. */ + auto sized_prompt = [&](int64_t want, uint32_t doc_salt, std::vector* out) -> int { + const std::string ask = "Summarise the document above in detail."; + int64_t chars = want * 4; + for (int pass = 0; pass < 4; ++pass) { + RAD_TRY(render(user(diag::synthetic_document(chars, doc_salt) + "\n\n" + ask), out)); + const int64_t got = (int64_t)out->size(); + if (got <= want && got >= want - std::max(8, want / 50)) return RAD_OK; + chars = std::max(16, (int64_t)((double)chars * (double)want / (double)got * 0.99)); + } + if ((int64_t)out->size() > want) { + RAD_ERR("diagnose: could not fit a prefill prompt in %lld tokens", (long long)want); + return RAD_E_STATE; + } + return RAD_OK; + }; + + const SamplingParams sp0 = sampling_defaults(); + uint64_t next_id = 1; + /* TEMPERATURE 1 FOR EVERY REQUEST, whatever the server's default: it is the temperature the + * model is served at, and draft acceptance -- what an adaptive draft depth is tuned on -- falls + * with temperature, so a greedy workload would tune it for traffic that never comes. top_k, + * top_p and min_p stay the server's. Parity does not need greedy: a fixed seed per request + * makes bit-identical logits sample identical tokens at any temperature. */ + const float kTemp = 1.0f; + + /* ---- one run: submit, wait, collect ---- + * `late` is submitted once every request of `early` has produced `late_after` tokens; the + * early requests are cancelled once every late one has produced `late_after` tokens too, so a + * stream started only to be interfered with does not decode to its limit. */ + auto run_set = [&](const std::string& name, diag::PhaseKind kind, const std::vector& early, + const std::vector& late, int late_after, diag::PhaseInput* in) -> int { + for (const auto* set : { &early, &late }) + for (const Job& jb : *set) + if ((int64_t)jb.prompt.size() + jb.max_tokens > ctx_limit) { + RAD_ERR("diagnose: %s needs %zu + %d tokens of context and the engine serves %lld", + name.c_str(), jb.prompt.size(), jb.max_tokens, (long long)ctx_limit); + return RAD_E_INVAL; + } + sched_.reset_prefix_cache(); + const std::vector cards0 = diag::sample_cards("", serving_bdfs); + const SchedMetrics before = sched_.metrics(); + const uint64_t seq0 = sched_.step_record_count(); + + std::vector> sinks; + auto submit = [&](const std::vector& jobs) -> int { + std::vector> reqs; + for (const Job& jb : jobs) { + sinks.push_back(std::make_unique((size_t)jb.max_tokens + 64)); + auto r = std::make_unique(); + r->id = next_id++; + r->prompt = jb.prompt; + r->max_tokens = jb.max_tokens; + r->ignore_eos = jb.ignore_eos; + r->sp = sp0; + if (jb.temp >= 0.0f) r->sp.temp = jb.temp; + r->sp.seed = 0x5eedull * 7919ull + r->id; /* fixed per request, so reruns sample alike */ + r->sink = sinks.back().get(); + sinks.back()->id = r->id; + reqs.push_back(std::move(r)); + } + std::vector rc(reqs.size(), RAD_OK); + /* All at once, under one hold of the queue: the streams are admitted into the same steps. */ + sched_.add_all(reqs.data(), reqs.size(), rc.data()); + for (int c : rc) + if (c < 0) { + RAD_ERR("diagnose: the scheduler refused a %s request: %s", name.c_str(), rad_strerror(c)); + return c; + } + return RAD_OK; + }; + auto produced_all = [&](size_t from, size_t to, int64_t n) { + for (size_t i = from; i < to; ++i) + if (!sinks[i]->done() && sinks[i]->n_produced() < n) return false; + return true; + }; + auto wait_until = [&](const std::function& ready) -> int { + while (!ready()) { + const int ls = loop_status_.load(std::memory_order_acquire); + if (ls < 0) return ls; + std::this_thread::sleep_for(std::chrono::milliseconds(1)); + } + return RAD_OK; + }; + + const int64_t t0 = steady_ns(); + RAD_TRY(submit(early)); + const size_t n_early = sinks.size(); + if (!late.empty()) { + RAD_TRY(wait_until([&] { return produced_all(0, n_early, late_after); })); + RAD_TRY(submit(late)); + RAD_TRY(wait_until([&] { return produced_all(n_early, sinks.size(), late_after); })); + for (size_t i = 0; i < n_early; ++i) + if (!sinks[i]->done()) sched_.cancel(sinks[i]->id); + } + for (size_t first = 0;;) { + while (first < sinks.size() && sinks[first]->done()) ++first; + if (first == sinks.size()) break; + const int ls = loop_status_.load(std::memory_order_acquire); + if (ls < 0) return ls; + sinks[first]->wait(200); + } + /* A sink finishes before the step that produced its last token is charged to the + * counters, so wait for the scheduler to go idle and its step count to stop moving. */ + for (uint64_t last = UINT64_MAX;;) { + const uint64_t c = sched_.step_record_count(); + const SchedMetrics m = sched_.metrics(); + if (c == last && m.running == 0 && m.queue_depth == 0) break; + last = c; + std::this_thread::sleep_for(std::chrono::milliseconds(20)); + } + const std::vector cards1 = diag::sample_cards("", serving_bdfs); + *in = diag::PhaseInput{}; + if (!serving_bdfs.empty()) + in->cards = { { "start", diag::card_samples_json(cards0) }, { "end", diag::card_samples_json(cards1) } }; + in->name = name; + in->kind = kind; + in->streams = (int)sinks.size(); + in->wall_ns = steady_ns() - t0; + in->before = before; + in->after = sched_.metrics(); + in->steps_lost = sched_.step_records(seq0, &in->steps); + int bad = 0; + for (size_t i = 0; i < sinks.size(); ++i) { + const server::Sink& s = *sinks[i]; + diag::RequestTiming t; + const int64_t base = s.t_start_ns(); + t.start_ns = base; + t.admitted_ns = s.t_admitted_ns() >= 0 ? base + s.t_admitted_ns() : -1; + t.first_ns = s.t_first_token_ns() >= 0 ? base + s.t_first_token_ns() : -1; + t.last_ns = s.t_last_token_ns() >= 0 ? base + s.t_last_token_ns() : -1; + t.tokens = s.n_produced(); + t.prompt = s.n_prompt(); + t.cached = s.n_cached(); + t.drafted = s.n_drafted(); + t.accepted = s.n_draft_accepted(); + { + std::vector toks((size_t)std::max(s.n_produced(), 0) + 1); + const size_t got = sinks[i]->read(toks.data(), toks.size()); + t.output.reserve(got); + for (size_t k = 0; k < got; ++k) t.output.push_back(toks[k].token); + } + const server::Finish f = s.finish_reason(); + const bool cancelled_by_us = i < n_early && !late.empty() && f == server::Finish::Cancelled; + t.ok = f == server::Finish::Length || f == server::Finish::Stop || cancelled_by_us; + t.stopped = f == server::Finish::Stop; + if (!t.ok) { + RAD_ERR("diagnose: a %s request did not finish: %s", name.c_str(), + s.why() ? s.why() : rad_strerror(s.status())); + ++bad; + } + in->requests.push_back(t); + sched_.reap(s.id); + } + int64_t cached = 0; + for (const auto& t : in->requests) cached += t.cached; + if (cached > 0) + problems.push_back(name + ": the prefix cache served " + std::to_string(cached) + + " prompt tokens, so this run measured a cache hit"); + if (in->steps_lost > 0) + problems.push_back(name + ": " + std::to_string(in->steps_lost) + + " step records were overwritten before they were read"); + RAD_INFO("diagnose: %s done in %.2f s", name.c_str(), (double)in->wall_ns / 1e9); + return bad ? RAD_E_STATE : RAD_OK; + }; + /* A measured point: one unmeasured run, then `runs` measured ones. `make` builds a run's jobs + * fresh each time, so every run has its own salt. */ + auto measure = [&](const std::string& name, diag::PhaseKind kind, + const std::function*)>& make, + std::vector* out) -> int { + diag::PhaseInput in; + std::vector jobs; + RAD_TRY(make(true, &jobs)); + RAD_TRY(run_set(name + "/warmup", kind, jobs, {}, 0, &in)); + for (int r = 0; r < runs; ++r) { + jobs.clear(); + RAD_TRY(make(false, &jobs)); + RAD_TRY(run_set(name + "/" + std::to_string(r + 1), kind, jobs, {}, 0, &in)); + out->push_back(diag::phase_report(in)); + } + return RAD_OK; + }; + + /* ---- categories ---- */ + std::vector corpus; + if (!cfg_.diagnose_corpus.empty()) { + std::string why; + if (diag::load_corpus(cfg_.diagnose_corpus, &corpus, &why) < 0) { + RAD_ERR("diagnose: %s", why.c_str()); + return RAD_E_INVAL; + } + } else { + corpus = diag::builtin_corpus(); + } + std::vector cats; + for (const auto& e : corpus) + if (std::find(cats.begin(), cats.end(), e.category) == cats.end()) cats.push_back(e.category); + json categories = json::array(); + for (const std::string& cat : cats) { + std::vector es; + for (const auto& e : corpus) + if (e.category == cat) es.push_back(&e); + std::vector rs; + /* A category's summary pools its prompts; whether a number repeats is a question about one + * prompt's runs, so each prompt is summarised on its own as well (diag::stability_report). */ + json per_prompt = json::array(); + for (size_t k = 0; k < es.size(); ++k) { + const diag::CorpusEntry& e = *es[k]; + const size_t from = rs.size(); + const int mt = e.max_tokens > 0 ? e.max_tokens : dec_tokens; + RAD_TRY(measure("category " + cat + " #" + std::to_string(k + 1), diag::PhaseKind::Decode, + [&](bool warm, std::vector* jobs) -> int { + Job jb; + RAD_TRY(render(e.messages, &jb.prompt)); + jb.max_tokens = warm ? std::min(mt, 32) : mt; + jb.ignore_eos = false; /* the model's own lengths: that is the category */ + jb.temp = kTemp; + jobs->push_back(std::move(jb)); + return RAD_OK; + }, + &rs)); + per_prompt.push_back({ { "prompt", (int64_t)k + 1 }, + { "summary", diag::summarize_runs(std::vector(rs.begin() + (std::ptrdiff_t)from, rs.end())) } }); + } + int64_t reqs = 0, stopped = 0; + for (const json& r : rs) { + reqs += r["requests"]["count"].get(); + stopped += r["requests"]["stopped_on_eos"].get(); + } + categories.push_back({ { "category", cat }, { "prompts", (int64_t)es.size() }, + { "requests", reqs }, { "stopped_on_eos", stopped }, + { "summary", diag::summarize_runs(rs) }, { "prompts_summary", per_prompt }, + { "draft_by_position", diag::pool_draft_positions(rs) }, { "runs", rs } }); + } + + /* ---- concurrency ---- */ + json concurrency = json::array(); + for (int n : cfg_.diagnose_concurrency) { + if (n > cfg_.max_seqs) { + warn("concurrency " + std::to_string(n) + " skipped: --max-num-seqs is " + std::to_string(cfg_.max_seqs)); + continue; + } + std::vector rs; + RAD_TRY(measure("concurrency " + std::to_string(n), diag::PhaseKind::Decode, + [&](bool warm, std::vector* jobs) -> int { + for (int s = 0; s < n; ++s) { + Job jb; + RAD_TRY(render(corpus[(size_t)s % corpus.size()].messages, &jb.prompt)); + jb.max_tokens = warm ? std::min(dec_tokens, 32) : dec_tokens; + jb.ignore_eos = true; /* every stream decodes the whole run */ + jb.temp = kTemp; + jobs->push_back(std::move(jb)); + } + return RAD_OK; + }, + &rs)); + concurrency.push_back({ { "streams", n }, { "summary", diag::summarize_runs(rs) }, + { "draft_by_position", diag::pool_draft_positions(rs) }, { "runs", rs } }); + } + + /* ---- prefill ---- */ + const int depth_tokens = std::min(dec_tokens, 64); + json prefill = json::array(); + uint32_t doc_salt = 1; + for (int want : cfg_.diagnose_prefill) { + if ((int64_t)want + depth_tokens > ctx_limit) { + warn("prefill " + std::to_string(want) + " skipped: the engine serves " + std::to_string(ctx_limit) + + " tokens of context"); + continue; + } + std::vector rs; + int64_t got = 0; + RAD_TRY(measure("prefill " + std::to_string(want), diag::PhaseKind::Prefill, + [&](bool warm, std::vector* jobs) -> int { + Job jb; + RAD_TRY(sized_prompt(want, doc_salt++, &jb.prompt)); + got = (int64_t)jb.prompt.size(); + jb.max_tokens = warm ? 1 : depth_tokens; + jb.ignore_eos = true; + jb.temp = kTemp; + jobs->push_back(std::move(jb)); + return RAD_OK; + }, + &rs)); + prefill.push_back({ { "requested_tokens", want }, { "prompt_tokens", got }, + { "summary", diag::summarize_runs(rs) }, { "runs", rs } }); + } + + /* ---- interference: a prompt arriving into running streams ---- */ + json interference = nullptr; + { + const int streams = (int)std::min(4, cfg_.max_seqs - 1); + /* The arriving prompt: the longest measured prefill up to 16k, so its idle TTFT is known. */ + const json* pick = nullptr; + for (const json& p : prefill) + if (p["requested_tokens"].get() <= 16384) pick = &p; + if (!pick && !prefill.empty()) pick = &prefill[0]; + if (streams < 1 || !pick) { + not_measured.push_back("a prompt arriving into running streams: needs --max-num-seqs of 2 or " + "more and a measured prefill length"); + } else { + const int want = (*pick)["requested_tokens"].get(); + /* The running streams must outlast the arrival's prefill; they are cancelled once it has + * decoded a little, so their limit only has to be out of reach. */ + const int run_tokens = (int)std::min(1 << 16, ctx_limit / 2); + const int after = 16; + std::vector rs; + for (int r = -1; r < runs; ++r) { + std::vector early, late(1); + for (int s = 0; s < streams; ++s) { + Job jb; + RAD_TRY(render(corpus[(size_t)s % corpus.size()].messages, &jb.prompt)); + jb.max_tokens = run_tokens; + jb.ignore_eos = true; + jb.temp = kTemp; + early.push_back(std::move(jb)); + } + RAD_TRY(sized_prompt(want, doc_salt++, &late[0].prompt)); + late[0].max_tokens = after; + late[0].ignore_eos = true; + late[0].temp = kTemp; + diag::PhaseInput in; + const std::string name = "interference/" + (r < 0 ? std::string("warmup") : std::to_string(r + 1)); + RAD_TRY(run_set(name, diag::PhaseKind::Decode, early, late, after, &in)); + if (r < 0) continue; + const diag::RequestTiming& a = in.requests.back(); + json x; + x["arrival_ttft_ms"] = a.admitted_ns >= 0 && a.first_ns >= 0 + ? json(std::round((double)(a.first_ns - a.admitted_ns) / 1e3) / 1e3) + : json(nullptr); + /* The running streams' steps only: the arrival's own decode would fill the gap. */ + x["interference"] = diag::interference_report(in.steps, a.admitted_ns, a.first_ns); + x["phase"] = diag::phase_report(in); + rs.push_back(x); + } + json idle = nullptr; + const json& ps = (*pick)["summary"]; + if (ps.contains("requests.ttft_ms.p50") && ps["requests.ttft_ms.p50"].is_object()) + idle = ps["requests.ttft_ms.p50"]["median"]; + interference = { { "streams", streams }, { "prompt_tokens", (*pick)["prompt_tokens"] }, + { "idle_ttft_ms", idle }, + { "summary", diag::summarize_paths(rs, { "/arrival_ttft_ms", + "/interference/typical_gap_ms", + "/interference/longest_gap_ms", + "/interference/stall_ratio" }) }, + { "runs", rs } }; + } + } + + /* ---- the report ---- */ + json rep; + { + /* The engine's /server_info is not spliced in: its container is the model's path and its + * control vector carries a file (diag::engine_report says what is kept). */ + const json info = json::parse(engine_info(), nullptr, /*allow_exceptions=*/false); + json eng = info.is_object() ? diag::engine_report(info) : json::object(); + eng["tp"] = cfg_.tp; + eng["backend"] = device_is_host() ? "host" : "device"; + eng["plan"] = cfg_.deterministic ? "deterministic (static placement)" : "dynamic placement"; + eng["max_num_seqs"] = cfg_.max_seqs; + eng["context"] = ctx_limit; + rep["engine"] = eng; + } + json w; + w["description"] = std::string(use_chat ? "chat-templated" : "raw-text") + " prompts, each salted at its head; " + + std::to_string(runs) + " measured run(s) a point after one unmeasured; categories from " + + (cfg_.diagnose_corpus.empty() ? std::string("the built-in corpus") + : std::string("the external corpus (its contents are in " + "workload.fingerprint)")) + + " up to " + std::to_string(dec_tokens) + " tokens, ending on EOS; concurrency streams " + + std::to_string(dec_tokens) + " tokens with ignore_eos; prefill then " + + std::to_string(depth_tokens) + " tokens of decode; temperature 1 with the server's " + "top_k/top_p/min_p and a fixed seed per request; prefix cache emptied before every run"; + w["sampling"] = { { "temp", kTemp }, { "top_k", sp0.top_k }, { "top_p", sp0.top_p }, { "min_p", sp0.min_p } }; + w["reasoning_effort"] = cfg_.reasoning_effort; + w["runs"] = runs; + w["tokens"] = dec_tokens; + { + /* What decides the prompts and the seeds: two reports with the same fingerprint ran the + * same requests in the same order. */ + json fp; + json c = json::array(); + for (const auto& e : corpus) c.push_back({ e.category, e.messages, e.max_tokens }); + fp["corpus"] = c; + fp["tokens"] = dec_tokens; + fp["runs"] = runs; + fp["concurrency"] = cfg_.diagnose_concurrency; + fp["prefill"] = cfg_.diagnose_prefill; + fp["max_num_seqs"] = cfg_.max_seqs; + fp["context"] = ctx_limit; + fp["chat_template"] = use_chat; + fp["reasoning_effort"] = cfg_.reasoning_effort; + fp["sampling"] = w["sampling"]; + w["fingerprint"] = diag::workload_fingerprint(fp); + } + rep["workload"] = w; + const double load1 = loadavg1(); + if (load1 > (double)ncpu / 4) + warn("the host was busy at the end (load average " + std::to_string(load1) + " on " + + std::to_string(ncpu) + " CPUs)"); + json envj; + envj["variables"] = env_snapshot(); + envj["loadavg_start"] = load0; + envj["loadavg_end"] = load1; + envj["cpus"] = ncpu; + rep["environment"] = envj; + rep["conditions"] = diag::conditions_report(facts0, rfacts, findings); + { + const json measured = { { "categories", categories }, { "concurrency", concurrency }, + { "prefill", prefill }, { "interference", interference } }; + rep["stability"] = diag::stability_report(measured); + for (const json& u : rep["stability"]["unstable"]) { + char b[256]; + std::snprintf(b, sizeof b, "%s: %s spread %.1f%% over %s runs (median %s), above %.0f%%", + u["point"].get().c_str(), u["metric"].get().c_str(), + u["spread_pct"].get(), u["runs"].dump().c_str(), u["median"].dump().c_str(), + diag::kMaxSpreadPct); + warn(b); + } + rep["thermal"] = diag::thermal_report(measured); + for (const json& w : rep["thermal"]["warnings"]) warn(w.get()); + } + rep["reproducibility"] = repro; + rep["verdict"] = problems.empty() ? std::string("valid") : std::string("NOT A MEASUREMENT -- see problems"); + rep["problems"] = problems; + for (const auto& p : problems) warnings.push_back(p); + rep["warnings"] = warnings; + rep["categories"] = categories; + rep["concurrency"] = concurrency; + rep["prefill"] = prefill; + rep["interference"] = interference; + rep["not_measured"] = not_measured; + + bool parity_ok = true; + if (!cfg_.diagnose_baseline.empty()) { + std::ifstream f(cfg_.diagnose_baseline); + const json base = json::parse(f, nullptr, /*allow_exceptions=*/false); + std::string why; + json cmp; + if (!f.is_open() || base.is_discarded()) { + why = "the baseline file is not readable JSON"; + } else if (diag::compare_outputs(rep, base, &cmp, &why) == RAD_OK) { + cmp["baseline"] = "an earlier report"; + rep["parity"] = cmp; + parity_ok = cmp["verdict"] == "identical" && cmp["acceptance_verdict"] == "no drop"; + RAD_INFO("diagnose: parity %s, %lld of %lld requests identical; draft acceptance: %s", + cmp["verdict"].get().c_str(), (long long)cmp["identical"].get(), + (long long)cmp["compared"].get(), cmp["acceptance_verdict"].get().c_str()); + } + if (!why.empty()) { + rep["parity"] = { { "baseline", "an earlier report" }, + { "verdict", "not compared: " + why } }; + parity_ok = false; + RAD_ERR("diagnose: %s", why.c_str()); + } + } + + const fs::path dir(cfg_.diagnose); + { + std::ofstream f(dir / "diagnose.json"); + f << rep.dump(2) << "\n"; + if (!f) { + RAD_ERR("diagnose: cannot write %s", (dir / "diagnose.json").c_str()); + return RAD_E_IO; + } + } + { + std::ofstream f(dir / "diagnose.md"); + f << diag::render_markdown(rep); + if (!f) { + RAD_ERR("diagnose: cannot write %s", (dir / "diagnose.md").c_str()); + return RAD_E_IO; + } + } + RAD_INFO("diagnose: report in %s", (dir / "diagnose.md").c_str()); + return problems.empty() && parity_ok ? RAD_OK : RAD_E_STATE; +} + +} /* namespace rad */ diff --git a/core/engine_draft.cpp b/core/engine_draft.cpp index 9a2e1aa5..b516b789 100644 --- a/core/engine_draft.cpp +++ b/core/engine_draft.cpp @@ -215,7 +215,7 @@ int Engine::tree_compact(int rows) { const int64_t row = bits > 0 ? b->shape[3] * bits / 8 : 0; int32_t layers = 0; for (int32_t s : b->layer_slot) layers += s >= 0; - if (row <= 0 || row % 16 || (bits != 8 && bits != 16 && bits != 32) || + if (row <= 0 || row % 4 || (bits != 8 && bits != 16 && bits != 32) || (b->bytes && (int64_t)layers * b->layer_stride > b->bytes)) { RAD_ERR("speculation: KV group %zu's cache (%s, %lld-byte rows) is not one a tree's " "acceptance can move", g, rad_dtype_name(b->dtype), (long long)row); diff --git a/core/engine_priv.h b/core/engine_priv.h index 641624af..e5f2fd2a 100644 --- a/core/engine_priv.h +++ b/core/engine_priv.h @@ -113,4 +113,5 @@ struct TierPump { * still hold the previous step's values when the step loop dumps. */ void dump_buffers(Ctx& ctx, int step, const char* phase = ""); + } /* namespace rad */ diff --git a/core/fleet/config.cpp b/core/fleet/config.cpp index 4762d077..17af664f 100644 --- a/core/fleet/config.cpp +++ b/core/fleet/config.cpp @@ -403,10 +403,12 @@ int Reader::read_scheduler(const Item& sec, FleetConfig* out) { if (k == "load-timeout") s = duration(it, &out->load_timeout_ms); else if (k == "drain-timeout") s = duration(it, &out->drain_timeout_ms); else if (k == "keepalive") s = duration(it, &out->keepalive_ms); + else if (k == "stuck-exit") s = duration(it, &out->stuck_exit_ms); else if (k == "warm-up") s = boolean(it, &out->warm_up); else { return fail(it.node, "scheduler." + k + " is not a scheduler key" + - suggest(k, { "load-timeout", "drain-timeout", "keepalive", "warm-up" })); + suggest(k, { "load-timeout", "drain-timeout", "keepalive", + "stuck-exit", "warm-up" })); } if (s < 0) return s; } @@ -834,6 +836,7 @@ void print_reference(FILE* to) { " load-timeout: DURATION how long a request waits for its model (default 120s)\n" " drain-timeout: DURATION how long a model being evicted may finish requests (30s)\n" " keepalive: DURATION SSE comment interval while a request waits (10s)\n" + " stuck-exit: DURATION a device stuck this long ends the process (60s; 0 never)\n" " warm-up: true|false fill free VRAM, then host RAM, with models at start (true)\n" "\ndefaults: any model key, merged under every model\n" "\nmodels:\n" diff --git a/core/fleet/config.h b/core/fleet/config.h index c23fa807..f87ea946 100644 --- a/core/fleet/config.h +++ b/core/fleet/config.h @@ -104,6 +104,9 @@ struct FleetConfig { int64_t load_timeout_ms = 120000; int64_t drain_timeout_ms = 30000; int64_t keepalive_ms = 10000; + /* A device that has advanced nothing for this long ends the process, so a restart policy can + * bring the server back (dev_stuck_exit_ms); 0 never. */ + int64_t stuck_exit_ms = 60000; /* Once the listener is open and nothing waits, unpinned models load one at a time into free * VRAM and park to host memory and the disk tier as later ones displace them, so a first * request finds its model parked rather than cold (docs/MULTIMODEL.md §8.6). */ diff --git a/core/fleet/fleet.cpp b/core/fleet/fleet.cpp index 99a4d465..430616b8 100644 --- a/core/fleet/fleet.cpp +++ b/core/fleet/fleet.cpp @@ -142,6 +142,23 @@ double sysfs_number(const std::string& path) { return f >> v ? v : -1; } +/* A card's temperature in millidegrees: the sensor its driver labels `junction`, else temp1. amdgpu + * labels three, edge (temp1), junction and mem, and throttles on the junction, the hottest spot on + * the die: under a decode load an R9700 read 56 C at the edge and 75-77 C at the junction. A driver + * that labels none, or no junction, keeps temp1. -1 when neither can be read. */ +double card_temp_mc(const std::string& hwmon) { + for (int i = 1; i <= 8; ++i) { + const std::string t = hwmon + "/temp" + std::to_string(i); + std::ifstream f(t + "_label"); + std::string label; + if (!(f >> label)) continue; + if (label != "junction") continue; + if (const double mc = sysfs_number(t + "_input"); mc >= 0) return mc; + break; + } + return sysfs_number(hwmon + "/temp1_input"); +} + /* What the driver reports of a card right now: busy share, power and temperature, on the routes of * a dashboard being watched and nowhere on a request's path. A card that reports none adds none. */ void card_telemetry(int card, json& o) { @@ -156,7 +173,7 @@ void card_telemetry(int card, json& o) { double uw = sysfs_number(hp + "/power1_average"); if (uw < 0) uw = sysfs_number(hp + "/power1_input"); if (uw >= 0) o["power_w"] = uw / 1e6; - if (const double mc = sysfs_number(hp + "/temp1_input"); mc >= 0) o["temp_c"] = mc / 1000.0; + if (const double mc = card_temp_mc(hp); mc >= 0) o["temp_c"] = mc / 1000.0; break; } } @@ -502,6 +519,7 @@ private: Fleet::Fleet(FleetConfig fc) : fc_(std::move(fc)), front_(transport_options(fc_), fc_.keepalive_ms) { + dev_stuck_exit_ms.store(fc_.stuck_exit_ms, std::memory_order_relaxed); bool any = false; int64_t head = 0; for (const ModelEntry& e : fc_.models) { @@ -2301,6 +2319,7 @@ std::string Fleet::reload() { front_.update(e.name, e.aliases, nf.load_timeout_ms, required); } fc_ = std::move(nf); + dev_stuck_exit_ms.store(fc_.stuck_exit_ms, std::memory_order_relaxed); for (const ModelEntry& e : fc_.models) if (e.pin) demand(e.name); RAD_INFO("reload: %s applied, %zu model(s)", fc_.path.c_str(), fc_.models.size()); diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 1ca7ca74..f02161b1 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -347,6 +347,7 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) { * pass through in the free-form list. */ const std::string a = out->arch; if (a == "hy_v3") out->arch = "hyv3"; + if (a == "bailingmoe3") out->arch = "bailinghybrid"; auto gi = [&](const char* suffix, int64_t dflt) -> int64_t { int64_t v = 0; return g.get_i64(a + "." + suffix, &v) ? v : dflt; @@ -443,6 +444,57 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) { out->kv("attention_bias", "0"); out->kv("mlp_bias", "0"); } + if (a == "bailingmoe3") { + /* Ling 3.0 (the arch alias above): the release GGUF spells the family's keys + * bailingmoe3.*, and the plugin (arch/bailing_hybrid) reads them as the checkpoint's + * config.json names, so the reader re-spells them here and one plugin serves both + * formats. eps and rope_theta take the generic paths above. Four of the family's + * design choices the GGUF does not carry are Ling 3.0's, stated as constants. */ + if (gi("kda.head_dim", 0) <= 0 || gi("rope.dimension_count", 0) <= 0 || + gi("attention.key_length_mla", 0) <= gi("rope.dimension_count", 0)) + return RAD_E_FORMAT; + out->kv("num_attention_heads", fmt("%lld", (long long)m.n_head)); + /* The typed head_dim the generic pass fell back to (the MLA query width) is not the + * KDA head the plugin asserts; rad-convert publishes the typed fields before the kv + * table, and lookups take the first row, so the typed field must carry the 128. */ + out->m.head_dim = (int)gi("kda.head_dim", 0); + out->kv("head_dim", fmt("%lld", (long long)gi("kda.head_dim", 0))); + /* The GGUF's key_length_mla is the full query (nope + rotary); the plugin's + * qk_nope_head_dim is the rotary part subtracted. */ + out->kv("qk_nope_head_dim", + fmt("%lld", (long long)(gi("attention.key_length_mla", 0) - gi("rope.dimension_count", 0)))); + out->kv("qk_rope_head_dim", fmt("%lld", (long long)gi("rope.dimension_count", 0))); + out->kv("v_head_dim", fmt("%lld", (long long)gi("attention.value_length_mla", 0))); + out->kv("kv_lora_rank", fmt("%lld", (long long)gi("attention.kv_lora_rank", 0))); + out->kv("q_lora_rank", fmt("%lld", (long long)gi("attention.q_lora_rank", 0))); + out->kv("num_experts", fmt("%lld", (long long)m.n_expert)); + out->kv("num_experts_per_tok", fmt("%lld", (long long)m.n_expert_used)); + out->kv("n_group", fmt("%lld", (long long)gi("expert_group_count", 0))); + out->kv("topk_group", fmt("%lld", (long long)gi("expert_group_used_count", 0))); + out->kv("moe_intermediate_size", fmt("%lld", (long long)gi("expert_feed_forward_length", 0))); + out->kv("moe_shared_expert_intermediate_size", + fmt("%lld", (long long)gi("expert_shared_feed_forward_length", 0))); + out->kv("num_shared_experts", fmt("%lld", (long long)m.n_expert_shared)); + out->kv("intermediate_size", fmt("%lld", (long long)m.n_ff)); + out->kv("first_k_dense_replace", fmt("%lld", (long long)gi("leading_dense_block_count", 0))); + out->kv("short_conv_kernel_size", fmt("%lld", (long long)gi("ssm.conv_kernel", 0))); + out->kv("kda_lower_bound", fmt("%.17g", gf("kda.gate_lower_bound", 0.0))); + out->kv("routed_scaling_factor", fmt("%.17g", gf("expert_weights_scale", 1.0))); + out->kv("norm_topk_prob", fmt("%lld", (long long)gi("expert_weights_norm", 0))); + out->kv("kda_safe_gate", fmt("%lld", (long long)gi("kda.safe_gate", 0))); + out->kv("layer_group_size", "4"); + out->kv("no_kda_lora", "1"); + out->kv("rope_interleave", "1"); + out->kv("gated_attention_proj_granularity_type", "head_wise"); + out->kv("num_nextn_predict_layers", "0"); + /* The plugin picks its checkpoint names from this: the GGUF spells the family's tensors + * blk. and ssm. names (and carries the layouts bailingmoe3_layouts rebuilds), the safetensors + * their config.json spellings. */ + out->kv("gguf_source", "1"); + std::string gating = "sigmoid"; + g.get_str("bailingmoe3.expert_gating_func", &gating); + out->kv("score_function", gating); + } /* Everything else, stringified, for the plugin. Arrays are summarised (small integer arrays * spelled out); tokenizer keys are skipped, since the vocab has its own section. */ @@ -497,7 +549,9 @@ int Checkpoint::open_gguf(const std::string& path) { index_.emplace(s.name, tensors_.size()); tensors_.push_back(std::move(s)); } - return meta_from_gguf(gguf_, &meta_); + RAD_TRY(meta_from_gguf(gguf_, &meta_)); + if (meta_.arch == "bailinghybrid") RAD_TRY(bailingmoe3_layouts()); + return RAD_OK; } int Checkpoint::add_shard(const std::string& p, const std::string& prefix, @@ -557,6 +611,7 @@ int shard_list(const std::string& dir, const std::string& index, bool index_give } /* namespace */ + /* A JSON file flattened under `prefix`; absent is not an error when `optional`. */ static int meta_merge_json_file(const std::string& path, const std::string& prefix, bool optional, MetaOwn* out) { @@ -1382,10 +1437,13 @@ void Checkpoint::detect_import() { "; it is read in groups of 16"; if (algos.empty() && import_why_.empty()) import_why_ = "ModelOpt's quantization_config names no quant_algo"; + /* W4A16_NVFP4 is the same NVFP4 weight with bf16 activations, which is what this reader + * serves either way: activations are quantised from their own values, never from a stored + * input scale. NVIDIA's Muse Glimmer release states it per layer beside FP8. */ for (const std::string& a : algos) - if (a != "NVFP4" && a != "FP8" && import_why_.empty()) - import_why_ = "ModelOpt's quant_algo '" + a + "' is not one this reads; NVFP4 " - "and FP8 (per tensor), alone or per layer, are"; + if (a != "NVFP4" && a != "W4A16_NVFP4" && a != "FP8" && import_why_.empty()) + import_why_ = "ModelOpt's quant_algo '" + a + "' is not one this reads; NVFP4, " + "W4A16_NVFP4 and FP8 (per tensor), alone or per layer, are"; if (import_why_.empty()) import_ = Import::ModelOpt; else import_why_ = "modelopt: " + import_why_; } else if (qm == "paroquant") { @@ -2970,9 +3028,17 @@ namespace { /* ---------------------------------------------------------------- GGUF block types * * ggml block types decodable to f32. Their geometry lives in core/text; decoding lives here, where - * weights are read. Q4_K and Q6_K are the K-quants this HYV3 GGUF adapter needs. */ + * weights are read. Q4_K, Q5_K and Q6_K are the K-quants the GGUF releases ship, IQ4_NL the + * non-linear 4-bit. */ enum { GGML_F32 = 0, GGML_F16 = 1, GGML_Q4_0 = 2, GGML_Q4_1 = 3, GGML_Q5_0 = 6, GGML_Q5_1 = 7, - GGML_Q8_0 = 8, GGML_Q4_K = 12, GGML_Q6_K = 14, GGML_BF16 = 30 }; + GGML_Q8_0 = 8, GGML_Q4_K = 12, GGML_Q5_K = 13, GGML_Q6_K = 14, GGML_BF16 = 30, + GGML_IQ4_NL = 20 }; + +/* IQ4_NL's non-linear levels (llama.cpp's kvalues_iq4nl), one per 4-bit code. */ +static const int8_t kIq4NlLevels[16] = { + -127, -104, -83, -65, -49, -35, -22, -10, 1, 13, 25, 38, 53, 69, 89, 113 +}; + int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) { auto half = [&](const uint8_t* q) { uint16_t h; std::memcpy(&h, q, 2); return rad_f16_to_f32(h); }; @@ -3032,13 +3098,7 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) { const uint8_t* qs = p + 16; for (int j = 0; j < 8; ++j) { uint32_t sc, mn; - if (j < 4) { - sc = scales[j] & 63u; - mn = scales[j + 4] & 63u; - } else { - sc = (scales[j + 4] & 15u) | ((uint32_t)(scales[j - 4] >> 6) << 4); - mn = (scales[j + 4] >> 4) | ((uint32_t)(scales[j] >> 6) << 4); - } + ggml_planes::k4_scale_min(j, scales, &sc, &mn); const float ds = d * (float)sc, ms = dmin * (float)mn; for (int l = 0; l < 32; ++l) { const int v = j * 32 + l; @@ -3049,7 +3109,33 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) { } } return RAD_OK; + case GGML_Q5_K: + /* block: d, dmin, scales[12], qh[32], qs[128]. The fifth bit of value v is bit + * (v/64)*2 + (v%64)/32 of qh's byte (v/64)*32 + v%32. */ + for (int64_t b = 0; b < n / 256; ++b, p += 176) { + const float d = half(p), dmin = half(p + 2); + const uint8_t* scales = p + 4; + const uint8_t* qh = p + 16; + const uint8_t* qs = p + 48; + for (int j = 0; j < 256; j += 64) { + const int hb = j / 64; + const uint32_t u1 = 1u << (2 * hb), u2 = 1u << (2 * hb + 1); + uint32_t sc1, m1, sc2, m2; + ggml_planes::k4_scale_min(j / 32, scales, &sc1, &m1); + ggml_planes::k4_scale_min(j / 32 + 1, scales, &sc2, &m2); + const float d1 = d * (float)sc1, m1f = dmin * (float)m1; + const float d2 = d * (float)sc2, m2f = dmin * (float)m2; + const uint8_t* ql = qs + (j / 2); + /* The 32 qh bytes are shared across all four 64-blocks; only the mask moves. */ + for (int l = 0; l < 32; ++l) + dst[b * 256 + j + l] = d1 * (float)((ql[l] & 0xF) + ((qh[l] & u1) ? 16 : 0)) - m1f; + for (int l = 0; l < 32; ++l) + dst[b * 256 + j + 32 + l] = d2 * (float)((ql[l] >> 4) + ((qh[l] & u2) ? 16 : 0)) - m2f; + } + } + return RAD_OK; case GGML_Q6_K: + /* block: ql[128], qh[64], scales[16], d. */ for (int64_t b = 0; b < n / 256; ++b, p += 210) { const uint8_t* ql = p; const uint8_t* qh = p + 128; @@ -3064,6 +3150,16 @@ int ggml_rows_f32(uint32_t type, const uint8_t* p, int64_t n, float* dst) { } } return RAD_OK; + case GGML_IQ4_NL: + for (int64_t b = 0; b < n / 32; ++b, p += 18) { + const float d = half(p); + const uint8_t* qs = p + 2; + for (int j = 0; j < 16; ++j) { + dst[b * 32 + j] = d * (float)kIq4NlLevels[qs[j] & 0x0F]; + dst[b * 32 + j + 16] = d * (float)kIq4NlLevels[qs[j] >> 4]; + } + } + return RAD_OK; default: return RAD_E_UNSUPPORTED; } @@ -3433,6 +3529,141 @@ int ckpt_import_form(CkptWeight* w, const ImportForm& f, std::string* why) { return RAD_OK; } + +int Checkpoint::bailingmoe3_layouts() { + /* The release GGUF keeps layouts the plugin's names cannot spell through the row and slice + * maps. The MLA layers' latent projections are head-last: k_b [128, 512, heads] and + * v_b [512, 128, heads] (a 128-row k block and a 128-row v block a head), where the plugin + * reads one interleaved kv_b [heads * 2 * 128, 512] -- head h's k rows [2 * 128 * h, + * + 128), its v rows the next 128. The MoE layers' routed stacks are expert-last (gate and + * up [ff, emb, E], down [emb, ff, E]); the reader's fastest-first flip orients them, and + * the block's split-stacked source slices one expert off the flipped [E, ...] stack, so + * they stay where they are. Everything the flip already hands over in the plugin's + * orientation (the shared expert, the KDA and the norms) needs only a name, which the + * plugin takes from the gguf_source meta. */ + const int64_t n_layer = meta_.m.n_layers; + const char* grp_s = meta_.get("layer_group_size"); + const int64_t group = grp_s ? std::stoll(grp_s) : 4; + const char* dense_s = meta_.get("first_k_dense_replace"); + const int64_t dense = dense_s ? std::stoll(dense_s) : 1; + const char* heads_s = meta_.get("num_attention_heads"); + const int64_t heads = heads_s ? std::stoll(heads_s) : 16; + const char* latent_s = meta_.get("kv_lora_rank"); + const int64_t latent = latent_s ? std::stoll(latent_s) : 512; + const char* ff_s = meta_.get("moe_intermediate_size"); + const int64_t ff = ff_s ? std::stoll(ff_s) : 512; + /* The experts' third axis is the embedding width, not the dense feed-forward's. */ + const int64_t emb = meta_.m.n_embd; + const char* nexp_s = meta_.get("num_experts"); + const int64_t n_expert = nexp_s ? std::stoll(nexp_s) : 0; + if (n_layer < 1 || group < 2 || heads < 1 || latent < 1 || ff < 1 || emb < 1) + return RAD_E_FORMAT; + + /* Decode a whole source tensor to f32: a block type row by row, a plain one a copy. */ + auto whole = [&](const SrcTensor* t, std::vector& dst) -> int { + const int64_t n = t->numel(); + dst.resize((size_t)n); + return piece_f32(*t, 0, n, dst.data()); + }; + auto add = [&](const std::string& name, std::vector shape, + std::vector&& v) -> int { + if (index_.count(name)) return RAD_OK; /* the checkpoint already spells it */ + SrcTensor s; + s.name = name; + s.rad_dtype = RAD_F32; + s.shape = std::move(shape); + s.owned = std::move(v); + s.data = s.owned.data(); + s.bytes = (int64_t)(s.owned.size() * sizeof(float)); + index_.emplace(s.name, tensors_.size()); + tensors_.push_back(std::move(s)); + return RAD_OK; + }; + + /* The exporter's ssm_a is exp(A_log) (llama.cpp's bailingmoe3 modify_tensors); the KDA + * kernel exponentiates internally, so the container wants the log values back. */ + for (int64_t l = 0; l < n_layer; ++l) { + if ((l + 1) % group == 0) continue; /* the MLA layers carry no ssm_a */ + const SrcTensor* sa = find(fmt("blk.%lld.ssm_a", (long long)l)); + if (!sa) continue; + std::vector a3, raw; + RAD_TRY(whole(sa, a3)); + raw.resize(a3.size()); + for (size_t i = 0; i < a3.size(); ++i) + raw[i] = std::logf(a3[i] > 0.0f ? a3[i] : 1.0f); + RAD_TRY(add(fmt("blk.%lld.ssm_a_raw", (long long)l), sa->shape, std::move(raw))); + } + + for (int64_t l = 1; l < n_layer; ++l) { + if ((l + 1) % group) continue; /* the MLA layers */ + const std::string kn = fmt("blk.%lld.attn_k_b.weight", (long long)l); + const std::string vn = fmt("blk.%lld.attn_v_b.weight", (long long)l); + const SrcTensor* k = find(kn); + const SrcTensor* v = find(vn); + if (!k || !v) continue; + if (k->shape.size() != 3 || v->shape.size() != 3 || k->shape[0] != heads || + k->shape[1] != latent || k->shape[2] != 128 || v->shape[0] != heads || + v->shape[1] != 128 || v->shape[2] != latent) + return RAD_E_SHAPE; + std::vector k3, v3, fused; + RAD_TRY(whole(k, k3)); + RAD_TRY(whole(v, v3)); + fused.assign((size_t)(heads * (2 * 128) * latent), 0.0f); + for (int64_t h = 0; h < heads; ++h) + for (int64_t d = 0; d < 128; ++d) { + /* k_b's head block [latent, 128] transposed into the 128 k rows. */ + for (int64_t l2 = 0; l2 < latent; ++l2) + fused[((h * 2 + 0) * 128 + d) * latent + l2] = k3[((h * latent + l2) * 128) + d]; + /* v_b's head block [128, latent] already runs its v rows. */ + std::memcpy(&fused[((h * 2 + 1) * 128 + d) * latent], + &v3[((h * 128 + d) * latent)], (size_t)latent * sizeof(float)); + } + RAD_TRY(add(fmt("blk.%lld.attn_kv_b.weight", (long long)l), + { heads * 2 * 128, latent }, std::move(fused))); + /* q_b is one [heads * (nope + rope), q_lora] matrix the plugin row-maps; a quantised + * source cannot be row-mapped, so split it into the plain nope and rope blocks. The + * per-head boundary comes from the meta the reader republished, so the split only runs + * when the geometry is the one the plugin will consume. */ + const char* nps = meta_.get("qk_nope_head_dim"), *rps = meta_.get("qk_rope_head_dim"); + const int64_t qn = nps ? std::stoll(nps) : 0, qr = rps ? std::stoll(rps) : 0; + const SrcTensor* qb = find(fmt("blk.%lld.attn_q_b.weight", (long long)l)); + if (qb && qb->shape.size() == 2 && qb->shape[1] > 0 && qn > 0 && qr > 0 && + qb->shape[0] == heads * (qn + qr)) { + const int64_t ql = qb->shape[1], w = qn + qr; + std::vector q3, nblk, rblk; + RAD_TRY(whole(qb, q3)); + nblk.assign((size_t)(heads * qn) * ql, 0.0f); + rblk.assign((size_t)(heads * qr) * ql, 0.0f); + for (int64_t h = 0; h < heads; ++h) { + std::memcpy(&nblk[(h * qn) * ql], &q3[(h * w) * ql], (size_t)(qn * ql) * sizeof(float)); + std::memcpy(&rblk[(h * qr) * ql], &q3[(h * w + qn) * ql], (size_t)(qr * ql) * sizeof(float)); + } + RAD_TRY(add(fmt("blk.%lld.attn_q_b_nope.weight", (long long)l), { heads * qn, ql }, std::move(nblk))); + RAD_TRY(add(fmt("blk.%lld.attn_q_b_rope.weight", (long long)l), { heads * qr, ql }, std::move(rblk))); + } + } + for (int64_t l = dense; l < n_layer; ++l) { + if (n_expert < 1) continue; + /* The routed stacks stay where they are: the block's split-stacked source + * (gate, up, down per expert, a dim-0 slice each) slices the reader's flipped + * [E, ff, emb] / [E, emb, ff] tensors directly. Only the shared expert needs + * re-spelling under the block's prefix: copies, the reader's flip already + * orienting them. */ + const char* sh[3] = { "ffn_gate_shexp", "ffn_up_shexp", "ffn_down_shexp" }; + const char* shd[3] = { "mlp.shared_experts.gate_proj.weight", + "mlp.shared_experts.up_proj.weight", + "mlp.shared_experts.down_proj.weight" }; + for (int q = 0; q < 3; ++q) { + const SrcTensor* t = find(fmt("blk.%lld.%s.weight", (long long)l, sh[q])); + if (!t) continue; + std::vector v; + RAD_TRY(whole(t, v)); + RAD_TRY(add(fmt("blk.%lld.%s", (long long)l, shd[q]), t->shape, std::move(v))); + } + } + return RAD_OK; +} + int ckpt_plane_rows(const CkptWeight& w, int k, int64_t r0, int64_t nr, void* dst, std::string* why) { auto refuse = [&](int rc, std::string m) { diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 3ed6dd4c..de6496c9 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -49,6 +49,10 @@ struct SrcTensor { std::vector shape; /* row-major */ const void* data = nullptr; int64_t bytes = 0; + /* Owned payload for a derived tensor: a checkpoint's layout rebuilt at load time (the Ling + * GGUF's head-last k_b/v_b fused into the plugin's interleaved kv_b, its expert-last stacks + * regrouped per expert). When non-empty `data` points here and `rad_dtype` is RAD_F32. */ + std::vector owned; /* GPTQ-packed (auto_gptq's layout, shared by AutoRound's `auto_round:auto_gptq` export): * `data` is the qweight's int32 words [K * bits / 32, N], each packing 32 / bits codes along K * from the low bits up, unsigned with zero point 2^(bits-1). The tensor described is the @@ -220,6 +224,13 @@ private: int add_torch_files(); int open_gguf(const std::string& path); void detect_import(); + /* The Ling GGUF's layouts the plugin's names expect, rebuilt at load so the container's + * recipe never sees the source layout: the KDA layers' ssm_a (the exporter's exp(A_log)) + * logged back to ssm_a_raw, the MLA layers' head-last k_b and v_b fused into one + * interleaved kv_b, the quantised q_b split into the plugin's nope and rope blocks, and + * the shared experts re-spelled under the block's mlp.shared_experts prefix. The routed + * stacks stay where the reader's fastest-first flip leaves them. */ + int bailingmoe3_layouts(); enum Kind { None, Gguf, SafeT } kind_ = None; std::string path_, dir_, tok_dir_, meta_dir_; diff --git a/core/format/radfile.cpp b/core/format/radfile.cpp index e3c4ca2f..08b15d96 100644 --- a/core/format/radfile.cpp +++ b/core/format/radfile.cpp @@ -71,13 +71,72 @@ int RadFile::read_at(void* dst, int64_t bytes, int64_t off) const { return RAD_OK; } +bool rad_blob_range(const uint8_t* base, int64_t size, const void* p, int64_t n, + int64_t* off, int64_t* len) { + if (!base || size <= 0 || !p || n <= 0) return false; + const uintptr_t lo = (uintptr_t)base, a = (uintptr_t)p; + const uint64_t hi = (uint64_t)lo + (uint64_t)size, end = (uint64_t)a + (uint64_t)n; + if (a < lo || end > hi || end < (uint64_t)a) return false; /* outside, or wraps */ + if (off) *off = (int64_t)(a - lo); + if (len) *len = n; + return true; +} + +std::vector> rad_keep_complement( + int64_t tables, int64_t size, std::vector> keep) { + /* Clamp to the blob, drop empties, sort and merge: the caller may hand in one range per rank, + * and every rank publishes the same table. */ + std::vector> k; + k.reserve(keep.size()); + for (const auto& r : keep) { + const int64_t a = std::max(r.first, tables), b = std::min(r.first + r.second, size); + if (b > a) k.emplace_back(a, b); + } + std::sort(k.begin(), k.end()); + size_t m = 0; + for (size_t i = 0; i < k.size(); ++i) { + if (m && k[i].first <= k[m - 1].second) k[m - 1].second = std::max(k[m - 1].second, k[i].second); + else k[m++] = k[i]; + } + k.resize(m); + /* Whole pages only, so a page that holds kept bytes stays: a gap's start rounds up and its + * end rounds down (the blob's own end is the mapping's). */ + const int64_t pg = 4096; + std::vector> out; + auto gap = [&](int64_t a, int64_t b) { + a = (a + pg - 1) / pg * pg; + if (b < size) b = b / pg * pg; + if (b > a) out.emplace_back(a, b - a); /* (offset, bytes), as `keep` is written */ + }; + int64_t cur = tables; + for (const auto& r : k) { + if (r.first > cur) gap(cur, r.first); + cur = std::max(cur, r.second); + } + if (cur < size) gap(cur, size); + return out; +} + +int64_t RadFile::keep_cached(const void* p, int64_t n) { + int64_t off = 0, len = 0; + if (rad_blob_range(base_, size_, p, n, &off, &len) && + std::find(keep_.begin(), keep_.end(), std::make_pair(off, len)) == keep_.end()) + keep_.emplace_back(off, len); + int64_t kept = 0; + for (const auto& r : keep_) kept += r.second; + return kept; +} + void RadFile::drop_blob_cache() const { if (!base_ || !hdr_ || fd_ < 0) return; const int64_t tables = (int64_t)hdr_->data_off < size_ ? (int64_t)hdr_->data_off : size_; if (tables >= size_) return; - /* Unmap first, then drop the cache: the kernel cannot drop a page still mapped here. */ - ::madvise(base_ + tables, (size_t)(size_ - tables), MADV_DONTNEED); - ::posix_fadvise(fd_, (off_t)tables, (off_t)(size_ - tables), POSIX_FADV_DONTNEED); + /* Unmap first, then drop the cache: the kernel cannot drop a page still mapped here. Only the + * ranges that are not kept (keep_cached); with none kept this is the whole blob. */ + for (const auto& r : rad_keep_complement(tables, size_, keep_)) { + ::madvise(base_ + r.first, (size_t)r.second, MADV_DONTNEED); + ::posix_fadvise(fd_, (off_t)r.first, (off_t)r.second, POSIX_FADV_DONTNEED); + } } /* Advisory, with no madvise: the load reads with pread and never maps these pages. The one region diff --git a/core/format/radfile.h b/core/format/radfile.h index 8ce80a3c..3a9937b5 100644 --- a/core/format/radfile.h +++ b/core/format/radfile.h @@ -68,8 +68,14 @@ public: /* Drop the blob from the page cache and this process's page tables, so a container larger * than RAM does not leave the cache full of pages nothing will read. Only the blob: the tables - * are small and read constantly. Advisory; the kernel may decline. */ + * are small and read constantly. The ranges named to keep_cached() are left alone, on whole + * pages. Advisory; the kernel may decline either way. */ void drop_blob_cache() const; + /* Names [p, p + n) as read through the mapping for the engine's life (the mapped tier: an + * n-gram table), so no drop_blob_cache() frees its pages: a gather from dropped pages starts + * cold, from the drive. An address outside the container is ignored (a copy in RAM, or a + * table read from its own file). Returns the bytes now kept. */ + int64_t keep_cached(const void* p, int64_t n); /* Drop one range of the blob behind a single forward cursor. A buffered front-to-back read of * a container larger than RAM otherwise builds reclaim pressure that slows the read itself. @@ -153,6 +159,7 @@ private: std::string path_; uint8_t* base_ = nullptr; int64_t size_ = 0; + std::vector> keep_; /* keep_cached: (blob offset, bytes) */ int fd_ = -1; const RadFileHeader* hdr_ = nullptr; @@ -168,6 +175,21 @@ private: std::unordered_map by_name_; }; +/* The blob range [*off, *off + *len) a pointer covers, when it lies wholly inside the container + * [base, base + size): what a load records for the mapped tier. False when the address is not in + * the blob (a copy in RAM under `ngram-placement: ram`, or a table read from its own file under + * `disk=DIR`), where keeping it would name bytes that belong to something else. */ +bool rad_blob_range(const uint8_t* base, int64_t size, const void* p, int64_t n, + int64_t* off, int64_t* len); + +/* The ranges of [tables, size) a page-cache drop must free when `keep` stays: the complement of + * the keep ranges as (offset, bytes), the same convention `keep` uses. Page-rounded the way the + * drop needs it -- a gap's start rounds up and its end down, so a page holding kept bytes is never + * dropped. Unsorted, overlapping and out-of-range input is merged and clamped; a keep list covering + * the whole blob gives no ranges. */ +std::vector> rad_keep_complement( + int64_t tables, int64_t size, std::vector> keep); + /* ================================================================== writer */ /* Streaming writer: the blob is never held in RAM (a checkpoint may be 100 GB). The tables * (strings, directory, planes, encodings, vocab, profile) are in memory; ~50k directory rows for a diff --git a/core/gen/audio.h b/core/gen/audio.h index f649c408..4e25a6e2 100644 --- a/core/gen/audio.h +++ b/core/gen/audio.h @@ -71,6 +71,8 @@ struct AudioRequest { std::vector ref_audio; std::vector ref_cu; std::vector ref_frame; + /* Reference-direction guidance: the negative prompt's own map into the same clips. */ + std::vector neg_ref_frame; int64_t max_frames = 0; /* the most frames to make, >= 1 */ int32_t steps = 0; /* 0: the model's default */ float cfg = 0.0f; /* 0: the model's default */ diff --git a/core/gen/audio_driver.cpp b/core/gen/audio_driver.cpp index 07889f00..1405812c 100644 --- a/core/gen/audio_driver.cpp +++ b/core/gen/audio_driver.cpp @@ -292,7 +292,10 @@ int AudioDriver::submit(std::unique_ptr r, std::string* why) { if (r->cfg != 0.0f && !(r->cfg >= 1.0f)) return no("guidance_scale must be >= 1"); /* References: the clips the declaration allows, each a whole number of frames, and a frame * for every row that names one. */ - if (!r->ref_cu.empty() || !r->ref_frame.empty() || !r->ref_audio.empty()) { + if (!r->ref_cu.empty() || !r->ref_frame.empty() || !r->ref_audio.empty() || + !r->neg_ref_frame.empty()) { + if (nb_ == 2 && r->cfg != 0.0f && r->cfg != 1.0f && r->neg_ref_frame.empty()) + return no("voice cloning requires guidance_scale 1; reference CFG is not served"); const int64_t n_ref = (int64_t)r->ref_cu.size() - 1, hop = d.ref_hop; bool ok = d.ref_max > 0 && n_ref >= 1 && n_ref <= d.ref_max && r->ref_cu[0] == 0 && r->ref_cu.back() == (int64_t)r->ref_audio.size() && @@ -303,6 +306,10 @@ int AudioDriver::submit(std::unique_ptr r, std::string* why) { const int64_t frames = ok ? r->ref_cu.back() / hop : 0; for (int64_t t = 0; ok && t < T; ++t) ok = r->ref_frame[(size_t)t] >= -1 && r->ref_frame[(size_t)t] < frames; + if (ok && !r->neg_ref_frame.empty()) { + ok = nb_ == 2 && neg_own_ && (int64_t)r->neg_ref_frame.size() == Tn; + for (int32_t f : r->neg_ref_frame) ok = ok && f >= -1 && f < frames; + } if (!ok) return no(d.ref_max > 0 ? "the references do not fit this model: at most " + std::to_string(d.ref_max) + " clips of whole frames, " + @@ -707,12 +714,24 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { if (n_ref > 0) { std::memcpy(hptr(R_RAUD), q.ref_audio.data(), q.ref_audio.size() * 4); std::memcpy(hptr(R_RCU), q.ref_cu.data(), q.ref_cu.size() * 4); - std::memcpy(hptr(R_RFRM), q.ref_frame.data() + p0, (size_t)cb[0] * 4); reg_[R_RAUD].used = (int64_t)q.ref_audio.size() * 4; reg_[R_RCU].used = (int64_t)q.ref_cu.size() * 4; - reg_[R_RFRM].used = cb[0] * 4; h_rcu_ = q.ref_cu; h_rfrm_.assign(q.ref_frame.begin() + p0, q.ref_frame.begin() + p0 + cb[0]); + /* At guidance 1 the driver runs the conditional prompt in both branches. Its audio + * rows must be duplicated too, not silently turned into text in the second branch. */ + if (nb_ > 1) { + if (j.cfg == 1.0f) + h_rfrm_.insert(h_rfrm_.end(), q.ref_frame.begin() + p0, + q.ref_frame.begin() + p0 + cb[1]); + else if (!q.neg_ref_frame.empty()) + h_rfrm_.insert(h_rfrm_.end(), q.neg_ref_frame.begin() + p0, + q.neg_ref_frame.begin() + p0 + cb[1]); + else + h_rfrm_.resize((size_t)rows, -1); + } + std::memcpy(hptr(R_RFRM), h_rfrm_.data(), h_rfrm_.size() * 4); + reg_[R_RFRM].used = (int64_t)h_rfrm_.size() * 4; } if (upload() < 0) return nullptr; base_batches(rows, nb_, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch); @@ -721,6 +740,7 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { for (size_t r = 0; r < ranks_.size(); ++r) { out_[r].gen = RAD_GEN_PASS_PROMPT; RadAudioGenBatch& A = aout_[r]; + A.prompt_cu_h = cu; A.n_lane = 1; A.lane_h = h_lane_.data(); A.last_h = h_last_.data(); diff --git a/core/main.cpp b/core/main.cpp index ddd356eb..12feef00 100644 --- a/core/main.cpp +++ b/core/main.cpp @@ -58,11 +58,11 @@ int main(int argc, char** argv) { return 0; } - /* An offline mode (KL scoring, calibration) or the graph dump runs one engine to its end and - * serves nothing; every other configuration is served by the fleet. */ + /* An offline mode (KL scoring, calibration, the diagnose workload) or the graph dump runs one + * engine to its end and serves nothing; every other configuration is served by the fleet. */ bool offline = false; for (const rad::fleet::ModelEntry& m : fleet.models) - offline |= m.cfg.kld() || m.cfg.calib() || m.cfg.debug_graph; + offline |= m.cfg.kld() || m.cfg.calib() || m.cfg.diagnose_mode() || m.cfg.debug_graph; if (!offline) return rad::fleet::run(fleet); if (fleet.models.size() != 1) { RAD_ERR("%s: an offline mode or the graph dump runs one model; the file names %zu", diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index 3ec2baa7..41d1a10b 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -822,6 +822,22 @@ int64_t KVManager::total_blocks(int32_t g) const { int64_t KVManager::live_blocks(int32_t g) const { return (g >= 0 && g < (int32_t)live_.size()) ? live_[(size_t)g] : 0; } +int64_t KVManager::live_blocks_at(int32_t g, int64_t tokens) const { + if (g < 0 || g >= (int32_t)plans_.size()) return 0; + return plans_[(size_t)g].n_blocks - lent_blocks((size_t)g, tokens); +} +int64_t KVManager::straggler_mark(int32_t g) const { + if (g < 0 || g >= (int32_t)plans_.size()) return 0; + const int64_t top = held_top((size_t)g), per = bucket_blocks_[(size_t)g]; + const auto& h = held_hist_[(size_t)g]; + int64_t mark = top, best = 0, held = 0; + for (int64_t b = (top + per - 1) / per; b-- > 0;) { + held += h[(size_t)b]; + const int64_t gain = top - b * per - kStragglerCost * held; + if (gain > best) { best = gain; mark = b * per; } + } + return mark; +} int64_t KVManager::held_top_blocks(int32_t g) const { return (g >= 0 && g < (int32_t)plans_.size()) ? held_top((size_t)g) : 0; } diff --git a/core/mem/kv.h b/core/mem/kv.h index 1f4e3963..7dbc94a8 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -508,6 +508,18 @@ public: /* Blocks of a group the cache may hand out: the carve less the loan. */ int64_t live_blocks(int32_t group) const; + /* The same under a loan of `tokens`: the first block of the group that loan would take. A + * group that does not lend answers its whole carve. */ + int64_t live_blocks_at(int32_t group, int64_t tokens) const; + /* Where a group's stragglers start. A loan reaches down only to the highest held block, so a + * few held blocks high in the pool keep everything between them and the dense part of the + * cache from the expert slab. Giving up the held blocks at or above a mark m extends what + * can be lent by (held top - m) blocks at the cost of the blocks held there; the mark is the + * m that gains the most over kStragglerCost times that cost, to a bucket of held_hist_. The + * held top itself when no m gains anything: a pool held densely up to its top has no + * stragglers, and the edge of a dense part is never one. Rank 0 only. */ + int64_t straggler_mark(int32_t group) const; + static constexpr int64_t kStragglerCost = 16; /* ---------------- flex (docs/MULTIMODEL.md §6) ---------------- * diff --git a/core/mem/kvtier.cpp b/core/mem/kvtier.cpp index 1d779948..f5878395 100644 --- a/core/mem/kvtier.cpp +++ b/core/mem/kvtier.cpp @@ -356,8 +356,10 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector* out) { RAD_WARN("kv tiers: %lld entries (%lld tokens of context) got no host copy: the host " "tier (--prefix-cache-mib, %s, %lld tokens) is full of context used more " "recently or nearer the start of its conversation. They stay in VRAM only and " - "are prefilled again once VRAM gives them up; a larger --prefix-cache-mib holds " - "more. Counted in /sessions moved.held_back", + "are prefilled again once VRAM gives them up, which it does for a request that " + "needs the room, or where a few of them keep the expert loan from most of the " + "pool; a larger --prefix-cache-mib holds more. " + "Counted in /sessions moved.held_back", (long long)held, (long long)(held * cfg_.block_tokens), humanb(arena_.cap_bytes()).c_str(), (long long)(arena_.capacity() * cfg_.block_tokens)); @@ -375,6 +377,15 @@ void IdleTiers::take_clean(std::vector* out) { clean_q_.clear(); } +bool IdleTiers::no_copy_coming(const BlockHash& key) const { + std::lock_guard lk(mu_); + auto it = recs_.find(key); + if (it == recs_.end()) return false; + const Rec& r = it->second; + if (r.pending || r.doomed || r.tier != KVTier::Device || r.host_slot >= 0) return false; + return !r.queued || (wb_stuck_ && arena_.full()); +} + bool IdleTiers::droppable(const BlockHash& key) const { std::lock_guard lk(mu_); auto it = recs_.find(key); diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h index 5bd9b244..f8664090 100644 --- a/core/mem/kvtier.h +++ b/core/mem/kvtier.h @@ -156,6 +156,10 @@ public: void take_clean(std::vector* out); /* Host copy landed and no job out: the blocks can leave VRAM at no cost. */ bool droppable(const BlockHash& key) const; + /* In VRAM only with no host copy coming: none made or on its way, and either none asked for + * (a full arena refused it, Stats::held_back) or the queue it waits in has stopped because + * the arena is full of entries worth more. */ + bool no_copy_coming(const BlockHash& key) const; /* The cache released the blocks; the record becomes a host record on the host list. Its * snapshot stays in its store slot. */ void drop_commit(const BlockHash& key); diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index e044e605..12ad68f0 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -796,12 +796,13 @@ int64_t PrefixCache::trim_sparing(int64_t n_entries, return done; } -int64_t PrefixCache::drop_clean() { +int64_t PrefixCache::drop_clean(int64_t loan_goal) { if (!tiers_ || !kv_) return 0; drop_scratch_.clear(); tiers_->take_clean(&drop_scratch_); const uint64_t frees = kv_->seq_frees(); - if (frees != frees_seen_ || released_) { + const bool recheck = frees != frees_seen_ || released_; + if (recheck) { frees_seen_ = frees; released_ = false; for (const BlockHash& h : drop_wait_) { @@ -830,6 +831,53 @@ int64_t PrefixCache::drop_clean() { tiers_->drop_commit(h); ++n; } + return n + drop_stragglers(loan_goal, recheck); +} + +/* drop_clean's second half: resident entries with no host copy coming that are stragglers inside + * a loan of `loan_goal` tokens. One walk of the resident list, taken only while something is held + * above a group's mark, and then when a sequence has freed blocks (`recheck`) or the marks have + * moved since the last walk, a second or more ago. */ +int64_t PrefixCache::drop_stragglers(int64_t loan_goal, bool recheck) { + if (loan_goal <= 0 || !tiers_->host_on()) return 0; + const size_t ng = entry_groups_.size(); + strag_mark_.assign(2 * ng, 0); + bool any = false; + for (size_t k = 0; k < ng; ++k) { + const int32_t g = entry_groups_[k]; + const int64_t top = kv_->held_top_blocks(g); + const int64_t mark = !kv_->lendable(g) ? INT64_MAX + : std::max(kv_->straggler_mark(g), kv_->live_blocks_at(g, loan_goal)); + strag_mark_[k] = mark; + strag_mark_[ng + k] = top; + any = any || top > mark; + } + if (!any) return 0; + const uint64_t now = rad_mono_ns(); + if (!recheck && (strag_mark_ == strag_seen_ || now - strag_ns_ < 1000000000ull)) return 0; + strag_seen_ = strag_mark_; + strag_ns_ = now; + + int64_t n = 0; + for (auto it = lru_.begin(); it != lru_.end();) { + const BlockHash h = *it; + auto m = map_.find(h); + if (m == map_.end()) { ++it; continue; } + Entry& e = m->second; + bool above = false; + for (size_t k = 0; k < ng && k < e.blocks.size(); ++k) + above = above || e.blocks[k] >= strag_mark_[k]; + if (!above || held_.count(h) > 0 || shared_with_live(e) || !tiers_->no_copy_coming(h)) { + ++it; + continue; + } + release_blocks(e); + it = lru_.erase(it); + tiers_->forget(h); + map_.erase(m); + ++stats_.evictions; + ++n; + } return n; } diff --git a/core/mem/prefix.h b/core/mem/prefix.h index ff6190dc..10c9bbda 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -306,8 +306,17 @@ public: int64_t trim(int64_t n_entries); /* Give up every VRAM copy that costs nothing to drop: host copy landed and no running sequence * reading it. Used when the memory has a better use (the expert slab's loan). Entries still - * shared are retried after a sequence frees blocks. Returns how many entries left VRAM. */ - int64_t drop_clean(); + * shared are retried after a sequence frees blocks. Returns how many entries left VRAM. + * + * `loan_goal` is the loan the slab is short of, in tokens (0: none). An entry with no host + * copy coming (the host tier is full of context worth more) never becomes clean, and the + * loan reaches down only to the highest held block: a few such entries high in the pool keep + * the slab from everything below them for as long as the server runs. Where they are + * stragglers (KVManager::straggler_mark: giving them up lends at least sixteen blocks for + * each one lost) and stand inside `loan_goal`, they are forgotten, and their tokens are + * prefilled again if their conversation returns. Context that fills its part of the pool + * stays: there the cache is worth more than the loan it holds back. */ + int64_t drop_clean(int64_t loan_goal = 0); int64_t size() const { return (int64_t)map_.size(); } /* Entries holding blocks in the pool, as opposed to only a copy off the card. */ int64_t resident() const { return (int64_t)lru_.size(); } @@ -544,6 +553,11 @@ private: * sequence-free count then. They are rechecked only once that count moves. */ std::vector drop_wait_; std::vector drop_scratch_; + /* drop_stragglers: the marks and held tops it last walked the list for, and when. It walks + * again when a sequence frees blocks, or once they have moved and a second has passed. */ + std::vector strag_mark_, strag_seen_; + uint64_t strag_ns_ = 0; + int64_t drop_stragglers(int64_t loan_goal, bool recheck); uint64_t frees_seen_ = 0; /* hold(): keys per waiting request, and holders per key. A release also triggers a recheck * of drop_wait_. */ diff --git a/core/mem/vram_budget.cpp b/core/mem/vram_budget.cpp index b6f20f43..b0994eb2 100644 --- a/core/mem/vram_budget.cpp +++ b/core/mem/vram_budget.cpp @@ -152,6 +152,14 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg "or free the card.\n" : "Lower --gpu-headroom-mib, lower --max-num-batched-tokens (the arena scales with it), " "or free the card.\n"; + /* KL mode holds a whole-vocabulary row for every scored token and lends no pool back, so + * its fixed cost sits far above a serve's at the same flags. Without naming the split, the + * operator has no way to know which knob to turn. */ + const char* kld_hint = cfg.kld() + ? "KL mode holds a full-vocabulary logits row for every scored token and lends no pool " + "back: pass --gpu-headroom-mib and --host-pool-mib explicitly, and lower " + "--max-num-batched-tokens (the logits rows scale with it).\n" + : ""; b.report = fmt( "VRAM does not cover the fixed costs before a single pool is sized:\n" " card total %10s\n" @@ -169,6 +177,7 @@ static int resolve(Config& cfg, const std::vector& per_rank, VramBudg humanb(b.headroom).c_str(), humanb(b.arena).c_str(), humanb(b.staging).c_str(), humanb(b.queues).c_str(), b.n_queues, humanb(b.queue_bytes).c_str(), humanb(b.prefetch).c_str(), humanb(-b.claimable).c_str(), how); + if (*kld_hint) b.report += kld_hint; if (log) RAD_ERR("%s", b.report.c_str()); if (out) *out = b; return RAD_E_NOMEM; diff --git a/core/mm/mp4.cpp b/core/mm/mp4.cpp index 08548ea8..437aecf6 100644 --- a/core/mm/mp4.cpp +++ b/core/mm/mp4.cpp @@ -50,7 +50,15 @@ struct MemReader { int64_t pos = 0; }; -int mem_write(void* op, const uint8_t* buf, int n) { +/* avio_alloc_context's write_packet takes a const buffer from libavformat 61 and a mutable one + * before it; the callback is declared as the library at hand wants it. */ +#if LIBAVFORMAT_VERSION_MAJOR >= 61 +using WriteBuf = const uint8_t*; +#else +using WriteBuf = uint8_t*; +#endif + +int mem_write(void* op, WriteBuf buf, int n) { MemFile* f = static_cast(op); const int64_t end = f->pos + n; if (end > (int64_t)f->data.size()) f->data.resize((size_t)end); diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index 625c9599..1ab4f9c6 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -50,6 +50,11 @@ static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) { return std::strtol(v, nullptr, 10) != 0; } +/* Muse Glimmer's shipped processor config (processor.image_mean, processor.image_std), over the + * reference class's IMAGENET_STANDARD defaults. */ +static const float kMuseDefaultMean[3] = { 0.5f, 0.5f, 0.5f }; +static const float kMuseDefaultStd[3] = { 0.5f, 0.5f, 0.5f }; + int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) { /* Only the requested noncausal Mistral3/Ministral3 wrapper selects this new path. */ if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "mistral3") && @@ -303,6 +308,64 @@ int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) { } return RAD_OK; } + /* Meta's Muse Glimmer 30B: the vision tower states the patch geometry and the processor + * configs the token caps; the markers are numbered by config.json where they are numbered at + * all, and the vocabulary spells the rest (resolved at Processor::init). */ + if (mt && !std::strcmp(mt, "muse_glimmer_vision")) { + family = Family::MuseGlimmer; + patch = (int32_t)rad_meta_geti(&m, "vision_config.patch_size", 0); + temporal = (int32_t)rad_meta_geti(&m, "vision_config.patch_temporal", + rad_meta_geti(&m, "vision_config.temporal_patch_size", 0)); + merge = (int32_t)rad_meta_geti(&m, "vision_config.merge_size", + rad_meta_geti(&m, "vision_config.spatial_merge_size", 0)); + if (patch <= 0 || temporal <= 0 || merge <= 0) { + if (why) *why = "the container states no vision tower geometry (vision_config." + "patch_size, patch_temporal, merge_size)"; + return RAD_E_NOTFOUND; + } + tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1); + tok_video = (int32_t)rad_meta_geti(&m, "video_token_id", -1); + if (tok_image < 0 || tok_video < 0) { + if (why) *why = "the container states no media token ids (image_token_id, " + "video_token_id)"; + return RAD_E_NOTFOUND; + } + /* The markers: a container that numbers them wins; the rest the vocabulary resolves. */ + tok_start = (int32_t)rad_meta_geti(&m, "image_start_token_id", -1); + tok_end = (int32_t)rad_meta_geti(&m, "image_end_token_id", -1); + tok_video_start = (int32_t)rad_meta_geti(&m, "video_start_token_id", -1); + tok_video_end = (int32_t)rad_meta_geti(&m, "video_end_token_id", -1); + tok_video_sep = (int32_t)rad_meta_geti(&m, "video_frame_separator_token_id", -1); + /* The token caps, in merged tokens: one per picture and one per video frame. */ + max_image_tokens = (int32_t)rad_meta_geti(&m, "processor.image_processor.max_image_tokens", + 4096); + max_frame_rows = (int32_t)rad_meta_geti(&m, "processor.video_processor.max_video_frame_tokens", + 144); + max_frames = (int32_t)rad_meta_geti(&m, "processor.video_processor.num_frames", 96); + fps = rad_meta_getf(&m, "processor.video_processor.fps", 2.0); + min_frames = temporal; + /* The shipped checkpoints (mean and deviation 0.5) over the reference class's + * IMAGENET_STANDARD defaults: the config wins, as it does for every family. */ + if (!read_triple(m, "processor.image_mean", mean)) std::copy(std::begin(kMuseDefaultMean), + std::end(kMuseDefaultMean), mean); + if (!read_triple(m, "processor.image_std", stdv)) std::copy(std::begin(kMuseDefaultStd), + std::end(kMuseDefaultStd), stdv); + /* The pixel bands only have to be consistent for check(); the caps size by tokens. */ + const int64_t f2 = (int64_t)factor() * factor(); + image_min_pixels = video_min_pixels = f2; + image_max_pixels = std::max(f2, (int64_t)std::max(1, max_image_tokens) * f2); + video_max_pixels = std::max(f2, (int64_t)std::max(1, max_frame_rows) * f2); + std::string bad; + if (max_image_tokens < 1 || max_frame_rows < 1) + bad = "max_image_tokens and max_video_frame_tokens must be positive"; + if (bad.empty() && check(&bad) < 0) bad = "the container's Muse Glimmer processor " + "configuration is inconsistent: " + bad; + if (!bad.empty()) { + if (why) *why = bad; + return RAD_E_INVAL; + } + return RAD_OK; + } /* Gemma 4 12B ("unified") has no tower: its embedder takes a whole 48 x 48 pooling window as * one patch, so a patch is a row (merge 1), and its values are u / 255. The sizes are the * same: a window is 48 pixels a side either way. */ @@ -644,6 +707,125 @@ std::vector sample_frames_gemma4(const VideoInfo& info, double fps, int return idx; } +/* CPython's tuple hash (tuplehash, the xxHash-based combination of 3.8 and later) for the + * candidates' (grid height, grid width) pairs. Lane = hash(int) = the value itself. */ +static inline uint64_t py_tuple_hash(int64_t a, int64_t b) { + constexpr uint64_t P1 = 0x9E3779B185EBCA87ull, P2 = 0xC2B2AE3D27D4EB4Full, + P5 = 0x27D4EB2F165667C5ull; + uint64_t acc = P5; + for (int64_t v : { a, b }) { + acc += (uint64_t)v * P2; + acc = (acc << 31) | (acc >> 33); + acc *= P1; + } + acc += (uint64_t)2 ^ (P5 ^ 3527539ull); + return acc; +} + +/* CPython's set of those pairs, as an 8-slot open table (PySet_MINSIZE) with its probing, and + * iteration in slot order -- what `list(set(...))` gives, which fixes which of equally-near + * candidate grids Python's `min` keeps. */ +class PyCandidateSet { +public: + void add(int64_t h, int64_t w) { + for (int32_t s = 0; s < 8; ++s) + if (slots_[s].used && slots_[s].h == h && slots_[s].w == w) return; + uint64_t hash = py_tuple_hash(h, w), perturb = hash; + int32_t i = (int32_t)(hash & 7); + for (;;) { + if (!slots_[i].used) { + slots_[i] = { true, h, w }; + return; + } + if (slots_[i].h == h && slots_[i].w == w) return; + perturb >>= 5; + i = (int32_t)(((uint64_t)i * 5 + perturb + 1) & 7); + } + } + /* In slot order, i from 0 to 7: the next used slot's grid, or false at the end. */ + bool next(int32_t* i, int64_t* h, int64_t* w) const { + for (; *i < 8; ++*i) + if (slots_[*i].used) { + *h = slots_[*i].h; + *w = slots_[*i].w; + ++*i; + return true; + } + return false; + } + +private: + struct Slot { bool used = false; int64_t h = 0, w = 0; }; + Slot slots_[8]; +}; + +/* MuseGlimmer{Image,Video}Processor.smart_resize, in Python's doubles: the ideal merged-token + * sides are capped to the token budget by area, then the whole grids at their floor and ceiling + * are candidates, and the one whose aspect is nearest the picture's own wins. Ties are real -- + * every square picture's floor and ceiling grids are both exactly nearest -- and the reference + * resolves them by iterating the candidates in a CPython set's order, so the set's slot order is + * simulated above. The fallback for an empty candidate set is the reference's own, kept for + * parity; it cannot fire for a budget of at least one token. */ +int muse_size(int64_t h, int64_t w, int32_t factor, int64_t max_tokens, int64_t* oh, int64_t* ow, + std::string* why) { + if (h <= 0 || w <= 0) { if (why) *why = "the picture has no size"; return RAD_E_INVAL; } + if (max_tokens < 1) { if (why) *why = "the token budget is empty"; return RAD_E_INVAL; } + const double f = factor; + double ih = (double)h / f; + double iw = (double)w / f; + const double ratio = ih > 0.0 ? iw / ih : 1.0; + if (ih * iw > (double)max_tokens) { + ih = std::sqrt((double)max_tokens / ratio); + iw = ih * ratio; + } + const int64_t fh = (int64_t)std::floor(ih), ch = (int64_t)std::ceil(ih); + const int64_t fw = (int64_t)std::floor(iw), cw = (int64_t)std::ceil(iw); + PyCandidateSet cand; + cand.add(fh, fw); + cand.add(fh, cw); + cand.add(ch, fw); + cand.add(ch, cw); + const double aspect = (double)h / (double)w; + int64_t gh = -1, gw = -1; + double best = 0.0; + for (int32_t i = 0;;) { + int64_t ch2 = 0, cw2 = 0; + if (!cand.next(&i, &ch2, &cw2)) break; + if (ch2 < 1 || cw2 < 1 || (double)ch2 * (double)cw2 > (double)max_tokens) continue; + const double diff = std::fabs((double)ch2 / (double)cw2 - aspect); + if (gh < 0 || diff < best) { + best = diff; + gh = ch2; + gw = cw2; + } + } + if (gh < 0) { + gh = std::max(1, pyround(ih)); + gw = std::max(1, pyround(iw)); + } + *oh = gh * factor; + *ow = gw * factor; + return RAD_OK; +} + +/* MuseGlimmerVideoProcessor.sample_frames: torch.linspace(0, total - 1, n).long(), which + * truncates, against the .long() of a float tensor (half ties go toward zero). */ +std::vector sample_frames_muse(const VideoInfo& info, double fps, int32_t temporal, + int32_t num_frames) { + const int64_t total = info.n_frames; + if (total <= 0) return {}; + const double vfps = info.fps > 0.0 ? info.fps : 24.0; + int64_t n = (int64_t)((double)total * fps / vfps); /* Python's int(): toward zero */ + n = std::min(std::min(n, num_frames), total); + n = std::max(temporal, (n / temporal) * temporal); + n = std::min(n, total); + std::vector idx((size_t)n); + if (n == 1) { idx[0] = 0; return idx; } + const double step = (double)(total - 1) / (double)(n - 1); + for (int64_t i = 0; i < n; ++i) idx[(size_t)i] = (int64_t)((double)i * step); + return idx; +} + /* ================================================================== the resample * * Pillow's ImagingResample for 8-bit RGB: coefficients in double, normalised per output pixel and @@ -663,6 +845,20 @@ inline double bicubic(double x) { return 0.0; } +/* ATen's HelperInterpLanczos filter, which it credits to Pillow's Resample.c: sin(pi x) / (pi x) + * windowed by the same at a third. |x| >= 3 contributes nothing. */ +inline double sinc_lanczos(double x) { + if (x == 0.0) return 1.0; + x *= 3.14159265358979323846; + return std::sin(x) / x; +} + +inline double lanczos(double x) { + if (x < 0.0) x = -x; + if (x >= 3.0) return 0.0; + return sinc_lanczos(x) * sinc_lanczos(x / 3.0); +} + inline uint8_t clip8(int32_t v, int prec) { const int32_t s = v >> prec; return (uint8_t)(s < 0 ? 0 : (s > 255 ? 255 : s)); @@ -672,10 +868,11 @@ inline uint8_t clip8(int32_t v, int prec) { * `ksize` per row; `*prec` gets their fraction bits. PIL uses a fixed 22; with `torch`, ATen's * per-axis choice: the most bits at which the largest weight still fits an int16. */ int coeffs(int32_t in_size, int32_t out_size, std::vector* bounds, - std::vector* kk, bool torch, int* prec) { + std::vector* kk, bool torch, int* prec, double (*filter)(double), + double support_scale = 2.0) { const double scale = (double)in_size / (double)out_size; const double fscale = scale < 1.0 ? 1.0 : scale; - const double support = 2.0 * fscale; + const double support = support_scale * fscale; const int ksize = (int)std::ceil(support) * 2 + 1; std::vector k((size_t)ksize), w((size_t)out_size * (size_t)ksize, 0.0); bounds->assign((size_t)out_size * 2, 0); @@ -691,7 +888,7 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector* bounds, double ww = 0.0; int x = 0; for (; x < xmax; ++x) { - const double w = bicubic((x + xmin - center + 0.5) * ss); + const double w = filter((x + xmin - center + 0.5) * ss); k[(size_t)x] = w; ww += w; } @@ -982,12 +1179,13 @@ static void pass_vertical(const Frame& src, int32_t shift, int32_t h, }); } -static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch) { +static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch, + double (*filter)(double) = bicubic, double support_scale = 2.0) { if (in.w == w && in.h == h) { *out = in; return; } std::vector bh, kh, bv, kv; int ph = kPrec, pv = kPrec; - const int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph); - const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv); + const int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph, filter, support_scale); + const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv, filter, support_scale); const bool need_h = w != in.w, need_v = h != in.h; /* Pillow's pass order (libImaging/Resample.c): vertical first when the height shrinks and by @@ -1026,6 +1224,20 @@ void resize_bicubic_torch(const Frame& in, int32_t w, int32_t h, Frame* out) { resize_bicubic_impl(in, w, h, out, true); } +/* The Muse Glimmer reference's resize filter: torchvision's tvF.resize on the uint8 pixels with + * InterpolationMode.LANCZOS and antialias=True, CPU (the TorchvisionBackend refuses it anywhere + * else and falls back to bicubic). On CPU torchvision sends a uint8 tensor to torch's native + * uint8 kernel, which is PIL's two-pass fixed-point scheme with ATen's parameter choices: weights + * in double, normalised, quantised to int16 at an adaptive precision (the most bits at which the + * largest weight still fits, at most 22), the horizontal pass first, its output rounded to eight + * bits and clamped, then the vertical pass; each pass rounds half up and clamps 0..255. That is + * resize_bicubic_impl's `torch` branch with the Lanczos filter in place of bicubic -- the same + * quantisation, pass order and rounding this file already implements for torchvision's bicubic + * (coeffs, kPrec, pass_horizontal, pass_vertical). */ +void resize_lanczos_torch(const Frame& in, int32_t w, int32_t h, Frame* out) { + resize_bicubic_impl(in, w, h, out, true, lanczos, 3.0); +} + /* Python's round(): the nearest integer, a tie to the even one. The default floating-point * environment rounds that way, which nearbyint follows. */ static inline int64_t py_round(double x) { return (int64_t)std::nearbyint(x); } @@ -1260,6 +1472,47 @@ void patchify(const VisionConfig& c, const std::vector& frames, It } } +/* Muse Glimmer's patch rows, in raster order like the reference's processor emits them (row by + * row, not merge-block order): the tower's patch GEMM reads each row as one patch and its + * coordinate planes/merge op need the raster grid, and the merge is `pixtral_merge`, which packs + * each 2x2 block into one row of the reference's pixel_shuffle layout (channel-major). Each + * flattened patch is (temporal, channel), not (channel, temporal), and each value is normalised + * through the same per-(channel, byte) lookup as patchify's -- the fused (u - 255 mean) / + * (255 std) in f32 is the form the reference's rescale-and-normalise gives, byte for byte, + * rounded to bf16. + */ +void patchify_muse(const VisionConfig& c, const std::vector& frames, Item* it) { + const int P = c.patch, T = c.temporal, M = c.merge; + const int gh = it->grid_h, gw = it->grid_w; + float m255[3], s255[3]; + for (int ch = 0; ch < 3; ++ch) { + m255[ch] = c.mean[ch] * 255.0f; + s255[ch] = c.stdv[ch] * 255.0f; + } + uint16_t lut[3][256]; + for (int ch = 0; ch < 3; ++ch) + for (int v = 0; v < 256; ++v) + lut[ch][v] = rad_f32_to_bf16(((float)v - m255[ch]) / s255[ch]); + const int64_t dim = it->patch_dim; + it->pixels.assign((size_t)it->n_patch * (size_t)dim, 0); + it->patch_raster = true; + uint16_t* dst = it->pixels.data(); + for (int g = 0; g < it->grid_t; ++g) + for (int y = 0; y < gh; ++y) + for (int x = 0; x < gw; ++x) { + const int py0 = y * P, px0 = x * P; + for (int t = 0; t < T; ++t) { + const Frame& f = *frames[(size_t)(g * T + t)]; + for (int ch = 0; ch < 3; ++ch) + for (int yy = 0; yy < P; ++yy) { + const uint8_t* row = f.rgb.data() + + ((size_t)(py0 + yy) * f.w + px0) * 3 + ch; + for (int xx = 0; xx < P; ++xx) *dst++ = lut[ch][row[xx * 3]]; + } + } + } +} + /* Gemma 4's patch rows, in merge-block order like patchify's: each pooling window's patches are * consecutive, so the pooler is a mean of k^2 consecutive rows (attention and the position terms * read each patch's own coordinates, so the order is otherwise free). Each row is (y, x, channel); @@ -1436,6 +1689,33 @@ int Processor::init(const VisionConfig& cfg, encode_text_ = std::move(encode_text); return RAD_OK; } + if (cfg.family == Family::MuseGlimmer) { + /* The markers the container does not number are vocabulary words, refused here so a + * missing one fails at startup, not on the first media. An image and a video frame are + * one segment each of merged tokens, so the caps are lowered to what a pass holds. */ + if (cfg_.tok_start < 0 || cfg_.tok_end < 0 || cfg_.tok_video_start < 0 || + cfg_.tok_video_end < 0 || cfg_.tok_video_sep < 0) { + if (!token_id) return RAD_E_INVAL; + if (cfg_.tok_start < 0) cfg_.tok_start = token_id("<|image_start|>"); + if (cfg_.tok_end < 0) cfg_.tok_end = token_id("<|image_end|>"); + if (cfg_.tok_video_start < 0) cfg_.tok_video_start = token_id("<|vid_start|>"); + if (cfg_.tok_video_end < 0) cfg_.tok_video_end = token_id("<|vid_end|>"); + if (cfg_.tok_video_sep < 0) cfg_.tok_video_sep = token_id("<|vid_frame_separator|>"); + if (cfg_.tok_start < 0 || cfg_.tok_end < 0 || cfg_.tok_video_start < 0 || + cfg_.tok_video_end < 0 || cfg_.tok_video_sep < 0) + return RAD_E_NOTFOUND; + } + const int64_t pass_tok = cfg.max_patches / ((int64_t)cfg.merge * cfg.merge); + if (pass_tok < 1 || (int64_t)cfg_.max_frame_rows * cfg.merge * cfg.merge > cfg.max_patches) + return RAD_E_INVAL; + if (cfg_.max_image_tokens > pass_tok) cfg_.max_image_tokens = (int32_t)pass_tok; + if (cfg_.max_video_patches <= 0) + cfg_.max_video_patches = + (int64_t)((cfg.max_frames + cfg.temporal - 1) / cfg.temporal) * + (int64_t)cfg_.max_frame_rows * cfg.merge * cfg.merge; + encode_text_ = std::move(encode_text); + return RAD_OK; + } if (cfg.family == Family::UnlimitedOcr) { /* The vocabulary spells the marker (`processor.image_token`), and every placeholder of a * picture is that same id: there is nothing else to resolve. */ @@ -2071,6 +2351,96 @@ int Processor::video_radio(const Video& v, std::shared_ptr* out, std::stri return RAD_OK; } +/* Meta's Muse Glimmer image processor (transformers' MuseGlimmerImageProcessor, Torchvision + * backend): the picture at muse_size's grid under the token cap, resized with torchvision's + * antialiased Lanczos on the uint8 pixels, values (u / 255 - mean) / std in bf16. One segment. */ +int Processor::image_muse(const Frame& f, std::shared_ptr* out, std::string* why) const { + const VisionConfig& c = cfg_; + int64_t h = 0, w = 0; + RAD_TRY(muse_size(f.h, f.w, c.factor(), c.max_image_tokens, &h, &w, why)); + Frame r; + resize_lanczos_torch(f, (int32_t)w, (int32_t)h, &r); + auto it = std::make_shared(); + it->kind = Kind::Image; + it->grid_t = 1; + it->grid_h = (int32_t)(h / c.patch); + it->grid_w = (int32_t)(w / c.patch); + finish_item(c, it.get()); + if (it->n_patch > c.max_patches) { + if (why) *why = "the image resizes to more patches than one encoder pass holds"; + return RAD_E_INVAL; + } + /* An image fills the temporal depth by repetition, as the reference's expand does. */ + std::vector frames((size_t)c.temporal, &r); + patchify_muse(c, frames, it.get()); + one_run(it.get(), c.tok_start, it->seg_rows, c.tok_image, c.tok_end); + *out = std::move(it); + return RAD_OK; +} + +/* Its video processor: every frame at the first frame's muse_size grid under the per-frame token + * cap (the reference resizes the whole stack once), the frames padded to whole temporal groups by + * repeating the last, and per group one "Time: T s" stamp -- the group's first frame's time at + * the stream's rate, 24 fps when the stream states none -- between <|vid_start|> and + * <|vid_end|>, the groups separated by <|vid_frame_separator|>. */ +int Processor::video_muse(const Video& v, std::shared_ptr* out, std::string* why) const { + const VisionConfig& c = cfg_; + if (v.frames.empty()) { if (why) *why = "the video decoded to no frames"; return RAD_E_INVAL; } + int64_t h = 0, w = 0; + RAD_TRY(muse_size(v.frames[0].h, v.frames[0].w, c.factor(), c.max_frame_rows, &h, &w, why)); + + /* Pad the frames and their indices to whole temporal groups by repeating the last. */ + std::vector frames; + std::vector idx = v.index; + for (const Frame& f : v.frames) frames.push_back(&f); + while (frames.size() % (size_t)c.temporal != 0 || frames.size() < (size_t)c.temporal) { + frames.push_back(frames.back()); + idx.push_back(idx.empty() ? 0 : idx.back()); + } + + auto it = std::make_shared(); + it->kind = Kind::Video; + it->grid_t = (int32_t)(frames.size() / (size_t)c.temporal); + it->grid_h = (int32_t)(h / c.patch); + it->grid_w = (int32_t)(w / c.patch); + finish_item(c, it.get()); + if ((int64_t)it->grid_h * it->grid_w > c.max_patches) { + if (why) *why = "a video frame resizes to more patches than one encoder pass holds"; + return RAD_E_INVAL; + } + if (it->n_patch > c.max_video_patches) { + if (why) *why = "the video is over the server's patch budget for one video"; + return RAD_E_INVAL; + } + + /* Resize each distinct frame once; padding repeats share the resized copy. */ + std::vector resized(v.frames.size()); + for (size_t i = 0; i < v.frames.size(); ++i) + resize_lanczos_torch(v.frames[i], (int32_t)w, (int32_t)h, &resized[i]); + std::vector rframes; + for (const Frame* f : frames) rframes.push_back(&resized[(size_t)(f - v.frames.data())]); + patchify_muse(c, rframes, it.get()); + content_key(*it, &it->key_hi, &it->key_lo); + + const double vfps = v.info.fps > 0.0 ? v.info.fps : 24.0; + it->expand.push_back(c.tok_video_start); + for (int32_t g = 0; g < it->grid_t; ++g) { + char ts[64]; + std::snprintf(ts, sizeof ts, "Time: %.1fs", (double)idx[(size_t)g * c.temporal] / vfps); + const std::vector tt = encode_text_ ? encode_text_(ts) : std::vector{}; + if (tt.empty()) { + if (why) *why = "the tokenizer produced nothing for a video timestamp"; + return RAD_E_STATE; + } + it->expand.insert(it->expand.end(), tt.begin(), tt.end()); + it->seg_at.push_back((int32_t)it->expand.size()); + it->expand.insert(it->expand.end(), (size_t)it->seg_rows, c.tok_video); + it->expand.push_back(g + 1 == it->grid_t ? c.tok_video_end : c.tok_video_sep); + } + *out = std::move(it); + return RAD_OK; +} + int Processor::image_from(const Frame& f, std::shared_ptr* out, std::string* why, const ImageMode& mode) const { const VisionConfig& c = cfg_; @@ -2083,6 +2453,7 @@ int Processor::image_from(const Frame& f, std::shared_ptr* out, std::strin if (c.family == Family::Lfm2) return image_lfm2(f, out, why); if (c.family == Family::Glm5Next) return image_glm5next(f, out, why); if (c.family == Family::Radio) return image_radio(f, out, why); + if (c.family == Family::MuseGlimmer) return image_muse(f, out, why); if (c.family == Family::UnlimitedOcr) return image_unlimitedocr(f, mode, out, why); int64_t h = 0, w = 0; RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels, @@ -2177,6 +2548,7 @@ int Processor::video_from(const Video& v, std::shared_ptr* out, std::strin const VisionConfig& c = cfg_; if (c.family == Family::Gemma4) return video_gemma4(v, out, why); if (c.family == Family::Radio) return video_radio(v, out, why); + if (c.family == Family::MuseGlimmer) return video_muse(v, out, why); if (c.family == Family::Glm5Next || c.family == Family::Pixtral) { if (why) *why = "this model's processor takes pictures, not video"; return RAD_E_UNSUPPORTED; @@ -2418,12 +2790,16 @@ int Processor::encoder_audio(const uint8_t* bytes, size_t n, int32_t rate, int64 } namespace { -struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; }; +struct SampleArgs { double fps; int32_t lo, hi; bool gemma4; int32_t temporal; }; std::vector sample_cb(const VideoInfo& info, const void* user) { const SampleArgs* a = static_cast(user); return a->gemma4 ? sample_frames_gemma4(info, a->fps, a->hi) : sample_frames(info, a->fps, a->lo, a->hi); } +std::vector muse_sample_cb(const VideoInfo& info, const void* user) { + const SampleArgs* a = static_cast(user); + return sample_frames_muse(info, a->fps, a->temporal, a->hi); +} } /* namespace */ int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr* out, @@ -2434,8 +2810,13 @@ int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr* out, return RAD_E_UNSUPPORTED; } Video v; + if (cfg_.family == Family::MuseGlimmer) { + const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames, false, cfg_.temporal }; + RAD_TRY(decode_video(bytes, n, muse_sample_cb, &a, cfg_.max_source_pixels, &v, why)); + return video_from(v, out, why); + } const SampleArgs a{ cfg_.fps, cfg_.min_frames, cfg_.max_frames, - cfg_.family == Family::Gemma4 }; + cfg_.family == Family::Gemma4, cfg_.temporal }; RAD_TRY(decode_video(bytes, n, sample_cb, &a, cfg_.max_source_pixels, &v, why)); return video_from(v, out, why); } diff --git a/core/mm/processor.h b/core/mm/processor.h index 4f1e524b..0ab6050c 100644 --- a/core/mm/processor.h +++ b/core/mm/processor.h @@ -92,8 +92,20 @@ enum class Kind { Image, Video, Audio }; * zero rows ahead of its patches, which the tower fills with its class and register * tokens. Pictures are spelled placeholders ; a video one such run a * tubelet, each after its "Frame i sampled at T seconds and frame i+1 ...: " label, - * runs joined by a newline. Tokens at their positions (NoPE). */ -enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next, Pixtral, Radio }; + * runs joined by a newline. Tokens at their positions (NoPE). + * MuseGlimmer Meta's Muse Glimmer 30B: a picture (a video frame the same) resized so both + * sides are multiples of patch * merge and its merged-token count stays under the cap + * (max_image_tokens, a frame max_frame_rows), to the whole-merged-patch grid whose + * aspect is nearest its own (muse_size, no floor band: a small picture is downscaled + * onto the grid). Resized with torchvision's antialiased Lanczos on the uint8 pixels + * (resize_lanczos_torch); values (u / 255 - mean) / std in f32, rounded to bf16. A + * patch row is (frame, channel, y, x), the reference's (temporal, channel), a picture + * duplicated to fill the depth. A picture is spelled <|patch|>*N + * ; a video one , then per temporal group the text `Time: T s` + * and <|video|>*N rows, the groups separated by <|vid_frame_separator|> and closed by + * , T the group's first frame time (the reference stamps a group once, after + * repeating the last frame to a whole group). */ +enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next, Pixtral, Radio, MuseGlimmer }; struct VisionConfig { Family family = Family::QwenVL; @@ -116,6 +128,11 @@ struct VisionConfig { float mean[3] = { 0.5f, 0.5f, 0.5f }; float stdv[3] = { 0.5f, 0.5f, 0.5f }; int32_t tok_image = -1, tok_video = -1, tok_start = -1, tok_end = -1; + /* MuseGlimmer: the video run's own markers, , and the groups' + * <|vid_frame_separator|> (a picture shares tok_start and tok_end). A container that numbers + * them (`video_start_token_id`, `video_end_token_id`, `video_frame_separator_token_id`) + * wins; otherwise the vocabulary resolves the spellings at Processor::init. */ + int32_t tok_video_start = -1, tok_video_end = -1, tok_video_sep = -1; /* Lfm2: the tiling (see Family). `max_segment_patches` is the tower's longest segment. */ int32_t min_tiles = 0, max_tiles = 0, tile = 0; bool use_thumbnail = false; @@ -456,11 +473,13 @@ private: int image_glm5next(const Frame& f, std::shared_ptr* out, std::string* why) const; int image_pixtral(const Frame& f, std::shared_ptr* out, std::string* why) const; int image_radio(const Frame& f, std::shared_ptr* out, std::string* why) const; + int image_muse(const Frame& f, std::shared_ptr* out, std::string* why) const; int video_radio(const Video& v, std::shared_ptr* out, std::string* why) const; /* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */ int32_t tok_thumbnail_ = -1; std::vector tok_tiles_; int video_gemma4(const Video& v, std::shared_ptr* out, std::string* why) const; + int video_muse(const Video& v, std::shared_ptr* out, std::string* why) const; VisionConfig cfg_{}; AudioConfig acfg_{}; @@ -494,6 +513,21 @@ std::vector sample_frames_gemma4(const VideoInfo& info, double fps, int * within `max_patches`, aspect ratio kept (get_aspect_ratio_preserving_size). */ int gemma4_size(int64_t h, int64_t w, int32_t patch, int32_t pool, int64_t max_patches, int64_t* oh, int64_t* ow, std::string* why); + +/* MuseGlimmer's smart_resize (MuseGlimmer{Image,Video}Processor.smart_resize): the whole + * merged-patch grid (`factor` = patch * merge pixels a side, so a grid cell is one output row) + * under `max_tokens` merged tokens whose aspect is nearest the picture's own, in Python's + * doubles. A picture over the cap scales to the cap first. */ +int muse_size(int64_t h, int64_t w, int32_t factor, int64_t max_tokens, int64_t* oh, int64_t* ow, + std::string* why); + +/* MuseGlimmerVideoProcessor.sample_frames: `total * fps / native` frames, truncated, clamped to + * [temporal, min(num_frames, total)] and floored to a whole temporal group, then torch's + * linspace(0, total - 1, n) truncated to integers. A stream with no stated rate is taken at + * 24 fps. */ +std::vector sample_frames_muse(const VideoInfo& info, double fps, int32_t temporal, + int32_t num_frames); + /* Radio's tile for a picture of w x h pixels (NVIDIA's _compute_target_patches, Python's * round-half-even included) and for a video frame (_compute_target_patches_video), in patches. */ void radio_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, int32_t* hp); @@ -503,6 +537,9 @@ void radio_video_size(int64_t w, int64_t h, const VisionConfig& c, int32_t* wp, * filter's overshoot. Separable, width first, as ATen's CPU kernel; a side that keeps its size is * the identity. */ void resize_bicubic_aa_f32(const Frame& in, int32_t w, int32_t h, std::vector* out); +/* The Muse Glimmer reference's resize filter, torchvision's antialiased Lanczos on the uint8 + * pixels (see processor.cpp). */ +void resize_lanczos_torch(const Frame& in, int32_t w, int32_t h, Frame* out); /* PIL's antialiased bicubic resample of packed RGB, bit for bit: fixed-point coefficients, a * horizontal pass into an 8-bit intermediate and then a vertical one. */ void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out); diff --git a/core/rad_core.h b/core/rad_core.h index 3cdabf36..33e03c09 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -444,6 +444,7 @@ public: struct AudioGenStrings { /* "" for an absent template; tmpl_ref and ref_item RadAudioGenDecl's references */ std::string name, tmpl, tmpl_plain, neg_tmpl, tmpl_ref, ref_item; + std::string tmpl_ref_instruct, neg_tmpl_ref; } agen_str; bool is_audio_generator() const { return audio_gen.max_lanes != 0; } /* The declared video generator (rad_declare_video_generator); `max_lanes` 0 when none. */ @@ -848,6 +849,9 @@ struct Config { bool prefill_interleave_set = false; int64_t prefill_interleave = 0; /* --prefill-interleave: decode-only steps between chunks; * -1 auto (Scheduler::interleave_steps) */ + /* --mixed-step-target-ms: soft duration target for a mixed prefill/decode step. The scheduler + * learns an aggregate prefill-row cap from completed mixed steps; 0 keeps the fixed policy. */ + int64_t mixed_step_target_ms = 0; /* --preempt-wait-ms: how long a preempted prefill may wait for the whole-recompute gate * before the scheduler evicts cache blocks and preempts a lower-priority running request to * make room for it. 0 = fall back on the next step; default 5000 ms. */ @@ -1052,6 +1056,22 @@ struct Config { std::string kld_out; /* --kld-out FILE: the report as JSON, rows beside it */ bool kld() const { return !kld_record.empty() || !kld_ref.empty(); } + /* ---------------- DIAGNOSIS (core/diag/diagnose.h, core/engine_diagnose.cpp) ---------------- + * + * A mode, like the KL mode: the engine starts as it would to serve, then runs a fixed workload + * on itself -- decode by prompt category, a concurrency sweep, a prefill sweep with decode at + * each depth, a prompt arriving into running streams -- and writes DIR/diagnose.json and + * DIR/diagnose.md instead of listening. Every point is run once unmeasured and then + * `diagnose_runs` times. */ + std::string diagnose; /* --diagnose DIR */ + int diagnose_tokens = 256; /* --diagnose-tokens N: tokens a decode stream generates */ + int diagnose_runs = 3; /* --diagnose-runs N: measured runs a point */ + std::vector diagnose_concurrency = { 1, 2, 4, 8 }; /* --diagnose-concurrency */ + std::vector diagnose_prefill = { 1024, 4096, 16384, 65536 }; /* --diagnose-prefill */ + std::string diagnose_corpus; /* --diagnose-corpus FILE; empty is the built-in one */ + std::string diagnose_baseline; /* --diagnose-baseline FILE: an earlier diagnose.json to compare outputs with */ + bool diagnose_mode() const { return !diagnose.empty(); } + /* --mm-max-patches: the most patches one encoder pass carries, which bounds the largest image * (one image is one pass) and sizes the encoder's activations. -1 is `auto`: the default below * when the container carries a vision tower and 0 when it does not. 0 serves text only and diff --git a/core/sched/advance.hip b/core/sched/advance.hip index dd68fc51..3d32f7d6 100644 --- a/core/sched/advance.hip +++ b/core/sched/advance.hip @@ -31,7 +31,7 @@ __global__ __launch_bounds__(kThreads) void r4dchain_step_advance(rad::AdvanceAr } /* ADV_COMPACT: block (x, y) is work item x (a pool, layer and head) of batch row y; its threads - * split the K|V row into 16-byte chunks. Chained like the advance where launches chain, every + * split the K|V row into 16-byte chunks and its last words. Chained like the advance where launches chain, every * block waiting for the kernels before it and counting itself in after its moves. */ constexpr int kCompactThreads = 64; __device__ __forceinline__ void step_compact_body(const rad::AdvanceArgs& a) { diff --git a/core/sched/advance_impl.h b/core/sched/advance_impl.h index 6b1699fe..130d5e73 100644 --- a/core/sched/advance_impl.h +++ b/core/sched/advance_impl.h @@ -320,7 +320,9 @@ RAD_ADV_FN void adv_row(const AdvanceArgs& a, int i) { } /* ADV_COMPACT for one (batch row, pool, layer, head): the moves the row's accepted path asks - * for, `c0` and every `cstep`-th 16-byte chunk of each K|V row. Node path[t] stored at + * for, `c0` and every `cstep`-th 16-byte chunk of each K|V row. A row is whole 32-bit words; the + * words past its last whole chunk (an int8 cache's two f16 scales) go with the caller whose chunk + * set the next chunk would be in. Node path[t] stored at * base + path[t] and belongs at base + t + 1. path[] increases (a parent's index is below its * child's) and path[t] >= t + 1, so in t order no move overwrites a node a later move still reads: * a destination base + t + 1 is either the node's own place or a place a node already moved out @@ -340,7 +342,8 @@ RAD_ADV_FN void adv_compact(const AdvanceArgs& a, int i, int p, int l, int h, in const int32_t base = S.head - S.acc; const int32_t bs = e.block_size; char* lay = P.base + (int64_t)l * P.layer_stride; - const int32_t chunks = P.row_bytes / 16; + const int32_t chunks = P.row_bytes / 16, tail = P.row_bytes % 16 / 4; + const bool tails = tail > 0 && chunks % cstep == c0; for (int32_t t = 0; t < np; ++t) { const int32_t src = base + S.path[t], dst = base + t + 1; if (src == dst) continue; @@ -355,6 +358,8 @@ RAD_ADV_FN void adv_compact(const AdvanceArgs& a, int i, int p, int l, int h, in v3 = from[4 * c + 3]; to[4 * c] = v0; to[4 * c + 1] = v1; to[4 * c + 2] = v2; to[4 * c + 3] = v3; } + if (tails) + for (int32_t j = 0; j < tail; ++j) to[4 * chunks + j] = from[4 * chunks + j]; } } diff --git a/core/sched/metrics.h b/core/sched/metrics.h index c3bcd49c..f0316709 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -43,9 +43,14 @@ struct SchedMetrics { * (Scheduler::step_next). Every other step leaves the card idle during the host's commit and * staging. */ int64_t steps_ahead = 0; - /* Prefill chunks capped to leave room for decode rows or a waiting admission in the same - * step (--busy-prefill-chunk). Zero under `off`. */ + /* Prefill chunks capped to leave room for other work in the same step, by the fixed busy + * policy or the adaptive mixed-step target. */ int64_t prefill_chunks_capped = 0; + /* --mixed-step-target-ms: mixed steps observed, those over their target, and the current + * seeded or learned aggregate prefill-row cap (0 when the policy is disabled). */ + int64_t mixed_step_target_steps = 0; + int64_t mixed_step_target_misses = 0; + int64_t mixed_step_target_prefill_cap = 0; /* Cumulative nanoseconds spent inside steps, total and for decode steps only. Wall time over * a step count is not a step time: it charges idle gaps between requests to steps and mixes @@ -213,4 +218,85 @@ private: double mean_ = 0.0; /* the rejection reference */ }; +/* Feedback controller for --mixed-step-target-ms. Completed mixed-step service time includes the + * forward and drafter work, but not queueing or HTTP transport. Scale rows by target/observed when the + * target is missed; grow only after three representative steps below 95% of the target and by at + * most a quarter of the measured headroom. A one-quantum probe lets a conservative cap recover + * when fixed decode cost makes proportional scaling alone predict no larger legal chunk. + * + * The controller is deliberately model-agnostic. It may take a cap below an expert stager's + * throughput floor: satisfying an explicitly requested latency target while decoders are active + * is the point of the flag. With the flag off no caller consults it. */ +struct MixedStepTarget { + void reset() { cap_ = 0; good_ = 0; } + + /* A new server has no mixed-step timing yet. Begin at a conservative fraction of that + * model's declared mixed-step capacity instead of allowing one unbounded calibration miss; + * subsequent observations replace or grow this seed exactly like any learned cap. */ + void seed(int64_t rows, int64_t quantum, int64_t max_rows) { + if (rows <= 0 || max_rows <= 0) return; + const int64_t q = quantum > 0 ? quantum : 1; + max_rows = std::max(q, max_rows / q * q); + rows = std::max(q, rows / q * q); + cap_ = std::min(rows, max_rows); + good_ = 0; + } + + void observe(int64_t rows, int64_t ns, int64_t target_ns, int64_t quantum, + int64_t max_rows, bool representative = true) { + if (rows <= 0 || ns <= 0 || target_ns <= 0 || max_rows <= 0) return; + const int64_t q = quantum > 0 ? quantum : 1; + max_rows = max_rows / q * q; + if (max_rows < q) max_rows = q; + + long double scaled = (long double)rows * (long double)target_ns / (long double)ns; + int64_t want = scaled >= (long double)max_rows ? max_rows : (int64_t)scaled; + want = want / q * q; + if (want < q) want = q; + + if (cap_ == 0) { + cap_ = want; + good_ = 0; + return; + } + if (ns > target_ns) { + good_ = 0; + /* A prompt tail did not exercise a reusable limit. A checkpoint, fixed busy cap or + * other policy boundary still leaves the prompt unfinished and is representative: + * reducing this controller below that boundary can shorten the next mixed step. */ + if (!representative) return; + /* A representative miss corrects immediately. */ + if (want < cap_) cap_ = want; + return; + } + /* A short tail did not exercise the cap and cannot justify growing it. Near-target steps + * reset the recovery streak; three clearly fast full-cap samples earn one probe. */ + if (!representative || ns * 20 >= target_ns * 19 || cap_ >= max_rows) { + good_ = 0; + return; + } + if (++good_ < 3) return; + good_ = 0; + const int64_t goal = std::max(want, std::min(max_rows, cap_ + q)); + int64_t grow = (goal - cap_) / 4; + if (grow < q) grow = q; + cap_ = cap_ + grow; + cap_ = cap_ / q * q; + if (cap_ > goal) cap_ = goal; + if (cap_ > max_rows) cap_ = max_rows; + } + + int64_t cap() const { return cap_; } + int64_t limit(int64_t budget, int64_t quantum) const { + if (cap_ <= 0 || budget <= 0) return budget; + const int64_t q = quantum > 0 ? quantum : 1; + const int64_t c = cap_ / q * q; + return c > 0 && c < budget ? c : budget; + } + +private: + int64_t cap_ = 0; + int good_ = 0; +}; + } /* namespace rad */ diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 6edb052f..7a98be20 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -57,6 +57,15 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac cfg_ = cfg; kv_ = kv; pc_ = pc; + /* THE STEP RECORD EXISTS ONLY FOR --diagnose. Sized here, once, and never on the serving + * path: 64 Ki steps is minutes of decode at any step rate this engine reaches and 2.5 MiB, and + * a record a step is work a serving process has no reader for. A reader that falls further + * behind is told how many it lost, not handed the wrong ones. The recorder is chosen here so + * the step path calls one instead of testing the mode on every step. */ + if (cfg_.diagnose_mode()) { + step_ring_.reset(1u << 16); + record_step_ = &Scheduler::record_step; + } /* The engine resolves the geometry once, because the prefix cache needs its checkpoint * interval first; a caller without one (tests) resolves its own from prog and cfg. Both @@ -143,10 +152,48 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac "prompt unfinished while other sequences decode, decode-only steps follow for up " "to %.2f of the chunk step's measured time (at most %lld steps)", cfg.prefill_interleave_share, (long long)kInterleaveAutoMax); + mixed_target_.reset(); + m_.mixed_step_target_prefill_cap = 0; + if (cfg.mixed_step_target_ms > 0) { + const int64_t Q = std::max(geo_.quantum, 1); + /* A mixed step never receives a span's wide lone-prefill budget. Validate the same + * shared budget step() will use, or a spanned deployment can start even though no legal + * prefill quantum fits beside a decoder. */ + const int64_t mixed_budget = geo_.shared_tok; + const int64_t draft_rows = 1 + std::max(cfg.n_spec, 0); + const int64_t mixed_floor = cfg.max_seqs > 1 ? Q + draft_rows : 0; + if ((cfg.busy_prefill_chunk > 0 && cfg.busy_prefill_chunk < Q) || + (mixed_floor > 0 && mixed_budget < mixed_floor)) { + RAD_ERR("--mixed-step-target-ms needs room for one legal prefill quantum and " + "the active decode rows: quantum=%lld, max_seqs=%lld, draft_rows=%lld, " + "mixed_step_budget=%lld, max_num_batched_tokens=%lld, busy_prefill_chunk=%lld", + (long long)Q, (long long)cfg.max_seqs, (long long)draft_rows, + (long long)mixed_budget, + (long long)cfg.max_tok, (long long)cfg.busy_prefill_chunk); + return RAD_E_INVAL; + } + const int64_t max_prefill_quanta = mixed_budget > draft_rows + ? (mixed_budget - draft_rows) / Q : 0; + if (cfg.max_seqs > 1 && cfg.max_seqs - 1 > max_prefill_quanta) + RAD_WARN("--mixed-step-target-ms: this batch budget can carry at most %lld legal " + "prefill quantum(s) beside a speculative decode row; with more simultaneous " + "prefills, priority and arrival order continue across later steps", + (long long)max_prefill_quanta); + mixed_target_.seed(std::max(Q, geo_.shared_tok / 4), Q, geo_.shared_tok); + m_.mixed_step_target_prefill_cap = mixed_target_.cap(); + RAD_INFO("scheduler: --mixed-step-target-ms %lld: completed mixed steps teach an adaptive " + "aggregate prefill-row cap; while another sequence decodes the cap starts at " + "%lld rows and aims for a full mixed-step duration near %lld ms (a soft target)", + (long long)cfg.mixed_step_target_ms, (long long)mixed_target_.cap(), + (long long)cfg.mixed_step_target_ms); + } interleave_left_ = 0; ema_chunk_s_ = 0.0; ema_decode_s_ = 0.0; held_prefill_ = 0; + mixed_target_active_ = false; + mixed_target_prefill_planned_ = 0; + mixed_target_prefill_continues_ = false; draft_refill_ = 0; if (cfg.n_spec > 0 && prog.drafter.kind == RAD_DRAFT_BLOCK && prog.drafter.window > 0 && hit_holes_draft_) { @@ -1298,23 +1345,24 @@ void Scheduler::set_stage_rows(int64_t rows) { * about the size of the reserve, as the next step's whole chunk. When that would be under the * floor, the interval is split into two chunks at or above the floor instead. */ int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget, - int64_t reserve, bool shared, bool rows_only) const { + int64_t reserve, bool shared, bool rows_only, + int64_t mixed_target_shares, int64_t mixed_target_decode_reserve) const { const int64_t mode = cfg_.busy_prefill_chunk; - if (mode == 0 || budget <= 0) return budget; + if (budget <= 0 || (mode == 0 && !mixed_target_active_)) return budget; /* Auto holds a chunk back only for work that would otherwise get nothing this step: rows * behind it, or a request waiting to start. Rows planned ahead of it are in the step anyway. * An explicit N trades prefill speed for every other row's latency, so it applies whenever * the chunk shares the step. */ - if (reserve <= 0 && !(mode > 0 && shared)) return budget; + if (reserve <= 0 && !(mode > 0 && shared) && !(mixed_target_active_ && shared)) return budget; reserve = std::max(reserve, 0); const int64_t Q = std::max(geo_.quantum, 1); - int64_t cap = budget - reserve; + int64_t cap = mode == 0 ? budget : budget - reserve; if (mode > 0) { /* The operator's number, with no floor; set_stage_rows warns when it is under the * stager's step. */ cap = std::min(cap, mode); - } else { + } else if (mode < 0) { const int64_t floor = std::max(Q, stage_rows_ / Q * Q); cap = std::max(cap, floor); const int64_t remaining = n_target - n_computed; @@ -1331,6 +1379,25 @@ int64_t Scheduler::busy_cap(int64_t n_computed, int64_t n_target, int64_t budget if (!rows_only && cap < span && span - cap < floor && span - floor >= floor) cap = span - floor; } + /* Apply the decoder reservation after the auto staging floor. Otherwise the floor can raise + * a reduced cap back to the whole budget, exclude the decoder, and prevent feedback. */ + if (mixed_target_active_ && mixed_target_decode_reserve > 0) + cap = std::min(cap, budget - mixed_target_decode_reserve); + if (mixed_target_active_ && mixed_target_.cap() > 0) { + mixed_target_shares = std::max(0, mixed_target_shares); + /* Share the aggregate allowance evenly among this prefill and those expected later in + * the step. Stable queue order must not let the first request consume the cap while the + * others receive only a minimum quantum on every step. If the learned cap cannot hold + * one quantum apiece, the effective allowance grows just enough to make progress; this + * may miss an impossible target, but it cannot silently starve a queued prompt. */ + const int64_t floor = mixed_target_prefill_planned_ + (mixed_target_shares + 1) * Q; + const int64_t allowance = std::max(mixed_target_.cap(), floor); + const int64_t left = std::max(0, allowance - mixed_target_prefill_planned_); + const int64_t participants = mixed_target_shares + 1; + const int64_t fair = left / participants / Q * Q; + if (fair < Q || cap < Q) return 0; + cap = std::min(cap, fair); + } return std::min(std::max(cap, Q), budget); } @@ -1397,7 +1464,8 @@ bool Scheduler::preempt_back() { /* ------------------------------------------------------------------ admission */ /* Admission checks the KV budget before a request enters running; a request admitted without the * blocks to run would be preempted on its first step, a full recompute for nothing. */ -int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { +int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve, + int64_t mixed_target_shares) { Request& r = *s.req; /* A REQUEST THAT WAS PREEMPTED WAITS FOR ROOM FOR THE WHOLE RECOMPUTE, plus one block of @@ -1622,11 +1690,13 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { /* An admission shares the step the same way: otherwise a cold prompt with requests * queued behind it takes every token left. The hit is known by now, so the cap applies * to what really has to run. */ - const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty()); + const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(), + false, mixed_target_shares, 0); const int64_t end = chunk_end(r, target); want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at, &r); /* A run read both ways (bidi_fit) the share cannot hold takes the step instead. */ - if (want <= 0 && cap < budget && prog_->encoder.bidirectional) + if (want <= 0 && cap < budget && prog_->encoder.bidirectional && + (!mixed_target_active_ || r.media)) want = plan_chunk(r.n_computed, end, budget, &ckpt, r.checkpoint_at, &r); else if (cap < budget && want > 0) admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at, &r); @@ -1775,6 +1845,8 @@ const RadBatch* Scheduler::step() { plan_.spec_is_tree = tree_; step_prefill_tok_ = 0; step_decode_tok_ = 0; + mixed_target_prefill_planned_ = 0; + mixed_target_prefill_continues_ = false; /* A preempted prefill waits for the whole-recompute gate so it cannot loop. That wait is * bounded here, for every overdue preempted request, not only the queue head: a head that @@ -1865,7 +1937,7 @@ const RadBatch* Scheduler::step() { bool any_decoding = false; bool hold_prefill = false; held_prefill_ = 0; - if (cfg_.prefill_interleave != 0) { + if (cfg_.prefill_interleave != 0 || cfg_.mixed_step_target_ms > 0) { for (int32_t slot : running_) { const SchedReq& s = *reqs_[(size_t)slot]; if (!s.req || !s.running) continue; @@ -1875,8 +1947,9 @@ const RadBatch* Scheduler::step() { break; } if (!any_decoding) interleave_left_ = 0; - hold_prefill = interleave_left_ > 0; + hold_prefill = cfg_.prefill_interleave != 0 && interleave_left_ > 0; } + mixed_target_active_ = cfg_.mixed_step_target_ms > 0 && any_decoding; /* A span is for a prefill alone in its step (ChunkGeometry::span). A spanned step takes as * long as the intervals it carries, so a decode row riding along would wait that long for its @@ -1920,7 +1993,7 @@ const RadBatch* Scheduler::step() { * to be walked needs 1 + the deepest window it can take, each prefill row a share, plus one * share when a request waits and a slot is free. Counted down as the loop walks, so a row's * reserve is what is behind it. */ - const bool share_step = cfg_.busy_prefill_chunk != 0; + const bool share_step = cfg_.busy_prefill_chunk != 0 || mixed_target_active_; const int64_t Q = std::max(geo_.quantum, 1); /* An eighth of this step's budget, which under a span is shared_tok for a shared step. */ const int64_t share_tok = std::max(Q, budget / 8 / Q * Q); @@ -1934,6 +2007,10 @@ const RadBatch* Scheduler::step() { if (pf) ++behind_pf; else behind_dec += dec_row_tok; } } + const int64_t admit_room = std::min( + (int64_t)free_cards_.size(), cfg_.max_seqs - (int64_t)running_.size()); + const int64_t mixed_target_waits = mixed_target_active_ + ? std::min((int64_t)waiting_.size(), std::max(0, admit_room)) : 0; const bool admit_waits = share_step && !waiting_.empty() && !free_cards_.empty() && (int64_t)running_.size() < cfg_.max_seqs; /* The first prefill chunk held back this step (its index in plan_.e before the sort) and what @@ -1977,13 +2054,15 @@ const RadBatch* Scheduler::step() { if (prefill && hold_prefill) { ++held_prefill_; ++i; continue; } if (prefill) { const int64_t shares = share_step ? behind_pf + (admit_waits ? 1 : 0) : 0; + const int64_t mixed_target_shares = mixed_target_active_ ? behind_pf + mixed_target_waits : 0; const int64_t reserve = share_step ? behind_dec + share_tok * shares : 0; const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(), - /*rows_only=*/shares == 0); + /*rows_only=*/shares == 0, mixed_target_shares, behind_dec); const int64_t end = chunk_end(r, target); want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at, &r); /* A run read both ways (bidi_fit) the share cannot hold takes the step instead. */ - if (want <= 0 && cap < budget && prog_->encoder.bidirectional) + if (want <= 0 && cap < budget && prog_->encoder.bidirectional && + (!mixed_target_active_ || r.media)) want = plan_chunk(r.n_computed, end, budget, &ckpt, r.checkpoint_at, &r); else if (cap < budget && want > 0 && capped_at < 0) { const int64_t full = plan_chunk(r.n_computed, end, budget, nullptr, @@ -2129,6 +2208,9 @@ const RadBatch* Scheduler::step() { s.sched_tokens = (int32_t)want; plan_.e.push_back(e); plan_.n_tok += want; + if (prefill && mixed_target_active_) { + mixed_target_prefill_planned_ += want; + } if (!prefill && s.n_draft > plan_.n_spec) plan_.n_spec = s.n_draft; budget -= want; ++i; @@ -2173,7 +2255,15 @@ const RadBatch* Scheduler::step() { ? share_tok : 0; admit_full_ = 0; admit_next_step_ = false; - const int as = admit_one(s, budget, areserve); + const int64_t mixed_target_shares = mixed_target_active_ + ? std::min( + (int64_t)waiting_.size() - (int64_t)at - 1, + std::min( + cfg_.max_seqs - (int64_t)plan_.e.size() - 1, + (int64_t)free_cards_.size() - 1)) + : 0; + const int as = admit_one(s, budget, areserve, + std::max(0, mixed_target_shares)); /* A preempted request waiting for its whole-recompute gate lets the next one be asked; * an overdue one does not. The room the overdue path made this step is for it, and a * request queued behind it would take that room back: a victim just forced off for it, @@ -2237,6 +2327,9 @@ const RadBatch* Scheduler::step() { s.entry = (int32_t)plan_.e.size(); plan_.e.push_back(e); plan_.n_tok += s.sched_tokens; + if (mixed_target_active_) { + mixed_target_prefill_planned_ += s.sched_tokens; + } budget -= s.sched_tokens; took_.push_back(at); ++at; @@ -2266,6 +2359,11 @@ const RadBatch* Scheduler::step() { * to it at most. */ int64_t limit = std::min(capped_full, had + budget); if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk)); + if (mixed_target_active_ && mixed_target_.cap() > 0) { + const int64_t other = std::max(0, mixed_target_prefill_planned_ - had); + const int64_t left = std::max(0, mixed_target_.cap() - other); + limit = std::min(limit, std::max(had, left)); + } int64_t ckpt = -1; const int64_t grown = e.ckpt_slot < 0 && limit > had ? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at, &r) @@ -2276,6 +2374,7 @@ const RadBatch* Scheduler::step() { if (ckpt > 0) reserve_ckpt(e, r, ckpt, (int32_t)(ckpt - r.n_computed - 1)); s.sched_tokens = (int32_t)grown; plan_.n_tok += grown - had; + if (mixed_target_active_) mixed_target_prefill_planned_ += grown - had; budget -= grown - had; } if (e.n_tokens < capped_full) ++m_.prefill_chunks_capped; @@ -2313,6 +2412,11 @@ const RadBatch* Scheduler::step() { plan_.phase = any_pf && n_dec ? RAD_PHASE_MIXED : any_pf ? RAD_PHASE_PREFILL : RAD_PHASE_DECODE; + if (mixed_target_active_) { + mixed_target_prefill_continues_ = false; + for (const StepEntry& e : plan_.e) + if (e.is_prefill && !e.produces_token) mixed_target_prefill_continues_ = true; + } /* Step-shape counters. `steps_mixed` / `steps` shows how often a step carries both kinds of * row. `decode_rows_unspeculated` counts every decode row that took no draft, whatever the @@ -2907,6 +3011,18 @@ int Scheduler::commit(StepResult& res) { * * Host timing, always available. Per-op device timing adds synchronisations that change the * mover's slot supply, so profiled runs are not comparable (spec §16). */ +void Scheduler::record_step(int64_t ns, int64_t end_ns) { + diag::StepRecord r; + r.step = m_.steps; + r.phase = plan_.phase; + r.n_seq = (int32_t)plan_.e.size(); + r.prefill_tok = (int32_t)step_prefill_tok_; + r.decode_tok = (int32_t)step_decode_tok_; + r.ns = ns; + r.end_ns = end_ns; + step_ring_.push(r); +} + void Scheduler::step_finished() { std::lock_guard lk(mu_); if (step_start_.time_since_epoch().count() == 0) return; /* no step has run */ @@ -2915,6 +3031,9 @@ void Scheduler::step_finished() { const int64_t ns = std::chrono::duration_cast(step_end - step_start_).count(); m_.step_ns += ns; + mixed_target_observe_locked(ns); + (this->*record_step_)(ns, std::chrono::duration_cast( + step_end.time_since_epoch()).count()); if (plan_.phase == RAD_PHASE_DECODE) { m_.step_ns_decode += ns; /* The single-sequence floor over the step just timed (rad::DecodeFloor). A mixed step @@ -2972,6 +3091,48 @@ void Scheduler::step_finished() { step_start_ = {}; } +/* The mixed-step target's one timing entry point. `step_finished` supplies the live bracket; + * note_mixed_step_cost supplies a deterministic bracket to scheduler tests and host simulations. */ +void Scheduler::mixed_target_observe_locked(int64_t ns) { + int64_t rows = 0; + for (const StepEntry& e : plan_.e) if (e.is_prefill) rows += e.n_tokens; + if (cfg_.mixed_step_target_ms <= 0 || plan_.phase != RAD_PHASE_MIXED || + rows <= 0 || plan_.n_seq_decode <= 0 || ns <= 0) return; + + const int64_t target_ns = cfg_.mixed_step_target_ms * 1000000ll; + ++m_.mixed_step_target_steps; + if (ns > target_ns) ++m_.mixed_step_target_misses; + const int64_t before = mixed_target_.cap(); + mixed_target_.observe(rows, ns, target_ns, std::max(geo_.quantum, 1), + geo_.shared_tok, mixed_target_prefill_continues_); + m_.mixed_step_target_prefill_cap = mixed_target_.cap(); + if (mixed_target_.cap() != before && (int)log_level() >= (int)Log::Debug) + RAD_DEBUG("scheduler: mixed-step target observed %.2f ms over %lld prefill token(s); " + "adaptive mixed-prefill cap %lld -> %lld for a %lld ms target", + (double)ns / 1e6, (long long)rows, (long long)before, + (long long)mixed_target_.cap(), (long long)cfg_.mixed_step_target_ms); +} + +void Scheduler::note_mixed_step_cost(int64_t ns) { + std::lock_guard lk(mu_); + mixed_target_observe_locked(ns); +} + +uint64_t Scheduler::step_record_count() const { + std::lock_guard lk(mu_); + return step_ring_.count(); +} + +size_t Scheduler::step_record_capacity() const { + std::lock_guard lk(mu_); + return step_ring_.capacity(); +} + +uint64_t Scheduler::step_records(uint64_t from, std::vector* out) const { + std::lock_guard lk(mu_); + return step_ring_.copy_since(from, out); +} + /* ------------------------------------------------------------------ the serial drafter */ /* Which sequences may take a serial draft after the step just run, and what each needs. Called * while plan() still describes that step, since everything here indexes into it: the head reads diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index d69d8b75..e8f3b4e6 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -17,6 +17,7 @@ #include "lookup.h" #include "metrics.h" #include "ngram.h" +#include "diag/diagnose.h" #include #include @@ -230,6 +231,17 @@ public: void take_completed(std::vector* out); int reap(uint64_t id); + /* ---------------------------------------------------------- the step record (--diagnose) + * + * One diag::StepRecord per committed step, in a ring sized at init and only with --diagnose: a + * serving process keeps no ring and records nothing. A reader takes every step a phase ran -- + * its shape and its time -- without a second clock. Both calls take the lock; `step_records` + * appends what came after `from` and returns how many of those the ring overwrote before they + * were read (diag/diagnose.h). */ + uint64_t step_record_count() const; + size_t step_record_capacity() const; /* 0 without --diagnose */ + uint64_t step_records(uint64_t from, std::vector* out) const; + /* ---------------------------------------------------------- the lock, for the engine * * Every mutation of the KV manager and the prefix cache happens under this lock; neither has @@ -374,6 +386,9 @@ public: * so the draft rounds are charged to the step (see the definition). Without it the counters * stay correct but there is no timing. */ void step_finished(); + /* Feed the open mixed step a completed service time, as step_finished does. Visible for + * deterministic scheduler tests and timed host simulations. */ + void note_mixed_step_cost(int64_t ns); /* ---------------------------------------------------- the serial drafter (spec §10) * @@ -514,7 +529,8 @@ public: * and `shared` says rows are already planned ahead of it. Returns `budget` when * --busy-prefill-chunk is off, or when auto has nothing to reserve. */ int64_t busy_cap(int64_t n_computed, int64_t n_target, int64_t budget, int64_t reserve, - bool shared = false, bool rows_only = false) const; + bool shared = false, bool rows_only = false, + int64_t mixed_target_shares = 0, int64_t mixed_target_decode_reserve = 0) const; /* Where a prefill chunk of a `n_target`-token sequence may end. For a sequence with a runtime * window (IKVManager::set_window) a chunk ends at the prompt, and past it the output a * recompute replays runs one token a step: the ring rewrites its slots in place, so a @@ -800,6 +816,13 @@ private: * throughput window; metrics() decays what it reports by this. */ std::chrono::steady_clock::time_point last_step_at_ = std::chrono::steady_clock::now(); int64_t step_prefill_tok_ = 0, step_decode_tok_ = 0; + /* The step record, picked once at init: with --diagnose the ring is sized and record_step is + * written into it, without it step_finished calls a no-op. One indirect call a step, no test + * of the mode and no ring on the serving path. Callers of step_finished hold mu_. */ + void record_step(int64_t ns, int64_t end_ns); + void record_no_step(int64_t, int64_t) {} + void (Scheduler::*record_step_)(int64_t, int64_t) = &Scheduler::record_no_step; + diag::StepRing step_ring_; /* --prefill-interleave: decode-only steps still owed before the next chunk, and how many * prefilling requests the last step() held back. step_next_locked stops issuing ahead once * the hold is spent, or the chunk would wait as long as the decoders keep stepping ahead. */ @@ -812,6 +835,17 @@ private: static constexpr int64_t kInterleaveAutoMax = 64; double ema_chunk_s_ = 0.0, ema_decode_s_ = 0.0; void step_cost_locked(bool chunk, double seconds); + /* --mixed-step-target-ms: learned mixed-step cap and whether this planning pass has a decoder + * whose output latency the cap protects. */ + MixedStepTarget mixed_target_; + bool mixed_target_active_ = false; + /* Aggregate prefill rows already admitted to this mixed step. The learned cap is a budget + * for the step, not a per-request allowance. */ + int64_t mixed_target_prefill_planned_ = 0; + /* At least one prefill in the issued mixed step has work beyond this chunk. Unlike a true + * prompt tail, a policy or checkpoint-limited chunk is representative feedback. */ + bool mixed_target_prefill_continues_ = false; + void mixed_target_observe_locked(int64_t ns); /* The throughput window (step_finished): each kind's tokens and the wall time the steps * covered, both decayed with the same time constant, so their ratio is tokens over time. */ double tps_win_prefill_ = 0.0, tps_win_decode_ = 0.0, tps_win_time_ = 0.0; @@ -875,7 +909,8 @@ private: /* RAD_OK, or a negative status when the request cannot be admitted now, nor anything behind * it. `reserve`: tokens of the step to leave for the requests queued behind this one * (--busy-prefill-chunk; busy_cap); 0 plans the chunk on the whole budget. */ - int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0); + int admit_one(SchedReq& s, int64_t budget, int64_t reserve = 0, + int64_t mixed_target_shares = 0); /* Positive sentinel from admit_one: the request waits (its context is still being read off * disk, or a preempted prefill has no room yet) and the walk may ask the one behind it. */ static constexpr int kAdmitWait = 1; diff --git a/core/server/adapters.h b/core/server/adapters.h index da358175..0c085442 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -152,6 +152,9 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) { o.steps_ahead = m.steps_ahead; o.prefill_chunks_capped = m.prefill_chunks_capped; o.steps_held = m.steps_held; + o.mixed_step_target_steps = m.mixed_step_target_steps; + o.mixed_step_target_misses = m.mixed_step_target_misses; + o.mixed_step_target_prefill_cap = m.mixed_step_target_prefill_cap; o.decode_rows_unspeculated = m.decode_rows_unspeculated; o.step_ns = m.step_ns; o.step_ns_decode = m.step_ns_decode; o.step_ns_decode_best = m.step_ns_decode_best; diff --git a/core/server/audio_gen.cpp b/core/server/audio_gen.cpp index 023b0677..ed60b806 100644 --- a/core/server/audio_gen.cpp +++ b/core/server/audio_gen.cpp @@ -254,9 +254,16 @@ int Server::speech_request(const json& body, const std::string& text, } if (refs.empty()) r->ref_cu.clear(); } - if (!refs.empty() && !inst.empty()) + const bool ref_direction = !refs.empty() && !inst.empty(); + if (ref_direction && info.tmpl_ref_instruct.empty()) return fail(err_unsupported("instructions", "a request with references takes no " "instructions; the clips set the voice")); + /* A model whose negative template omits the reference has not declared reference CFG. + * In particular Breeze's ref_clone_tata is an unguided continuation, not voice design. */ + if (!refs.empty() && info.branches != 1 && r->cfg > 1.0f && + (!ref_direction || info.neg_tmpl_ref.empty())) + return fail(err_unsupported("guidance_scale", "voice cloning requires guidance_scale 1; " + "this model has no guided reference template")); /* ---- the prompt */ std::string i2, t2, why; @@ -277,26 +284,28 @@ int Server::speech_request(const json& body, const std::string& text, /* One reference (ref_item): its header, the transcript in it, tokenised as one segment with * its special tokens (the speaker tags prepare() allows), a row a frame of its clip, and what * follows the clip as another segment. */ - int64_t frame0 = 0; - auto render_ref = [&](size_t i, std::vector* ids_out) { + auto render_ref = [&](size_t i, std::vector* ids_out, + std::vector* frame_map, int64_t& frame0) { static const std::string kAudio = "{audio}"; const std::string idx = std::to_string(i + 1); const size_t a = info.ref_item.find(kAudio); encode(subst(subst(info.ref_item.substr(0, a), "{index}", idx), "{text}", refs[i].text), true, ids_out); - r->ref_frame.resize(ids_out->size(), -1); + frame_map->resize(ids_out->size(), -1); for (int64_t f = 0; f < refs[i].frames; ++f) { ids_out->push_back(0); - r->ref_frame.push_back((int32_t)(frame0 + f)); + frame_map->push_back((int32_t)(frame0 + f)); } frame0 += refs[i].frames; encode(subst(info.ref_item.substr(a + kAudio.size()), "{index}", idx), true, ids_out); }; /* A template a segment at a time: its own text with special tokens, each slot without. */ - auto render = [&](const std::string& t, std::vector* ids_out) { + auto render = [&](const std::string& t, std::vector* ids_out, + std::vector* frame_map) { static const std::string kInst = "{instructions}", kInput = "{input}", kRefs = "{references}"; size_t at = 0; + int64_t frame0 = 0; while (at <= t.size()) { const size_t a = t.find(kInst, at), b = t.find(kInput, at), c = t.find(kRefs, at); const size_t p = std::min(a, std::min(b, c)); @@ -304,7 +313,7 @@ int Server::speech_request(const json& body, const std::string& text, ids_out); if (p == std::string::npos) break; if (p == c) { - for (size_t i = 0; i < refs.size(); ++i) render_ref(i, ids_out); + for (size_t i = 0; i < refs.size(); ++i) render_ref(i, ids_out, frame_map, frame0); at = p + kRefs.size(); continue; } @@ -314,11 +323,14 @@ int Server::speech_request(const json& body, const std::string& text, encode(is_inst ? i2 : t2, !is_inst && info.input_special, ids_out); at = p + (is_inst ? kInst : kInput).size(); } + if (frame_map) frame_map->resize(ids_out->size(), -1); }; - render(!refs.empty() ? info.tmpl_ref : inst.empty() ? info.tmpl_plain : info.tmpl, - &r->tokens); - if (!refs.empty()) r->ref_frame.resize(r->tokens.size(), -1); - if (!info.neg_tmpl.empty()) render(info.neg_tmpl, &r->neg_tokens); + render(ref_direction ? info.tmpl_ref_instruct : !refs.empty() ? info.tmpl_ref : + inst.empty() ? info.tmpl_plain : info.tmpl, &r->tokens, + refs.empty() ? nullptr : &r->ref_frame); + if (ref_direction) + render(info.neg_tmpl_ref, &r->neg_tokens, &r->neg_ref_frame); + else if (!info.neg_tmpl.empty()) render(info.neg_tmpl, &r->neg_tokens, nullptr); const size_t n_prompt = std::max(r->tokens.size(), r->neg_tokens.size()); if ((int64_t)n_prompt > info.max_prompt) return fail(err_bad("input", "the prompt is " + std::to_string(n_prompt) + diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 91172ab5..9bf7fe0e 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -372,6 +372,9 @@ HttpResponse Server::handle_stats(const HttpRequest&) { o["prefill_chunks_capped"] = m.prefill_chunks_capped; o["steps_decode"] = m.steps_decode; o["steps_held"] = m.steps_held; + o["mixed_step_target_steps"] = m.mixed_step_target_steps; + o["mixed_step_target_misses"] = m.mixed_step_target_misses; + o["mixed_step_target_prefill_cap"] = m.mixed_step_target_prefill_cap; /* Time inside steps. The one rate the page cannot derive: wall clock between polls also * covers idle time (see SchedMetrics::step_ns). */ o["step_ns"] = m.step_ns; diff --git a/core/server/iface.h b/core/server/iface.h index 987df41d..f1b58851 100644 --- a/core/server/iface.h +++ b/core/server/iface.h @@ -142,6 +142,9 @@ struct SchedMetrics { int64_t steps_ahead = 0; /* issued behind the step before, ahead of its commit */ int64_t prefill_chunks_capped = 0; /* held back for other work in the step (--busy-prefill-chunk) */ int64_t steps_held = 0; /* decode-only steps --prefill-interleave inserted */ + int64_t mixed_step_target_steps = 0; /* mixed steps observed by --mixed-step-target-ms */ + int64_t mixed_step_target_misses = 0; /* those whose completed wall time exceeded the target */ + int64_t mixed_step_target_prefill_cap = 0; /* current learned mixed-prefill row cap */ int64_t decode_rows_unspeculated = 0; /* Cumulative nanoseconds inside steps, all shapes and decode-only. Wall clock over a step * count is not a step time: the engine idles between turns, and a prefill chunk costs an @@ -753,6 +756,7 @@ struct AudioGenInfo { /* RadAudioGenDecl's references: the prompt with them and one reference ("" when the model * takes none), the clips' rate and frame, and the most of them and their samples. */ std::string tmpl_ref, ref_item; + std::string tmpl_ref_instruct, neg_tmpl_ref; int64_t ref_rate = 0, ref_hop = 0, ref_max_samples = 0; int32_t ref_max = 0; }; diff --git a/core/server/metrics.cpp b/core/server/metrics.cpp index 1dd65298..5db56040 100644 --- a/core/server/metrics.cpp +++ b/core/server/metrics.cpp @@ -154,6 +154,7 @@ void Metrics::sample(const SchedMetrics& m) { /* Nanoseconds in the scheduler, seconds on the wire, as engine_step_seconds_* use. */ g_step_best_.set((double)m.step_ns_decode_best / 1e9); g_step_recent_.set((double)m.step_ns_decode_recent / 1e9); + g_mixed_step_target_cap_.set((double)m.mixed_step_target_prefill_cap); const int seen = std::max(0, std::min(m.draft_depth_seen, (int)MAX_DRAFT_POS)); for (int j = 0; j < seen; ++j) { const int64_t r = m.draft_pos_reached[j]; @@ -184,6 +185,8 @@ void Metrics::sample(const SchedMetrics& m) { c_steps_ahead_.advance_to(m.steps_ahead); c_prefill_capped_.advance_to(m.prefill_chunks_capped); c_steps_held_.advance_to(m.steps_held); + c_mixed_step_target_steps_.advance_to(m.mixed_step_target_steps); + c_mixed_step_target_misses_.advance_to(m.mixed_step_target_misses); c_rows_unspec_.advance_to(m.decode_rows_unspeculated); c_step_secs_.advance_to((double)m.step_ns * 1e-9); c_step_secs_decode_.advance_to((double)m.step_ns_decode * 1e-9); @@ -418,6 +421,16 @@ std::string Metrics::render() const { w.counter("radiance:engine_steps_held_total", "Decode-only steps run after a prefill chunk while other sequences decode " "(--prefill-interleave).", L, c_steps_held_.get()); + w.counter("radiance:mixed_step_target_steps_total", + "Mixed prefill/decode steps observed by --mixed-step-target-ms.", + L, c_mixed_step_target_steps_.get()); + w.counter("radiance:mixed_step_target_misses_total", + "Mixed steps whose completed service time exceeded --mixed-step-target-ms.", + L, c_mixed_step_target_misses_.get()); + if (g_mixed_step_target_cap_.get() > 0) + w.gauge("radiance:mixed_step_target_prefill_cap", + "Current learned prefill-row cap used while decode sequences are active.", + L, g_mixed_step_target_cap_.get()); w.counter("radiance:decode_rows_unspeculated_total", "Decode rows that took no draft, for any reason.", L, c_rows_unspec_.get()); diff --git a/core/server/metrics.h b/core/server/metrics.h index 8702af83..ab5734ab 100644 --- a/core/server/metrics.h +++ b/core/server/metrics.h @@ -149,6 +149,8 @@ private: * rate over a window rather than an average dominated by startup. */ Counter c_steps_prefill_, c_steps_mixed_, c_steps_decode_, c_rows_unspec_, c_steps_ahead_; Counter c_prefill_capped_, c_steps_held_; + Counter c_mixed_step_target_steps_, c_mixed_step_target_misses_; + Gauge g_mixed_step_target_cap_; /* Seconds inside a step, all shapes and decode-only. Wall clock over a step count is not a * step time (see SchedMetrics::step_ns). */ Counter c_step_secs_, c_step_secs_decode_; diff --git a/core/text/chat.cpp b/core/text/chat.cpp index 63753551..eb5c3f33 100644 --- a/core/text/chat.cpp +++ b/core/text/chat.cpp @@ -263,6 +263,13 @@ static bool alias_reasoning(const ojson& messages, ojson* out) { } return v; }; + /* A call that takes no arguments, as clients replay it: null, or the empty or blank string a + * client stores from a stream that sent none. */ + auto no_arguments = [](const ojson& a) { + return a.is_null() || + (a.is_string() && a.get_ref().find_first_not_of(" \t\r\n") == + std::string::npos); + }; auto needs = [&](const ojson& m) { if (!m.is_object()) return false; const auto rc = m.find("reasoning_content"); @@ -283,7 +290,7 @@ static bool alias_reasoning(const ojson& messages, ojson* out) { if (!call.is_object()) continue; const auto fn = call.find("function"); if (!call.contains("type") || fn == call.end() || !fn->is_object() || - !fn->contains("arguments") || fn->at("arguments").is_null()) + !fn->contains("arguments") || no_arguments(fn->at("arguments"))) return true; } return false; @@ -336,7 +343,7 @@ static bool alias_reasoning(const ojson& messages, ojson* out) { call.erase("name"); call.erase("arguments"); } - } else if (!fn->contains("arguments") || fn->at("arguments").is_null()) { + } else if (!fn->contains("arguments") || no_arguments(fn->at("arguments"))) { (*fn)["arguments"] = "{}"; } } @@ -344,6 +351,33 @@ static bool alias_reasoning(const ojson& messages, ojson* out) { return true; } +/* The first replayed call whose arguments are a string that is not JSON, as + * "messages[i].tool_calls[j].function.arguments is not JSON: ", or empty when every call's + * arguments parse. The template refuses such a conversation with the parser's words alone, which reads as + * the template's fault; this names the call. */ +static std::string bad_arguments(const ojson& messages) { + if (!messages.is_array()) return ""; + for (size_t i = 0; i < messages.size(); ++i) { + const ojson& m = messages[i]; + const auto tcs = m.is_object() ? m.find("tool_calls") : m.end(); + if (!m.is_object() || tcs == m.end() || !tcs->is_array()) continue; + for (size_t j = 0; j < tcs->size(); ++j) { + const ojson& tc = (*tcs)[j]; + const auto fn = tc.is_object() ? tc.find("function") : tc.end(); + if (!tc.is_object() || fn == tc.end() || !fn->is_object()) continue; + const auto args = fn->find("arguments"); + if (args == fn->end() || !args->is_string()) continue; + try { + (void)ojson::parse(args->get_ref()); + } catch (const std::exception& e) { + return "messages[" + std::to_string(i) + "].tool_calls[" + std::to_string(j) + + "].function.arguments is not JSON: " + e.what(); + } + } + } + return ""; +} + int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOptions& opt, ChatPrompt* out) const { if (!ready()) { @@ -430,6 +464,11 @@ int ChatTemplate::apply(const ojson& messages, const ojson& tools, const ChatOpt } } if (!served) { + if (const std::string bad = bad_arguments(msgs); !bad.empty()) { + if (!opt.quiet) RAD_WARN("chat: request did not parse: %s", bad.c_str()); + out->error = bad; + return RAD_E_INVAL; + } const std::string w = template_words(e.what()); if (!opt.quiet) RAD_WARN("chat: the model's chat template refused the request: %s", w.c_str()); diff --git a/core/text/chat.h b/core/text/chat.h index 292cd0bb..f5eeb6c6 100644 --- a/core/text/chat.h +++ b/core/text/chat.h @@ -114,7 +114,8 @@ public: /* Render. `messages` and `tools` are OpenAI-shaped JSON (`tools` may be null or empty). * Returns RAD_OK, RAD_E_INVAL when the request does not parse, or RAD_E_UNSUPPORTED when the * template refuses it (e.g. a system message without a system role, or tools without tool - * support). */ + * support). Replayed history is read in other servers' shapes first: a turn's reasoning under + * `reasoning` or `thinking`, and a call whose arguments are null, blank or absent. */ int apply(const Json& messages, const Json& tools, const ChatOptions& opt, ChatPrompt* out) const; diff --git a/core/text/chatfmt.cpp b/core/text/chatfmt.cpp index b1cb467e..a8ba4e2d 100644 --- a/core/text/chatfmt.cpp +++ b/core/text/chatfmt.cpp @@ -353,6 +353,7 @@ int chat_format_from_abi(const RadChatFormat* in, ChatFormat* out, std::string* f.object_bare_keys = c.object_bare_keys != 0; f.reasoning_anywhere = c.reasoning_anywhere != 0; f.arg_json_value_prefix = s(c.arg_json_value_prefix); + f.content_open = s(c.content_open); *out = std::move(f); return RAD_OK; } @@ -468,6 +469,7 @@ std::string chat_format_describe(const ChatFormat& f) { (f.reasoning_anywhere ? " anywhere" : ""); else s += " no reasoning"; + if (!f.content_open.empty()) s += "; content " + show(f.content_open); if (f.has_tools() && !f.section_open.empty()) s += "; section " + show(f.section_open) + ".." + show(f.section_close); if (f.has_tools() && f.object_args()) { @@ -498,7 +500,8 @@ std::string chat_format_describe(const ChatFormat& f) { std::vector chat_format_markers(const ChatFormat& f) { std::vector out; - for (const std::string* s : { &f.reasoning_open, &f.reasoning_close, &f.section_open, + for (const std::string* s : { &f.reasoning_open, &f.reasoning_close, &f.content_open, + &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_json_value_prefix, diff --git a/core/text/chatfmt.h b/core/text/chatfmt.h index cf826ddc..978bb2ed 100644 --- a/core/text/chatfmt.h +++ b/core/text/chatfmt.h @@ -100,6 +100,9 @@ struct ChatFormat { * reasoning there; a close with no block open is dropped. Gemma 4 sometimes writes an empty * block after its answer, or a lone close. Needs `reasoning_open`. */ bool reasoning_anywhere = false; + /* A header the model writes first when it answers without reasoning; dropped when the reply + * starts with it. Empty: none. */ + std::string content_open; /* ------------------------------------------------------------------ tool calls * `name_prefix` is what opens a call (after `call_open`, when there is one). Empty means the diff --git a/core/text/chatparse.cpp b/core/text/chatparse.cpp index adc74165..73d5ba0b 100644 --- a/core/text/chatparse.cpp +++ b/core/text/chatparse.cpp @@ -1063,7 +1063,8 @@ int ReplyParser::create(std::shared_ptr fmt, const ReplyOptio /* A response format replaces the call grammar outright; the calls are not parsed. */ 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.pure = !F.f.has_reasoning() && !want_calls && !opt.response_format && + F.f.content_open.empty(); P.anywhere = F.f.reasoning_anywhere && F.f.has_reasoning() && opt.extract_reasoning && !opt.response_format; @@ -1093,6 +1094,7 @@ enum class St : uint8_t { LeadWs, /* whitespace before the reply proper: dropped */ ThinkOpen, /* the core of reasoning_open */ ThinkOpenWs, /* the optional whitespace that ends reasoning_open */ + ContentOpen, /* content_open, the header of a reply that does not reason */ Think, /* reasoning text */ ThinkCloseWs, /* the optional whitespace that ends reasoning_close */ Text, /* content, watching for the call opener when calls are on */ @@ -1149,6 +1151,7 @@ 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; + think_hold_on = P.calls && !F.f.reasoning_breaks.empty(); if (P.anywhere) { text_dfa = P.calls ? &F.text_think : &F.think_only; n_open = P.calls ? F.openers.size() : 0; @@ -1211,6 +1214,16 @@ struct ReplyStream::Impl { std::string vheld; size_t vs_pos = 0; bool fenced = false; + /* Channel-scoped protocols (Muse): with tools on, a trailing `to=NAME<|message|>` while + * reasoning streams is the handoff to a tool call, not reasoning text. The reasoning's + * tail is held until it cannot grow into framing or a header; a completed tool-channel + * header is dropped along with everything after it -- the section opener is where the + * call machinery takes over. Without the hold the header lands in the reasoning stream, + * and a model that hesitates at the handoff repeats it (observed on Muse Glimmer: three + * or four `to=read<|message|>` headers before the section, under speculative decoding). */ + bool think_hold_on = false; + std::string think_hold; + bool think_handoff = false; /* The argument object being read: its open brackets; whether a key (not a value) is being * read; a separator read but not yet written (written only once the next member shows the @@ -1293,12 +1306,108 @@ struct ReplyStream::Impl { void think_out(const char* p, size_t n) { if (n == 0) return; + if (think_handoff) return; /* past the tool-channel header: call framing, dropped */ touch(0); - if (think_text) { msg.reasoning.append(p, n); return; } - for (size_t i = 0; i < n; ++i) - if (!is_blank((unsigned char)p[i])) { think_text = true; break; } - think_pend.append(p, n); - if (think_text) { msg.reasoning += think_pend; think_pend.clear(); } + if (!think_hold_on) { + if (think_text) { msg.reasoning.append(p, n); return; } + for (size_t i = 0; i < n; ++i) + if (!is_blank((unsigned char)p[i])) { think_text = true; break; } + think_pend.append(p, n); + if (think_text) { msg.reasoning += think_pend; think_pend.clear(); } + return; + } + touch(0); + think_hold.append(p, n); + flush_think_hold(false); + } + + void emit_reasoning_upto(size_t emit) { + if (emit == 0) return; + const std::string part = think_hold.substr(0, emit); + if (think_text) { msg.reasoning += part; } + else { + for (size_t i = 0; i < part.size(); ++i) + if (!is_blank((unsigned char)part[i])) { think_text = true; break; } + think_pend += part; + if (think_text) { msg.reasoning += think_pend; think_pend.clear(); } + } + } + + /* The handoff position from the last `<|eom|>`: the tail reads as the tool-channel + * header -- optional `<|start|>assistant`, ws, `to=`, recipient name bytes (never + * `user`: that transition matches the reply close above and is consumed by it), then + * `<|message|>` or a prefix of it while the header streams. npos: no handoff. */ + size_t tool_handoff_at() const { + static const std::string eom = "<|eom|>", start = "<|start|>assistant", to = "to="; + /* The framing is bounded (terminator + assistant + `to=` + a recipient + the message + * marker); scanning only the tail keeps a byte-at-a-time stream linear. */ + const size_t wstart = think_hold.size() - std::min(kHoldWindow, think_hold.size()); + size_t p = std::string::npos; + for (size_t q = think_hold.find(eom, wstart); q != std::string::npos; + q = think_hold.find(eom, q + 1)) + p = q; + if (p == std::string::npos) return std::string::npos; + size_t k = p + eom.size(); + if (think_hold.compare(k, start.size(), start) == 0) k += start.size(); + while (k < think_hold.size() && is_ws((unsigned char)think_hold[k])) ++k; + if (think_hold.compare(k, to.size(), to) != 0) return std::string::npos; + return p; /* everything from `<|eom|>` on is the tool call's framing */ + } + + /* Muse's channel protocol, per the reference parsers (vLLM's muse reasoning/tool + * parsers; llama.cpp PR #26841): reasoning streams until `<|eom|>`, and the model + * sometimes leaves the analysis channel WITHOUT it, opening a tool channel directly + * (`<|start|>assistant to=read<|message|>`) -- a documented model-side defect. So the + * reasoning's tail is held while it could still grow into that framing, and once the + * handoff is detected everything from the header on is dropped: the call machinery + * (the section + invoke tags) has already produced the tool_calls events. */ + void flush_think_hold(bool final_feed) { + if (think_handoff) return; /* past the handoff: framing, dropped */ + size_t emit = think_hold.size(); + const size_t handoff = tool_handoff_at(); + if (handoff != std::string::npos) { + emit = handoff; + think_handoff = true; + } else if (!final_feed) { + /* Hold a tail that could still grow into the handoff framing: a partial + * `<|eom|>` / `<|start|>` / `<|message|>` marker, or a trailing ` to=NAME`. */ + static const std::string markers[] = {"<|eom|>", "<|start|>", "<|message|>"}; + for (const std::string& mk : markers) + for (size_t k = std::min(mk.size(), think_hold.size()); k > 0; --k) + if (think_hold.compare(think_hold.size() - k, k, mk, 0, k) == 0) + emit = std::min(emit, think_hold.size() - k); + const size_t wstart_t = think_hold.size() - std::min(kHoldWindow, think_hold.size()); + size_t at = std::string::npos; + for (size_t q = think_hold.find("to=", wstart_t); q != std::string::npos; + q = think_hold.find("to=", q + 1)) + at = q; + if (at != std::string::npos) { + bool tail = true; + for (size_t k = at + 3; k < think_hold.size(); ++k) + if (!is_name_byte((unsigned char)think_hold[k])) { tail = false; break; } + if (tail) { + size_t a = at; + while (a > 0 && is_ws((unsigned char)think_hold[a - 1])) --a; + emit = std::min(emit, a); + } + } + if (emit >= think_hold.size()) { + emit_reasoning_upto(emit); + think_hold.clear(); /* nothing held: everything goes out now */ + return; + } + } + if (emit > 0) emit_reasoning_upto(emit); + think_hold.erase(0, emit); + if (final_feed) think_hold.clear(); + } + + /* The tail the framing scans read; a longer tail is real reasoning, never framing. */ + static constexpr size_t kHoldWindow = 160; + + static bool is_name_byte(unsigned char c) { + return (c >= 'A' && c <= 'Z') || (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || + c == '_' || c == '.' || c == '-'; } void text_out(const char* p, size_t n) { @@ -2051,6 +2160,20 @@ struct ReplyStream::Impl { return p + 1; } /* No block: what was held is read again as whatever follows one. */ + st = after_no_block(); + read_again(lhold); + lhold.clear(); + return p; + } + + case St::ContentOpen: { + const unsigned char c = (unsigned char)*p; + if (lpos < F.f.content_open.size() && (unsigned char)F.f.content_open[lpos] == c) { + lhold.push_back((char)c); + if (++lpos == F.f.content_open.size()) { lhold.clear(); st = after_think(); } + return p + 1; + } + /* Not the header: what was held is content (or the start of the document). */ st = after_think(); read_again(lhold); lhold.clear(); @@ -2066,10 +2189,11 @@ struct ReplyStream::Impl { case St::Think: { const Dfa& d = P.breaks ? F.think_breaks : F.think; p = scan(d, p, e, &hit, [this](const char* q, size_t n) { think_out(q, n); }); - if (hit == 0) { trail = 0; st = St::ThinkCloseWs; } + if (hit == 0) { flush_think_hold(true); trail = 0; st = St::ThinkCloseWs; } else if (hit > 0) { const std::string& marker = d.pattern(hit); if (!F.section_open_core.empty() && marker == F.section_open_core) { + flush_think_hold(true); open_section(); st = St::Text; } else if (!F.section_open_core.empty() && !section_active) { @@ -2754,10 +2878,17 @@ struct ReplyStream::Impl { return e; } - St after_lead() const { + St after_lead() { if (F.f.has_reasoning() && P.opt.extract_reasoning) return F.open_core.empty() ? St::Think : St::ThinkOpen; - return after_think(); + return after_no_block(); + } + /* The reply did not open a reasoning block: its content_open header, when the format has one, + * is matched from the first byte (the bytes of a failed reasoning opener are read again). */ + St after_no_block() { + if (F.f.content_open.empty()) return after_think(); + lpos = 0; + return St::ContentOpen; } St after_think() const { return P.opt.response_format ? St::RfWs : St::Text; } @@ -2887,6 +3018,14 @@ struct ReplyStream::Impl { rerun(); } if (st == St::ObjStr || st == St::ObjQStr) str_flush(); + /* The reply ended inside a header that never completed: its bytes are the reply. */ + while (!F.f.content_open.empty() && !lhold.empty() && + (st == St::ContentOpen || st == St::ThinkOpen)) { + st = st == St::ThinkOpen ? after_no_block() : after_think(); + read_again(lhold); + lhold.clear(); + rerun(); + } while (in_loose_attempt()) { fail_attempt(); rerun(); @@ -2935,6 +3074,7 @@ struct ReplyStream::Impl { } hold.clear(); ds = 0; + if (think_hold_on) flush_think_hold(true); if (!think_text) think_pend.clear(); content.finish(msg.content); if (cur >= 0) publish(cur, true); diff --git a/data/flint-chat-template.jinja b/data/flint-chat-template.jinja new file mode 100644 index 00000000..2299578f --- /dev/null +++ b/data/flint-chat-template.jinja @@ -0,0 +1,61 @@ +{%- macro flint_text(t) -%} +{%- if t is string -%} +{{- t | replace("", "") | replace("", "") | replace("<|begin_of_text|>", "<|begin_of_text|>") | replace("<|end_of_text|>", "<|end_of_text|>") | replace("<|system|>", "<|system|>") | replace("<|developer|>", "<|developer|>") | replace("<|user|>", "<|user|>") | replace("<|assistant|>", "<|assistant|>") | replace("<|observation|>", "<|observation|>") -}} +{%- else -%} +{{- t -}} +{%- endif -%} +{%- endmacro -%} +{%- set tool_preamble -%} +{%- if tools %}<|system|> +# Tools + +You may call one or more functions to assist with the user query. + +You are provided with function signatures within XML tags: + +{%- for tool in tools %} +{%- set fn = tool.function if tool.function is defined else tool %} +{{ fn | tojson(ensure_ascii=False) }} +{%- endfor %} + + +For each function call, output the function name and arguments within the following XML format: +{function-name}{arg-key-1}{arg-value-1}... +{% endif -%} +{%- endset -%} +{%- set ns = namespace(tools_pending=true) -%} +{%- for m in messages -%} +{%- if ns.tools_pending and m.role != 'system' -%} +{{ tool_preamble }} +{%- set ns.tools_pending = false -%} +{%- endif -%} +{%- if m.role == 'system' -%} +<|system|>{{ flint_text(m.content) }} +{%- elif m.role == 'developer' -%} +<|developer|>{{ flint_text(m.content) }} +{%- elif m.role == 'user' -%} +<|user|>{{ flint_text(m.content) }} +{%- elif m.role == 'assistant' -%} +<|assistant|> +{%- if m.reasoning_content %}{{ m.reasoning_content }}{% endif -%} +{%- if m.content %}{{ m.content }}{% endif -%} +{%- if m.tool_calls -%} +{%- for tc in m.tool_calls -%} +{%- set fn = tc.function if tc.function is defined else tc -%} +{{ fn.name }} +{%- for k, v in fn.arguments.items() -%} +{{ k }}{{ v | tojson(ensure_ascii=False) if v is not string else v }} +{%- endfor -%} + +{%- endfor -%} +{%- endif -%} +{%- elif m.role == 'tool' -%} +<|observation|>{{ flint_text(m.content) }} +{%- endif -%} +{%- endfor -%} +{%- if ns.tools_pending -%} +{{ tool_preamble }} +{%- endif -%} +{%- if add_generation_prompt -%} +<|assistant|> +{%- endif -%} diff --git a/data/flint-zero-bias.safetensors b/data/flint-zero-bias.safetensors new file mode 100644 index 00000000..eb43e239 Binary files /dev/null and b/data/flint-zero-bias.safetensors differ diff --git a/data/recipes/breeze-tts2-bf16.recipe b/data/recipes/breeze-tts2-bf16.recipe index c0a42dbe..4c70f73b 100644 --- a/data/recipes/breeze-tts2-bf16.recipe +++ b/data/recipes/breeze-tts2-bf16.recipe @@ -11,6 +11,8 @@ # layer scales and snake parameters stay f32 -- read once a pass or less. dep.heads.weight cast dtype=bf16 +# The reference-audio encoder and Euclidean RVQ run in their released f32 precision. +ref.* cast dtype=f32 codec.*.n1.weight cast dtype=f32 codec.*.n2.weight cast dtype=f32 codec.*.ls1.weight cast dtype=f32 diff --git a/data/recipes/flint-bf16-q4.recipe b/data/recipes/flint-bf16-q4.recipe new file mode 100644 index 00000000..a1a3eecb --- /dev/null +++ b/data/recipes/flint-bf16-q4.recipe @@ -0,0 +1,32 @@ +# flint-bf16-q4.recipe -- Flint as flint-q4.rad: the 19.72 GiB container. +# +# 4-bit attention projections and routed experts; INT8 dense layers, shared expert and output +# head; BF16 router, norms and embedding. Attention tolerates U4; the dense and shared MLPs do +# not, so they stay INT8. +# +# rad-convert --add data/flint-zero-bias.safetensors \ +# --recipe data/recipes/flint-bf16-q4.recipe \ +# --chat-template data/flint-chat-template.jinja \ +# -o flint-q4.rad +# +# Serve: +# radiance --model flint-q4.rad --max-model-len 262144 # one card +# radiance --model flint-q4.rad --tp 2 --max-model-len 262144 # two cards + +blk.*.attn_q.weight rtn codes=u4 zero=u8 group=128 scale=f16 +blk.*.attn_k.weight rtn codes=u4 zero=u8 group=128 scale=f16 +blk.*.attn_v.weight rtn codes=u4 zero=u8 group=128 scale=f16 +blk.*.attn_output.weight rtn codes=u4 zero=u8 group=128 scale=f16 + +blk.*.ffn_gate_up_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +blk.*.ffn_down_shexp.weight rtn codes=i8 group=128 scale=bf16 clamp=sym + +blk.0.ffn_gate_up.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +blk.0.ffn_down.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +blk.1.ffn_gate_up.weight rtn codes=i8 group=128 scale=bf16 clamp=sym +blk.1.ffn_down.weight rtn codes=i8 group=128 scale=bf16 clamp=sym + +blk.*.ffn_gate_up_exps.*.weight rtn codes=i4 group=128 scale=bf16 +blk.*.ffn_down_exps.*.weight rtn codes=i4 group=128 scale=bf16 + +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym diff --git a/data/recipes/flint-iq8r.recipe b/data/recipes/flint-iq8r.recipe new file mode 100644 index 00000000..76463da5 --- /dev/null +++ b/data/recipes/flint-iq8r.recipe @@ -0,0 +1,43 @@ +# flint-iq8r.recipe -- Recursive Flint from its bf16 release with an IQ8R trunk and rotated int8 +# experts, served by arch/flint (the same rotated int8 forms qwen35moe_w8a8 serves with +# data/recipes/q36-35b-a3b-iq8r.recipe). +# +# rad-convert --add data/flint-zero-bias.safetensors \ +# --recipe data/recipes/flint-iq8r.recipe \ +# --chat-template data/flint-chat-template.jinja \ +# -o flint-iq8r.rad +# +# - IQ8R: every trunk linear (attention q, k, v and output; the two dense layers' gate/up and +# down; the shared expert's gate/up) as int8 codes in -127..127 with one u8 scale per +# (row, 256 of K) under one bf16 scale a row, each 128 of K rotated by the unnormalised +# Hadamard before rounding and the 1/128 kept in the row scale (`transform=fwht128`). Round to +# nearest with a scale search; no calibration data is read. The norms, the gated products and +# the attention output write the matching rotated int8 codes, so no linear quantises its own +# input. +# - The 256 routed experts of every layer as int8 on the same rotated grid with one bf16 scale +# per (row, 128 of K). The grouped GEMM reads them at i8a8h (moe_gemm_i8a8): gate/up against +# the block input's own rotated codes, down against the gated product's at one scale a 128. +# - The shared expert's down projection on the experts' grid, its input written at one scale a +# 128 by its gated product. +# - The router, the norms, the sinks and the embedding stay bf16; the lm_head is int8 unrotated +# with a bf16 scale per (row, 128) (logits_gemm_i8). +# +# About 38 GiB, as the int8 container measured on the 1.17-era build. Serve with --tp 2 (expert +# parallel: each card holds 128 whole experts a layer). + +blk.*.attn_q.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.attn_k.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.attn_v.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.attn_output.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search + +blk.0.ffn_gate_up.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.0.ffn_down.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.1.ffn_gate_up.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.1.ffn_down.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search + +blk.*.ffn_gate_up_exps.*.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ffn_down_exps.*.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ffn_gate_up_shexp.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.ffn_down_shexp.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search + +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search diff --git a/data/recipes/ling-3.0-tiny-bf16-gguf.recipe b/data/recipes/ling-3.0-tiny-bf16-gguf.recipe new file mode 100644 index 00000000..576466cd --- /dev/null +++ b/data/recipes/ling-3.0-tiny-bf16-gguf.recipe @@ -0,0 +1,13 @@ +# Ling-3.0-tiny from the IQ4_NL GGUF, fully decoded to bf16: a coherence control that removes +# the quantisation from the equation (the container is the dequantised GGUF, ~15 GiB). +blk.*.attn_norm.weight cast dtype=f32 +blk.*.attn_q_a_norm.weight cast dtype=f32 +blk.*.attn_kv_a_norm.weight cast dtype=f32 +blk.*.ffn_norm.weight cast dtype=f32 +blk.*.ssm_norm.weight cast dtype=f32 +blk.*.ssm_a cast dtype=f32 +blk.*.ssm_dt_bias cast dtype=f32 +blk.*.glm_router.weight cast dtype=f32 +blk.*.glm_router.correction cast dtype=f32 +output_norm.weight cast dtype=f32 +* cast dtype=bf16 diff --git a/data/recipes/ling-3.0-tiny-iq4.recipe b/data/recipes/ling-3.0-tiny-iq4.recipe new file mode 100644 index 00000000..49931732 --- /dev/null +++ b/data/recipes/ling-3.0-tiny-iq4.recipe @@ -0,0 +1,20 @@ +# Ling-3.0-tiny on the 8 GiB gfx1102: the 128 experts of each MoE layer at 4 bits (the +# moe_gemm_w4a8 form, i4 with bf16 scales per 128 of K, ~3.6 GiB over 23 layers), everything +# else bf16 (dense layer 0, the KDA and MLA projections, the shared expert, embed and output: +# ~1.7 GiB). The source is the IQ4_NL GGUF; libquant's ggml port decodes it for the re-quant. +blk.*.ffn_gate_up_exps.*.weight rtn codes=i4 group=128 scale=bf16 +blk.*.ffn_down_exps.*.weight rtn codes=i4 group=128 scale=bf16 +# The shared blocks declare their gains and router correction as f32 planes (A_log and +# dt_bias ship f32 in the checkpoint), so they keep the f32 form the plugin reads; the +# catch-all below takes only what is left. +blk.*.attn_norm.weight cast dtype=f32 +blk.*.attn_q_a_norm.weight cast dtype=f32 +blk.*.attn_kv_a_norm.weight cast dtype=f32 +blk.*.ffn_norm.weight cast dtype=f32 +blk.*.ssm_norm.weight cast dtype=f32 +blk.*.ssm_a cast dtype=f32 +blk.*.ssm_dt_bias cast dtype=f32 +blk.*.glm_router.weight cast dtype=f32 +blk.*.glm_router.correction cast dtype=f32 +output_norm.weight cast dtype=f32 +* cast dtype=bf16 diff --git a/data/recipes/ling-3.0-tiny-iq8r.recipe b/data/recipes/ling-3.0-tiny-iq8r.recipe new file mode 100644 index 00000000..bdde8b31 --- /dev/null +++ b/data/recipes/ling-3.0-tiny-iq8r.recipe @@ -0,0 +1,44 @@ +# ling-3.0-tiny-iq8r.recipe -- Ling-3.0-tiny from its bf16 release with an IQ8R trunk and rotated +# int8 experts, served by bailing_hybrid. +# +# rad-convert --recipe data/recipes/ling-3.0-tiny-iq8r.recipe \ +# -o ling-3.0-tiny-iq8r.rad +# +# - IQ8R: the KDA projections (q|k|v fused, forget, gate, output), the MLA output, the dense +# layer's feed-forward and the shared expert's gate/up as int8 codes in -127..127 with one u8 +# scale per (row, 256 of K) under one bf16 scale a row, each 128 of K rotated by the +# unnormalised Hadamard before rounding (`transform=fwht128`). Round to nearest with a scale +# search; no calibration data is read. +# - The 128 routed experts of every layer and the shared expert's down projection as int8 on the +# same rotated grid with one bf16 scale per (row, 128 of K): an expert is 512 columns. +# - Kept bf16: the KDA beta projection, the MLA's low-rank q and kv projections and its gate, the +# conv1d weights, the router, the embedding and the lm_head. +# +# Serves at --tp 1 or 2: at 4 the dense layer's 1152-column slice cuts a 256-column scale group. +# Ling-3.0-flash clamps its SwiGLU in its last layers, which the int8 gated products have no form +# for, so this recipe's forms do not serve it. + +blk.*.attn_qkv.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.attn_forget.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.attn_gate.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.attn_output.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.ffn_gate_up.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.ffn_down.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.ffn_gate_up_shexp.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search + +blk.*.ffn_gate_up_exps.*.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ffn_down_exps.*.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search +blk.*.ffn_down_shexp.weight rtn codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search + +# The shared blocks declare their gains and router correction as f32 planes (A_log and dt_bias +# ship f32 in the checkpoint), so they keep the f32 form the plugin reads. +blk.*.attn_norm.weight cast dtype=f32 +blk.*.attn_q_a_norm.weight cast dtype=f32 +blk.*.attn_kv_a_norm.weight cast dtype=f32 +blk.*.ffn_norm.weight cast dtype=f32 +blk.*.ssm_norm.weight cast dtype=f32 +blk.*.ssm_a cast dtype=f32 +blk.*.ssm_dt_bias cast dtype=f32 +blk.*.glm_router.weight cast dtype=f32 +blk.*.glm_router.correction cast dtype=f32 +output_norm.weight cast dtype=f32 diff --git a/data/recipes/museglimmer-30b-bf16.recipe b/data/recipes/museglimmer-30b-bf16.recipe new file mode 100644 index 00000000..3eb6fc21 --- /dev/null +++ b/data/recipes/museglimmer-30b-bf16.recipe @@ -0,0 +1,10 @@ +# museglimmer-30b-bf16.recipe -- Meta Muse Glimmer 30B (text + images + video) at bf16. +# Every weight stays as the release holds it: the trunk's linears are bf16 GEMMs served by the +# museglimmer plugin, the tower and its projector keep the checkpoint's bf16, and the vision +# position table is resampled at run time (grid_embed_pad), so nothing is recomputed here. +# +# rad-convert --recipe data/recipes/museglimmer-30b-bf16.recipe \ +# -o muse-glimmer-30b-bf16.rad +# +# The lm_head is declared at whatever the container holds; a block-fp8 recipe aimed at it selects +# the fp8 logits kernel without a second plugin. diff --git a/data/recipes/museglimmer-30b-iq8r.recipe b/data/recipes/museglimmer-30b-iq8r.recipe new file mode 100644 index 00000000..34744075 --- /dev/null +++ b/data/recipes/museglimmer-30b-iq8r.recipe @@ -0,0 +1,35 @@ +# museglimmer-30b-iq8r.recipe -- Meta Muse Glimmer 30B from the bf16 release with an IQ8R trunk and +# an int8 head, served by arch/museglimmer_ct. +# +# rad-convert --recipe data/recipes/museglimmer-30b-iq8r.recipe \ +# --set quantization_config.quant_method=compressed-tensors -o muse-glimmer-30b-iq8r.rad +# +# The --set selects the plugin registered at ("museglimmer", "compressed-tensors"), which reads the +# trunk's form from layer 0's q projection; no other descriptor key is read. +# +# - IQ8R: every trunk linear (attention q, gate, k, v and output; the feed-forward's gate/up and +# down) as int8 codes in -127..127 with one u8 scale per (row, 256 of K) under one bf16 scale a +# row, each 128 of K rotated by the unnormalised Hadamard before rounding and the 1/128 kept in +# the row scale (`transform=fwht128`). Round to nearest with a scale search; no calibration +# data is read. The plugin serves them at gemm_nt_q i8a8h against int8 activations under the +# same rotation, written by the two pre-norms (q, gate, k, v and gate/up), the gated product +# (down) and the out projection's own quantiser (o). An IQ8R container is IQ8R in all seven. +# The rules are the ones the other IQ8R recipes give their trunks (arch/qwen35_w8a8, +# arch/llama_dense_fp8, arch/flint). +# - The lm_head as int8 unrotated with a bf16 scale per (row, 128) (logits_gemm_i8), which the +# DFlash drafter, when the container carries one, reads as its head too. +# - The norms, the embedding, the vision tower and its adapter match no rule and stay bf16, and +# so do a merged drafter's own matrices (`dspark.*`; the trunk patterns do not reach them). +# +# About 30.8 GiB by the tensor shapes: 23.5 GiB of IQ8R trunk, 1.3 GiB of int8 head, 2.5 GiB of +# bf16 embedding, 3.4 GiB of bf16 vision tower. + +blk.*.attn_q.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.attn_gate.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.attn_k.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.attn_v.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.attn_output.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.ffn_gate_up.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search +blk.*.ffn_down.weight rtn codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128 clamp=sym rule=search + +output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search diff --git a/data/recipes/museglimmer-30b-w4a8.recipe b/data/recipes/museglimmer-30b-w4a8.recipe new file mode 100644 index 00000000..3aa259c5 --- /dev/null +++ b/data/recipes/museglimmer-30b-w4a8.recipe @@ -0,0 +1,22 @@ +# museglimmer-30b-w4a8.recipe -- Meta Muse Glimmer 30B from the bf16 release: an int4 trunk on +# the same grid gemma4's CT-INT4 release uses (i4 codes, an f16 scale per 128 columns, least +# squares scale search), with attention value and the feed-forward's down projection at int8 +# where int4 costs more than it saves. About 15.7 GiB: 10.2 GiB of int4 trunk, 90 MiB of int8 +# value projections, 5.4 GiB of bf16 embedding and head (the head is where int4 hurts most on a +# 202k vocabulary; keep it until a measured reason says otherwise). +# +# rad-convert --recipe data/recipes/museglimmer-30b-w4a8.recipe \ +# --set quantization_config.quant_method=compressed-tensors -o muse-glimmer-30b-w4a8.rad +# +# The --set selects the plugin registered at ("museglimmer", "compressed-tensors"), which serves +# both this encoding and plain bf16. Norms, the embedding and the lm_head match no rule and stay +# bf16. A linear may be held at int8 on the same grid (gemm_nt_q w8a8): +# blk.*.attn_output.weight rtn codes=i8 group=128 scale=f16 rule=search + +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=i8 group=128 scale=f16 rule=search +blk.*.attn_gate.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.attn_output.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.ffn_gate_up.weight rtn codes=i4 group=128 scale=f16 rule=search +blk.*.ffn_down.weight rtn codes=i4 group=128 scale=f16 rule=search diff --git a/docs/ARCHITECTURES.md b/docs/ARCHITECTURES.md index 53385e48..65dec245 100644 --- a/docs/ARCHITECTURES.md +++ b/docs/ARCHITECTURES.md @@ -14,6 +14,7 @@ plugin claims. | `arch/hyv3_bf16` | `hyv3` | *(empty)* | Tencent Hy-Memory-30B-A3B BF16 safetensors; BF16, W4 or W8A8 weights by recipe; TP1/2, BF16 KV | | `arch/hyv3_fp8` | `hyv3` | `fp8` | Tencent Hy-Memory-30B-A3B-FP8's descriptor: the same graph, one dense layer then sigmoid-routed MoE; its per-tensor E4M3 linears are a form this build does not serve; TP1/2, bf16 or int8 KV | | `arch/hyv3_gguf` | `hyv3` | `gguf_ftype_15` | llama.cpp Hy-Memory Q4_K_M GGUF, dequantized and recipe-converted to native Radiance weights; TP1/2 | +| `arch/flint` | `flint` | *(empty)* | Recursive Flint (39.8B-A2.5B): 2 dense layers then 47 sigmoid-routed MoE layers (256 experts top-6, ungated 1024-wide shared expert), GQA 32/4 at head_dim 128 with QK RMSNorm, a learned per-head sink on every layer, RoPE on the 35 sliding layers (window 513) and NoPE on the 14 full layers; two KV groups (full and window), TP1/2 (expert parallel); BF16 or int8 KV. Weights by recipe: an IQ8R trunk with rotated int8 experts (`data/recipes/flint-iq8r.recipe`), or u4 attention, int4 experts and plain int8 dense/shared/head (`data/recipes/flint-bf16-q4.recipe`); `docs/FLINT.md` | | `arch/qwen35_w8a8` | `qwen35` | `w8a8_fwht128` | `qwen35_fp8` with an int8 trunk: i8 weights with a bf16 scale per 128 of K, rotated by a 128-wide Hadamard, against int8 activations under the same rotation: IQ8R and IQR-V4 (`data/recipes/q38-27b-iq8r.recipe`, `q38-27b-iq4r-s-v4.recipe`) | | `arch/qwen35moe_fp8` | `qwen35moe` | `fp8_e4m3` | `qwen35_fp8` with the feed-forward routed | | `arch/qwen35moe_w8a8` | `qwen35moe` | `w8a8_fwht128` | `qwen35moe_fp8` with `qwen35_w8a8`'s int8 trunk and rotated int8 experts, the routed arm reading the trunk's own int8 codes (`data/recipes/q36-35b-a3b-iq8r.recipe`) | @@ -21,7 +22,12 @@ plugin claims. | `arch/clef_fp8` | `clef` | `fp8_e4m3` | the same over `qwen35_fp8`'s trunk | | `arch/qwen4exp_fp8` | `qwen4exp` | *(empty)* | Qwen4-Exp (Qwen3.8-Flash-Next), a bf16 checkpoint quantised at convert (`data/recipes/qwen4exp-w4nl64-i8-hc8m.recipe`) or an AutoRound int4 release (`qwen4exp-autoround-i8-hc8m.recipe`) | | `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 experts at top-8 under sigmoid routing, attention and dense layers as the container stores them; its MTP layer is a serial drafter. Pictures through its vision tower (`arch/common/rad_block_glm_vision.h`); bf16 KV | -| `arch/bailing_hybrid` | `bailinghybrid` | *(empty)* | Ling-3.0-flash and its fine-tunes (Ling-3.0-flash-Sante) from the bf16 checkpoint: 35 KDA and 7 dense latent-attention (MLA) layers with a rotary part and a head-wise gate, 512 experts at top-8 under group-limited sigmoid routing with an ungated shared expert, the routed experts as the recipe stores them (`data/recipes/ling3-w4a8-rtn.recipe`); its MTP layer is a serial drafter; bf16 KV | +| `arch/bailing_hybrid` | `bailinghybrid` | *(empty)* | Ling-3.0-flash and its fine-tunes (Ling-3.0-flash-Sante) from the bf16 checkpoint: 35 KDA and 7 dense latent-attention (MLA) layers with a rotary part and a head-wise gate, 512 experts at top-8 under group-limited sigmoid routing with an ungated shared expert, the routed experts as the recipe stores them (`data/recipes/ling3-w4a8-rtn.recipe`); its MTP layer is a serial drafter; Ling-3.0-tiny from its bf16 checkpoint with an IQ8R trunk and rotated int8 experts (`data/recipes/ling-3.0-tiny-iq8r.recipe`, TP1/2; flash's clamped SwiGLU layers have no int8 form); bf16 KV | +| `arch/bailing_hybrid_gguf` | `bailinghybrid` | `gguf_ftype_25` | Ling-3.0-tiny (24 layers, MLA every fourth with a 256-wide query LoRA, 128 experts of 512 at top-8) as the IQ4_NL GGUF release, its experts re-quantised by `data/recipes/ling-3.0-tiny-iq4.recipe`; no MTP; bf16 KV | +| `arch/bailing_hybrid_gguf_q80` | `bailinghybrid` | `gguf_ftype_7` | the same tiny family, Q8_0 GGUF release, served whole | +| `arch/bailing_hybrid_gguf_q4km` | `bailinghybrid` | `gguf_ftype_15` | the same tiny family, Q4_K_M GGUF release, served whole | +| `arch/bailing_hybrid_gguf_q5km` | `bailinghybrid` | `gguf_ftype_17` | the same tiny family, Q5_K_M GGUF release, served whole | +| `arch/bailing_hybrid_gguf_q6k` | `bailinghybrid` | `gguf_ftype_18` | the same tiny family, Q6_K GGUF release, served whole | | `arch/nemotronh` | `nemotronh` | *(empty)* | Nemotron-3.5-Bolt-74B-A9B (`nemotron_h_omni` around `nemotron_h_puzzle`), its language model from the bf16 checkpoint: 40 Mamba-2, 40 latent-MoE and 8 NoPE attention blocks in the order `layers_block_type` gives, 240 to 496 ungated relu^2 experts a layer in a 1024-wide latent with a relu^2 shared expert; linears and experts as the recipe stores them; pictures and video through its C-RADIO tower (`arch/nemotronh/radio.h`); bf16 KV | | `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16 or IQ8R, one rank | | `arch/spark25_bf16` | `spark25` | *(empty)* | Spark X2.6, bf16 checkpoint, mixed sliding/full attention, TP1 or TP with exact collectives ([geometry](#spark25-spark-x26)). Optional DSpark drafter when the container already holds `draft.*` tensors, TP1 only. | @@ -1031,10 +1037,12 @@ the four depths above. --- -# `bailing_hybrid`: Ling-3.0-flash +# `bailing_hybrid`: Ling-3.0-flash and Ling-3.0-tiny -`arch/bailing_hybrid` serves Ling-3.0-flash (`model_type: bailing_hybrid`, BailingMoeV3ForCausalLM) -and its fine-tunes from the bf16 checkpoint. The reference is vLLM's `bailing_moe_v3.py` and +`arch/bailing_hybrid` serves Ling-3.0-flash and Ling-3.0-tiny (`model_type: bailing_hybrid`, +BailingMoeV3ForCausalLM) and their fine-tunes from the bf16 checkpoint, tiny additionally as its +GGUF releases through thin-include wrappers (`arch/bailing_hybrid_gguf` and kin). The reference is +vLLM's `bailing_moe_v3.py` and SGLang's; the HF `modeling_bailing_moe_v3.py` agrees except for the SwiGLU clamp (below). The plugin reuses GLM-5.3's KDA core (`KdaState`), sigmoid router (`GlmRouter`, with groups) and draft head (`GlmMtp`), and `MoeFP8`; its KDA and MLA blocks are in the plugin file. @@ -1059,6 +1067,34 @@ feed-forward: layers 0-1 dense SwiGLU 2 x 6144; layers 2-41 MoE routed experts at 4 in layers 35-41, the shared one at 5 (34-39) and 7 (40-41) MTP: checkpoint layer 42 -- enorm, hnorm, eh_proj 5120 -> 2560, one MLA layer with the full MoE, final_layernorm; the trunk's embedding and lm_head + +tiny: 24 layers, hidden 1536, rope_theta 6e6, groups of four -- MLA at 3, 7, ..., 23; 16 heads + of 128 through the whole model + the MLA takes its query through a LoRA: q_a 1536 -> 256, RMS-normed, then q_b 256 -> + 16 x (128 + 64), whose rows serve the two parts; kv_a 1536 -> 512 + 64, kv_b 512 -> + 16 x (128 + 128); the gate 1536 -> 16; o 2048 -> 1536 (`dense`) + KDA, 16 heads of 128: q, k, v 1536 -> 3 x 2048, convs, forget and output gates as flash + feed-forward: layer 0 dense SwiGLU 2 x 4608; layers 1-23 MoE, 128 routed experts of 512 at + top-8, 8 groups of 16 ranked the same way, 4 kept; one shared expert of 512; no clamp lists + no MTP layer (`num_nextn_predict_layers: 0`) + +IQ8R (tiny, `data/recipes/ling-3.0-tiny-iq8r.recipe`): the KDA q|k|v, forget, gate and out, the + MLA out, the dense pair and the shared gate/up as IQ8R (`gemm_nt_q` at `i8a8h`, group 256); the + routed experts and the shared down rotated int8 at a bf16 scale a (row, 128) (`moe_gemm_q` and + `gemm_nt_q` at `i8a8h`, group 128). The block norms write `rmsnorm_had_quant_i8g`'s codes (256), + read by every KDA projection, the shared gate/up and the routed gate/up; `had_quant_act_i8g` + (256) quantises the KDA core's gated norm and the MLA's values for their out projections; + `gated_had_quant_i8g` writes the dense product's codes at 256, the shared and routed products' + at 128. The KDA beta, the MLA's q_a, q_b parts, kv_a, kv_b and head gate, the taps, the router, + the embedding and the head stay bf16. TP1 and TP2 (at TP4 the dense 1152-column slice cuts a + 256-column group and is refused). + +GGUF releases (tiny): IQ4_NL, Q8_0, Q4_K_M, Q5_K_M, Q6_K -- the file's `general.file_type` is + the claim (`gguf_ftype_25`, `_7`, `_15`, `_17`, `_18`); the release files carry their + producer's renumbered ftable (IQ4_NL 25, Q4_K_M 15, Q5_K_M 17, Q6_K 18, Q8_0 7), not the + pinned ggml enum. Q8_0, Q4_K and Q6_K import as planes and are served whole; Q5_K and + IQ4_NL decode in checkpoint.cpp, the IQ4_NL experts re-quantise to the engine's i4 planes + through `data/recipes/ling-3.0-tiny-iq4.recipe`. ``` Traps: @@ -1077,6 +1113,10 @@ Traps: for `rope` and `[T, 32 * 128]` for the absorption. A single `[T, 32, 192]` plane with column views turns the wrong rows on libavx, whose `rope` reads a rank-3 operand's head stride as its row stride. +- **tiny's query runs a LoRA first.** q_a 1536 -> 256 and its norm precede q_b; the same two-plane + row maps run over `q_b_proj` against the normed latent, so the parts' GEMMs take K = 256 and read + the LoRA's ActFP8 wire (the producer quantises it when the container stores fp8). The `need[]` + gate admits `q_lora_rank` 256 and nothing else. - **The cache row is [latent | rotary key].** One KV head of 288, the row's first half in the K slot and the second in the V slot, so `kv_store` writes the 576-wide row contiguously and `mla_attn_paged` reads it as `[pages, 1, block, 576]`. Scores are taken in the latent; the head @@ -1103,7 +1143,16 @@ and the latent are replicated. The dense feed-forward splits its 6144 columns. A 768 columns are six 128-column blocks: halves at two ranks, and at four 2, 2, 1, 1 blocks rotated by the expert's number mod 4 (`moe_gemm_q_mod4`), so every rank carries six blocks per four experts. The shared expert splits the same way, unrotated. A calibration run -(`RADIANCE_CALIB_DIR`) and bf16 experts give every rank whole experts instead. +(`RADIANCE_CALIB_DIR`) and bf16 experts give every rank whole experts instead. The IQ8R trunk +shards the same way; its norms take no collective (each block's all-reduce stays a standalone +`all_reduce` before the residual add), so no `ar_` norm is declared at two ranks. + +**The trunk's form** is read from layer 0's fused q|k|v. A rotated int8 trunk needs rotated +experts (int8 or a rotated four-bit form) and no SwiGLU clamp: the int8 gated products have no +clamped form, so flash's clamped layers (routed 35-41, shared 34-41) are refused on it by name. +Rotated int8 experts under an unrotated trunk are refused too. Where no loaded library serves +`rmsnorm_had_quant_i8g` (a CPU-only engine), each int8 linear quantises the norm's bf16 output +itself and the routed experts read a rotated int8 copy written once a layer. --- @@ -1812,6 +1861,198 @@ is one 800-token translation run four times). --- +# `museglimmer`: Meta Muse Glimmer 30B + +`arch/museglimmer` serves the text trunk and the vision tower of a +`MuseGlimmerForConditionalGeneration` checkpoint (`model_type: muse_glimmer`, HF +`meta-models/Muse-Glimmer-30B`), `arch/museglimmer_ct` the same container converted to an int4 +or IQ8R trunk (`--set quantization_config.quant_method=compressed-tensors`). The trunk block lives +in the plugin, the tower in `arch/common/rad_block_museglimmer_vision.h`; the reference is +transformers' `modeling_muse_glimmer`. + +``` +Muse Glimmer 30B + 52 layers, hidden 6656, ff 19968, vocab 202048 (head not tied), rms_norm_eps 1e-5 + layer_types: sliding_attention except every 4th layer full (3, 7, ..., 51) + sliding 32 heads / 2 kv x 128, rope theta 500000 over all 128 dims, window 2048 + full NoPE: no rotary at all (the config's layer_rope_theta is 0 there) + q_proj and gate_proj are separate tensors, each [4096, 6656]: two GEMMs, not a fused q|gate + q and k are RMS-normed per head with NO gain (MuseGlimmerRMSNorm with_scale=False); the query + is then multiplied by qk_scale_factor 3.87, the key is not; scores scaled 1/sqrt(128) + every layer norm is centered, x_hat * (1 + w): the attention's and feed-forward's inputs at + rms_norm_eps 1e-5, their OUTPUTS at post_norm_eps 1e-8, and the residual adds the normed + branch (Gemma-2 sandwich); the final norm is a plain gain, wadd 0 + the embedding is RMS-normed after the lookup (weightless, 1e-5); not folded into the table, + because a drafter embeds without it + logits are pre-scaled by output_multiplier 1/sqrt(26) (carried on the final norm's mult) and + soft-capped: 20 * tanh(logits * mult / 20) +``` + +Traps: + +- **The q/k norm is weightless and the query alone carries qk_scale_factor.** Serving it as a + plain 1/sqrt(head_dim) with no norm, or scaling both q and k, is a different model. +- **The full-attention layers have no rotary.** A theta of 500000 there (the family default + rope_parameters value) is wrong; the per-layer `layer_rope_theta` array is the authority, and + where a container omits it the plugin derives it: theta on the sliding layers, 0 on the full + ones. +- **The output branch is normed, not the raw projection**: `x += post_norm(y)` at both junctions, + the post norm at 1e-8. +- **The head sees scaled inputs.** The final norm's `mult` carries output_multiplier, so logits + are already pre-scaled when `logit_softcap` applies cap * tanh(x / cap). Scaling the head's + weights instead would break a bf16 head against a quantised one under the same container. + +**KV groups.** `kv_sliding` (`RAD_KV_WINDOW`, 2048) bound to the sliding layers, `kv_full` +(`RAD_KV_FULL`) to the full ones, 2 heads of 128. The window group holds 2048 tokens a sequence +per sliding layer, so long contexts cost a fraction of what a full pool would. + +**Vision.** A 50-block windowed ViT (hidden 1536, 16 heads x 96, ff 8960, patch 14, temporal 2, +merge 2) declared only when the deployment asked for media (`--mm-max-patches`). The preprocessor +resizes to a multiple of 28 px under a 4096-token budget (closest aspect, no minimum size), emits +patch rows as (temporal, channel, y, x) in the reference's raster order, and expands +`<|image_start|> 200080`, `(grid/4) x <|patch|> 200092`, `<|image_end|> 200081`; video is +`<|vid_start|>`, then per frame group `Time: {t:.1f}s` (tokenised text), the group's `<|video|> +200091` tokens and a `<|vid_frame_separator|> 200087`, and `<|vid_end|> 200083` last, fps 2.0 at +96 frames with a 144-token per-group budget. + +The tower differs from Qwen-VL's (`rad_block_vit.h`) in five ways, each visible in +`rad_block_museglimmer_vision.h`: + +- **Window attention is a permutation, not a banded mask.** `window_order` computes the + InternVL-style reorder (windows of `pos_emb_height` = 32 patches a side, partitioned per frame, + ragged edges kept as smaller windows) from the coordinate planes, plus its inverse, the rope + positions and the per-window cu. Full-attention layers pass the frame `cu` unchanged: the + permutation moves rows within a frame, so frame boundaries survive it. Blocks run in window + order; the inverse gather restores it before `ln_post`. +- **The rope positions are (col + 1, row + 1)**, not (row, col): the reference flips the two + components and offsets by one (`position_ids.flip(-1) + 1`). `window_order` emits them ready. +- **The position table is resampled with zero-padding bilinear** (`grid_embed_pad`): at + half-pixel centres, align_corners=False, taps beyond the 32x32 table weighted zero. `grid_embed` + (Qwen-VL's) clamps to the border instead; they agree only at grids at or below the table. +- **The merge is the reference's `pixel_shuffle`.** `pixtral_merge` folds each 2x2 block's four + patch rows into one row of 4 x width with the channels interleaved + (`[block, 4, width].permute(0, 2, 1)`); four consecutive rows concatenated instead would be a + different tensor, and the adapter's first linear (whose weights are trained on the interleaved + form) would read a permuted image. +- **The DFlash drafter is declared from the same container** (`rad_block_muse_dflash.h`), when the + conversion merged `meta-models/Muse-Glimmer-30B-assistant` under `draft.` (`rad-convert + --draft-model`). Five plain layers over the residuals of trunk layers 1/13/25/37/49, SwiGLU, + per-head q/k gains, no attention gate, no Markov head and no candidate selector: the head is the + trunk's own `output.weight` and the proposal is its plain argmax over the last `block_size - 1` + rows (the anchor row predicts nothing, so `steps()` is 15 of a 16-row block). It shards with the + trunk at tp (q/k/v/gate_up by rows, o/down by columns, an all_reduce after each; the block's rows + embed from the trunk's vocab-sharded table, so the partial lookup gets an exact all_reduce of its + own, like the trunk's embedding) and its argmax + is distributed over the vocab-sharded head (`row_topk` with `vocab_off` → `all_gather` → + `pair_argmax`); buffers are sized by `max_seqs * steps` and the head reads the predicting rows + through `out_ids`, so batches draft side by side. + Its seven matrices are block fp8 / MXFP4 like the trunk's (the recipe's `dspark.*` rules; + `DenseFP8`, an E4M3 activation per row and 128 of K), which is what the 53-tensor assistant + release is not: converted without them it stayed bf16 and 4.76 GiB of the 26.5 GiB container, + read in full every draft step. It also declares a **short block** of 4 rows / 3 drafts + (`rad_drafter_short_block`; `--draft-short-from 2`), since the same graph is ranged by rows. + Measured on one 30B trunk card (`museglimmer-30b-nvfp4.rad` and the drafter container, 300-token + prompts, spec against the trunk's own no-speculation numbers): + + | | tp 1 b1 | tp 1 b4 (aggregate) | tp 2 b1 | tp 2 b2 | tp 2 b4 | + |---|---|---|---|---|---| + | no drafter | 51.7 | 51.5 (206) | 52.1 | 51.4 (103) | 51.4 (206) | + | bf16 drafter | 57.2 | 51.5 (202) | 57.2 | 32.7 (130) | 32.7 (130) | + | block fp8 / MXFP4 drafter | **89.9** | **57.0 (228)** | **65.5** | **55.0 (110)** | 41.7 (167) | + + The tp 2 b2/b4 rows of the quantised drafter measured the batched drafts while they were broken + (the shifted read below scored each sequence's neighbour's anchor as its first draft, so batched + acceptance sat near single digits and the drafter paid pure overhead). With the head reading + `out_ids`, batched acceptance returns to single-stream levels: measured on the NVFP4 + + quantised-drafter container at tp 2, 500-token answers, four streams, **18.0-19.9%** acceptance + and **196-208 tok/s wall** against **52.3 tok/s a stream** on the drafter-less container; single + stream runs **121-205 tok/s, 2.3-3.9x** the drafter-less container's 52.3. + + The bf16 drafter paid 4.76 GiB of read a draft step, which dominated the step and is why tp 2's + batches lost; quantising it takes that to 1.42 GiB and the container from 26.51 to 23.17 GiB. + The two remaining losses at tp 2/b4 (~38 ms a speculative step against 19.8 ms plain, with the + short block at either 4 or 2 rows) are the drafter's per-step work, not its read. + **The workload sets the win.** Fresh prose is the drafter's floor and a rewrite/transcription task + its ceiling: tp 2, one stream, per stream 52.1 -> 60.7 tok/s on prose, 52.1 -> 76.3 on a Python + script written from scratch, 51.9 -> 86.4 on a script reproduced and re-documented, with the + draft-acceptance metric reading 3.7% / ~6% / 8.5% on those three. At two sequences the same + order holds (+8% / +1% / +36%), and at four the drafter loses in all three (~40-42 against + ~49-50), which is the step's fixed cost, not the text. + **The head reads the scheduler's `out_ids`**, gathered out of the staged block (`w.hg`): one + query-pass entry per drafting sequence, `block` rows, and `out_ids` its last `depth` rows (the + scheduler's block_query fills them from each entry's own `hidden_row`). "The last `depth` rows + of the staged block" -- an earlier read, kept when a chunked prefill handed `out_ids` that were + not block-local -- coincides with `out_ids` only while every staged sequence drafts; at two or + more it drops each sequence's first mask row and scores its neighbour's anchor row, whose + logits pose as that sequence's first draft. Measured, one card on the rewrite task single + stream: **108.5 tok/s** (2.09x the 51.9 the same prompt gets with no drafter), position-0 + acceptance 79.8%; at four streams the shifted read's acceptance collapses to a few percent + while the text stays clean, because every rejected draft changes no token. + **Fusions.** `gate_up|silu|quantise` is one launch (`gemm_nt_q_gated_mx` over the MXFP4 weight, + `gemm_nt_q_gated` over block fp8), verified and measured: tp 2 b1/b2/b4 64.9/55.6/42.5 tok/s + against 65.5/55.0/41.7 unfused -- equal within noise, so ten fewer launches a step is not what + the speculative step spends its ~38 ms on. `rmsnorm_quant_fp8` (norm + quantise in one launch) + is *not* usable here: declaring it makes the engine lay the drafter's fp8 attention weights out + in `r4d.fp8.w.frag64`, and a weight in that form cannot be read where it lies, so a weight the + planner puts on the mapped tier refuses to start ('...was placed on the mapped tier ... its + stored form is not the container's'). Reproduced with and without the `rad_op_declared` probe, + with the gated fold on and off; not with it undeclared. +- **The adapter activates twice**: `gelu(fc2(gelu(fc1(x))))`, then a bias-less projection to the + text width, then a weightless RMS norm (`perception_emb_norm`, the text model's eps) before the + rows scatter into the embedding. +- **The vision layer rule counts from the first block and always makes the last full** (the + reference config's derivation); the shipped array is checked against that rule and a + disagreement is refused. + +**Linears.** Each trunk weight is served as its encoding stores it: + +| recipe rule | served | activation | +|---|---|---| +| none (bf16) | `gemm_nt` | bf16 | +| `codes=u4\\|u5 zero=u8 group=128 scale=f16` (CT-INT4) | `gemm_nt_q` w4a8i8_asym, decode band at w4a16_asym | int8, a scale per (row, 128) (`quant_act_i8g`) | +| `codes=i8 group=128 scale=bf16` | `gemm_nt_q` i8a8 | int8, an f32 scale per (row, 128) (`quant_act_i8g`) | +| `codes=i4\\|i8 group=128 scale=f16` (`museglimmer-30b-w4a8.recipe`) | `gemm_nt_q` w4a8 / w8a8 | int8, one scale a row (`quant_act_i8`; the grouped producer paired with these GEMMs makes NaN logits, as in gemma4_bf16) | +| `codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* transform=fwht128` (IQ8R, `museglimmer-30b-iq8r.recipe`) | `gemm_nt_q` i8a8h, group 256 | int8 rotated 128 wide, an f32 scale per (row, 256): written by the pre-norms (`rmsnorm_had_quant_i8g`) for q, gate, k, v and gate/up, by the gated product (`gated_had_quant_i8g`) for down, by o_proj's own `had_quant_act_i8g` for o | + +IQ8R is a whole-trunk form: layer 0's q projection decides it before any activation is declared, +and every trunk linear of such a container must be IQ8R (one that is not, or an IQ8R linear in a +trunk whose layer 0 q is not, is refused by name). A layer quantises four times, once per +distinct linear input: the centered pre-norms write the pair q, gate, k and v share and the one +gate/up reads; the gated product writes down's and not its bf16 plane (written only when +`--calib-dir` records the layer). The gated attention output keeps `sigmoid` + `mul` and o_proj +quantises the product itself, since the fused gate quantiser runs per head and a head (128) is +narrower than the 256-column scale group. No norm absorbs a collective at tp 2 (the all-reduce +sits before the post norm), so the all-reduce form of the rotating norm is not declared; the +linears shard as the other forms do (q, gate, k, v, gate/up by rows, o and down by columns, whole +256-column groups a rank). Where no loaded library declares a rotating producer (the CPU +kernels), its plain op runs instead (`rmsnorm`, `silu_mul`) and the first linear reading that input +quantises it with `had_quant_act_i8g`: q for the four, gate/up, down. The head is plain int8 +(`codes=i8 group=128 scale=bf16`, `logits_gemm_i8`), which the drafter reads as its own head. + +The tower's weights are never quantised: a container that quantises them is refused by name. + +**Context extension.** The architecture takes it by mechanical means, and takes it well: 13 of +the 52 layers are full-attention **NoPE** (`layer_rope_theta` 0 -- no positions at all) and the 39 +sliding layers carry rotary over a 2048-wide window, so the rotary is only ever read as in-window +relative offsets. Serving past the trained 131072 positions is `--max-model-len` alone; the +engine's warning that nothing scales the rotary is expected and harmless here. Measured at tp 2 +(NVFP4 trunk, quantised drafter, fp8 KV): a **495,145-token** prompt -- three administration +needles at 20/50/80% of a repetitive hay -- prefills in 272 s (1822 tok/s; the tail chunks slow +quadratically) and retrieves **all three codes in order**; decode at that depth runs 16 tok/s +(62 ms/token: attention over 495K keys, the drafter, prompt lookup), and draft acceptance is +*higher* than at short context (31.8-37.8% -- the repetitive hay suits the drafter and prompt +lookup alike). For a stronger stretch, `--rope-scaling yarn:FACTOR[:ORIG]` writes YaRN into the +container's rotary keys at load (llama.cpp's 1M recipe is factor 8 over 131072); the blend lands +on the sliding layers' rope ops only (`yarn_from` reads the keys into the rope Geom -- the NoPE +layers have nothing to scale) and the drafter reads its own `draft.rope_parameters` +(`drafter_geom` already calls `yarn_from` for it). Measured under `yarn:8` at tp 2: a +**913,130-token** prompt -- the same three needles at 20/50/80% -- prefills in 717 s (1273 tok/s) +and retrieves **all three codes in order**; decode runs 6.6 tok/s (151 ms/token) with 21.6% +acceptance. The windows fit the two 32 GB cards beside the weights with fp8 KV: the full pool is +~1.6 GiB a rank at 495K and ~3.3 at 1M. + +--- + # `qwenimage21`: Qwen-Image 2.1 and 2.1-Turbo, an image generator `arch/qwenimage21` declares a generator (`rad_declare_generator`), which makes the program a @@ -2316,6 +2557,65 @@ plays a lane's newest frames, four at most, as soon as they are made. It is serv `/v1/audio/speech` and `/v1/audio/speech/stream` ([GUIDE §5.15](GUIDE.md)), bf16 on one card. The checkpoint is the release directory; its codec, in `audio_tokenizer/`, is read with it. +Voice cloning uses the same `/v1/audio/speech` `references` array as drama-3, limited to one +recording of at most ten seconds, with its exact transcript. Plain cloning uses guidance 1; +reference-plus-direction also supplies `instructions` (start with guidance 4). +`arch/breeze/reference.h` declares the tokenizer's encoder in f32: SEANet's causal convolutions +(ELU, residual bottlenecks, strides 4/5/6/8), eight Mimi transformer layers at 25 Hz (LayerNorm, +8 heads of 64, causal window 250, GELU feed-forward, learned residual scales), a replicate-padded +stride-2 convolution, then independent semantic/acoustic input projections and 1+15 Euclidean +residual quantisation steps. Centroids are EMA sums divided by usage; ties choose the lower code. +These are the encoder's codebooks, not the decoder's dequantisation tables, and not drama-3's +cosine quantiser. The encoder weights are included by the updated conversion recipe. +Its f32 GEMM, LayerNorm, GELU, causal attention and full-head 64-dimensional NeoX rotary have +device paths too; reference encoding does not depend on host-reference fallbacks. The f32 causal +strided convolution uses the same FMA tile as the vocoder's f32 convolution. + +The clone prompt is `[S0]transcript`, the reference frames, an audio EOS frame (sixteen +codebook EOS indices, all zero), then `[S0]input`. Each text segment is independently encoded +bidirectionally at position zero. Audio rows are the f32 sum of sixteen backbone codebook +embeddings rounded once to bf16; they never pass through the text encoder. The backbone attends +causally over the assembled prompt. At guidance 1 both branches repeat the conditional prompt, +including its reference-frame map; no reference context is carried into another request. +Reference direction uses `ref_edit_tata`: the final text segment is +`[S0]instructionsinput`; its negative branch is the plain clone prompt +with the same reference. ABI 38 appends opt-in conditional/negative direction templates to +`RadAudioGenDecl` and host prompt boundaries to `RadAudioGenBatch`. The driver stages each +branch's own frame map and the architecture splits text segments at the actual branch boundary, +not half the pass length. The reference encoder still runs once. This is two-branch CFG, not +the upstream three-branch dual-guidance scheme. Engine and plugins must be rebuilt together; +the already-updated cloning weights do not need another conversion for direction. +`rvq_embed` reads codebook zero from its first table and codebooks 1..15 from its second: +the latter is a view starting at row 2051 of the shared table, just as for generated-frame +feedback. This applies to both reference frames and their audio EOS; passing the full table +twice shifts fifteen codebooks and corrupts the conditioning even when encoder codes are right. + +Native cloning verification (2026-11-10, one R9700): all 688 codec indices of a synthetic +3.44-second reference agreed with the upstream Mimi encoder. With an eight-second recording, +the assembled reference-audio and EOS embeddings matched an independent PyTorch calculation +exactly after correcting the residual-table view. Independently encoded text segments differed +by about 1.1% relative L2 (cosine >0.9999); both prompt branches were byte-identical. The +architecture recording test checks the table view for both reference frames and EOS. +Fourteen device checks cover the encoder primitives, including Euclidean/tie behaviour, +pitched guards, f32 causal strided convolutions and attention against a double softmax oracle. +These checks do not constitute a speaker-similarity benchmark; listening evaluation is separate. +The corrected eight-second-reference clone was subsequently approved by the local listener as +matching the supplied voice. This is one subjective evaluation, not broad speaker/language +coverage. Through the local manager on a warm R9700, 2.80 seconds of cloned speech completed in +1.85 seconds (1.80 seconds on repeat), about 1.5 times real-time playback speed. Live PCM and +SSE completed in 1.80 seconds each. These are whole-response times, including reference encoding +and transfer, not measurements of time to first audio. The same seed reproduced the WAV bytes. +Reference direction was also verified locally with the same eight-second reference and text: +plain cloning made 9.92 seconds of speech in 6.15 seconds (RTF 0.620); soft/slow direction made +11.44 seconds in 7.01 seconds (0.612); bright/energetic made 8.40 seconds in 5.19 seconds (0.618). +First PCM/SSE audio arrived in about 0.27 seconds through the manager. A subsequent angry +direction made 9.76 seconds in 6.03 seconds (0.618). The local listener approved soft, bright +and angry delivery with the cloned voice. These are single-reference subjective checks, not +general speaker/language validation. Plain cloning remained byte-identical to its previously +approved native sample, and fixed-seed directed WAVs reproduced byte for byte. Host ABI, +builder, speech, driver and architecture suites, fourteen reference GPU checks, live PCM/SSE, +and real browser direction/reset-to-plain-clone tests passed. Lower RTF is faster. + ``` text T5Gemma 2's text encoder in Gemma 3 1B's shape: 26 layers of 1152, 4 query heads over one KV head of 256 (q/k RMS-normed, scale 1/16), sandwich RMS norms with a (1 + w) gain, diff --git a/docs/DIAGNOSE.md b/docs/DIAGNOSE.md new file mode 100644 index 00000000..7e266b29 --- /dev/null +++ b/docs/DIAGNOSE.md @@ -0,0 +1,90 @@ +# the diagnose mode: the engine measures itself + +A model entry with `diagnose: DIR` in the YAML file (`radiance --config FILE`) starts as a serve +would — same placement, same kernels, same prefix cache — runs a fixed workload on itself instead +of listening, and writes `DIR/diagnose.json` and `DIR/diagnose.md`. The keys are in +[TOOLS.md](TOOLS.md#the-diagnose-mode); this file is what the numbers mean, what makes a run a +measurement, and what is not measured yet. + +## What the run does + +`core/engine_diagnose.cpp` is the driver; the arithmetic and the report format are +`core/diag/diagnose.{h,cpp}`, which know nothing about the engine and are tested on the host +(`tests/diagnose_test.cpp`). The driver builds requests with no client, hands them to +`Scheduler::add_all` and reads their tokens back from `server::Sink` — the same path the KL mode +takes. The four points, each run once unmeasured and then `diagnose-runs` times: + +| point | what it answers | +|---|---| +| decode by category | code, reasoning, prose, json, file_edit and summarization prompts to EOS: time per token by prompt shape, draft acceptance, tokens a step | +| concurrency sweep | 1, 2, 4, 8 streams at once (`diagnose-concurrency`): how TTFT and per-token time give way as the batch fills | +| prefill sweep | a prompt of 1k, 4k, 16k, 64k tokens (`diagnose-prefill`) then decode at that depth: prefill time, prefill tokens/s, and how deep context changes decode | +| interference | a prompt that arrives while streams are running: its TTFT, and the stall of the streams it joined | + +A point the engine cannot run — a concurrency above `max-num-seqs`, a prompt the context cannot +hold with its decode — is skipped and said so in the report. It is never reported as a zero. + +Per phase the report carries, from the scheduler's step ring and its counters: steps, step time +(median, p95, worst), prefill/decode tokens a step, decode tokens/s, draft positions drafted and +accepted, TTFT, per-token emission interval and its jitter, and each request's own tokens. Every +statistic over an empty set is `null` in the JSON and `–` in the Markdown, with the count beside it. + +## What makes a run a measurement + +| what would spoil it | what the run does | +|---|---| +| a prefix-cache hit — the second run of a point would measure lookups, not work | every prompt carries a tag unique to its run and stream, the cache is emptied before every run, and each request's `n_cached` is checked afterwards. A hit, or step records the ring overwrote before they were read, makes the verdict `NOT A MEASUREMENT`, lists the reason, and exits non-zero | +| the first time a shape runs (tape recording, code objects, pool growth) | each point runs once unmeasured first, in the same shape | +| `ignore_eos` generating past EOS, where a drafter hits differently | categories stop at the model's EOS; only the concurrency and prefill sweeps use `ignore_eos`, so every stream decodes for the whole run | +| a client-side temperature that a deployment never serves | decode runs at temperature 1 — draft acceptance is tuned on it — with the server's top_k/top_p/min_p and a fixed seed per request. Parity does not need greedy: identical logits sample identical tokens at any temperature | +| the environment | the report lists the engine's configuration knobs **by name only**, from a fixed list (`RADIANCE_HOME`, `RADIANCE_KERNELS`, `OMP_NUM_THREADS`, …) — a value may be a path or a token, and a name that is only a prefix plus a secret suffix is not on the list. The report is pasted into issues, so it carries no path either: the model is named by its architecture and quantisation, and the corpus and baseline are named as such | + +The mode warns, in the report, about the settings that make its numbers those of a different +engine: `profile-ops` (recorded passes off, barriers added), `no-prefix-cache` (no lookups or +publishing to pay for), no usable chat +template (raw text, so tokens a step and acceptance are not chat traffic's), and a busy host. + +## Reproducibility: whether the numbers repeat + +The table above makes a run a measurement. Whether its numbers repeat on the next run, or on another +day, depends on more than the workload, so every report states it in three parts and the Markdown +gathers them under **Reproducibility**. None of them changes the verdict or the exit code: each is +how the engine serves, and its fix makes it a different engine. + +| what moves the numbers | what the report carries | +|---|---| +| the runs of one point disagree | `spread_pct`, (max − min) / median, beside every summarised number. `stability` lists each headline number above **5 %** (`diag::kMaxSpreadPct`) — ms a step for every category prompt and concurrency point (not their token rate, which also moves with the text each run samples from its own seed), TTFT and prefill rate for the prefill sweep, the arriving prompt's TTFT — and its verdict is `stable`, `UNSTABLE` or `not judged` (no point with two runs). A category's own summary pools prompts that differ by design, so its stability is judged prompt by prompt (`prompts_summary`) | +| the machine | `conditions`: the build, the host settings that move a step's time (CPU governor and energy preference, kernel, device runtime, THP, IOMMU) and the serving cards (DPM ranges, power cap against its default, voltage offset, runtime PM, link), with the startup report's findings and their fix. A finding at warn level is also a warning of the run. `conditions.fingerprint` hashes all but the findings; with `diagnose-baseline`, `parity.conditions` lists every field that differs between the two reports — informational, since tokens do not depend on clocks | +| the cards' state | each run's `cards`: temperature (edge, junction, memory), power, performance level and current DPM levels before and after it, read between runs only (the SMU answers under its lock). `thermal` gives each card's range over the report and warns when runs started more than 10 °C apart (`diag::kMaxStartTempSpreadC`) or the performance level changed | +| the engine's own adaptivity | `reproducibility` notes it: dynamic placement (the heat engine moves experts as it sees routing, so a run starts with the resident set the runs before it left; `deterministic` pins it), `prefill-interleave auto` (decode-only steps sized by how long a chunk step took), a card at performance level `auto` (clocks chosen by the firmware; a fixed level such as `profile_standard` holds them, below serving clocks), and fewer than 5 runs a point | + +For an A/B comparison of two builds: the same `conditions.fingerprint`, `diagnose-runs: 5` or more, +`deterministic` for a MoE model, a fixed `prefill-interleave`, a fixed performance level on the +cards, and both reports `stable`. Then a difference larger than the points' spread is the build's. + +## Parity + +`diagnose-baseline: FILE` compares every request's tokens with an earlier `diagnose.json` of the +same workload, and fails the run on any difference. Two reports are comparable only if their +`workload.fingerprint` — corpus, tokens, runs, sweeps, context, template, sampling — is the same; +`compare_outputs` refuses rather than compare a different workload. Points only one side ran are +reported as missing, not as equal. A drop in draft acceptance that every request shares is +reported beside the token comparison, since it is not a correctness difference. + +## Sequence + +1. **Done, host-tested.** The flag, the driver, the step ring, the report with categories, the + concurrency and prefill sweeps, and interference. +1b. Placement, expert-streaming and link counters per phase; the dashboard's Diagnose tab reading + the last report. +2. An issue census: every (op, band, domain, `n`) with calls per step and operand shapes, exported + for `rad-kbench`. +3. Per-dispatch device time in the play path, joined to the op through a record-to-op table made at + recording time, evaluated like `libr4d/isa/tsum.sh` and `libr4d/isa/gaps.sh`. +4. A correctness window: repeat and oracle for chosen ops over a step window rather than the whole + process, with ops that have no `libref` line reported as NOT CHECKED. + +Steps 1b to 4 are listed under `not_measured` in every report, so a number that is absent says so +in the artifact itself and never reads as a zero. The mode is host-buildable and its arithmetic is +tested on the host; the numbers it writes on a card are the measurement, and belong with the +hardware they came from. diff --git a/docs/FLINT.md b/docs/FLINT.md new file mode 100644 index 00000000..b6788e32 --- /dev/null +++ b/docs/FLINT.md @@ -0,0 +1,186 @@ +# Flint on radiance + +Recursive Flint (39.8B total / ~2.5B active): a 49-layer decoder with 2 dense layers followed by +47 sigmoid-routed MoE layers. The architecture plugin is `arch/flint`; the containers are built +from the BF16 checkpoint with `rad-convert`. + +## Status + +- **Q4** (`flint-q4.rad`, 19.72 GiB, fits one card): u4 attention, int4 experts, plain int8 + dense/shared/head. Served on this build by the same forms as `hyv3_bf16`'s W4 and W8 recipes. +- **IQ8R** (`flint-iq8r.rad`, about 38 GiB, two cards): an IQ8R trunk and rotated int8 experts, + the forms `qwen35moe_w8a8` serves Qwen3.6-35B-A3B with. It replaces the plain int8 "Q8" + container of the 1.17-era port, whose unrotated int8 experts this build does not serve (a + container converted that way is refused by name; convert it again with the IQ8R recipe). + +The measurements below were taken on the 1.17-era build with the forms it used then (the plain +int8 Q8 container and that build's plain int8 grouped GEMM); they have not been repeated on this +build. See [Measured](#measured). + +## Geometry + +| | | +|---|---| +| layers | 49: 2 dense, 47 MoE | +| attention | 32 query / 4 KV heads, head_dim 128, QK RMSNorm per head | +| sink | learned per-head `softmax_offset` on every layer (`attn_paged_sink`) | +| position | RoPE on the 35 sliding layers; NoPE on the 14 full layers | +| window | 513 on the sliding layers | +| FFN | dense `n_ff` 6144; MoE 256 experts, top-6, expert width 512, shared 1024, sigmoid routing, `norm_topk_prob` | +| vocab | 150144, untied head | +| KV | two groups: full (14 layers) and window 513 (35 layers) | + +The full layers are `0, 1, 5, 9, ..., 45, 48`; the rest are sliding and carry RoPE. + +## Containers and recipes + +| file | contents | size | +|---|---|---| +| `flint-q4.rad` | U4 attention, I4 experts, INT8 dense/shared/head, BF16 router/norms/embed | 19.72 GiB | +| `flint-iq8r.rad` | IQ8R attention/dense/shared gate-up, rotated INT8 experts and shared down, INT8 head, BF16 router/norms/sinks/embed | about 38 GiB (not re-measured) | + +Recipes: `data/recipes/flint-bf16-q4.recipe` and `data/recipes/flint-iq8r.recipe`. + +The plugin reads which form a container holds from layer 0's q projection: + +- **Rotated int8 trunk** (IQ8R, or the 128-group rotated int8 form): the norms write + `rmsnorm_had_quant_i8g`'s codes (`ar_rmsnorm_had_quant_i8g` with the fused all-reduce at TP2), + the attention output `had_quant_act_i8g`'s and the gated products `gated_had_quant_i8g`'s, and + every linear reads them at `i8a8h` without a quantiser of its own. The routed experts must be + stored rotated (int8, or a rotated four-bit form with an int8 row); the grouped GEMM + (`moe_gemm_i8a8`) reads the block input's own codes for gate/up and the gated product's, at one + scale a 128, for down. +- **Any other trunk** (bf16, the Q4 recipe's u4 attention, plain int8 linears): each linear reads + the bf16 plane or quantises it itself (`quant_act_i8g` for a plain int8 weight), and four-bit + experts read the block input's E4M3 pair (`moe_gemm_w4a8`). + +A rotated trunk over unrotated experts, or rotated int8 experts under an unrotated trunk, is +refused at declare with the recipe to use. + +Two non-obvious inputs: + +- `data/flint-zero-bias.safetensors`: Flint has no router correction bias. The sigmoid router's + bias is selection-only, so the converter merges 47 x `[256]` zero tensors under + `model.layers.N.mlp.expert_bias`. +- `data/flint-chat-template.jinja`: the checkpoint's template contains `\x00`, which the Jinja + parser rejects. This is the same template without that replace; pass it with `--chat-template`, + or `/v1/chat/completions` answers 501 for want of a template. + +## Convert + +```bash +export RADIANCE_HOME=$PWD/build/radiance_home + +# Q4 +./build/bin/rad-convert "$HOME/models/flint" \ + --add data/flint-zero-bias.safetensors \ + --recipe data/recipes/flint-bf16-q4.recipe \ + --chat-template data/flint-chat-template.jinja \ + --report 20 --gpus 0,1 -o "$HOME/models/rad/flint-q4.rad" + +# IQ8R +./build/bin/rad-convert "$HOME/models/flint" \ + --add data/flint-zero-bias.safetensors \ + --recipe data/recipes/flint-iq8r.recipe \ + --chat-template data/flint-chat-template.jinja \ + --report 20 --gpus 0,1 -o "$HOME/models/rad/flint-iq8r.rad" +``` + +`--plan-only` is the cheap pre-flight: it runs declare and resolves every op against the loaded +kernels before reading the 75 GiB checkpoint. + +## Serve + +```bash +# Q4, one card +./build/bin/radiance --model "$HOME/models/rad/flint-q4.rad" \ + --radiance-home build/radiance_home --max-model-len 262144 --port 8090 + +# Q4, two cards (long context, expert parallel) +./build/bin/radiance --model "$HOME/models/rad/flint-q4.rad" --tp 2 \ + --radiance-home build/radiance_home --max-model-len 262144 --port 8090 + +# Q4 with the int8 KV cache (about half the cache memory) +./build/bin/radiance --model "$HOME/models/rad/flint-q4.rad" \ + --radiance-home build/radiance_home --max-model-len 262144 \ + --kv-cache-dtype i8 --port 8090 + +# IQ8R needs both cards: about 38 GiB of weights +./build/bin/radiance --model "$HOME/models/rad/flint-iq8r.rad" --tp 2 \ + --radiance-home build/radiance_home --max-model-len 131072 --port 8090 +``` + +The KV cache is bf16 by default, or with `--kv-cache-dtype i8` the int8 cache: K and V as int8 +codes with one f16 scale each per token and head (`2 * head_dim + 4` bytes a token and head). +Both KV groups, the full one and the 513-token window, take it, and the sink attention, the store +and the fused prologue all have rows for both. No other cache dtype is served. + +## Measured + +Taken on the 1.17-era build, before this port: the "Q8" columns are the plain int8 container +(unrotated int8 linears and experts, served by that build's plain int8 grouped GEMM), which this +build no longer serves; the IQ8R container has not been measured. The Q4 container is the same +recipe, served now by this build's kernels, and has not been re-measured either. + +Two R9700s, greedy, warm, prefix cache disabled. Q4 and Q8 both at TP2. The payloads are +1,325 / 8,928 / 26,073 tokens. Tokenizers differ at 26K, so the payload is not the same token +count on both sides. + +| context | Q4 prefill | Q4 decode | Q8 prefill | Q8 decode | +|---|---|---|---|---| +| 1.3K | 14,488 | 161.4 | 8,036 | 112.5 | +| 9K | 14,019 | 154.5 | 8,232 | 109.8 | +| 26K | 11,850 | 136.6 | 7,621 | 100.4 | + +Reference on the same box, llama-server Q8 (fresh server, `-ngl 999 --jinja`) and Q4 (the +release's GGUF): about 2,364 / 5,359 / ~5,028 tok/s prefill for Q8 at 1.3K / 9K / 26K, ~65-70 +tok/s decode, and 2,197 / 5,400 / ~3,290 tok/s prefill for Q4 with 77.7 tok/s decode at 1.3K. +llama.cpp's numbers move with its build and flags; re-measure beside the run being reported. + +## Kernels + +- **Experts.** IQ8R: `moe_gemm_q` at dtype `i8a8h` (`moe_gemm_i8a8`), rotated int8 weights at a + bf16 scale a (row, 128 of K) against the rotated int8 activation. Q4: `moe_gemm_q` at `w4a8` + (`moe_gemm_w4a8`) against the E4M3 activation. Expert parallel at TP2: each rank holds 128 + whole experts a layer. On the 1.17-era build the Q4 w4a8 oracle reported the rows past + `off[n_expert]` as a mismatch (the kernel zeros the dropped tail, the reference computes it); + every live row agreed, and the first bad offset was `live * N`. +- **Sink attention.** `attn_paged_sink` at head_dim 128, gqa 8, on the bf16 or the int8 cache. + A prefill-shaped launch takes the WMMA kernel with the sink folded in: the sink seeds the running + max and one lane's denominator in the log2 domain, and the final reduction adds both lanes. + Decode and verify launches take the scalar kernel with split-KV, whose unsplit store and merge + fold the sink. +- **Residual and all-reduce.** `NormQuantFP8` folds the previous block's delta and its two-rank + all-reduce into the norm (`fuse_ar`), so only the embedding's reduce and the last block's + remain. Flint also sets `shared_fp32_combine` 0: the gather adds the local routed and shared + partials and one collective covers both, which is the TP1 arithmetic. The exact cross-rank + wire is the default; under `--tp-wire wht6` both trunk forms' norms have a 6-bit fused form + (`ar_rmsnorm_had_quant_i8g` and `ar_rmsnorm_quant_fp8` at `wire` 6). +- **NoPE prologue.** At decode heights the 14 full layers use `qkv_norm_rope_kv_store` with + `rotary_dim` 0: the kernel copies the normed head through the rotary stage, so it is the norms + and the store alone. Prefill heights take the standalone norms and `kv_store`, without a + rope on those layers. + +## Correctness + +On the 1.17-era build (not repeated on this one): + +- Needle retrieval at 8K and 32K returned `ZX-417-QQ` exactly, with BF16 and E4M3 KV, including + after the sink-aware WMMA prefill. +- A `get_weather` tool call parsed as `tool_calls` with `{"city":"Paris"}`; reasoning uses + `...`. +- A 250,696-token prompt completed on two cards. On one card, Q4 at 262K fit with that build's + E4M3 KV cache: 19.37 GiB of weights plus an 11.45 GiB cache. The int8 cache of this build takes + a few percent more a token (its two f16 scales a token and head). + +On this build, `tests/flint_arch_test.cpp` checks the declared graph and the step of both +containers at one and two ranks on both caches, and `tests/r4d_emu/test_attn.cpp` the sink WMMA +prefill on the bf16 and the int8 cache. + +## Known limitations + +- **Decode attention.** The scalar sink kernel is the short-context ceiling: ~184 us for a + 513-window layer at 1.3K, against ~15 us of KV traffic. A flash-decoding decode form is the + follow-up. +- **No draft head.** Flint has no MTP head. Prompt-lookup speculation is available at serve time + and is workload-dependent. diff --git a/docs/GUIDE.md b/docs/GUIDE.md index b12a7e5d..0b66e7f4 100644 --- a/docs/GUIDE.md +++ b/docs/GUIDE.md @@ -314,6 +314,8 @@ and runs. | `qwen4exp_fp8` | Qwen4-Exp / Qwen3.8-Flash-Next: hybrid Gated DeltaNet + gated attention, 512 experts | | `gemma4` | Gemma 4 text decoders (26B-A4B MoE and the dense members): bf16 trunk, routed experts bf16 or block fp8, and the DFlash drafter | | `gemma4_bf16` | Gemma 4 dense in bf16, with its vision tower | +| `museglimmer` | Meta Muse Glimmer 30B: gated attention alternating sliding-window (rotary) and NoPE full layers, Gemma-2 double norms, a 50-block windowed ViT; bf16 | +| `museglimmer_ct` | the same trunk as an int4 container (`--set quantization_config.quant_method=compressed-tensors`) | | `lfm2_bf16` | LiquidAI LFM2 and LFM2-VL in bf16, including d1 (§5.13) | | `embgemma2` | EmbeddingGemma 2, an embedding model (§5.6) | | `nomicbert` | nomic-embed-text-v2-moe, an embedding model (§5.6) | @@ -1469,6 +1471,32 @@ short of the boundary and the next step finishes it. A prompt with nothing besid `off` lets a chunk take the whole step; `N` holds a shared chunk to N tokens (startup warns when N is under the stager's step). `radiance:engine_prefill_chunks_capped_total` counts the chunks held back. +**Adaptive mixed-step latency** (`mixed-step-target-ms: N`, default off). A mixed step contains +both prefill rows and at least one decoding sequence. When this flag is set, completed mixed steps +teach a model-agnostic controller an aggregate prefill-row cap. The cap is shared fairly among the +prefills in that step, decode rows are reserved first, and a lone prefill remains unchanged. This +is a soft service-time target, not a request deadline: timing starts when the engine issues the +step and ends after its forward and speculative-drafter work. Queueing, HTTP transport and the +client are outside it, and the legal chunk quantum, fixed decode cost, media passes or host jitter +can make the target unattainable. + +The controller starts at one quarter of the model's shared-step capacity, corrects an over-target +representative chunk immediately, and grows cautiously after three clearly under-target samples. +A true prompt tail does not change the learned cap; a checkpoint or fixed busy-chunk boundary does, +because the prompt continues and a lower cap can shorten its next step. If the target is lower than +one legal mixed step, the cap bottoms out at one prefill quantum and misses remain visible. Startup +refuses configurations whose token budget or explicit busy cap cannot carry one legal prefill +quantum beside a decode row. When the batch budget cannot carry one quantum for every simultaneous +prefill, equal sharing applies to the requests that fit and the scheduler's priority/arrival order +continues the rest on later steps; startup prints that capacity. Raise the batch budget if every +admitted prefill must progress in every mixed step. + +Use the target for an interactive multi-user deployment where long fresh prompts otherwise make +active streams pause. It redistributes when useful work completes; it does not make the prefill +free, and may lower fresh-prefill throughput under contention. Pin and measure the target per +deployment rather than branching the scheduler by model name. The relevant metrics are +`radiance:mixed_step_target_steps_total`, `_misses_total`, and `_prefill_cap`. + **Check the prefix cache after changing the chunk.** The larger arena shrinks the KV pool (here 516,864 to 499,920 pool tokens, 3.3%), and §4.3's cliff is sharp. With two ~180K sessions (first turns back to back, then the first session's second turn), a 512 chunk took 137.7 s, 130.0 s and @@ -1844,7 +1872,9 @@ models: - `prefix-cache-mib: N` enables the host tier, up to N MiB. It holds attention blocks only; a hybrid model's linear-state snapshots are already in host memory, in the `checkpoint-slots` store. A conversation larger than the tier keeps its start there and is prefilled again past it once VRAM - gives the rest up; the startup log warns when the tier holds less than one `max-model-len` + gives the rest up (for a request that needs the room, or where a few leftover blocks high in the + pool keep the expert slab's loan from most of it under `placement: expert_tiered`); the startup + log warns when the tier holds less than one `max-model-len` conversation and says how many MiB would, and a `kv tiers: ... got no host copy` line appears when it happens (`/sessions` `moved.held_back`). While a KV group streams (`kv-resident`), the tier is off and its MiB are not reserved: a @@ -2297,6 +2327,7 @@ switch is set with `true`. The fleet's own keys (a model's `aliases`, `priority` |---|---|---| | `max-num-batched-tokens: N` | 2048 | largest token count one step may carry | | `prefill-interleave: N` | auto:1 (0 under `deterministic: true`, KL mode, generators) | decode-only steps after each prefill chunk while other sequences decode (§4.5), at most 64; `auto` fits them in a quarter of the chunk step's measured time, `auto:SHARE` in SHARE of it (0 < SHARE <= 4); `0` lets every step carry a chunk | +| `mixed-step-target-ms: N` | 0 (off) | soft completed-service-time target for mixed prefill/decode steps; learns one aggregate prefill cap while decoders are active and leaves uncontended prefill unchanged (§4.5) | | `preempt-wait-ms: N` | 5000 | how long a preempted prefill may wait for its whole-recompute gate before reclaiming cache blocks and preempting lowest-priority running requests until one overdue request can prefill; `0` falls back on the next step. A preempted request publishes what it computed to the prefix cache, as a finished one does, so its recompute adopts its prompt instead of computing it again; under pressure the cache gives those blocks back, the newest last, before another request is preempted | | `busy-prefill-chunk: MODE` | auto | a prefill chunk's share of a step that has other work: `auto` leaves decode rows and waiting requests their room (§4.5), `off` takes the whole step, `N` holds it to N tokens | | `max-num-seqs: N` | 256 | largest number of sequences one step may carry | @@ -2446,6 +2477,18 @@ keys are refused on it, and so are the pixel bands. | `kld-lora: NAME` | run the documents through the `lora` adapter `NAME` (§4.9.1), e.g. against a reference recorded from the merged checkpoint | | `kld-lora-sources: PREFIX` | with `kld-lora`, only the documents whose `source` starts with `PREFIX` run through the adapter; the rest run as the base, in the same steps | +**Self-measurement**, instead of serving: a fixed workload, a report, an exit code; see [DIAGNOSE.md](DIAGNOSE.md) + +| key | default | | +|---|---|---| +| `diagnose: DIR` | — | run a fixed workload instead of serving and write `DIR/diagnose.json` and `DIR/diagnose.md`: step times, tokens a step, draft acceptance, TTFT, emission intervals, jitter, by prompt category, concurrency and prefill depth | +| `diagnose-tokens: N` | 256 | tokens a decode stream generates | +| `diagnose-runs: N` | 3 | measured runs of each point, after one unmeasured | +| `diagnose-concurrency: LIST` | 1,2,4,8 | stream counts of the concurrency sweep | +| `diagnose-prefill: LIST` | 1024,4096,16384,65536 | prompt lengths of the prefill sweep | +| `diagnose-corpus: FILE` | built-in | JSONL of category prompts | +| `diagnose-baseline: FILE` | — | an earlier `diagnose.json`: compare every request's tokens with it | + **Diagnostics** | key | | @@ -2488,7 +2531,7 @@ keys are refused on it, and so are the pixel bands. | `POST /v1/responses`, `POST /v1/responses/input_tokens` | OpenAI's Responses API, for Codex and the OpenAI SDKs' `responses` client (§5.9) | | `POST /completion`, `/completions`, `POST /infill` | llama-server's native completion and fill-in-the-middle, for llama.vim, llama.vscode and clients of llama-server's own API (§5.9) | | `GET /v1/models`, `/v1/models/:id` | what is loaded, with `max_model_len` (the context it serves) and `root` (the `model` path) as vLLM reports them, and `capabilities` (the same object `/server_info` reports); `:id` returns the entry itself, as OpenAI's retrieve does | -| `GET /health`, `/v1/health`, `/ping`, `POST /ping` | liveness | +| `GET /health`, `/v1/health`, `/ping`, `POST /ping` | liveness; 503 with `"status": "stuck"` once the device has advanced nothing for a minute. A device stuck for `scheduler.stuck-exit` (60s; `0` never) ends the process (exit status 70, the queues it is stuck on in the log), so a restart policy brings the server back | | `GET /load` | current load | | `GET /version` | server version | | `GET /props` | llama-server's props: `n_ctx`, `total_slots`, `modalities`, `model_path`, the chat template and its capabilities, `bos_token`/`eos_token`, and the request defaults under llama-server's names | @@ -3551,12 +3594,48 @@ curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json minutes; the model ends the speech at the end of the text. The prompt holds at most 512 tokens. - **`seed`**, **`response_format`**, **`speed`** and **`voice`** are read as for music below (`voice` is ignored here too: the instructions say who speaks); `num_inference_steps` is refused - (the model has no denoiser). Cloning a voice from a recording is not served. + (the model has no denoiser). + +**Voice cloning:** supply `references: [{"audio": "...", "text": "..."}]`, with one clean recording +and its exact transcript. `audio` is a base64-encoded audio file or a base64 data URL, not a server +path or remote URL. The server decodes/resamples it to 24 kHz mono. The recording may hold at most +10 seconds, including zero-padding to whole 1920-sample frames. Its transcript, audio frames and +new speech together must fit the 512-row prompt. Obtain the speaker's consent and rights to the +recording before cloning. + +```sh +python3 - <<'PY' > clone.json +import base64, json +with open("reference.wav", "rb") as f: + audio = base64.b64encode(f.read()).decode("ascii") +print(json.dumps({"input": "Here is a new sentence in the reference voice.", + "references": [{"audio": audio, "text": "The exact words in reference.wav."}], + "guidance_scale": 1, "response_format": "wav", "seed": 42})) +PY +curl --fail-with-body http://localhost:8000/v1/audio/speech \ + -H 'Content-Type: application/json' --data-binary @clone.json -o clone.wav +``` + +Cloning uses Breeze's `ref_clone_tata` continuation template. Omit `instructions` and use +`guidance_scale: 1` (the default) to keep the reference delivery. To direct the cloned voice, +also supply `instructions`, for example `"Speak softly and slowly, with a reassuring delivery."`, +and start with `guidance_scale: 4`. This selects `ref_edit_tata`: the conditional prompt includes +the reference and direction, while its guidance baseline includes the same reference without +direction. Each branch has its own text length and reference-frame map; the audio is encoded +once and shared. Higher guidance strengthens direction but can affect naturalness or identity. +This is ordinary two-branch guidance, not Breeze's three-branch dual-guidance mode (not served). +WAV, PCM, HTTP streaming and the speech WebSocket use the same reference encoder and templates. +**Reconvert older Breeze `.rad` files with the updated recipe to clone voices:** older conversions +omitted the audio encoder's weights. Such a container still serves speech as before, and a request +with `references` is answered 400 (`this model takes no reference audio`). The new encoder and its +Euclidean codebooks stay in f32; no Python model runtime or external encoder service is needed for +requests. Speech is played four frames (0.32 s) at a time as it is made, so the streamed forms below carry it as it is spoken. On one R9700 a sentence is made at 0.6 of the time it plays (5.1 s of speech in 3.1 s), and a stream's first audio comes 0.21 s after the request; four speak at once at about the -speed they play (43 s of speech in 12.1 s). Breeze-TTS-2 is licensed for research and +speed they play (43 s of speech in 12.1 s). These measurements are for reference-free speech; +cloning adds reference-encoding work before the first frame. Breeze-TTS-2 is licensed for research and non-commercial use only, and BreezeBlue counts hosting it as an API as commercial. #### Speech: drama-3 @@ -4152,6 +4231,8 @@ always 1 and carries the cache's settings as labels: `cache_dtype`, `block_size` | `draft_depth_adaptive`, `draft_verify_depth_total{depth}` | the adaptive window's mean over the running sequences, and verifies by the drafts they carried; only with `draft-window: adaptive` (§4.6) | | `engine_prefill_chunks_capped_total` | prefill chunks held back to share a step (§4.5) | | `engine_steps_held_total` | decode-only steps `prefill-interleave` ran between chunks (§4.5) | +| `mixed_step_target_steps_total`, `mixed_step_target_misses_total` | mixed steps observed by `mixed-step-target-ms`, and those whose completed engine service time exceeded its soft target (§4.5) | +| `mixed_step_target_prefill_cap` | current learned aggregate prefill-row cap; absent while the policy is off (§4.5) | | `attn_cached_tokens_total`, `linear_cached_tokens_total` | prefix reuse, both halves | | `linear_checkpoints_written_total`, `linear_prefix_cache_hit_rate` | | | `prefix_cache_evictions_total`, `prefix_cache_ckpt_evictions_total` | | @@ -4313,7 +4394,7 @@ is the part of a log to paste into an issue. Its sections: warning is also printed as a `W` line of its own. ``` -I STARTUP REPORT -- radiance 2.0.0 +I STARTUP REPORT -- radiance 2.1.0 I CONFIGURATION -- every option, the value in force, and where it came from I --model /models/flashnext.rad [models.flashnext.model] I --tp 2 [models.flashnext.tp] diff --git a/docs/MULTIMODEL.md b/docs/MULTIMODEL.md index 69ccffde..ffe3f30d 100644 --- a/docs/MULTIMODEL.md +++ b/docs/MULTIMODEL.md @@ -186,6 +186,7 @@ scheduler: load-timeout: 120s # a request waits this long for its model, then 503 drain-timeout: 30s # a model being evicted gets this long to finish its requests keepalive: 10s # SSE comment interval for streaming requests waiting on a load + stuck-exit: 60s # a device that advances nothing this long ends the process; 0 never warm-up: true # fill free VRAM, then host RAM, with models at start (§8.6) ``` @@ -196,7 +197,7 @@ scheduler: | `server:` | `host`, `port`, `api-key`, `api-key-env`, `allow-host`, `trusted-proxy`, `http-threads`, `read-timeout`, `write-timeout`, `keep-alive-timeout`, `max-body-mib`, `retry-after`, `no-cors`, `live`, `log` (`info`/`debug`/`trace`), `radiance-home`, `kernels`, `download-dir`, `proceed-with-incompatible-configuration`, `debug-accept-reference-kernels` | | `cards:` | `all` or a list of card indices | | `memory:` | `gpu-headroom-mib`, `gpu-memory-mib` (per card), `host-mib`, `host-headroom-mib`, `disk-tier` | -| `scheduler:` | `load-timeout`, `drain-timeout`, `keepalive`, `warm-up` | +| `scheduler:` | `load-timeout`, `drain-timeout`, `keepalive`, `stuck-exit`, `warm-up` | | `defaults:` / `models.:` | every per-model flag: model source, TP, placement, KV, scheduler, spec decode, LoRA, request defaults and limits, media limits, offline modes, debug; plus the fleet keys `aliases`, `priority`, `pin`, `ttl`, `flex`, `park` | | `groups:` | `together` / `exclusive` lists | @@ -208,7 +209,8 @@ adds more. A one-model YAML is the only way to run one model too. `radiance --model X ...` is refused with a message that prints the equivalent YAML, so a migration is copy and paste. Offline modes (KL -recording, calibration) run from a one-model YAML with the `kld-*` / `calib-*` keys on that model; +recording, calibration, the diagnose workload) run from a one-model YAML with the `kld-*` / +`calib-*` / `diagnose` keys on that model; the process does that job and exits, as today. ### 4.5 Provenance diff --git a/docs/OPS.md b/docs/OPS.md index bacdf55f..d9cef5c4 100644 --- a/docs/OPS.md +++ b/docs/OPS.md @@ -206,6 +206,8 @@ at once. Run it before adding a kernel plugin; the loader names only the first c | `hc_project` | `M`(range) `n` `hc` `scale`:f64 `dtype` | `h`:inout, `v`, `on` | | `layernorm` | `M`(range) `n` `eps`:f64 `dtype` | `x`, `w`w, `b`w? → `y` | | `grid_embed` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | +| `grid_embed_pad` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | +| `window_order` | `M`(range) `window` | `coord`, `cu` → `idx`, `inv`, `pos`, `cuw` | | `grid_embed_aa` | `M`(range) `n` `side` `dtype` | `x`:inout, `table`w, `coord` | | `grid_embed_cpe` | `M`(range) `n` `side` `dtype` `n_prefix`/opt | `x`:inout, `table`w, `coord`, `prefix`w? | | `add` | `M`(range) `n` `dtype` `div`:f64/opt | `a`, `b` → `y` | @@ -339,6 +341,29 @@ is `[4, M]` (row, column, grid height, grid width); sampling is bilinear with th the table's (align_corners), edge taps clamped, the four taps summed in f32 and rounded to `x`'s dtype before the add. +**`grid_embed_pad`** adds the same table with the same operands in the half-pixel-centre form +(align_corners=False) under grid_sample's `padding_mode="zeros"`: per axis taps at `floor(src)` and +`floor(src) + 1` of `src = (i + 0.5) * side / size - 0.5`, each carrying the hat weight +`(1 - |src - tap|)+`, and a tap whose UNCLAMPED index falls outside `[0, side)` contributes zero +rather than reading a clamped edge. The taps are summed in f32 in `grid_embed`'s order and rounded +the same way. For a grid no larger than the table no tap is ever out of range and the op is +`grid_embed`'s function at the different sample positions; it differs from it materially only when +a grid upsamples past the table, which is the common case for Muse (448 px and larger images). + +**`window_order`** computes the window-attention permutation of one encoder pass, entirely from +on-device coordinates: HF's `get_vision_window_index` as a gather-index computation over the packed +pass. `coord` is `[4, P]` i32 (row, column, segment height, segment width per patch) and `cu` is +`[S+1]` i32, the per-frame segment boundaries. Windows of `window` patches partition each segment +(one segment == one frame), scanned window-row-major, ragged at the segment's right and bottom +edges; patches keep raster order within a window and windows never span segments. The outputs are +i32: `idx` `[P]`, slot -> source patch (the gather index: `permuted[slot] = x[src[idx[slot]]]`); +`inv` `[P]`, its inverse, used to undo at the tower's end; `pos` `[2, P]`, each slot's rope +positions `(col + 1, row + 1)`, laid out component-major like the coordinate planes (Muse's rotary +wants the axes swapped and offset by one relative to them, HF's `position_ids.flip(-1) + 1`); and +`cuw` `[P+1]`, the cumulative window boundaries in the permuted order, `n_windows + 1` entries +used. `M` is the patches this pass covers; slots past `M` are the identity. `window` <= 0 makes the +permutation the identity and `cuw = cu`. + **`grid_embed_aa`** is the same addition with SigLIP2's resample, torch's `F.interpolate(mode="bilinear", align_corners=False, antialias=True)`: per axis a triangle filter on half-pixel centres, widened by the scale when the grid is smaller than the table, its in-table taps @@ -1448,6 +1473,8 @@ libref function says which (`libref/ref_audio.cpp`). | `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt `top_p`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? | | `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt `clamp`/opt | `codes`, `t0`w, `t1`w → `y` | | `vq_encode` | `M`(range) `n` `dim` `bins` `dtype` | `x`:inout, `in_w`w, `in_b`w, `cb`w, `out_w`w, `out_b`w → `codes` | +| `vq_euclidean` | `M`(range) `n` `bins` `dtype` | `x`:inout, `cb`w → `codes` | +| `elu` | `M`(range) `n` `dtype` | `x` → `y` | | `frame_mix_store` | `M`(range) `n_embd` `L` `stride` `rep`/opt `dtype` | `hid`, `logits`w, `scale`w, `lane`, `frame`, `status`, `dst`:inout | | `end_status` | `M`(range) `end` `rep` | `ids`, `lane`, `status`:inout | | `ras_pick` | `M`(range) `win` `lo` `hi` `rep`/opt `clear`/opt | `first`, `alt`, `lane`, `hist`:inout → `ids` | @@ -1503,6 +1530,20 @@ conditional first, then the unconditional) are consecutive rows, `rep` of them a `x -= out_w cb[code] + out_b` (`out_w` `[n, dim]`, the raw codebook row), rounded once into `x`. f32 arithmetic. A chain of these over a codec's codebooks, each quantising what the last left, is its residual quantiser. +- `vq_euclidean`: Mimi's RVQ step (Breeze's reference encoder), after the enclosing split + quantiser's input projection. For each row of `x` `[rows, n]`, choose the nearest row of `cb` + `[bins, n]` by squared Euclidean distance in f32, ties to the lower index; write that index to + `codes` i32 at its own stride, and subtract the chosen centroid from `x`. No normalisation and + no per-codebook projections; the semantic and acoustic residual chains are independent. The + device kernel supports f32, one workgroup a row, `n <= 4096`, `bins <= 65536`. +- `elu`: `y = x >= 0 ? x : expm1(x)`, alpha 1, at each operand's row pitch. In-place use is valid. + The device kernel supports f32 (Breeze's reference encoder). + +The reference encoder also uses f32 device forms of ordinary `gemm_nt`, `layernorm` (up to 4096 +channels), exact-erf `gelu` and `attn_dense` (causal, head dimension 64, GQA 1, at most 512 rows). +The existing `rope` entry dispatches f32 inputs to the full-head 64-dimensional NeoX form with +one-component positions and no YaRN or Llama-3 scaling. Causal strided `conv1d` supports f32 as +well as bf16; the explicit symmetric `pad` form remains bf16-only. - `frame_store`: `dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]` for every `k`, when `frame >= skip` and `status[lane] >= 0`: a frame's codes into its lane's history, each codebook a row over the lane's frames, so a run of a lane's frames is a block of `n_codes` diff --git a/docs/TOOLS.md b/docs/TOOLS.md index 1b5fe820..572b5e4f 100644 --- a/docs/TOOLS.md +++ b/docs/TOOLS.md @@ -1000,6 +1000,52 @@ H = np.zeros((k, k), np.float32); H[np.triu_indices(k)] = t; H = H + np.triu(H, --- +## The diagnose mode + +```yaml +# diag.yaml: the model's own keys, plus the mode +models: + quant: + model: M.rad + diagnose: DIR +``` + +```sh +radiance --config diag.yaml # the workload, the report, and the exit code +``` + +Runs a fixed workload on the engine instead of serving it — decode by prompt category, a +concurrency sweep, a prefill sweep with decode at each depth, and a prompt arriving into running +streams — and writes `DIR/diagnose.json` and `DIR/diagnose.md`: step times and their spread, tokens +a step, draft positions drafted and accepted, TTFT, per-token emission intervals and jitter, per +request and per phase, with the machine and the settings it ran under. It starts as a serve would +(same placement, same kernels, same prefix cache) and exits, so it can be run on every candidate +build and compared. + +| key | default | | +|---|---|---| +| `diagnose: DIR` | — | run the workload and write the report to DIR; `diagnose.json` is the whole report, `diagnose.md` reads it | +| `diagnose-tokens: N` | 256 | tokens a decode stream generates | +| `diagnose-runs: N` | 3 | measured runs of each point, after one unmeasured; median and spread are reported | +| `diagnose-concurrency: LIST` | 1,2,4,8 | stream counts of the concurrency sweep; a count above `max-num-seqs` is skipped and reported | +| `diagnose-prefill: LIST` | 1024,4096,16384,65536 | prompt lengths of the prefill sweep, in tokens; a length the context cannot hold is skipped and reported | +| `diagnose-corpus: FILE` | built-in | JSONL, one `{"category", "messages" or "prompt", "max_tokens"?}` a line: code, reasoning, prose, json, file_edit, summarization | +| `diagnose-baseline: FILE` | — | an earlier `diagnose.json` of the same workload: compare every request's tokens with it and fail the run on any difference | + +Every prompt is salted so the prefix cache serves none of it, the cache is emptied before every +run, and each request's cached-token count is checked afterwards: a hit, or step records the ring +overwrote before they were read, makes the verdict `NOT A MEASUREMENT` and the exit code non-zero. +Requests run at temperature 1 with the server's top_k/top_p/min_p and a fixed seed per request, so +two builds of the same model are compared token for token. `diagnose` is a mode of the engine +like `kld-ref`: it cannot be combined with the KL keys, `calib-corpus` or `debug-graph`, and the +file names one model. `diagnose-corpus` and `diagnose-baseline` need it. + +The report says in `not_measured` what it does not cover — per-kernel device time, placement and +link counters per phase, op correctness over a step window, and the HTTP path. What the numbers +mean, what makes a run a measurement and what is still missing: [DIAGNOSE.md](DIAGNOSE.md). + +--- + ## The shell harnesses `scripts/` drives a running engine: bring a model up, measure it, and assert on what comes back diff --git a/docs/YARN.md b/docs/YARN.md index b8dfc301..f2e806d3 100644 --- a/docs/YARN.md +++ b/docs/YARN.md @@ -19,7 +19,11 @@ The factor convention is the config's, as vLLM and transformers read it: `factor Validated: the Qwen3.8-27B and Qwen3.6-35B-A3B containers and both Flash-Next variants at factor 2, with retrieval at about 500K tokens, and TP3 perplexity with `rope-scaling` within about ±1% of the unscaled model at factor 2. The LLaMA plugins read the same keys and declare the same ops, but -YaRN has not been run on a LLaMA model. +YaRN has not been run on a LLaMA model. Muse Glimmer validated at factor 8 over 131072 (a 1M +serving window) with retrieval at 913K tokens -- and, unusually, without any scaling at all +(mechanical window extension to 495K, also retrieval-passing): only its 2048-wide sliding layers +carry rotary and its full-attention layers are NoPE, so the unscaled window is the family's +default recipe (docs/ARCHITECTURES.md, museglimmer). ## Metadata diff --git a/libavx/avx_audio.cpp b/libavx/avx_audio.cpp index 49e8af16..2c53cd05 100644 --- a/libavx/avx_audio.cpp +++ b/libavx/avx_audio.cpp @@ -845,6 +845,64 @@ AVX_KERNEL(vq_encode) { return RAD_OK; } +/* ------------------------------------------------------------------ vq_euclidean */ +/* libref's step a row at a time: the squared distance to every centroid summed in channel order, + * the nearest taken (the lower index on a tie), its code written and the centroid subtracted from + * the row, rounded once into x. The codebook is read dense in f32 once a launch. */ +AVX_KERNEL(vq_euclidean) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *X = &a->t[0], *cb = &a->t[1], *codes = &a->t[2]; + const int64_t n = p_int(a, "n", 0), bins = p_int(a, "bins", 0); + if (n <= 0 || bins <= 0 || numel(cb) != bins * n || codes->dtype != RAD_I32) + return RAD_E_SHAPE; + const int64_t rows = rows_of(X, n); + if (rows < 1 || numel(codes) < rows) return RAD_E_SHAPE; + std::vector dense((size_t)(bins * n)); + for (int64_t i = 0; i < bins * n; ++i) dense[(size_t)i] = ldt(cb, offlin(cb, i)); + const float* C = dense.data(); + AVX_PARALLEL_FOR_IF(rows * bins * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + const int64_t xb = rowoff(X, r, n); + const float* xv = in_row(X, xb, n, scratch_f32((size_t)n + 16)); + float best = INFINITY; + int64_t pick = 0; + for (int64_t k = 0; k < bins; ++k) { + const float* c = C + k * n; + float d = 0.0f; + for (int64_t j = 0; j < n; ++j) { + const float delta = xv[j] - c[j]; + d += delta * delta; + } + if (d < best) { best = d; pick = k; } + } + st_int_dt(codes->dtype, codes->data, offlin(codes, r), pick); + float* y = scratch_f32_b((size_t)n + 16); + const float* c = C + pick * n; + for (int64_t j = 0; j < n; ++j) y[j] = xv[j] - c[j]; + out_row(X, xb, n, y); + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ elu */ +/* y = x >= 0 ? x : expm1(x) (alpha 1), a row at a time, as libref. */ +AVX_KERNEL(elu) { + 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", numel(Y)); + if (n <= 0) return RAD_E_SHAPE; + const int64_t rows = rows_of(Y, n); + if (rows <= 0 || numel(X) < rows * n) return RAD_E_SHAPE; + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + float* sy = scratch_f32_b((size_t)n); + const float* v = in_row(X, rowoff(X, r, n), n, scratch_f32((size_t)n)); + for (int64_t i = 0; i < n; ++i) sy[i] = v[i] >= 0.0f ? v[i] : std::expm1(v[i]); + out_row(Y, rowoff(Y, r, n), n, sy); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ frame_mix_store */ /* m = bf16(bf16(sum_l w_l h_l) * bf16(scale)), w = bf16(softmax(bf16(logits))) in libref's double * arithmetic, the planes summed in order with each product rounded before its add (`keep`). Entries diff --git a/libavx/avx_cases.cpp b/libavx/avx_cases.cpp index e6af9db9..fd40a5cf 100644 --- a/libavx/avx_cases.cpp +++ b/libavx/avx_cases.cpp @@ -660,6 +660,9 @@ std::vector build_cases() { HF("theta", 10000.0), HF("eps", 1e-6), HI("rotary_dim", 0), HI("v_norm", 1), HS("dtype", dt) }); add("grid_embed", { HI("M", 20), HI("n", 72), HI("side", 6), HS("dtype", dt) }); + /* The zero-padded form: drawn grids never exceed the table, so the off-table masking is + * covered by avx_check's hand-built case. */ + add("grid_embed_pad", { HI("M", 20), HI("n", 72), HI("side", 6), HS("dtype", dt) }); /* Two table sides. A drawn grid never exceeds the table, so upscaling is covered by * avx_check's hand-built case. */ add("grid_embed_aa", { HI("M", 20), HI("n", 72), HI("side", 16), HS("dtype", dt) }); @@ -1243,6 +1246,13 @@ std::vector build_cases() { } add("vq_encode", { HI("M", 3), HI("n", 40), HI("dim", 5), HI("bins", 33), HS("dtype", "f32") }); + /* Mimi's Euclidean quantiser step at its codebook's shape and at widths that are no + * vector's, and the encoder's ELU over a row that is none either. */ + for (const char* dt : { "f32", "bf16" }) { + add("vq_euclidean", { HI("M", 7), HI("n", 256), HI("bins", 2048), HS("dtype", dt) }); + add("vq_euclidean", { HI("M", 3), HI("n", 37), HI("bins", 33), HS("dtype", dt) }); + add("elu", { HI("M", 6), HI("n", 645), HS("dtype", dt) }); + } add("frame_store", { HI("M", 2), HI("n_codes", 16), HI("stride", 9), HI("rep", 2), HI("skip", 0) }); add("frame_store", { HI("M", 4), HI("n_codes", 3), HI("stride", 5), HI("rep", 1), diff --git a/libavx/avx_check_hand.cpp b/libavx/avx_check_hand.cpp index c98c07fe..1673195c 100644 --- a/libavx/avx_check_hand.cpp +++ b/libavx/avx_check_hand.cpp @@ -556,6 +556,37 @@ void shape_cases(std::vector& hs) { .pi("M", 6).pi("n", N).pi("side", 4).pi("n_prefix", 3).ps("dtype", "f32"); hs.push_back(std::move(gc)); + /* Muse's zero-padded resample: a 4 x 4 table onto rows of an 8 x 8 grid, whose top row + * and right column reach taps off the table (zero-weight) and blend the rest. */ + static const int32_t kPadCrd[4][6] = { { 0, 7, 1, 4, 7, 3 }, { 0, 7, 3, 2, 0, 7 }, + { 8, 8, 8, 8, 8, 8 }, { 8, 8, 8, 8, 8, 8 } }; + Hand gp("a 4 x 4 table onto an 8 x 8 grid, off-table taps weighted zero", "grid_embed_pad", + 1e-6); + gp.dense(RAD_F32, { 6, N }, hfill(64), true) + .dense(RAD_F32, { 16, N }, hfill(65)) + .dense(RAD_I32, { 4, 6 }, [](int64_t i) { return (float)kPadCrd[i / 6][i % 6]; }) + .pi("M", 6).pi("n", N).pi("side", 4).ps("dtype", "f32"); + hs.push_back(std::move(gp)); + + /* Muse's window permutation: a 12 x 10 segment and an 8 x 8 one, window 8 (the first + * segment's right and bottom windows are ragged). */ + constexpr int64_t WP = 12 * 10 + 8 * 8; + Hand gw("12 x 10 and 8 x 8 segments, window 8", "window_order", 0.0); + gw.dense(RAD_I32, { 4, WP }, [=](int64_t i) { + const int64_t p = i % WP, cplx = i / WP; + const int seg = p < 120 ? 0 : 1, base = seg ? 120 : 0; + const int gh = seg ? 8 : 12, gw_ = seg ? 8 : 10; + const int q = (int)(p - base), r = q / gw_, c = q % gw_; + return (float)(cplx == 0 ? r : cplx == 1 ? c : cplx == 2 ? gh : gw_); + }) + .dense(RAD_I32, { 3 }, [](int64_t i) { return i == 0 ? 0.0f : i == 1 ? 120.0f : 184.0f; }) + .dense(RAD_I32, { WP }, [](int64_t) { return 0.0f; }, true) + .dense(RAD_I32, { WP }, [](int64_t) { return 0.0f; }, true) + .dense(RAD_I32, { 2, WP }, [](int64_t) { return 0.0f; }, true) + .dense(RAD_I32, { WP + 1 }, [](int64_t) { return 0.0f; }, true) + .pi("M", WP).pi("window", 8); + hs.push_back(std::move(gw)); + /* LiLiCorr's candidates over two ranks' sample_logprobs rows: a merge that interleaves the * ranks, an equal value on both (the lower id first), a rank with an unfilled slot. Rows * of (max, sum, 4 (id, logit) pairs descending) a rank, k = 4, steps 3, n = 24. */ diff --git a/libavx/avx_isa.h b/libavx/avx_isa.h index a681578e..423a02a1 100644 --- a/libavx/avx_isa.h +++ b/libavx/avx_isa.h @@ -85,7 +85,7 @@ int avx_par_force(int threads); X(mla_attn) \ X(mla_attn_paged) \ X(add) X(grid_embed) X(grid_embed_aa) X(causal_conv1d) \ - X(grid_embed_cpe) \ + X(grid_embed_cpe) X(grid_embed_pad) X(window_order) \ X(lili_cand) X(lili_attn) X(lili_factor) X(lili_walk) \ X(mul) X(silu_mul) X(gelu_mul) X(gelu) \ X(silu) X(sigmoid) X(logit_softcap) X(gather_rows) \ @@ -148,7 +148,7 @@ int avx_par_force(int threads); X(resample_nearest) X(fourier_embed) X(win_input) X(win_prep) \ X(win_finish) X(chan_split) X(interleave2) X(iota) \ X(cu_repeat) X(snake_aa) X(int_affine) X(sub_i32) \ - X(ras_pick) X(vq_encode) \ + X(ras_pick) X(vq_encode) X(vq_euclidean) X(elu) \ /* ---- sampling, and the drafter's token walk */ \ X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \ X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \ diff --git a/libavx/avx_norm.cpp b/libavx/avx_norm.cpp index cf2876e6..dfd1f64e 100644 --- a/libavx/avx_norm.cpp +++ b/libavx/avx_norm.cpp @@ -19,6 +19,8 @@ #include "avx_vec.h" #include "avx_common.h" +#include + using namespace avx; /* Widen the gain once per launch, not once per row, into a caller buffer built before the @@ -290,6 +292,159 @@ AVX_KERNEL(grid_embed) { return RAD_OK; } +/* ------------------------------------------------------------------ grid_embed_pad */ +/* grid_embed with the half-pixel-centre resample (align_corners=False) and grid_sample's + * padding_mode="zeros": a tap whose UNCLAMPED index falls outside [0, side) carries weight zero + * instead of reading the clamped edge. Matches libref's grid_embed_pad operation: four taps in + * f32 in the same order, rounded to x's dtype, then added and rounded again. Scalar, one row per + * vision-tower patch, as grid_embed's is. */ +AVX_KERNEL(grid_embed_pad) { + if (!rad_args_have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2]; + const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0); + const int64_t side = p_int(a, "side", 0); + if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE; + const int64_t rows = rows_of(x, n); + if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows) + return RAD_E_SHAPE; + const int64_t cs = crd->stride[0], ms = crd->stride[1]; + const int64_t ts = laststride(tab); + + AVX_PARALLEL_FOR_IF(rows * n >= AVX_PAR_MIN) + for (int64_t r = 0; r < rows; ++r) { + int64_t g[4]; + for (int c = 0; c < 4; ++c) g[c] = ldi(crd, c * cs + r * ms); + int64_t th[2], tw[2]; + float wh[2], ww[2]; + auto axis = [&](int64_t idx, int64_t size, int64_t* t, float* w) { + if (size < 1) size = 1; + const float src = (float)side / (float)size * ((float)idx + 0.5f) - 0.5f; + const float fl = std::floor(src); + for (int k = 0; k < 2; ++k) { + const int64_t raw = (int64_t)fl + k; + t[k] = raw < 0 ? 0 : (raw > side - 1 ? side - 1 : raw); + const float d = std::fabs(src - fl - (float)k); + const float u = 1.0f - d > 0.0f ? 1.0f - d : 0.0f; + w[k] = raw >= 0 && raw <= side - 1 ? u : 0.0f; + } + }; + axis(g[0], g[2], th, wh); + axis(g[1], g[3], tw, ww); + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + for (int64_t i = 0; i < n; ++i) { + float acc = 0.0f; + for (int ki = 0; ki < 2; ++ki) + for (int kj = 0; kj < 2; ++kj) + acc += ldt(tab, rowoff(tab, th[ki] * side + tw[kj], n) + i * ts) * + (wh[ki] * ww[kj]); + const float pe = round_act(x->dtype, acc); + stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ window_order */ +/* The window-attention permutation of one pass from the coordinate planes alone (libref's + * window_order operation). One thread does the whole pass: the slot of each patch follows from + * its window's base, computed as a prefix over windows, so the work is two linear walks over P -- + * nothing to vectorise, and off the step path. */ +AVX_KERNEL(window_order) { + if (!rad_args_have(a, 6)) return RAD_E_INVAL; + const RadTensor *crd = &a->t[0], *cu = &a->t[1]; + RadTensor *idx = const_cast(&a->t[2]), *inv = const_cast(&a->t[3]), + *pos = const_cast(&a->t[4]), *cuw = const_cast(&a->t[5]); + const int64_t M = p_int(a, "M", 0); + const int64_t win = p_int(a, "window", 0); + if (M <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < M) return RAD_E_SHAPE; + if (numel(cu) < 2 || numel(idx) < M || numel(inv) < M || numel(pos) < 2 * M || + numel(cuw) < M + 1) + return RAD_E_SHAPE; + const int64_t P = crd->shape[1]; + const int64_t cs = crd->stride[0], ms = crd->stride[1]; + auto gx = [&](int c, int64_t p) { return ldi(crd, (int64_t)c * cs + p * ms); }; + auto sti = [](const RadTensor* t, int64_t i, int64_t v) { st_int_dt(t->dtype, t->data, i, v); }; + if (idx->dtype != RAD_I32 || inv->dtype != RAD_I32 || pos->dtype != RAD_I32 || + cuw->dtype != RAD_I32) + return RAD_E_DTYPE; + + auto identity = [&]() { + for (int64_t p = 0; p < P; ++p) { + sti(idx, p, p); + sti(inv, p, p); + if (p < M) { + sti(pos, p, gx(1, p) + 1); + sti(pos, P + p, gx(0, p) + 1); + } else { + sti(pos, p, 1); + sti(pos, P + p, 1); + } + } + int64_t last = 0; + const int64_t k = numel(cu) < M + 1 ? numel(cu) : M + 1; + for (int64_t i = 0; i < k; ++i) { + last = ldi(cu, i); + sti(cuw, i, last); + } + for (int64_t i = k; i < M + 1; ++i) sti(cuw, i, last); + }; + if (win <= 0) { + identity(); + return RAD_OK; + } + + std::vector seg((size_t)M), seg_nw, seg_first_win; + std::vector wbase((size_t)M); + int64_t nwin = 0, slot = 0; + const int64_t S = numel(cu) - 1; + for (int64_t s = 0; s < S; ++s) { + const int64_t start = ldi(cu, s); + if (start >= M) break; + int64_t end = ldi(cu, s + 1); + if (end > M) end = M; + const int64_t gh = start < end ? gx(2, start) : 1; + const int64_t gw = start < end ? gx(3, start) : 1; + const int64_t nh = (gh + win - 1) / win, nw = (gw + win - 1) / win; + seg_first_win.push_back(nwin); + seg_nw.push_back(nw); + for (int64_t p = start; p < end; ++p) seg[(size_t)p] = (int64_t)seg_first_win.size() - 1; + for (int64_t wr = 0; wr < nh; ++wr) + for (int64_t wc = 0; wc < nw; ++wc) { + const int64_t rows_in = std::min(win, gh - wr * win); + const int64_t cols_in = std::min(win, gw - wc * win); + sti(cuw, nwin, slot); + wbase[(size_t)nwin] = slot; + ++nwin; + slot += rows_in * cols_in; + } + } + sti(cuw, nwin, slot); + for (int64_t i = nwin + 1; i < M + 1; ++i) sti(cuw, i, slot); + + for (int64_t p = 0; p < P; ++p) { + if (p >= M) { + sti(idx, p, p); + sti(inv, p, p); + sti(pos, p, 1); + sti(pos, P + p, 1); + continue; + } + const int64_t r = gx(0, p), c = gx(1, p), gw = gx(3, p); + int64_t wr = r / win, wc = c / win; + if (wr < 0) wr = 0; + if (wc < 0) wc = 0; + const int64_t cols_in = std::min(win, gw - wc * win); + const int64_t wid = seg_first_win[(size_t)seg[(size_t)p]] + + wr * seg_nw[(size_t)seg[(size_t)p]] + wc; + const int64_t at = wbase[(size_t)wid] + (r - wr * win) * cols_in + (c - wc * win); + sti(idx, at, p); + sti(inv, p, at); + sti(pos, at, c + 1); + sti(pos, P + at, r + 1); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ grid_embed_aa */ /* Adds the table resampled as torch's F.interpolate(bilinear, align_corners=False, * antialias=True) does (SigLIP2's position embedding); matches libref's grid_embed_aa. Per axis: a diff --git a/libavx/avx_registry.cpp b/libavx/avx_registry.cpp index 499cdc92..c6654ae2 100644 --- a/libavx/avx_registry.cpp +++ b/libavx/avx_registry.cpp @@ -144,6 +144,9 @@ static const RadParamSpec pLayernorm[] = { P_INT("M"), P_INT("n"), P_F64("eps" static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT("y") }; static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") }; static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") }; +static const RadParamSpec pWindowOrder[] = { P_INT("M"), P_INT("window") }; +static const RadOperandSpec oWindowOrder[] = { OPD("crd"), OPD_O("cu"), OUT("idx"), OUT("inv"), + OUT("pos"), OUT("cuw") }; static const RadParamSpec pGridEmbedCpe[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype"), P_INTO("n_prefix") }; static const RadOperandSpec oGridEmbedCpe[] = { INOUT("x"), WGT("table"), OPD("coord"), WGT_O("prefix") }; @@ -859,6 +862,8 @@ static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_STR("dtype") }; static const RadOperandSpec oVqEncode[] = { INOUT("x"), WGT("in_w"), WGT("in_b"), WGT("cb"), WGT("out_w"), WGT("out_b"), OUT("codes") }; +static const RadParamSpec pVqEuclidean[] = { P_INT("M"), P_INT("n"), P_INT("bins"), P_STR("dtype") }; +static const RadOperandSpec oVqEuclidean[] = { INOUT("x"), WGT("cb"), OUT("codes") }; static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), P_INTO("rep"), P_STR("dtype") }; static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"), @@ -1013,6 +1018,13 @@ static const RadOpSchema kSchemas[] = { { "layernorm", ARR(pLayernorm), ARR(oLayernorm), "layer norm with gain and optional bias." }, { "grid_embed", ARR(pGridEmbed), ARR(oGridEmbed), "x += a side x side position table resampled bilinearly to the row's grid." }, +{ "grid_embed_pad", ARR(pGridEmbed), ARR(oGridEmbed), + "x += the table resampled half-pixel bilinear (align_corners=False) with zero-padded taps: a " + "tap off the table contributes nothing rather than reading an edge (Muse's)." }, +{ "window_order", ARR(pWindowOrder), ARR(oWindowOrder), + "The window-attention permutation of one pass from its coordinate planes: idx/inv the " + "permutation and its inverse, pos the swapped one-offset rope positions, cuw the cumulative " + "window boundaries; window <= 0 is the identity." }, { "grid_embed_aa", ARR(pGridEmbed), ARR(oGridEmbed), "x += the table resampled as torch's antialiased half-pixel bilinear, SigLIP2's." }, { "lili_cand", ARR(pLiliCand), ARR(oLiliCand), @@ -1457,6 +1469,10 @@ static const RadOpSchema kSchemas[] = { { "vq_encode", ARR(pVqEncode), ARR(oVqEncode), "one residual vector quantiser step: the code of greatest cosine with in_w x + in_b, then " "x -= out_w cb[code] + out_b; libref's arithmetic in another summation order." }, +{ "vq_euclidean", ARR(pVqEuclidean), ARR(oVqEuclidean), + "the nearest Euclidean centroid (the lower index on a tie): its code written and the centroid " + "subtracted from x, libref's arithmetic." }, +{ "elu", ARR(pMnD), ARR(oUnary), "y = x >= 0 ? x : expm1(x), alpha 1." }, { "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix), "a frame's softmax-weighted mix of hidden planes, stored into its lane, bit for bit libref's." }, { "end_status", ARR(pEndStatus), ARR(oEndStatus), @@ -1678,6 +1694,12 @@ SIMPLE("avx_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT L(layernorm)), SIMPLE("avx_grid_embed", "grid_embed", "elem", "bilinear resample of a learned position grid, added in", DT_FLOAT, L(grid_embed)), +SIMPLE("avx_grid_embed_pad", "grid_embed_pad", "elem", + "half-pixel bilinear resample of a position grid, zero-padded taps, added in", DT_FLOAT, + L(grid_embed_pad)), +SIMPLE("avx_window_order", "window_order", "elem", + "the window-attention permutation of one pass, from its coordinates", DT_ANY, + L(window_order)), SIMPLE("avx_grid_embed_aa", "grid_embed_aa", "elem", "antialiased half-pixel bilinear resample of a position grid, added in", DT_FLOAT, L(grid_embed_aa)), @@ -2076,6 +2098,9 @@ SIMPLE("avx_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its resid DT_FLOAT, L(rvq_embed)), SIMPLE("avx_vq_encode", "vq_encode", "elem", "a residual quantiser's step: the nearest code by cosine", DT_FLOAT, L(vq_encode)), +SIMPLE("avx_vq_euclidean", "vq_euclidean", "elem", + "a residual quantiser's step: the nearest centroid by distance", DT_FLOAT, L(vq_euclidean)), +SIMPLE("avx_elu", "elu", "elem", "ELU, alpha 1", DT_FLOAT, L(elu)), SIMPLE("avx_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane", DT_FLOAT, L(frame_mix_store)), SIMPLE("avx_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY, diff --git a/libr3d/CMakeLists.txt b/libr3d/CMakeLists.txt index b7c3fa35..ecbcdeb4 100644 --- a/libr3d/CMakeLists.txt +++ b/libr3d/CMakeLists.txt @@ -78,6 +78,11 @@ set(R3D_UNITS # split-KV) and the prefill leg (a 16-token query tile staged in LDS), over a bf16 or an E4M3 # cache. The walk is shared; the tile is what a workgroup stages once and every wave consumes. "r3d_attn_paged_h128|" + # Absorbed MLA: the per-head projections (absorb/expand through the shared latent weight). + "r3d_mla_project|" + # Dense causal latent attention over a paged [latent | rope] cache: a wave a (row, head), the + # score one wave sum, split history with an f32 partial merge, the optional head gate. + "r3d_mla_attn_paged|" # The sampler's spine: the row's top-R in one scan, and the stages that turn the candidate plane # the top-R produces into one token -- argmax, temp, top-k, the draw, and the four narrowings. "r3d_sample_f32|" @@ -124,10 +129,21 @@ set(R3D_UNITS "r3d_gdn_gated_rmsnorm_h128|" "r3d_gdn_gated_norm_had_quant_i8|" "r3d_gdn_conv_w4_h128|" + # GLM's per-channel KDA recurrence over the paged f32 state cache, with the speculative + # candidate snapshots (the state in registers, no LDS). + "r3d_kda_update|" + # PLE's dilated depthwise convolution (taps `dilation` apart), its silu and the residual add: + # one thread a channel walking a 32-token tile, with the conv window's write-back fused in. + "r3d_ple_conv|" # Mixture of experts: each routing weight times its expert's own scale, in place. "r3d_expert_scale_bf16|" # The router: softmax over the expert logits, the top_k by value, renormalised if `norm`. "r3d_moe_router_topk_bf16|" + # The router's F32 projection: a bf16 activation against an f32 weight, f32 out. + "r3d_gemm_nt_f32|" + # The group-limited sigmoid router (Ling-3.0's noaux_tc): the groups ranked by their two best + # p + bias, selection over the kept groups' experts, one wave a row. + "r3d_router_group_topk|" # The routed slots' stable counting sort (the small form, one workgroup). "r3d_moe_scatter|" # Fold the expert outputs back to the token (the gather, and the inverse-table form). diff --git a/libr3d/r3d_gemm_nt_f32.hip b/libr3d/r3d_gemm_nt_f32.hip new file mode 100644 index 00000000..e7f3523a --- /dev/null +++ b/libr3d/r3d_gemm_nt_f32.hip @@ -0,0 +1,189 @@ +/* r3d_gemm_nt_f32.hip -- gemm_nt_f32: the router's and the index gate's F32 projection. + + x [M][K] bf16, w [N][K] f32 -> y [M][N] f32, y = x @ w^T + + Routing logits and index-head gates stay F32 projections even in a BF16 checkpoint (libref's + ref_gemm_nt_f32), so nothing narrows: the accumulation is f32, the weight is read as f32 and the + store writes f32. N is tiny -- a checkpoint's expert count, a handful of gate columns, at most + 512 -- against a hidden width K, so the op streams the weight plane and is bandwidth-bound, not + compute-bound. There is no matrix tile here and RDNA3's wave matrix could not take it: the wave + matrix is f16 and i8 only (r3d_common.h), an f32 weight has no fragment form. Plain f32 FMAs, + one output element a lane-grid, is the arithmetic and the idiomatic libr3d shape for a GEMV-like + projection. + + ---- the lane map -------------------------------------------------------------------------- + + One wave computes R rows by C columns, so each loaded weight serves R rows and each input C + columns. Every output has the same arithmetic: lane l folds k = l, l+32, ... ascending with fmaf, + then the xor butterfly over 16, 8, 4, 2, 1. libr3d runs that butterfly with wave_sum (DPP16 and + v_permlanex16, r3d_common.h), which is the same exchange in the same order as the __shfl_xor + loop libr4d uses, so a wave's sum is bit-for-bit the sum libr4d's wave forms and the row's host + arithmetic in r4d_selftest --perff32 write out. Every form below is byte-identical to every + other: the wave count, the tile and the steps in flight change how the bytes are fetched, never + how they add. Tail rows and columns read a clamped valid address and are never stored. + + A lane loads U steps of k before their FMAs. At a decode pass's few rows a wave streams its + weight row with no other work to hide the load behind, and one step in flight leaves the router + at a fraction of the card's bandwidth; the deep forms buy that latency back with registers. + + ---- what the launcher checks --------------------------------------------------------------- + + The three operands present, x bf16, w f32 and y f32 (RAD_E_DTYPE), 1 <= N <= 512 and + 1 <= K <= 16384, x, w and y rank 2 with x [M][K], w [N][K] and y [M][N] for x's own M + (RAD_E_SHAPE), every row k-contiguous with a pitch of at least the row's width (the same + RAD_E_SHAPE, as in libr4d), and M within the row-count grid, 1..65535. Nothing is staged in + LDS, so RDNA3's 64 KiB a workgroup is not in play; the check below is written against the cap + so a staged form added later cannot skip it. + + ---- RDNA4 -> RDNA3 ------------------------------------------------------------------------- + + The tiling (R rows, C columns, U steps of k in flight), the four forms and the rule that picks + one are libr4d's (r4d_glm.hip, gemm_nt_f32_tile_kernel), transcribed: the arithmetic is + identical, so the choice between forms is speed only. The block stays four waves of 32 and the + grid x * 4 * C columns by y * R rows. The reduction is wave_sum, not __shfl_xor: on gfx11 a + shuffle is a ds_bpermute plus an LDS wait, and five of them per accumulator dominates a wave's + tail. R3D_WAVES(8) states the occupancy against gfx11's 1024 VGPRs a SIMD at wave32: the + U = 16 form carries 2 * 16 * 2 = 64 registers of loads in flight plus R * C accumulators, inside + the 128 eight waves a SIMD allows. The form rule's thresholds are gfx1201's measurements as + libr4d quotes them; they are kept as the starting point, and a tune on a gfx11 part is free to + move them, because every form computes the same bytes. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include + +namespace { + +constexpr uint32_t kThreads = 128; // four waves a block, as in libr4d +constexpr uint32_t kWaves = kThreads / kWave; +constexpr uint32_t kWavesPerSimd = 8; // 1024 VGPRs a SIMD / 8 = 128 a wave + +/* The geometry the shim admits, from the row's constraint table. */ +constexpr long long kNMax = 512, kKMax = 16384, kMMax = 65535; + +/* Dynamic LDS a launch asks for. Every form keeps its tile in registers, so the launch's shared + * byte count is 0 and the cap below is the exemplar's, for the launcher to enforce. */ +constexpr size_t kStageBytes = 0; + +template +__global__ void __launch_bounds__(kThreads) R3D_WAVES(kWavesPerSimd) + gemm_nt_f32_tile_kernel(const uint16_t* x, const float* w, float* y, long xp, long wp, long yp, + int m, int n, int k) { + const int lane = (int)(threadIdx.x & (kWave - 1)), wave = (int)(threadIdx.x / kWave); + const int c0 = (int)(blockIdx.x * kWaves + (unsigned)wave) * C, r0 = (int)blockIdx.y * R; + if (c0 >= n) return; + const uint16_t* xr[R]; + const float* wc[C]; +#pragma unroll + for (int q = 0; q < R; ++q) xr[q] = x + (long)(r0 + q < m ? r0 + q : m - 1) * xp; +#pragma unroll + for (int c = 0; c < C; ++c) wc[c] = w + (long)(c0 + c < n ? c0 + c : n - 1) * wp; + float sum[R][C]; +#pragma unroll + for (int q = 0; q < R; ++q) +#pragma unroll + for (int c = 0; c < C; ++c) sum[q][c] = 0; + int j = lane; + for (; j + 32 * (U - 1) < k; j += 32 * U) { + float weight[U][C]; + uint32_t in[U][R]; +#pragma unroll + for (int u = 0; u < U; ++u) +#pragma unroll + for (int c = 0; c < C; ++c) weight[u][c] = ldg_f32(wc[c] + j + 32 * u); +#pragma unroll + for (int u = 0; u < U; ++u) +#pragma unroll + for (int q = 0; q < R; ++q) in[u][q] = ldg_u16(xr[q] + j + 32 * u); +#pragma unroll + for (int u = 0; u < U; ++u) +#pragma unroll + for (int q = 0; q < R; ++q) { + const float v = bf16_to_f32((uint16_t)in[u][q]); +#pragma unroll + for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, weight[u][c], sum[q][c]); + } + } + for (; j < k; j += 32) { +#pragma unroll + for (int q = 0; q < R; ++q) { + const float v = bf16_to_f32((uint16_t)ldg_u16(xr[q] + j)); +#pragma unroll + for (int c = 0; c < C; ++c) sum[q][c] = fmaf(v, ldg_f32(wc[c] + j), sum[q][c]); + } + } +#pragma unroll + for (int q = 0; q < R; ++q) +#pragma unroll + for (int c = 0; c < C; ++c) sum[q][c] = wave_sum(sum[q][c]); + if (lane) return; +#pragma unroll + for (int q = 0; q < R; ++q) + if (r0 + q < m) +#pragma unroll + for (int c = 0; c < C; ++c) + if (c0 + c < n) y[(long)(r0 + q) * yp + c0 + c] = sum[q][c]; +} + +/* One tile form at the grid it owns: x * 4 * C columns, y * R rows, no LDS. */ +template +int gemm_f32_tile(RadStream s, const void* x, const void* w, void* y, long xp, long wp, long yp, + long m, long n, long k) { + const dim3 grid((unsigned)((n + (long)kWaves * C - 1) / ((long)kWaves * C)), + (unsigned)((m + R - 1) / R)), blk(kThreads); + R3D_KLAUNCH(R3D_KNAME((gemm_nt_f32_tile_kernel)), grid, blk, (hipStream_t)s, + (const uint16_t*)x, (const float*)w, (float*)y, xp, wp, yp, (int)m, (int)n, (int)k); + return hipGetLastError() == hipSuccess ? RAD_OK : RAD_E_DEVICE; +} + +/* The tile form, rows x columns a wave and steps of k in flight, by M; all forms are + * byte-identical, so the choice is speed only. Measured on gfx1201 (r4d_selftest --perff32, cold) + * at N 4/32/36/288, K 4096: 16x4 gains 3-5 % at N 288/32 above 64 rows but loses 16 % at N 36; + * 8x4 holds at every width. Below 64 rows the steps of k in flight decide: 2x2 with 16 steps is 2 + * to 2.5 times as fast as one step at N 288 up to 16 rows, and about 3 times at N 32 at every + * count below 64; at N 288 from 17 rows 8x1 with 8 steps is faster. A projection of a few columns + * has too few waves for wide tiles at any M. The thresholds are libr4d's, kept as the starting + * point for gfx11: the forms compute the same bytes, so a tune here moves them, not the kernel. */ +int gemm_f32_body(const RadArgs* a, RadStream s) { + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + const RadTensor *xt = &a->t[0], *wt = &a->t[1], *yt = &a->t[2]; + const long long n = r3d_geti_or(a, "N", 0), k = r3d_geti_or(a, "K", 0); + if (xt->dtype != RAD_BF16 || wt->dtype != RAD_F32 || yt->dtype != RAD_F32) + return R3D_NO(RAD_E_DTYPE); + if (!r3d_p(xt) || !r3d_p(wt) || !r3d_wp(yt)) return R3D_NO(RAD_E_INVAL); + if (n < 1 || n > kNMax || k < 1 || k > kKMax || xt->rank != 2 || wt->rank != 2 || + yt->rank != 2 || xt->shape[0] < 1 || xt->shape[0] > kMMax || xt->shape[1] != k || + wt->shape[0] != n || wt->shape[1] != k || yt->shape[0] != xt->shape[0] || + yt->shape[1] != n || xt->stride[1] != 1 || wt->stride[1] != 1 || yt->stride[1] != 1 || + xt->stride[0] < k || wt->stride[0] < k || yt->stride[0] < n) + return R3D_NO(RAD_E_SHAPE); + /* Nothing is staged: a wave's whole tile is its register grid, so RDNA3's 64 KiB a workgroup + * is not in play. The cap is asserted where the exemplar's launcher checks it, so a staged + * form added to this unit cannot skip it. */ + static_assert(kStageBytes <= 60 * 1024, "a workgroup's stage must fit RDNA3's 64 KiB of LDS"); + + const long m = (long)xt->shape[0]; // the step's rows, not the band's bound + const void* px = r3d_p(xt); + const void* pw = r3d_p(wt); + void* py = r3d_wp(yt); + const long xp = (long)xt->stride[0], wp = (long)wt->stride[0], yp = (long)yt->stride[0]; + if (n <= 8) return gemm_f32_tile<4, 1>(s, px, pw, py, xp, wp, yp, m, n, k); + if (m <= 16 || (m < 64 && n < 128)) return gemm_f32_tile<2, 2, 16>(s, px, pw, py, xp, wp, yp, m, n, k); + if (m < 64) return gemm_f32_tile<8, 1, 8>(s, px, pw, py, xp, wp, yp, m, n, k); + return gemm_f32_tile<8, 4>(s, px, pw, py, xp, wp, yp, m, n, k); +} + +} // namespace + +/* ============================================================== the plugin ABI entry point + * + * gemm_nt_f32's operand list is [a, b, y] and its parameters M, N, K, dtype (libref's pGemm / + * oGemm, libr4d's pGemmNt / oGemmNt). The row count comes from the operand: the band's `M` is an + * upper bound, and `N` and `K` are read as the shim's extents, exactly as libr4d's shim reads them. */ +extern "C" int r3d_rad_gemm_nt_f32(const RadArgs* a, RadStream s) +{ + return gemm_f32_body(a, s); +} diff --git a/libr3d/r3d_kda_update.hip b/libr3d/r3d_kda_update.hip new file mode 100644 index 00000000..e435d874 --- /dev/null +++ b/libr3d/r3d_kda_update.hip @@ -0,0 +1,441 @@ +/* r3d_kda_update.hip -- kda_update: GLM's per-channel KDA recurrence over a paged f32 state cache, + * including the speculative candidate snapshots. + * + * The convolution's outputs come straight in (q, k, v, a, b); the gates are decoded here and the + * delta-rule step runs per token against one [128, 128] f32 state per head: + * + * decay = exp(lower_bound / (1 + e^-(A_log[head] * (a + dt_bias)))) beta = sigmoid(b) + * q, k l2-normalised (q's root scaled by `scale`, both by `l2_eps`) + * S *= decay u = beta * (v - S k) S += u k^T o = S q + * + * `mode` "prefill" runs the same recurrence over a sequence's tokens and commits only its final + * state; "verify" writes a state slot per candidate token, since which candidate survives is not + * known while this runs. `state_form` "anchor" is the rollback pair: the state is read at the + * anchor's slot, every candidate's factors are recorded into a scratch slot, and a second launch + * replays the accepted prefix of that record into the committed slot. The replay is a separate + * dispatch because every old factor read must finish before the next window overwrites them. + * + * q, k, a, o [tokens, heads, 128] bf16, accepted as [tokens, heads*128] too + * b [tokens, heads] bf16 (width 1, the same two forms) + * A_log [heads] f32, dt_bias [heads*128] f32 + * state [slots, heads, 128, 128] f32 in/out, at the cache's own strides (a mamba page is + * padded to the attention page size, so a shape-derived stride reads every slot but + * the first at the wrong offset) + * state_idx [seqs, width] i32, width >= 2 for `anchor` (column width/2 is the scratch slot) + * cu [seqs+1] i32, absolute token offsets + * num_accepted, has_init [seqs] i32, optional + * + * The launcher checks what libr4d's checks: 13 operands, heads 1..65535 with head_k = head_v = + * 128, the five bf16 inputs in one of the two headed forms at the token count, the state a rank-4 + * f32 cache of at least one slot whose strides cover it, cu rank-1 i32 of 2..65536 entries, + * state_idx rank-2 i32 with a row per sequence, A_log and dt_bias rank-1 f32 of at least heads and + * heads*128, the two optional i32 vectors one entry per sequence, mode in {prefill, verify} and + * state_form in {per_candidate, anchor} (anything else RAD_E_INVAL), anchor with a two-column + * state_idx, lower_bound finite and negative, l2_eps finite and positive, scale finite. + * + * RDNA4 -> RDNA3 (from libr4d/r4d_kda.hip, geometry unchanged). gfx1102 has the same wave32 and + * the same 64 KiB LDS as gfx1201, and this kernel tiles nothing in LDS: one wave owns four value + * rows and keeps each row's 128 state elements in four registers a lane, so a workgroup stages + * nothing and the 60 KiB bound the launcher states is vacuous by construction (a state tile moved + * into LDS is 64 KiB, one head's whole state, and would not fit a workgroup's budget). The + * reductions are libr3d's wave_sum, the same XOR butterflies in the same order as r4d_wave_sum, so + * the l2 sums, the predictions and the outputs are bit-identical; a bf16 operand widens through + * bf16_to_f32, the same shift into the high half as libr4d's bf16w_lo. Nothing here is fp8: the + * state, the recorded factors and the decay are f32, and the recurrence is bandwidth-bound, so the + * plain vectorised f32 ALU is the correct tool -- no WMMA (gfx11's is f16/i8 only) and no fp8 + * matrix instruction, which gfx11 lacks. libr4d's typed R4D_EMIT dispatch becomes R3D_KLAUNCH plus + * hipGetLastError, returning RAD_E_DEVICE for a launch the driver refused, as R4D_EMIT does. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" +#include +#include +#include + +namespace { + +/* Four waves a workgroup, as in libr4d: the rows kernel grids (128 / (waves * R), heads, + * sequences) and the replay kernel, one value row a wave, (128 / waves, heads, sequences). */ +constexpr uint32_t kThreads = 128; +constexpr uint32_t kWaves = kThreads / kWave; +constexpr int kRows = 4; /* value rows a wave owns: 32 % 4 == 0 */ +constexpr int kDim = 128; /* head_k and head_v, the row's compiled-in law */ + +/* The workgroup's dynamic stage. A wave keeps its state in registers, so there is none; the bound + * is stated because RDNA3 gives a workgroup 64 KiB of LDS and a future tile of the state (one + * head is 128*128*4 = 64 KiB) has to be checked against it here, not at the launch. */ +constexpr size_t kLdsBytes = 0; +static_assert(kLdsBytes <= 60 * 1024, "a workgroup's stage must fit RDNA3's 64 KiB LDS"); + +struct KdaMeta { + int row[5], head[5]; + long os0, os1, ss0, ss1, ss2; + long is0, is1, cs0, as0, hs0; + int tokens, slots, width, verify, anchor; + float lower, eps, scale; +}; +struct KdaJob : KdaMeta { + const uint16_t* input[5]; + const float *alog, *bias; + float* state; + uint16_t* out; + const int *idx, *cu, *accepted, *init; +}; + +/* A bf16 as ldg_u16 leaves it, widened: the code is the register's low half, so widening is a + * shift (libr4d's bf16w_lo). */ +__device__ __forceinline__ float bf_lo(uint32_t w) { return bf16_to_f32((uint16_t)w); } + +__device__ long factor_offset(long base, int logical, long pitch) { + return base + (logical / 128) * pitch + (logical % 128); +} +/* Separate dispatch: all old factor reads finish before the next window overwrites them. */ +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void kda_replay_kernel( + float* state, const int* idx, const int* cu, const int* accepted, const int* init, KdaMeta m) { + const int lane = threadIdx.x & (kWave - 1), e = blockIdx.x * kWaves + (threadIdx.x / kWave), + head = blockIdx.y, seq = blockIdx.z; + /* A sequence without tokens this step leaves its slots as they are. */ + if (cu[(long)seq * m.cs0] == cu[(long)(seq + 1) * m.cs0]) return; + const int anchor = idx[(long)seq * m.is0], + scratch = idx[(long)seq * m.is0 + (m.width / 2) * m.is1]; + if (anchor < 0 || anchor >= m.slots || scratch < 0 || scratch >= m.slots || anchor == scratch) + return; + const long fb = (long)scratch * m.ss0 + (long)head * m.ss1; + const long sb = (long)anchor * m.ss0 + (long)head * m.ss1 + (long)e * m.ss2; + if (init && !init[(long)seq * m.hs0]) { +#pragma unroll + for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = 0; + return; + } + const float count = state[fb]; + const int na = accepted ? accepted[(long)seq * m.as0] : 1; + if (!(count >= 0 && count <= 32) || count != floorf(count) || na < 1 || na > 32 || + (count > 0 && na > count)) + return; + float s[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) s[d] = state[sb + lane + d * 32]; + for (int t = 0; t < (count > 0 ? na : 0); ++t) { + const int f = 1 + t * 385; + float k[4], prediction = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int c = lane + d * 32; + k[d] = state[factor_offset(fb, f + c, m.ss2)]; + s[d] *= state[factor_offset(fb, f + 256 + c, m.ss2)]; + prediction += s[d] * k[d]; + } + const float delta = + state[factor_offset(fb, f + 384, m.ss2)] * + (state[factor_offset(fb, f + 128 + e, m.ss2)] - wave_sum(prediction)); +#pragma unroll + for (int d = 0; d < 4; ++d) s[d] += delta * k[d]; + } +#pragma unroll + for (int d = 0; d < 4; ++d) state[sb + lane + d * 32] = s[d]; +} +/* R value rows a wave: the loads, norms and decay exponentials, which do not depend on the state, + * are formed once for R rows, and the rows' reductions interleave. The next token's operands are + * loaded while this one is reduced. */ +template +__global__ __launch_bounds__(kThreads) R3D_WAVES(kWaves) void kda_rows_kernel( + const uint16_t* q, const uint16_t* k, const uint16_t* v, const uint16_t* g, + const uint16_t* beta, const float* alog, const float* bias, float* state_ptr, uint16_t* out, + const int* idx, const int* cu, const int* accepted_ptr, const int* init, KdaMeta meta) { + static_assert(32 % R == 0, "the 128 value rows split evenly over the waves"); + KdaJob j{}; + static_cast(j) = meta; + j.input[0] = q; + j.input[1] = k; + j.input[2] = v; + j.input[3] = g; + j.input[4] = beta; + j.alog = alog; + j.bias = bias; + j.state = state_ptr; + j.out = out; + j.idx = idx; + j.cu = cu; + j.accepted = accepted_ptr; + j.init = init; + const int lane = threadIdx.x & (kWave - 1), + e0 = (blockIdx.x * kWaves + (threadIdx.x / kWave)) * R; + const int head = blockIdx.y, seq = blockIdx.z; + const int begin = j.cu[(long)seq * j.cs0], end = j.cu[(long)(seq + 1) * j.cs0]; + const int accepted = j.accepted ? j.accepted[(long)seq * j.as0] : 1; + if (begin < 0 || end <= begin || end > j.tokens || accepted < 1 || + accepted > (j.anchor ? 32 : j.width) || + (j.verify && end - begin > (j.anchor ? 32 : j.width))) + return; + const int read = j.idx[(long)seq * j.is0 + (j.verify && !j.anchor ? accepted - 1 : 0) * j.is1]; + if (read >= j.slots) return; + uint16_t* const out_row = j.out + (long)head * j.os1 + e0; + if (read < 0) { + if (lane < R) + for (int t = begin; t < end; ++t) out_row[(long)t * j.os0 + lane] = 0; + return; + } + const bool initialized = !j.init || j.init[(long)seq * j.hs0] != 0; + const int scratch = j.anchor ? j.idx[(long)seq * j.is0 + (j.width / 2) * j.is1] : 0; + if (j.anchor && (scratch < 0 || scratch >= j.slots || scratch == read)) return; + const long fb = (long)scratch * j.ss0 + (long)head * j.ss1; + const long initial = (long)read * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2; + float state[R][4]; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int d = 0; d < 4; ++d) + state[r][d] = initialized ? j.state[initial + r * j.ss2 + lane + 32 * d] : 0; + const float gain = expf(j.alog[head]); + float shift[4]; +#pragma unroll + for (int d = 0; d < 4; ++d) shift[d] = j.bias[head * 128 + lane + 32 * d]; + const uint16_t* const qb = j.input[0] + (long)head * j.head[0] + lane; + const uint16_t* const kb = j.input[1] + (long)head * j.head[1] + lane; + const uint16_t* const vb = j.input[2] + (long)head * j.head[2] + e0; + const uint16_t* const gb = j.input[3] + (long)head * j.head[3] + lane; + const uint16_t* const bb = j.input[4] + (long)head * j.head[4]; + struct Token { + uint32_t q[4], k[4], g[4], beta, value[R]; + }; + auto fetch = [&](int t, Token& o) { +#pragma unroll + for (int d = 0; d < 4; ++d) { + o.q[d] = ldg_u16(qb + (long)t * j.row[0] + 32 * d); + o.k[d] = ldg_u16(kb + (long)t * j.row[1] + 32 * d); + o.g[d] = ldg_u16(gb + (long)t * j.row[3] + 32 * d); + } + o.beta = ldg_u16(bb + (long)t * j.row[4]); +#pragma unroll + for (int r = 0; r < R; ++r) o.value[r] = ldg_u16(vb + (long)t * j.row[2] + r); + }; + Token cur; + if (begin < end) fetch(begin, cur); + for (int t = begin; t < end; ++t) { + Token next; + /* The last token loads itself again rather than a row past `end`. */ + fetch(t + 1 < end ? t + 1 : t, next); + float qv[4], kv[4], decay[4], sq = 0, sk = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + qv[d] = bf_lo(cur.q[d]); + kv[d] = bf_lo(cur.k[d]); + sq += qv[d] * qv[d]; + sk += kv[d] * kv[d]; + const float raw = bf_lo(cur.g[d]); + decay[d] = expf(j.lower / (1.0f + expf(-gain * (raw + shift[d])))); + } + const float qi = j.scale * rsqrtf(wave_sum(sq) + j.eps), + ki = rsqrtf(wave_sum(sk) + j.eps); + const float b = 1.0f / (1.0f + expf(-bf_lo(cur.beta))); + float predicted[R]; +#pragma unroll + for (int r = 0; r < R; ++r) predicted[r] = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + qv[d] *= qi; + kv[d] *= ki; +#pragma unroll + for (int r = 0; r < R; ++r) { + state[r][d] *= decay[d]; + predicted[r] += state[r][d] * kv[d]; + } + } + float value[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + predicted[r] = wave_sum(predicted[r]); + value[r] = bf_lo(cur.value[r]); + } + if (j.anchor && j.verify) { + const int f = 1 + (t - begin) * 385; + if (e0 == 0) { +#pragma unroll + for (int d = 0; d < 4; ++d) { + const int c = lane + 32 * d; + j.state[factor_offset(fb, f + c, j.ss2)] = kv[d]; + j.state[factor_offset(fb, f + 256 + c, j.ss2)] = decay[d]; + } + if (!lane) j.state[factor_offset(fb, f + 384, j.ss2)] = b; + } + if (!lane) { +#pragma unroll + for (int r = 0; r < R; ++r) + j.state[factor_offset(fb, f + 128 + e0 + r, j.ss2)] = value[r]; + } + } + float result[R]; +#pragma unroll + for (int r = 0; r < R; ++r) { + const float delta = b * (value[r] - predicted[r]); + result[r] = 0; +#pragma unroll + for (int d = 0; d < 4; ++d) { + state[r][d] += delta * kv[d]; + result[r] += state[r][d] * qv[d]; + } + } + float mine = 0; +#pragma unroll + for (int r = 0; r < R; ++r) { + result[r] = wave_sum(result[r]); + if (lane == r) mine = result[r]; + } + if (lane < R) out_row[(long)t * j.os0 + lane] = f32_to_bf16(mine); + if ((!j.anchor && j.verify) || (!j.verify && t + 1 == end)) { + const int write = j.idx[(long)seq * j.is0 + (j.verify ? t - begin : 0) * j.is1]; + if (write >= 0 && write < j.slots) { + const long target = (long)write * j.ss0 + (long)head * j.ss1 + (long)e0 * j.ss2; +#pragma unroll + for (int r = 0; r < R; ++r) +#pragma unroll + for (int d = 0; d < 4; ++d) + j.state[target + r * j.ss2 + lane + 32 * d] = state[r][d]; + } + } + cur = next; + } + if (j.anchor && e0 == 0 && !lane) j.state[fb] = j.verify ? (float)(end - begin) : 0.0f; +} + +/* A bf16 operand shaped [tokens, heads, dim] or the fused [tokens, heads*dim], read at its own row + * and head pitches. libr4d's `headed`, with an unbound descriptor (null data) refused the same way + * a missing operand is: as a shape the shim does not accept. */ +template +bool headed(const RadTensor* t, long tokens, long heads, long dim, Pitch* row, Pitch* head) { + if (!t || !t->data || t->dtype != RAD_BF16 || t->shape[0] != tokens || + t->stride[0] > INT_MAX || (t->rank == 3 && t->stride[1] > INT_MAX)) + return false; + if (t->rank == 3 && t->shape[1] == heads && t->shape[2] == dim && t->stride[2] == 1 && + t->stride[1] >= dim && t->stride[0] >= heads * t->stride[1]) { + *row = t->stride[0]; + *head = t->stride[1]; + return true; + } + if (t->rank == 2 && t->shape[1] == heads * dim && t->stride[1] == 1 && + t->stride[0] >= heads * dim) { + *row = t->stride[0]; + *head = dim; + return true; + } + return false; +} +bool vector(const RadTensor* t, uint32_t dt, long n) { + return t && t->data && t->dtype == dt && t->rank == 1 && t->shape[0] >= n && t->stride[0] == 1; +} +int body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 13) return R3D_NO(RAD_E_INVAL); + const long H = r3d_geti_or(a, "heads", 0); + if (H < 1 || H > 65535 || r3d_geti_or(a, "head_k", 0) != kDim || + r3d_geti_or(a, "head_v", 0) != kDim) + return R3D_NO(RAD_E_SHAPE); + KdaJob j{}; + const RadTensor *state = r3d_opt(a, 7), *idx = r3d_opt(a, 8), *cu = r3d_opt(a, 9); + const long tokens = r3d_dim(r3d_opt(a, 0), 0); + /* The three null guards below stand where libr4d tests `!state.data`, `!cu.data` and + * `!idx.data`: an unbound operand is refused as the shape it is not, the same code. */ + if (tokens < 1 || tokens > INT_MAX || !state || state->rank != 4 || state->dtype != RAD_F32 || + !state->data || state->shape[0] < 1 || state->shape[0] > INT_MAX || + state->shape[1] != H || state->shape[2] != kDim || state->shape[3] != kDim || + state->stride[3] != 1 || state->stride[2] < kDim || + state->stride[1] < kDim * state->stride[2] || state->stride[0] < H * state->stride[1] || + !cu || cu->rank != 1 || cu->dtype != RAD_I32 || !cu->data || cu->shape[0] < 2 || + cu->shape[0] > 65536 || cu->stride[0] < 1 || !idx || idx->rank != 2 || + idx->dtype != RAD_I32 || + !idx->data || idx->shape[0] < cu->shape[0] - 1 || idx->shape[1] < 1 || + idx->shape[1] > INT_MAX || idx->stride[1] < 1 || + idx->stride[0] < idx->shape[1] * idx->stride[1]) + return R3D_NO(RAD_E_SHAPE); + for (int i = 0; i < 5; ++i) { + if (!headed(r3d_opt(a, i), tokens, H, i == 4 ? 1 : kDim, &j.row[i], &j.head[i])) + return R3D_NO(RAD_E_SHAPE); + j.input[i] = (const uint16_t*)r3d_p(r3d_opt(a, i)); + } + const RadTensor* o = r3d_opt(a, 12); + if (!headed(o, tokens, H, kDim, &j.os0, &j.os1) || !vector(r3d_opt(a, 5), RAD_F32, H) || + !vector(r3d_opt(a, 6), RAD_F32, H * kDim)) + return R3D_NO(RAD_E_SHAPE); + const RadTensor *accepted = r3d_opt(a, 10), *init = r3d_opt(a, 11); + if ((accepted && !vector(accepted, RAD_I32, cu->shape[0] - 1)) || + (init && !vector(init, RAD_I32, cu->shape[0] - 1))) + return R3D_NO(RAD_E_SHAPE); + const char* mode = r3d_gets(a, "mode"); + if (!mode || (std::strcmp(mode, "verify") && std::strcmp(mode, "prefill"))) + return R3D_NO(RAD_E_INVAL); + j.verify = !std::strcmp(mode, "verify"); + const char* form = r3d_gets(a, "state_form"); + j.anchor = form && !std::strcmp(form, "anchor"); + if (form && !j.anchor && std::strcmp(form, "per_candidate")) return R3D_NO(RAD_E_INVAL); + if (j.anchor && idx->shape[1] < 2) return R3D_NO(RAD_E_SHAPE); + j.lower = (float)r3d_getf(a, "lower_bound", 0); + j.eps = (float)r3d_getf(a, "l2_eps", 0); + j.scale = (float)r3d_getf(a, "scale", 1); + if (!std::isfinite(j.lower) || j.lower >= 0 || !std::isfinite(j.eps) || j.eps <= 0 || + !std::isfinite(j.scale)) + return R3D_NO(RAD_E_SHAPE); + j.tokens = (int)tokens; + j.slots = (int)state->shape[0]; + j.width = (int)idx->shape[1]; + j.alog = (const float*)r3d_p(r3d_opt(a, 5)); + j.bias = (const float*)r3d_p(r3d_opt(a, 6)); + j.state = (float*)r3d_wp(state); + j.out = (uint16_t*)r3d_wp(o); + j.ss0 = state->stride[0]; + j.ss1 = state->stride[1]; + j.ss2 = state->stride[2]; + j.idx = (const int*)idx->data; + j.is0 = idx->stride[0]; + j.is1 = idx->stride[1]; + j.cu = (const int*)cu->data; + j.cs0 = cu->stride[0]; + if (accepted) { + j.accepted = (const int*)accepted->data; + j.as0 = accepted->stride[0]; + } + if (init) { + j.init = (const int*)init->data; + j.hs0 = init->stride[0]; + } + const unsigned seqs = (unsigned)(cu->shape[0] - 1); + const hipStream_t st = (hipStream_t)stream; + if (j.anchor && j.verify) { + /* One value row a wave, a workgroup's four waves covering four rows: 128 / 4 = 32 + * workgroups, as libr4d grids the replay. Clear the error flag before the chevron and read + * it after: hipGetLastError reports the first error since it was last cleared, so an + * uncleared read blames this launch for an earlier one. */ + (void)hipGetLastError(); + R3D_KLAUNCH(kda_replay_kernel, dim3(kDim / kWaves, (unsigned)H, seqs), dim3(kThreads), st, + j.state, j.idx, j.cu, j.accepted, j.init, static_cast(j)); + const hipError_t re = hipGetLastError(); + if (re != hipSuccess) { + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] kda_update: %s on the replay: grid (%u, %u, %u)\n", + hipGetErrorName(re), (unsigned)(kDim / kWaves), (unsigned)H, seqs); + return R3D_NO(RAD_E_DEVICE); + } + } + /* The 128 value rows split over the workgroup's waves, R rows a wave: 128 / (4 waves * 4 rows) + * = 8 workgroups a (head, sequence), as libr4d grids it. */ + (void)hipGetLastError(); + R3D_KLAUNCH(R3D_KNAME((kda_rows_kernel)), + dim3(kDim / (kWaves * kRows), (unsigned)H, seqs), dim3(kThreads), st, j.input[0], + j.input[1], j.input[2], j.input[3], j.input[4], j.alog, j.bias, j.state, j.out, + j.idx, j.cu, j.accepted, j.init, static_cast(j)); + const hipError_t ke = hipGetLastError(); + if (ke != hipSuccess) { + if (r3d_trace_on()) + std::fprintf(stderr, "[r3d] kda_update: %s on the rows launch: grid (%u, %u, %u) %d\n", + hipGetErrorName(ke), kDim / (kWaves * kRows), (unsigned)H, seqs, kRows); + return R3D_NO(RAD_E_DEVICE); + } + return RAD_OK; +} +} // namespace + +extern "C" { + +int r3d_rad_kda_update(const RadArgs* a, RadStream s) { return body(a, s); } + +} // extern "C" diff --git a/libr3d/r3d_mla_attn_paged.hip b/libr3d/r3d_mla_attn_paged.hip new file mode 100644 index 00000000..b60fcb8a --- /dev/null +++ b/libr3d/r3d_mla_attn_paged.hip @@ -0,0 +1,278 @@ +/* r3d_mla_attn_paged.hip -- mla_attn_paged: dense causal latent attention over a paged cache + * whose token row is the normed latent followed by the rotated key part (Ling-3.0's MLA). + * + * out[r, head, :] = softmax_j( scale * ( q[r, head, :] . kv[j, :512] + * + q_rope[r, head, :] . kv[j, 512:576] ) ) . kv[j, :512] + * + * over one page table per sequence, in libref's reading: sequence s owns query rows + * [cu[s], cu[s+1]), its context after this step is seqused[s], and row i of it sits at position + * seqused[s] - qlen + i and sees keys 0..position. A negative page (an unmapped block) hides its + * tokens, as attn_paged reads the table. The value is the latent; the rotary part scores only. + * With `gate`, out = bf16( bf16(out) * bf16(sigmoid(gate[r, head])) ). + * + * A wave is a (query row, head). Lane l holds latent columns 16l..16l+15 and rotary columns + * 2l, 2l+1, so a score is one wave sum: the lane's latent pair of the 512-wide dot plus its rope + * pair, wave_sum, then scale. The running softmax is online (a rescaling max/den update per + * token), exactly the libr4d kernel's: a row's bytes do not depend on the batch it is in. + * + * A short batch splits its history over the z axis, one (value[512], max, den) f32 partial per + * (row, head, split) in the scratch arena, and merge_paged joins the partials against the global + * maximum before the single narrowing. The split count is a function of the head count alone + * (paged_splits), not of the launch's rows, for the same reason the libr4d kernel states it: a + * speculative verify scores the k + 1 rows of a sequence in one launch, and greedy output equals + * the run without speculation only if each row gives the single-row decode at its position bit + * for bit. + * + * Operands: q [M, heads, 512] bf16, q_rope [M, heads, 64] bf16, kv [pages, 1, bs, >= 576] bf16, + * block_table [seqs, blocks] i32, seqused [seqs] i32, cu_seqlens [seqs + 1] i32, gate [M, >= + * heads] bf16 (optional), out [M, heads, 512] bf16. A 2-D [M, heads*width] plane is viewed as + * 3-D, as libr4d. + * + * The launcher (r3d_rad_mla_attn_paged) checks: the dtypes above; latent_dim 512, rope_dim 64; + * heads 1..64; block_size 1..256; scale finite and positive; M 1..65535; the shapes, strides and + * pitches as libr4d's (last axes contiguous, row pitches at least the dense ones, the table at + * least as wide as seqused's rows, cu [seqs + 1] contiguous); RAD_E_INVAL, RAD_E_DTYPE, + * RAD_E_SHAPE. A scratch arena too small for the split lowers the split, down to 1, which needs + * none -- the band is never refused for lack of scratch. + * + * RDNA4 -> RDNA3: the kernel is a bandwidth-bound GEMV shape, so it runs plain vectorised f32 + * with the library's bf16 codecs -- no WMMA (RDNA3's wave matrix is f16/i8 only) and no fp8. The + * wave sum is wave_sum, the same butterfly order as libr4d's, so a row's bytes are + * bit-identical to the libr4d kernel. The aligned 16-byte latent loads keep their alignment + * guard: a misaligned 16-byte load returns garbage on this hardware, and the scalar path takes + * the misaligned row. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include +#include +#include +#include + +namespace { + +constexpr int D = 512; /* the latent width */ +constexpr int RD = 64; /* the rotary width */ +constexpr int PART = D + 2; /* a partial: value[512], max, den */ + +/* The rows the scratch serves at full split: a verify at depth 31. */ +constexpr long kPagedRows = 32; + +struct PagedMeta { + long qr, qh, rr, rh, kp, kt, bp, bc, orr, oh, gr; + int rows, heads, seqs, blocks, bs, pages, splits; + float scale; +}; + +int paged_splits(long heads) { return (int)std::min(16l, (256 + heads - 1) / heads); } + +int64_t paged_scratch_bytes(long rows, long heads) { + return std::min(rows, kPagedRows) * heads * paged_splits(heads) * PART * 4; +} + +/* Which sequence owns dense query row `r`, walking the descriptor once per wave. */ +__device__ __forceinline__ int paged_seq(const int* cu, int seqs, int r) { + int s = 0; + while (s + 1 < seqs && cu[s + 1] <= r) ++s; + return s; +} + +/* Sixteen bf16 elements as f32: two 16-byte loads when the row is aligned, element-wise when it + * is not (a misaligned 16-byte load returns garbage on this hardware). The 16-byte staging goes + * through r3d_u32x4, the ext_vector_type the library keeps in registers (r3d_common.h). */ +__device__ __forceinline__ void load_latent(const uint16_t* p, float (&v)[16]) { + if (!((uintptr_t)p & 15)) { + const r3d_u32x4 a = + *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)p; + const r3d_u32x4 b = + *(const __attribute__((address_space(1))) r3d_u32x4*)(const void*)(p + 8); + const uint32_t packed[8] = { a.x, a.y, a.z, a.w, b.x, b.y, b.z, b.w }; +#pragma unroll + for (int j = 0; j < 16; ++j) + v[j] = bf16_to_f32((uint16_t)(packed[j / 2] >> (16 * (j & 1)))); + } else { +#pragma unroll + for (int j = 0; j < 16; ++j) v[j] = bf16_to_f32((uint16_t)ldg_u16(p + j)); + } +} + +/* The narrowed output, with the optional head gate: bf16(bf16(out) * bf16(sigmoid(logit))). */ +__device__ __forceinline__ void paged_store(uint16_t* out, const uint16_t* gate, const PagedMeta& m, + int r, int head, int lane, const float (&value)[16], + float den) { + float g = 1.0f; + if (gate) + g = bf16_to_f32(f32_to_bf16(1.0f / (1.0f + expf(-bf16_to_f32((uint16_t)ldg_u16( + gate + (long)r * m.gr + head)))))); +#pragma unroll + for (int j = 0; j < 16; ++j) { + float v = den > 0 ? value[j] / den : 0; + if (gate) v = bf16_to_f32(f32_to_bf16(v)) * g; + out[(long)r * m.orr + (long)head * m.oh + lane * 16 + j] = f32_to_bf16(v); + } +} + +__global__ __launch_bounds__(128) R3D_WAVES(4) +void attend_paged(const uint16_t* __restrict__ q, const uint16_t* __restrict__ qrot, + const uint16_t* __restrict__ kv, const int* __restrict__ bt, + const int* __restrict__ used, const int* __restrict__ cu, + const uint16_t* __restrict__ gate, uint16_t* __restrict__ out, + float* __restrict__ scratch, PagedMeta m) { + const int lane = (int)threadIdx.x & 31, head = (int)blockIdx.y * 4 + ((int)threadIdx.x >> 5), + r = (int)blockIdx.x, split = (int)blockIdx.z; + if (head >= m.heads) return; + const int s = paged_seq(cu, m.seqs, r); + const int qlen = cu[s + 1] - cu[s], i = r - cu[s]; + const int live = std::min(std::max(used[s] - qlen + i + 1, 0), m.blocks * m.bs); + const int begin = (int)((long)live * split / m.splits), + end = (int)((long)live * (split + 1) / m.splits); + float query[16], value[16] = {}; + load_latent(q + (long)r * m.qr + (long)head * m.qh + lane * 16, query); + const uint16_t* const qp = qrot + (long)r * m.rr + (long)head * m.rh + lane * 2; + const float rq0 = bf16_to_f32((uint16_t)ldg_u16(qp)), + rq1 = bf16_to_f32((uint16_t)ldg_u16(qp + 1)); + float max_score = -INFINITY, den = 0; + for (int token = begin; token < end; ++token) { + const int page = bt[(long)s * m.bp + (token / m.bs) * m.bc]; + if (page < 0 || page >= m.pages) continue; + const uint16_t* const row = kv + (long)page * m.kp + (token % m.bs) * m.kt; + float key[16]; + load_latent(row + lane * 16, key); + float score = rq0 * bf16_to_f32((uint16_t)ldg_u16(row + D + lane * 2)) + + rq1 * bf16_to_f32((uint16_t)ldg_u16(row + D + lane * 2 + 1)); +#pragma unroll + for (int j = 0; j < 16; ++j) score += query[j] * key[j]; + score = wave_sum(score) * m.scale; + const bool higher = score > max_score; + const float weight = expf(higher ? max_score - score : score - max_score); + if (higher) { +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] = value[j] * weight + key[j]; + den = den * weight + 1; + max_score = score; + } else { +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] += key[j] * weight; + den += weight; + } + } + if (m.splits == 1) { + paged_store(out, gate, m, r, head, lane, value, den); + } else { + float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART; +#pragma unroll + for (int j = 0; j < 16; ++j) dst[lane * 16 + j] = value[j]; + if (!lane) { + dst[D] = max_score; + dst[D + 1] = den; + } + } +} + +__global__ __launch_bounds__(128) R3D_WAVES(4) +void merge_paged(const float* __restrict__ scratch, const uint16_t* __restrict__ gate, + uint16_t* __restrict__ out, PagedMeta m) { + const int lane = (int)threadIdx.x & 31, head = (int)blockIdx.y * 4 + ((int)threadIdx.x >> 5), + r = (int)blockIdx.x; + if (head >= m.heads) return; + const float* src = scratch + ((long)r * m.heads + head) * m.splits * PART; + float max_score = -INFINITY; + for (int s = 0; s < m.splits; ++s) + if (src[s * PART + D + 1] > 0) max_score = fmaxf(max_score, src[s * PART + D]); + float value[16] = {}, den = 0; + for (int s = 0; s < m.splits; ++s) { + const float part_den = src[s * PART + D + 1]; + if (!(part_den > 0)) continue; + const float w = expf(src[s * PART + D] - max_score); + den += part_den * w; +#pragma unroll + for (int j = 0; j < 16; ++j) value[j] += src[s * PART + lane * 16 + j] * w; + } + paged_store(out, gate, m, r, head, lane, value, den); +} + +int paged_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 8) return R3D_NO(RAD_E_INVAL); + RadTensor q = a->t[0], qr = a->t[1], o = a->t[7]; + const RadTensor& kv = a->t[2], &bt = a->t[3], &su = a->t[4], &cu = a->t[5]; + const RadTensor* gate = r3d_opt(a, 6); + const long heads = r3d_geti_or(a, "heads", 0), bs = r3d_geti_or(a, "block_size", 0); + const float scale = (float)r3d_getf(a, "scale", 0); + auto heads_view = [&](RadTensor& t, long width) { + if (heads > 0 && t.rank == 2 && t.shape[1] == heads * width) { + t.rank = 3; + t.shape[1] = heads; + t.shape[2] = width; + t.stride[2] = t.stride[1]; + t.stride[1] *= width; + } + }; + heads_view(q, D); + heads_view(qr, RD); + heads_view(o, D); + if (q.dtype != RAD_BF16 || qr.dtype != RAD_BF16 || kv.dtype != RAD_BF16 || + o.dtype != RAD_BF16 || bt.dtype != RAD_I32 || su.dtype != RAD_I32 || cu.dtype != RAD_I32 || + (gate && gate->dtype != RAD_BF16)) + return R3D_NO(RAD_E_DTYPE); + if (!q.data || !qr.data || !kv.data || !bt.data || !su.data || !cu.data || !o.data) + return R3D_NO(RAD_E_INVAL); + if (r3d_geti_or(a, "latent_dim", 0) != D || r3d_geti_or(a, "rope_dim", 0) != RD || heads < 1 || + heads > 64 || bs < 1 || bs > 256 || !std::isfinite(scale) || scale <= 0 || q.rank != 3 || + q.shape[0] < 1 || q.shape[0] > 65535 || q.shape[1] != heads || q.shape[2] != D || + q.stride[2] != 1 || q.stride[1] < D || q.stride[0] < heads * q.stride[1] || qr.rank != 3 || + qr.shape[0] != q.shape[0] || qr.shape[1] != heads || qr.shape[2] != RD || + qr.stride[2] != 1 || qr.stride[1] < RD || qr.stride[0] < heads * qr.stride[1] || + kv.rank != 4 || kv.shape[0] < 1 || kv.shape[0] > INT_MAX || kv.shape[1] != 1 || + kv.shape[2] != bs || kv.shape[3] < D + RD || kv.stride[3] != 1 || kv.stride[2] < D + RD || + kv.stride[0] < bs * kv.stride[2] || bt.rank != 2 || bt.shape[1] < 1 || + bt.shape[1] > INT_MAX / bs || bt.stride[1] < 1 || bt.stride[0] < bt.shape[1] * bt.stride[1] || + su.rank != 1 || su.shape[0] < 1 || bt.shape[0] < su.shape[0] || !r3d_contig(&su) || + !r3d_contig(&cu) || r3d_numel(&cu) != su.shape[0] + 1 || o.rank != 3 || + o.shape[0] != q.shape[0] || o.shape[1] != heads || o.shape[2] != D || o.stride[2] != 1 || + o.stride[1] < D || o.stride[0] < heads * o.stride[1] || + (gate && (gate->rank != 2 || gate->shape[0] != q.shape[0] || gate->shape[1] < heads || + gate->stride[1] != 1))) + return R3D_NO(RAD_E_SHAPE); + /* The split comes from the head count alone (paged_splits). Only a batch whose partials the + * scratch cannot hold takes fewer, as many as fit. */ + const long rows = q.shape[0], slots = a->scratch ? (long)(a->scratch_bytes / (PART * 4)) : 0; + int splits = paged_splits(heads); + if (rows * heads * splits > slots) splits = (int)std::max(1l, slots / (rows * heads)); + const PagedMeta m{ q.stride[0], q.stride[1], qr.stride[0], qr.stride[1], + kv.stride[0], kv.stride[2], bt.stride[0], bt.stride[1], + o.stride[0], o.stride[1], gate ? (long)gate->stride[0] : 0L, + (int)q.shape[0], (int)heads, (int)su.shape[0], (int)bt.shape[1], + (int)bs, (int)kv.shape[0], splits, scale }; + const uint16_t* gp = gate ? (const uint16_t*)gate->data : nullptr; + (void)hipGetLastError(); + R3D_KLAUNCH(attend_paged, dim3(m.rows, (m.heads + 3) / 4, m.splits), dim3(128), + (hipStream_t)stream, (const uint16_t*)q.data, (const uint16_t*)qr.data, + (const uint16_t*)kv.data, (const int*)bt.data, (const int*)su.data, + (const int*)cu.data, gp, (uint16_t*)o.data, (float*)a->scratch, m); + hipError_t e = hipGetLastError(); + if (e != hipSuccess) return R3D_NO(RAD_E_DEVICE); + if (splits > 1) { + (void)hipGetLastError(); + R3D_KLAUNCH(merge_paged, dim3(m.rows, (m.heads + 3) / 4), dim3(128), (hipStream_t)stream, + (const float*)a->scratch, gp, (uint16_t*)o.data, m); + e = hipGetLastError(); + if (e != hipSuccess) return R3D_NO(RAD_E_DEVICE); + } + return RAD_OK; +} + +} // namespace + +extern "C" int r3d_rad_mla_attn_paged(const RadArgs* a, RadStream s) { + return paged_body(a, s); +} + +/* Sized at the band's top row count, at most kPagedRows (paged_splits). */ +extern "C" int64_t r3d_rad_mla_attn_paged_scratch(const RadArgs* a) { + const long heads = r3d_geti_or(a, "heads", 0), rows = r3d_geti_or(a, "M", kPagedRows); + if (heads < 1 || heads > 64 || rows < 1) return R3D_NO(RAD_E_SHAPE); + return paged_scratch_bytes(rows, heads); +} diff --git a/libr3d/r3d_mla_project.hip b/libr3d/r3d_mla_project.hip new file mode 100644 index 00000000..72a571f3 --- /dev/null +++ b/libr3d/r3d_mla_project.hip @@ -0,0 +1,175 @@ +/* r3d_mla_project.hip -- mla_project: the per-head absorbed-MLA projections. + * + * An absorbed MLA model keeps one 512-wide latent per token and folds the per-head K/V + * projections into two matrices: + * + * mode "absorb" y[M, heads, 512] = x[M, heads, head_dim] @ w[head, 0, :, :]^T per head + * mode "expand" y[M, heads, head_dim] = x[M, heads, 512] @ w[head, 1, :, :]^T per head + * + * where w is the shared [heads, 2 * head_dim, 512] BF16 matrix (the K half, then the V half, of + * each head's rows) and head_dim is 128 or 256. f32 arithmetic, one bf16 rounding at the store, + * as libref. + * + * Absorption streams adjacent latent columns: one thread a column, R rows a thread, and each + * weight element is loaded once for the R rows it serves. Expansion reduces a contiguous weight + * row: one wave a column, R rows a wave, each lane its share of the 512-wide sum in ascending j, + * then one wave sum. Every row's sum runs over j in the same order whatever R is, so a row's + * bytes do not depend on the batch it is in. A tail group past the last row reads that row again + * and stores nothing for it. + * + * Bandwidth-bound GEMV shapes: plain vectorised f32 is the idiomatic RDNA3 path here, as in the + * skinny GEMM rows. No WMMA (RDNA3's wave matrix is f16/i8 only and adds a fragment layout for no + * throughput at these shapes) and no fp8. + * + * The launcher (r3d_rad_mla_project) checks: bf16 in, weights and out; heads 1..64; head_dim + * 128 or 256; latent_dim 512; x [M, heads, head_dim|512], w [heads, 2*head_dim, 512], y + * [M, heads, 512|head_dim], M 1..65535, last axes contiguous and row pitches at least the dense + * ones (a 2-D [M, heads*width] plane is viewed as 3-D); RAD_E_INVAL, RAD_E_DTYPE, RAD_E_SHAPE. + * + * RDNA4 -> RDNA3: the kernels use only bf16 loads, f32 FMAs and the wave-sum butterfly + * (r3d_xor_sum<32>, the same order as libr4d's, so bit-identical). The element loads are the + * library's ldg_u16 (a whole register, no register-half wait); everything else is unchanged. + */ +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include +#include +#include + +namespace { + +struct ProjectMeta { + long xr, xh, wp, yr, yh; + int rows, heads; +}; + +/* Absorption streams adjacent latent columns; expansion reduces a contiguous weight row. R rows + * a thread (absorb) or a wave (expand): each weight element is loaded once for R rows. Every row's + * sum runs over j in the same order whatever R is (expand: each lane's share in ascending j, then + * r3d_xor_sum<32>), so a row's bytes do not depend on the batch it is in. A tail group past the + * last row reads that row again and stores nothing for it. */ +template +__global__ __launch_bounds__(128) R3D_WAVES(4) +void project_absorb_rows(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + uint16_t* __restrict__ y, ProjectMeta m) { + const int col = (int)blockIdx.x * 128 + (int)threadIdx.x, head = (int)blockIdx.y, + r0 = (int)blockIdx.z * R; + if (col >= 512) return; + const uint16_t* xr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) + xr[r] = x + (long)std::min(r0 + r, m.rows - 1) * m.xr + (long)head * m.xh; + float sum[R]; +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = 0; + for (int j = 0; j < HD; ++j) { + const float wv = bf16_to_f32((uint16_t)ldg_u16(w + ((long)head * 2 * HD + j) * m.wp + col)); +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32((uint16_t)ldg_u16(xr[r] + j)), wv, sum[r]); + } +#pragma unroll + for (int r = 0; r < R; ++r) + if (r0 + r < m.rows) y[(long)(r0 + r) * m.yr + (long)head * m.yh + col] = f32_to_bf16(sum[r]); +} + +template +__global__ __launch_bounds__(128) R3D_WAVES(4) +void project_expand_rows(const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + uint16_t* __restrict__ y, ProjectMeta m) { + const int lane = (int)threadIdx.x & 31, col = (int)blockIdx.x * 4 + ((int)threadIdx.x >> 5), + head = (int)blockIdx.y, r0 = (int)blockIdx.z * R; + const uint16_t* xr[R]; +#pragma unroll + for (int r = 0; r < R; ++r) + xr[r] = x + (long)std::min(r0 + r, m.rows - 1) * m.xr + (long)head * m.xh; + const uint16_t* const wr = w + ((long)head * 2 * HD + HD + col) * m.wp; + float sum[R]; +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = 0; + for (int j = lane; j < 512; j += 32) { + const float wv = bf16_to_f32((uint16_t)ldg_u16(wr + j)); +#pragma unroll + for (int r = 0; r < R; ++r) sum[r] = fmaf(bf16_to_f32((uint16_t)ldg_u16(xr[r] + j)), wv, sum[r]); + } + float mine = 0; +#pragma unroll + for (int r = 0; r < R; ++r) { + sum[r] = r3d_xor_sum<32>(sum[r]); + if (lane == r) mine = sum[r]; + } + if (lane < R && r0 + lane < m.rows) + y[(long)(r0 + lane) * m.yr + (long)head * m.yh + col] = f32_to_bf16(mine); +} + +int project_body(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return R3D_NO(RAD_E_INVAL); + RadTensor x = a->t[0], y = a->t[2]; + const RadTensor& w = a->t[1]; + const char* mode = r3d_gets(a, "mode"); + const bool absorb = mode && !std::strcmp(mode, "absorb"), + expand = mode && !std::strcmp(mode, "expand"); + const long h = r3d_geti_or(a, "heads", 0), hd = r3d_geti_or(a, "head_dim", 0); + auto heads_view = [&](RadTensor& t, long width) { + if (h > 0 && t.rank == 2 && t.shape[1] == h * width) { + t.rank = 3; + t.shape[1] = h; + t.shape[2] = width; + t.stride[2] = t.stride[1]; + t.stride[1] *= width; + } + }; + heads_view(x, absorb ? hd : 512); + heads_view(y, absorb ? 512 : hd); + if (x.dtype != RAD_BF16 || w.dtype != RAD_BF16 || y.dtype != RAD_BF16) + return R3D_NO(RAD_E_DTYPE); + if (!x.data || !w.data || !y.data) return R3D_NO(RAD_E_INVAL); + if ((!absorb && !expand) || h < 1 || h > 64 || (hd != 128 && hd != 256) || + r3d_geti_or(a, "latent_dim", 0) != 512 || x.rank != 3 || w.rank != 2 || y.rank != 3 || + x.shape[0] < 1 || x.shape[0] > 65535 || x.shape[1] != h || + x.shape[2] != (absorb ? hd : 512) || w.shape[0] != h * 2 * hd || w.shape[1] != 512 || + y.shape[0] != x.shape[0] || y.shape[1] != h || y.shape[2] != (absorb ? 512 : hd) || + x.stride[2] != 1 || w.stride[1] != 1 || y.stride[2] != 1 || x.stride[1] < x.shape[2] || + x.stride[0] < h * x.stride[1] || w.stride[0] < 512 || y.stride[1] < y.shape[2] || + y.stride[0] < h * y.stride[1]) + return R3D_NO(RAD_E_SHAPE); + const ProjectMeta m{ x.stride[0], x.stride[1], w.stride[0], y.stride[0], + y.stride[1], (int)x.shape[0], (int)h }; + const uint16_t* xp = (const uint16_t*)x.data; + const uint16_t* wp = (const uint16_t*)w.data; + uint16_t* yp = (uint16_t*)y.data; + /* The largest of 8, 4, 2 and 1 rows a group that the batch fills. */ + const int R = m.rows >= 8 ? 8 : m.rows >= 4 ? 4 : m.rows >= 2 ? 2 : 1; +#define MLA_PROJECT_HD(RR, HD) \ + do { \ + const unsigned groups = (unsigned)((m.rows + RR - 1) / RR); \ + (void)hipGetLastError(); \ + if (absorb) \ + R3D_KLAUNCH((project_absorb_rows), dim3(4, h, groups), dim3(128), \ + (hipStream_t)stream, xp, wp, yp, m); \ + else \ + R3D_KLAUNCH((project_expand_rows), dim3(HD / 4, h, groups), dim3(128), \ + (hipStream_t)stream, xp, wp, yp, m); \ + const hipError_t e = hipGetLastError(); \ + return e == hipSuccess ? RAD_OK : R3D_NO(RAD_E_DEVICE); \ + } while (0) +#define MLA_PROJECT_ROWS(RR) \ + do { \ + if (hd == 128) MLA_PROJECT_HD(RR, 128); \ + MLA_PROJECT_HD(RR, 256); \ + } while (0) + if (R == 8) MLA_PROJECT_ROWS(8); + if (R == 4) MLA_PROJECT_ROWS(4); + if (R == 2) MLA_PROJECT_ROWS(2); + MLA_PROJECT_ROWS(1); +#undef MLA_PROJECT_ROWS +#undef MLA_PROJECT_HD +} + +} // namespace + +extern "C" int r3d_rad_mla_project(const RadArgs* a, RadStream s) { + return project_body(a, s); +} diff --git a/libr3d/r3d_moe_gather.hip b/libr3d/r3d_moe_gather.hip index ee0a269f..a498bcd7 100644 --- a/libr3d/r3d_moe_gather.hip +++ b/libr3d/r3d_moe_gather.hip @@ -125,7 +125,10 @@ int r3d_rad_moe_gather(const RadArgs* a, RadStream s) const uint32_t ew_ld = (uint32_t)ew->stride[0]; const uint32_t y_ld = (uint32_t)y->stride[0]; const uint32_t T = (uint32_t)r3d_numel(sorted); - if (T < M * top_k) return R3D_NO(RAD_E_SHAPE); + /* M is the batch capacity, not the token count: the engine pads the batch, and the slot + * table covers only the tokens present, so it may be shorter than M * top_k (the kernel + * zeroes the padding rows). It may never be longer. */ + if (T > (uint64_t)M * top_k) return R3D_NO(RAD_E_SHAPE); // The optional shared arm (operands 3 and 4, present together). const RadTensor* sh = r3d_opt(a, 3), *sg = r3d_opt(a, 4); diff --git a/libr3d/r3d_ple_conv.hip b/libr3d/r3d_ple_conv.hip new file mode 100644 index 00000000..373c60b9 --- /dev/null +++ b/libr3d/r3d_ple_conv.hip @@ -0,0 +1,271 @@ +/* r3d_ple_conv.hip -- ple_conv: Per-Layer Embedding's dilated depthwise convolution, its silu, and + * the residual add that finishes the layer. + * + * y[t][c] = resid[t][c] + silu( sum_j w[c][j] * x[t - (width-1-j)*dilation][c] ) + * + * x [M, n] bf16, w [n, width] bf16, conv_state [n_slots, n, state_len] bf16, cu [N+1] i32, + * resid [M, n] bf16 (optional), cache_idx [N] i32 (optional), has_init [N] i32 (optional), + * num_accepted [N] i32 (optional), y [M, n] bf16 out. + * + * libref/ref_ple.cpp is the oracle and docs/OPS.md the contract. The taps are `dilation` apart, so + * at width 4 and dilation 3 they sit 9, 6, 3 and 0 timesteps back and a sequence carries a history + * of (width-1)*dilation = 9, not 3. An off-by-one in a convolution cache yields fluent output from + * a slightly wrong context, so the indexing mirrors ref's line for line: state slot `i` holds + * relative position `i - hist`, a read at `src < 0` becomes `cs[slot][c][off + src + hist]`, and + * `has_init` 0 means that window is zeros, not the slot's stale contents. + * + * One thread per channel: a depthwise convolution never mixes channels, so only time must stay + * together. A thread walks a tile of tokens; consecutive threads own consecutive channels, so a + * wave loads one contiguous 64-byte slice of a token row and a workgroup a contiguous 512-byte one. + * + * The grid is (channel blocks, token tiles, sequences). Token tiles are counted from the batch's + * total token count, an upper bound on any one sequence's; a short sequence's extra blocks find + * `t0 >= slen` and return. A per-sequence count would mean reading `cu` on the host. + * + * The taps are read from memory, not kept in a shift register: the window would need `hist + 1` + * registers indexed by a runtime value, which compiles to a select tree, and a compile-time window + * would need a specialisation per (width, dilation). The re-reads hit a tile working set of + * (BT + hist) * 512 bytes (21 KB at BT 32), and the op is bound by the three arrays it must touch + * anyway. Nothing is staged in LDS: there is no reduction here, so the launcher's 60 KiB stage + * check has no stage to size, and no wave barrier is needed for the write-back (see below). + * + * The window write-back is in the same launch; see the note at the end of the kernel. It relies + * on `hist < kPcBT`, asserted below. + * + * RDNA3 notes. The kernel is the libr4d one (r4d_ple_conv_bf16.hip) with three adaptations: + * every 16-bit read goes through ldg_u16, so it is a global load through the device address space + * (measured on the box: the two builds emit the same 50 global_load_u16 / 50 global_load_d16_b16 / + * 46 global_load_d16_hi_b16 / 2 global_load_b32, the d16 pairs being the write-back packing two + * bf16 into one register); the kernel is annotated R3D_WAVES(16), the wave-slot cap of a gfx11 + * SIMD, not R3D_WAVES(8) for its own eight waves -- the op is bandwidth-bound and wants the most + * resident waves it can get, and the 8 annotation costs registers (113 VGPRs against 28 at 16, + * both spill-free, 28 being what the RDNA4 build of the same source allocates); and an optional + * operand whose descriptor is present but unbound is read as absent (r3d_has), which is how the + * kernel treats it. The compute is plain f32: the op moves bytes, and RDNA3 has no bf16 dot2 and + * nothing here is a 16x16x16 tile, so the wave matrix would add a fragment layout for no + * throughput (r3d_common.h). + */ +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#include +#include + +namespace { + +enum { + kPcThreads = 256, + kPcWaves = kPcThreads / kWave, /* 8 waves of 32 a workgroup */ + kPcWpS = 16, /* waves a SIMD: gfx11's wave32 slot count, and the register budget (64) */ + kPcBT = 32, /* tokens a thread walks; the tile's working set is (BT + hist) * 512 B */ + kPcMaxW = 8, /* taps held in registers, so the weight loop unrolls to a static bound */ + kPcMaxHist = 16, /* (width-1)*dilation, the write-back's register window; see cPleConv */ +}; + +/* The write-back lives in tile 0, which is sound only while the deepest tap is inside the first + * tile. At hist >= BT a second block would read history and the write-back would overwrite bytes + * it is still reading, silently corrupting a sequence's first tokens. The constraint table caps + * hist <= 16; the tile size is the other half of that bound. */ +static_assert(kPcMaxHist < kPcBT, "the conv history must fit inside tile 0 for the fused write-back"); + +/* A bf16 of global memory widened in one instruction; see ldg_u16 in r3d_common.h. */ +__device__ __forceinline__ float pc_ld(const uint16_t* p, size_t i) { + return bf16_to_f32((uint16_t)ldg_u16(p + i)); +} + +/* expf rather than __expf: the op is bound by memory, not the transcendental, and the oracle uses + * std::exp (ref_common.h's act_silu). The instruction-bound GDN conv makes the opposite trade. */ +__device__ __forceinline__ float pc_silu(float z) { return z / (1.0f + expf(-z)); } + +/* SILU is ple_conv's activation; causal_conv1d (LFM2's short convolution) is the same window with + * no activation, no residual and dilation one, and shares this kernel. */ +template +__global__ __launch_bounds__(kPcThreads) R3D_WAVES(kPcWpS) void r3d_ple_conv_kernel( + const uint16_t* __restrict__ x, const uint16_t* __restrict__ w, + uint16_t* __restrict__ cs, const int32_t* __restrict__ cu, + const uint16_t* __restrict__ resid, const int32_t* __restrict__ sidx, + const int32_t* __restrict__ hini, const int32_t* __restrict__ nacc, + uint16_t* __restrict__ y, uint32_t n, uint32_t wid, uint32_t dil, uint32_t hist, + uint32_t xld, uint32_t rld, uint32_t yld, uint32_t wld, + long long cs_slot, long long cs_ch, long long cs_tok, long long state_len) { + + const uint32_t c = blockIdx.x * kPcThreads + threadIdx.x; + if (c >= n) return; + const uint32_t s = blockIdx.z; + const int32_t bos = cu[s]; + const int32_t slen = cu[s + 1] - bos; + if (slen <= 0) return; + const int32_t t0 = (int32_t)(blockIdx.y * kPcBT); + if (t0 >= slen) return; + const int32_t t1 = min(t0 + (int32_t)kPcBT, slen); + + const int32_t slot = sidx ? sidx[s] : (int32_t)s; + if (slot < 0) return; + /* A cold slot's window is zeros: a fresh sequence on a recycled slot would otherwise convolve + * the previous sequence's tail into its first `hist` tokens. */ + const bool warm = cs && (!hini || hini[s] != 0); + const long long off = nacc ? (long long)nacc[s] - 1 : 0; + + /* This channel's taps, read once for the whole tile. */ + float wt[kPcMaxW]; +#pragma unroll + for (uint32_t j = 0; j < kPcMaxW; ++j) wt[j] = j < wid ? pc_ld(w, (size_t)c * wld + j) : 0.0f; + + const uint16_t* __restrict__ xc = x + (size_t)bos * xld + c; + const uint16_t* __restrict__ rc = resid ? resid + (size_t)bos * rld + c : nullptr; + uint16_t* __restrict__ dst = cs ? cs + (size_t)slot * cs_slot + (size_t)c * cs_ch : nullptr; + const uint16_t* __restrict__ hc = warm ? dst + off * cs_tok : nullptr; + uint16_t* __restrict__ yc = y + (size_t)bos * yld + c; + + for (int32_t t = t0; t < t1; ++t) { + float acc = 0.0f; +#pragma unroll + for (uint32_t j = 0; j < kPcMaxW; ++j) { + if (j < wid) { + const int32_t src = t - (int32_t)hist + (int32_t)(j * dil); + const float v = src >= 0 ? pc_ld(xc, (size_t)src * xld) + : (hc ? pc_ld(hc, (size_t)(src + (int32_t)hist) * cs_tok) + : 0.0f); + acc += v * wt[j]; + } + } + const float r = rc ? pc_ld(rc, (size_t)t * rld) : 0.0f; + yc[(size_t)t * yld] = f32_to_bf16(r + (SILU ? pc_silu(acc) : acc)); + } + + /* The window this step leaves, in the same launch with no barrier. History is read only where + * `t - hist + j*dilation < 0`, i.e. by tokens below `hist` (9, against a 32-token tile), so + * tile 0 is the only block touching state[slot][c]. One thread owns the whole channel there, so + * its reads precede its writes in program order. At decode the op's cost is the dispatch itself + * (flat from M=1 to M=8), so a second launch would roughly double it. + * + * The layout is libref/ref_ple.cpp's, chosen by `num_accepted`. Present, this is a decode step + * whose drafts a verify may reject: the history read shifts down by one and every input of the + * step follows it, slot i holding position i + 1 of (window read ++ step), so a next step that + * kept k tokens reads at k - 1. Absent, every token commits and the last `hist` inputs land at + * offset zero. The two agree at one token. Slots past `state_len` are not written; the manager + * sizes the window hist + n_spec, enough for a step of 1 + n_spec tokens. + * + * Values are copied as bf16 bits, the same tensor's bytes on both sides. The step's rows come + * from the read-only `x`, so other tiles reading them is no hazard. Every history value is + * loaded before the first store. */ + if (!dst || blockIdx.y != 0) return; + uint16_t keep[kPcMaxHist]; + if (nacc) { +#pragma unroll + for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i) + if (i + 1 < hist) + keep[i] = hc ? (uint16_t)ldg_u16(hc + (size_t)(i + 1) * cs_tok) : (uint16_t)0; +#pragma unroll + for (uint32_t i = 0; i + 1 < kPcMaxHist; ++i) + if (i + 1 < hist) dst[(size_t)i * cs_tok] = keep[i]; + for (int32_t t = 0; t < slen && (long long)hist - 1 + t < state_len; ++t) + dst[(size_t)(hist - 1 + (uint32_t)t) * cs_tok] = (uint16_t)ldg_u16(xc + (size_t)t * xld); + return; + } +#pragma unroll + for (uint32_t i = 0; i < kPcMaxHist; ++i) { + if (i < hist) { + const int32_t src = slen - (int32_t)hist + (int32_t)i; + keep[i] = src >= 0 ? (uint16_t)ldg_u16(xc + (size_t)src * xld) + : (hc ? (uint16_t)ldg_u16(hc + (size_t)(src + (int32_t)hist) * cs_tok) + : (uint16_t)0); + } + } +#pragma unroll + for (uint32_t i = 0; i < kPcMaxHist; ++i) + if (i < hist) dst[(size_t)i * cs_tok] = keep[i]; +} + +/* The operand slots, in ple_conv's schema order. causal_conv1d is this kernel's SILU=false arm + * with `resid` out of the schema and `dilation` fixed at one; its entry point and operand table + * are not in this unit, so only ple_conv's positions are named here. */ +enum { PC_X = 0, PC_W, PC_CS, PC_CU, PC_RESID, PC_CIDX, PC_HINIT, PC_NACC, PC_Y }; + +/* The launcher: the shape checks libr4d's r4d_rad_ple_conv makes, in the same order with the same + * refusals. `silu` selects the activation. */ +int r3d_conv_launch(const RadArgs* a, RadStream s, bool silu, const RadTensor* x, const RadTensor* w, + const RadTensor* cs, const RadTensor* cu, const RadTensor* resid, + const RadTensor* cidx, const RadTensor* hini, const RadTensor* nacc, + const RadTensor* y) { + if (!r3d_p(x) || !r3d_p(w) || !r3d_p(cu) || !r3d_wp(y)) return R3D_NO(RAD_E_INVAL); + if (x->dtype != RAD_BF16 || w->dtype != RAD_BF16 || y->dtype != RAD_BF16) + return R3D_NO(RAD_E_DTYPE); + /* An optional operand the engine bound to nothing is absent, so it is tested with r3d_has: + * a descriptor with a null `data` carries the schema's dtype, not a tensor's. */ + if (r3d_has(resid) && resid->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (r3d_has(cs) && cs->dtype != RAD_BF16) return R3D_NO(RAD_E_DTYPE); + if (cu->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + if (r3d_has(cidx) && cidx->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + /* `has_init` must be int32 (RadBatch::ctx_lens, like every derived buffer): read as bytes, a + * ctx_len of 512 has a zero low byte and the history would be dropped. Anything else is + * refused. */ + if (r3d_has(hini) && hini->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + if (r3d_has(nacc) && nacc->dtype != RAD_I32) return R3D_NO(RAD_E_DTYPE); + + const long long n = r3d_geti_or(a, "n", 0); + const long long wid = r3d_geti_or(a, "width", 0); + const long long dil = r3d_geti_or(a, "dilation", 1); + if (n <= 0 || wid <= 0 || dil <= 0) return R3D_NO(RAD_E_SHAPE); + if (wid > kPcMaxW) return R3D_NO(RAD_E_UNSUPPORTED); + const long long hist = (wid - 1) * dil; + if (hist > kPcMaxHist) return R3D_NO(RAD_E_UNSUPPORTED); + + long long T = 0, ty = 0, tr = 0, wrows = 0; + const long long xld = r3d_rows_pitch(x, n, &T); + const long long yld = r3d_rows_pitch(y, n, &ty); + const bool have_r = r3d_has(resid); + const long long rld = have_r ? r3d_rows_pitch(resid, n, &tr) : 0; + const long long wld = r3d_rows_pitch(w, wid, &wrows); + if (xld < 0 || yld < 0 || wld < 0 || (have_r && rld < 0)) return R3D_NO(RAD_E_STRIDE); + /* The row count comes from the operands, and they must agree: `M` is ranged, so the arg holds + * the band's upper bound and a grid sized by it would run off the arena. */ + if (T <= 0 || ty != T || (have_r && tr != T)) return R3D_NO(RAD_E_SHAPE); + if (wrows < n) return R3D_NO(RAD_E_SHAPE); + + const long long N = r3d_numel(cu) - 1; + if (N <= 0) return R3D_NO(RAD_E_SHAPE); + if (!r3d_contig(cu)) return R3D_NO(RAD_E_STRIDE); + + /* [n_slots, n, state_len]. A state too shallow for the deepest tap is refused here; the + * rollback offset cannot be checked without reading `num_accepted` on the host, which is why + * the manager sizes the window hist + n_spec. */ + long long cs_slot = 0, cs_ch = 0, cs_tok = 0, state_len = 0; + const bool have_cs = r3d_has(cs) && hist > 0; + if (have_cs) { + if (cs->rank != 3) return R3D_NO(RAD_E_SHAPE); + if (r3d_dim(cs, 1) < n || r3d_dim(cs, 2) < hist) return R3D_NO(RAD_E_SHAPE); + cs_slot = r3d_stride(cs, 0); + cs_ch = r3d_stride(cs, 1); + cs_tok = r3d_stride(cs, 2); + state_len = r3d_dim(cs, 2); + } + + const uint32_t cb = (uint32_t)((n + kPcThreads - 1) / kPcThreads); + const uint32_t tb = (uint32_t)((T + kPcBT - 1) / kPcBT); + const auto kernel = silu ? r3d_ple_conv_kernel : r3d_ple_conv_kernel; + R3D_KLAUNCH(R3D_KNAME(kernel), dim3(cb, tb, (uint32_t)N), dim3(kPcThreads), (hipStream_t)s, + (const uint16_t*)r3d_p(x), (const uint16_t*)r3d_p(w), + have_cs ? (uint16_t*)r3d_wp(cs) : nullptr, + (const int32_t*)r3d_p(cu), + have_r ? (const uint16_t*)r3d_p(resid) : nullptr, + r3d_has(cidx) ? (const int32_t*)r3d_p(cidx) : nullptr, + r3d_has(hini) ? (const int32_t*)r3d_p(hini) : nullptr, + r3d_has(nacc) ? (const int32_t*)r3d_p(nacc) : nullptr, + (uint16_t*)r3d_wp(y), (uint32_t)n, (uint32_t)wid, (uint32_t)dil, + (uint32_t)hist, (uint32_t)xld, (uint32_t)rld, (uint32_t)yld, (uint32_t)wld, + cs_slot, cs_ch, cs_tok, state_len); + return hipGetLastError() == hipSuccess ? RAD_OK : R3D_NO(RAD_E_DEVICE); +} + +} // namespace + +extern "C" int r3d_rad_ple_conv(const RadArgs* a, RadStream s) { + return r3d_conv_launch(a, s, true, r3d_opt(a, PC_X), r3d_opt(a, PC_W), r3d_opt(a, PC_CS), + r3d_opt(a, PC_CU), r3d_opt(a, PC_RESID), r3d_opt(a, PC_CIDX), + r3d_opt(a, PC_HINIT), r3d_opt(a, PC_NACC), r3d_opt(a, PC_Y)); +} diff --git a/libr3d/r3d_plugin.h b/libr3d/r3d_plugin.h index 685dc539..d84e38e1 100644 --- a/libr3d/r3d_plugin.h +++ b/libr3d/r3d_plugin.h @@ -142,6 +142,7 @@ int r3d_rad_dequant (const RadArgs* a, RadStream s); /* --- r3d_gemm_bf16_nt_m16.hip, r3d_gemm_f16_nt_m16.hip, r3d_gemm_fp8a16_nt_m1.hip --- */ int r3d_rad_gemm_nt_bf16_m16 (const RadArgs* a, RadStream s); int r3d_rad_gemm_nt_f16_m16 (const RadArgs* a, RadStream s); +int r3d_rad_gemm_nt_f32 (const RadArgs* a, RadStream s); /* --- r3d_gemm_w4a16_nt_m64.hip: the 4-bit weight against an f16 activation at M <= 64. The * codes are read in the container's order; the layout and relayout hooks present the @@ -184,11 +185,19 @@ int r3d_rad_gdn_gated_norm_hq_i8(const RadArgs* a, RadStream s); int r3d_rad_gdn_conv_prep(const RadArgs* a, RadStream s); int r3d_rad_gdn_conv_update(const RadArgs* a, RadStream s); +/* --- r3d_ple_conv.hip: PLE's dilated depthwise convolution, its silu and the residual add that + * finishes the layer: one thread a channel, the conv window rewritten in the same launch. */ +int r3d_rad_ple_conv(const RadArgs* a, RadStream s); + /* --- r3dh_gdn_recurrent_update.hip (libhalo's): the gated-delta-net recurrent state update at * decode against the paged state cache, in either state form (per_candidate or anchor). */ extern "C" int r3dh_rad_gdn_recurrent_update(const RadArgs* a, RadStream s); extern "C" int r3dh_rad_gdn_conv_recurrent_update(const RadArgs* a, RadStream s); +/* --- r3d_kda_update.hip: GLM's per-channel KDA recurrence at decode and prefill, over the + * paged f32 state cache, with the speculative candidate snapshots. */ +int r3d_rad_kda_update(const RadArgs* a, RadStream s); + /* --- r3d_expert_scale_bf16.hip: each routing weight times its expert's own scale, in place. */ int r3d_rad_expert_scale_bf16(const RadArgs* a, RadStream s); @@ -205,6 +214,10 @@ int r3d_rad_moe_gather(const RadArgs* a, RadStream s); int r3d_rad_moe_gather_inv(const RadArgs* a, RadStream s); int r3d_rad_router_topk_scatter(const RadArgs* a, RadStream s); int r3d_rad_router_sigmoid_topk(const RadArgs* a, RadStream s); +int r3d_rad_router_sigmoid_group_topk(const RadArgs* a, RadStream s); +int r3d_rad_mla_project(const RadArgs* a, RadStream s); +int r3d_rad_mla_attn_paged(const RadArgs* a, RadStream s); +int64_t r3d_rad_mla_attn_paged_scratch(const RadArgs* a); /* --- r3d_moe_gemm_q.hip: the grouped quantised GEMM (E4M3 x E4M3, the per-(row, grid) scale fold). */ int r3d_rad_moe_gemm_q(const RadArgs* a, RadStream s); @@ -274,7 +287,12 @@ int r3d_shape_scale (const RadParam* p, int n_p, int operand, RadOpdDe int r3d_shape_fill (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_rope (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_kv_store (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_kda_update (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_embed_lookup (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_gemm_nt_f32 (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_router_sigmoid_group_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_mla_project (const RadParam* p, int n_p, int operand, RadOpdDesc* out); +int r3d_shape_mla_attn_paged (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_gather_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_scatter_rows (const RadParam* p, int n_p, int operand, RadOpdDesc* out); int r3d_shape_quant_act_fp8 (const RadParam* p, int n_p, int operand, RadOpdDesc* out); diff --git a/libr3d/r3d_router_group_topk.hip b/libr3d/r3d_router_group_topk.hip new file mode 100644 index 00000000..13bdcdca --- /dev/null +++ b/libr3d/r3d_router_group_topk.hip @@ -0,0 +1,257 @@ +/* r3d_router_group_topk.hip -- router_sigmoid_group_topk: group-limited sigmoid routing. + * + * p[e] = sigmoid(logit[e]) and rank[e] = p[e] + bias[e]. The experts fall into `n_group` equal + * groups; a group ranks by the sum of its two highest ranks, the `topk_group` best groups are + * kept, and the top_k are taken from the kept groups' experts only. The weights are the kept + * experts' unbias'd p, times `route_scale` (divided by their own sum first, if `norm`): the + * correction bias selects, it never weights. + * + * logits [M][n_expert] f32, bias [n_expert] f32 -> ids [M][top_k] i32, weights [M][top_k] f32 + * + * One wave per row: a lane holds experts lane, lane+32, ... as 64-bit keys -- the rank's + * order-preserving bits (-0 folded to +0, a NaN keyed 0 so it is never selected) above ~expert, so + * a tie goes to the lower expert -- and lane g holds group g's sum. Round j takes the largest key + * below round j-1's winner, which is a serial scan with a strict `>` done as a wave reduce: equal + * ranks to the lower expert, equal group sums to the lower group, a group with no finite pair + * never. A row with fewer selectable experts than top_k names expert 0 in the slots left over, + * weighted by expert 0's p, as libr4d's wave leaves it. + * + * The shim takes the row count from `logits` and every pitch from the operands, and refuses: + * fewer than 1 or more than 512 experts, top_k outside 1..32, fewer than 1 or more than 32 groups, + * a group count that does not divide the experts into at least two each, topk_group outside + * 1..n_group, a top_k wider than the kept groups can supply, a non-finite or non-positive + * route_scale, a logits plane that is not [M >= 1, pitch >= n_expert] with rows of stride 1, a + * bias that is not [n_expert] with a stride of at least 1, ids and weights that are not [M, pitch + * >= top_k] with rows of stride 1, and any dtype other than f32 logits, f32 bias, i32 ids and f32 + * weights. Null operands are RAD_E_INVAL and every geometry rule above RAD_E_SHAPE, as in + * libr4d's launcher; libr3d's convention (r3d_args.h: an issue bug, not a shape) names the null + * case, and libr4d spells it inside its shape clause. + * + * gfx1102, from libr4d's router_group_wave_kernel (r4d_glm.hip). Two adaptations, no change to the + * arithmetic: + * * One wave per block, one block per row, where libr4d packs four rows into a 128-thread block. + * A wave reduction in a loop body miscompiles for a non-first wave of a block here -- wave 0 + * is right, waves 1+ drop out (r3d_moe_router_topk_bf16.hip) -- and every loop in this kernel + * is one: the group ranking runs a wave merge per group, the group selection and the top_k + * each run one per round. One wave a block retires the case, and the __syncthreads that stages + * the scores is then a single-wave barrier. + * * The wave reductions are libr3d's DPP16 and v_permlanex16 lane exchanges (r3d_common.h), + * which is what libr4d's butterflies lower to and what `__shfl_xor` costs on RDNA3 (a + * ds_bpermute and a dscnt wait). Same lanes, same order, so the merge is bit-identical to + * libr4d's: the top-2 merge over 16, 8, 4, 2, 1, the group max and the expert max are the r4d + * kernel's, key for key, so a tied row, a row with a -0 rank and a row with a NaN rank land on + * the same bytes in both backends. The scores are staged in LDS and the kept sum read back lane + * by lane (the libr3d router's idiom) instead of a gather shuffle per key. + * + * No matrix instruction: this is a selection over at most 512 f32, bandwidth-bound and + * register-resident. The only LDS is a small static stage -- `n_expert` scores plus 32 kept sums, + * 2.2 KiB at the widest row, far under RDNA3's 64 KiB -- so there is no dynamic LDS to size + * against the cap in the launcher. + */ +#include + +#include +#include + +#include "r3d.h" +#include "r3d_args.h" +#include "r3d_common.h" +#include "r3d_launch.h" + +#define R3D_BARRIER() do { __syncthreads(); asm volatile("" ::: "memory"); } while (0) + +namespace { + +/* (order-preserving rank, ~expert) as one 64-bit key: the rank's monotone bits (-0 folded to +0) + * above the complemented expert, so a tie goes to the lower expert. A NaN rank keys 0, which no + * round selects. libr4d's router_rank_key, unchanged. */ +__device__ __forceinline__ unsigned long long r3d_router_rank_key(float rank, uint32_t e) { + uint32_t u = __float_as_uint(rank); + if (u == 0x80000000u) u = 0; + const uint32_t k = (u & 0x80000000u) ? ~u : (u | 0x80000000u); + return rank == rank ? ((unsigned long long)k << 32) | (uint32_t)~e : 0ull; +} + +/* The wave's largest key: the xor butterfly over 16, 8, 4, 2, 1, the halves exchanged as a 64-bit + * shuffle does. Keys are unique (the low half is the expert), so the winner is unique and the + * butterfly's order cannot matter. */ +__device__ __forceinline__ unsigned long long r3d_router_wave_max(unsigned long long b) { + unsigned long long o; + o = r3d_xor_lane_u64<16>(b); + b = b > o ? b : o; + o = r3d_xor_lane_u64<8>(b); + b = b > o ? b : o; + o = r3d_xor_lane_u64<4>(b); + b = b > o ? b : o; + o = r3d_xor_lane_u64<2>(b); + b = b > o ? b : o; + o = r3d_xor_lane_u64<1>(b); + b = b > o ? b : o; + return b; +} + +/* One butterfly round of the two best: the higher head, and the higher of the two tails and the + * lower head. A NaN rank never reaches here -- a lane's own scan drops it on both `>` tests. */ +template +__device__ __forceinline__ void r3d_router_top2_merge(float& t0, float& t1) { + const float o0 = r3d_xor_lane(t0), o1 = r3d_xor_lane(t1); + const float hi = fmaxf(t0, o0), lo = fmaxf(fminf(t0, o0), fmaxf(t1, o1)); + t0 = hi; + t1 = lo; +} + +/* The wave's two best, in the order libr4d's `for (mask = 16; mask; mask >>= 1)` runs them. */ +__device__ __forceinline__ void r3d_router_top2_wave(float& t0, float& t1) { + r3d_router_top2_merge<16>(t0, t1); + r3d_router_top2_merge<8>(t0, t1); + r3d_router_top2_merge<4>(t0, t1); + r3d_router_top2_merge<2>(t0, t1); + r3d_router_top2_merge<1>(t0, t1); +} + +/* One row, one wave, one block. OWN is a template bound because the keys are registers: a + * lane-derived trip count would index them divergently. A tail expert reads address 0 of its row + * and keys absent; it is never stored. */ +template +__global__ __launch_bounds__(kWave) void r3d_router_group_topk_kernel( + const float* __restrict__ logits, const float* __restrict__ bias, int32_t* __restrict__ ids, + float* __restrict__ weights, long lp, long bp, long ip, long wp, uint32_t m, uint32_t ne, + uint32_t k, uint32_t ng, uint32_t kg, int norm, float factor) { + __shared__ float s_score[kWave * OWN]; // the row's p, so a weight is read back, not recomputed + __shared__ float s_sel[kWave]; // the kept p, lane j = round j + const uint32_t lane = threadIdx.x, r = blockIdx.x; + if (r >= m) return; + const uint32_t gs = ne / ng; // experts a group; the shim divided ne by ng exactly + + float p[OWN], rank[OWN]; +#pragma unroll + for (uint32_t i = 0; i < OWN; ++i) { + const uint32_t e = lane + i * kWave, s = e < ne ? e : 0; + p[i] = 1.0f / (1.0f + expf(-logits[(size_t)r * lp + s])); // the reference's sigmoid + rank[i] = e < ne ? p[i] + bias[(size_t)s * bp] : -INFINITY; + s_score[lane * OWN + i] = p[i]; + } + R3D_BARRIER(); + + // The groups, largest sum first: lane g takes group g's two-best sum after the wave merge. + float group = -INFINITY; + for (uint32_t g = 0; g < ng; ++g) { + float t0 = -INFINITY, t1 = -INFINITY; +#pragma unroll + for (uint32_t i = 0; i < OWN; ++i) { + const uint32_t e = lane + i * kWave; + if (e < ne && e / gs == g) { + const float v = rank[i]; + if (v > t0) { + t1 = t0; + t0 = v; + } else if (v > t1) + t1 = v; + } + } + r3d_router_top2_wave(t0, t1); + if (lane == g) group = t0 + t1; + } + const unsigned long long gkey = + lane < ng && group > -INFINITY ? r3d_router_rank_key(group, lane) : 0ull; + + // The kg best groups, by key: bit g of `kept` says group g's experts are selectable. + unsigned kept = 0; + unsigned long long below = ~0ull; + for (uint32_t j = 0; j < kg; ++j) { + const unsigned long long best = r3d_router_wave_max(gkey < below ? gkey : 0ull); + if (best) kept |= 1u << (int)~(uint32_t)best; + below = best; + } + + // Then the top_k of the kept groups' experts, the same rounds on the experts' own keys. + unsigned long long key[OWN]; +#pragma unroll + for (uint32_t i = 0; i < OWN; ++i) { + const uint32_t e = lane + i * kWave; + key[i] = e < ne && ((kept >> (e / gs)) & 1u) ? r3d_router_rank_key(rank[i], e) : 0ull; + } + unsigned long long mine = 0; + below = ~0ull; + for (uint32_t j = 0; j < k; ++j) { + unsigned long long best = 0; +#pragma unroll + for (uint32_t i = 0; i < OWN; ++i) { + const unsigned long long c = key[i] < below ? key[i] : 0ull; + best = c > best ? c : best; + } + best = r3d_router_wave_max(best); + if (lane == j) mine = best; + below = best; + } + + // The weights are the unbias'd scores, summed in round order -- lane order, since lane j parked + // round j's winner -- and the sum is over the kept k, not over the wave. + const uint32_t e = mine ? (uint32_t)~(uint32_t)mine : 0u; + const float chosen = s_score[(e & (kWave - 1)) * OWN + (e >> 5)]; + s_sel[lane] = chosen; + R3D_BARRIER(); + float total = 0.0f; +#pragma unroll + for (uint32_t j = 0; j < kWave; ++j) + if (j < k) total += s_sel[j]; + const float mult = norm ? factor / (total + 1e-20f) : factor; + if (lane < k) { + ids[(size_t)r * ip + lane] = (int32_t)e; + weights[(size_t)r * wp + lane] = chosen * mult; + } + static_assert(sizeof(s_score) + sizeof(s_sel) <= 60 * 1024, + "the row's stage is 2.2 KiB at 512 experts, well under RDNA3's 64 KiB"); +} + +} // namespace + +extern "C" { + +int r3d_rad_router_sigmoid_group_topk(const RadArgs* a, RadStream s) +{ + if (!a || a->n_t < 4) return R3D_NO(RAD_E_INVAL); + const long long ne = r3d_geti_or(a, "n_expert", 0), k = r3d_geti_or(a, "top_k", 0), + ng = r3d_geti_or(a, "n_group", 0), kg = r3d_geti_or(a, "topk_group", 0); + const float factor = (float)r3d_getf(a, "route_scale", 0.0); + const RadTensor* lg = r3d_opt(a, 0); + const RadTensor* bs = r3d_opt(a, 1); + const RadTensor* id = r3d_opt(a, 2); + const RadTensor* w = r3d_opt(a, 3); + if (!r3d_p(lg) || !r3d_p(bs) || !r3d_wp(id) || !r3d_wp(w)) return R3D_NO(RAD_E_INVAL); + if (lg->dtype != RAD_F32 || bs->dtype != RAD_F32 || id->dtype != RAD_I32 || + w->dtype != RAD_F32) + return R3D_NO(RAD_E_DTYPE); + + const long long m = r3d_dim(lg, 0); // the row count of the call, not the band's bound + if (ne < 1 || ne > 512 || k < 1 || k > 32 || ng < 1 || ng > 32 || ne % ng || ne / ng < 2 || + kg < 1 || kg > ng || k > kg * (ne / ng) || !std::isfinite(factor) || factor <= 0 || + lg->rank != 2 || m < 1 || m > 65535 || r3d_dim(lg, 1) != ne || bs->rank != 1 || + r3d_dim(bs, 0) != ne || id->rank != 2 || w->rank != 2 || r3d_dim(id, 0) != m || + r3d_dim(w, 0) != m || r3d_dim(id, 1) != k || r3d_dim(w, 1) != k || + r3d_stride(lg, 1) != 1 || r3d_stride(id, 1) != 1 || r3d_stride(w, 1) != 1 || + r3d_stride(lg, 0) < ne || r3d_stride(id, 0) < k || r3d_stride(w, 0) < k || + r3d_stride(bs, 0) < 1) + return R3D_NO(RAD_E_SHAPE); + + const int norm = (int)(r3d_geti_or(a, "norm", 0) != 0); + const long lp = r3d_stride(lg, 0), bp = r3d_stride(bs, 0), ip = r3d_stride(id, 0), + wp = r3d_stride(w, 0); + dim3 grid((unsigned)m), blk(kWave); // one wave a row, one block a row (gfx1102) + const float* lgd = (const float*)r3d_p(lg); + const float* bpd = (const float*)r3d_p(bs); + int32_t* ipd = (int32_t*)r3d_wp(id); + float* wpd = (float*)r3d_wp(w); + // 9 keys a lane to 288 experts (DeepSeek-V3's 256, GLM-5.3's 288), 16 to 512; libr4d's split. + if (ne <= (long long)9 * kWave) + R3D_KLAUNCH(r3d_router_group_topk_kernel<9>, grid, blk, (hipStream_t)s, lgd, bpd, ipd, + wpd, lp, bp, ip, wp, (uint32_t)m, (uint32_t)ne, (uint32_t)k, (uint32_t)ng, + (uint32_t)kg, norm, factor); + else + R3D_KLAUNCH(r3d_router_group_topk_kernel<16>, grid, blk, (hipStream_t)s, lgd, bpd, ipd, + wpd, lp, bp, ip, wp, (uint32_t)m, (uint32_t)ne, (uint32_t)k, (uint32_t)ng, + (uint32_t)kg, norm, factor); + return (int)hipGetLastError(); +} + +} // extern "C" diff --git a/libr3d/r3d_rows.cpp b/libr3d/r3d_rows.cpp index 3c4640d1..c4cb2fc4 100644 --- a/libr3d/r3d_rows.cpp +++ b/libr3d/r3d_rows.cpp @@ -184,6 +184,8 @@ static const RadOperandSpec oRouterSigmoid[] = { { "logits", RAD_OPD_IN, 0 }, { "weights", RAD_OPD_OUT, 0 } }; static const RadParamSpec pRouterSigmoid[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), P_INT("norm"), P_F64("route_scale"), P_STR("dtype") }; +static const RadParamSpec pRouterSigmoidGroup[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), + P_INT("n_group"), P_INT("topk_group"), P_INT("norm"), P_F64("route_scale"), P_STR("dtype") }; static const RadOperandSpec oGatedQuant[] = { { "gate_up", RAD_OPD_IN, 0 }, { "q", RAD_OPD_OUT, 0 }, { "scale", RAD_OPD_OUT, 0 }, @@ -227,6 +229,9 @@ static const RadOperandSpec oDequant[] = { { "q", RAD_OPD_IN, 0 }, { "scale", RA /* --- gemm --- */ static const RadParamSpec pGemm[] = { P_INT("M"), P_INT("N"), P_INT("K"), P_STR("dtype") }; + +/* pGemmNt/oGemmNt (gemm_nt_f32) reuse pGemm/oGemm above: the pair is byte-identical to + * libr4d's, and the loader compares positionally. */ static const RadOperandSpec oGemm[] = { { "a", RAD_OPD_IN, 0 }, { "b", RAD_OPD_WEIGHT, 0 }, { "y", RAD_OPD_OUT, 0 } }; @@ -313,6 +318,22 @@ static const RadOperandSpec oGdnConvUpdate[] = { { "x", RAD_OPD_IN, 0 }, { "k", RAD_OPD_OUT, 0 }, { "v", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pPleConv[] = { P_INT("M"), P_INT("n"), P_INT("width"), + P_INT("dilation"), P_STR("dtype") }; +/* The optionals unite gdn_conv_prep's and gdn_conv_update's contracts: `has_init` serves + * prefill, `num_accepted` decode. */ +static const RadOperandSpec oPleConv[] = { + { "x", RAD_OPD_IN, 0 }, + { "w", RAD_OPD_WEIGHT, 0 }, + { "conv_state", RAD_OPD_INOUT, 0 }, + { "cu", RAD_OPD_IN, 0 }, + { "resid", RAD_OPD_IN, 1 }, + { "cache_idx", RAD_OPD_IN, 1 }, + { "has_init", RAD_OPD_IN, 1 }, + { "num_accepted", RAD_OPD_IN, 1 }, + { "y", RAD_OPD_OUT, 0 }, +}; + static const RadParamSpec pExpertScale[] = { P_INT("M"), P_INT("n_expert"), P_INT("top_k"), P_STR("dtype") }; static const RadOperandSpec oExpertScale[] = { { "ids", RAD_OPD_IN, 0 }, @@ -394,6 +415,18 @@ static const RadOperandSpec oGdnRecurrent[] = { { "q", RAD_OPD_IN, 0 }, { "o", RAD_OPD_OUT, 0 }, { "o_q", RAD_OPD_OUT, 1 }, { "o_scale", RAD_OPD_OUT, 1 } }; +static const RadParamSpec pKdaUpdate[] = { + P_INT("M"), P_INT("heads"), P_INT("head_k"), P_INT("head_v"), P_F64("lower_bound"), + P_F64("scale"), P_F64("l2_eps"), P_STR("mode"), P_STR("dtype"), + P_STRO("state_form"), +}; +static const RadOperandSpec oKdaUpdate[] = { + {"q", RAD_OPD_IN, 0}, {"k", RAD_OPD_IN, 0}, {"v", RAD_OPD_IN, 0}, + {"a", RAD_OPD_IN, 0}, {"b", RAD_OPD_IN, 0}, {"A_log", RAD_OPD_WEIGHT, 0}, + {"dt_bias", RAD_OPD_WEIGHT, 0}, {"state", RAD_OPD_INOUT, 0}, {"state_idx", RAD_OPD_IN, 0}, + {"cu", RAD_OPD_IN, 0}, {"num_accepted", RAD_OPD_IN, 1}, {"has_init", RAD_OPD_IN, 1}, + {"o", RAD_OPD_OUT, 0}, +}; /* gdn_conv_recurrent_update: the decode conv and the recurrent update as one kernel, the * convolution's operands then the recurrence's minus q, k and v (never materialised). */ @@ -487,6 +520,21 @@ static const RadOperandSpec oAttnPaged[] = { { "cu_seqlens", RAD_OPD_IN, 1 }, { "out", RAD_OPD_OUT, 0 } }; +static const RadParamSpec pMlaProject[] = { P_INT("M"), P_INT("heads"), P_INT("head_dim"), + P_INT("latent_dim"), P_STR("mode"), P_STR("dtype") }; + +static const RadParamSpec pMlaAttnPaged[] = { P_INT("M"), P_INT("heads"), P_INT("latent_dim"), + P_INT("rope_dim"), P_INT("block_size"), P_F64("scale"), + P_STR("dtype") }; +static const RadOperandSpec oMlaAttnPaged[] = { { "q", RAD_OPD_IN, 0 }, + { "q_rope", RAD_OPD_IN, 1 }, + { "kv", RAD_OPD_IN, 0 }, + { "block_table", RAD_OPD_IN, 0 }, + { "seqused", RAD_OPD_IN, 0 }, + { "cu_seqlens", RAD_OPD_IN, 0 }, + { "gate", RAD_OPD_IN, 1 }, + { "out", RAD_OPD_OUT, 0 } }; + /* The row's top-R over a vocabulary slice, and the sampler's stages. The history stages write this * rank's columns and read global ids, so they carry `vocab_off`; the narrowing stages work on the * candidate set the top-k produced and need only its width. */ @@ -693,6 +741,9 @@ static const RadOpSchema kSchemas[] = { "y = code * scale, the read of a container's own quantised weight: `group`-wide f32 " "scales against E4M3, E5M2 or int8 codes."), SCHEMA("gemm_nt", pGemm, oGemm, "y[M,N] = a[M,K] @ b[N,K]^T, f32 accumulate."), + SCHEMA("gemm_nt_f32", pGemm, oGemm, + "BF16 activations times F32 weights, F32 accumulation and output; preserves routing " + "and index gate precision."), SCHEMA("gemm_nt_q", pGemmQ, oGemmQ, "The same product against a quantised weight. `dtype` names the scheme: fp8a16 a bf16 " "activation against E4M3 codes, fp8a8 quant_act_fp8's codes and scales, i8a8 int8 on " @@ -728,6 +779,22 @@ static const RadOpSchema kSchemas[] = { "conv-state buffer, read at the slot the last accepted token left and rewritten " "shifted by one; writes q, k and v in their own layouts."), + SCHEMA("ple_conv", pPleConv, oPleConv, + "y[t] = resid[t] + silu(sum_j w[c][j] * x[t - (width-1-j)*dilation]), a DEPTHWISE " + "CAUSAL convolution whose taps are `dilation` apart -- at width 4 and dilation 3 they " + "are 9, 6, 3 and 0 timesteps back, so the history a sequence carries is " + "(width-1)*dilation and not width-1. The state is [n_slots, n, state_len] with slot i " + "holding the value at relative position i - (width-1)*dilation, and `has_init` 0 means " + "that window is ZEROS rather than whatever the slot last held. `num_accepted` shifts " + "the READ offset within a deeper window and marks a decode step: the window is then " + "rewritten as gdn_conv_update rewrites its own -- the history read shifted down by one, " + "then every input of the step -- so a next step that kept k tokens reads at k - 1. " + "Absent, every token commits: the read is at offset zero and the last " + "(width-1)*dilation inputs land at offset zero, which is the prefill chunk. " + "`resid` absent drops the add and leaves the plain convolution."), + SCHEMA("kda_update", pKdaUpdate, oKdaUpdate, + "Bounded per-channel KDA recurrence. verify stores candidate states; prefill commits final state. " + "Absolute cu offsets, accepted-prefix read slot, optional cold initialization, no output norm."), SCHEMA("gdn_recurrent_update", pGdnRecurrent, oGdnRecurrent, "The gated-delta-net recurrent state update at decode: g = -exp(A_log) softplus(a + " "dt_bias), beta = sigmoid(b), q/k l2-normalised, S *= e^g, u = beta (v - S k), S += u " @@ -760,6 +827,10 @@ static const RadOpSchema kSchemas[] = { "n_expert logits, then the sort over this rank's n_local slice. expert_w is the " "selection output the sort reads."), + SCHEMA("router_sigmoid_group_topk", pRouterSigmoidGroup, oRouterSigmoid, + "Group-limited sigmoid routing: groups rank by the sum of their two best p + bias, " + "selection runs over the topk_group best groups; correction bias selects, original " + "scores weight."), SCHEMA("router_sigmoid_topk", pRouterSigmoid, oRouterSigmoid, "The GLM-style router: scores = sigmoid(logits), the selection on scores + bias, the " "kept weights the scores scaled by route_scale (renormalised if `norm`). Ties to the " @@ -793,6 +864,12 @@ static const RadOpSchema kSchemas[] = { "`seqused` its length. `gqa` is the head ratio; `causal` and `window` are the mask; " "`scale` is 1/sqrt(head_dim) unless the graph says otherwise. k_descale and v_descale " "come with an fp8 cache, cu_seqlens with a packed prefill."), + SCHEMA("mla_attn_paged", pMlaAttnPaged, oMlaAttnPaged, + "Dense causal latent attention over a paged cache whose token row is the latent then the " + "rotated key part: score = scale * (q . latent + q_rope . rope), value = the latent; " + "sequences as in attn_paged. With `gate`, out = bf16(bf16(out) * bf16(sigmoid(gate[head])))."), + SCHEMA("mla_project", pMlaProject, oGemm, + "Per-head query absorption or value expansion through the shared [head,(K|V),latent] BF16 matrix."), SCHEMA("row_topk", pRowTopk, oRowTopk, "Exact per-row top-R, descending, ties to the lower column. `vocab_off` shifts every " "column reported, so a rank's slice reports global ids; `pairs` is the [M, R, 2] plane an " @@ -1194,11 +1271,13 @@ static const RadConstraint cActSigmoid[] = { C_IN("act", "sigmoid"), C_IN("dtype static const RadConstraint cFillBf16[] = { C_IN("dtype", "bf16") }; static const RadConstraint cFillF32[] = { C_IN("dtype", "f32") }; static const RadConstraint cDequantW4[] = { C_DIV("N", 16), C_DIV("K", 64) }; -static const RadConstraint cRowTopkMerge[] = { C_GE("R", 1), C_LE("R", 32) }; +static const RadConstraint cRowTopkMerge[] = { C_GE("R", 1), C_LE("R", 32), C_IN("dtype", "f32") }; static const RadConstraint cNgramIds[] = { C_GE("ngram", 2), C_LE("ngram", 8) }; + static const RadConstraint cGemmQBias[] = { C_IN("dtype", "fp8a8"), C_GE("M", 1), C_LE("M", 16) }; static const RadConstraint cGemmQShort[] = { C_IN("dtype", "fp8a8"), C_GE("M", 1), C_LE("M", 64) }; static const RadConstraint cMoeGemmQMod4[] = { C_GE("n_expert", 4) }; + static const RadConstraint cFillI32[] = { C_IN("dtype", "i32") }; static const RadConstraint cFillI64[] = { C_IN("dtype", "i64") }; @@ -1219,6 +1298,22 @@ static const RadConstraint cKvFp8[] = { C_IN("kv_dtype", "fp8_e4m3"), C_DIV("he C_DIV("block_size", 16) }; static const RadConstraint cKvF16[] = { C_IN("kv_dtype", "f16"), C_DIV("head_dim", 2), C_DIV("block_size", 16) }; +/* head_dim is 128 or 256 (the launcher refuses anything else); the constraint system has no + * int-set form, so the row states the range and the kernel enforces the set. */ +static const RadConstraint cMlaProject[] = { C_GE("M", 1), + C_LE("M", 65535), + C_GE("heads", 1), + C_LE("heads", 64), + C_GE("head_dim", 128), + C_LE("head_dim", 256), + C_EQ("latent_dim", 512), + C_IN("mode", "absorb expand"), + C_IN("dtype", "bf16") }; +static const RadConstraint cMlaAttnPaged[] = { + C_GE("M", 1), C_LE("M", 65535), C_EQ("latent_dim", 512), C_EQ("rope_dim", 64), + C_GE("heads", 1), C_LE("heads", 64), C_GE("block_size", 1), C_LE("block_size", 256), + C_IN("dtype", "bf16") +}; static const RadConstraint cEmbed[] = { C_IN("dtype", "bf16"), C_DIV("n_embd", 2) }; @@ -1275,6 +1370,10 @@ static const RadConstraint cDequantI8[] = { C_IN("dtype", "i8"), C_EQ("group", * through LDS pays. K even because the inner loop consumes pairs. N has no bound: a wave covering N * handles the tail, and feed-forward and vocabulary widths (11008, 14336, 128256, a checkpoint's * `intermediate_size`) vary. */ +static const RadConstraint cGemmNtF32[] = { C_GE("M", 1), C_LE("M", 65535), + C_GE("N", 1), C_LE("N", 512), + C_GE("K", 1), C_LE("K", 16384), + C_IN("dtype", "bf16") }; static const RadConstraint cGemmM16[] = { C_IN("dtype", "bf16"), C_GE("M", 1), C_LE("M", 16), C_DIV("K", 2), C_GE("N", 1) }; static const RadConstraint cGemmM16F16[] = { C_IN("dtype", "f16"), C_GE("M", 1), C_LE("M", 16), @@ -1300,8 +1399,20 @@ static const RadConstraint cGdnConvW4[] = { C_GE("M", 1), C_EQ("head_k", 128), C C_EQ("conv_width", 4) }; static const RadConstraint cGdnConvUpdW4[] = { C_GE("q_len", 1), C_EQ("head_k", 128), C_EQ("head_v", 128), C_EQ("conv_width", 4) }; +/* PLE's convolution. The kernel bounds (width-1)*dilation, the state write-back's register + * window, at 16; a constraint cannot express a product, so these are the tightest separate caps + * admitting every combination under it. */ +static const RadConstraint cPleConv[] = { C_IN("dtype", "bf16"), C_GE("width", 1), + C_LE("width", 5), C_GE("dilation", 1), + C_LE("dilation", 4) }; static const RadConstraint cGdnRecurrent[] = { C_GE("q_len", 1), C_EQ("head_k", 128), C_EQ("head_v", 128) }; +static const RadConstraint cKdaUpdate[] = { + C_GE("M", 1), C_GE("heads", 1), C_LE("heads", 65535), + C_EQ("head_k", 128), C_EQ("head_v", 128), C_IN("mode", "prefill verify"), + C_IN("dtype", "bf16"), +}; + static const RadConstraint cGdnConvRecurrent[] = { C_GE("q_len", 1), C_EQ("head_k", 128), C_EQ("head_v", 128), C_EQ("conv_width", 4) }; static const RadConstraint cExpertScaleBf16[] = { C_IN("dtype", "bf16"), C_GE("top_k", 1), @@ -1332,6 +1443,11 @@ static const RadConstraint cRouterTopkScatter[] = { C_GE("M", 1), C_GE("n_expert static const RadConstraint cRouterSigmoid[] = { C_GE("M", 1), C_GE("n_expert", 1), C_GE("top_k", 1), C_LE("n_expert", 512), C_IN("dtype", "bf16") }; +static const RadConstraint cRouterSigmoidGroup[] = { C_GE("M", 1), C_LE("M", 65535), + C_GE("n_expert", 1), C_LE("n_expert", 512), + C_GE("top_k", 1), C_LE("top_k", 32), + C_GE("n_group", 1), C_LE("n_group", 32), + C_IN("dtype", "f32") }; static const RadConstraint cMoeGemmBf16[] = { C_IN("dtype", "bf16"), C_GE("n_expert", 1), C_GE("top_k", 1) }; /* The vocabulary projection has no `dtype` constraint because its band carries no `dtype` key: the @@ -1976,6 +2092,21 @@ static const RadKernelInfo kKernels[] = { [](const RadArgs* a) -> int64_t { return gemm_scratch(a->p, a->n_p); }, nullptr, nullptr, r3d_shape_gemm_nt }, +/* ------------------------------------------------------------------ r3d_gemm_nt_f32.hip + * + * The router's F32 projection: a bf16 activation against an f32 weight, f32 out, no narrowing. + * One wave R rows by C columns, lane l folding k = l, l+32, ... with fmaf and the xor butterfly; + * the tile form its rule picks for M, every form byte-identical. + */ +{ "gemm_nt_f32_bf16", "gemm_nt_f32", "gemm", + "F32 routing and index gate projection", + "N<=512, K<=16384; pitched rows", + "bf16 input, f32 weights and output", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cGemmNtF32), NOTUNE, + nullptr, nullptr, r3d_rad_gemm_nt_f32, nullptr, nullptr, nullptr, + r3d_shape_gemm_nt_f32 }, + /* ------------------------------------------------------------------ r3d_gemm_w4a16_nt_m64.hip * * The 4-bit weight against an f16 activation, at the verify and small-prefill heights: the @@ -2122,6 +2253,14 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, nullptr, nullptr, nullptr }, +{ "ple_conv_bf16", "ple_conv", "norm", + "PLE's dilated depthwise conv, silu and residual add; one thread a channel", + "width up to 5 and dilation up to 4 -- (width-1)*dilation is a register window", + "bf16 activations, weights and conv state; i32 cu, slots, has_init and num_accepted", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cPleConv), NOTUNE, + nullptr, nullptr, r3d_rad_ple_conv, nullptr, nullptr, nullptr, nullptr }, + { "expert_scale_bf16", "expert_scale", "moe", "Each routing weight times its expert's own per-expert scale, in place", "the router's renormalised top-k weight scaled by the [n_expert] table, an out-of-table id " @@ -2168,6 +2307,14 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r3d_rad_router_sigmoid_topk, nullptr, nullptr, nullptr, nullptr, nullptr }, +{ "moe_router_sigmoid_group_topk_f32", "router_sigmoid_group_topk", "moe", + "group-limited sigmoid correction-bias routing, one wave a row", + "experts <=512, groups <=32, top_k<=32", + "f32 logits, bias and weights; i32 ids", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cRouterSigmoidGroup), NOTUNE, + nullptr, nullptr, r3d_rad_router_sigmoid_group_topk, nullptr, nullptr, nullptr, + r3d_shape_router_sigmoid_group_topk }, { "moe_scatter_small", "moe_scatter", "moe", "The routed slots' stable counting sort", @@ -2328,19 +2475,6 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }, - { "ngram_ids_i32", "ngram_ids", "vocab", - "The hashed row ids of the Per-Layer Embedding: mixed(k) = XOR of t_s * mult[s], " - "ids[h] = mixed % vocab_sizes[h] + offsets[h]", - "One thread a token, looping its heads; n-gram shifts with EOS walk; 64-bit wrapping " - "multiply and floor-mod; ngram <= 8, heads divisible by (ngram-1)", - "i32 tok, i32 state, i32 cu, i64 mult, i64 vsz, i64 off, i32 ids; " - "optional i32 cidx, hini, nacc, ahead", - RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, - ROW(cNgramIds), NOTUNE, - nullptr, nullptr, r3d_rad_ngram_ids, - nullptr, nullptr, nullptr, - nullptr, nullptr, nullptr }, - { "gemm_nt_q_bias_fp8a8_m16", "gemm_nt_q_bias", "gemm", "The narrow fp8 GEMM with a per-column bias epilogue: y = a @ b^T + bias", "M <= 16, K a multiple of the block; fp8a8 codes and scales, bf16 bias and output; " @@ -2376,7 +2510,23 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, nullptr, nullptr, nullptr, nullptr }, - /* ------------------------------------------------------------------ r3d_gdn_recurrent_update_k128_v128.hip + /* ------------------------------------------------------------------ r3d_kda_update.hip + * + * GLM's per-channel KDA recurrence over a paged f32 state cache: the decay from the softplus- + * limited gate, the l2-normalised q and k, the delta-rule step and o = S q per token, with the + * speculative candidate snapshots. The state never touches LDS: a wave owns four value rows and + * keeps each row's 128 state elements in four registers a lane, so the RDNA3 64 KiB stage is not + * in play. + */ +{ "kda_update_k128_v128_bf16", "kda_update", "gdn", + "per-channel KDA recurrence and candidate rollback", + "heads 1..65535, K=V=128, prefill and verify", + "bf16 activations, f32 gates and state", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, + ROW(cKdaUpdate), NOTUNE, + nullptr, nullptr, r3d_rad_kda_update, nullptr, nullptr, nullptr, r3d_shape_kda_update }, + +/* ------------------------------------------------------------------ r3d_gdn_recurrent_update_k128_v128.hip * * The gated-delta-net recurrent state update at decode: the per-token state step against a paged * fp32 state cache, the state in registers (one thread per v row and half its k range), the @@ -2640,6 +2790,20 @@ static const RadKernelInfo kKernels[] = { r3d_shape_attn_paged }, +{ "mla_project_bf16", "mla_project", "attn", "per-head absorbed MLA projections", + "head_dim 128 or 256, latent_dim=512; pitched tensors", "bf16 input, weights and output; fp32 arithmetic", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cMlaProject), NOTUNE, + nullptr, nullptr, r3d_rad_mla_project, nullptr, nullptr, nullptr, + r3d_shape_mla_project }, + +{ "mla_attn_paged_bf16", "mla_attn_paged", "attn", + "dense causal latent attention with a rotary part, a wave a (row, head), split history", + "latent_dim=512, rope_dim=64, heads<=64, block_size<=256; one page table a sequence", + "bf16 Q/rotary/cache/gate/output, f32 softmax and partials", + RAD_DOMAIN_DEVICE, R3D_PRIO_ONLY, ROW(cMlaAttnPaged), NOTUNE, + nullptr, nullptr, r3d_rad_mla_attn_paged, r3d_rad_mla_attn_paged_scratch, nullptr, nullptr, + r3d_shape_mla_attn_paged }, + /* ------------------------------------------------------------------ r3d_sample_f32.hip * * The sampler's spine: the row's top-R and the stages that turn its candidate plane into one token. diff --git a/libr3d/r3d_shapes.cpp b/libr3d/r3d_shapes.cpp index e9ae767e..3dd5809f 100644 --- a/libr3d/r3d_shapes.cpp +++ b/libr3d/r3d_shapes.cpp @@ -277,6 +277,27 @@ int r3d_shape_kv_store(const RadParam* p, int n_p, int operand, RadOpdDesc* out) /* x[r] = wte[ids[r] - vocab_offset]. Ids are global, so the draw's bound is `vocab_offset + n_vocab`: * under a shard the draw crosses the slice boundary and exercises the zero-row path. */ +/* The KDA recurrence (r3d_kda_update.hip). The state cache's slot axis is the step's candidate + * count plus one, and `state_idx` draws inside it, uniquely per sequence. */ +int r3d_shape_kda_update(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const char* form = gs(p, n_p, "state_form"); + if (form && !std::strcmp(form, "anchor")) return RAD_E_UNSUPPORTED; + const int64_t M = gi(p, n_p, "M", 0), H = gi(p, n_p, "heads", 0); + const int64_t K = gi(p, n_p, "head_k", 0), V = gi(p, n_p, "head_v", 0); + const uint32_t D = act_dt(p, n_p); + const char* mode = gs(p, n_p, "mode"); + const int64_t history = (mode && !std::strcmp(mode, "verify")) ? M : 1; + const RadOpdDesc l[] = { + opd(D, M, H, K), opd(D, M, H, K), opd(D, M, H, V), opd(D, M, H, K), opd(D, M, H), + opd((uint32_t)RAD_F32, H), opd((uint32_t)RAD_F32, H * K), + opd((uint32_t)RAD_F32, history + 1, H, V, K), + opd_idx(1, history + 1, -1, RAD_OPD_F_IDX_UNIQUE, history), + opd_idx(2, M, -1, RAD_OPD_F_IDX_CU), + opd_idx(1, 0, 1), opd_idx(1, 0, 1), opd(D, M, H, V), + }; + R3D_PICK(l); +} + int r3d_shape_embed_lookup(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const int64_t M = gi(p, n_p, "M", 0); const int64_t ne = gi(p, n_p, "n_embd", 0); @@ -504,6 +525,15 @@ int r3d_shape_gemm_nt(const RadParam* p, int n_p, int operand, RadOpdDesc* out) const RadOpdDesc list[] = { opd(D, M, K), opd(D, N, K), opd(D, M, N) }; /* a, b, y */ R3D_PICK(list); } +/* y[M,N] = a[M,K] @ b[N,K]^T with an F32 weight and output: the router's logits and the index + * gates, the row's own dtype. */ +int r3d_shape_gemm_nt_f32(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), K = gi(p, n_p, "K", 0); + const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, K), opd((uint32_t)RAD_F32, N, K), + opd((uint32_t)RAD_F32, M, N) }; /* a, b, y */ + R3D_PICK(list); +} + /* The vocabulary projection, transcribed from ref_logits_gemm_shape: x [M, n_embd] and the head * [n_vocab, n_embd] in the activation's dtype, logits in f32 because every sampler stage reads @@ -708,6 +738,42 @@ int r3d_shape_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* ou }; R3D_PICK(list); } +/* The absorbed MLA projection (r3d_mla_project.hip): a[M, heads, head_dim|latent] against the + * shared [heads, 2*head_dim, latent] weight, absorb or expand. */ +int r3d_shape_mla_project(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), h = gi(p, n_p, "heads", 0), d = gi(p, n_p, "head_dim", 0), + l = gi(p, n_p, "latent_dim", 0); + const char* mode = gs(p, n_p, "mode"); + const bool absorb = mode && !std::strcmp(mode, "absorb"), + expand = mode && !std::strcmp(mode, "expand"); + if (!absorb && !expand) return RAD_E_UNSUPPORTED; + const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, h, absorb ? d : l), + opd((uint32_t)RAD_BF16, h * 2 * d, l), + opd((uint32_t)RAD_BF16, M, h, absorb ? l : d) }; + R3D_PICK(list); +} + +/* The paged latent attention (r3d_mla_attn_paged.hip): the cache row is the latent then the + * rotated key part; `block_table` draws its page indices, `seqused` the context so far, and + * `cu_seqlens` the [0, M+1] cumulative form. */ +int r3d_shape_mla_attn_paged(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), h = gi(p, n_p, "heads", 0), L = gi(p, n_p, "latent_dim", 0), + R = gi(p, n_p, "rope_dim", 0), bs = gi(p, n_p, "block_size", 0); + if (M <= 0 || h <= 0 || L <= 0 || R <= 0 || bs <= 0) return RAD_E_UNSUPPORTED; + int64_t ctx = gi(p, n_p, "ctx", 0); + if (ctx < M) ctx = M; + const int64_t blocks = (ctx + bs - 1) / bs; + const RadOpdDesc list[] = { opd((uint32_t)RAD_BF16, M, h, L), + opd((uint32_t)RAD_BF16, M, h, R), + opd((uint32_t)RAD_BF16, blocks, 1, bs, L + R), + opd_idx(1, blocks, -1, 0, blocks), + opd_idx(1, 0, ctx), + opd_idx(2, M + 1, -1, (uint32_t)RAD_OPD_F_IDX_CU), + opd_none(), + opd((uint32_t)RAD_BF16, M, h, L) }; + R3D_PICK(list); +} + /* Exact per-row top-R. `pairs` packs an int32 id's bits in the first slot beside its value, in an * f32 plane. */ @@ -721,6 +787,22 @@ int r3d_shape_row_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) }; /* x, idx, val, pairs */ R3D_PICK(list); } +/* Group-limited sigmoid routing: the group form of router_sigmoid_topk. The geometry's bounds are + * the shim's: `n_expert` 1..512, `n_group` 1..32 dividing the experts by at least two, + * `topk_group` a group count, `top_k` inside the kept groups' experts. f32 operands, as the row's + * constraints; `ids` is drawn over `n_expert`. (libr4d's r4d_shape_router_sigmoid_group_topk.) */ +int r3d_shape_router_sigmoid_group_topk(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { + const int64_t M = gi(p, n_p, "M", 0), ne = gi(p, n_p, "n_expert", 0), k = gi(p, n_p, "top_k", 0); + const int64_t ng = gi(p, n_p, "n_group", 0), kg = gi(p, n_p, "topk_group", 0); + if (ne <= 0 || ne > 512 || k <= 0 || ng <= 0 || ng > 32 || ne % ng || ne / ng < 2 || kg <= 0 || + kg > ng || k > kg * (ne / ng)) + return RAD_E_UNSUPPORTED; + const uint32_t D = act_dt(p, n_p); + const RadOpdDesc list[] = { opd(D, M, ne), opd((uint32_t)RAD_F32, ne), + opd_idx(M, ne, -1, 0, k), opd(D, M, k) }; + R3D_PICK(list); +} + int r3d_shape_sample_argmax(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { int64_t M = 0, nv = 0; diff --git a/libr4d/CMakeLists.txt b/libr4d/CMakeLists.txt index 3ad8c635..94af5b2a 100644 --- a/libr4d/CMakeLists.txt +++ b/libr4d/CMakeLists.txt @@ -104,6 +104,8 @@ set(R4D_UNITS # Vision tower ops: layer norm, the learned-grid position embedding, and the biased GEMM with # activation and residual fused into its store. "r4d_vit_bf16|" + # Muse Glimmer's vision-tower coordinate ops: grid_embed_pad, window_order. + "r4d_vit_muse|" # The same biased GEMM over f32 operands (a diffusion transformer's patch projections and heads, # a video decoder's 1x1 projections), on the f32 FMA tile r4d_audio's f32 convolutions share. "r4d_gemm_f32_nt_bias|" diff --git a/libr4d/r4d_attn_dense_bf16.hip b/libr4d/r4d_attn_dense_bf16.hip index 17d6a494..d1707563 100644 --- a/libr4d/r4d_attn_dense_bf16.hip +++ b/libr4d/r4d_attn_dense_bf16.hip @@ -358,6 +358,12 @@ extern "C" int r4d_attn_dense_bf16(const void* q, const void* k, const void* v, return r4d_attn_dense_launch<80, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, n_head_kv, scale, window, wright, block, cdiv, causal, q_ld, k_ld, v_ld, o_ld, s); + /* h96 gqa1: Muse Glimmer's vision tower, 16 heads of 96, bidirectional over segments. The + * h80 shape (8 query blocks of 16, K/V tiles of 64) with six 16-wide k-tiles a head. */ + if (head_dim == 96 && gqa == 1) + return r4d_attn_dense_launch<96, 1, 8, 1, 64>(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, + n_head_kv, scale, window, wright, block, + cdiv, causal, q_ld, k_ld, v_ld, o_ld, s); #define R4D_DENSE(HD, G, NQB, DS, T) \ return r4d_attn_dense_launch(q, k, v, o, cu_seqlens, num_seqs, max_seqlen, \ n_head_kv, scale, window, wright, block, \ diff --git a/libr4d/r4d_attn_paged_window.hip b/libr4d/r4d_attn_paged_window.hip index f69522b1..bf087aa0 100644 --- a/libr4d/r4d_attn_paged_window.hip +++ b/libr4d/r4d_attn_paged_window.hip @@ -30,8 +30,8 @@ * k_descale / v_descale per (sequence, kv head), absent = 1 * attn_paged_sink: `sinks` [query heads] f32, one logit a head in the scaled-score domain, in * the softmax's maximum and denominator and with no value (LiLiCorr's drafter). Folded in where - * a row is normalised: the unsplit kernel's store and the merge. The WMMA kernel takes none, - * so a sink launch stays scalar. + * a row is normalised: the unsplit kernel's store, the merge, and the WMMA prefill kernel's + * running max and denominator. A decode-sized sink launch stays scalar. * * Paged layout: kv_cache[n_blocks, kv_heads, 16, 2*head_dim], K then V per slot, so one block of * one KV head is a contiguous run of 16 * 2 * head_dim elements; a key tile is one or two runs, @@ -732,7 +732,12 @@ __global__ __launch_bounds__(kWThreads) void attn_wmma_kernel(AttnArgs A) { for (int mc = 0; mc < kDQ / 16; ++mc) #pragma unroll for (int e = 0; e < 8; ++e) oacc[mc][e] = 0.0f; - float m = -__builtin_inff(), l = 0.0f; + /* The learned sink is a key with no value: it joins the running max and the denominator + * (log2 domain). Keys are split across lane and lane^16, so only lane h=0 seeds the sink's + * weight of one; the final lt2 adds the two lanes. */ + const float sink = A.sinks ? A.sinks[kh * GQA + g] * 1.4426950408889634f + : -__builtin_inff(); + float m = sink, l = (A.sinks && h == 0) ? 1.0f : 0.0f; /* ---- the key tiles, one paged block each, prefetched one ahead through registers */ uint4 pk[KPT], pv[VPT][2]; @@ -1249,7 +1254,7 @@ static int launch_attn(const RadArgs* a, RadStream stream, bool sink = false) { rows >= n_seq * (kWmmaMinQ / 2); const bool aligned = rad_ptr_aligned(q->data, 16) && rad_ptr_aligned(o->data, 16) && (q_rs | q_hs | o_rs | o_hs) % 8 == 0; - if (shaped && aligned && !sk) { + if (shaped && aligned) { constexpr int BQW = WGeo::R / GQA; int64_t ntw = 0, tpsw = 0; if (!cu) { @@ -1282,6 +1287,7 @@ static int launch_attn(const RadArgs* a, RadStream stream, bool sink = false) { W.window = (int)window; W.shared_window = SHARED; W.ahead = FWD ? 1 : 0; + W.sinks = sk ? (const float*)sk->data : nullptr; W.n_split = 1; R4D_KLAUNCH(R4D_KNAME(attn_wmma_kernel), dim3((unsigned)ntw, (unsigned)kvh, 1u), dim3(kWThreads), (hipStream_t)stream, W); @@ -1304,7 +1310,6 @@ static int launch_attn(const RadArgs* a, RadStream stream, bool sink = false) { !rad_ptr_aligned(a->scratch, 16))) ns = 1; /* never wrong, only slower: the unsplit kernel writes the rows itself */ } - AttnArgs A{}; A.q = (const uint16_t*)q->data; A.q_rs = q_rs; A.q_hs = q_hs; A.kv = (const unsigned char*)kv->data; A.kv_sb = kv->stride[0]; A.kv_sh = kv->stride[1]; @@ -1365,7 +1370,9 @@ extern "C" { int r4d_rad_attn_window_h##HD##_gqa##G##_i8(const RadArgs* a, RadStream s) { \ return r4d_win::launch_attn(a, s); \ } -R4D_WIN_DEF(128, 1) +/* h128 gqa16: Muse Glimmer's sliding layers, 32 query heads over 2 KV heads; the same + * launch_attn the sink variant below already runs at this geometry. */ +R4D_WIN_DEF(128, 1) R4D_WIN_DEF(128, 16) R4D_WIN_DEF(256, 1) R4D_WIN_DEF(256, 2) R4D_WIN_DEF(256, 4) R4D_WIN_DEF(256, 8) R4D_WIN_DEF(512, 1) R4D_WIN_DEF(512, 2) R4D_WIN_DEF(512, 4) R4D_WIN_DEF(512, 8) R4D_WIN_DEF(512, 16) #undef R4D_WIN_DEF diff --git a/libr4d/r4d_audio.hip b/libr4d/r4d_audio.hip index 1e9eeb35..78a76c5d 100644 --- a/libr4d/r4d_audio.hip +++ b/libr4d/r4d_audio.hip @@ -21,8 +21,139 @@ namespace { +__global__ void elu_f32_kernel(const float* x, float* y, int rows, int n, int xp, int yp) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * n) return; + const float v = x[(size_t)(i / n) * xp + i % n]; + y[(size_t)(i / n) * yp + i % n] = v >= 0 ? v : expm1f(v); +} + +/* One workgroup a frame, one thread a candidate at a time. Candidate ties reduce to the + * lower index. The projected residual is only updated after every candidate has read it. */ +__global__ void vq_euclidean_kernel(float* x, const float* cb, int* codes, int n, int bins, + int xp, int cp, int cs) { + const int r = blockIdx.x, t = threadIdx.x; + __shared__ float dist[256]; + __shared__ int pick[256]; + float best = INFINITY; + int id = 0; + for (int k = t; k < bins; k += 256) { + float d = 0; + for (int j = 0; j < n; ++j) { + const float delta = x[(size_t)r * xp + j] - cb[(size_t)k * cp + j]; + d += delta * delta; + } + if (d < best) { best = d; id = k; } + } + dist[t] = best; pick[t] = id; + __syncthreads(); + for (int s = 128; s; s /= 2) { + if (t < s && (dist[t + s] < dist[t] || + (dist[t + s] == dist[t] && pick[t + s] < pick[t]))) { + dist[t] = dist[t + s]; pick[t] = pick[t + s]; + } + __syncthreads(); + } + if (!t) codes[(size_t)r * cs] = pick[0]; + for (int j = t; j < n; j += 256) + x[(size_t)r * xp + j] -= cb[(size_t)pick[0] * cp + j]; +} + constexpr int kT = 256; +/* Small f32 encoder primitives. The generator remains bf16; these keep the released + * reference tokenizer in f32 instead of routing its transformer through a host fallback. */ +__device__ float encoder_sum(float v, float* buf) { + const int t = threadIdx.x; + buf[t] = v; + __syncthreads(); + for (int s = 128; s; s /= 2) { + if (t < s) buf[t] += buf[t + s]; + __syncthreads(); + } + return buf[0]; +} + +__global__ void encoder_layernorm(const float* x, const float* w, const float* bias, + float* y, int n, int xp, int yp, float eps) { + __shared__ float buf[256]; + const int r = blockIdx.x, t = threadIdx.x; + float v = 0; + for (int j = t; j < n; j += 256) v += x[(size_t)r * xp + j]; + const float mean = encoder_sum(v, buf) / n; + __syncthreads(); + v = 0; + for (int j = t; j < n; j += 256) { + const float d = x[(size_t)r * xp + j] - mean; + v += d * d; + } + const float inv = rsqrtf(encoder_sum(v, buf) / n + eps); + __syncthreads(); + for (int j = t; j < n; j += 256) + y[(size_t)r * yp + j] = (x[(size_t)r * xp + j] - mean) * inv * w[j] + (bias ? bias[j] : 0); +} + +__global__ void encoder_gelu(const float* x, float* y, int rows, int n, int xp, int yp) { + const int i = blockIdx.x * blockDim.x + threadIdx.x; + if (i >= rows * n) return; + const float v = x[(size_t)(i / n) * xp + i % n]; + y[(size_t)(i / n) * yp + i % n] = 0.5f * v * (1.0f + erff(v * 0.7071067811865475f)); +} + +__global__ void encoder_rope(float* x, const int* positions, int heads, int pitch, + float theta, float scale) { + const int r = blockIdx.x; + for (int k = threadIdx.x; k < heads * 32; k += 256) { + const int h = k / 32, j = k % 32; + float* row = x + (size_t)r * pitch + h * 64; + const float angle = positions[r] / scale / powf(theta, (2.0f * j) / 64.0f); + float sn, cs; + sincosf(angle, &sn, &cs); + const float a = row[j], b = row[j + 32]; + row[j] = a * cs - b * sn; row[j + 32] = a * sn + b * cs; + } +} + +/* One workgroup a (query, head), <=512 keys. Only the reference encoder uses this f32 + * attention path; its sequence is at most 250 rows, so no quadratic global score plane. */ +__global__ void encoder_attn(const float* q, const float* k, const float* v, const int* cu, + float* out, int heads, int qp, int kp, int vp, int op, + int nseq, int div, int window, float scale) { + __shared__ float score[512], reduce[256]; + const int r = blockIdx.x, h = blockIdx.y, t = threadIdx.x; + int seq = 0; + while (seq + 1 < nseq && cu[seq + 1] <= r * div) ++seq; + const int first = max(cu[seq] / div, window > 0 ? r - window + 1 : 0); + const int last = min(cu[seq + 1] / div, r + 1), count = last - first; + if (count <= 0 || count > 512) return; + float best = -INFINITY; + for (int j = t; j < count; j += 256) { + float dot = 0; + for (int d = 0; d < 64; ++d) + dot += q[(size_t)r * qp + h * 64 + d] * k[(size_t)(first + j) * kp + h * 64 + d]; + score[j] = dot * scale; + best = fmaxf(best, score[j]); + } + reduce[t] = best; + __syncthreads(); + for (int s = 128; s; s /= 2) { + if (t < s) reduce[t] = fmaxf(reduce[t], reduce[t + s]); + __syncthreads(); + } + best = reduce[0]; + __syncthreads(); + float sum = 0; + for (int j = t; j < count; j += 256) { score[j] = expf(score[j] - best); sum += score[j]; } + const float denom = encoder_sum(sum, reduce); + __syncthreads(); + if (t < 64) { + float result = 0; + for (int j = 0; j < count; ++j) + result += score[j] / denom * v[(size_t)(first + j) * vp + h * 64 + t]; + out[(size_t)r * op + h * 64 + t] = result; + } +} + // A window entry's flags (RadAudioGenBatch, RAD_AGEN_F_*), as libref restates them. enum { kFirst = 1, kLast = 8, kJoin = 16 }; @@ -1334,6 +1465,119 @@ extern "C" int r4d_rad_conv_t1d(const RadArgs* a, RadStream s) { /* The f32 rows. The weight is the _f32 layout hooks' (tap-major for conv1d, phase-major with * ceil(k / stride) taps for conv_t1d). The column tile is the narrowest of 128, 64 and 32 that * covers cout in as few workgroups; fewer than 16 channels take the direct conv1d kernel. */ +extern "C" int r4d_rad_encoder_layernorm(const RadArgs* a, RadStream s) { + const auto *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *b = r4d_opt(a, 2), *y = r4d_opt(a, 3); + if (!x || !w || !y || !is_f32(x) || !is_f32(w) || !is_f32(y) || (b && !is_f32(b))) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + if (n < 1 || n > 4096 || r4d_numel(w) != n || (b && r4d_numel(b) != n)) return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0; + const auto xp = r4d_rows_pitch(x, n, &rx), yp = r4d_rows_pitch(y, n, &ry); + if (xp < 0 || yp < 0 || !r4d_contig(w) || (b && !r4d_contig(b))) return R4D_NO(RAD_E_STRIDE); + const float eps = r4d_getf(a, "eps", 1e-5); + if (ry < 1 || ry > 65535 || rx < ry || xp > 0x7fffffffll || yp > 0x7fffffffll || !(eps > 0)) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(encoder_layernorm, dim3((unsigned)ry), dim3(kT), 0, (hipStream_t)s, + (const float*)x->data, (const float*)w->data, b ? (const float*)b->data : nullptr, + (float*)y->data, (int)n, (int)xp, (int)yp, eps); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_encoder_gelu(const RadArgs* a, RadStream s) { + const auto *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y || !is_f32(x) || !is_f32(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + if (n < 1 || n > 0x7fffffffll) return R4D_NO(RAD_E_SHAPE); + long long rx = 0, ry = 0; + const auto xp = r4d_rows_pitch(x, n, &rx), yp = r4d_rows_pitch(y, n, &ry); + if (xp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); + if (ry < 1 || rx < ry || ry > 0x7fffffffll / n || xp > 0x7fffffffll || yp > 0x7fffffffll) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(encoder_gelu, dim3(blocks_for(ry * n)), dim3(kT), 0, (hipStream_t)s, + (const float*)x->data, (float*)y->data, (int)ry, (int)n, (int)xp, (int)yp); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_encoder_rope(const RadArgs* a, RadStream s) { + const auto *x = r4d_opt(a, 0), *p = r4d_opt(a, 1); + if (!x || !p || !is_f32(x) || !is_i32(p)) return R4D_NO(RAD_E_DTYPE); + const long long nh = r4d_geti_or(a, "n_head", 0), nk = r4d_geti_or(a, "n_head_kv", 0); + const char* mode = r4d_gets(a, "mode"); + if (r4d_geti_or(a, "head_dim", 0) != 64 || r4d_geti_or(a, "rotary_dim", 64) != 64 || + nh < 1 || nh > 64 || nk != nh || !mode || std::strcmp(mode, "neox") || p->rank != 1 || + r4d_gets(a, "sections") || r4d_getf(a, "yarn_factor", 0) != 0 || + r4d_getf(a, "llama3_factor", 0) != 0) return R4D_NO(RAD_E_UNSUPPORTED); + long long rx = 0; + const auto xp = r4d_rows_pitch(x, 3 * nh * 64, &rx), rows = r4d_numel(p); + if (xp < 0 || !r4d_contig(p)) return R4D_NO(RAD_E_STRIDE); + const float theta = r4d_getf(a, "theta", 10000), scale = r4d_getf(a, "scale", 1); + if (rows < 1 || rows > 65535 || rx < rows || xp > 0x7fffffffll || !(theta > 0) || !(scale > 0)) + return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(encoder_rope, dim3((unsigned)rows), dim3(kT), 0, (hipStream_t)s, + (float*)x->data, (const int*)p->data, (int)(nh + nk), (int)xp, theta, scale); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_encoder_attn(const RadArgs* a, RadStream s) { + const auto *q = r4d_opt(a, 0), *k = r4d_opt(a, 1), *v = r4d_opt(a, 2), + *cu = r4d_opt(a, 3), *y = r4d_opt(a, 4); + if (!q || !k || !v || !cu || !y || !is_f32(q) || !is_f32(k) || !is_f32(v) || + !is_f32(y) || !is_i32(cu)) return R4D_NO(RAD_E_DTYPE); + if (r4d_geti_or(a, "head_dim", 0) != 64 || r4d_geti_or(a, "gqa", 1) != 1 || + r4d_geti_or(a, "causal", 0) != 1) return R4D_NO(RAD_E_UNSUPPORTED); + const long long n = r4d_dim(q, (int)q->rank - 1), div = r4d_geti_or(a, "cu_div", 1); + if (n < 64 || n % 64 || n > 4096 || div < 1 || div > 0x7fffffffll) return R4D_NO(RAD_E_SHAPE); + long long rq = 0, rk = 0, rv = 0, ry = 0; + const auto qp = r4d_rows_pitch(q, n, &rq), kp = r4d_rows_pitch(k, n, &rk), + vp = r4d_rows_pitch(v, n, &rv), yp = r4d_rows_pitch(y, n, &ry); + if (qp < 0 || kp < 0 || vp < 0 || yp < 0 || !r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE); + const auto ns = r4d_numel(cu) - 1, window = r4d_geti_or(a, "window", 0); + if (ry < 1 || ry > 512 || rq < ry || rk < ry || rv < ry || ns < 1 || ns > 512 || + qp > 0x7fffffffll || kp > 0x7fffffffll || vp > 0x7fffffffll || yp > 0x7fffffffll || + window < 0 || window > 0x7fffffffll) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(encoder_attn, dim3((unsigned)ry, (unsigned)(n / 64)), dim3(kT), 0, + (hipStream_t)s, (const float*)q->data, (const float*)k->data, (const float*)v->data, + (const int*)cu->data, (float*)y->data, (int)(n / 64), (int)qp, (int)kp, (int)vp, (int)yp, + (int)ns, (int)div, (int)window, (float)r4d_getf(a, "scale", 0.125)); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_elu(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *y = r4d_opt(a, 1); + if (!x || !y || !is_f32(x) || !is_f32(y)) return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0); + long long rx = 0, ry = 0; + if (n <= 0) return R4D_NO(RAD_E_SHAPE); + const long long xp = r4d_rows_pitch(x, n, &rx), yp = r4d_rows_pitch(y, n, &ry); + if (xp < 0 || yp < 0) return R4D_NO(RAD_E_STRIDE); + if (ry <= 0 || rx < ry || n > 0x7fffffffll || ry > 0x7fffffffll / n || + xp > 0x7fffffffll || yp > 0x7fffffffll) return R4D_NO(RAD_E_SHAPE); + hipLaunchKernelGGL(elu_f32_kernel, dim3(blocks_for(ry * n)), dim3(kT), 0, + (hipStream_t)s, (const float*)x->data, (float*)y->data, + (int)ry, (int)n, (int)xp, (int)yp); + return st_of(hipGetLastError()); +} + +extern "C" int r4d_rad_vq_euclidean(const RadArgs* a, RadStream s) { + const RadTensor *x = r4d_opt(a, 0), *cb = r4d_opt(a, 1), *c = r4d_opt(a, 2); + if (!x || !cb || !c || !is_f32(x) || !is_f32(cb) || !is_i32(c)) + return R4D_NO(RAD_E_DTYPE); + const long long n = r4d_geti_or(a, "n", 0), bins = r4d_geti_or(a, "bins", 0); + if (n <= 0 || bins <= 0) return R4D_NO(RAD_E_SHAPE); + long long rx = 0, rc = 0; + const long long xp = r4d_rows_pitch(x, n, &rx), cp = r4d_rows_pitch(cb, n, &rc); + if (xp < 0 || cp < 0) return R4D_NO(RAD_E_STRIDE); + if (rx < 1 || rc != bins || r4d_numel(c) < rx || rx > 65535 || n > 4096 || + bins > 65536 || xp > 0x7fffffffll || cp > 0x7fffffffll) + return R4D_NO(RAD_E_SHAPE); + const long long cs = c->rank ? c->stride[c->rank - 1] : 1; + if (cs < 1 || cs > 0x7fffffffll) return R4D_NO(RAD_E_STRIDE); + hipLaunchKernelGGL(vq_euclidean_kernel, dim3((unsigned)rx), dim3(kT), 0, + (hipStream_t)s, (float*)x->data, (const float*)cb->data, + (int*)c->data, (int)n, (int)bins, (int)xp, (int)cp, (int)cs); + return st_of(hipGetLastError()); +} + extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) { const RadTensor *x = r4d_opt(a, 0), *w = r4d_opt(a, 1), *cu = r4d_opt(a, 2); const RadTensor *res = r4d_opt(a, 3), *y = r4d_opt(a, 4), *b = r4d_opt(a, 5); @@ -1348,8 +1592,9 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) { const long long cd = r4d_geti_or(a, "cu_div", 1); const int act = conv1d_act(r4d_gets(a, "act")); if (act < 0) return R4D_NO(RAD_E_INVAL); - /* The strided forms are bf16 only. */ - if (r4d_geti_or(a, "stride", 1) != 1 || r4d_geti_or(a, "pad", -1) >= 0) + /* Explicit symmetric padding is still the bf16-only form. Causal strides share the + * same loaders as stride 1 and retain each clip's own cu_div bounds. */ + if (r4d_geti_or(a, "pad", -1) >= 0) return R4D_NO(RAD_E_DTYPE); if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 || causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1) diff --git a/libr4d/r4d_gemm_f32_nt_bias.hip b/libr4d/r4d_gemm_f32_nt_bias.hip index eb74447c..79c88ae6 100644 --- a/libr4d/r4d_gemm_f32_nt_bias.hip +++ b/libr4d/r4d_gemm_f32_nt_bias.hip @@ -68,7 +68,7 @@ __global__ __launch_bounds__(r4d_f32::kThr) void gemm_f32_bias_kernel( for (int j = 0; j < TN; ++j) { const int n = n0 + (j / CW) * 16 * CW + tx * CW + j % CW; const int nc = n < N ? n : N - 1; - bc[j] = bias_f32 ? ((const float*)bias)[nc] : bf16_to_f32(((const uint16_t*)bias)[nc]); + bc[j] = !bias ? 0.0f : bias_f32 ? ((const float*)bias)[nc] : bf16_to_f32(((const uint16_t*)bias)[nc]); } auto ep = [&](int r, int c, int cnt, float4 q, int g) { const int m = m0 + r, n = n0 + c; @@ -99,23 +99,23 @@ __global__ __launch_bounds__(r4d_f32::kThr) void gemm_f32_bias_kernel( // ============================================================== the plugin ABI entry point enum { GF_A = 0, GF_W, GF_BIAS, GF_RES, GF_Y }; -extern "C" int r4d_rad_gemm_f32_nt_bias(const RadArgs* a, RadStream stream) { +static int gemm_f32_emit(const RadArgs* a, RadStream stream, bool plain) { const RadTensor* A = r4d_opt(a, GF_A); const RadTensor* W = r4d_opt(a, GF_W); const RadTensor* B = r4d_opt(a, GF_BIAS); const RadTensor* R = r4d_opt(a, GF_RES); const RadTensor* Y = r4d_opt(a, GF_Y); - if (!A || !W || !B || !Y) return R4D_NO(RAD_E_INVAL); + if (!A || !W || !Y || (!B && !plain)) return R4D_NO(RAD_E_INVAL); /* f32 A and W; C f32 or bf16, the residual C's dtype; the bias f32 or bf16. */ if (A->dtype != RAD_F32 || W->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); if (Y->dtype != RAD_F32 && Y->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); - if (B->dtype != RAD_F32 && B->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); + if (B && B->dtype != RAD_F32 && B->dtype != RAD_BF16) return R4D_NO(RAD_E_DTYPE); if (R && R->dtype != Y->dtype) return R4D_NO(RAD_E_DTYPE); - if (!r4d_contig(W) || !r4d_contig(B)) return R4D_NO(RAD_E_STRIDE); + if (!r4d_contig(W) || (B && !r4d_contig(B))) return R4D_NO(RAD_E_STRIDE); const long long K = r4d_geti_or(a, "K", r4d_dim(W, (int)W->rank - 1)); const long long N = r4d_geti_or(a, "N", r4d_numel(W) / (K > 0 ? K : 1)); - if (K <= 0 || N <= 0 || r4d_numel(W) < N * K || r4d_numel(B) < N) return R4D_NO(RAD_E_SHAPE); + if (K <= 0 || N <= 0 || r4d_numel(W) < N * K || (B && r4d_numel(B) < N)) return R4D_NO(RAD_E_SHAPE); long long M = 0, Ma = 0, Mr = 0; const long long ldc = r4d_rows_pitch(Y, N, &M); const long long lda = r4d_rows_pitch(A, K, &Ma); @@ -135,7 +135,7 @@ extern "C" int r4d_rad_gemm_f32_nt_bias(const RadArgs* a, RadStream stream) { else if (!std::strcmp(act_s, "gelu_tanh")) act = 2; else if (std::strcmp(act_s, "none")) return R4D_NO(RAD_E_SCHEMA); } - const int bias_f32 = B->dtype == RAD_F32; + const int bias_f32 = B && B->dtype == RAD_F32; const bool f32 = Y->dtype == RAD_F32; /* Whole-run stores where every row starts aligned to a run of four. */ const unsigned run_bytes = f32 ? 16u : 8u; @@ -161,3 +161,14 @@ extern "C" int r4d_rad_gemm_f32_nt_bias(const RadArgs* a, RadStream stream) { GF_L(2, uint16_t); #undef GF_L } + +extern "C" int r4d_rad_gemm_f32_nt_bias(const RadArgs* a, RadStream stream) { + return gemm_f32_emit(a, stream, false); +} + +extern "C" int r4d_rad_gemm_f32_nt(const RadArgs* a, RadStream stream) { + if (!a || a->n_t < 3) return R4D_NO(RAD_E_INVAL); + const RadTensor t[] = {a->t[0], a->t[1], {}, {}, a->t[2]}; + RadArgs b = *a; b.t = t; b.n_t = 5; + return gemm_f32_emit(&b, stream, true); +} diff --git a/libr4d/r4d_model_bf16.hip b/libr4d/r4d_model_bf16.hip index 9e6bf299..72a26f63 100644 --- a/libr4d/r4d_model_bf16.hip +++ b/libr4d/r4d_model_bf16.hip @@ -35,6 +35,9 @@ #include #include +/* The f32 reference encoder shares rope's schema but keeps its activations in f32. */ +extern "C" int r4d_rad_encoder_rope(const RadArgs*, RadStream); + namespace { constexpr uint32_t kWave = 32; @@ -2391,9 +2394,13 @@ static int rope_emit(const RadArgs* a, RadStream s, bool rows_form) { const RadTensor* qkv = r4d_opt(a, RP_QKV); const RadTensor* pos = r4d_opt(a, RP_POS); if (!qkv || !pos) return R4D_NO(RAD_E_INVAL); + if (qkv->dtype == RAD_F32) return r4d_rad_encoder_rope(a, s); R4D_NEED(dt_bf16(qkv)); R4D_NEED(dt_i32(pos)); - if (!r4d_contig(pos)) return R4D_NO(RAD_E_STRIDE); + /* A component list is read at its own pitch: a [C, M] view of a [C, P] buffer (a tower's + * per-pass rope positions) is row-contiguous with a leading stride wider than M. */ + if (pos->rank == 2 ? pos->stride[1] != 1 : pos->stride[0] != 1) + return R4D_NO(RAD_E_STRIDE); const long long head_dim = r4d_geti_or(a, "head_dim", 0); const long long n_head = r4d_geti_or(a, "n_head", 0); @@ -2452,7 +2459,7 @@ static int rope_emit(const RadArgs* a, RadStream s, bool rows_form) { if (mc != 3 && [&] { int t = 0; for (int c = 0; c < n_sec; ++c) t += sec[c]; return t != (int)(rot / 2); }()) return R4D_NO(RAD_E_SHAPE); - plane = (int)pos->shape[1]; + plane = (int)(pos->stride[0] >= pos->shape[1] ? pos->stride[0] : pos->shape[1]); } const float theta = (float)r4d_getf(a, "theta", 10000.0); diff --git a/libr4d/r4d_plugin.h b/libr4d/r4d_plugin.h index 4c1fd9a6..9dba0c58 100644 --- a/libr4d/r4d_plugin.h +++ b/libr4d/r4d_plugin.h @@ -161,6 +161,9 @@ int64_t r4d_rad_attn_qrow_h128_gqa8_scratch(const RadArgs*); * row pitch, so they serve both attn_paged and attn_paged_qrow. */ int r4d_rad_attn_window_h128_gqa1_bf16(const RadArgs*, RadStream); int r4d_rad_attn_window_h128_gqa1_i8 (const RadArgs*, RadStream); +/* h128 gqa16: Muse Glimmer's 32 query heads over 2 KV heads. */ +int r4d_rad_attn_window_h128_gqa16_bf16(const RadArgs*, RadStream); +int r4d_rad_attn_window_h128_gqa16_i8 (const RadArgs*, RadStream); /* The same kernels under attn_paged_sink (a sink logit a query head). */ int r4d_rad_attn_window_sink_h128_gqa8_bf16 (const RadArgs*, RadStream); int r4d_rad_attn_window_sink_h128_gqa8_i8 (const RadArgs*, RadStream); @@ -292,6 +295,14 @@ int r4d_rad_snake (const RadArgs*, RadStream); int r4d_rad_cfg_topk_sample (const RadArgs*, RadStream); int r4d_rad_rvq_embed (const RadArgs*, RadStream); int r4d_rad_vq_encode (const RadArgs*, RadStream); +int r4d_rad_vq_euclidean (const RadArgs*, RadStream); +int r4d_rad_elu (const RadArgs*, RadStream); +int r4d_rad_encoder_layernorm (const RadArgs*, RadStream); +int r4d_rad_encoder_gelu (const RadArgs*, RadStream); +int r4d_rad_encoder_rope (const RadArgs*, RadStream); +int r4d_rad_encoder_attn (const RadArgs*, RadStream); +int r4d_rad_gemm_f32_nt (const RadArgs*, RadStream); +int r4d_shape_vq_euclidean (const RadParam*, int, int, RadOpdDesc*); int r4d_rad_frame_mix_store (const RadArgs*, RadStream); int r4d_rad_end_status (const RadArgs*, RadStream); int r4d_rad_ras_pick (const RadArgs*, RadStream); @@ -882,6 +893,9 @@ int r4d_rad_layernorm (const RadArgs*, RadStream); int r4d_rad_grid_embed (const RadArgs*, RadStream); int r4d_rad_grid_embed_aa (const RadArgs*, RadStream); int r4d_rad_grid_embed_cpe (const RadArgs*, RadStream); +/* Muse's vision-tower coordinate ops (r4d_vit_muse.hip). */ +int r4d_rad_grid_embed_pad (const RadArgs*, RadStream); +int r4d_rad_window_order (const RadArgs*, RadStream); int r4d_rad_gemm_nt_bias (const RadArgs*, RadStream); /* gemm_nt_bias at f32 (r4d_gemm_f32_nt_bias.hip). */ int r4d_rad_gemm_f32_nt_bias(const RadArgs*, RadStream); @@ -948,6 +962,9 @@ int r4d_shape_scatter_rows_bf16(const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_layernorm (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_grid_embed (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_grid_embed_cpe (const RadParam*, int, int operand, RadOpdDesc*); +/* Muse's vision-tower coordinate ops. */ +int r4d_shape_grid_embed_pad (const RadParam*, int, int operand, RadOpdDesc*); +int r4d_shape_window_order (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_gemm_nt_bias (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_unary (const RadParam*, int, int operand, RadOpdDesc*); int r4d_shape_fill (const RadParam*, int, int operand, RadOpdDesc*); diff --git a/libr4d/r4d_qkv_norm_rope.hip b/libr4d/r4d_qkv_norm_rope.hip index 0992389d..5f73c753 100644 --- a/libr4d/r4d_qkv_norm_rope.hip +++ b/libr4d/r4d_qkv_norm_rope.hip @@ -263,7 +263,9 @@ static int qkv_norm_rope_launch(const RadArgs* a, RadStream stream, bool store) const long long vn = r4d_geti_or(a, "v_norm", 1); if (hd != 128 && hd != 256 && hd != 512) return R4D_NO(RAD_E_SHAPE); if (vk && !vn) return R4D_NO(RAD_E_INVAL); // v from k is v's norm - if (nq < 0 || nkv <= 0 || rot <= 0 || rot > hd || (rot & 1)) return R4D_NO(RAD_E_SHAPE); + /* rot 0 is the NoPE layer: the norm still runs, and `rotate` with half = 0 only copies the + * unrotated tail, which is the whole head. */ + 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); diff --git a/libr4d/r4d_rows.cpp b/libr4d/r4d_rows.cpp index 3909da8a..673b4336 100644 --- a/libr4d/r4d_rows.cpp +++ b/libr4d/r4d_rows.cpp @@ -2185,6 +2185,15 @@ static const RadOperandSpec oGridEmbed[] = { { "table", RAD_OPD_WEIGHT, 0 }, { "coord", RAD_OPD_IN, 0 }, }; +static const RadParamSpec pWindowOrder[] = { P_INT("M"), P_INT("window") }; +static const RadOperandSpec oWindowOrder[] = { + { "crd", RAD_OPD_IN, 0 }, + { "cu", RAD_OPD_IN, 1 }, + { "idx", RAD_OPD_OUT, 0 }, + { "inv", RAD_OPD_OUT, 0 }, + { "pos", RAD_OPD_OUT, 0 }, + { "cuw", RAD_OPD_OUT, 0 }, +}; static const RadParamSpec pGridEmbedCpe[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype"), { "n_prefix", RAD_P_INT, RAD_OPTIONAL }, @@ -2846,7 +2855,11 @@ static const RadOperandSpec oVqEncode[] = { { "codes", RAD_OPD_OUT, 0 }, }; static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), - P_INTO("rep"), P_STR("dtype") }; + P_INTO("rep"), P_STR("dtype") }; +static const RadParamSpec pVqEuclidean[] = { P_INT("M"), P_INT("n"), P_INT("bins"), P_STR("dtype") }; +static const RadOperandSpec oVqEuclidean[] = { + { "x", RAD_OPD_INOUT, 0 }, { "cb", RAD_OPD_WEIGHT, 0 }, { "codes", RAD_OPD_OUT, 0 }, +}; static const RadOperandSpec oFrameMix[] = { { "hid", RAD_OPD_IN, 0 }, { "logits", RAD_OPD_WEIGHT, 0 }, { "scale", RAD_OPD_WEIGHT, 0 }, { "lane", RAD_OPD_IN, 0 }, { "frame", RAD_OPD_IN, 0 }, { "status", RAD_OPD_IN, 0 }, @@ -3294,6 +3307,25 @@ static const RadOpSchema kSchemas[] = { "x += a side x side table resampled bilinearly (corners aligned, taps clamped) to each " "row's grid; coord is [4, M] row, column, height, width. The taps are summed in f32 " "and rounded before the add."), + SCHEMA("grid_embed_pad", pGridEmbed, oGridEmbed, + "x += the side x side table resampled at each row's grid in the half-pixel-centre form " + "(align_corners=False) with grid_sample's padding_mode=\"zeros\": per axis taps at " + "floor(src) and floor(src) + 1 of src = (i + 0.5) * side / size - 0.5, each carrying " + "the hat weight (1 - |src - tap|)+, and a tap whose UNCLAMPED index falls outside the " + "table contributes zero rather than reading an edge. Same operands and tap order as " + "`grid_embed`; equal to it whenever the grid fits the table, different only when a " + "grid upsamples past it (Muse's case)."), + SCHEMA("window_order", pWindowOrder, oWindowOrder, + "The window-attention permutation of one encoder pass (HF's get_vision_window_index) " + "computed from the coordinates alone: `crd` [4, P] i32 is row, column, segment height, " + "segment width per patch and `cu` [S+1] i32 the per-frame segment boundaries. Windows " + "of `window` patches partition each segment, window-row-major, ragged at the segment's " + "right and bottom edges, patches raster within a window and windows never across " + "segments. Outputs i32: `idx` [P], slot -> source patch (the gather index); `inv` [P], " + "the inverse; `pos` [2, P], each slot's rope positions (col + 1, row + 1), " + "component-major like the planes; `cuw` [P+1], the cumulative window boundaries in the " + "permuted order, n_windows + 1 entries used. `M` bands the pass; slots past M are the " + "identity. `window` <= 0 is the identity permutation, cuw = cu."), SCHEMA("grid_embed_aa", pGridEmbed, oGridEmbed, "x += the side x side table resampled as torch's F.interpolate(bilinear, " "align_corners=False, antialias=True) resamples it to the row's grid -- SigLIP2's " @@ -4033,6 +4065,9 @@ static const RadOpSchema kSchemas[] = { "(the lower index on a tie), then x -= out_w cb[code] + out_b."), SCHEMA("frame_mix_store", pFrameMix, oFrameMix, "a frame's conditioning row (softmax-weighted planes times scale) into its lane."), + SCHEMA("vq_euclidean", pVqEuclidean, oVqEuclidean, + "nearest Euclidean centroid, codes written and centroid subtracted from x."), + SCHEMA("elu", pGenMn, oGenUnary, "y = x >= 0 ? x : expm1(x), alpha 1."), SCHEMA("end_status", pEndStatus, oEndStatus, "status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]."), SCHEMA("ras_pick", pRasPick, oRasPick, @@ -4617,6 +4652,10 @@ static const RadConstraint cAttnDenseH64[] = { static const RadConstraint cAttnDenseH80[] = { C_EQ("head_dim", 80), C_EQ("gqa", 1), C_IN("dtype", "bf16"), }; +/* head_dim 96 without GQA: Muse Glimmer's vision tower heads (16 of 96). */ +static const RadConstraint cAttnDenseH96[] = { + C_EQ("head_dim", 96), C_EQ("gqa", 1), C_IN("dtype", "bf16"), +}; /* head_dim 256 without GQA, sequences past the small kernel's. */ static const RadConstraint cAttnDenseH256G1[] = { C_EQ("head_dim", 256), C_EQ("gqa", 1), C_GE("max_seqlen", 33), C_IN("dtype", "bf16"), @@ -5847,6 +5886,9 @@ static const RadTunable tRmsQ8[] = { * power-of-two padding. */ static const RadConstraint cBf16Row[] = { C_IN("dtype", "bf16") }; static const RadConstraint cF32Row[] = { C_IN("dtype", "f32") }; +static const RadConstraint cEncoderNorm[] = { C_IN("dtype", "f32"), C_GE("n", 1), C_LE("n", 4096) }; +static const RadConstraint cEncoderAttn[] = { C_IN("dtype", "f32"), C_EQ("head_dim", 64), + C_EQ("gqa", 1), C_EQ("causal", 1), C_GE("M", 1), C_LE("M", 512) }; /* 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 vectorised copy's alignment, stated so the selector @@ -5891,6 +5933,8 @@ static const RadConstraint cRopeRow[] = { C_GE("head_dim", 1), * the position embedding take any width. */ static const RadConstraint cLayernorm[] = { C_GE("n", 1), C_IN("dtype", "bf16") }; static const RadConstraint cGridEmbed[] = { C_GE("n", 1), C_GE("side", 1), C_IN("dtype", "bf16") }; +/* window_order has no dtype of its own: its operands are i32 by schema, `M` the only band. */ +static const RadConstraint cWindowOrder[] = { C_GE("M", 1) }; static const RadConstraint cGemmBias[] = { C_GE("M", 1), C_DIV("K", 8), C_IN("dtype", "bf16") }; /* The f32 GEMM reads its rows a float at a time: any K. */ static const RadConstraint cGemmBiasF32[] = { C_GE("M", 1), C_IN("dtype", "f32") }; @@ -6456,6 +6500,26 @@ static const RadKernelInfo kKernels[] = { nullptr, nullptr, r4d_rad_grid_embed_cpe, nullptr, nullptr, nullptr, r4d_shape_grid_embed_cpe }, +{ "grid_embed_pad_bf16", "grid_embed_pad", "elem", + "the position grid resampled half-pixel bilinear with zero-padded off-table taps and added in " + "(Muse's)", + "any n and side; coord [4, M] dense; one workgroup a row", + "bf16 x, bf16 or f32 table, i32 coord, f32 taps", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cGridEmbed), NOTUNE, + nullptr, nullptr, r4d_rad_grid_embed_pad, nullptr, nullptr, nullptr, + r4d_shape_grid_embed_pad }, + +{ "window_order_i32", "window_order", "elem", + "the window-attention permutation of one pass from its coordinate planes: idx, its inverse, " + "the swapped one-offset rope positions and the cumulative window boundaries", + "M in [1, P); one workgroup the pass", + "i32 coord [4, P] and cu [S+1]; i32 idx, inv, pos [2, P] and cuw [P+1]", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cWindowOrder), NOTUNE, + nullptr, nullptr, r4d_rad_window_order, nullptr, nullptr, nullptr, + r4d_shape_window_order }, + { "gemm_bf16_nt_bias_tiled", "gemm_nt_bias", "gemm", "biased GEMM C = res + act(A @ W^T + bias) over 64-deep K tiles, the K tail staged as zeros, " "the activation and residual in the store: from 32 blocks of 128x128 the weight read straight " @@ -6476,7 +6540,27 @@ static const RadKernelInfo kKernels[] = { RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cGemmBiasF32), NOTUNE, nullptr, nullptr, r4d_rad_gemm_f32_nt_bias, nullptr, nullptr, nullptr, - r4d_shape_gemm_nt_bias }, + r4d_shape_gemm_nt_bias }, +{ "gemm_f32_nt", "gemm_nt", "gemm", + "unbiased f32 GEMM on the shared FMA tile", "pitched A and Y, contiguous W", "f32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_gemm_f32_nt, nullptr, nullptr, nullptr, r4d_shape_gemm_nt }, +{ "layernorm_f32", "layernorm", "norm", + "two-pass f32 layer norm", "n <= 4096, pitched rows", "f32 rows, gain and bias", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cEncoderNorm), NOTUNE, + nullptr, nullptr, r4d_rad_encoder_layernorm, nullptr, nullptr, nullptr, r4d_shape_layernorm }, +{ "gelu_f32", "gelu", "elem", + "exact erf GELU", "pitched rows", "f32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_encoder_gelu, nullptr, nullptr, nullptr, r4d_shape_unary }, +{ "attn_dense_h64_f32", "attn_dense", "attn", + "f32 causal encoder attention without a global score plane", "M <= 512, head_dim 64, gqa 1", "f32", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cEncoderAttn), NOTUNE, + nullptr, nullptr, r4d_rad_encoder_attn }, { "add_bf16", "add", "elem", "elementwise sum, with the one row-broadcast form; `div` divides the rounded sum", @@ -7349,7 +7433,7 @@ static const RadKernelInfo kKernels[] = { #define R4D_WIN_PAIR(HD, GQ) \ R4D_WIN_ROW(HD, GQ, bf16kv, bf16, cWinH##HD##G##GQ##Bf16, "bf16") \ R4D_WIN_ROW(HD, GQ, i8kv, i8, cWinH##HD##G##GQ##I8, "int8 (an f16 scale of K and of V per token and head)") -R4D_WIN_PAIR(128, 1) +R4D_WIN_PAIR(128, 1) R4D_WIN_PAIR(128, 16) /* Muse Glimmer's 32/2-head sliding layers */ R4D_WIN_PAIR(256, 1) R4D_WIN_PAIR(256, 2) R4D_WIN_PAIR(256, 4) R4D_WIN_PAIR(256, 8) R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512, 8) R4D_WIN_PAIR(512, 16) @@ -7867,6 +7951,16 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8) ROW(cAttnDenseH80), NOTUNE, nullptr, nullptr, r4d_rad_attn_dense }, +{ "attn_dense_h96_bf16", "attn_dense", "attn", + "dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window or " + "blocks, or causal with an optional window behind", + "head_dim 96, multi-head (no GQA), q/k/v/o at their own token pitches (column slices of a " + "fused projection allowed)", + "bf16 query / key / value / out, f16 operands, fp32 accumulate", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cAttnDenseH96), NOTUNE, + nullptr, nullptr, r4d_rad_attn_dense }, + { "attn_dense_h256_bf16", "attn_dense", "attn", "dense varlen attention over cu_seqlens: bidirectional with an optional two-sided window or " "blocks, or causal with an optional window behind", @@ -10296,7 +10390,17 @@ R4D_WIN_TREE_PAIR(512, 4) R4D_WIN_TREE_PAIR(512, 8) "bf16 or f32 rows and weights, f32 arithmetic, the row rounded once", RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, ROW(cVqEncode), NOTUNE, - nullptr, nullptr, r4d_rad_vq_encode }, + nullptr, nullptr, r4d_rad_vq_encode }, +{ "vq_euclidean_f32", "vq_euclidean", "elem", + "nearest Euclidean centroid", "one workgroup a row", "f32 rows and centroids, i32 codes", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_vq_euclidean, nullptr, nullptr, nullptr, r4d_shape_vq_euclidean }, +{ "elu_f32", "elu", "elem", + "ELU, alpha 1", "row pitches honoured", "f32 rows", + RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY, + ROW(cF32Row), NOTUNE, + nullptr, nullptr, r4d_rad_elu, nullptr, nullptr, nullptr, r4d_shape_unary }, { "frame_mix_store_bf16", "frame_mix_store", "elem", "a frame's conditioning row into its lane", "a workgroup a lane, L <= 16", diff --git a/libr4d/r4d_selftest.cpp b/libr4d/r4d_selftest.cpp index 22a0d058..27451154 100644 --- a/libr4d/r4d_selftest.cpp +++ b/libr4d/r4d_selftest.cpp @@ -8498,6 +8498,10 @@ static void mxfp4a8_gated_case(const Plugin& pl, int64_t M, int64_t N, int64_t K * libref function (libref/ref_audio.cpp, ref_elementwise.cpp, ref_attn.cpp) over the same bf16 * inputs. Picks, ids and the history are compared exactly; a sum the kernel orders differently is * held to a relative L2 against the answer rounded to bf16. */ +namespace vg { +void* stored_weight_f32(const RadKernelInfo*, const std::vector&, + const std::vector&, int64_t, int64_t, const char*); +} namespace au { uint64_t g_seed = 0xa0d10ull; @@ -8719,8 +8723,8 @@ void conv1d_cases(const Plugin& pl) { } check(nm + " numerics", down_bf16(dy, want.size()), want, 1e-2); } - /* An even kernel is causal only; a stride needs its pad and its one sequence; and the - * strided form refuses the f32 rows. */ + /* An even kernel is causal only; the explicit padded stride needs one sequence and + * remains bf16-only (the causal strided form also supports f32). */ std::vector ps = { PI("M", 4), PI("cin", 8), PI("cout", 16), PI("k", 4), PI("dil", 1), PS("dtype", "bf16") }; const int rc = launch(r, { TA(RAD_BF16, { 4, 8 }), TA(RAD_BF16, { 16, 8, 4 }), @@ -8744,14 +8748,14 @@ void conv1d_cases(const Plugin& pl) { ok("conv1d_bf16 refuses a stride over two sequences", rt == RAD_E_SHAPE, "rc " + std::to_string(rt)); if (const RadKernelInfo* f = find(pl, "conv1d_f32")) { - /* Odd k so the refusal comes from the stride, not from the even-kernel rule. */ + /* Odd k so the refusal comes from explicit padding, not the even-kernel rule. */ const std::vector f32 = { PI("M", 8), PI("cin", 8), PI("cout", 16), PI("k", 3), PI("dil", 1), PS("dtype", "f32"), PI("stride", 2), PI("pad", 1) }; const int rf = launch(f, { TA(RAD_F32, { 8, 8 }), TA(RAD_F32, { 16, 8, 3 }), TI32({ 2 }, { 0, 8 }), TA(RAD_F32, { 4, 16 }), TA(RAD_F32, { 4, 16 }), TA(RAD_F32, { 16 }) }, f32); - ok("conv1d_f32 refuses a stride", rf == RAD_E_DTYPE, "rc " + std::to_string(rf)); + ok("conv1d_f32 refuses explicit symmetric stride padding", rf == RAD_E_DTYPE, "rc " + std::to_string(rf)); } } @@ -9169,6 +9173,179 @@ void rvq_embed_cases(const Plugin& pl) { * codes a dense row and a strided column: each code against the host's cosine argmax in double (a * pick within 1e-5 of the best score is a near tie, not a miss), the row after against * x - out_w cb[code] - out_b for the code the kernel took. */ +void breeze_reference_cases(const Plugin& pl) { + const auto* q = find(pl, "vq_euclidean_f32"); + const auto* e = find(pl, "elu_f32"); + const auto* cv = find(pl, "conv1d_f32"); + if (!q || !e || !cv) { ok("breeze reference rows present", false); return; } + constexpr int n = 256, bins = 2048, xp = 259, cp = 261, cs = 3; + std::vector x(3 * xp, 0), cb(bins * cp, 0); + x[0] = 4; x[xp] = 2; x[2 * xp] = -1; + cb[0] = 1; cb[cp] = 3; cb[2 * cp] = -1; + for (int k = 3; k < bins; ++k) cb[k * cp] = 100 + k; + for (int r = 0; r < 3; ++r) for (int j = n; j < xp; ++j) x[r * xp + j] = 77; + void* dx = up_f32(x); + void* dc = up_i32(std::vector(3 * cs, -7)); + RadTensor tx = T(dx, RAD_F32, {3, n}); tx.stride[0] = xp; + RadTensor tc = T(up_f32(cb), RAD_F32, {bins, n}); tc.stride[0] = cp; + RadTensor codes = T(dc, RAD_I32, {3}); codes.stride[0] = cs; + const int rc = launch(q, {tx, tc, codes}, {PI("M", 3), PI("n", n), PI("bins", bins), PS("dtype", "f32")}); + ok("breeze Euclidean RVQ launch", rc == RAD_OK, "rc " + std::to_string(rc)); + if (rc == RAD_OK) { + const auto got = down_i32(dc, 3 * cs); + const auto residual = down_f32(dx, x.size()); + bool valid = got[0] == 1 && got[cs] == 0 && got[2 * cs] == 2; + for (int i = 0; i < 3 * cs; ++i) if (i % cs) valid &= got[i] == -7; + for (int r = 0; r < 3; ++r) for (int j = 0; j < xp; ++j) { + const float want = j == 0 ? (r == 2 ? 0 : 1) : j < n ? 0 : 77; + valid &= residual[r * xp + j] == want; + } + ok("breeze Euclidean distance, tie order, residual and pitched guards", valid); + } + std::vector v = {-1, 0, 2, -100}; + void* dv = up_f32(v); + const int re = launch(e, {T(dv, RAD_F32, {4, 1}), T(dv, RAD_F32, {4, 1})}, + {PI("M", 4), PI("n", 1), PS("dtype", "f32")}); + ok("breeze ELU in place launch", re == RAD_OK); + if (re == RAD_OK) { + const auto g = down_f32(dv, 4); + ok("breeze ELU in place values", std::abs(g[0] + 0.6321205588f) < 1e-7f && + g[1] == 0 && g[2] == 2 && g[3] == -1); + } + if (const auto* g = find(pl, "gemm_f32_nt")) { + void* out = dalloc(6 * sizeof(float)); + const int s = launch(g, {T(up_f32({1, 2, 3, 4, -1, 2}), RAD_F32, {3, 2}), + T(up_f32({2, 0, 0, 3}), RAD_F32, {2, 2}), T(out, RAD_F32, {3, 2})}, + {PI("M", 3), PI("N", 2), PI("K", 2), PS("dtype", "f32")}); + ok("breeze unbiased f32 GEMM", s == RAD_OK && down_f32(out, 6) == std::vector({2, 6, 6, 12, -2, 6})); + } else ok("breeze unbiased f32 GEMM present", false); + if (const auto* ln = find(pl, "layernorm_f32")) { + void* out = dalloc(4 * sizeof(float)); + const int s = launch(ln, {T(up_f32({-1, 1, 3, 5}), RAD_F32, {2, 2}), + T(up_f32({2, 2}), RAD_F32, {2}), T(up_f32({1, 1}), RAD_F32, {2}), T(out, RAD_F32, {2, 2})}, + {PI("M", 2), PI("n", 2), PF("eps", 1e-5), PS("dtype", "f32")}); + bool valid = s == RAD_OK; + if (valid) { + const auto got = down_f32(out, 4); + const float inv = 1 / std::sqrt(1.00001f); + for (int i = 0; i < 4; ++i) valid &= std::abs(got[i] - (1 + (i % 2 ? 2 : -2) * inv)) < 1e-6f; + } + ok("breeze f32 layer norm mean, variance, gain and bias", valid); + } else ok("breeze f32 layer norm present", false); + if (const auto* gl = find(pl, "gelu_f32")) { + void* out = dalloc(4 * sizeof(float)); + const int s = launch(gl, {T(up_f32({-1, 0, 1, 2}), RAD_F32, {2, 2}), T(out, RAD_F32, {2, 2})}, + {PI("M", 2), PI("n", 2), PS("dtype", "f32")}); + bool valid = s == RAD_OK; + if (valid) { + const auto got = down_f32(out, 4); + for (int i = 0; i < 4; ++i) { + const float v = i - 1; + valid &= std::abs(got[i] - 0.5f * v * (1 + std::erf(v / std::sqrt(2.f)))) < 1e-6f; + } + } + ok("breeze f32 exact GELU", valid); + } else ok("breeze f32 GELU present", false); + if (const auto* rope = find(pl, "rope_bf16")) { + std::vector x(2 * 192, 0); + for (int r = 0; r < 2; ++r) { + x[r * 192] = 1; x[r * 192 + 32] = 2; + x[r * 192 + 64] = 3; x[r * 192 + 96] = 4; + for (int d = 128; d < 192; ++d) x[r * 192 + d] = 9; + } + void* dx = up_f32(x); + const int s = launch(rope, {T(dx, RAD_F32, {2, 192}), TI32({2}, {0, 1})}, + {PI("M", 2), PI("head_dim", 64), PI("n_head", 1), PI("n_head_kv", 1), + PF("theta", 10000), PF("scale", 1), PS("mode", "neox")}); + bool valid = s == RAD_OK; + if (valid) { + const auto got = down_f32(dx, x.size()); + for (int i = 0; i < 192; ++i) valid &= got[i] == x[i]; + valid &= std::abs(got[192] - (std::cos(1.f) - 2 * std::sin(1.f))) < 1e-6f; + valid &= std::abs(got[224] - (std::sin(1.f) + 2 * std::cos(1.f))) < 1e-6f; + valid &= std::abs(got[256] - (3 * std::cos(1.f) - 4 * std::sin(1.f))) < 1e-6f; + for (int i = 320; i < 384; ++i) valid &= got[i] == 9; + } + ok("breeze f32 rotary turns Q/K and preserves V", valid); + } + if (const auto* attn = find(pl, "attn_dense_h64_f32")) { + constexpr int N = 128; + std::vector zeros(4 * N, 0), values(4 * N); + for (int r = 0; r < 4; ++r) for (int d = 0; d < N; ++d) values[r * N + d] = r + 1 + 10 * (d / 64); + void* out = dalloc(values.size() * sizeof(float)); + const int s = launch(attn, {T(up_f32(zeros), RAD_F32, {4, N}), T(up_f32(zeros), RAD_F32, {4, N}), + T(up_f32(values), RAD_F32, {4, N}), TI32({3}, {0, 4, 8}), T(out, RAD_F32, {4, N})}, + {PI("M", 4), PI("head_dim", 64), PI("gqa", 1), PI("causal", 1), PI("window", 2), + PI("max_seqlen", 4), PI("cu_div", 2), PF("scale", 0.125), PS("dtype", "f32")}); + bool valid = s == RAD_OK; + if (valid) { + const auto got = down_f32(out, values.size()); + const float mean[] = {1, 1.5, 3, 3.5}; + for (int r = 0; r < 4; ++r) for (int d = 0; d < N; ++d) + valid &= std::abs(got[r * N + d] - (mean[r] + 10 * (d / 64))) < 1e-6f; + } + ok("breeze f32 attention isolates sequences, heads and causal windows", valid); + constexpr int R = 7, H = 2; + const auto q = randv(R * N, 0.2f), k = randv(R * N, 0.2f), v = randv(R * N, 1.0f); + void* dy = dalloc(R * N * sizeof(float)); + const int rc = launch(attn, {T(up_f32(q), RAD_F32, {R, N}), T(up_f32(k), RAD_F32, {R, N}), + T(up_f32(v), RAD_F32, {R, N}), TI32({3}, {0, 3, R}), T(dy, RAD_F32, {R, N})}, + {PI("M", R), PI("head_dim", 64), PI("gqa", 1), PI("causal", 1), PI("window", 3), + PI("max_seqlen", R), PF("scale", 0.125), PS("dtype", "f32")}); + bool matches = rc == RAD_OK; + if (matches) { + const auto got = down_f32(dy, R * N); + for (int r = 0; r < R; ++r) for (int h = 0; h < H; ++h) { + const int first = std::max(r < 3 ? 0 : 3, r - 2); + std::vector scores; + double sum = 0; + for (int j = first; j <= r; ++j) { + double dot = 0; + for (int d = 0; d < 64; ++d) dot += (double)q[r * N + h * 64 + d] * k[j * N + h * 64 + d]; + scores.push_back(std::exp(dot * 0.125)); sum += scores.back(); + } + for (int d = 0; d < 64; ++d) { + double want = 0; + for (int j = first; j <= r; ++j) want += scores[j - first] / sum * v[j * N + h * 64 + d]; + matches &= std::abs(got[r * N + h * 64 + d] - want) < 5e-6; + } + } + } + ok("breeze f32 attention agrees with double softmax/dot oracle", matches); + } else ok("breeze f32 attention present", false); + /* Exercise both the direct and tiled f32 causal strided conv, with two clips whose bounds + * are expressed in samples at a different rate. */ + for (int channels : {1, 32}) { + constexpr int R = 12, O = 6, K = 4; + std::vector cx(R * channels, 0), w(channels * channels * K, 0); + for (int r = 0; r < R; ++r) for (int c = 0; c < channels; ++c) cx[r * channels + c] = r % 8 + 1; + for (int c = 0; c < channels; ++c) for (int k = 0; k < K; ++k) w[(c * channels + c) * K + k] = 1; + std::vector ps = {PI("M", R), PI("cin", channels), PI("cout", channels), PI("k", K), + PI("dil", 1), PI("causal", 1), PI("stride", 2), PI("cu_div", 4), PS("dtype", "f32")}; + const std::string nm = fmt("breeze f32 causal stride, %d channels", channels); + void* dw = vg::stored_weight_f32(cv, ps, w, channels, channels * K, nm.c_str()); + if (!dw) continue; + void* dy = dalloc(O * channels * sizeof(float)); + RadTensor nores = TA(RAD_F32, {O, channels}), nobias = TA(RAD_F32, {channels}); + absent(nores); absent(nobias); + const int s = launch(cv, {T(up_f32(cx), RAD_F32, {R, channels}), T(dw, RAD_F32, {channels, channels, K}), + TI32({3}, {0, 32, 48}), nores, T(dy, RAD_F32, {O, channels}), nobias}, ps); + bool valid = s == RAD_OK; + if (valid) { + const auto got = down_f32(dy, O * channels); + for (int r = 0; r < O; ++r) for (int c = 0; c < channels; ++c) { + float want = 0; + for (int k = 0; k < K; ++k) { + const int ir = 2 * r + k - 2, begin = r < 4 ? 0 : 8, end = r < 4 ? 8 : 12; + if (ir >= begin && ir < end) want += cx[ir * channels + c]; + } + valid &= got[r * channels + c] == want; + } + } + ok(nm.c_str(), valid, "rc " + std::to_string(s)); + } +} + void vq_encode_cases(const Plugin& pl) { const RadKernelInfo* r = find(pl, "vq_encode"); if (!r) { ok("vq_encode", false, "row absent"); return; } @@ -15027,7 +15204,9 @@ static void gelu_mul_quant_i8_numeric(const Plugin& pl, bool grp = false) { * every width r4d_act_threads answers, including 256 at head_dim 512 (two channels per thread). * Gemma 3's class (head_dim 128, 16 q over 8 kv heads at one rank of two) has no value norm * (v_norm 0), so its chain is four ops and v must come back untouched. HYV3 adds 32 q / 4 kv - * heads, F32 norm gains widened from BF16 and positions near the 65K serving bound. */ + * heads, F32 norm gains widened from BF16 and positions near the 65K serving bound. Flint's full + * layers are the same heads with no positional encoding (`rotary_dim` 0): the chain is the two + * norms alone, and the one dispatch copies each normed head through its rotary stage. */ static void qkv_norm_rope_numeric(const Plugin& pl) { const RadKernelInfo* np = find(pl, "rmsnorm_p_bf16"); const RadKernelInfo* nrm = find(pl, "rmsnorm_bf16"); @@ -15045,7 +15224,8 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { Cls{ 128, 16, 8, 128, "rotary", 10000.0, false, false }, Cls{ 128, 32, 4, 128, "rotary", 11158840.0, false, false, true }, Cls{ 256, 8, 4, 256, "rotary", 10000.0, false, false }, - Cls{ 256, 0, 4, 256, "rotary", 10000.0, false, false } }) { + Cls{ 256, 0, 4, 256, "rotary", 10000.0, false, false }, + Cls{ 128, 32, 4, 0, "rotary", 10000.0, false, false, true } }) { /* 8 rows of the head-256 class are 8 x 32 workgroups of 8 wavefronts, a full card: the * launch adds an idle row past the cliff (r4d_cliff_rows), which must not change a byte. */ for (const int64_t M : { (int64_t)1, (int64_t)4, (int64_t)8, (int64_t)40 }) { @@ -15099,7 +15279,7 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { if (rc == RAD_OK) rc = launch_row(nrm, { T(dk[0], RAD_BF16, { M * cl.nkv, cl.hd }), T(dkw, wdt, { 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 = cl.nq ? 0 : 1; j < 2 && rc == RAD_OK; ++j) + for (int j = cl.nq ? 0 : 1; j < 2 && rc == RAD_OK && cl.rot; ++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), @@ -15114,6 +15294,7 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { PI("v_from_k", cl.vk ? 1 : 0), PI("v_norm", cl.vn ? 1 : 0), PS("dtype", "bf16") }); const std::string what = std::string("qkv_norm_rope hd=") + std::to_string(cl.hd) + (cl.nq ? "" : " n_head=0") + (cl.vn ? "" : " v_norm=0") + + (cl.rot ? "" : " rotary_dim=0") + (cl.w32 ? " f32 gains" : "") + " 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; @@ -15126,8 +15307,9 @@ static void qkv_norm_rope_numeric(const Plugin& pl) { 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 + (cl.nq ? " is byte-identical to rmsnorm_p + rmsnorm x2 + rope x2" - : " is byte-identical to rmsnorm + rope over k")).c_str(), + ok((what + (!cl.rot ? " is byte-identical to its norms alone" + : cl.nq ? " is byte-identical to rmsnorm_p + rmsnorm x2 + rope x2" + : " is byte-identical to rmsnorm + rope over k")).c_str(), nd == 0 && moved > 0, "differs " + std::to_string(nd) + ", changed from the input " + std::to_string(moved)); @@ -32287,6 +32469,9 @@ static void device_phase(const Plugin& pl) { if (sel("ras_pick")) au::ras_pick_cases(pl); if (sel("rvq_embed_bf16")) au::rvq_embed_cases(pl); if (sel("vq_encode")) au::vq_encode_cases(pl); + if (sel("breeze_reference") || sel("vq_euclidean_f32") || sel("elu_f32") || + sel("gemm_f32_nt") || sel("layernorm_f32") || sel("gelu_f32") || sel("attn_dense_h64_f32")) + au::breeze_reference_cases(pl); if (sel("frame_store")) au::frame_store_cases(pl); if (sel("iota")) au::iota_cases(pl); if (sel("sub_i32")) au::sub_i32_cases(pl); diff --git a/libr4d/r4d_shapes.cpp b/libr4d/r4d_shapes.cpp index 64dcf9af..dae28d44 100644 --- a/libr4d/r4d_shapes.cpp +++ b/libr4d/r4d_shapes.cpp @@ -382,6 +382,20 @@ extern "C" int r4d_shape_grid_embed_cpe(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +/* grid_embed_pad's: the same operands and drawing as grid_embed's. */ +extern "C" int r4d_shape_grid_embed_pad(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"), side = pi(p, n_p, "side"); + const uint32_t D = dt_act(p, n_p, "dtype"); + const RadOpdDesc l[] = { opd(D, M, n), opd(D, side * side, n), opd_idx(4, M, side) }; + R4D_PICK(l); +} + +/* window_order declines: its `crd` rows, segment grids and `cu` boundaries must describe whole + * raster grids, and an index draw cannot; the emu and unit tests build them by hand. */ +extern "C" int r4d_shape_window_order(const RadParam*, int, int, RadOpdDesc*) { + return RAD_E_UNSUPPORTED; +} + extern "C" int r4d_shape_gemm_nt_bias(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"), K = pi(p, n_p, "K"); const uint32_t D = dt_act(p, n_p, "dtype"); @@ -605,6 +619,13 @@ extern "C" int r4d_shape_unary(const RadParam* p, int n_p, int operand, R4D_PICK(l); } +extern "C" int r4d_shape_vq_euclidean(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"), bins = pi(p, n_p, "bins"); + if (M <= 0 || n <= 0 || bins <= 0) return RAD_E_UNSUPPORTED; + const RadOpdDesc l[] = {opd(RAD_F32, M, n), opd(RAD_F32, bins, n), opd(RAD_I32, 1, M)}; + R4D_PICK(l); +} + extern "C" int r4d_shape_silu_mul(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { diff --git a/libr4d/r4d_vit_muse.hip b/libr4d/r4d_vit_muse.hip new file mode 100644 index 00000000..6e859ed0 --- /dev/null +++ b/libr4d/r4d_vit_muse.hip @@ -0,0 +1,251 @@ +// r4d_vit_muse.hip -- Muse Glimmer's vision-tower coordinate ops: the zero-padded position-table +// resample (grid_embed_pad) and the window-attention permutation (window_order). +// +// Arithmetic matches libref (ref_elementwise.cpp): grid_embed_pad is grid_embed with the +// half-pixel-centre resample (align_corners=False) and grid_sample's padding_mode="zeros" -- a tap +// whose UNCLAMPED index falls outside [0, side) contributes nothing rather than reading an edge -- +// the four taps summed in f32 in libref's order, rounded to bf16, added and rounded again. +// window_order derives the whole permutation on the device from the coordinate planes: one +// workgroup walks the segments' windows, writes the cumulative boundaries, then scatters the +// gather index, its inverse and the swapped one-offset rope positions. +#include "r4d.h" +#include "r4d_args.h" +#include "r4d_emit.h" +#include "r4d_common.h" +#include "r4d_gdn_wmma.h" // bf2f / f32_to_bf16 + +#include + +namespace { + +constexpr int kThr = 256; + +__device__ __forceinline__ int imin2(int a, int b) { return a < b ? a : b; } + +// ldw: a table channel as f32, the weight stored bf16 or f32 (as grid_embed's kernel reads it). +template +__device__ __forceinline__ float ldw(const void* p, uint32_t i) { + return F32 ? ((const float*)p)[i] : bf2f(((const unsigned short*)p)[i]); +} + +// ---------------------------------------------------------------------------- grid_embed_pad +// ref_grid_embed_pad: grid_embed's operands, half-pixel-centre taps, off-table taps weighted zero. +// `crd` is [4, planes]: row, column, segment height, segment width. +template +__global__ __launch_bounds__(kThr) void grid_embed_pad_kernel( + unsigned short* __restrict__ x, const void* __restrict__ tab, const int32_t* __restrict__ crd, + uint32_t n, int side, uint32_t x_ld, uint32_t plane) { + const uint32_t m = blockIdx.x; + const int g[4] = { crd[m], crd[plane + m], crd[2 * plane + m], crd[3 * plane + m] }; + int th[2], tw[2]; + float wh[2], ww[2]; + auto axis = [&](int idx, int size, int* t, float* wt) { + if (size < 1) size = 1; + const float src = (float)side / (float)size * ((float)idx + 0.5f) - 0.5f; + const float fl = floorf(src); +#pragma unroll + for (int k = 0; k < 2; ++k) { + const int raw = (int)fl + k; + t[k] = raw < 0 ? 0 : (raw > side - 1 ? side - 1 : raw); + const float d = fabsf(src - fl - (float)k); + const float u = 1.0f - d > 0.0f ? 1.0f - d : 0.0f; + wt[k] = raw >= 0 && raw <= side - 1 ? u : 0.0f; + } + }; + axis(g[0], g[2], th, wh); + axis(g[1], g[3], tw, ww); + unsigned short* __restrict__ xr = x + (size_t)m * x_ld; + for (uint32_t i = threadIdx.x; i < n; i += kThr) { + float acc = 0.0f; +#pragma unroll + for (int ki = 0; ki < 2; ++ki) +#pragma unroll + for (int kj = 0; kj < 2; ++kj) + acc += ldw(tab, (uint32_t)(th[ki] * side + tw[kj]) * n + i) * + (wh[ki] * ww[kj]); + const float pe = bf2f(f32_to_bf16(acc)); + xr[i] = f32_to_bf16(bf2f(xr[i]) + pe); + } +} + +// ---------------------------------------------------------------------------- window_order +// ref_window_order: HF's get_vision_window_index as a gather-index computation, entirely from the +// coordinate planes. One workgroup for the pass, three phases over global memory (P is a tower +// pass's patches, at most a few thousand): +// 1. every thread lays down the identity over [0, P); +// 2. thread 0 walks the segments' windows in permuted order, writing each window's base slot as +// cuw's boundary -- the prefix the caller's windowed attention and the scatter both read; +// 3. the threads re-derive each patch's window from the boundaries and scatter idx, inv and pos. +// `window` <= 0 is the identity permutation with cuw = cu. +__global__ __launch_bounds__(kThr) void window_order_kernel( + const int32_t* __restrict__ crd, const int32_t* __restrict__ cu, int32_t* __restrict__ idx, + int32_t* __restrict__ inv, int32_t* __restrict__ pos, int32_t* __restrict__ cuw, + uint32_t P, uint32_t M, uint32_t plane, uint32_t pos_plane, uint32_t cu_len, + uint32_t cuw_len, int window) { + // 1. the identity everywhere, so slots the pass does not cover are defined; the covered slots + // already get their rope positions (col + 1, row + 1), identity or not. + for (uint32_t p = threadIdx.x; p < P; p += kThr) { + idx[p] = (int32_t)p; + inv[p] = (int32_t)p; + if (p < M) { + pos[p] = crd[plane + p] + 1; + pos[pos_plane + p] = crd[p] + 1; + } else { + pos[p] = 1; + pos[pos_plane + p] = 1; + } + } + if (window <= 0) { + if (threadIdx.x == 0) { + /* The caller narrows cuw to the pass's window count + 1, so every write below is + * bounded by its length rather than by P. */ + const uint32_t k = cu_len < cuw_len ? cu_len : cuw_len; + for (uint32_t i = 0; i < k; ++i) cuw[i] = cu[i]; + const int32_t last = k ? cuw[k - 1] : 0; + for (uint32_t i = k; i < cuw_len; ++i) cuw[i] = last; + } + return; + } + __syncthreads(); + // 2. the windows of each segment in permuted order; each boundary is a window's base slot. + if (threadIdx.x == 0) { + int64_t slot = 0; + uint32_t nwin = 0; + for (uint32_t s = 0; s + 1 < cu_len && cu[s] < (int32_t)M; ++s) { + const int start = cu[s] < 0 ? 0 : cu[s]; + int end = cu[s + 1]; + if (end > (int32_t)M) end = (int32_t)M; + const int gh = start < end ? crd[2 * plane + start] : 1; + const int gw = start < end ? crd[3 * plane + start] : 1; + const int nh = (gh + window - 1) / window, nw = (gw + window - 1) / window; + for (int wr = 0; wr < nh; ++wr) + for (int wc = 0; wc < nw; ++wc) { + const int rows_in = imin2(window, gh - wr * window); + const int cols_in = imin2(window, gw - wc * window); + if (nwin < cuw_len) cuw[nwin] = (int32_t)slot; + ++nwin; + slot += (int64_t)rows_in * cols_in; + } + } + if (nwin < cuw_len) cuw[nwin] = (int32_t)slot; + for (uint32_t i = nwin + 1; i < cuw_len; ++i) cuw[i] = (int32_t)slot; + } + __syncthreads(); + // 3. each patch's slot: its segment, window id and rank in the window, off the boundaries. + for (uint32_t p = threadIdx.x; p < M; p += kThr) { + const int r = crd[p], c = crd[plane + p], gw = crd[3 * plane + p]; + int wr = r / window, wc = c / window; + if (wr < 0) wr = 0; + if (wc < 0) wc = 0; + const int cols_in = imin2(window, gw - wc * window); + // The patch's segment: the last boundary at or before p; the windows before it, replayed. + uint32_t s = 0; + int64_t wbefore = 0; + for (; s + 1 < cu_len && cu[s + 1] <= (int32_t)p; ++s) { + const int tstart = cu[s] < 0 ? 0 : cu[s]; + int tend = cu[s + 1]; + if (tend > (int32_t)M) tend = (int32_t)M; + const int th = tstart < tend ? crd[2 * plane + tstart] : 1; + const int tw_ = tstart < tend ? crd[3 * plane + tstart] : 1; + wbefore += (int64_t)((th + window - 1) / window) * ((tw_ + window - 1) / window); + } + const int start = cu[s] < 0 ? 0 : cu[s]; + const int sgw = start < (int)M ? crd[3 * plane + start] : 1; + const int nw = (sgw + window - 1) / window; + const int64_t wid = wbefore + (int64_t)wr * nw + wc; + const int64_t at = cuw[wid] + (int64_t)(r - wr * window) * cols_in + (c - wc * window); + idx[at] = (int32_t)p; + inv[p] = (int32_t)at; + pos[at] = c + 1; + pos[pos_plane + at] = r + 1; + } +} + +} // namespace + +/* ------------------------------------------------------------------ grid_embed_pad */ +enum { GEP_X = 0, GEP_TAB, GEP_CRD }; + +extern "C" int r4d_rad_grid_embed_pad(const RadArgs* a, RadStream stream) { + const RadTensor* x = r4d_opt(a, GEP_X); + const RadTensor* tab = r4d_opt(a, GEP_TAB); + const RadTensor* crd = r4d_opt(a, GEP_CRD); + if (!x || !tab || !crd) return R4D_NO(RAD_E_INVAL); + if (x->dtype != RAD_BF16 || crd->dtype != RAD_I32) return R4D_NO(RAD_E_DTYPE); + if (tab->dtype != RAD_BF16 && tab->dtype != RAD_F32) return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(tab)) return R4D_NO(RAD_E_STRIDE); + const long long n = r4d_geti_or(a, "n", r4d_dim(tab, (int)tab->rank - 1)); + const long long side = r4d_geti_or(a, "side", 0); + if (n <= 0 || side <= 0 || r4d_numel(tab) < side * side * n) return R4D_NO(RAD_E_SHAPE); + long long M = 0; + const long long x_ld = r4d_rows_pitch(x, n, &M); + if (x_ld < 0) return R4D_NO(RAD_E_STRIDE); + if (crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < M || crd->stride[1] != 1) + return R4D_NO(RAD_E_SHAPE); + if (M <= 0) return R4D_NO(RAD_E_SHAPE); + /* crd is a [4, pass] view of the full-pass coord buffer: the plane pitch is its leading + * stride when that exceeds the shape. */ + const uint32_t plane = (uint32_t)(crd->stride[0] >= crd->shape[1] ? crd->stride[0] + : crd->shape[1]); + if (tab->dtype == RAD_F32) + return R4D_EMIT(stream, grid_embed_pad_kernel, dim3((uint32_t)M), dim3(kThr), 0, + (unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd), + (uint32_t)n, (int)side, (uint32_t)x_ld, plane); + return R4D_EMIT(stream, grid_embed_pad_kernel, dim3((uint32_t)M), dim3(kThr), 0, + (unsigned short*)r4d_wp(x), r4d_p(tab), (const int32_t*)r4d_p(crd), + (uint32_t)n, (int)side, (uint32_t)x_ld, plane); +} + +/* ------------------------------------------------------------------ window_order */ +enum { WO_CRD = 0, WO_CU, WO_IDX, WO_INV, WO_POS, WO_CUW }; + +extern "C" int r4d_rad_window_order(const RadArgs* a, RadStream stream) { + const RadTensor* crd = r4d_opt(a, WO_CRD); + const RadTensor* cu = r4d_opt(a, WO_CU); + const RadTensor* idx = r4d_opt(a, WO_IDX); + const RadTensor* inv = r4d_opt(a, WO_INV); + const RadTensor* pos = r4d_opt(a, WO_POS); + const RadTensor* cuw = r4d_opt(a, WO_CUW); + if (!crd || !cu || !idx || !inv || !pos || !cuw) return R4D_NO(RAD_E_INVAL); + if (crd->dtype != RAD_I32 || cu->dtype != RAD_I32 || idx->dtype != RAD_I32 || + inv->dtype != RAD_I32 || pos->dtype != RAD_I32 || cuw->dtype != RAD_I32) + return R4D_NO(RAD_E_DTYPE); + if (!r4d_contig(cu) || !r4d_contig(idx) || !r4d_contig(inv) || !r4d_contig(cuw)) + return R4D_NO(RAD_E_STRIDE); + /* `M` is a ranged parameter: the params carry the band's bound (16384), while this issue's + * patches are the coord view's columns. cuw is narrowed to the pass's windows + 1. */ + const long long M = crd ? crd->shape[crd->rank - 1] : 0; + const long long window = r4d_geti_or(a, "window", 0); + if (M <= 0) return R4D_NO(RAD_E_SHAPE); + /* crd and pos are plane views of full-pass buffers ([4, P] and [2, P] declared) read at this + * pass's M rows; their plane pitch is the leading stride when it exceeds the shape. */ + if (crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < M || crd->stride[1] != 1) + return R4D_NO(RAD_E_SHAPE); + /* `pos` is the two rope planes either as [2, M] (or a pitched [2, P] view) or as one + * [2 * M] row: both describe the same bytes, so the pitch is the row length in the first form + * and M in the second. */ + long long pplane = 0; + if (pos->rank == 1) { + if (pos->stride[0] != 1 || r4d_numel(pos) < 2 * M) return R4D_NO(RAD_E_SHAPE); + pplane = M; + } else if (pos->rank == 2) { + if (pos->shape[0] < 2 || pos->shape[1] < M || pos->stride[1] != 1) + return R4D_NO(RAD_E_SHAPE); + pplane = pos->stride[0] >= pos->shape[1] ? pos->stride[0] : pos->shape[1]; + } else { + return R4D_NO(RAD_E_SHAPE); + } + /* P is THIS pass's patches (M), not the coord buffer's declared width: the caller narrows + * idx/inv/pos/cuw to the pass, so a slot lies in [0, M). */ + const long long P = M; + const long long cplane = crd->stride[0] >= crd->shape[1] ? crd->stride[0] : crd->shape[1]; + if (r4d_numel(cu) < 2 || r4d_numel(idx) < M || r4d_numel(inv) < M || r4d_numel(pos) < 2 * M || + r4d_numel(cuw) < 2) + return R4D_NO(RAD_E_SHAPE); + return R4D_EMIT(stream, window_order_kernel, dim3(1), dim3(kThr), 0, + (const int32_t*)r4d_p(crd), (const int32_t*)r4d_p(cu), + (int32_t*)r4d_wp(idx), (int32_t*)r4d_wp(inv), (int32_t*)r4d_wp(pos), + (int32_t*)r4d_wp(cuw), (uint32_t)P, (uint32_t)M, (uint32_t)cplane, + (uint32_t)pplane, (uint32_t)r4d_numel(cu), (uint32_t)r4d_numel(cuw), + (int)window); +} diff --git a/libref/ref_audio.cpp b/libref/ref_audio.cpp index 6a2a4f00..8a79ee0b 100644 --- a/libref/ref_audio.cpp +++ b/libref/ref_audio.cpp @@ -46,6 +46,50 @@ inline int64_t ldi(const RadTensor* t, int64_t i) { } /* namespace */ /* ------------------------------------------------------------------ conv1d */ +int ref_elu(const RadArgs* a, RadStream) { + if (!have(a, 2)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *y = &a->t[1]; + if (numel(y) <= 0 || numel(x) < numel(y)) return RAD_E_SHAPE; + REF_PAR_FOR(numel(y)) + for (int64_t i = 0; i < numel(y); ++i) { + const float v = ldt(x, offlin(x, i)); + stt(y, offlin(y, i), v >= 0 ? v : std::expm1(v)); + } + return RAD_OK; +} + +/* Mimi's Euclidean RVQ, not the cosine quantiser used by drama-3. Projections belong to + * the enclosing split quantiser; each step subtracts its centroid in the projected space. */ +int ref_vq_euclidean(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *cb = &a->t[1], *codes = &a->t[2]; + const int64_t n = p_int(a, "n", 0), bins = p_int(a, "bins", 0); + if (n <= 0 || bins <= 0 || numel(cb) != bins * n || codes->dtype != RAD_I32) + return RAD_E_SHAPE; + const int64_t rows = rows_of(x, n); + if (rows < 1 || numel(codes) < rows) return RAD_E_SHAPE; + REF_PAR_FOR(rows * bins * n) + for (int64_t r = 0; r < rows; ++r) { + float best = INFINITY; + int64_t pick = 0; + for (int64_t k = 0; k < bins; ++k) { + float d = 0; + for (int64_t j = 0; j < n; ++j) { + const float delta = ldt(x, rowoff(x, r, n) + j * laststride(x)) - + ldt(cb, rowoff(cb, k, n) + j * laststride(cb)); + d += delta * delta; + } + if (d < best) { best = d; pick = k; } + } + st_int(codes->dtype, codes->data, offlin(codes, r), pick); + for (int64_t j = 0; j < n; ++j) { + const int64_t at = rowoff(x, r, n) + j * laststride(x); + stt(x, at, ldt(x, at) - ldt(cb, rowoff(cb, pick, n) + j * laststride(cb))); + } + } + return RAD_OK; +} + /* A 1-D convolution over sequences of rows, channels innermost: x [rows, cin], y [rows, cout], * `cu_seqlens` bounding each sequence (row indices of both operands, as every sequenced op reads * them), outside of which the input reads zero (each sequence is padded on its own). w is diff --git a/libref/ref_elementwise.cpp b/libref/ref_elementwise.cpp index 0f383143..f0bb8e99 100644 --- a/libref/ref_elementwise.cpp +++ b/libref/ref_elementwise.cpp @@ -316,6 +316,178 @@ int ref_grid_embed_cpe(const RadArgs* a, RadStream) { return RAD_OK; } +/* ------------------------------------------------------------------ grid_embed_pad */ +/* The same learned table and operands as grid_embed's, resampled in the half-pixel-centre form + * (align_corners=False) with grid_sample's padding_mode="zeros": taps whose UNCLAMPED index falls + * outside [0, side-1) contribute nothing rather than reading the edge. Per axis, + * src = (i + 0.5) * side / size - 0.5; floor(src) and floor(src) + 1, each carrying the linear hat + * weight (1 - |src - tap|)+ masked to zero off the table. For grids no larger than the table the + * mask never fires and the op agrees with grid_embed_aa's centre positions (not grid_embed's + * corners-aligned ones); it differs from them only when a grid upsamples past the table, which is + * the common case for Muse. The four products are summed in f32 in grid_embed's order (top-left, + * top-right, bottom-left, bottom-right), rounded to x's dtype, then added and rounded again. */ +int ref_grid_embed_pad(const RadArgs* a, RadStream) { + if (!have(a, 3)) return RAD_E_INVAL; + const RadTensor *x = &a->t[0], *tab = &a->t[1], *crd = &a->t[2]; + const int64_t n = p_int(a, "n", tab->rank ? tab->shape[tab->rank - 1] : 0); + const int64_t side = p_int(a, "side", 0); + if (n <= 0 || side <= 0 || numel(tab) < side * side * n) return RAD_E_SHAPE; + const int64_t rows = rows_of(x, n); + if (rows <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < rows) + return RAD_E_SHAPE; + const int64_t cs = crd->stride[0], ms = crd->stride[1]; + const int64_t ts = laststride(tab); + + REF_PAR_FOR(rows * n * 4) + for (int64_t r = 0; r < rows; ++r) { + const int64_t gr = ld_int(crd->dtype, crd->data, 0 * cs + r * ms); + const int64_t gc = ld_int(crd->dtype, crd->data, 1 * cs + r * ms); + const int64_t gh = ld_int(crd->dtype, crd->data, 2 * cs + r * ms); + const int64_t gw = ld_int(crd->dtype, crd->data, 3 * cs + r * ms); + int64_t th[2], tw[2]; + float wh[2], ww[2]; + auto axis = [&](int64_t idx, int64_t size, int64_t* t, float* w) { + if (size < 1) size = 1; + const float src = (float)side / (float)size * ((float)idx + 0.5f) - 0.5f; + const float fl = std::floor(src); + for (int k = 0; k < 2; ++k) { + const int64_t raw = (int64_t)fl + k; + t[k] = raw < 0 ? 0 : (raw > side - 1 ? side - 1 : raw); + const float d = std::fabs(src - fl - (float)k); + const float u = 1.0f - d > 0.0f ? 1.0f - d : 0.0f; + w[k] = raw >= 0 && raw <= side - 1 ? u : 0.0f; + } + }; + axis(gr, gh, th, wh); + axis(gc, gw, tw, ww); + const int64_t xb = rowoff(x, r, n), xs = laststride(x); + for (int64_t i = 0; i < n; ++i) { + float acc = 0.0f; + for (int ki = 0; ki < 2; ++ki) + for (int kj = 0; kj < 2; ++kj) + acc += ldt(tab, rowoff(tab, th[ki] * side + tw[kj], n) + i * ts) * + (wh[ki] * ww[kj]); + const float pe = round_dt(x->dtype, acc); + stt(x, xb + i * xs, ldt(x, xb + i * xs) + pe); + } + } + return RAD_OK; +} + +/* ------------------------------------------------------------------ window_order */ +/* The window-attention permutation of one encoder pass, computed entirely from the on-device + * coordinate planes: HF's get_vision_window_index as a gather-index computation. Windows partition + * each segment (one segment == one frame): window row = row/window, window col = col/window, + * windows scanned window-row-major and ragged at the segment's right and bottom edges; within a + * window patches keep raster order, and windows never span segments. + * + * `crd` is [4, P] i32 -- row, column, segment height, segment width per patch -- and `cu` is [S+1] + * i32, the per-frame segment boundaries in patches. Outputs, all i32: `idx` [P], slot -> source + * patch (the gather index); `inv` [P], source patch -> slot; `pos` [2, P], each slot's rope + * positions (col + 1, row + 1) -- Muse's rotary wants the axes swapped and offset by one relative + * to the coordinate planes (HF's position_ids.flip(-1) + 1) -- laid out component-major like the + * planes; and `cuw` [P+1], the cumulative window boundaries in the permuted order, n_windows + 1 + * entries used, the rest holding the total. `M` is the patches this pass covers, 1..P: slots past + * M are the identity, so a caller may reuse buffers sized for a bigger pass. `window` <= 0 makes + * the permutation the identity and cuw = cu. */ +int ref_window_order(const RadArgs* a, RadStream) { + if (!have(a, 6)) return RAD_E_INVAL; + const RadTensor *crd = &a->t[0], *cu = &a->t[1]; + RadTensor *idx = const_cast(&a->t[2]), *inv = const_cast(&a->t[3]), + *pos = const_cast(&a->t[4]), *cuw = const_cast(&a->t[5]); + const int64_t M = p_int(a, "M", 0); + const int64_t win = p_int(a, "window", 0); + if (M <= 0 || crd->rank != 2 || crd->shape[0] < 4 || crd->shape[1] < M) return RAD_E_SHAPE; + if (numel(cu) < 2 || numel(idx) < M || numel(inv) < M || numel(pos) < 2 * M || + numel(cuw) < M + 1) + return RAD_E_SHAPE; + const int64_t P = crd->shape[1]; + const int64_t cs = crd->stride[0], ms = crd->stride[1]; + auto gx = [&](int c, int64_t p) { + return ld_int(crd->dtype, crd->data, (int64_t)c * cs + p * ms); + }; + + /* The identity: every slot its own patch, cuw = cu, the tail padded with the last boundary. */ + auto identity = [&]() { + for (int64_t p = 0; p < P; ++p) { + st_int(idx->dtype, idx->data, p, p); + st_int(inv->dtype, inv->data, p, p); + if (p < M) { + st_int(pos->dtype, pos->data, p, gx(1, p) + 1); + st_int(pos->dtype, pos->data, P + p, gx(0, p) + 1); + } else { + st_int(pos->dtype, pos->data, p, 1); + st_int(pos->dtype, pos->data, P + p, 1); + } + } + int64_t last = 0; + const int64_t k = numel(cu) < M + 1 ? numel(cu) : M + 1; + for (int64_t i = 0; i < k; ++i) { + last = ld_int(cu->dtype, cu->data, i); + st_int(cuw->dtype, cuw->data, i, last); + } + for (int64_t i = k; i < M + 1; ++i) st_int(cuw->dtype, cuw->data, i, last); + }; + if (win <= 0) { + identity(); + return RAD_OK; + } + + /* Slot arithmetic: patch p's segment, its window and its rank in the window follow from the + * coordinates alone, so a first walk writes the window boundaries and a second scatters. */ + std::vector seg(M), seg_nw, seg_first_win; + std::vector wbase((size_t)M); /* each window's base slot; windows <= M */ + int64_t s = 0, slot = 0, nwin = 0; + const int64_t S = numel(cu) - 1; + while (s < S) { + const int64_t start = ld_int(cu->dtype, cu->data, s); + if (start >= M) break; + int64_t end = ld_int(cu->dtype, cu->data, s + 1); + if (end > M) end = M; + const int64_t gh = start < end ? gx(2, start) : 1; + const int64_t gw = start < end ? gx(3, start) : 1; + const int64_t nh = (gh + win - 1) / win, nw = (gw + win - 1) / win; + seg_first_win.push_back(nwin); + seg_nw.push_back(nw); + for (int64_t p = start; p < end; ++p) seg[p] = (int64_t)seg_first_win.size() - 1; + for (int64_t wr = 0; wr < nh; ++wr) + for (int64_t wc = 0; wc < nw; ++wc) { + const int64_t rows_in = std::min(win, gh - wr * win); + const int64_t cols_in = std::min(win, gw - wc * win); + st_int(cuw->dtype, cuw->data, nwin, slot); + wbase[(size_t)nwin] = slot; + ++nwin; + slot += rows_in * cols_in; + } + ++s; + } + st_int(cuw->dtype, cuw->data, nwin, slot); + for (int64_t i = nwin + 1; i < M + 1; ++i) st_int(cuw->dtype, cuw->data, i, slot); + + for (int64_t p = 0; p < P; ++p) { + if (p >= M) { + st_int(idx->dtype, idx->data, p, p); + st_int(inv->dtype, inv->data, p, p); + st_int(pos->dtype, pos->data, p, 1); + st_int(pos->dtype, pos->data, P + p, 1); + continue; + } + const int64_t r = gx(0, p), c = gx(1, p); + const int64_t gw = gx(3, p); + int64_t wr = r / win, wc = c / win; + if (wr < 0) wr = 0; + if (wc < 0) wc = 0; + const int64_t cols_in = std::min(win, gw - wc * win); + const int64_t wid = seg_first_win[(size_t)seg[p]] + wr * seg_nw[(size_t)seg[p]] + wc; + const int64_t at = wbase[(size_t)wid] + (r - wr * win) * cols_in + (c - wc * win); + st_int(idx->dtype, idx->data, at, p); + st_int(inv->dtype, inv->data, p, at); + st_int(pos->dtype, pos->data, at, c + 1); + st_int(pos->dtype, pos->data, P + at, r + 1); + } + return RAD_OK; +} + /* ------------------------------------------------------------------ add / mul */ /* Elementwise over the output's extent. `b` may be a single row of exactly `n` elements, which * broadcasts along rows (a bias add); nothing else broadcasts, so a shape bug cannot pass as a diff --git a/libref/ref_ops.h b/libref/ref_ops.h index 25d5e164..32652adb 100644 --- a/libref/ref_ops.h +++ b/libref/ref_ops.h @@ -72,8 +72,10 @@ int ref_hc_project (const RadArgs*, RadStream); int ref_mtp_enter (const RadArgs*, RadStream); int ref_layernorm (const RadArgs*, RadStream); int ref_grid_embed (const RadArgs*, RadStream); +int ref_grid_embed_pad (const RadArgs*, RadStream); int ref_grid_embed_aa (const RadArgs*, RadStream); int ref_grid_embed_cpe (const RadArgs*, RadStream); +int ref_window_order (const RadArgs*, RadStream); int ref_lili_cand (const RadArgs*, RadStream); int ref_lili_attn (const RadArgs*, RadStream); int ref_lili_factor (const RadArgs*, RadStream); @@ -232,6 +234,10 @@ int ref_vsa_select(const RadArgs*, RadStream); int ref_attn_vsa(const RadArgs*, RadStream); /* ref_audio.cpp */ int ref_conv1d(const RadArgs*, RadStream); +int ref_elu(const RadArgs*, RadStream); +int ref_vq_euclidean(const RadArgs*, RadStream); +int ref_elu_shape(const RadParam*, int, int, RadOpdDesc*); +int ref_vq_euclidean_shape(const RadParam*, int, int, RadOpdDesc*); int ref_conv_t1d(const RadArgs*, RadStream); int ref_snake(const RadArgs*, RadStream); int ref_snake_aa(const RadArgs*, RadStream); @@ -362,8 +368,10 @@ REF_SHAPE_FN(ref_hc_project); REF_SHAPE_FN(ref_mtp_enter); REF_SHAPE_FN(ref_layernorm); REF_SHAPE_FN(ref_grid_embed); +REF_SHAPE_FN(ref_grid_embed_pad); REF_SHAPE_FN(ref_grid_embed_aa); REF_SHAPE_FN(ref_grid_embed_cpe); +REF_SHAPE_FN(ref_window_order); REF_SHAPE_FN(ref_lili_cand); REF_SHAPE_FN(ref_lili_attn); REF_SHAPE_FN(ref_lili_factor); diff --git a/libref/ref_registry.cpp b/libref/ref_registry.cpp index dc1a5547..c0bca2e8 100644 --- a/libref/ref_registry.cpp +++ b/libref/ref_registry.cpp @@ -172,6 +172,10 @@ static const RadOperandSpec oLayernorm[] = { OPD("x"), WGT("w"), WGT_O("b"), OUT /* A learned position table resampled to each row's grid and added in (a vision tower's). */ static const RadParamSpec pGridEmbed[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype") }; static const RadOperandSpec oGridEmbed[] = { INOUT("x"), WGT("table"), OPD("coord") }; +/* window_order: the window permutation of one pass, from the coordinate planes alone. */ +static const RadParamSpec pWindowOrder[] = { P_INT("M"), P_INT("window") }; +static const RadOperandSpec oWindowOrder[] = { OPD("crd"), OPD_O("cu"), OUT("idx"), OUT("inv"), + OUT("pos"), OUT("cuw") }; /* grid_embed_cpe adds the rows a segment carries ahead of its patches (n_prefix, `prefix`). */ static const RadParamSpec pGridEmbedCpe[] = { P_INT("M"), P_INT("n"), P_INT("side"), P_STR("dtype"), P_INTO("n_prefix") }; @@ -1095,6 +1099,8 @@ static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_STR("dtype") }; static const RadOperandSpec oVqEncode[] = { INOUT("x"), WGT("in_w"), WGT("in_b"), WGT("cb"), WGT("out_w"), WGT("out_b"), OUT("codes") }; +static const RadParamSpec pVqEuclidean[] = { P_INT("M"), P_INT("n"), P_INT("bins"), P_STR("dtype") }; +static const RadOperandSpec oVqEuclidean[] = { INOUT("x"), WGT("cb"), OUT("codes") }; static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"), P_INTO("rep"), P_STR("dtype") }; static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"), @@ -1227,6 +1233,23 @@ static const RadOpSchema kSchemas[] = { "`coord` is [4, M] -- row, column, grid height, grid width -- and the position is sampled " "bilinearly with the grid's corners on the table's corners (align_corners), edge taps clamped. " "The taps are summed in f32 and rounded to x's dtype, then added to x and rounded again." }, +{ "grid_embed_pad", ARR(pGridEmbed), ARR(oGridEmbed), + "x[m] += the table resampled at row m's grid position in the half-pixel-centre form " + "(align_corners=False) with grid_sample's padding_mode=\"zeros\": per axis taps at floor(src) " + "and floor(src) + 1 of src = (i + 0.5) * side / size - 0.5, each carrying the hat weight " + "(1 - |src - tap|)+, and a tap whose UNCLAMPED index falls outside the table contributes zero " + "rather than reading an edge. Same operands and tap order as `grid_embed`; equal to it whenever " + "the grid fits the table, different only when a grid upsamples past it (Muse's case)." }, +{ "window_order", ARR(pWindowOrder), ARR(oWindowOrder), + "The window-attention permutation of one encoder pass (HF's get_vision_window_index) computed " + "from the coordinates alone: `crd` [4, P] i32 is row, column, segment height, segment width per " + "patch and `cu` [S+1] i32 the per-frame segment boundaries. Windows of `window` patches " + "partition each segment, window-row-major, ragged at the segment's right and bottom edges, " + "patches raster within a window and windows never across segments. Outputs i32: `idx` [P], " + "slot -> source patch (the gather index); `inv` [P], the inverse; `pos` [2, P], each slot's rope " + "positions (col + 1, row + 1), component-major like the planes; `cuw` [P+1], the cumulative " + "window boundaries in the permuted order, n_windows + 1 entries used. `M` bands the pass; slots " + "past M are the identity. `window` <= 0 is the identity permutation, cuw = cu." }, { "grid_embed_aa", ARR(pGridEmbed), ARR(oGridEmbed), "x += the side x side table resampled as torch's F.interpolate(bilinear, align_corners=False, " "antialias=True) resamples it to the row's grid -- SigLIP2's position embedding: per axis a " @@ -2093,8 +2116,8 @@ static const RadOpSchema kSchemas[] = { "a 1-D convolution over the sequences `cu_seqlens` bounds, channels innermost: x [rows, cin], " "y [rows, cout], PyTorch's [cout, cin, k] weight and an optional bias, dilation `dil` and padding " "dil (k - 1) / 2 a side (k odd), or dil (k - 1) on the left with `causal` 1, zeros outside each " - "sequence; `res` added after the bias, then `act` none, tanh or clamp (to [-1, 1]). bf16 only " - "with `stride` > 1: one sequence [0, rows of x], an explicit `pad` and any k, output row m " + "sequence; `res` added after the bias, then `act` none, tanh or clamp (to [-1, 1]). With " + "`stride` > 1 and an explicit `pad` (bf16 only): one sequence [0, rows of x], any k, output row m " "reading x[m * stride + tap * dil - pad] — PyTorch's zero-padded strided conv exactly." }, { "conv_t1d", ARR(pConvT1d), ARR(oConvT1d), "a transposed 1-D convolution of kernel `k` >= stride (2 stride by default), padding `pad` " @@ -2123,7 +2146,10 @@ static const RadOpSchema kSchemas[] = { { "vq_encode", ARR(pVqEncode), ARR(oVqEncode), "one residual vector quantiser step: e = in_w x + in_b, the code the row of cb of greatest " "cosine with e (the lower index on a tie), then x -= out_w cb[code] + out_b; f32, x rounded " - "once." }, + "once." }, +{ "vq_euclidean", ARR(pVqEuclidean), ARR(oVqEuclidean), + "nearest Euclidean centroid (lower index on ties), codes written and centroid subtracted from x." }, +{ "elu", ARR(pMnD), ARR(oUnary), "y = x >= 0 ? x : expm1(x), alpha 1." }, { "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix), "a frame's conditioning row: the softmax(logits)-weighted sum of hid's L planes times scale, " "stored at dst[lane * stride + frame - 1] for frame >= 1 and status[lane] >= 0." }, @@ -2356,6 +2382,12 @@ SIMPLE("ref_layernorm", "layernorm", "norm", "layer norm with gain and bias", DT ref_layernorm), SIMPLE("ref_grid_embed", "grid_embed", "elem", "bilinear resample of a learned position grid, added in", DT_FLOAT, ref_grid_embed), +SIMPLE("ref_grid_embed_pad", "grid_embed_pad", "elem", + "half-pixel bilinear resample of a position grid, zero-padded taps, added in", DT_FLOAT, + ref_grid_embed_pad), +SIMPLE("ref_window_order", "window_order", "elem", + "the window-attention permutation of one pass, from its coordinates", DT_ANY, + ref_window_order), SIMPLE("ref_grid_embed_aa", "grid_embed_aa", "elem", "antialiased half-pixel bilinear resample of a position grid, added in", DT_FLOAT, ref_grid_embed_aa), @@ -2805,7 +2837,10 @@ SIMPLE("ref_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick SIMPLE("ref_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes", DT_FLOAT, ref_rvq_embed), SIMPLE("ref_vq_encode", "vq_encode", "elem", - "a residual quantiser's step: the nearest code by cosine", DT_FLOAT, ref_vq_encode), + "a residual quantiser's step: the nearest code by cosine", DT_FLOAT, ref_vq_encode), +SIMPLE("ref_vq_euclidean", "vq_euclidean", "elem", "Euclidean residual quantiser", DT_FLOAT, + ref_vq_euclidean), +SIMPLE("ref_elu", "elu", "elem", "ELU, alpha 1", DT_FLOAT, ref_elu), SIMPLE("ref_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane", DT_FLOAT, ref_frame_mix_store), SIMPLE("ref_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY, diff --git a/libref/ref_shapes.cpp b/libref/ref_shapes.cpp index c6e34fb1..2db2b433 100644 --- a/libref/ref_shapes.cpp +++ b/libref/ref_shapes.cpp @@ -510,6 +510,22 @@ int ref_grid_embed_aa_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* return o.finish("grid_embed_aa", operand, out); } +/* grid_embed_pad's: the same operands and drawing as grid_embed's. */ +int ref_grid_embed_pad_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), side = gi(p, n_p, "side", 0); + if (M <= 0 || n <= 0 || side <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(D, { M, n }); /* x, INOUT */ + o.t(D, { side * side, n }); /* table */ + o.t_idx({ 4, M }, side, -1, 0); + return o.finish("grid_embed_pad", operand, out); +} + +/* window_order declines: its `crd` rows, segment grids and `cu` boundaries must describe whole + * raster grids, and an index draw cannot; avx_check_hand.cpp and the unit tests build them. */ +int ref_window_order_shape(const RadParam*, int, int, RadOpdDesc*) { return RAD_E_UNSUPPORTED; } + /* grid_embed's operands plus the prefix rows; coordinates drawn over the table's side. */ int ref_grid_embed_cpe_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) { const uint32_t D = act_dt(p, n_p); @@ -3896,6 +3912,25 @@ int ref_resample_nearest_shape(const RadParam* p, int n_p, int operand, RadOpdDe return o.finish("resample_nearest", operand, out); } +int ref_elu_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; + Opd o; + o.t(act_dt(p, n_p), {M, n}); + o.t(act_dt(p, n_p), {M, n}); + return o.finish("elu", operand, out); +} + +int ref_vq_euclidean_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), bins = gi(p, n_p, "bins", 0); + if (M <= 0 || n <= 0 || bins <= 0) return RAD_E_UNSUPPORTED; + Opd o; + o.t(act_dt(p, n_p), {M, n}); + o.t(act_dt(p, n_p), {bins, n}); + o.t_idx({M}, bins, -1, 0); + return o.finish("vq_euclidean", operand, out); +} + int ref_fourier_embed_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 || (n & 1)) return RAD_E_UNSUPPORTED; diff --git a/tests/CMakeLists.txt b/tests/CMakeLists.txt index 1b687f28..797187d9 100644 --- a/tests/CMakeLists.txt +++ b/tests/CMakeLists.txt @@ -10,12 +10,12 @@ # fast every test with none of slow, gpu, oot and perf, set at the end of this file: the # inner loop (`ctest --preset fast`, or `ctest -L fast`) # -# arch_test, glm5next_test, nemotron35_test, spark25_arch_test and nemotronh_test do not link rad_core: they supply +# arch_test, bailing_hybrid_arch_test, flint_arch_test, glm5next_test, museglimmer_test, nemotron35_test, spark25_arch_test and nemotronh_test do not link rad_core: they supply # their own recording fake of the declare-phase C ABI (arch_fakes.h), so plugins are tested without # depending on core/build/'s builder. With the archive linked, a new ABI call missing from the fake # would pull in rad_builder.cpp.o and collide on every rad_decl_* symbol; without it the error is a # single undefined reference. -set(RAD_TESTS_NO_CORE arch_test glm5next_test nemotron35_test spark25_arch_test nemotronh_test) +set(RAD_TESTS_NO_CORE arch_test bailing_hybrid_arch_test breeze_arch_test flint_arch_test glm5next_test museglimmer_test nemotron35_test spark25_arch_test nemotronh_test) # fixture_test tests tools/kfixture.cpp and tools/opshapes.cpp (the seeded draw, the reduction and # the on-disk recording) directly, kbench_test tools/kbench_core.cpp (rad-kbench's rules), and @@ -137,6 +137,7 @@ set(RAD_TEST_CPU_BUDGET_tokenizer_test 20) # the reference encoder over every c set(RAD_TEST_CPU_BUDGET_arch_test 15) # every plugin's graph declared; ~10.8 s with the batched-tower case set(RAD_TEST_CPU_BUDGET_device_test 30) # on a card, the paging and remap cases spin in stream waits: ~10 s; with no card (the image's test stage) they copy, write and compare on the host: 17-19 s set(RAD_TEST_CPU_BUDGET_glm5next_test 20) # GLM-5.3-Flash's graphs and op schemas: ~4.8 s built by GCC 16, ~10.1 s by GCC 14 (the image's Ubuntu) +set(RAD_TEST_CPU_BUDGET_museglimmer_test 10) # Muse Glimmer's trunk and tower graphs and steps: ~2 s built by GCC 14 # Binaries whose OpenMP team is busy for most of their run, so a parallel ctest counts them as a # team's worth of slots rather than one. @@ -415,7 +416,7 @@ endif() # arch_test and nemotronh_test read libref's vocabulary from $RADIANCE_HOME/kernels to check that # each architecture declares on it, and glm5next_test the loaded libraries' op schemas, so libref is # built before them. -foreach(t arch_test glm5next_test nemotronh_test) +foreach(t arch_test breeze_arch_test glm5next_test nemotronh_test) if(TARGET libref AND TARGET ${t}) add_dependencies(${t} libref) endif() @@ -565,9 +566,10 @@ set(R4D_EMU_HIP ${R4D_DIR}/r4d_attn_paged_window.hip ${R4D_DIR}/r4d_pair_argmax_ ${R4D_DIR}/r4d_mhc.hip ${R4D_DIR}/r4d_kda.hip ${R4D_DIR}/r4d_mla.hip ${R4D_DIR}/r4d_quant_act_fp8.hip ${R4D_DIR}/r4d_kv_resolve.hip ${R4D_DIR}/r4d_dsa.hip - ${R4D_DIR}/r4d_keyed.hip ${R4D_DIR}/r4d_lili.hip) + ${R4D_DIR}/r4d_keyed.hip ${R4D_DIR}/r4d_lili.hip + ${R4D_DIR}/r4d_vit_muse.hip) set(R4D_EMU_TESTS attn pick norm escale qsa lora f32 mhc kda mla moefuse kvres - dsa lili) + dsa lili vit) set(R4D_EMU_BUILT OFF) if(NOT CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64)$") # No fiber switch for this ISA. @@ -608,7 +610,8 @@ else() ${R4D_EMU}/test_f32.cpp ${R4D_EMU}/test_mhc.cpp ${R4D_EMU}/test_kda.cpp ${R4D_EMU}/test_mla.cpp ${R4D_EMU}/test_moefuse.cpp ${R4D_EMU}/test_kvres.cpp - ${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_lili.cpp) + ${R4D_EMU}/test_dsa.cpp ${R4D_EMU}/test_lili.cpp + ${R4D_EMU}/test_vit.cpp) get_filename_component(stem ${src} NAME_WE) set(lang "") if(src MATCHES "\\.hip$") @@ -645,7 +648,7 @@ else() endif() endif() if(R4D_EMU_BUILT) - foreach(t pick norm escale qsa lora f32 mhc kda mla moefuse kvres dsa lili) + foreach(t pick norm escale qsa lora f32 mhc kda mla moefuse kvres dsa lili vit) add_test(NAME r4d_emu_${t} COMMAND ${CMAKE_BINARY_DIR}/tests/r4d_emu_${t}) endforeach() # The attention cases take about 11 s, 7 of them in the two long prefills on the WMMA kernel, @@ -865,9 +868,23 @@ endif() # standalone against it with find_package(radiance). The result must match the tree's plugins, # vocabulary and registration, and serve rad-kbench's fixture through the installed tools # (tests/oot_plugins.sh). libr4d is included when the tree built it, with the same HIP compiler, -# targets and RAD_HIP_VOPD_REPEATABLE. Labelled `oot`: it rebuilds every plugin and takes minutes. +# targets, build type and RAD_HIP_VOPD_REPEATABLE. Labelled `oot`: it rebuilds every plugin and +# takes minutes. +# +# An installed radiance finds ROCm through ROCM_PATH and HIP_PATH (radiance-config.cmake), so the +# test gets the root of the HIP runtime this tree links, and that root's tools first on PATH: the +# out-of-tree build then uses the tree's ROCm whatever the shell that runs ctest exports. Left to +# the caller's environment, a shell without them failed to find hip_runtime.h, and one naming +# another ROCm build linked the out-of-tree libr4d against that one's runtime. set(RAD_OOT_COMPILER "") set(RAD_OOT_TARGETS "") +set(RAD_OOT_ENV "") +if(RAD_HIP_FOUND AND RAD_HIP_RUNTIME) + get_filename_component(RAD_OOT_ROCM "${RAD_HIP_RUNTIME}" DIRECTORY) + get_filename_component(RAD_OOT_ROCM "${RAD_OOT_ROCM}" DIRECTORY) + set(RAD_OOT_ENV "ROCM_PATH=${RAD_OOT_ROCM}" "HIP_PATH=${RAD_OOT_ROCM}" + "PATH=${RAD_OOT_ROCM}/bin:${RAD_OOT_ROCM}/lib/llvm/bin:$ENV{PATH}") +endif() if(RAD_HIP_FOUND AND TARGET libr4d) get_target_property(RAD_OOT_R4D_ARCH libr4d HIP_ARCHITECTURES) string(REPLACE ";" "\\;" RAD_OOT_R4D_ARCH "${RAD_OOT_R4D_ARCH}") @@ -877,13 +894,13 @@ endif() add_test(NAME oot_plugins COMMAND sh ${CMAKE_CURRENT_SOURCE_DIR}/oot_plugins.sh ${CMAKE_BINARY_DIR} ${CMAKE_SOURCE_DIR} ${CMAKE_BINARY_DIR}/oot "${RAD_OOT_COMPILER}" "${RAD_OOT_TARGETS}" - "${RAD_HIP_VOPD_REPEATABLE}" "${CMAKE_CXX_COMPILER}") + "${RAD_HIP_VOPD_REPEATABLE}" "${CMAKE_CXX_COMPILER}" "${CMAKE_BUILD_TYPE}") # RESOURCE_LOCK kbench_memory: its replay holds operands in host memory as the kbench entries do. set_tests_properties(oot_plugins PROPERTIES LABELS "oot" TIMEOUT 3600 RESOURCE_LOCK kbench_memory - ENVIRONMENT "CMAKE_GENERATOR=${CMAKE_GENERATOR};${RAD_TEST_OMP_ENV}") + ENVIRONMENT "CMAKE_GENERATOR=${CMAKE_GENERATOR};${RAD_TEST_OMP_ENV};${RAD_OOT_ENV}") # ================================================================== the kernel library, as a test # diff --git a/tests/abi_layout_table.h b/tests/abi_layout_table.h index bbc27e3a..f2a363a0 100644 --- a/tests/abi_layout_table.h +++ b/tests/abi_layout_table.h @@ -1,4 +1,4 @@ -/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 39 and +/* abi_layout_table.h -- every abi/ struct's size and field offsets at RAD_ABI_VERSION 40 and * RAD_FORMAT_VER 2, as { type, field, offset, size } rows ("" is the struct itself). A snapshot * of the headers on x86-64 Linux, which abi_layout_test.cpp holds the layout to; regenerate it * from the test's printout only together with a version bump. */ @@ -142,7 +142,7 @@ { "RadBuildCtx", "gen_max_refs", 184, 8 }, { "RadBuildCtx", "expert_file_tier", 192, 4 }, { "RadBuildCtx", "slot_base", 196, 4 }, -{ "RadAudioGenBatch", "", 0, 344 }, +{ "RadAudioGenBatch", "", 0, 352 }, { "RadAudioGenBatch", "n_lane", 0, 8 }, { "RadAudioGenBatch", "lane", 8, 8 }, { "RadAudioGenBatch", "lane_h", 16, 8 }, @@ -188,7 +188,8 @@ { "RadAudioGenBatch", "ref_cu_h", 320, 8 }, { "RadAudioGenBatch", "ref_frame", 328, 8 }, { "RadAudioGenBatch", "ref_frame_h", 336, 8 }, -{ "RadAudioGenDecl", "", 0, 280 }, +{ "RadAudioGenBatch", "prompt_cu_h", 344, 8 }, +{ "RadAudioGenDecl", "", 0, 296 }, { "RadAudioGenDecl", "name", 0, 8 }, { "RadAudioGenDecl", "tmpl", 8, 8 }, { "RadAudioGenDecl", "neg_token", 16, 4 }, @@ -228,6 +229,8 @@ { "RadAudioGenDecl", "ref_hop", 256, 8 }, { "RadAudioGenDecl", "ref_max_samples", 264, 8 }, { "RadAudioGenDecl", "ref_max", 272, 4 }, +{ "RadAudioGenDecl", "tmpl_ref_instruct", 280, 8 }, +{ "RadAudioGenDecl", "neg_tmpl_ref", 288, 8 }, { "RadControlVector", "", 0, 32 }, { "RadControlVector", "dir", 0, 8 }, { "RadControlVector", "scales", 8, 8 }, @@ -243,7 +246,7 @@ { "RadAudioFormat", "language_lead", 48, 8 }, { "RadAudioFormat", "languages", 56, 8 }, { "RadAudioFormat", "n_languages", 64, 4 }, -{ "RadChatFormat", "", 0, 208 }, +{ "RadChatFormat", "", 0, 216 }, { "RadChatFormat", "struct_size", 0, 4 }, { "RadChatFormat", "name", 8, 8 }, { "RadChatFormat", "reasoning_open", 16, 8 }, @@ -274,6 +277,7 @@ { "RadChatFormat", "object_bare_keys", 192, 4 }, { "RadChatFormat", "reasoning_anywhere", 196, 4 }, { "RadChatFormat", "arg_json_value_prefix", 200, 8 }, +{ "RadChatFormat", "content_open", 208, 8 }, { "RadConstraint", "", 0, 32 }, { "RadConstraint", "key", 0, 8 }, { "RadConstraint", "op", 8, 4 }, diff --git a/tests/abi_layout_test.cpp b/tests/abi_layout_test.cpp index 14ce95f0..bbbd3de5 100644 --- a/tests/abi_layout_test.cpp +++ b/tests/abi_layout_test.cpp @@ -58,8 +58,8 @@ std::vector cpp_rows() { }; } -/* The layout at RAD_ABI_VERSION 39 / RAD_FORMAT_VER 2 (see the file header). */ -constexpr uint32_t kTableAbi = 39, kTableFormat = 2; +/* The layout at RAD_ABI_VERSION 40 / RAD_FORMAT_VER 2 (see the file header). */ +constexpr uint32_t kTableAbi = 40, kTableFormat = 2; const AbiRow kTable[] = { #include "abi_layout_table.h" }; diff --git a/tests/advance_test.cpp b/tests/advance_test.cpp index 24361d06..5de42626 100644 --- a/tests/advance_test.cpp +++ b/tests/advance_test.cpp @@ -301,6 +301,58 @@ TEST(the_cards_tree_acceptance_is_accept_tree_and_the_end_of_generation_cut) { CHECK(cut_cases > 100); } +/* ================================================================== ADV_COMPACT */ + +/* An accepted path's rows move to their committed positions whole, in every layer and head, and + * nothing else in the cache changes: at 512 bytes a row (bf16 and fp8 at head_dim 256 and 128) + * and at 516 and 260 (the int8 cache's K, V and two f16 scales, which is never whole 16-byte + * chunks). Run as the host backend does (one caller, every chunk) and as the kernel's 64 threads + * split a row; the path crosses a block boundary. A row that sampled nothing keeps its cache. */ +TEST(a_trees_accepted_rows_move_whole_at_every_row_size) { + for (int row_bytes : { 512, 516, 260, 1028 }) { + for (int cstep : { 1, 64 }) { + Slab s(ADV_ACCEPT); + const int layers = 2, heads = 3, bs = 16, blocks = Slab::kPitch; + const int64_t stride = (int64_t)blocks * heads * bs * row_bytes + 64; + std::vector cache((size_t)(layers * stride / 4)); + uint32_t rng = 0xc0a9ac7u + (uint32_t)row_bytes; + for (uint32_t& v : cache) v = lcg(rng); + std::vector want = cache; + + s.row(0, true, 0, 8, 0, /*card=*/3, 0, /*rout=*/0, 7); + s.row(1, true, 8, 8, 0, /*card=*/5, 8, /*rout=*/-1, 7); + const int32_t path[3] = { 2, 5, 7 }, base = 28; + for (int card : { 3, 5 }) { + StepSlot& S = s.st[card]; + S.acc = 3; S.npath = 3; S.head = base + 3; + std::memcpy(S.path, path, sizeof path); + } + s.a.n_pool = 1; + s.a.pool[0] = { reinterpret_cast(cache.data()), stride, layers, heads, + row_bytes, 0 }; + + auto at = [&](std::vector& c, int l, int h, int pos) { + return reinterpret_cast(c.data()) + l * stride + + (((int64_t)(pos / bs) * heads + h) * bs + pos % bs) * row_bytes; + }; + for (int l = 0; l < layers; ++l) + for (int h = 0; h < heads; ++h) + for (int t = 0; t < 3; ++t) + std::memcpy(at(want, l, h, base + t + 1), at(want, l, h, base + path[t]), + (size_t)row_bytes); + + CHECK_EQ(adv_compact_items(s.a), layers * heads); + for (int i = 0; i < s.a.n_seq; ++i) + for (int w = 0; w < adv_compact_items(s.a); ++w) { + int p = 0, l = 0, h = 0; + CHECK(adv_compact_item(s.a, w, &p, &l, &h)); + for (int c0 = 0; c0 < cstep; ++c0) adv_compact(s.a, i, p, l, h, c0, cstep); + } + CHECK(cache == want); + } + } +} + /* ================================================================== ADV_TRUNK */ /* A verify step issued ahead takes its rows from the StepSlots: the bonus token and the head's diff --git a/tests/audio_gen_test.cpp b/tests/audio_gen_test.cpp index 7a4a86ef..81b4ff34 100644 --- a/tests/audio_gen_test.cpp +++ b/tests/audio_gen_test.cpp @@ -209,6 +209,66 @@ TEST(the_unconditional_branch_is_the_conditional_prompt_at_guidance_one) { } } +TEST(breeze_reference_rows_are_repeated_with_the_guidance_one_prompt) { + for (float cfg : {1.0f, 2.0f}) { + AudioFixture f; + f.build(); + f.prog.audio_gen.ref_max = 1; + f.prog.audio_gen.ref_rate = 50; + f.prog.audio_gen.ref_hop = 4; + f.prog.audio_gen.ref_max_samples = 8; + CHECK_OK(f.start()); + auto r = f.req(cfg); + r->ref_audio.assign(4, 0.25f); + r->ref_cu = {0, 4}; + r->ref_frame = {-1, 0, -1, -1}; + std::string why; + if (cfg != 1.0f) { + CHECK_EQ(f.drv.submit(std::move(r), &why), RAD_E_INVAL); + CHECK(has(why, "guidance_scale 1")); + continue; + } + CHECK_OK(f.drv.submit(std::move(r), &why)); + const RadBatch* b = f.drv.next(0); + REQUIRE(b != nullptr && b->gen == RAD_GEN_PASS_PROMPT); + const auto* A = b->agen_b; + REQUIRE(A->ref_frame_h != nullptr && A->ref_frame != nullptr); + CHECK_EQ(A->ref_frame_h[1], 0); + CHECK_EQ(A->ref_frame_h[4], -1); + CHECK_EQ(A->ref_frame_h[5], cfg == 1.0f ? 0 : -1); + for (int64_t i = 0; i < b->n_tok; ++i) CHECK_EQ(A->ref_frame[i], A->ref_frame_h[i]); + CHECK_EQ(A->ref_samples, (int64_t)4); + f.answer(b, 0, 0); + CHECK_OK(f.drv.done()); + } +} + +TEST(reference_direction_keeps_each_guidance_branchs_reference_map) { + for (float cfg : {1.0f, 4.0f}) { + AudioFixture f; + f.build(); + f.prog.audio_gen.ref_max = 1; + f.prog.audio_gen.ref_rate = 50; + f.prog.audio_gen.ref_hop = 4; + f.prog.audio_gen.ref_max_samples = 8; + CHECK_OK(f.start()); + auto r = f.req(cfg); + r->ref_audio.assign(4, 0.25f); r->ref_cu = {0, 4}; + r->ref_frame = {-1, 0, -1, -1}; r->neg_ref_frame = {-1, 0}; + std::string why; + CHECK_OK(f.drv.submit(std::move(r), &why)); + const RadBatch* b = f.drv.next(0); + REQUIRE(b && b->agen_b && b->agen_b->prompt_cu_h); + CHECK_EQ(b->n_tok, (int64_t)(cfg == 1.0f ? 8 : 6)); + CHECK_EQ(b->agen_b->prompt_cu_h[1], 4); + CHECK_EQ(b->agen_b->prompt_cu_h[2], b->n_tok); + CHECK_EQ(b->agen_b->ref_frame_h[5], 0); + for (int64_t i = 0; i < b->n_tok; ++i) + CHECK_EQ(b->agen_b->ref_frame[i], b->agen_b->ref_frame_h[i]); + f.answer(b, 0, 0); CHECK_OK(f.drv.done()); + } +} + /* A hybrid language model (paged attention beside a linear-attention state and a convolution * group, as Qwen3.5's delta-net layers keep) of one branch: every pass stages one sequence a * request, the state groups' rows are the sequence's slots, and each entry carries its context diff --git a/tests/bailing_hybrid_arch_test.cpp b/tests/bailing_hybrid_arch_test.cpp new file mode 100644 index 00000000..4d43945a --- /dev/null +++ b/tests/bailing_hybrid_arch_test.cpp @@ -0,0 +1,529 @@ +/* Ling-3.0's declaration and step (arch/bailing_hybrid), without a GPU or checkpoint: the IQ8R + * container data/recipes/ling-3.0-tiny-iq8r.recipe makes, at one and two ranks, and the bf16 and + * four-bit containers, tiny and flash (with its MTP layer). */ +#define RAD_ARCH_NO_EXPORTS 1 +#include "arch_fakes.h" +#include "rad_plugin.h" +#include "../arch/bailing_hybrid/bailing_hybrid.cpp" + +using namespace rad_fake; + +namespace { + +/* Ling-3.0-tiny's configuration as rad-convert records it. */ +MetaKV tiny_meta() { + RadModelMeta m{}; + m.arch_id = "bailinghybrid"; + m.name = "test-ling-tiny"; + m.quant = ""; + m.n_layers = 24; + m.n_embd = 1536; + m.n_head = 16; + m.n_head_kv = 16; + m.head_dim = 128; + m.n_ff = 4608; + m.n_vocab = 157184; + m.n_ctx_train = 131072; + m.rms_eps = 1e-6f; + m.rope_theta = 6e6f; + m.n_expert = 128; + m.n_expert_used = 8; + MetaKV k(m); + k.set("num_attention_heads", "16").set("head_dim", "128").set("qk_nope_head_dim", "128") + .set("qk_rope_head_dim", "64").set("v_head_dim", "128").set("kv_lora_rank", "512") + .set("num_experts", "128").set("num_experts_per_tok", "8").set("n_group", "8") + .set("topk_group", "4").set("moe_intermediate_size", "512") + .set("moe_shared_expert_intermediate_size", "512").set("num_shared_experts", "1") + .set("intermediate_size", "4608").set("first_k_dense_replace", "1") + .set("layer_group_size", "4").set("short_conv_kernel_size", "4").set("q_lora_rank", "256") + .set("kda_lower_bound", "-5").set("routed_scaling_factor", "2.5").set("no_kda_lora", "1") + .set("kda_safe_gate", "1").set("rope_interleave", "1") + .set("gated_attention_proj_granularity_type", "head_wise").set("score_function", "sigmoid") + .set("num_nextn_predict_layers", "0").set("norm_topk_prob", "1"); + return k; +} + +/* Ling-3.0-flash's: 42 layers of 2560, MLA every sixth with no query LoRA, two dense layers, 512 + * experts of 768, the SwiGLU clamped in the last layers, one MTP layer. */ +MetaKV flash_meta() { + MetaKV k = tiny_meta(); + k.m.name = "test-ling-flash"; + k.m.n_layers = 42; + k.m.n_embd = 2560; + k.m.n_head = 32; + k.m.n_head_kv = 32; + k.m.n_ff = 6144; + k.m.n_expert = 512; + std::string routed, shared; + for (int l = 0; l < 42; ++l) { + routed += std::string(l ? "," : "") + (l >= 35 ? "4" : "0"); + shared += std::string(l ? "," : "") + (l >= 40 ? "7" : l >= 34 ? "5" : "0"); + } + k.set("num_attention_heads", "32").set("num_experts", "512") + .set("moe_intermediate_size", "768").set("moe_shared_expert_intermediate_size", "768") + .set("intermediate_size", "6144").set("first_k_dense_replace", "2") + .set("layer_group_size", "6").set("q_lora_rank", "0").set("num_nextn_predict_layers", "1") + .set("expert_swiglu_limit_list", routed.c_str()) + .set("share_expert_swiglu_limit_list", shared.c_str()); + return k; +} + +/* IQ8R as libquant states it: int8 codes rotated by fwht128, a u8 scale per [1 x 256] of K under + * a bf16 scale a row. */ +RadEncoding iq8r() { + RadEncoding e = rad_enc_affine(RAD_I8, RAD_U8, 1, 256); + rad_enc_add_plane(&e, "scale.1", RAD_BF16, 1, 0); + rad_enc_copy_str(e.transform, "fwht128"); + return e; +} + +/* Int8 rotated by fwht128 at a bf16 scale a (row, 128 of K): the experts' form. */ +RadEncoding i8h() { + RadEncoding e = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128); + rad_enc_copy_str(e.transform, "fwht128"); + return e; +} + +const RadEncoding kI4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128); + +/* data/recipes/ling-3.0-tiny-iq8r.recipe's encodings by declared name, every other weight plain + * bf16. `attn_gate.weight` is the KDA output gate; the MLA's head gate is `attn_head_gate`. */ +void iq8r_encs(RadBuilder* b) { + b->encs.clear(); + for (const char* t : { "ffn_gate_up_exps", "ffn_down_exps", "ffn_down_shexp" }) + b->encs.push_back({ t, i8h() }); + for (const char* t : { "attn_qkv.weight", "attn_forget.weight", "attn_gate.weight", + "attn_output.weight", "ffn_gate_up.weight", "ffn_down.weight", + "ffn_gate_up_shexp" }) + b->encs.push_back({ t, iq8r() }); + b->encs.push_back({ "", rad_enc_plain(RAD_BF16) }); +} + +/* data/recipes/ling3-w4a8-rtn.recipe's: four-bit routed experts, everything else bf16. */ +void w4_encs(RadBuilder* b) { + b->encs.clear(); + b->encs.push_back({ "ffn_gate_up_exps", kI4 }); + b->encs.push_back({ "ffn_down_exps", kI4 }); + b->encs.push_back({ "", rad_enc_plain(RAD_BF16) }); +} + +/* The bf16 checkpoint. */ +void bf16_encs(RadBuilder* b) { + b->encs.clear(); + b->encs.push_back({ "", rad_enc_plain(RAD_BF16) }); +} + +bool is_mla(int l) { return (l + 1) % 4 == 0; } + +const std::string& wname(const RadBuilder& b, rad_weight w) { return b.weights[w - 1].name; } + +/* The buffer a name declared, 0 if none. */ +rad_buf buf(const RadBuilder& b, const char* n) { + for (size_t i = 0; i < b.bufs.size(); ++i) + if (b.bufs[i].name == n) return (rad_buf)(i + 1); + return 0; +} + +/* graph_hash with the name maps in declared-name order (stable, so maps that extend one name keep + * theirs): where among the other declarations a map is made (the trunk probe maps layer 0's + * q|k|v ahead of the buffers) is not part of what the core builds from it. */ +uint64_t graph_hash_maps_by_name(const RadBuilder& b0) { + RadBuilder b = b0; + std::stable_sort(b.maps.begin(), b.maps.end(), + [](const RecMap& x, const RecMap& y) { return x.declared < y.declared; }); + return graph_hash(b); +} + +/* A decode step, a prefill of two prompts and a mixed step, each pass clean. */ +void steps_lint_clean(RadBuilder& b, int rank, int world) { + const auto dc = kit(b, { 1, 1, 1 }, {}); + const auto pf = kit(b, {}, { 64, 100 }, 0); + const auto mx = kit(b, { 1, 1 }, { 120 }, 300); + for (const Kit* k : { dc.get(), pf.get(), mx.get() }) { + auto v = run_passes(b, bailing_hybrid::step, { k }, rank, world); + CHECK_PASSES(b, v); + } +} + +} /* namespace */ + +/* The IQ8R container at one rank and both ranks of two: every trunk linear the recipe quantises is + * one gemm_nt_q at i8a8h, its N and K this rank's, reading the codes of the producer that feeds it + * at that producer's group; the linears the recipe keeps bf16 are gemm_nt over the norm's bf16 + * output; the grouped GEMMs are the int8 rows. No E4M3 code and no unrotated int8 quantiser + * exist, and no linear quantises its own input. */ +TEST(iq8r_container_declares_the_rotated_int8_trunk) { + for (int world : { 1, 2 }) + for (int rank = 0; rank < world; ++rank) { + MetaKV mk = tiny_meta(); + RadBuilder b; + iq8r_encs(&b); + RadBuildCtx ctx = build_ctx(rank, world); + REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK); + const bailing_hybrid::Model& m = bailing_hybrid::g_model[rank]; + CHECK(m.trunk_rot); + CHECK(m.norm_fed); + CHECK_EQ(m.trunk_g8, 256); + const int64_t H = 16 / world, W = 128 * H, FF = 4608 / world, SH = 512 / world, + EX = 512 / world; + const rad_buf normed = buf(b, "normed"), nq = buf(b, "normed.q8"), + ns = buf(b, "normed.s8"), kq = buf(b, "kda_out.q8"), + vq = buf(b, "mla_value.q8"), dq = buf(b, "dense_ff.q8"), + sq = buf(b, "shared_ff.q8"), eq = buf(b, "expert_ff.q8"), + qa = buf(b, "mla_q_a"); + REQUIRE(normed && nq && ns && kq && vq && dq && sq && eq && qa); + CHECK_EQ(m.act.q8, (uint32_t)nq); + + /* ---- each quantised linear: N, K, group, the codes it reads. */ + struct Want { int64_t N, K, group; rad_buf in; int n; }; + std::map want; + for (int l = 0; l < 24; ++l) { + char n[96]; + if (is_mla(l)) { + std::snprintf(n, sizeof n, "blk.%d.attn_output.weight", l); + want[n] = { 1536, H * 128, 256, vq, 0 }; + } else { + std::snprintf(n, sizeof n, "blk.%d.attn_qkv.weight", l); + want[n] = { 3 * W, 1536, 256, nq, 0 }; + std::snprintf(n, sizeof n, "blk.%d.attn_forget.weight", l); + want[n] = { W, 1536, 256, nq, 0 }; + std::snprintf(n, sizeof n, "blk.%d.attn_gate.weight", l); + want[n] = { W, 1536, 256, nq, 0 }; + std::snprintf(n, sizeof n, "blk.%d.attn_output.weight", l); + want[n] = { 1536, W, 256, kq, 0 }; + } + if (l == 0) { + want["blk.0.ffn_gate_up.weight"] = { 2 * FF, 1536, 256, nq, 0 }; + want["blk.0.ffn_down.weight"] = { 1536, FF, 256, dq, 0 }; + } else { + std::snprintf(n, sizeof n, "blk.%d.ffn_gate_up_shexp.weight", l); + want[n] = { 2 * SH, 1536, 256, nq, 0 }; + std::snprintf(n, sizeof n, "blk.%d.ffn_down_shexp.weight", l); + want[n] = { 1536, SH, 128, sq, 0 }; + } + } + int q = 0; + for (const auto& o : b.ops) { + if (o.op != "gemm_nt_q") continue; + ++q; + CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h")); + REQUIRE(!o.w.empty()); + auto it = want.find(wname(b, o.w[0])); + REQUIRE(it != want.end()); + Want& x = it->second; + ++x.n; + CHECK_EQ(pint(&o, "N"), x.N); + CHECK_EQ(pint(&o, "K"), x.K); + CHECK_EQ(pint(&o, "group"), x.group); + CHECK(in(o.reads, x.in)); + } + CHECK_EQ(q, 18 * 4 + 6 + 2 + 23 * 2); + for (const auto& [name, x] : want) CHECK_EQ(x.n, 1); + + /* ---- the linears the recipe keeps bf16, over the norm's bf16 output (the query parts + * over the LoRA's normed latent). */ + int keep = 0; + for (const auto& o : b.ops) { + if (o.op != "gemm_nt" || o.w.empty()) continue; + const std::string& n = wname(b, o.w[0]); + const bool lora = n.find("attn_q_rope") != std::string::npos || + n.find("attn_q_nope") != std::string::npos; + if (n.find("attn_beta") == std::string::npos && + n.find("attn_q_a.") == std::string::npos && + n.find("attn_kv_a.") == std::string::npos && + n.find("attn_head_gate") == std::string::npos && !lora) + continue; + ++keep; + CHECK_EQ(pstr(&o, "dtype"), std::string("bf16")); + CHECK(in(o.reads, lora ? qa : normed)); + CHECK(!in(o.reads, nq)); + } + CHECK_EQ(keep, 18 + 6 * 5); + + /* ---- the producers and their groups. */ + int norms = 0, outq = 0, dense = 0, shared = 0, routed = 0; + for (const auto& o : b.ops) { + if (o.op == "rmsnorm_had_quant_i8g") { + ++norms; + CHECK_EQ(pint(&o, "group"), 256); + CHECK_EQ(pint(&o, "n"), 1536); + CHECK(in(o.writes, nq) && in(o.writes, ns) && in(o.writes, normed)); + } else if (o.op == "had_quant_act_i8g") { + ++outq; + CHECK_EQ(pint(&o, "group"), 256); + const bool kda = in(o.writes, kq); + CHECK(kda || in(o.writes, vq)); + CHECK_EQ(pint(&o, "n"), kda ? W : H * 128); + } else if (o.op == "gated_had_quant_i8g") { + if (in(o.writes, dq)) { + ++dense; + CHECK_EQ(pint(&o, "group"), 256); + CHECK_EQ(pint(&o, "n"), FF); + } else if (in(o.writes, sq)) { + ++shared; + CHECK_EQ(pint(&o, "group"), 128); + CHECK_EQ(pint(&o, "n"), SH); + } else { + CHECK(in(o.writes, eq)); + ++routed; + CHECK_EQ(pint(&o, "group"), 128); + CHECK_EQ(pint(&o, "n"), EX); + } + } + } + CHECK_EQ(norms, 48); + CHECK_EQ(outq, 18 + 6); + CHECK_EQ(dense, 1); + CHECK_EQ(shared, 23); + CHECK_EQ(routed, 23); + for (const char* op : { "rmsnorm_quant_fp8", "ar_rmsnorm_quant_fp8", + "ar_rmsnorm_had_quant_i8g", "quant_act_fp8", "quant_act_i8g", + "gated_quant_fp8", "had_quant_act_fp8", "gated_had_quant_fp8", + "swiglu_step", "silu_mul" }) + CHECK_EQ(count_op(b, op), 0); + for (const char* n : { "normed.q", "kda_out.q", "mla_value.q", "mla_q_a.q", + "dense_ff.q", "shared_ff.q", "expert_ff.q", "normed_rot.q", + "normed_rot.q8" }) + CHECK(find_b(b, n) == nullptr); + + /* ---- the routed experts: rotated int8 rows, gate_up over the norm's codes at 256, + * down over the gated product's at 128, each rank a slice of every expert. */ + int gu = 0, dn = 0; + for (const auto& o : b.ops) { + if (o.op != "moe_gemm_q") continue; + CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h")); + const bool token = pstr(&o, "a_order") == "token"; + CHECK_EQ(pint(&o, "a_group"), token ? 256 : 128); + CHECK(in(o.reads, token ? nq : eq)); + CHECK_EQ(pint(&o, "N"), token ? 2 * EX : 1536); + CHECK_EQ(pint(&o, "K"), token ? 1536 : EX); + CHECK_EQ(pint(&o, "n_expert"), 128); + (token ? gu : dn) += 1; + } + CHECK_EQ(gu, 23); + CHECK_EQ(dn, 23); + const RecWeight* e0 = find_w(b, "blk.1.ffn_gate_up_exps.127.weight"); + REQUIRE(e0 != nullptr); + CHECK_EQ(e0->d.dtype, (uint32_t)RAD_I8); + CHECK_EQ((int)e0->d.shard, (int)RAD_SHARD_ROW); + steps_lint_clean(b, rank, world); + } +} + +/* The IQ8R container shards as the bf16 one does: every weight both declare outside the routed + * experts is split the same way, and the collectives are the same standalone all-reduces (the plugin's norms take no + * collective, so no `ar_` norm is declared at two ranks). */ +TEST(iq8r_container_follows_the_plugins_sharding) { + for (int world : { 1, 2 }) { + MetaKV mk = tiny_meta(); + RadBuilder q, f; + iq8r_encs(&q); + bf16_encs(&f); + RadBuildCtx cq = build_ctx(0, world), cf = build_ctx(0, world); + cf.slot_base = 4; + REQUIRE_EQ(bailing_hybrid::declare(&q, mk.meta(), &cq), RAD_OK); + REQUIRE_EQ(bailing_hybrid::declare(&f, mk.meta(), &cf), RAD_OK); + int same = 0; + for (const RecWeight& w : q.weights) { + const RecWeight* o = find_w(f, w.name); + if (!o || w.name.find("_exps.") != std::string::npos) continue; + ++same; + CHECK_EQ(w.d.shard, o->d.shard); + CHECK_EQ(w.d.n_row_parts, o->d.n_row_parts); + } + CHECK(same > 300); + CHECK_EQ(count_op(q, "all_reduce"), count_op(f, "all_reduce")); + CHECK_EQ(count_op(q, "all_reduce"), world == 2 ? 1 + 24 + 24 : 0); + /* Rotated int8 experts are a slice of every expert on each rank, where bf16 ones are + * whole on one. */ + CHECK(find_w(q, "blk.1.ffn_gate_up_exps.0.weight") != nullptr); + CHECK(find_w(q, "blk.1.ffn_gate_up_exps.127.weight") != nullptr); + } +} + +/* Where no loaded library serves the rotating norm (a CPU-only engine), the norms write E4M3 + * codes no linear reads, every int8 trunk linear quantises the norm's bf16 output itself at the + * trunk's group, and the routed gate_up reads a rotated int8 copy written once a layer at 128. */ +TEST(iq8r_container_without_the_rotating_norm_quantises_each_input) { + for (int world : { 1, 2 }) { + MetaKV mk = tiny_meta(); + RadBuilder b; + b.undeclared.insert("rmsnorm_had_quant_i8g"); + iq8r_encs(&b); + RadBuildCtx ctx = build_ctx(0, world); + REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK); + CHECK(bailing_hybrid::g_model[0].trunk_rot); + CHECK(!bailing_hybrid::g_model[0].norm_fed); + CHECK_EQ(count_op(b, "rmsnorm_quant_fp8"), 48); + const rad_buf normed = buf(b, "normed"), hr = buf(b, "normed_rot.q8"); + REQUIRE(hr != 0); + int own = 0, copy = 0; + for (const auto& o : b.ops) { + if (o.op == "had_quant_act_i8g" && in(o.reads, normed)) { + const bool c = in(o.writes, hr); + (c ? copy : own) += 1; + CHECK_EQ(pint(&o, "group"), c ? 128 : 256); + } + if (o.op == "moe_gemm_q" && pstr(&o, "a_order") == "token") { + CHECK_EQ(pint(&o, "a_group"), 128); + CHECK(in(o.reads, hr)); + } + } + /* q|k|v, forget and gate on 18 layers, the dense gate_up, 23 shared gate_ups. */ + CHECK_EQ(own, 18 * 3 + 1 + 23); + CHECK_EQ(copy, 23); + steps_lint_clean(b, 0, world); + } +} + +/* A shared expert whose down projection is stored IQ8R too takes its input codes at 256. */ +TEST(iq8r_shared_down_sets_its_inputs_group) { + MetaKV mk = tiny_meta(); + RadBuilder b; + iq8r_encs(&b); + b.encs.insert(b.encs.begin(), { "ffn_down_shexp", iq8r() }); + RadBuildCtx ctx = build_ctx(); + REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK); + const rad_buf sq = buf(b, "shared_ff.q8"); + int n = 0; + for (const auto& o : b.ops) + if (o.op == "gated_had_quant_i8g" && in(o.writes, sq)) { + CHECK_EQ(pint(&o, "group"), 256); + ++n; + } + CHECK_EQ(n, 23); + CHECK_EQ(find_b(b, "shared_ff.s8")->d.shape[1], 2); +} + +/* The bf16 and four-bit containers at one rank and both ranks of two, tiny and flash (with its + * MTP layer under speculation), pinned by their graphs' fingerprints: no int8 op, E4M3 codes from + * the norms, and the four-bit experts reading the norm's E4M3 pair at w4a8. */ +TEST(bf16_and_four_bit_containers_keep_their_graphs) { + struct Case { bool flash, w4; int world, rank; uint64_t hash; }; + const Case cases[] = { + { false, false, 1, 0, 0x86ab7d6c2a6c7d9aull }, + { false, false, 2, 0, 0x08a9d5eac89cbfdcull }, + { false, false, 2, 1, 0x6bbc016892e93dacull }, + { false, true, 1, 0, 0xcdcf0243f2a0c792ull }, + { false, true, 2, 0, 0xda4c82105c0feb47ull }, + { false, true, 2, 1, 0xd94daa2c5c90352bull }, + { true, false, 1, 0, 0x21f7c41f985de35eull }, + { true, false, 2, 0, 0x0420376396574defull }, + { true, false, 2, 1, 0xb7df9b2e13bc4ae6ull }, + { true, true, 1, 0, 0xf9dec754da195628ull }, + { true, true, 2, 0, 0x7da4ef872c9304e9ull }, + { true, true, 2, 1, 0xcc97ada7f98fca85ull }, + }; + for (const Case& c : cases) { + MetaKV mk = c.flash ? flash_meta() : tiny_meta(); + RadBuilder b; + if (c.w4) w4_encs(&b); else bf16_encs(&b); + RadBuildCtx ctx = build_ctx(c.rank, c.world); + if (c.flash) ctx.max_spec = 3; + REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK); + const bailing_hybrid::Model& m = bailing_hybrid::g_model[c.rank]; + CHECK(!m.trunk_rot); + CHECK_EQ(m.have_mtp, c.flash); + CHECK_EQ(graph_hash_maps_by_name(b), c.hash); + CHECK(count_op(b, "rmsnorm_quant_fp8") > 0); + for (const char* op : { "rmsnorm_had_quant_i8g", "had_quant_act_i8g", + "gated_had_quant_i8g", "gemm_nt_q" }) + CHECK_EQ(count_op(b, op), 0); + if (c.w4) { + const rad_buf nq = buf(b, "normed.q"); + int moe = 0; + for (const auto& o : b.ops) + if (o.op == "moe_gemm_q") { + CHECK_EQ(pstr(&o, "dtype"), std::string("w4a8")); + if (pstr(&o, "a_order") == "token") CHECK(in(o.reads, nq)); + ++moe; + } + CHECK_EQ(moe, 2 * (c.flash ? 41 : 23)); + } + if (!c.flash) steps_lint_clean(b, c.rank, c.world); + } +} + +/* What the plugin refuses by name: a rotated trunk over unrotated experts, rotated int8 experts + * under an unrotated trunk, an IQ8R trunk over a clamped SwiGLU (flash's last layers), and the + * tiny IQ8R trunk at four ranks, whose 1152-column dense slice cuts a 256-column scale group. */ +TEST(refuses_mismatched_forms) { + { + MetaKV mk = tiny_meta(); + RadBuilder b; + iq8r_encs(&b); + for (auto& e : b.encs) + if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = kI4; + RadBuildCtx ctx = build_ctx(); + CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }), + RAD_E_UNSUPPORTED); + } + { + MetaKV mk = tiny_meta(); + RadBuilder b; + w4_encs(&b); + for (auto& e : b.encs) + if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = i8h(); + RadBuildCtx ctx = build_ctx(); + CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }), + RAD_E_UNSUPPORTED); + } + { + MetaKV mk = flash_meta(); + RadBuilder b; + iq8r_encs(&b); + RadBuildCtx ctx = build_ctx(); + CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }), + RAD_E_UNSUPPORTED); + } + { + MetaKV mk = tiny_meta(); + RadBuilder b; + iq8r_encs(&b); + RadBuildCtx ctx = build_ctx(0, 4); + CHECK_EQ(stderr_of_rc([&] { return bailing_hybrid::declare(&b, mk.meta(), &ctx); }), + RAD_E_UNSUPPORTED); + } +} + +/* Flash's IQ8R trunk with the clamp lists cut declares, MTP layer included: the drafter's MLA and + * routed feed-forward read the trunk's codes like any trunk layer. */ +TEST(flash_iq8r_without_clamps_declares_its_drafter_on_the_int8_trunk) { + for (int world : { 1, 2 }) { + MetaKV mk = flash_meta(); + mk.drop("expert_swiglu_limit_list").drop("share_expert_swiglu_limit_list"); + RadBuilder b; + iq8r_encs(&b); + RadBuildCtx ctx = build_ctx(0, world); + ctx.max_spec = 3; + REQUIRE_EQ(bailing_hybrid::declare(&b, mk.meta(), &ctx), RAD_OK); + const bailing_hybrid::Model& m = bailing_hybrid::g_model[0]; + CHECK(m.trunk_rot); + CHECK(m.have_mtp); + const RecWeight* d = find_w(b, "blk.42.attn_output.weight"); + REQUIRE(d != nullptr); + CHECK_EQ(d->d.dtype, (uint32_t)RAD_I8); + /* 40 routed layers and the drafter's; two norms a layer. */ + CHECK_EQ(count_op(b, "moe_gemm_q"), 2 * 41); + CHECK_EQ(count_op(b, "rmsnorm_had_quant_i8g"), 2 * 43); + } +} + +/* Per-instance state lives in the declaring instance's slot, so a second engine in the process + * leaves the first one's model alone. */ +TEST(declares_into_its_own_slot) { + MetaKV mk = tiny_meta(); + RadBuilder b0, b1; + iq8r_encs(&b0); + w4_encs(&b1); + RadBuildCtx c0 = build_ctx(); + RadBuildCtx c1 = build_ctx(); + c1.slot_base = 4; + REQUIRE_EQ(bailing_hybrid::declare(&b0, mk.meta(), &c0), RAD_OK); + REQUIRE_EQ(bailing_hybrid::declare(&b1, mk.meta(), &c1), RAD_OK); + CHECK(bailing_hybrid::g_model[0].trunk_rot); + CHECK(!bailing_hybrid::g_model[4].trunk_rot); + CHECK_EQ(bailing_hybrid::g_model[4].s.n_layer, 24); +} + +RAD_TEST_MAIN() diff --git a/tests/breeze_arch_test.cpp b/tests/breeze_arch_test.cpp new file mode 100644 index 00000000..79b2fc66 --- /dev/null +++ b/tests/breeze_arch_test.cpp @@ -0,0 +1,150 @@ +/* Recording tests of Breeze's reference encoder and prompt assembly; no weights or GPU. */ +#define RAD_ARCH_NO_EXPORTS 1 +#include "arch_fakes.h" +#include +#include "../arch/breeze/breeze.cpp" + +extern "C" int rad_declare_audio_generator(RadBuilder*, const RadAudioGenDecl*) { return RAD_OK; } + +namespace { +struct Fixture { + RadBuilder b; + breeze::Model m; + Fixture() { + m.gl.max_tok = 1024; + m.gl.n_embd = 2048; + m.ge = m.gl; + m.b_x = rad::arch::decl_b(&b, "lm.x", RAD_BF16, {1024, 2048}); + m.w_cb = rad::arch::decl_w(&b, "frame.codebooks.weight", RAD_BF16, {16 * 2051, 2048}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, rad::arch::grp_layer(0)); + const char* keys[] = {"text_encoder_config.layer_types", "text_encoder_config.num_hidden_layers", + "audio_tokenizer.encoder_config.hidden_size", "audio_tokenizer.encoder_config.num_hidden_layers", + "audio_tokenizer.encoder_config.num_filters"}; + const char* vals[] = {"full_attention", "1", "512", "8", "64"}; + RadModelMeta meta{}; + meta.n_kv = 5; meta.kv_key = keys; meta.kv_val = vals; + CHECK_OK(breeze::declare_encoder(&b, &meta, m)); + CHECK_OK(breeze::declare_reference(&b, &meta, m)); + } +}; +} + +TEST(breeze_clone_encodes_text_segments_independently_and_audio_only_once) { + Fixture f; + /* Three text rows, two reference frames, one audio EOS, three new text rows, twice. */ + int32_t tokens[18]{}, positions[18]{}, cu[] = {0, 9, 18}, ref_cu[] = {0, 3840}; + int32_t map[] = {-1, -1, -1, 0, 1, -1, -1, -1, -1, + -1, -1, -1, 0, 1, -1, -1, -1, -1}; + int32_t last[] = {0}; + float audio = 0; + RadAudioGenBatch A{}; + A.n_lane = 1; A.last_h = last; A.n_ref = 1; A.ref_samples = 3840; + A.ref_cu = ref_cu; A.ref_cu_h = ref_cu; A.ref_audio = &audio; A.ref_frame_h = map; + A.prompt_cu_h = cu; + RadBatch batch{}; + batch.gen = RAD_GEN_PASS_PROMPT; batch.n_tok = 18; batch.n_seq = 2; + batch.token_ids = tokens; batch.positions = positions; batch.cu_seqlens = cu; batch.agen_b = &A; + RadCtx c; c.b = &f.b; c.batch = &batch; + breeze::step_prompt(&c, &batch, f.m); + int text_segments = 0, reference_encodes = 0, quantisers = 0, embeddings = 0; + std::vector output_offsets; + for (const auto& issue : c.issues) { + if (issue.op == f.m.op_eembed) { + ++text_segments; + CHECK_EQ(issue.n, (int64_t)3); + } + if (issue.op == f.m.enc[0].op_qknr) + CHECK_EQ(issue.opd[1].handle, f.m.ref.text_pos); + if (issue.op == f.m.op_eproj) output_offsets.push_back(issue.opd.back().offset / 2048); + if (issue.op == f.m.ref.first.op) ++reference_encodes; + if (f.b.ops[issue.op - 1].op == "vq_euclidean") { + ++quantisers; CHECK_EQ(issue.n, (int64_t)2); + } + if (issue.op == f.m.ref.embed) { + ++embeddings; + /* rvq_embed's second table starts at codebook 1, not at codebook 0. + * The same slice is required for the reference frames and their audio EOS. */ + CHECK_EQ(issue.opd[1].handle, f.m.w_cb); + CHECK_EQ(issue.opd[1].offset, (int64_t)0); + CHECK_EQ(issue.opd[2].handle, f.m.w_cb); + CHECK_EQ(issue.opd[2].offset, (int64_t)2051 * 2048); + CHECK_EQ(issue.opd[2].rows, (int64_t)15 * 2051); + } + } + CHECK_EQ(text_segments, 4); + CHECK_EQ(reference_encodes, 1); + CHECK_EQ(quantisers, 16); + CHECK_EQ(embeddings, 4); /* a clip and its EOS in each branch */ + CHECK(output_offsets == std::vector({0, 6, 9, 15})); + CHECK_LINT(f.b, &c); +} + +TEST(breeze_reference_transcripts_cannot_inject_audio_or_template_markers) { + char out[128]; + CHECK_EQ(breeze::text_prepare(RAD_TEXT_REFERENCE, "the reference words", out, sizeof(out)), 19); + for (const char* marker : {"", "", "<|AUDIO|>", "<|audio_eos|>", "", ""}) + CHECK_EQ(breeze::text_prepare(RAD_TEXT_REFERENCE, marker, out, sizeof(out)), (int64_t)RAD_E_INVAL); +} + +TEST(breeze_reference_direction_uses_actual_unequal_branch_boundaries) { + Fixture f; + int32_t tokens[22]{}, positions[22]{}, cu[] = {0, 13, 22}, ref_cu[] = {0, 3840}; + int32_t map[] = {-1, -1, -1, 0, 1, -1, -1, -1, -1, -1, -1, -1, -1, + -1, -1, -1, 0, 1, -1, -1, -1, -1}; + int32_t last[] = {0}; float audio = 0; + RadAudioGenBatch A{}; + A.n_lane = 1; A.last_h = last; A.n_ref = 1; A.ref_samples = 3840; + A.ref_cu = ref_cu; A.ref_cu_h = ref_cu; A.ref_audio = &audio; + A.ref_frame_h = map; A.prompt_cu_h = cu; + RadBatch batch{}; + batch.gen = RAD_GEN_PASS_PROMPT; batch.n_tok = 22; batch.n_seq = 2; + batch.token_ids = tokens; batch.positions = positions; batch.cu_seqlens = cu; batch.agen_b = &A; + RadCtx c; c.b = &f.b; c.batch = &batch; + breeze::step_prompt(&c, &batch, f.m); + std::vector lengths, offsets; + int encodes = 0; + for (const auto& issue : c.issues) { + if (issue.op == f.m.op_eembed) lengths.push_back(issue.n); + if (issue.op == f.m.op_eproj) offsets.push_back(issue.opd.back().offset / 2048); + if (issue.op == f.m.ref.first.op) ++encodes; + } + CHECK(lengths == std::vector({3, 7, 3, 3})); + CHECK(offsets == std::vector({0, 6, 13, 19})); + CHECK_EQ(encodes, 1); + CHECK_LINT(f.b, &c); +} + +TEST(breeze_reference_declarations_use_the_real_kernel_vocabulary) { + const char* home = std::getenv("RADIANCE_HOME"); + REQUIRE(home != nullptr); + void* lib = dlopen((std::string(home) + "/kernels/libref.so").c_str(), RTLD_NOW | RTLD_LOCAL); + REQUIRE(lib != nullptr); + auto count = (int (*)())dlsym(lib, "rad_kernel_schema_count"); + auto at = (const RadOpSchema* (*)(int))dlsym(lib, "rad_kernel_schema_at"); + REQUIRE(count && at); + std::map schemas; + for (int i = 0; i < count(); ++i) schemas[at(i)->op] = at(i); + Fixture f; + for (const auto& op : f.b.ops) { + REQUIRE(schemas.count(op.op) != 0); + const auto* s = schemas.at(op.op); + for (const auto& p : op.p) { + bool known = false; + for (int i = 0; i < s->n_params; ++i) known |= p.key == s->params[i].key; + CHECK(known); + } + for (int i = 0; i < s->n_params; ++i) { + if (!s->params[i].required) continue; + CHECK(std::any_of(op.p.begin(), op.p.end(), [&](const auto& p) { return p.key == s->params[i].key; })); + } + size_t min_w = 0, max_w = 0; + for (int i = 0; i < s->n_operands; ++i) if (s->operands[i].role == RAD_OPD_WEIGHT) { + ++max_w; if (!s->operands[i].optional) ++min_w; + } + CHECK(op.w.size() >= min_w && op.w.size() <= max_w); + for (auto w : op.w) CHECK(w != 0 && w <= f.b.weights.size()); + } + dlclose(lib); +} + +RAD_TEST_MAIN() diff --git a/tests/chat_test.cpp b/tests/chat_test.cpp index c5eeef3e..828dc180 100644 --- a/tests/chat_test.cpp +++ b/tests/chat_test.cpp @@ -367,6 +367,50 @@ TEST(replayed_tool_call_arguments_render_as_parameter_xml) { CHECK(pb.prompt.find("") != std::string::npos); } +/* A tool-call round in the current turn, as a client replays it, with the call's arguments as + * `args` (absent when null). */ +static json replayed_round(const json* args) { + json fn = {{"name", "read"}}; + if (args) fn["arguments"] = *args; + json msgs = json::array(); + msgs.push_back({{"role", "user"}, {"content", "Read /work/a.py."}}); + msgs.push_back({{"role", "assistant"}, {"content", ""}, + {"tool_calls", json::array({{{"id", "c1"}, {"type", "function"}, + {"function", fn}}})}}); + msgs.push_back({{"role", "tool"}, {"tool_call_id", "c1"}, {"content", "print(1)\n"}}); + return msgs; +} + +/* A call without arguments, replayed as "" (a stored stream) or with no `arguments`, is the + * empty object. Refusing it refused every later turn of the conversation. */ +TEST(a_replayed_call_with_empty_or_absent_arguments_is_the_empty_object) { + if (!qwen().need()) return; + const json empty = "", spaces = " \n", obj = "{}"; + ChatPrompt want; + ChatOptions opt; + CHECK_OK(qwen().t->apply(replayed_round(&obj), tools_json(), opt, &want)); + CHECK(want.prompt.find("\n") != std::string::npos); + for (const json* a : {&empty, &spaces, (const json*)nullptr}) { + ChatPrompt p; + CHECK_OK(qwen().t->apply(replayed_round(a), tools_json(), opt, &p)); + CHECK_EQ(p.prompt, want.prompt); + } +} + +/* Arguments that are not JSON are still refused, but as the request's fault and naming the call, + * not as a refusal by the template. */ +TEST(replayed_arguments_that_are_not_json_are_refused_naming_the_call) { + if (!qwen().need()) return; + const json bad = "{\"path\": \"/work/a.py\""; + ChatPrompt p; + ChatOptions opt; + opt.quiet = true; + CHECK_EQ(qwen().t->apply(replayed_round(&bad), tools_json(), opt, &p), (int)RAD_E_INVAL); + CHECK(p.error.find("messages[1].tool_calls[0].function.arguments is not JSON") != + std::string::npos); + CHECK(p.error.find("template") == std::string::npos); +} + /* ------------------------------------------------------------------ golden renders * * Every shipped template renders the requests in tests/data/chat/golden/cases.json byte for byte diff --git a/tests/chatparse_test.cpp b/tests/chatparse_test.cpp index 8cef9dc4..16eb2b59 100644 --- a/tests/chatparse_test.cpp +++ b/tests/chatparse_test.cpp @@ -32,6 +32,7 @@ #include "text/chatfmt.h" #include "text/chatparse.h" +#include "../arch/museglimmer/chat.h" #include #include "util/json.h" @@ -2668,5 +2669,129 @@ TEST(a_long_reply_holds_a_constant_number_of_bytes) { } } -RAD_TEST_MAIN() +/* ================================================================== Muse's channels + * + * The model opens its own channel after `<|start|>assistant`: ` to=self<|message|>` reasoning + * first, or ` to=user<|message|>` straight into the answer when it does not reason + * (arch/museglimmer/chat.h). The header of an answer that follows reasoning is reasoning_close's; + * the header of an answer that does not is content_open's. */ +static std::shared_ptr muse_parser(bool tools, bool extract = true) { + static const json t = agent_tools(); + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(museglimmer::muse_chat_format(), &f, &why)); + ReplyOptions ro; + ro.extract_reasoning = extract; + ro.terminators = { "<|eot|>" }; + if (tools) ro.tools = &t; + return parser_of(f, ro); +} + +/* `reply` read whole, then streamed at every cut: the answer must come out as `content`, with + * `reasoning` split off and no call. */ +static void muse_reads(const std::shared_ptr& rp, const std::string& reply, + const std::string& content, const std::string& reasoning = "") { + REQUIRE(rp); + const ReplyMessage m = reply_parse(*rp, reply); + if (m.content != content || m.reasoning != reasoning || !m.calls.empty()) + ::radtest::fail(__FILE__, __LINE__, "reply " + quote(reply) + " read as content " + + quote(m.content) + ", reasoning " + quote(m.reasoning) + ", " + + std::to_string(m.calls.size()) + " calls"); + const std::string e = stream_all(*rp, reply); + if (!e.empty()) ::radtest::fail(__FILE__, __LINE__, "reply " + quote(reply) + ": " + e); + ++::radtest::checks(); +} + +/* A reply with no reasoning opens on the user channel, and the header is not content. */ +TEST(a_muse_reply_that_opens_on_the_content_channel_drops_its_header) { + for (bool tools : { false, true }) { + const auto rp = muse_parser(tools); + muse_reads(rp, " to=user<|message|>Here are five prime numbers: 2, 3, 5, 7, 11.<|eot|>", + "Here are five prime numbers: 2, 3, 5, 7, 11."); + muse_reads(rp, "to=user<|message|>Hi", "Hi"); + muse_reads(rp, "\n to=user<|message|>\nHi there\n", "\nHi there"); + muse_reads(rp, " to=user<|message|>", ""); + /* The header's words later in the answer are the answer's. */ + muse_reads(rp, " to=user<|message|>write to=user<|message|> next", "write to=user<|message|> next"); + } + /* Reasoning kept inline (reasoning_format none): the answer's header is still dropped. */ + muse_reads(muse_parser(false, false), " to=user<|message|>Hi<|eot|>", "Hi"); +} + +/* Text that starts like the header but is not it is the reply, unchanged, and nothing of it is + * held back for good. */ +TEST(a_muse_reply_that_only_starts_like_the_content_header_is_unchanged) { + for (bool tools : { false, true }) { + const auto rp = muse_parser(tools); + for (const char* r : { "to=users are asked to wait", "to=user", "to=user<|message", "to=", + "to=user<|message|", "to=user <|message|>x", "to=use", "t", + "to=user<|messages|>x", "to=self", "to=sel", "x to=user<|message|>y", + "to=user to=user<|message|>y" }) + muse_reads(rp, r, r); + muse_reads(rp, "to=users are asked to wait<|eot|>", "to=users are asked to wait"); + muse_reads(rp, "to=user\n<|message|>x", "to=user\n<|message|>x"); + } +} + +/* Reasoning first, then the user channel: the header after the block is reasoning_close's, and + * a header-shaped string inside the answer stays. */ +TEST(a_muse_reply_that_reasons_first_reads_as_before) { + for (bool tools : { false, true }) { + const auto rp = muse_parser(tools); + muse_reads(rp, " to=self<|message|>Five primes.<|eom|><|start|>assistant to=user<|message|>2, 3, 5, 7, 11.<|eot|>", + "2, 3, 5, 7, 11.", "Five primes."); + muse_reads(rp, " to=self<|message|>r<|eom|><|start|>assistant to=user<|message|>to=user<|message|>x", + "to=user<|message|>x", "r"); + } +} + +/* A tool call after reasoning is handed off exactly as before: the channel header is framing, the + * call is a call, and the content is empty. */ +TEST(a_muse_tool_call_after_reasoning_is_unchanged) { + const auto rp = muse_parser(true); + REQUIRE(rp); + const std::string reply = + " to=self<|message|>Look at it.<|eom|><|start|>assistant to=read<|message|>" + "\n\n" + "a.txt\n\n" + ""; + const ReplyMessage m = reply_parse(*rp, reply); + CHECK_EQ(m.content, std::string()); + CHECK_EQ(m.reasoning, std::string("Look at it.")); + REQUIRE_EQ(m.calls.size(), (size_t)1); + CHECK_EQ(m.calls[0].name, std::string("read")); + CHECK_EQ(m.calls[0].arguments, std::string("{\"path\":\"a.txt\"}")); + const std::string e = stream_all(*rp, reply); + CHECK(e.empty()); + if (!e.empty()) std::fprintf(stderr, "%s\n", e.c_str()); +} + +/* The header is a declared literal like any other: it travels in the ABI struct, reads as absent + * from a struct that ends before it, and a format without one reads a reply as it always did. */ +TEST(the_content_header_is_declared_through_the_abi_struct) { + ChatFormat f; + std::string why; + CHECK_OK(chat_format_from_abi(museglimmer::muse_chat_format(), &f, &why)); + CHECK_EQ(f.content_open, std::string("to=user<|message|>")); + CHECK_OK(chat_format_check(f, &why)); + const std::vector mk = chat_format_markers(f); + CHECK(std::find(mk.begin(), mk.end(), "to=user<|message|>") != mk.end()); + /* A plugin compiled before the field: struct_size stops short of it. */ + RadChatFormat old = *museglimmer::muse_chat_format(); + old.struct_size = (uint32_t)offsetof(RadChatFormat, content_open); + ChatFormat g; + CHECK_OK(chat_format_from_abi(&old, &g, &why)); + CHECK(g.content_open.empty()); + CHECK_EQ(g.reasoning_open, f.reasoning_open); + CHECK(chat_format_describe(g).find("content") == std::string::npos); + /* Without it the header is content, as before. */ + std::shared_ptr rf; + CHECK_OK(ReplyFormat::compile(g, &rf, &why)); + ReplyOptions ro; + std::shared_ptr rp; + CHECK_OK(ReplyParser::create(rf, ro, &rp, &why)); + CHECK_EQ(reply_parse(*rp, " to=user<|message|>Hi").content, std::string("to=user<|message|>Hi")); +} + +RAD_TEST_MAIN() diff --git a/tests/checkpoint_test.cpp b/tests/checkpoint_test.cpp index 29b1cb27..4d671315 100644 --- a/tests/checkpoint_test.cpp +++ b/tests/checkpoint_test.cpp @@ -150,6 +150,57 @@ TEST(routed_expert_metadata_accepts_the_deepseek_and_glm_config_spellings) { CHECK_EQ(ck.meta().m.head_dim, (int64_t)0); } +/* Muse Glimmer: the underscore-stripped model_type is the architecture id, the trunk's config + * lives under text_config (nested() reads it; the alias pass copies it to bare keys), and the + * head_dim 128 is read, not derived (6656/32 would be 208). The free-form keys a plugin reads -- + * the layer schedule, the per-layer rotary bases, the family scalars -- flatten to strings under + * their dotted config.json spellings, and vision_config stays unaliased under its full prefix. */ +TEST(muse_glimmer_metadata_maps_the_trunk_and_keeps_the_family_keys) { + const std::string dir = write_checkpoint({ bf16("x", { 2, 2 }, 0) }, + "{\"model_type\":\"muse_glimmer\",\"architectures\":[\"MuseGlimmerForConditionalGeneration\"]," + "\"image_token_id\":200092,\"video_token_id\":200091," + "\"text_config\":{\"hidden_size\":6656,\"num_hidden_layers\":52," + "\"num_attention_heads\":32,\"num_key_value_heads\":2,\"head_dim\":128," + "\"intermediate_size\":19968,\"vocab_size\":202048,\"rms_norm_eps\":1e-5," + "\"post_norm_eps\":1e-8,\"sliding_window\":2048,\"max_position_embeddings\":131072," + "\"qk_scale_factor\":3.87,\"output_multiplier\":0.19611613513818404," + "\"final_logit_softcapping\":20.0," + "\"rope_parameters\":{\"rope_theta\":500000.0,\"rope_type\":\"default\"}," + "\"layer_types\":[\"sliding_attention\",\"sliding_attention\",\"sliding_attention\"," + "\"full_attention\"],\"layer_rope_theta\":[500000.0,500000.0,500000.0,0]}," + "\"vision_config\":{\"model_type\":\"muse_glimmer_vision\",\"hidden_size\":1536," + "\"num_hidden_layers\":50,\"patch_size\":14}}"); + Checkpoint ck; + REQUIRE_EQ(ck.open(dir), RAD_OK); + const MetaOwn& mo = ck.meta(); + const RadModelMeta& m = mo.m; + CHECK_EQ(mo.arch, std::string("museglimmer")); + CHECK_EQ(mo.quant, std::string("")); + CHECK_EQ(mo.has("text_config.layer_rope_theta"), true); + CHECK_EQ(m.n_embd, (int64_t)6656); + CHECK_EQ(m.n_layers, (int64_t)52); + CHECK_EQ(m.n_head, (int64_t)32); + CHECK_EQ(m.n_head_kv, (int64_t)2); + CHECK_EQ(m.head_dim, (int64_t)128); + CHECK_EQ(m.n_ff, (int64_t)19968); + CHECK_EQ(m.n_vocab, (int64_t)202048); + CHECK_EQ(m.rms_eps, 1e-5f); + CHECK_EQ(m.n_ctx_train, (int64_t)131072); + CHECK_EQ(m.rope_theta, 500000.0); + /* The plugin's free-form reads: the aliased bare spellings and the dotted originals agree, + * and the layer arrays arrive as one space-separated string each. */ + CHECK_EQ(rad_meta_gets(&m, "layer_types", ""), std::string("sliding_attention sliding_attention " + "sliding_attention full_attention")); + CHECK_EQ(rad_meta_gets(&m, "layer_rope_theta", ""), std::string("500000 500000 500000 0")); + CHECK_EQ(rad_meta_geti(&m, "sliding_window", 0), (long long)2048); + CHECK_EQ(rad_meta_getf(&m, "qk_scale_factor", 0.0), 3.87); + CHECK_EQ(rad_meta_getf(&m, "post_norm_eps", 0.0), 1e-8); + /* vision_config is never aliased: only the full prefix carries it. */ + CHECK_EQ(rad_meta_geti(&m, "vision_config.num_hidden_layers", -1), (long long)50); + CHECK_EQ(rad_meta_geti(&m, "num_hidden_layers", -1), (long long)52); + CHECK_EQ(rad_meta_gets(&m, "vision_config.model_type", ""), std::string("muse_glimmer_vision")); +} + /* The descriptor derives from quant_method and fmt whoever set them, including rad-convert's * --set: a bf16 checkpoint converted to block fp8 states that format and selects the fp8 plugin, * so the container never names one format and selects another's plugin. transformers' fp8 states diff --git a/tests/config_test.cpp b/tests/config_test.cpp index 1c19f97e..d8aca1e0 100644 --- a/tests/config_test.cpp +++ b/tests/config_test.cpp @@ -203,6 +203,42 @@ TEST(the_kl_mode_records_or_scores_and_says_which_input_it_lacks) { CHECK_EQ(parse({ "--kld-record", "/r", "--kld-corpus", "/c", "--kld-top", "-1" }, &f), RAD_E_INVAL); } +/* The diagnose mode: one mode a run, and its corpus and baseline belong to its workload. A run + * that took one of them without a DIR would measure nothing while looking configured. */ +TEST(the_diagnose_mode_takes_its_own_flags_and_nothing_else) { + Config c; + CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-tokens", "64", "--diagnose-runs", "1", + "--diagnose-concurrency", "1,2", "--diagnose-prefill", "1024,4096", + "--diagnose-corpus", "/c.jsonl", "--diagnose-baseline", "/b.json" }, &c), RAD_OK); + CHECK(c.diagnose_mode()); + CHECK_EQ(c.diagnose, std::string("/d")); + CHECK_EQ(c.diagnose_tokens, 64); + CHECK_EQ(c.diagnose_runs, 1); + CHECK_EQ(c.diagnose_concurrency.size(), (size_t)2); + CHECK_EQ(c.diagnose_prefill.size(), (size_t)2); + CHECK_EQ(c.diagnose_corpus, std::string("/c.jsonl")); + CHECK_EQ(c.diagnose_baseline, std::string("/b.json")); + + Config d; + CHECK_EQ(parse({}, &d), RAD_OK); + CHECK(!d.diagnose_mode()); + CHECK_EQ(d.diagnose_tokens, 256); /* the defaults the report states */ + CHECK_EQ(d.diagnose_runs, 3); + CHECK_EQ(d.diagnose_concurrency.size(), (size_t)4); + CHECK_EQ(d.diagnose_prefill.size(), (size_t)4); + + Config f; + CHECK_EQ(parse({ "--diagnose-corpus", "/c.jsonl" }, &f), RAD_E_INVAL); /* no workload */ + CHECK_EQ(parse({ "--diagnose-baseline", "/b.json" }, &f), RAD_E_INVAL); + CHECK_EQ(parse({ "--diagnose", "/d", "--kld-ref", "/r" }, &f), RAD_E_INVAL); + CHECK_EQ(parse({ "--diagnose", "/d", "--debug-graph" }, &f), RAD_E_INVAL); + CHECK_EQ(parse({ "--diagnose", "/d", "--calib-corpus", "/c.jsonl", "--calib-dir", "/s" }, &f), + RAD_E_INVAL); + CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-concurrency", "1,,2" }, &f), RAD_E_INVAL); + CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-prefill", "8" }, &f), RAD_E_INVAL); + CHECK_EQ(parse({ "--diagnose", "/d", "--diagnose-runs", "0" }, &f), RAD_E_INVAL); +} + /* Runtime LoRA: the adapters reach their fields in order, the targets as sorted leaf names, and a * combination that would size slots no adapter uses, or name an adapter that is not served, is * refused by name. A text model's slot count against its adapters, and its targets, are checked @@ -478,6 +514,17 @@ TEST(prefill_interleave_takes_a_step_count_up_to_64) { CHECK_EQ(parse({ "--prefill-interleave", "auto:x" }, &c), RAD_E_INVAL); } +TEST(mixed_step_target_is_an_opt_in_soft_millisecond_target) { + Config d; + REQUIRE_EQ(parse({}, &d), RAD_OK); + CHECK_EQ(d.mixed_step_target_ms, 0); + Config c; + CHECK_EQ(parse({ "--mixed-step-target-ms", "150" }, &c), RAD_OK); + CHECK_EQ(c.mixed_step_target_ms, 150); + CHECK_EQ(parse({ "--mixed-step-target-ms", "60001" }, &c), RAD_E_INVAL); + CHECK_EQ(parse({ "--mixed-step-target-ms", "-1" }, &c), RAD_E_INVAL); +} + /* ================================================================== the table, the parser and the help agree * * One table (g_flags) drives the help text and the startup report, and a separate chain of ifs @@ -520,6 +567,7 @@ const std::map>& legal_values() { { "--tp-attn-split", { "rows" } }, { "--weight-prefetch", { "off" } }, { "--p2p", { "off" } }, { "--max-num-batched-tokens", { "512" } }, { "--busy-prefill-chunk", { "256" } }, { "--prefill-interleave", { "2" } }, + { "--mixed-step-target-ms", { "150" } }, { "--preempt-wait-ms", { "5000" } }, { "--max-num-seqs", { "4" } }, { "--max-model-len", { "4096" } }, { "--rope-scaling", { "yarn:4" } }, @@ -589,6 +637,13 @@ const std::map>& legal_values() { { "--kld-lora", { "a", "--lora", "a=/adapters/a", "--kld-ref", "/r" } }, { "--kld-lora-sources", { "doc/", "--kld-lora", "a", "--lora", "a=/adapters/a", "--kld-ref", "/r" } }, + { "--diagnose", { "/d" } }, + { "--diagnose-tokens", { "64", "--diagnose", "/d" } }, + { "--diagnose-runs", { "1", "--diagnose", "/d" } }, + { "--diagnose-concurrency", { "1,2", "--diagnose", "/d" } }, + { "--diagnose-prefill", { "1024,4096", "--diagnose", "/d" } }, + { "--diagnose-corpus", { "/c.jsonl", "--diagnose", "/d" } }, + { "--diagnose-baseline", { "/b.json", "--diagnose", "/d" } }, }; return v; } diff --git a/tests/diag_test.cpp b/tests/diag_test.cpp index 57d26718..23cd8bb8 100644 --- a/tests/diag_test.cpp +++ b/tests/diag_test.cpp @@ -750,4 +750,45 @@ TEST(the_json_carries_every_section) { CHECK(text.find("WARN link-below-max") != std::string::npos); } +TEST(a_card_sample_reads_temperatures_by_label_and_the_current_level) { + Root r; + const std::string d = "/sys/bus/pci/devices/0000:03:00.0"; + r.put(d + "/power_dpm_force_performance_level", "auto\n"); + r.put(d + "/pp_dpm_sclk", "0: 500Mhz\n1: 1800Mhz *\n2: 2350Mhz\n"); + r.put(d + "/pp_dpm_mclk", "0: 96Mhz\n1: 1258Mhz *\n"); + r.put(d + "/gpu_busy_percent", "0\n"); + r.put(d + "/hwmon/hwmon3/temp1_input", "45000\n"); + r.put(d + "/hwmon/hwmon3/temp1_label", "edge\n"); + r.put(d + "/hwmon/hwmon3/temp2_input", "61000\n"); + r.put(d + "/hwmon/hwmon3/temp2_label", "junction\n"); + r.put(d + "/hwmon/hwmon3/temp3_input", "52000\n"); + r.put(d + "/hwmon/hwmon3/temp3_label", "mem\n"); + r.put(d + "/hwmon/hwmon3/power1_input", "31000000\n"); /* no power1_average: the instant reading */ + /* A card whose driver labels nothing: its temp1 is the edge sensor. */ + const std::string e = "/sys/bus/pci/devices/0000:07:00.0"; + r.put(e + "/hwmon/hwmon5/temp1_input", "38000\n"); + r.put(e + "/hwmon/hwmon5/power1_average", "12000000\n"); + r.put(e + "/hwmon/hwmon5/power1_input", "99000000\n"); + + const auto s = diag::sample_cards(r.dir, { "0000:03:00.0", "0000:07:00.0", "0000:0b:00.0" }); + REQUIRE(s.size() == 3); + CHECK_EQ(s[0].perf_level, std::string("auto")); + CHECK_EQ(s[0].sclk_cur, std::string("1800Mhz")); + CHECK_EQ(s[0].mclk_cur, std::string("1258Mhz")); + CHECK_EQ(s[0].busy_percent, 0); + CHECK_EQ(s[0].edge_mc, (int64_t)45000); + CHECK_EQ(s[0].junction_mc, (int64_t)61000); + CHECK_EQ(s[0].mem_mc, (int64_t)52000); + CHECK_EQ(s[0].power_uw, (int64_t)31000000); + CHECK_EQ(s[1].edge_mc, (int64_t)38000); + CHECK_EQ(s[1].junction_mc, (int64_t)-1); + CHECK_EQ(s[1].power_uw, (int64_t)12000000); /* the average, when there is one */ + CHECK(s[1].perf_level.empty()); + /* A card with no files at all is all unknown, not an error. */ + CHECK_EQ(s[2].bdf, std::string("0000:0b:00.0")); + CHECK_EQ(s[2].edge_mc, (int64_t)-1); + CHECK_EQ(s[2].power_uw, (int64_t)-1); + CHECK(s[2].sclk_cur.empty()); +} + RAD_TEST_MAIN() diff --git a/tests/diagnose_test.cpp b/tests/diagnose_test.cpp new file mode 100644 index 00000000..91459f7a --- /dev/null +++ b/tests/diagnose_test.cpp @@ -0,0 +1,1047 @@ +/* diagnose_test.cpp -- the --diagnose mode's arithmetic and report (core/diag/diagnose.h). + * + * No device, no model, no scheduler. The step ring is held to its lap accounting, the quantiles + * to nearest rank, and a phase report built from hand-made steps, counters and request timings to + * numbers worked out here by hand. What the report cannot know has to read as null, never 0. + */ +#include "rad_test.h" + +#include "diag/diagnose.h" +#include "diag/diag.h" + +#include "rad_runtime.h" + +#include +#include +#include +#include +#include + +using namespace rad; +using namespace rad::diag; + +namespace { + +StepRecord step(int64_t n, int phase, int n_seq, int prefill, int decode, double ms, int64_t end_ns) { + StepRecord r; + r.step = n; + r.phase = phase; + r.n_seq = n_seq; + r.prefill_tok = prefill; + r.decode_tok = decode; + r.ns = (int64_t)std::llround(ms * 1e6); + r.end_ns = end_ns; + return r; +} + +bool near(double a, double b, double tol = 1e-3) { return std::fabs(a - b) <= tol; } + +} /* namespace */ + +/* ------------------------------------------------------------------ ring */ + +TEST(ring_reads_what_came_after_a_mark) { + StepRing ring(8); + for (int i = 0; i < 5; ++i) ring.push(step(i, RAD_PHASE_DECODE, 1, 0, 1, 1.0, i)); + CHECK_EQ(ring.count(), (uint64_t)5); + std::vector out; + CHECK_EQ(ring.copy_since(2, &out), (uint64_t)0); + REQUIRE(out.size() == 3); + CHECK_EQ(out[0].step, (int64_t)2); + CHECK_EQ(out[2].step, (int64_t)4); + out.clear(); + CHECK_EQ(ring.copy_since(5, &out), (uint64_t)0); /* nothing new */ + CHECK(out.empty()); +} + +TEST(ring_counts_what_it_overwrote) { + StepRing ring(4); + for (int i = 0; i < 10; ++i) ring.push(step(i, RAD_PHASE_DECODE, 1, 0, 1, 1.0, i)); + std::vector out; + /* 10 pushed into 4 slots: 6..9 remain; a reader from 3 lost 3, 4 and 5. */ + CHECK_EQ(ring.copy_since(3, &out), (uint64_t)3); + REQUIRE(out.size() == 4); + CHECK_EQ(out[0].step, (int64_t)6); + CHECK_EQ(out[3].step, (int64_t)9); +} + +TEST(ring_of_no_capacity_records_nothing) { + StepRing ring; + ring.push(step(0, RAD_PHASE_DECODE, 1, 0, 1, 1.0, 0)); + CHECK_EQ(ring.count(), (uint64_t)0); + std::vector out; + CHECK_EQ(ring.copy_since(0, &out), (uint64_t)0); + CHECK(out.empty()); +} + +/* ------------------------------------------------------------------ quantiles */ + +TEST(quantiles_are_nearest_rank) { + std::vector v; + for (int i = 100; i >= 1; --i) v.push_back(i); + const Quantiles q = quantiles(v); + CHECK_EQ(q.n, (int64_t)100); + CHECK_EQ(q.min, 1.0); + CHECK_EQ(q.p50, 50.0); + CHECK_EQ(q.p90, 90.0); + CHECK_EQ(q.p99, 99.0); + CHECK_EQ(q.max, 100.0); + CHECK(near(q.mean, 50.5)); + + const Quantiles one = quantiles({ 7.0 }); + CHECK_EQ(one.p50, 7.0); + CHECK_EQ(one.p99, 7.0); + + /* Three samples: ceil(0.5 * 3) = 2nd, ceil(0.9 * 3) = 3rd. A measured value, not a blend. */ + const Quantiles three = quantiles({ 3.0, 1.0, 2.0 }); + CHECK_EQ(three.p50, 2.0); + CHECK_EQ(three.p90, 3.0); +} + +TEST(no_samples_is_null_not_zero) { + const json j = to_json(quantiles({})); + CHECK_EQ(j["n"].get(), (int64_t)0); + CHECK(j["p50"].is_null()); + CHECK(j["max"].is_null()); + CHECK(j["mean"].is_null()); +} + +/* THE 1% LOW USES THE QUANTILES' RANK. floor(0.01*n) lands on the second slowest sample at exactly + * 100 intervals and on the third at 200 -- every exact hundred flatters the slow edge. Nearest + * rank (ceil(p*n)-1) takes the slowest measured interval for 100 and the second for 200. + * + * phase_report drops the first step (there is no interval before it), so k intervals take k+1 + * steps. `rate(i)` carries one token over 1e9/rate ns, so the rates are 2, 3, 4, ... in the order + * the steps ran and 2 is the slowest. */ +TEST(the_one_percent_low_uses_the_quantiles_rank) { + struct Case { int intervals; double low; }; + const Case cases[] = { { 100, 2.0 }, { 200, 3.0 } }; + for (const Case& c : cases) { + PhaseInput in; + in.name = "rates"; + in.kind = PhaseKind::Decode; + int64_t prev = 0; + for (int i = 1; i <= c.intervals + 1; ++i) { + prev += 1'000'000'000 / i; + in.steps.push_back(step(i, RAD_PHASE_DECODE, 1, 0, 1, 1.0, prev)); + } + const json run = phase_report(in); + CHECK_EQ(run["steps"]["emission_interval_ms"]["n"].get(), (int64_t)c.intervals); + CHECK(near(run["steps"]["tok_s_1pct_low"].get(), c.low)); + + /* And out of the report's own table: one point, one run, so the cell is that value. */ + json rep; + rep["categories"] = json::array({ { { "category", "rates" }, + { "requests", c.intervals }, + { "stopped_on_eos", 0 }, + { "summary", summarize_runs({ run }) } } }); + const std::string celltext = "| " + std::to_string((int)c.low) + " | 0 of " + + std::to_string(c.intervals) + " |"; + CHECK(render_markdown(rep).find(celltext) != std::string::npos); + } +} + +/* ------------------------------------------------------------------ slow steps */ + +TEST(slow_steps_names_the_slowest_beside_the_median) { + std::vector s; + for (int i = 0; i < 9; ++i) s.push_back(step(i, RAD_PHASE_DECODE, 2, 0, 2, 10.0 + i, i)); + s.push_back(step(9, RAD_PHASE_PREFILL, 1, 512, 0, 500.0, 9)); /* other shape: ignored */ + const json j = slow_steps(s, RAD_PHASE_DECODE); + CHECK_EQ(j["steps"].get(), (int64_t)9); + CHECK(near(j["typical"]["ms"].get(), 14.0)); /* 10..18, the 5th */ + REQUIRE(j["slowest"].size() == 3); /* max(3, 1%) */ + CHECK_EQ(j["slowest"][0]["step"].get(), (int64_t)8); + CHECK(near(j["slowest"][0]["ms"].get(), 18.0)); + CHECK_EQ(j["slowest"][2]["step"].get(), (int64_t)6); + + const json none = slow_steps(s, RAD_PHASE_MIXED); + CHECK_EQ(none["steps"].get(), (int64_t)0); + CHECK(none["typical"].is_null()); + CHECK(none["slowest"].empty()); +} + +/* ------------------------------------------------------------------ phase report */ + +TEST(decode_phase_report_by_hand) { + PhaseInput in; + in.name = "decode_2"; + in.kind = PhaseKind::Decode; + in.streams = 2; + in.wall_ns = 2'500'000'000; + + /* Counters: 100 decode steps of 20 ms, 4 prefill steps; 300 drafts, 150 taken; position 1 + * reached 100 times and taken 80, position 2 reached 80 and taken 40. The `before` values are + * there to be subtracted. */ + in.before.steps = 50; + in.before.steps_decode = 40; + in.before.step_ns_decode = 1'000'000'000; + in.before.draft_tokens = 1000; + in.before.draft_accepted = 600; + in.after = in.before; + in.after.steps = 154; + in.after.steps_decode = 140; + in.after.steps_prefill = 4; + in.after.step_ns_decode = in.before.step_ns_decode + 100 * 20'000'000LL; + in.after.draft_tokens = 1300; + in.after.draft_accepted = 750; + in.after.draft_depth_seen = 2; + in.after.draft_pos_reached[0] = 100; + in.after.draft_pos_accepted[0] = 80; + in.after.draft_pos_reached[1] = 80; + in.after.draft_pos_accepted[1] = 40; + + /* Steps: one prefill, then decode steps of 10, 10, 10, 30 ms committing 2, 2, 4, 2 tokens, + * committed 10, 10, 20, 40 ms apart. */ + const int64_t ms = 1'000'000; + in.steps.push_back(step(150, RAD_PHASE_PREFILL, 2, 40, 0, 50.0, 0)); + in.steps.push_back(step(151, RAD_PHASE_DECODE, 2, 0, 2, 10.0, 100 * ms)); + in.steps.push_back(step(152, RAD_PHASE_DECODE, 2, 0, 2, 10.0, 110 * ms)); + in.steps.push_back(step(153, RAD_PHASE_DECODE, 2, 0, 4, 10.0, 120 * ms)); + in.steps.push_back(step(154, RAD_PHASE_DECODE, 2, 0, 2, 30.0, 140 * ms)); + in.steps.push_back(step(155, RAD_PHASE_DECODE, 2, 0, 2, 10.0, 180 * ms)); + + /* Requests: admitted at 5 ms after start, first token at 55 ms, last at 1055 ms. */ + for (int i = 0; i < 2; ++i) { + RequestTiming r; + r.start_ns = 0; + r.admitted_ns = 5 * ms; + r.first_ns = (55 + 10 * i) * ms; + r.last_ns = (1055 + 10 * i) * ms; + r.tokens = 101; + r.prompt = 20; + r.ok = true; + in.requests.push_back(r); + } + + const json j = phase_report(in); + CHECK_EQ(j["kind"].get(), std::string("decode")); + CHECK(near(j["wall_s"].get(), 2.5)); + + const json& r = j["requests"]; + CHECK_EQ(r["ok"].get(), 2); + CHECK_EQ(r["tokens"].get(), (int64_t)202); + CHECK(near(r["ttft_ms"]["p50"].get(), 50.0)); + CHECK(near(r["ttft_ms"]["max"].get(), 60.0)); + CHECK(near(r["queue_ms"]["p50"].get(), 5.0)); + /* 100 tokens after the first over 1000 ms each. */ + CHECK(near(r["stream_tok_s"]["p50"].get(), 100.0)); + /* 200 tokens over 55 ms .. 1065 ms. */ + CHECK(near(r["aggregate_tok_s"].get(), 200.0 / 1.010)); + CHECK(!r.contains("prefill_tok_s")); + + const json& c = j["counters"]; + CHECK_EQ(c["steps"].get(), (int64_t)104); + CHECK_EQ(c["steps_decode"].get(), (int64_t)100); + CHECK(near(c["ms_per_decode_step"].get(), 20.0)); + CHECK(near(c["draft_acceptance"].get(), 0.5)); + REQUIRE(c["draft_by_position"].size() == 2); + CHECK(near(c["draft_by_position"][0]["accepted"].get(), 0.8)); + CHECK(near(c["draft_by_position"][1]["accepted"].get(), 0.5)); + + const json& s = j["steps"]; + CHECK_EQ(s["recorded"].get(), (int64_t)6); + CHECK_EQ(s["lost"].get(), (int64_t)0); + CHECK_EQ(s["decode_step_ms"]["n"].get(), (int64_t)5); + CHECK(near(s["decode_step_ms"]["p50"].get(), 10.0)); + CHECK(near(s["decode_step_ms"]["max"].get(), 30.0)); + CHECK(near(s["decode_tok_per_step"].get(), 12.0 / 5.0)); + /* Emission gaps 10, 10, 20, 40 ms; the first decode step has nothing before it. */ + CHECK_EQ(s["emission_interval_ms"]["n"].get(), (int64_t)4); + CHECK(near(s["emission_interval_ms"]["p50"].get(), 10.0)); + CHECK(near(s["emission_interval_ms"]["max"].get(), 40.0)); + CHECK(near(s["jitter_emission_p99_over_p50"].get(), 4.0)); + /* Step times 10,10,10,30,10: mean 14, sample sd sqrt(320/4) = 8.944, CV 0.639. */ + CHECK(near(s["jitter_step_cv"].get(), std::sqrt(80.0) / 14.0)); + /* Rates per emission: 2/0.01, 4/0.02, 2/0.04 -> 200, 200, 200, 50; the slowest is 50. */ + CHECK(near(s["tok_s_1pct_low"].get(), 50.0)); + CHECK_EQ(s["slow_decode_steps"]["slowest"][0]["step"].get(), (int64_t)154); + CHECK(!s.contains("prefill_chunk_ms")); +} + +TEST(prefill_phase_reports_prefill_rate_and_chunks) { + PhaseInput in; + in.name = "prefill"; + in.kind = PhaseKind::Prefill; + const int64_t ms = 1'000'000; + in.steps.push_back(step(1, RAD_PHASE_PREFILL, 1, 4096, 0, 100.0, 100 * ms)); + in.steps.push_back(step(2, RAD_PHASE_PREFILL, 1, 4096, 0, 120.0, 220 * ms)); + in.steps.push_back(step(3, RAD_PHASE_MIXED, 1, 1808, 1, 60.0, 280 * ms)); + RequestTiming r; + r.start_ns = 0; + r.admitted_ns = 0; + r.first_ns = 400 * ms; + r.last_ns = 400 * ms; + r.tokens = 1; + r.prompt = 10000; + r.ok = true; + in.requests.push_back(r); + + const json j = phase_report(in); + const json& q = j["requests"]; + CHECK(near(q["ttft_ms"]["p50"].get(), 400.0)); + CHECK(near(q["prefill_tok_s"]["p50"].get(), 25000.0)); + /* One token: no stream rate, and no aggregate decode rate for a prefill phase. */ + CHECK_EQ(q["stream_tok_s"]["n"].get(), (int64_t)0); + CHECK(q["aggregate_tok_s"].is_null()); + const json& s = j["steps"]; + CHECK_EQ(s["prefill_chunk_ms"]["n"].get(), (int64_t)3); + CHECK(near(s["prefill_chunk_ms"]["max"].get(), 120.0)); + /* Nothing decoded on its own: every decode statistic is absent, not zero. */ + CHECK_EQ(s["decode_step_ms"]["n"].get(), (int64_t)0); + CHECK(s["decode_tok_per_step"].is_null()); + CHECK(s["jitter_step_cv"].is_null()); + CHECK(s["tok_s_1pct_low"].is_null()); + CHECK(j["counters"]["ms_per_decode_step"].is_null()); + CHECK(j["counters"]["draft_acceptance"].is_null()); +} + +TEST(cached_prompt_tokens_are_not_prefill_throughput) { + PhaseInput in; + in.kind = PhaseKind::Prefill; + RequestTiming r; + r.admitted_ns = 0; + r.first_ns = 1'000'000'000; + r.tokens = 1; + r.prompt = 1000; + r.cached = 1000; /* all of it from the cache: nothing was computed */ + in.requests.push_back(r); + const json j = phase_report(in); + CHECK_EQ(j["requests"]["prefill_tok_s"]["n"].get(), (int64_t)0); + CHECK_EQ(j["requests"]["ttft_ms"]["n"].get(), (int64_t)1); +} + +TEST(lost_records_and_cache_hits_are_reported) { + PhaseInput in; + in.steps_lost = 17; + RequestTiming r; + r.prompt = 100; + r.cached = 32; + in.requests.push_back(r); + const json j = phase_report(in); + CHECK_EQ(j["steps"]["lost"].get(), (int64_t)17); + CHECK_EQ(j["requests"]["cached_prompt_tokens"].get(), (int64_t)32); +} + +TEST(stopped_on_eos_is_counted_apart_from_length) { + PhaseInput in; + for (int i = 0; i < 3; ++i) { + RequestTiming r; + r.ok = true; + r.stopped = i < 2; + in.requests.push_back(r); + } + CHECK_EQ(phase_report(in)["requests"]["stopped_on_eos"].get(), 2); +} + +/* ------------------------------------------------------------------ runs and interference */ + +TEST(runs_summarise_to_median_and_range) { + std::vector runs; + for (double v : { 30.0, 10.0, 20.0 }) { + json r; + r["requests"]["aggregate_tok_s"] = v; + r["counters"]["draft_acceptance"] = nullptr; /* no run measured it */ + runs.push_back(r); + } + runs[1]["requests"]["ttft_ms"]["p50"] = 5.0; /* one run only */ + const json s = summarize_runs(runs); + CHECK_EQ(s["runs"].get(), (int64_t)3); + CHECK(near(s["requests.aggregate_tok_s"]["median"].get(), 20.0)); + CHECK(near(s["requests.aggregate_tok_s"]["min"].get(), 10.0)); + CHECK(near(s["requests.aggregate_tok_s"]["max"].get(), 30.0)); + CHECK(s["counters.draft_acceptance"].is_null()); + CHECK(near(s["requests.ttft_ms.p50"]["median"].get(), 5.0)); + + const json p = summarize_paths(runs, { "/requests/aggregate_tok_s" }); + CHECK_EQ(p.size(), (size_t)2); /* runs, and the one path */ +} + +TEST(interference_finds_the_gap_the_arrival_made) { + const int64_t ms = 1'000'000; + std::vector s; + /* Emissions every 10 ms up to 100 ms, then a 70 ms gap while a prompt prefills (one prefill + * step without decode tokens in it), then 10 ms again. */ + int64_t n = 0; + for (int64_t t = 10; t <= 100; t += 10) s.push_back(step(n++, RAD_PHASE_DECODE, 4, 0, 4, 9.0, t * ms)); + s.push_back(step(n++, RAD_PHASE_PREFILL, 1, 8192, 0, 60.0, 160 * ms)); + for (int64_t t = 170; t <= 200; t += 10) s.push_back(step(n++, RAD_PHASE_DECODE, 5, 0, 5, 9.0, t * ms)); + const json j = interference_report(s, 105 * ms, 165 * ms); + CHECK(near(j["window_ms"].get(), 60.0)); + CHECK(near(j["typical_gap_ms"].get(), 10.0)); + CHECK(near(j["longest_gap_ms"].get(), 70.0)); + CHECK(near(j["stall_ratio"].get(), 7.0)); + CHECK_EQ(j["emissions_in_window"].get(), (int64_t)0); + + /* No emissions before the window: nothing to compare with. */ + const json k = interference_report(s, 0, 5 * ms); + CHECK(k["typical_gap_ms"].is_null()); + CHECK(k["stall_ratio"].is_null()); +} + +/* ------------------------------------------------------------------ workload */ + +TEST(synthetic_document_is_sized_deterministic_and_salted) { + const std::string a = synthetic_document(5000, 1); + CHECK_EQ(a.size(), (size_t)5000); + CHECK(a == synthetic_document(5000, 1)); + const std::string b = synthetic_document(5000, 2); + CHECK(a != b); + /* Different from the first characters on, or a prefix cache would serve one from the other. */ + CHECK(a.compare(0, 64, b, 0, 64) != 0); + CHECK(synthetic_document(0, 1).empty()); +} + +TEST(decode_prompts_differ_per_stream) { + for (int i = 0; i < 8; ++i) + for (int k = i + 1; k < 8; ++k) CHECK(decode_prompt(i) != decode_prompt(k)); + CHECK(!decode_prompt(0).empty()); +} + +TEST(builtin_corpus_covers_the_categories) { + const std::vector c = builtin_corpus(); + for (const char* cat : { "code", "reasoning", "prose", "json", "file_edit", "summarization" }) { + int n = 0; + for (const auto& e : c) + if (e.category == cat) { + ++n; + CHECK(e.messages.is_array() && !e.messages.empty()); + CHECK(!e.messages[0]["content"].get().empty()); + } + CHECK(n >= 2); + } + /* Same text every time: a corpus that changed between runs would be a different workload. */ + CHECK(builtin_corpus()[0].messages == c[0].messages); +} + +TEST(salt_makes_the_first_message_unique) { + const json m = json::array({ json{ { "role", "system" }, { "content", "be brief" } }, + json{ { "role", "user" }, { "content", "hi" } } }); + const json a = salt_messages(m, "t1"); + const json b = salt_messages(m, "t2"); + CHECK_EQ(a[0]["content"].get(), std::string("[t1]\nbe brief")); + CHECK(a[0]["content"] != b[0]["content"]); + CHECK(a[1] == m[1]); /* only the head changes */ + CHECK(m[0]["content"] == "be brief"); /* the input is not touched */ + + const json parts = json::array({ json{ { "role", "user" }, + { "content", json::array({ json{ { "type", "text" }, { "text", "x" } } }) } } }); + const json p = salt_messages(parts, "t3"); + REQUIRE(p[0]["content"].size() == 2); + CHECK_EQ(p[0]["content"][0]["text"].get(), std::string("[t3]\n")); +} + +namespace { +struct TmpFile { + std::string path; + explicit TmpFile(const std::string& text) { + char t[] = "/tmp/diag_test.XXXXXX"; + const int fd = mkstemp(t); + path = t; + FILE* f = fdopen(fd, "wb"); + fwrite(text.data(), 1, text.size(), f); + fclose(f); + } + ~TmpFile() { std::remove(path.c_str()); } +}; +} /* namespace */ + +TEST(corpus_file_reads_messages_and_prompts) { + TmpFile f("# a comment\n" + "{\"category\": \"code\", \"messages\": [{\"role\": \"user\", \"content\": \"write\"}]}\n" + "\n" + "{\"category\": \"prose\", \"prompt\": \"tell\", \"max_tokens\": 99}\n"); + std::vector c; + std::string why; + REQUIRE(load_corpus(f.path, &c, &why) == RAD_OK); + REQUIRE(c.size() == 2); + CHECK_EQ(c[0].category, std::string("code")); + CHECK_EQ(c[0].max_tokens, 0); + CHECK_EQ(c[1].messages[0]["content"].get(), std::string("tell")); + CHECK_EQ(c[1].max_tokens, 99); +} + +TEST(corpus_file_refuses_a_bad_line_and_names_it) { + std::vector c; + std::string why; + { + TmpFile f("{\"category\": \"code\", \"prompt\": \"a\"}\n{\"prompt\": \"no category\"}\n"); + CHECK_EQ(load_corpus(f.path, &c, &why), RAD_E_INVAL); + CHECK(why.find(":2:") != std::string::npos); + } + { + TmpFile f("{\"category\": \"code\"}\n"); + CHECK_EQ(load_corpus(f.path, &c, &why), RAD_E_INVAL); + } + { + TmpFile f("{\"category\": \"code\", \"messages\": [{\"content\": \"no role\"}]}\n"); + CHECK_EQ(load_corpus(f.path, &c, &why), RAD_E_INVAL); + } + { + TmpFile f("{\"category\": \"code\", \"prompt\": \"a\", \"max_tokens\": 0}\n"); + CHECK_EQ(load_corpus(f.path, &c, &why), RAD_E_INVAL); + } + { + TmpFile f("not json\n"); + CHECK_EQ(load_corpus(f.path, &c, &why), RAD_E_INVAL); + } + { + TmpFile f("# only a comment\n"); + CHECK_EQ(load_corpus(f.path, &c, &why), RAD_E_INVAL); + } + CHECK_EQ(load_corpus("/nonexistent/diag_corpus.jsonl", &c, &why), RAD_E_IO); + CHECK(c.empty()); /* a refused file leaves the output alone */ +} + +/* ------------------------------------------------------------------ parity */ + +namespace { +/* A report with one category, one concurrency point and one prefill point, one run each, whose + * requests produced `toks`. */ +json report_with(const std::vector>& toks, const std::string& fp = "abc") { + PhaseInput in; + for (const auto& t : toks) { + RequestTiming r; + r.output = t; + in.requests.push_back(r); + } + const json run = phase_report(in); + json rep; + rep["workload"] = { { "fingerprint", fp } }; + rep["categories"] = json::array({ { { "category", "code" }, { "runs", json::array({ run }) } } }); + rep["concurrency"] = json::array({ { { "streams", 2 }, { "runs", json::array({ run }) } } }); + rep["prefill"] = json::array({ { { "requested_tokens", 1024 }, { "runs", json::array({ run }) } } }); + return rep; +} +} /* namespace */ + +TEST(phase_report_keeps_every_requests_tokens) { + const json r = report_with({ { 1, 2, 3 }, { 4 } }); + const json& o = r["categories"][0]["runs"][0]["requests"]["outputs"]; + REQUIRE(o.size() == 2); + CHECK(o[0] == json::array({ 1, 2, 3 })); + CHECK(o[1] == json::array({ 4 })); +} + +TEST(identical_outputs_are_parity) { + json out; + std::string why; + REQUIRE(compare_outputs(report_with({ { 1, 2, 3 }, { 4, 5 } }), report_with({ { 1, 2, 3 }, { 4, 5 } }), &out, &why) == RAD_OK); + CHECK_EQ(out["compared"].get(), (int64_t)6); /* 2 requests in each of 3 points */ + CHECK_EQ(out["identical"].get(), (int64_t)6); + CHECK(out["differing"].empty()); + CHECK_EQ(out["verdict"].get(), std::string("identical")); +} + +TEST(a_difference_names_the_first_token_that_differs) { + json out; + std::string why; + REQUIRE(compare_outputs(report_with({ { 1, 2, 3 }, { 4, 5, 6, 7 } }), report_with({ { 1, 2, 3 }, { 4, 5, 9 } }), &out, &why) == RAD_OK); + CHECK_EQ(out["identical"].get(), (int64_t)3); + REQUIRE(out["differing"].size() == 3); + const json& d = out["differing"][0]; + CHECK_EQ(d["point"].get(), std::string("categories code")); + CHECK_EQ(d["request"].get(), (int64_t)2); + CHECK_EQ(d["first_different_token"].get(), (int64_t)2); + CHECK_EQ(d["tokens"].get(), (int64_t)4); + CHECK_EQ(d["tokens_baseline"].get(), (int64_t)3); + CHECK_EQ(out["verdict"].get(), std::string("DIFFERS")); + /* A request that stopped early is a difference at the shorter one's end. */ + REQUIRE(compare_outputs(report_with({ { 1, 2 } }), report_with({ { 1, 2, 3 } }), &out, &why) == RAD_OK); + CHECK_EQ(out["differing"][0]["first_different_token"].get(), (int64_t)2); +} + +TEST(points_only_one_side_ran_are_missing_not_counted) { + json a = report_with({ { 1 } }); + json b = report_with({ { 1 } }); + b["prefill"][0]["requested_tokens"] = 65536; /* the baseline ran another length */ + json out; + std::string why; + REQUIRE(compare_outputs(a, b, &out, &why) == RAD_OK); + CHECK_EQ(out["compared"].get(), (int64_t)2); + CHECK_EQ(out["identical"].get(), (int64_t)2); + CHECK_EQ(out["missing"].size(), (size_t)2); + CHECK_EQ(out["verdict"].get(), std::string("identical where both ran; points missing")); +} + +TEST(different_workloads_are_not_compared) { + json out; + std::string why; + CHECK_EQ(compare_outputs(report_with({ { 1 } }, "abc"), report_with({ { 1 } }, "def"), &out, &why), RAD_E_INVAL); + CHECK(why.find("different workloads") != std::string::npos); + CHECK_EQ(compare_outputs(report_with({ { 1 } }, ""), report_with({ { 1 } }, ""), &out, &why), RAD_E_INVAL); +} + +TEST(fingerprint_is_stable_and_sensitive) { + const json a = { { "tokens", 256 }, { "runs", 3 } }; + const json b = { { "tokens", 257 }, { "runs", 3 } }; + CHECK_EQ(workload_fingerprint(a), workload_fingerprint(json::parse(a.dump()))); + CHECK(workload_fingerprint(a) != workload_fingerprint(b)); + CHECK_EQ(workload_fingerprint(a).size(), (size_t)16); +} + +namespace { +/* A report whose one category ran two runs, each proposing `n` drafts and taking `k`, with + * position 1 reached `n` times and taken `k1` times. Outputs identical, so only acceptance moves. */ +json acceptance_report(int64_t n, int64_t k, int64_t k1) { + std::vector runs; + for (int r = 0; r < 2; ++r) { + PhaseInput in; + in.after.draft_tokens = n; + in.after.draft_accepted = k; + in.after.draft_depth_seen = 1; + in.after.draft_pos_reached[0] = n; + in.after.draft_pos_accepted[0] = k1; + RequestTiming t; + t.output = { 7, 8 }; + in.requests.push_back(t); + runs.push_back(phase_report(in)); + } + json rep; + rep["workload"] = { { "fingerprint", "f" } }; + rep["categories"] = json::array({ { { "category", "code" }, { "runs", runs }, + { "summary", summarize_runs(runs) }, + { "draft_by_position", pool_draft_positions(runs) } } }); + return rep; +} +} /* namespace */ + +TEST(draft_positions_pool_counts_not_rates) { + std::vector runs(2); + runs[0]["counters"]["draft_by_position"] = json::array({ { { "position", 1 }, { "reached", 10 }, { "accepted_n", 9 } }, + { { "position", 2 }, { "reached", 9 }, { "accepted_n", 3 } } }); + runs[1]["counters"]["draft_by_position"] = json::array({ { { "position", 1 }, { "reached", 90 }, { "accepted_n", 45 } } }); + const json p = pool_draft_positions(runs); + REQUIRE(p.size() == 2); + CHECK_EQ(p[0]["reached"].get(), (int64_t)100); + CHECK(near(p[0]["accepted"].get(), 0.54)); /* 54 of 100, not the mean of 0.9 and 0.5 */ + CHECK(near(p[1]["accepted"].get(), 1.0 / 3.0)); + CHECK(pool_draft_positions({}).empty()); +} + +TEST(an_acceptance_drop_fails_the_comparison) { + json out; + std::string why; + /* 2 x 1000 drafts, 70% taken in the baseline. */ + REQUIRE(compare_outputs(acceptance_report(1000, 700, 800), acceptance_report(1000, 700, 800), &out, &why) == RAD_OK); + CHECK_EQ(out["verdict"].get(), std::string("identical")); + CHECK_EQ(out["acceptance_verdict"].get(), std::string("no drop")); + CHECK(near(out["acceptance"][0]["z"].get(), 0.0)); + + /* 70% -> 60% over 2000 drafts each: z is about -4.7. */ + REQUIRE(compare_outputs(acceptance_report(1000, 600, 800), acceptance_report(1000, 700, 800), &out, &why) == RAD_OK); + CHECK_EQ(out["acceptance_verdict"].get(), std::string("DROPPED")); + REQUIRE(out["acceptance_dropped"].size() == 1); + CHECK_EQ(out["acceptance_dropped"][0]["what"].get(), std::string("overall")); + CHECK(out["acceptance_dropped"][0]["z"].get() < -4.0); + + /* A collapse at one position alone is caught there. */ + REQUIRE(compare_outputs(acceptance_report(1000, 700, 500), acceptance_report(1000, 700, 800), &out, &why) == RAD_OK); + REQUIRE(out["acceptance_dropped"].size() == 1); + CHECK_EQ(out["acceptance_dropped"][0]["what"].get(), std::string("position 1")); + + /* 70% -> 69%: within noise at this many drafts (z about -0.5), not a drop. */ + REQUIRE(compare_outputs(acceptance_report(1000, 690, 800), acceptance_report(1000, 700, 800), &out, &why) == RAD_OK); + CHECK_EQ(out["acceptance_verdict"].get(), std::string("no drop")); + + /* A rise is never a drop. */ + REQUIRE(compare_outputs(acceptance_report(1000, 800, 900), acceptance_report(1000, 700, 800), &out, &why) == RAD_OK); + CHECK_EQ(out["acceptance_verdict"].get(), std::string("no drop")); + + const std::string md = render_markdown([&] { + json r = acceptance_report(1000, 600, 800); + compare_outputs(r, acceptance_report(1000, 700, 800), &out, &why); + r["parity"] = out; + return r; + }()); + CHECK(md.find("**DROPPED**") != std::string::npos); +} + +namespace { +/* A report whose one concurrency point ran `rates.size()` runs of one request each, request i + * proposing `n` drafts and taking `rates[i]` of them, position 1 counted the same way. */ +json request_report(const std::vector& rates, int64_t n) { + std::vector runs; + for (double rate : rates) { + PhaseInput in; + const int64_t k = (int64_t)std::llround(rate * (double)n); + in.after.draft_tokens = n; + in.after.draft_accepted = k; + in.after.draft_depth_seen = 1; + in.after.draft_pos_reached[0] = n; + in.after.draft_pos_accepted[0] = k; + RequestTiming t; + t.output = { 1 }; + t.drafted = n; + t.accepted = k; + in.requests.push_back(t); + runs.push_back(phase_report(in)); + } + json rep; + rep["workload"] = { { "fingerprint", "f" } }; + rep["concurrency"] = json::array({ { { "streams", 8 }, { "runs", runs }, + { "draft_by_position", pool_draft_positions(runs) } } }); + return rep; +} +} /* namespace */ + +TEST(phase_report_keeps_every_requests_drafts) { + PhaseInput in; + RequestTiming t; + t.drafted = 30; + t.accepted = 21; + in.requests.push_back(t); + const json d = phase_report(in)["requests"]["drafts"]; + REQUIRE(d.size() == 1); + CHECK(d[0] == json::array({ 30, 21 })); +} + +TEST(texts_that_diverged_are_not_a_drop) { + /* Two runs of one build whose texts went different ways: every request's rate moves, by as + * much up as down, over 2000 drafts a request. Pooled as coin flips, 0.79 against 0.80 over + * 48000 drafts is z of about -3.8 -- a drop, which is the false alarm two runs of one build + * raised on epyc; tested on the requests, t is about -0.5. */ + std::vector base, now; + for (int i = 0; i < 24; ++i) { + base.push_back(0.80); + now.push_back(0.80 + ((i % 2) ? 0.08 : -0.10)); + } + json out; + std::string why; + REQUIRE(compare_outputs(request_report(now, 2000), request_report(base, 2000), &out, &why) == RAD_OK); + CHECK_EQ(out["acceptance_verdict"].get(), std::string("no drop")); + const json& overall = out["acceptance"][0]; + CHECK_EQ(overall["test"].get(), std::string("paired t over requests")); + CHECK_EQ(overall["requests"].get(), (int64_t)24); + /* The positions take the requests' dispersion: far above 1 here, so their z shrinks with it. */ + const json& pos = out["acceptance"][1]; + CHECK(pos["dispersion"].get() > 10.0); + CHECK(pos["z"].get() > -3.0); +} + +TEST(a_drop_in_every_request_is_a_drop) { + /* Four requests, each 0.10 lower, give or take 0.02: t of about -12 on 3 degrees of freedom, + * p between 0.0005 and 0.001. */ + json out; + std::string why; + REQUIRE(compare_outputs(request_report({ 0.68, 0.72, 0.70, 0.70 }, 1000), request_report({ 0.80, 0.80, 0.80, 0.80 }, 1000), + &out, &why) == RAD_OK); + CHECK_EQ(out["acceptance_verdict"].get(), std::string("DROPPED")); + const json& overall = out["acceptance"][0]; + CHECK(near(overall["t"].get(), -12.247, 0.01)); + CHECK(overall["p"].get() < 0.001); + CHECK(overall["p"].get() > 0.0005); +} + +TEST(identical_requests_test_to_zero) { + json out; + std::string why; + REQUIRE(compare_outputs(request_report({ 0.7, 0.8, 0.9 }, 500), request_report({ 0.7, 0.8, 0.9 }, 500), &out, &why) == RAD_OK); + CHECK_EQ(out["acceptance_verdict"].get(), std::string("no drop")); + CHECK(near(out["acceptance"][0]["t"].get(), 0.0)); + CHECK(near(out["acceptance"][0]["p"].get(), 0.5)); + CHECK(near(out["acceptance"][1]["dispersion"].get(), 1.0)); +} + +TEST(parity_renders_with_its_differences) { + json rep = report_with({ { 1, 2, 3 } }); + json cmp; + std::string why; + REQUIRE(compare_outputs(rep, report_with({ { 1, 9, 3 } }), &cmp, &why) == RAD_OK); + cmp["baseline"] = "base.json"; + rep["parity"] = cmp; + const std::string md = render_markdown(rep); + CHECK(md.find("## Parity against base.json") != std::string::npos); + CHECK(md.find("**DIFFERS**: 0 of 3 requests") != std::string::npos); + CHECK(md.find("| categories code | 1 | 1 | 0 | 1 | 3 / 3 |") != std::string::npos); +} + +/* ------------------------------------------------------------------ report */ + +TEST(markdown_renders_the_sweeps_from_json_alone) { + const int64_t ms = 1'000'000; + PhaseInput in; + in.kind = PhaseKind::Decode; + for (int i = 0; i < 4; ++i) in.steps.push_back(step(i, RAD_PHASE_DECODE, 1, 0, 1, 12.5, (i + 1) * 13 * ms)); + const json run = phase_report(in); + PhaseInput in2 = in; + for (int i = 0; i < 4; ++i) in2.steps[(size_t)i].end_ns = (i + 1) * 20 * ms; /* a second run, slower */ + const json run2 = phase_report(in2); + + json rep; + rep["engine"] = { { "arch", "test" }, { "quant", "fp8" }, { "tp", 2 }, { "backend", "host" }, + { "plan", "dynamic placement" } }; + rep["workload"] = { { "description", "fixed" } }; + rep["verdict"] = "valid"; + rep["warnings"] = json::array({ "a warning" }); + rep["categories"] = json::array({ { { "category", "code" }, { "requests", 1 }, { "stopped_on_eos", 1 }, + { "summary", summarize_runs({ run }) } } }); + rep["concurrency"] = json::array({ { { "streams", 8 }, { "summary", summarize_runs({ run, run2 }) } } }); + rep["prefill"] = json::array({ { { "prompt_tokens", 4096 }, { "summary", summarize_runs({ run }) } } }); + rep["interference"] = { { "streams", 4 }, { "prompt_tokens", 4096 }, { "idle_ttft_ms", 300.0 }, + { "summary", summarize_paths({ json{ { "arrival_ttft_ms", 450.0 } } }, + { "/arrival_ttft_ms", "/interference/stall_ratio" }) } }; + rep["not_measured"] = json::array({ "per-kernel time" }); + + const std::string md = render_markdown(rep); + CHECK(md.find("# Diagnosis") == 0); + CHECK(md.find("Model `test` (fp8)") != std::string::npos); + CHECK(md.find("TP 2") != std::string::npos); + CHECK(md.find("**Verdict: valid**") != std::string::npos); + CHECK(md.find("- a warning") != std::string::npos); + CHECK(md.find("| code | 1 |") != std::string::npos); + CHECK(md.find("| 1 of 1 |") != std::string::npos); + CHECK(md.find("| 8 | 2 |") != std::string::npos); + CHECK(md.find("| 13 (13–20) |") != std::string::npos); /* emission p50: 13 ms and 20 ms runs */ + CHECK(md.find("| 4096 | 1 |") != std::string::npos); + CHECK(md.find("| TTFT of the arriving prompt | 450 ms |") != std::string::npos); + CHECK(md.find("| Stall ratio (longest / typical) | – |") != std::string::npos); + CHECK(md.find("## Not measured") != std::string::npos); + CHECK(md.find("## Parity") == std::string::npos); /* no baseline given */ + + /* And the same text from a report that went through a file. */ + CHECK(render_markdown(json::parse(rep.dump())) == md); +} + +/* The report's environment section: the knobs by name, from a fixed list, and never a value -- + * the report is pasted into issues and committed beside a baseline. */ +TEST(environment_is_a_fixed_name_list) { + char tp[] = "RADIANCE_LOG_STEPS=1"; + char omp[] = "OMP_NUM_THREADS=4"; + char wait[] = "OMP_WAIT_POLICY=passive"; + char suffix[] = "RADIANCE_API_KEY_SYNTHETIC_SECRET_IN_NAME=x"; + char key[] = "MY_API_KEY=sk-very-secret-value"; + char home[] = "HOME=/root"; + char radfake[] = "RADIATOR=not a prefix of RAD_ with a name"; + char vram[] = "RADIANCE_HOST_VRAM_MIB=512"; + char* env[] = { tp, omp, wait, suffix, key, home, radfake, vram, nullptr }; + + const std::vector v = diag::env_allowlist(env); + CHECK_EQ(v.size(), (size_t)4); + CHECK(std::find(v.begin(), v.end(), "RADIANCE_LOG_STEPS") != v.end()); + CHECK(std::find(v.begin(), v.end(), "OMP_NUM_THREADS") != v.end()); + CHECK(std::find(v.begin(), v.end(), "OMP_WAIT_POLICY") != v.end()); + CHECK(std::find(v.begin(), v.end(), "RADIANCE_HOST_VRAM_MIB") != v.end()); + /* A suffix on an allowed name is not an allowed name: a prefix list would print this one. */ + for (const std::string& n : v) { + CHECK(n.find('=') == std::string::npos); /* names, never values */ + CHECK(n.find("SECRET") == std::string::npos); + CHECK(n.find("API_KEY") == std::string::npos); + CHECK(n.find("RADIATOR") == std::string::npos); + } + CHECK(std::is_sorted(v.begin(), v.end())); + /* An empty environment is an empty section, not a fabricated one. */ + char* none[] = { nullptr }; + CHECK(diag::env_allowlist(none).empty()); +} + +/* The engine section names the model and the cards, never where they live: /server_info carries the + * model's path in `container` and the control vector's file. Neither reaches the report. */ +TEST(the_engine_section_carries_no_path) { + const json info = { { "arch", "llama" }, + { "quant", "fp8" }, + { "n_layers", 32 }, + { "n_embd", 4096 }, + { "n_vocab", 128256 }, + { "n_ctx_train", 8192 }, + { "container", "/home/alice/MARKER-private/llama.rad" }, + { "control_vector", { { "file", "/home/alice/MARKER-private/cvec.bin" } } }, + { "devices", json::array({ json{ { "rank", 0 }, { "name", "card" } } }) } }; + const json e = engine_report(info); + CHECK_EQ(e["arch"].get(), std::string("llama")); + CHECK_EQ(e["quant"].get(), std::string("fp8")); + CHECK_EQ(e["n_layers"].get(), (int64_t)32); + CHECK_EQ(e["devices"].size(), (size_t)1); + CHECK(!e.contains("container")); + CHECK(!e.contains("control_vector")); + CHECK(e.dump().find("MARKER") == std::string::npos); + /* Not an object (a failed engine_info parse) is an empty section, not a crash. */ + CHECK(engine_report(json::object()).empty()); + CHECK(engine_report(json()).empty()); +} + +/* ---- reproducibility ---- */ + +TEST(runs_carry_their_spread_against_the_median) { + std::vector runs; + for (double v : { 30.0, 10.0, 20.0 }) { + json r; + r["requests"]["aggregate_tok_s"] = v; + runs.push_back(r); + } + runs[1]["requests"]["ttft_ms"]["p50"] = 5.0; /* one run only: no spread */ + const json s = summarize_runs(runs); + CHECK(near(s["requests.aggregate_tok_s"]["spread_pct"].get(), 100.0)); /* (30-10)/20 */ + CHECK(s["requests.ttft_ms.p50"]["spread_pct"].is_null()); +} + +namespace { +json summary_with(double median, double min, double max, int64_t runs = 5) { + const json m = { { "median", median }, { "min", min }, { "max", max }, + { "spread_pct", (max - min) / median * 100.0 } }; + return { { "runs", runs }, { "requests.aggregate_tok_s", m }, { "counters.ms_per_decode_step", m } }; +} +} /* namespace */ + +TEST(stability_names_the_numbers_whose_runs_disagree) { + json rep; + auto prompt = [](int k, const json& sum) { return json{ { "prompt", k }, { "summary", sum } }; }; + /* code's pooled summary spreads 40%: its two prompts differ, which is not instability. */ + rep["categories"] = json::array( + { { { "category", "code" }, { "summary", summary_with(100, 80, 120) }, + { "prompts_summary", json::array({ prompt(1, summary_with(100, 96, 104)), prompt(2, summary_with(120, 120, 120)) }) } }, + { { "category", "prose" }, { "summary", summary_with(100, 99, 101) }, + { "prompts_summary", json::array({ prompt(1, summary_with(100, 99, 101)) }) } } }); + rep["concurrency"] = json::array({ { { "streams", 4 }, { "summary", summary_with(100, 100, 100) } } }); + const json s = stability_report(rep); + CHECK_EQ(s["verdict"].get(), std::string("UNSTABLE")); + CHECK_EQ(s["judged"].get(), (int64_t)4); /* three prompts and one point, by step time */ + REQUIRE(s["unstable"].size() == 1); /* code #1's step time spreads 8% */ + CHECK_EQ(s["unstable"][0]["metric"].get(), std::string("counters.ms_per_decode_step")); + CHECK_EQ(s["unstable"][0]["point"].get(), std::string("categories code #1")); + CHECK(near(s["unstable"][0]["spread_pct"].get(), 8.0)); + + rep["categories"].erase((size_t)0); + CHECK_EQ(stability_report(rep)["verdict"].get(), std::string("stable")); + CHECK_EQ(stability_report(rep, 0.5)["verdict"].get(), std::string("UNSTABLE")); /* prose: 2% */ + CHECK_EQ(stability_report(json::object())["verdict"].get(), std::string("not judged")); +} + +namespace { +diag::Facts two_cards() { + diag::Facts f; + f.host.cpu_model = "AMD Ryzen 9 9950X"; + f.host.cpu_governor = "powersave"; + f.host.cpu_epp = "performance"; + f.host.kernel = "6.18.0"; + f.host.cmdline = "root=/home/someone/secret iommu=pt"; + diag::CardFacts a; + a.bdf = "0000:03:00.0"; + a.rank = 0; + a.name = "AMD Radeon AI PRO R9700"; + a.gfx = "gfx1201"; + a.sclk = "500-2350 MHz"; + a.power_cap_uw = 250000000; + a.power_cap_default_uw = 300000000; + diag::CardFacts igpu; + igpu.bdf = "0000:7c:00.0"; + igpu.gfx = "gfx1036"; + f.cards = { igpu, a }; + return f; +} +} /* namespace */ + +TEST(conditions_carry_the_serving_cards_and_no_path) { + diag::RunFacts r; + r.version = "1.2.3"; + diag::Finding x; + x.level = diag::Finding::Warn; + x.id = "power-cap-below-default"; + x.what = "cap 250 W"; + const json c = conditions_report(two_cards(), r, { x }); + REQUIRE(c["cards"].size() == 1); /* the unserved iGPU is not a condition of the run */ + CHECK_EQ(c["cards"][0]["gfx"].get(), std::string("gfx1201")); + CHECK(near(c["cards"][0]["power_cap_w"].get(), 250.0)); + CHECK(near(c["cards"][0]["power_cap_default_w"].get(), 300.0)); + CHECK_EQ(c["host"]["cpu_governor"].get(), std::string("powersave")); + CHECK(c["host"]["cpu_driver"].is_null()); + CHECK_EQ(c["findings"][0]["id"].get(), std::string("power-cap-below-default")); + CHECK_EQ(c["fingerprint"].get().size(), (size_t)16); + CHECK(c.dump().find("/home") == std::string::npos); /* the command line is not carried */ +} + +TEST(conditions_differences_name_the_field_and_ignore_findings) { + diag::RunFacts r; + const json a = conditions_report(two_cards(), r, {}); + CHECK(conditions_differences(a, a).empty()); + + diag::Facts g = two_cards(); + g.host.cpu_governor = "performance"; + g.cards[1].power_cap_uw = 300000000; + diag::Finding x; + x.id = "link-below-max"; + const json b = conditions_report(g, r, { x }); + CHECK(a["fingerprint"] != b["fingerprint"]); + const json d = conditions_differences(b, a); + REQUIRE(d.size() == 2); /* the governor and the cap; not the findings, not the fingerprint */ + CHECK_EQ(d[0]["field"].get(), std::string("/host/cpu_governor")); + CHECK_EQ(d[0]["now"].get(), std::string("performance")); + CHECK_EQ(d[0]["baseline"].get(), std::string("powersave")); + CHECK_EQ(d[1]["field"].get(), std::string("/cards/0/power_cap_w")); + + /* The findings alone do not change the fingerprint: their text is read under load. */ + CHECK(conditions_report(two_cards(), r, { x })["fingerprint"] == a["fingerprint"]); +} + +namespace { +json run_on(double start_c, double end_c, const char* level) { + json card = { { "bdf", "0000:03:00.0" }, { "junction_c", start_c }, { "edge_c", start_c - 10 }, + { "perf_level", level } }; + json done = card; + done["junction_c"] = end_c; + return { { "cards", { { "start", json::array({ card }) }, { "end", json::array({ done }) } } } }; +} +} /* namespace */ + +TEST(thermal_report_flags_runs_started_in_different_states) { + json rep; + rep["categories"] = json::array({ { { "category", "code" }, + { "runs", json::array({ run_on(41, 70, "auto"), run_on(44, 72, "auto") }) } } }); + rep["interference"] = { { "runs", json::array({ { { "phase", run_on(43, 71, "auto") } } }) } }; + json t = thermal_report(rep); + REQUIRE(t["cards"].size() == 1); + CHECK_EQ(t["cards"][0]["runs"].get(), (int64_t)3); + CHECK(near(t["cards"][0]["start_c"]["min"].get(), 41.0)); + CHECK(near(t["cards"][0]["start_c"]["max"].get(), 44.0)); + CHECK(near(t["cards"][0]["end_c"]["max"].get(), 72.0)); + CHECK(t["warnings"].empty()); + + rep["prefill"] = json::array({ { { "requested_tokens", 1024 }, { "runs", json::array({ run_on(58, 80, "high") }) } } }); + t = thermal_report(rep); + REQUIRE(t["warnings"].size() == 2); /* 41..58 C at the start, and auto then high */ + CHECK(t["warnings"][0].get().find("between 41 and 58 C") != std::string::npos); + CHECK(t["warnings"][1].get().find("auto, high") != std::string::npos); + + CHECK(thermal_report(json::object())["cards"].empty()); /* a host run samples nothing */ +} + +TEST(parity_says_whether_the_conditions_matched) { + json a = report_with({ { 1, 2 } }), b = report_with({ { 1, 2 } }); + json out; + std::string why; + REQUIRE(compare_outputs(a, b, &out, &why) == RAD_OK); + CHECK(out["conditions"].is_string()); /* neither side recorded them */ + + diag::RunFacts r; + diag::Facts g = two_cards(); + a["conditions"] = conditions_report(two_cards(), r, {}); + g.host.kernel = "6.19.0"; + b["conditions"] = conditions_report(g, r, {}); + REQUIRE(compare_outputs(a, b, &out, &why) == RAD_OK); + CHECK_EQ(out["verdict"].get(), std::string("identical")); /* tokens do not depend on it */ + REQUIRE(out["conditions"].size() == 1); + CHECK_EQ(out["conditions"][0]["field"].get(), std::string("/host/kernel")); +} + +TEST(markdown_renders_the_reproducibility_section) { + json rep; + rep["verdict"] = "valid"; + rep["categories"] = json::array({ { { "category", "code" }, { "summary", summary_with(100, 90, 110) }, + { "prompts_summary", json::array({ { { "prompt", 1 }, + { "summary", summary_with(100, 90, 110) } } }) } } }); + rep["stability"] = stability_report(rep); + diag::RunFacts r; + r.version = "1.2.3"; + rep["conditions"] = conditions_report(two_cards(), r, {}); + rep["thermal"] = thermal_report(json::object()); + rep["reproducibility"] = json::array({ "a note" }); + const std::string m = render_markdown(rep); + CHECK(m.find("**Run-to-run: UNSTABLE**") != std::string::npos); + CHECK(m.find("## Reproducibility") != std::string::npos); + CHECK(m.find("| categories code #1 | counters.ms_per_decode_step | 20%") != std::string::npos); + CHECK(m.find("CPU governor powersave (energy preference performance)") != std::string::npos); + CHECK(m.find("250 W (300 W)") != std::string::npos); + CHECK(m.find("- a note") != std::string::npos); +} + +RAD_TEST_MAIN() diff --git a/tests/engine_e2e_test.cpp b/tests/engine_e2e_test.cpp index 7268c0ae..42a56a9f 100644 --- a/tests/engine_e2e_test.cpp +++ b/tests/engine_e2e_test.cpp @@ -714,6 +714,128 @@ TEST(qwen35_preemption_by_recompute_changes_no_logit) { CHECK(n > 0); } +/* The diagnose mode end to end: the real binary starts as a serve would, runs its own workload + * through the scheduler, and writes a report whose sections are the ones the report format + * declares. Its arithmetic is tests/diagnose_test.cpp's; this is that the driver runs at all, that + * every prompt was salted and the cache emptied (no request reports a cached token), and that a + * second run on the same build reproduces every request's tokens, which is what --diagnose-baseline + * compares. The numbers themselves are a card's measurement, not this test's. + * + * The model, the corpus and the baseline all live under a directory named after a marker: the + * report is pasted into issues, so no path of the machine may reach it, and a variable whose name + * is an allowed prefix plus a secret suffix must not be reported at all. */ +TEST(the_diagnose_mode_measures_itself_and_reproduces_its_tokens) { + World& w = world(); + tiny::TempDir d("diagnose"); + REQUIRE(d.ok()); + const std::string private_dir = d / "MARKER-private-home"; + REQUIRE_EQ(mkdir(private_dir.c_str(), 0755), 0); + const std::string model = private_dir + "/model.rad"; + REQUIRE_EQ(symlink(w.llama_rad.c_str(), model.c_str()), 0); + const std::string corpus = private_dir + "/corpus.jsonl"; + std::string body; + for (int i = 0; i < 3; ++i) { + tiny::Rng r(40 + i); + body += json{ { "category", "prose" }, { "prompt", words(r, 120) }, { "max_tokens", 8 } } + .dump() + "\n"; + } + REQUIRE(tiny::write_text(corpus, body)); + /* One point of each sweep, one measured run: the driver's whole shape, quickly. */ + const std::vector shared = { + "--diagnose-corpus", corpus, "--diagnose-tokens", "8", "--diagnose-runs", "1", + "--diagnose-concurrency", "1", "--diagnose-prefill", "512", + "--max-model-len", "1024", "--max-num-seqs", "2", "--max-num-batched-tokens", "256" }; + std::vector a = { "--diagnose", d / "first" }; + a.insert(a.end(), shared.begin(), shared.end()); + const Ran r = radiance(model, a, { "RADIANCE_API_KEY_SYNTHETIC_SECRET_IN_NAME=x" }, 600); + REQUIRE_RAN(r); + + std::string text; + { + const std::string path = d.path + "/first/diagnose.json"; + FILE* f = std::fopen(path.c_str(), "rb"); + REQUIRE(f != nullptr); + char buf[4096]; + for (size_t n; (n = std::fread(buf, 1, sizeof buf, f)) > 0;) text.append(buf, n); + std::fclose(f); + } + const json rep = json::parse(text, nullptr, false); + REQUIRE(rep.is_object()); + for (const char* k : { "engine", "workload", "categories", "concurrency", "prefill", + "interference", "environment", "not_measured", "verdict", "problems", + "warnings" }) + CHECK(rep.contains(k)); + CHECK_EQ(rep["verdict"].get(), std::string("valid")); + CHECK_EQ(rep["problems"].size(), (size_t)0); + /* Every point of the workload ran: three prose prompts once each, one stream, one 512-token + * prefill, and a prompt arriving into a running stream. A point the engine could not run is + * named in the report, never left as a zero. */ + REQUIRE_EQ(rep["categories"].size(), (size_t)1); + const json& cat = rep["categories"][0]; + CHECK_EQ(cat["prompts"].get(), (int64_t)3); + CHECK_EQ(cat["runs"].size(), (size_t)3); + CHECK_EQ(rep["concurrency"].size(), (size_t)1); + CHECK_EQ(rep["concurrency"][0]["streams"].get(), (int64_t)1); + REQUIRE_EQ(rep["prefill"].size(), (size_t)1); + CHECK_EQ(rep["prefill"][0]["prompt_tokens"].get(), (int64_t)512); + CHECK(rep["interference"]["runs"][0]["arrival_ttft_ms"].get() > 0); + CHECK(rep["interference"]["runs"][0]["interference"]["stall_ratio"].get() > 0); + + /* Salted and uncached, and the step ring lost nothing: the workload's own statement of its + * validity, checked afterwards from what each run recorded. */ + int64_t cached = 0, lost = 0; + for (const json& run : cat["runs"]) { + cached += run["requests"]["cached_prompt_tokens"].get(); + lost += run["steps"]["lost"].get(); + CHECK(run["steps"]["recorded"].get() > 0); + CHECK(run["requests"]["outputs"][0].size() > 0); + } + CHECK_EQ(cached, (int64_t)0); + CHECK_EQ(lost, (int64_t)0); + /* What the run was taken under, and whether its runs agree. The verdict itself is not held + * here: these are a CI host's timings. */ + REQUIRE(rep.contains("conditions")); + CHECK_EQ(rep["conditions"]["fingerprint"].get().size(), (size_t)16); + CHECK(rep["conditions"]["cards"].empty()); /* the host backend serves no card */ + CHECK(rep["stability"].contains("verdict")); + CHECK_EQ(cat["prompts_summary"].size(), (size_t)3); + CHECK(rep["thermal"]["cards"].empty()); + CHECK(rep["reproducibility"].is_array()); + /* Names, not values: the report is pasted into issues. */ + for (const json& n : rep["environment"]["variables"]) + CHECK(n.get().find('=') == std::string::npos); + /* No path and no secret-suffixed name in either artifact of either run. */ + for (const char* marker : { "MARKER", "SYNTHETIC_SECRET" }) { + CHECK(text.find(marker) == std::string::npos); + CHECK(tiny::read_text(d.path + "/first/diagnose.md").find(marker) == std::string::npos); + } + + /* The same build, the same workload: identical tokens, which is what the baseline compares. */ + const std::string baseline = private_dir + "/baseline.json"; + REQUIRE(tiny::write_text(baseline, text)); + std::vector b = { "--diagnose", d / "second", "--diagnose-baseline", baseline }; + b.insert(b.end(), shared.begin(), shared.end()); + const Ran r2 = radiance(model, b, {}, 600); + REQUIRE_RAN(r2); + const std::string json2 = tiny::read_text(d.path + "/second/diagnose.json"); + const std::string md = tiny::read_text(d.path + "/second/diagnose.md"); + CHECK(md.find("# Diagnosis") == 0); + CHECK(md.find("**Verdict: valid**") != std::string::npos); + CHECK(md.find("## Parity") != std::string::npos); + CHECK(md.find("## Reproducibility") != std::string::npos); + { + /* Two runs on one machine, one after the other: the same conditions. */ + const json rep2 = json::parse(json2, nullptr, false); + REQUIRE(rep2.is_object()); + CHECK(rep2["parity"]["conditions"].is_array()); + CHECK(rep2["parity"]["conditions"].empty()); + } + for (const char* marker : { "MARKER", "SYNTHETIC_SECRET" }) { + CHECK(json2.find(marker) == std::string::npos); + CHECK(md.find(marker) == std::string::npos); + } +} + /* A document longer than the whole KV pool could never be admitted: admission takes only a chunk * the pool can hold, so it would wait at the head of the queue forever. The run is refused before * anything is scored, naming the document's length and the pool's. Bounded by a timeout, so the diff --git a/tests/fleet_config_test.cpp b/tests/fleet_config_test.cpp index fa8daf31..55320e0e 100644 --- a/tests/fleet_config_test.cpp +++ b/tests/fleet_config_test.cpp @@ -95,6 +95,25 @@ TEST(structured_values_are_spelled_for_their_flag) { CHECK(c.sample_temp > 0.69f && c.sample_temp < 0.71f); } +/* The diagnose mode is a model key like the KL mode's: the entry's Config is what main() tests to + * run it offline, and a sequence spells the sweeps' lists. */ +TEST(the_diagnose_keys_are_model_keys) { + fleet::FleetConfig fc; + CHECK_EQ(yload("models:\n qwen:\n model: /m/q.rad\n diagnose: /out\n diagnose-runs: 5\n" + " diagnose-concurrency: [1, 2]\n diagnose-prefill: [1024, 4096]\n", &fc), RAD_OK); + REQUIRE_EQ(fc.models.size(), 1u); + const Config& c = fc.models[0].cfg; + CHECK(c.diagnose_mode()); + CHECK_EQ(c.diagnose, "/out"); + CHECK_EQ(c.diagnose_runs, 5); + CHECK_EQ(c.diagnose_concurrency.size(), 2u); + CHECK_EQ(c.diagnose_prefill.size(), 2u); + CHECK_EQ(c.given.at("--diagnose"), "models.qwen.diagnose"); + CHECK(refused("models:\n qwen:\n model: /m/q.rad\n diagnose-runs: 5\n diagnose: /out\n" + " kld-ref: /r\n")); + CHECK(refused("models:\n qwen:\n model: /m/q.rad\n diagnose-baseline: /b.json\n")); +} + TEST(model_ids_may_hold_dots) { fleet::FleetConfig fc; CHECK_EQ(yload("models:\n qwen3.8-27b:\n model: /m/q.rad\n tp: 2\n", &fc), RAD_OK); @@ -253,9 +272,16 @@ TEST(scheduler_cards_and_groups) { CHECK_EQ(fc.load_timeout_ms, 90000); CHECK_EQ(fc.drain_timeout_ms, 500); CHECK_EQ(fc.keepalive_ms, 5000); + CHECK_EQ(fc.stuck_exit_ms, 60000); /* a minute unless the file says otherwise */ CHECK(fc.warm_up); /* on unless the file turns it off */ CHECK_EQ(fc.groups.size(), 2u); CHECK(fc.groups[1].kind == fleet::Group::Kind::Exclusive); + fleet::FleetConfig off; + CHECK_EQ(yload("scheduler: {stuck-exit: 0}\nmodels:\n a: {model: /m/a.rad}\n", &off), RAD_OK); + CHECK_EQ(off.stuck_exit_ms, 0); + fleet::FleetConfig slow; + CHECK_EQ(yload("scheduler: {stuck-exit: 5m}\nmodels:\n a: {model: /m/a.rad}\n", &slow), RAD_OK); + CHECK_EQ(slow.stuck_exit_ms, 300000); CHECK_EQ(yload("cards: all\nmodels:\n a: {model: /m/a.rad}\n", &fc), RAD_OK); CHECK(fc.cards.empty()); CHECK_EQ(yload("scheduler: {warm-up: false}\nmodels:\n a: {model: /m/a.rad}\n", &fc), RAD_OK); diff --git a/tests/flint_arch_test.cpp b/tests/flint_arch_test.cpp new file mode 100644 index 00000000..215c3edb --- /dev/null +++ b/tests/flint_arch_test.cpp @@ -0,0 +1,318 @@ +/* Flint's declaration and step (arch/flint), without a GPU or checkpoint: the containers its + * recipes make, both KV caches, one and two ranks. */ +#define RAD_ARCH_NO_EXPORTS 1 +#include "arch_fakes.h" +#include "rad_plugin.h" +#include "../arch/flint/flint.cpp" + +using namespace rad_fake; + +namespace { + +/* Recursive Flint's configuration as rad-convert records it. */ +MetaKV flint_meta() { + RadModelMeta m{}; + m.arch_id = "flint"; + m.name = "test-flint"; + m.quant = ""; + m.n_layers = 49; + m.n_embd = 2048; + m.n_head = 32; + m.n_head_kv = 4; + m.head_dim = 128; + m.n_ff = 6144; + m.n_vocab = 150144; + m.n_ctx_train = 262144; + m.rms_eps = 1e-6f; + m.rope_theta = 10000.0f; + m.n_expert = 256; + m.n_expert_used = 6; + MetaKV k(m); + k.set("sliding_window", "513").set("num_experts", "256").set("num_experts_per_tok", "6") + .set("moe_intermediate_size", "512").set("shared_expert_intermediate_size", "1024") + .set("intermediate_size", "6144"); + return k; +} + +/* IQ8R as libquant states it: int8 codes rotated by fwht128, a u8 scale per [1 x 256] of K under + * a bf16 scale a row. */ +RadEncoding iq8r() { + RadEncoding e = rad_enc_affine(RAD_I8, RAD_U8, 1, 256); + rad_enc_add_plane(&e, "scale.1", RAD_BF16, 1, 0); + rad_enc_copy_str(e.transform, "fwht128"); + return e; +} + +/* Int8 rotated by fwht128 at a bf16 scale a (row, 128 of K): the experts' form. */ +RadEncoding i8h() { + RadEncoding e = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128); + rad_enc_copy_str(e.transform, "fwht128"); + return e; +} + +/* data/recipes/flint-iq8r.recipe's encodings by declared name. The head comes last because + * `output.weight` is in `attn_output.weight`. */ +void iq8r_encs(RadBuilder* b) { + b->encs.clear(); + for (const char* t : { "ffn_gate_up_exps", "ffn_down_exps", "ffn_down_shexp" }) + b->encs.push_back({ t, i8h() }); + for (const char* t : { "attn_q.weight", "attn_k.weight", "attn_v.weight", + "attn_output.weight", "ffn_gate_up.weight", "ffn_down.weight", + "ffn_gate_up_shexp" }) + b->encs.push_back({ t, iq8r() }); + b->encs.push_back({ "output.weight", rad_enc_affine(RAD_I8, RAD_BF16, 1, 128) }); +} + +/* data/recipes/flint-bf16-q4.recipe's: u4 attention under an f16 scale and a u8 zero a 128, + * plain int8 dense and shared linears and head, signed int4 experts. */ +void q4_encs(RadBuilder* b) { + RadEncoding u4 = rad_enc_affine(RAD_U4, RAD_F16, 1, 128); + rad_enc_add_plane(&u4, "zero", RAD_U8, 1, 128); + const RadEncoding w8 = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128); + const RadEncoding i4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128); + b->encs.clear(); + b->encs.push_back({ "ffn_gate_up_exps", i4 }); + b->encs.push_back({ "ffn_down_exps", i4 }); + for (const char* t : { "attn_q.weight", "attn_k.weight", "attn_v.weight", + "attn_output.weight" }) + b->encs.push_back({ t, u4 }); + for (const char* t : { "ffn_gate_up_shexp", "ffn_down_shexp", "ffn_gate_up.weight", + "ffn_down.weight", "output.weight" }) + b->encs.push_back({ t, w8 }); +} + +bool is_full(int l) { return l == 0 || l == 1 || l == 48 || (l >= 5 && l <= 45 && (l - 5) % 4 == 0); } + +/* Decode, a fused-prologue prefill and one past the fused band, each lint clean. */ +void steps_lint_clean(RadBuilder& b, int rank, int world) { + RadBatch d = decode_batch(); + RadCtx c1{.b = &b, .batch = &d, .rank = rank, .world = world}; + flint::step(&c1, &d); + CHECK_LINT(b, &c1); + CHECK(c1.step_fail.empty()); + RadBatch p = prefill_batch(); + RadCtx c2{.b = &b, .batch = &p, .rank = rank, .world = world}; + flint::step(&c2, &p); + CHECK_LINT(b, &c2); + CHECK(c2.step_fail.empty()); + RadBatch w = prefill_batch(); + w.n_tok = 200; + w.max_q_len = 100; + RadCtx c3{.b = &b, .batch = &w, .rank = rank, .world = world}; + flint::step(&c3, &w); + CHECK_LINT(b, &c3); + CHECK(c3.step_fail.empty()); +} + +} /* namespace */ + +/* The attention of every layer: the sink op, the 513 window on the sliding layers, and the fused + * prologue with the rotary on the sliding layers and none (`rotary_dim` 0) on the full ones, on + * the bf16 and the int8 cache; the two KV groups take the cache's dtype. */ +TEST(attention_takes_the_sink_window_and_nope_prologue_on_both_caches) { + for (const bool i8 : { false, true }) { + MetaKV mk = flint_meta(); + RadBuilder b; + iq8r_encs(&b); + RadBuildCtx ctx = build_ctx(); + if (i8) ctx.kv_dtype = RAD_I8; + REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK); + const char* kvn = i8 ? "i8" : "bf16"; + REQUIRE_EQ(b.kv_groups.size(), (size_t)2); + for (const auto& g : b.kv_groups) CHECK_EQ(g.d.dtype, (uint32_t)(i8 ? RAD_I8 : RAD_BF16)); + REQUIRE_EQ(count_op(b, "attn_paged_sink"), 49); + REQUIRE_EQ(count_op(b, "qkv_norm_rope_kv_store"), 49); + CHECK_EQ(count_op(b, "attn_paged"), 0); + CHECK_EQ(count_op(b, "rope"), 2 * 35); + for (int l = 0; l < 49; ++l) { + const RecOp* a = find_op(b, "attn_paged_sink", l); + const RecOp* f = find_op(b, "qkv_norm_rope_kv_store", l); + const RecOp* s = find_op(b, "kv_store", l); + REQUIRE(a && f && s); + CHECK_EQ(pint(a, "window"), is_full(l) ? 0 : 513); + CHECK_EQ(pint(a, "gqa"), 8); + CHECK_EQ(pint(a, "causal"), 1); + CHECK_EQ(pstr(a, "kv_dtype"), std::string(kvn)); + CHECK_EQ(pint(f, "rotary_dim"), is_full(l) ? 0 : 128); + CHECK_EQ(pstr(f, "kv_dtype"), std::string(kvn)); + CHECK_EQ(pstr(s, "kv_dtype"), std::string(kvn)); + CHECK(param(s, "k_scale") == nullptr); + } + steps_lint_clean(b, 0, 1); + } +} + +/* The IQ8R container: every trunk linear is an i8a8h GEMM, every grouped GEMM the int8 row, gate_up + * reading the block input's own rotated codes at IQ8R's 256 and down the gated product's at a 128; + * the norms, the gated products and the attention output write those codes, so no linear declares + * a quantiser and no E4M3 code is written. One rank and both ranks of two. */ +TEST(iq8r_container_reads_the_trunks_rotated_codes_everywhere) { + for (int world : { 1, 2 }) + for (int rank = 0; rank < world; ++rank) { + MetaKV mk = flint_meta(); + RadBuilder b; + iq8r_encs(&b); + RadBuildCtx ctx = build_ctx(rank, world); + REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK); + const flint::Model& m = flint::g_model[rank]; + CHECK(m.trunk_rot); + CHECK_EQ(m.trunk_g8, 256); + const rad_buf hq = (rad_buf)m.h.q8, fq = (rad_buf)m.mw.eff.q8; + REQUIRE(hq != 0); + REQUIRE(fq != 0); + int gu = 0, dn = 0; + for (const auto& o : b.ops) { + if (o.op == "gemm_nt_q") CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h")); + if (o.op != "moe_gemm_q") continue; + CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h")); + const bool token = pstr(&o, "a_order") == "token"; + CHECK_EQ(pint(&o, "a_group"), token ? 256 : 128); + CHECK(in(o.reads, token ? hq : fq)); + (token ? gu : dn) += 1; + } + CHECK_EQ(gu, 47); + CHECK_EQ(dn, 47); + /* q|k|v, o, the dense pair twice, the shared pair 47 times. */ + CHECK_EQ(count_op(b, "gemm_nt_q"), 49 * 4 + 2 * 2 + 47 * 2); + CHECK_EQ(count_op(b, "gated_had_quant_i8g"), 2 + 47 + 47); + CHECK_EQ(count_op(b, "had_quant_act_i8g"), 49); + for (const char* op : { "gated_quant_fp8", "quant_act_fp8", "rmsnorm_quant_fp8", + "ar_rmsnorm_quant_fp8", "quant_act_i8g" }) + CHECK_EQ(count_op(b, op), 0); + CHECK_EQ(count_op(b, world == 2 ? "ar_rmsnorm_had_quant_i8g" : "rmsnorm_had_quant_i8g") > 0, + true); + for (const char* a : { "h.q", "moe_ffn.q", "moe_hr.q8", "shared_ffn.q", "attn_out.q" }) + CHECK(find_b(b, a) == nullptr); + /* Expert parallel: each rank owns 128 whole experts. */ + CHECK(find_w(b, rank == 0 ? "blk.2.ffn_gate_up_exps.0.weight" + : "blk.2.ffn_gate_up_exps.128.weight") != nullptr); + steps_lint_clean(b, rank, world); + } +} + +/* Where the rotating norm is not served (the CPU kernels), every linear quantises `h` itself and + * the routed experts read a rotated int8 copy that had_quant_act_i8g writes once a layer. */ +TEST(iq8r_container_quantises_the_expert_input_without_the_rotating_norm) { + MetaKV mk = flint_meta(); + RadBuilder b; + for (const char* op : { "rmsnorm_had_quant_i8g", "ar_rmsnorm_had_quant_i8g" }) + b.undeclared.insert(op); + iq8r_encs(&b); + RadBuildCtx ctx = build_ctx(); + REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK); + const RecBuf* hr = find_b(b, "moe_hr.q8"); + REQUIRE(hr != nullptr); + const rad_buf hrb = (rad_buf)flint::g_model[0].hr.q8; + int reads = 0; + for (const auto& o : b.ops) + if (o.op == "moe_gemm_q" && pstr(&o, "a_order") == "token") { + CHECK_EQ(pint(&o, "a_group"), 128); + reads += in(o.reads, hrb); + } + CHECK_EQ(reads, 47); + steps_lint_clean(b, 0, 1); +} + +/* The four-bit container: u4 attention over the bf16 plane, four-bit experts over the block + * input's E4M3 pair (w4a8), plain int8 dense and shared linears each quantising its own input, + * an int8 head. */ +TEST(q4_container_serves_four_bit_experts_and_plain_int8_linears) { + for (int world : { 1, 2 }) + for (int rank = 0; rank < world; ++rank) { + MetaKV mk = flint_meta(); + RadBuilder b; + q4_encs(&b); + RadBuildCtx ctx = build_ctx(rank, world); + REQUIRE_EQ(flint::declare(&b, mk.meta(), &ctx), RAD_OK); + CHECK(!flint::g_model[rank].trunk_rot); + int moe = 0, asym = 0, i8 = 0; + for (const auto& o : b.ops) { + if (o.op == "moe_gemm_q") { + CHECK_EQ(pstr(&o, "dtype"), std::string("w4a8")); + ++moe; + } + if (o.op == "gemm_nt_q") { + const std::string dt = pstr(&o, "dtype"); + asym += dt == "w4a16_asym" || dt == "w4a8i8_asym"; + i8 += dt == "i8a8"; + } + } + CHECK_EQ(moe, 2 * 47); + CHECK(asym >= 4 * 49); + CHECK_EQ(i8, 2 * 2 + 2 * 47); + CHECK(count_op(b, world == 2 ? "ar_rmsnorm_quant_fp8" : "rmsnorm_quant_fp8") > 0); + /* No attention output quantiser: the u4 out projection reads the bf16 plane. */ + CHECK_EQ(count_op(b, "quant_act_fp8"), 0); + const RecWeight* head = find_w(b, "output.weight"); + REQUIRE(head != nullptr); + CHECK_EQ(head->d.dtype, (uint32_t)RAD_I8); + steps_lint_clean(b, rank, world); + } +} + +/* What the plugin refuses by name: a container whose experts are plain (unrotated) int8, a rotated + * trunk over unrotated four-bit experts, rotated int8 experts under an unrotated trunk, and a + * cache other than bf16 or int8. */ +TEST(refuses_mismatched_forms_and_other_caches) { + { + MetaKV mk = flint_meta(); + RadBuilder b; + iq8r_encs(&b); + const RadEncoding w8 = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128); + for (auto& e : b.encs) e.second = w8; + RadBuildCtx ctx = build_ctx(); + CHECK(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }) < 0); + } + { + MetaKV mk = flint_meta(); + RadBuilder b; + iq8r_encs(&b); + const RadEncoding i4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128); + for (auto& e : b.encs) + if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = i4; + RadBuildCtx ctx = build_ctx(); + CHECK_EQ(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }), + RAD_E_UNSUPPORTED); + } + { + MetaKV mk = flint_meta(); + RadBuilder b; + q4_encs(&b); + for (auto& e : b.encs) + if (e.first == "ffn_gate_up_exps" || e.first == "ffn_down_exps") e.second = i8h(); + RadBuildCtx ctx = build_ctx(); + CHECK_EQ(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }), + RAD_E_UNSUPPORTED); + } + { + MetaKV mk = flint_meta(); + RadBuilder b; + iq8r_encs(&b); + RadBuildCtx ctx = build_ctx(); + ctx.kv_dtype = RAD_F8E4M3; + CHECK_EQ(stderr_of_rc([&] { return flint::declare(&b, mk.meta(), &ctx); }), + RAD_E_UNSUPPORTED); + } +} + +/* Per-instance state lives in the declaring instance's slot, so a second engine in the process + * leaves the first one's model alone. */ +TEST(declares_into_its_own_slot) { + MetaKV mk = flint_meta(); + RadBuilder b0, b1; + iq8r_encs(&b0); + q4_encs(&b1); + RadBuildCtx c0 = build_ctx(); + RadBuildCtx c1 = build_ctx(); + c1.slot_base = 4; + REQUIRE_EQ(flint::declare(&b0, mk.meta(), &c0), RAD_OK); + REQUIRE_EQ(flint::declare(&b1, mk.meta(), &c1), RAD_OK); + RadArchProbe probe{}; + CHECK_OK(flint::probe(mk.meta(), &probe)); + CHECK_EQ(probe.draft_depth, 0); + CHECK(flint::g_model[0].trunk_rot); + CHECK(!flint::g_model[4].trunk_rot); + CHECK_EQ(flint::g_model[4].g.n_layer, 49); +} + +RAD_TEST_MAIN() diff --git a/tests/glimmer_golden.h b/tests/glimmer_golden.h new file mode 100644 index 00000000..23e94ccb --- /dev/null +++ b/tests/glimmer_golden.h @@ -0,0 +1,73 @@ +/* glimmer_golden.h -- GENERATED by mkglimmergolden.py from transformers 5.23.0.dev0 (MuseGlimmerImageProcessor, MuseGlimmerVideoProcessor, torch 2.15.0+cpu, torchvision 0.29.2+cpu); do not edit. */ +#pragma once +#include + +static const int32_t kGoldMusePatch = 14, kGoldMuseTemporal = 2, kGoldMuseMerge = 2; +static const int32_t kGoldMuseTokImage = 200092, kGoldMuseTokVideo = 200091; +static const int32_t kGoldMuseTokStart = 200080, kGoldMuseTokEnd = 200081; +static const int32_t kGoldMuseVidStart = 200082, kGoldMuseVidEnd = 200083; +static const int32_t kGoldMuseVidSep = 200087; + +/* A h x w picture's resize target, in pixels. */ +struct GoldMuseResize { int64_t h, w, oh, ow; }; +static const GoldMuseResize kGoldMuseResize[] = { + { 256, 320, 252, 308 }, + { 100, 100, 112, 112 }, + { 84, 84, 84, 84 }, + { 10, 10, 28, 28 }, + { 28, 28, 28, 28 }, + { 27, 27, 28, 28 }, + { 1, 1, 28, 28 }, + { 8000, 8000, 1792, 1792 }, + { 2000, 50, 2016, 56 }, + { 50, 2000, 56, 2016 }, + { 300, 500, 308, 504 }, + { 640, 427, 616, 420 }, + { 1920, 1080, 1932, 1092 }, + { 3, 5000, 28, 5012 }, + { 500, 3, 504, 28 }, + { 1234, 5678, 812, 3836 }, + { 7, 9, 28, 28 }, + { 112, 224, 112, 224 }, + { 224, 112, 224, 112 }, +}; + +/* A h x w picture: the grid (in patches), the plane's first 16 bf16 values and the FNV-1a of every bf16 value's bytes, patches in the reference's raster order, each row (temporal, channel, y, x) as the reference lays it out. */ +struct GoldMuseImage { int64_t h, w; int32_t gh, gw; uint16_t head[16]; uint64_t fnv; }; +static const GoldMuseImage kGoldMuseImage[] = { + { 100, 100, 8, 8, {0xbebf, 0xbf56, 0xbeaf, 0x3f50, 0x3db9, 0xbf10, 0x3ea7, 0x3f26, 0x3eef, 0xbeff, 0xbe75, 0xbf7e, 0x3f02, 0x3e2d, 0x3f08, 0xbe55}, 2422471396853671097ull }, + { 256, 320, 18, 22, {0xbec7, 0xbf54, 0x3e4d, 0x3f22, 0xbf18, 0x3e7d, 0x3f28, 0x3e45, 0xbeef, 0xbf22, 0xbd71, 0x3ec7, 0xbf1e, 0x3ebb, 0x3f28, 0x3ca1}, 116533246137817081ull }, +}; + +/* The clip: 37 source frames at 6 fps sampled at 2 fps; the sampled indices, the grid (groups x patches), the plane's first 16 bf16 values and FNV-1a, and each group's stamp. */ +static const int64_t kGoldMuseVideoTotal = 37; +static const double kGoldMuseVideoFps = 6.0; +static const int32_t kGoldMuseVideoN = 12; +static const int64_t kGoldMuseVideoIndex[] = { + 0, 3, 6, 9, 13, 16, 19, 22, 26, 29, 32, 36}; +static const int32_t kGoldMuseVideoGrid[] = { 6, 4, 6 }; +static const uint16_t kGoldMuseVideoHead[16] = { + 0xbebf, 0xbf38, 0x3f08, 0x3d89, 0xbe93, 0x3f02, 0x3ee3, 0xbef3, 0xbf12, 0xbd11, 0x3e83, 0xbedf, 0x3e15, 0xbf08, 0x3f30, 0x3e9b}; +static const uint64_t kGoldMuseVideoFnv = 11707344584801435184ull; +static const char* const kGoldMuseVideoStamps[] = { + "Time: 0.0s", + "Time: 1.0s", + "Time: 2.2s", + "Time: 3.2s", + "Time: 4.3s", + "Time: 5.3s", +}; +/* A source of `total` frames at `fps` sampled at 2 fps: the frame count and the FNV-1a of every int64 index's bytes (mm_test's fnv over int64). */ +struct GoldMuseSample { int64_t total; double fps; int32_t n; uint64_t fnv; }; +static const GoldMuseSample kGoldMuseSample[] = { + { 37, 6.0, 12, 7586201493087669970ull }, + { 6, 2.0, 6, 505324669386248260ull }, + { 96, 24.0, 8, 5899556429423025984ull }, + { 1, 2.0, 1, 12161962213042174405ull }, + { 2, 2.0, 2, 7576559462502111812ull }, + { 5, 12.0, 2, 879613241599343585ull }, + { 600, 30.0, 40, 14808218070874272101ull }, + { 1000, 24.0, 82, 13092565161413813425ull }, + { 13, 7.0, 2, 291392423630507241ull }, + { 4, 1.0, 4, 7267626464946418085ull }, +}; diff --git a/tests/mem_test.cpp b/tests/mem_test.cpp index 108b3de3..1053f90d 100644 --- a/tests/mem_test.cpp +++ b/tests/mem_test.cpp @@ -4725,6 +4725,110 @@ TEST(dropping_a_clean_entry_gives_its_vram_back_and_keeps_it_restorable) { CHECK_EQ(x.f.pc.drop_clean(), 0); /* nothing left to drop */ } +/* A conversation larger than the host tier keeps its end in VRAM only, with no host copy coming, + * so it never becomes clean. Left high in the pool by sequences that have since gone, a few such + * blocks stop the expert loan below them for as long as the server runs. drop_clean forgets them + * where giving them up lends far more than it loses, inside the loan it is asked about and once + * no sequence reads them. */ +struct Stragglers { + Fixture f; + IdleTiers t; + int64_t all = 0; + /* `slots` host entries; a sequence 9 over the bottom `under` blocks. */ + int build(int slots, int under) { + int s = f.build(/*with_linear=*/false, 0); + if (s < 0) return s; + IdleTiers::Config c = tier_config(slots * 1024, 1024); + c.block_tokens = 16; + s = t.configure(c); + if (s < 0) return s; + f.pc.set_tiers(&t); + all = f.kv.total_blocks(G_FULL); + if (under <= 0) return RAD_OK; + s = f.kv.add_sequence(9); + return s < 0 ? s : f.kv.ensure(9, 16 * under); + } + /* A sequence that comes and goes: what makes drop_clean look again. */ + void pass() { + CHECK_OK(f.kv.add_sequence(77)); + CHECK_OK(f.kv.ensure(77, 16)); + f.kv.free_sequence(77); + } +}; + +TEST(stragglers_with_no_host_copy_coming_leave_vram_for_the_loan) { + Stragglers x; + CHECK_OK(x.build(/*slots=*/16, /*under=*/300)); + REQUIRE(x.all >= 400); + const auto prompt = tok_run(7700, 336); + publish(x.f, 1, prompt, 320); /* twenty blocks, at 300 and up */ + CHECK_EQ(copy_now(x.t).size(), 16u); + CHECK_EQ(x.t.stats().held_back, 4ll); + const int64_t goal = (x.all - 100) * 16; /* a loan down to block 100 */ + + /* Still read by its sequence: nothing goes, whatever the loan. */ + CHECK_EQ(x.f.pc.drop_clean(goal), 0); + x.f.kv.free_sequence(9); + x.f.kv.free_sequence(1); + + /* No loan asked for: the copied start leaves VRAM, the four blocks past the tier stay. */ + CHECK_EQ(x.f.pc.drop_clean(), 16); + CHECK_EQ(x.f.pc.resident(), 4ll); + CHECK_EQ(x.f.pc.stats().evictions, 0ll); + CHECK_EQ(x.f.kv.straggler_mark(G_FULL), 0ll); /* four blocks keep 316 from the loan */ + const int64_t pinned = x.f.kv.spare_tokens(); + CHECK(pinned <= (x.all - 316) * 16); + /* A loan that stops above them takes nothing. */ + x.pass(); + CHECK_EQ(x.f.pc.drop_clean((x.all - 330) * 16), 0); + CHECK_EQ(x.f.pc.resident(), 4ll); + + /* The loan the slab is short of reaches below them: they are forgotten, the start is not. */ + x.pass(); + CHECK_EQ(x.f.pc.drop_clean(goal), 4); + CHECK_EQ(x.f.pc.resident(), 0ll); + CHECK_EQ(x.f.pc.size(), 16ll); + CHECK_EQ(x.f.pc.stats().evictions, 4ll); + CHECK_EQ(x.f.kv.pool_bytes_used(G_FULL), 0ll); + CHECK(x.f.kv.spare_tokens() > pinned); + CHECK_OK(x.f.kv.set_loan(x.f.kv.spare_tokens())); + CHECK_EQ(x.f.pc.restorable_from(prompt, {}).size(), 16u); +} + +/* Context that fills its part of the pool is not a straggler, with or without a host copy: the + * loan stops at its edge and takes none of it, however large the loan asked about. The end of an + * older conversation left far above it is, and goes alone. */ +TEST(cached_context_that_fills_its_part_of_the_pool_stays_and_the_blocks_far_above_it_go) { + Stragglers x; + CHECK_OK(x.build(/*slots=*/8, /*under=*/300)); + REQUIRE(x.all >= 400); + const auto older = tok_run(7800, 16 * 12 + 16); + publish(x.f, 1, older, 16 * 12); /* twelve blocks, at 300 and up */ + CHECK_EQ(copy_now(x.t).size(), 8u); /* its start fills the tier */ + x.f.kv.free_sequence(9); + x.f.kv.free_sequence(1); + const auto dense = tok_run(9100, 16 * 200 + 16); + publish(x.f, 2, dense, 16 * 200); /* two hundred blocks from the bottom */ + CHECK_EQ(copy_now(x.t).size(), 0u); /* no room, and none is made here */ + x.f.kv.free_sequence(2); + + CHECK_EQ(x.f.pc.drop_clean(), 8); /* the older start, to the host */ + CHECK_EQ(x.f.pc.resident(), 204ll); + CHECK_EQ(x.f.kv.held_top_blocks(G_FULL), 312ll); + CHECK_EQ(x.f.kv.straggler_mark(G_FULL), 200ll); /* the edge of the dense part */ + + x.pass(); + const int64_t goal = x.all * 16; /* every block the pool has */ + CHECK_EQ(x.f.pc.drop_clean(goal), 4); + CHECK_EQ(x.f.pc.resident(), 200ll); + CHECK_EQ(x.f.kv.held_top_blocks(G_FULL), 200ll); + CHECK_EQ(x.f.kv.straggler_mark(G_FULL), 200ll); /* nothing above the dense part now */ + x.pass(); + CHECK_EQ(x.f.pc.drop_clean(goal), 0); /* which keeps every block */ + CHECK_EQ(x.f.pc.resident(), 200ll); + CHECK_EQ(x.f.pc.lookup(dense, {}).n_attn_tokens, 16 * 200); +} + TEST(a_recomputed_shared_prefix_keeps_its_original_host_copy_and_snapshot) { /* A short request shares less than one checkpoint with an off-device conversation, so it * recomputes instead of adopting that prefix. Its different prefill shape can round the KV diff --git a/tests/mkglimmergolden.py b/tests/mkglimmergolden.py new file mode 100644 index 00000000..643a053a --- /dev/null +++ b/tests/mkglimmergolden.py @@ -0,0 +1,213 @@ +"""mkglimmergolden.py OUT.h -- goldens for tests/mm_test.cpp's Muse Glimmer cases, every number +from the reference itself: transformers' own MuseGlimmerImageProcessor and +MuseGlimmerVideoProcessor (transformers 5.23.0.dev0, torch 2.15.0+cpu, torchvision 0.29.2+cpu), +run on synthetic splitmix frames, plus their sample_frames and replace_video_token. + +The resize filter is the real reference path, not a reimplementation: the processor is a +TorchvisionBackend whose resize calls tvF.resize on the uint8 pixels with +InterpolationMode.LANCZOS and antialias=True on CPU, which torch serves with its native uint8 +kernel (int16 fixed-point weights, horizontal pass first, an 8-bit rounded intermediate). The +test's C++ side has to reproduce that byte for byte. + + * the resize table: each picture's grid straight out of image_grid_thw; + * two pictures' patch planes: the processor's f32 pixel_values cast to bfloat16, the patch rows + in the reference's own raster order (patch row by row), each row (temporal, channel, y, x) as + the reference lays it out, and the FNV-1a of the whole plane; + * a twelve-frame clip: the grid, the plane's FNV-1a, the per-group stamps (each + group's first frame's time, the reference's replace_video_token) and the sampled indices + (the reference's sample_frames, torch.linspace(...).long()); + * a sampling table: the indices' count, first entry and FNV-1a. + +The pixel at (frame f, row y, column x, channel c) is mm_test's pix(f, y, x, c) splitmix hash, +and pix's frame argument is the SOURCE frame's index, so the test's decoded frames match the +processor's sampled ones exactly. +""" +import sys + +import numpy as np +import torch +import transformers +import torchvision +from PIL import Image +from transformers.models.muse_glimmer.image_processing_muse_glimmer import MuseGlimmerImageProcessor +from transformers.models.muse_glimmer.video_processing_muse_glimmer import MuseGlimmerVideoProcessor +from transformers.video_utils import VideoMetadata + +PATCH, TEMPORAL, MERGE = 14, 2, 2 +MAX_IMAGE_TOKENS = 4096 +MAX_VIDEO_FRAME_TOKENS = 144 + +U = np.uint64 + + +def picture(f, h, w): + """[h, w, 3] uint8, mm_test's pix(f, y, x, c).""" + y = np.arange(h, dtype=np.uint64)[:, None] + x = np.arange(w, dtype=np.uint64)[None, :] + c = np.arange(3, dtype=np.uint64)[None, None, :] + z = (U(f) * U(0x9E3779B97F4A7C15) + y[:, :, None] * U(0xBF58476D1CE4E5B9) + + x[:, :, None] * U(0x94D049BB133111EB) + c * U(0x2545F4914F6CDD1D) + U(12345)) + z = (z ^ (z >> U(30))) * U(0xBF58476D1CE4E5B9) + z = (z ^ (z >> U(27))) * U(0x94D049BB133111EB) + return ((z ^ (z >> U(31))) & U(255)).astype(np.uint8) + + +def fnv16(bits): + """FNV-1a over each element's bytes, least significant first (mm_test's fnv).""" + h = 0xcbf29ce484222325 + for v in np.asarray(bits, dtype=np.uint16).ravel(order="C"): + for b in (0, 1): + h = ((h ^ U((int(v) >> (8 * b)) & 0xFF)) * U(0x100000001b3)) & U((1 << 64) - 1) + return int(h) + + +def bf16(a): + t = torch.from_numpy(np.ascontiguousarray(a, dtype=np.float32)) + return t.to(torch.bfloat16).view(torch.int16).numpy().view(np.uint16) + + +def image_processor(): + return MuseGlimmerImageProcessor( + patch_size=PATCH, temporal_patch_size=TEMPORAL, merge_size=MERGE, + max_image_tokens=MAX_IMAGE_TOKENS, image_mean=[0.5] * 3, image_std=[0.5] * 3) + + +def video_processor(): + return MuseGlimmerVideoProcessor( + patch_size=PATCH, temporal_patch_size=TEMPORAL, merge_size=MERGE, + max_video_frame_tokens=MAX_VIDEO_FRAME_TOKENS, num_frames=96, fps=2.0, + image_mean=[0.5] * 3, image_std=[0.5] * 3) + + +def process_image(h, w): + pil = Image.fromarray(picture(0, h, w), mode="RGB") + out = image_processor()(images=[pil], return_tensors="pt") + rows = out["pixel_values"] # [gh*gw, dim] f32, raster order + if rows.dim() == 3: + rows = rows[0] + gt, gh, gw = (int(v) for v in out["image_grid_thw"][0]) + assert gt == 1 + return bf16(rows.numpy()), gh, gw # raster order, as the reference emits it + + +def main(out): + print("transformers", transformers.__version__, "torch", torch.__version__, + "torchvision", torchvision.__version__) + + resize_cases = [ + (256, 320), (100, 100), (84, 84), (10, 10), (28, 28), (27, 27), (1, 1), + (8000, 8000), (2000, 50), (50, 2000), (300, 500), (640, 427), (1920, 1080), + (3, 5000), (500, 3), (1234, 5678), (7, 9), (112, 224), (224, 112), + ] + L = [f"/* glimmer_golden.h -- GENERATED by mkglimmergolden.py from transformers " + f"{transformers.__version__} (MuseGlimmerImageProcessor, MuseGlimmerVideoProcessor, " + f"torch {torch.__version__}, torchvision {torchvision.__version__}); do not edit. */", + "#pragma once", "#include ", "", + "static const int32_t kGoldMusePatch = 14, kGoldMuseTemporal = 2, kGoldMuseMerge = 2;", + "static const int32_t kGoldMuseTokImage = 200092, kGoldMuseTokVideo = 200091;", + "static const int32_t kGoldMuseTokStart = 200080, kGoldMuseTokEnd = 200081;", + "static const int32_t kGoldMuseVidStart = 200082, kGoldMuseVidEnd = 200083;", + "static const int32_t kGoldMuseVidSep = 200087;", + "", + "/* A h x w picture's resize target, in pixels. */", + "struct GoldMuseResize { int64_t h, w, oh, ow; };", + "static const GoldMuseResize kGoldMuseResize[] = {"] + + print(" resize table + image patch planes") + image_cases = [] + for h, w in resize_cases: + pil = Image.fromarray(picture(0, h, w), mode="RGB") + outi = image_processor()(images=[pil], return_tensors="pt") + _, gh, gw = (int(v) for v in outi["image_grid_thw"][0]) + L.append(f" {{ {h}, {w}, {gh * PATCH}, {gw * PATCH} }},") + L.append("};") + L.append("") + + for h, w in [(100, 100), (256, 320)]: + px, gh, gw = process_image(h, w) + image_cases.append((h, w, gh, gw, px)) + L += ["/* A h x w picture: the grid (in patches), the plane's first 16 bf16 values and the " + "FNV-1a of every bf16 value's bytes, patches in the reference's raster order, each row " + "(temporal, channel, y, x) as the reference lays it out. */", + "struct GoldMuseImage { int64_t h, w; int32_t gh, gw; uint16_t head[16]; uint64_t fnv; };", + "static const GoldMuseImage kGoldMuseImage[] = {"] + for h, w, gh, gw, px in image_cases: + head = ", ".join("0x%04x" % int(v) for v in px[0][:16]) + L.append(f" {{ {h}, {w}, {gh}, {gw}, {{{head}}}, {fnv16(px)}ull }},") + L.append("};") + L.append("") + + print(" video patch plane + stamps") + # A 37-frame source at 6 fps: the reference's sample_frames takes 12 frames at 2 fps, the + # indices linspace(0, 36, 12).long(); six temporal groups, one stamp per group, each the + # group's first frame's time. + total, native_fps, fps = 37, 6.0, 2.0 + n = min(int(total * fps / native_fps), 96, total) + n = max(TEMPORAL, (n // TEMPORAL) * TEMPORAL) + n = min(n, total) + idx = torch.linspace(0, total - 1, n).long().tolist() + print(" sampled", n, "frames:", idx) + src = np.stack([picture(f, 64, 96) for f in idx]) # [T, H, W, 3] + md = VideoMetadata(total_num_frames=total, fps=native_fps, width=96, height=64, + duration=total / native_fps, video_backend="nil", frames_indices=idx) + outv = video_processor()(videos=[torch.from_numpy(src)], return_tensors="pt", + video_metadata=[md], do_sample_frames=False) + pv = outv["pixel_values_videos"] # [gt*gh*gw, dim] f32 + gt, gh, gw = (int(v) for v in outv["video_grid_thw"][0]) + print(" grid", gt, gh, gw) + plane = np.empty((gt, gh * gw, pv.shape[1]), dtype=np.uint16) + for g in range(gt): + plane[g] = bf16(pv[(g * gh * gw):(g + 1) * gh * gw].numpy()) + flat = plane.reshape(-1) + + # The stamps: metadata.timestamps[::temporal][:grid_t], each formatted "Time: {t:.1f}s". + timestamps = [i / native_fps for i in idx] + stamps = [f"Time: {t:.1f}s" for t in timestamps[::TEMPORAL][:gt]] + while len(stamps) < gt: + stamps.append(stamps[-1] if stamps else "Time: 0.0s") + print(" stamps:", stamps) + + L += ["/* The clip: 37 source frames at 6 fps sampled at 2 fps; the sampled indices, the grid " + "(groups x patches), the plane's first 16 bf16 values and FNV-1a, and each group's " + "stamp. */", + f"static const int64_t kGoldMuseVideoTotal = {total};", + f"static const double kGoldMuseVideoFps = {native_fps};", + f"static const int32_t kGoldMuseVideoN = {n};", + "static const int64_t kGoldMuseVideoIndex[] = {", + " " + ", ".join(str(i) for i in idx) + "};", + f"static const int32_t kGoldMuseVideoGrid[] = {{ {gt}, {gh}, {gw} }};", + "static const uint16_t kGoldMuseVideoHead[16] = {", + " " + ", ".join("0x%04x" % int(v) for v in flat[:16]) + "};", + f"static const uint64_t kGoldMuseVideoFnv = {fnv16(flat)}ull;", + "static const char* const kGoldMuseVideoStamps[] = {", + "".join(f' "{s}",\n' for s in stamps) + "};", + ""] + while L[-1] == "": + L.pop() + + print(" sampling table") + sample_cases = [(37, 6.0), (6, 2.0), (96, 24.0), (1, 2.0), (2, 2.0), (5, 12.0), + (600, 30.0), (1000, 24.0), (13, 7.0), (4, 1.0)] + L += ["/* A source of `total` frames at `fps` sampled at 2 fps: the frame count and the " + "FNV-1a of every int64 index's bytes (mm_test's fnv over int64). */", + "struct GoldMuseSample { int64_t total; double fps; int32_t n; uint64_t fnv; };", + "static const GoldMuseSample kGoldMuseSample[] = {"] + proc = video_processor() + for total, fps in sample_cases: + md = VideoMetadata(total_num_frames=total, fps=fps, width=96, height=64, + duration=total / fps, video_backend="nil", frames_indices=None) + got = proc.sample_frames(md, temporal_patch_size=TEMPORAL, num_frames=96, fps=2.0).tolist() + h = 0xcbf29ce484222325 + for i in got: + for b in range(8): + h = ((h ^ U((int(i) >> (8 * b)) & 0xFF)) * U(0x100000001b3)) & U((1 << 64) - 1) + L.append(f" {{ {total}, {fps}, {len(got)}, {h}ull }},") + print(f" {total} @ {fps}: {got[:6]}{'...' if len(got) > 6 else ''} ({len(got)})") + L.append("};") + with open(out, "w") as f: + f.write("\n".join(L) + "\n") + print("wrote", out) + + +if __name__ == "__main__": + main(sys.argv[1]) diff --git a/tests/mm_test.cpp b/tests/mm_test.cpp index 839c694e..dd98bc2f 100644 --- a/tests/mm_test.cpp +++ b/tests/mm_test.cpp @@ -23,6 +23,7 @@ #include "mm/processor.h" #include "gemma4_golden.h" #include "gemma4u_golden.h" +#include "glimmer_golden.h" #include "glm5_golden.h" #include "radio_golden.h" #include "imaging_golden.h" @@ -1126,6 +1127,222 @@ TEST(glm5_reads_its_processor_from_the_container) { CHECK(why.find("patch_expand_factor") != std::string::npos); } +/* ================================================================== Muse Glimmer's processor + * + * glimmer_golden.h: transformers' own MuseGlimmerImageProcessor and MuseGlimmerVideoProcessor + * (mkglimmergolden.py ran them on synthetic splitmix frames), which the processor mirrors: the + * token-capped aspect-nearest resize, torchvision's antialiased Lanczos on the uint8 pixels, the + * (temporal, channel, y, x) patch rows in radiance's merge-block order, and the sampled frames' + * per-group "Time: T s" stamps. */ +namespace { + +VisionConfig muse_cfg() { + VisionConfig c; + c.family = Family::MuseGlimmer; + c.patch = kGoldMusePatch; + c.temporal = kGoldMuseTemporal; + c.merge = kGoldMuseMerge; + c.max_image_tokens = 4096; + c.max_frame_rows = 144; + c.fps = 2.0; + c.min_frames = c.temporal; + c.max_frames = 96; + const int64_t f2 = (int64_t)c.factor() * c.factor(); + c.image_min_pixels = c.video_min_pixels = f2; + c.image_max_pixels = (int64_t)c.max_image_tokens * f2; + c.video_max_pixels = (int64_t)c.max_frame_rows * f2; + c.tok_image = kGoldMuseTokImage; + c.tok_video = kGoldMuseTokVideo; + c.tok_start = kGoldMuseTokStart; + c.tok_end = kGoldMuseTokEnd; + c.tok_video_start = kGoldMuseVidStart; + c.tok_video_end = kGoldMuseVidEnd; + c.tok_video_sep = kGoldMuseVidSep; + c.max_patches = 16384; + return c; +} + +} /* namespace */ + +TEST(muse_sizes_are_the_references) { + for (const GoldMuseResize& g : kGoldMuseResize) { + int64_t oh = 0, ow = 0; + std::string why; + CHECK_OK(muse_size(g.h, g.w, kGoldMusePatch * kGoldMuseMerge, 4096, &oh, &ow, &why)); + if (oh != g.oh || ow != g.ow) + std::fprintf(stderr, " %lld x %lld: %lld x %lld, reference %lld x %lld\n", + (long long)g.h, (long long)g.w, (long long)oh, (long long)ow, + (long long)g.oh, (long long)g.ow); + CHECK_EQ(oh, g.oh); + CHECK_EQ(ow, g.ow); + } +} + +TEST(muse_pictures_patchify_as_the_reference_does) { + Processor p; + int rc = p.init(muse_cfg(), [](const std::string&) { return std::vector{ 1 }; }); + REQUIRE(rc >= 0); + for (const GoldMuseImage& g : kGoldMuseImage) { + std::shared_ptr it; + std::string why; + CHECK_OK(p.image_from(frame(0, (int)g.h, (int)g.w), &it, &why)); + REQUIRE(it != nullptr); + if (it->grid_h != g.gh || it->grid_w != g.gw) + std::fprintf(stderr, " %lld x %lld: grid %d x %d, reference %d x %d\n", + (long long)g.h, (long long)g.w, it->grid_h, it->grid_w, g.gh, g.gw); + CHECK_EQ(it->grid_t, 1); + CHECK_EQ(it->grid_h, g.gh); + CHECK_EQ(it->grid_w, g.gw); + REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * 1176); + for (int i = 0; i < 16; ++i) CHECK_EQ(it->pixels[(size_t)i], g.head[i]); + CHECK_EQ(fnv(it->pixels), g.fnv); + + /* <|image_start|>, one <|patch|> per merged row, <|image_end|>: the reference's + * replace_image_token. */ + const int32_t rows = (g.gh / 2) * (g.gw / 2); + REQUIRE_EQ(it->expand.size(), (size_t)rows + 2); + CHECK_EQ(it->expand.front(), kGoldMuseTokStart); + CHECK_EQ(it->expand.back(), kGoldMuseTokEnd); + for (int32_t i = 1; i <= rows; ++i) CHECK_EQ(it->expand[(size_t)i], kGoldMuseTokImage); + REQUIRE_EQ(it->seg_at.size(), (size_t)1); + CHECK_EQ(it->seg_at[0], 1); + CHECK_EQ(it->n_rows(), (int64_t)rows); + } +} + +TEST(muse_reads_its_processor_from_the_container) { + const char* keys[] = { "vision_config.model_type", "vision_config.patch_size", + "vision_config.patch_temporal", "vision_config.merge_size", + "image_token_id", "video_token_id", + "processor.image_processor.max_image_tokens", + "processor.video_processor.max_video_frame_tokens", + "processor.video_processor.num_frames", + "processor.video_processor.fps", + "processor.image_mean", "processor.image_std" }; + const char* vals[] = { "muse_glimmer_vision", "14", "2", "2", "200092", "200091", + "4096", "144", "96", "2", "", "" }; + RadModelMeta m{}; + m.n_kv = (int)(sizeof(keys) / sizeof(keys[0])); + m.kv_key = keys; + m.kv_val = vals; + VisionConfig c; + std::string why; + CHECK_OK(c.from_meta(m, &why)); + CHECK(c.family == Family::MuseGlimmer); + CHECK_EQ(c.patch, 14); + CHECK_EQ(c.temporal, 2); + CHECK_EQ(c.merge, 2); + CHECK_EQ(c.patch_dim(), (int64_t)1176); + CHECK_EQ(c.factor(), 28); + CHECK_EQ(c.max_image_tokens, 4096); + CHECK_EQ(c.max_frame_rows, 144); + CHECK_EQ(c.max_frames, 96); + CHECK_EQ(c.fps, 2.0); + CHECK_EQ(c.tok_image, 200092); + CHECK_EQ(c.tok_video, 200091); + /* The markers the container does not number stay unresolved for the vocabulary. */ + CHECK_EQ(c.tok_start, -1); + CHECK_EQ(c.tok_video_sep, -1); + /* The shipped mean and deviation, over the reference class's IMAGENET_STANDARD defaults. */ + for (int i = 0; i < 3; ++i) { + CHECK_EQ(c.mean[i], 0.5f); + CHECK_EQ(c.stdv[i], 0.5f); + } + /* Numbered markers and stated mean/std win. */ + vals[4] = "200090"; + vals[10] = "0.48 0.46 0.41"; + vals[11] = "0.27 0.26 0.28"; + vals[11] = "0.27 0.26 0.28"; + VisionConfig d; + CHECK_OK(d.from_meta(m, &why)); + CHECK_EQ(d.tok_image, 200090); + CHECK_EQ(d.mean[0], 0.48f); + CHECK_EQ(d.stdv[2], 0.28f); + /* No tower geometry: refused, not defaulted. */ + vals[1] = "0"; + VisionConfig e; + CHECK_EQ(e.from_meta(m, &why), RAD_E_NOTFOUND); + /* A marker the container does not number that the vocabulary cannot spell: refused at init, + * not on the first picture. */ + VisionConfig unnumbered = muse_cfg(); + unnumbered.tok_start = -1; + Processor p; + CHECK_EQ(p.init(unnumbered, [](const std::string&) { return std::vector{ 1 }; }, + [](const std::string&) { return -1; }), + RAD_E_NOTFOUND); + /* A frame budget above one pass: refused. */ + VisionConfig big = muse_cfg(); + big.max_patches = 100; + Processor q; + CHECK_EQ(q.init(big, [](const std::string&) { return std::vector{ 1 }; }), + RAD_E_INVAL); +} + +TEST(muse_frames_are_sampled_as_the_reference_does) { + for (const GoldMuseSample& g : kGoldMuseSample) { + VideoInfo info{}; + info.n_frames = g.total; + info.fps = g.fps; + const std::vector idx = sample_frames_muse(info, 2.0, kGoldMuseTemporal, 96); + if ((int32_t)idx.size() != g.n) + std::fprintf(stderr, " %lld frames at %g fps: %zu indices, reference %d\n", + (long long)g.total, g.fps, idx.size(), g.n); + CHECK_EQ((int32_t)idx.size(), g.n); + CHECK_EQ(fnv(idx), g.fnv); + } +} + +TEST(a_muse_clip_patchifies_and_is_stamped_as_the_reference_does) { + std::vector stamps; + Processor p; + REQUIRE(p.init(muse_cfg(), [&](const std::string& s) { + stamps.push_back(s); + return std::vector((size_t)s.size(), 7); /* a token per byte */ + }) >= 0); + Video v; + v.info.n_frames = kGoldMuseVideoTotal; + v.info.fps = kGoldMuseVideoFps; + v.info.w = 96; + v.info.h = 64; + v.index.assign(kGoldMuseVideoIndex, + kGoldMuseVideoIndex + sizeof(kGoldMuseVideoIndex) / sizeof(kGoldMuseVideoIndex[0])); + for (int64_t i : v.index) v.frames.push_back(frame((int)i, 64, 96)); + std::shared_ptr it; + std::string why; + CHECK_OK(p.video_from(v, &it, &why)); + REQUIRE(it != nullptr); + CHECK_EQ(it->grid_t, kGoldMuseVideoGrid[0]); + CHECK_EQ(it->grid_h, kGoldMuseVideoGrid[1]); + CHECK_EQ(it->grid_w, kGoldMuseVideoGrid[2]); + REQUIRE_EQ(it->pixels.size(), (size_t)it->n_patch * 1176); + for (int i = 0; i < 16; ++i) CHECK_EQ(it->pixels[(size_t)i], kGoldMuseVideoHead[i]); + CHECK_EQ(fnv(it->pixels), kGoldMuseVideoFnv); + + /* One stamp per group, the group's first frame's time. */ + const size_t n_stamps = sizeof(kGoldMuseVideoStamps) / sizeof(kGoldMuseVideoStamps[0]); + REQUIRE_EQ(stamps.size(), n_stamps); + for (size_t i = 0; i < n_stamps; ++i) CHECK_EQ(stamps[i], std::string(kGoldMuseVideoStamps[i])); + + /* <|vid_start|>, then per group: the stamp's tokens, one <|video|> per merged row, and a + * <|vid_frame_separator|> between the groups and <|vid_end|> after the last. */ + const int32_t rows = (kGoldMuseVideoGrid[1] / 2) * (kGoldMuseVideoGrid[2] / 2); + size_t at = 0; + REQUIRE_EQ(it->seg_at.size(), (size_t)kGoldMuseVideoGrid[0]); + CHECK_EQ(it->expand[at], kGoldMuseVidStart); + ++at; + for (int32_t g = 0; g < kGoldMuseVideoGrid[0]; ++g) { + at += stamps[(size_t)g].size(); + REQUIRE(at < it->expand.size()); + CHECK_EQ(it->seg_at[(size_t)g], (int32_t)at); + for (int32_t r = 0; r < rows; ++r) CHECK_EQ(it->expand[at + (size_t)r], kGoldMuseTokVideo); + at += (size_t)rows; + CHECK_EQ(it->expand[at], g + 1 == kGoldMuseVideoGrid[0] ? kGoldMuseVidEnd + : kGoldMuseVidSep); + ++at; + } + CHECK_EQ(at, it->expand.size()); +} + /* ================================================================== Pillow's arithmetic * * imaging_golden.h: Image.resize(LANCZOS) of an RGBA splitmix picture at sizes that shrink, grow, diff --git a/tests/museglimmer_test.cpp b/tests/museglimmer_test.cpp new file mode 100644 index 00000000..0f678ef7 --- /dev/null +++ b/tests/museglimmer_test.cpp @@ -0,0 +1,1693 @@ +/* museglimmer_test.cpp -- the declared graph and the steps of Meta's Muse Glimmer plugin: the + * trunk (gated attention alternating sliding-window rotary and NoPE full layers under Gemma-2 + * style double norms), its refusals, the InternVit-shaped vision tower and its adapter, and the + * scatter that puts the tower's rows into the trunk's embeddings. Asserted statically against the + * recording builder of arch_fakes.h, per op and per operand. */ +#define RAD_ARCH_NO_EXPORTS 1 + +#include "arch_fakes.h" + +#include "../arch/museglimmer/museglimmer.cpp" +#include "../arch/museglimmer_ct/museglimmer_ct.cpp" + +#include + +/* ==================================================================== fixtures */ + +namespace { + +/* The declared handle of a weight or buffer recorded by the fake builder. */ +template +int64_t handle_of(const std::vector& v, const char* name) { + for (size_t i = 0; i < v.size(); ++i) + if (v[i].name == name) return (int64_t)(i + 1); + return 0; +} +int64_t w_h(const RadBuilder& b, const char* name) { return handle_of(b.weights, name); } +int64_t b_h(const RadBuilder& b, const char* name) { return handle_of(b.bufs, name); } + +/* Doubles the plugin read through float config values: compared with a tolerance, not ==. */ +bool near(double a, double b, double tol) { return std::abs(a - b) < tol; } + +/* The trunk's config, at a fifth of the 30B's width and eight layers, with the family's free-form + * keys under both spellings rad-convert flattens to (text_config.X and the bare alias). The + * layer schedule is the 30B's pattern at eight layers: full attention on layers 3 and 7, the + * rest sliding with rotary. */ +MetaKV muse_meta() { + RadModelMeta m{}; + m.n_layers = 8; + m.n_embd = 128; + m.n_head = 4; + m.n_head_kv = 2; + m.head_dim = 8; + m.n_ff = 256; + m.n_vocab = 512; + m.rms_eps = 1e-5f; + m.rope_theta = 500000.0; + MetaKV k(m); + for (const char* pre : { "", "text_config." }) { + k.set((std::string(pre) + "sliding_window").c_str(), "4") + .set((std::string(pre) + "qk_scale_factor").c_str(), "3.87") + .set((std::string(pre) + "post_norm_eps").c_str(), "1e-8") + .set((std::string(pre) + "output_multiplier").c_str(), "0.19611613513818404") + .set((std::string(pre) + "final_logit_softcapping").c_str(), "20") + .set((std::string(pre) + "rope_parameters.rope_theta").c_str(), "500000") + .set((std::string(pre) + "rope_parameters.rope_type").c_str(), "default") + .set((std::string(pre) + "layer_types").c_str(), + "sliding_attention sliding_attention sliding_attention full_attention " + "sliding_attention sliding_attention sliding_attention full_attention") + .set((std::string(pre) + "layer_rope_theta").c_str(), + "500000 500000 500000 0 500000 500000 500000 0"); + } + return k; +} + +/* The tower, at a quarter of the release's width in four blocks: head_dim 12, so the axial rotary + * runs sections 3 and 3; the position grid 4 x 4, so the windows are 4 x 4 patches. Everything the + * tower reads is a config key, so the tiny geometry is served by the same code paths. The family + * rule puts a tower's full-attention layer on every fourth from the first, plus the last: layer 3 + * here. */ +MetaKV with_vision(MetaKV k) { + k.set("vision_config.model_type", "muse_glimmer_vision") + .set("vision_config.num_hidden_layers", "4") + .set("vision_config.hidden_size", "96") + .set("vision_config.num_attention_heads", "8") + .set("vision_config.intermediate_size", "256") + .set("vision_config.patch_size", "14") + .set("vision_config.patch_temporal", "2") + .set("vision_config.merge_size", "2") + .set("vision_config.pos_emb_height", "4") + .set("vision_config.pos_emb_width", "4") + .set("vision_config.layer_norm_eps", "1e-05") + .set("vision_config.hidden_act", "gelu") + .set("vision_config.rope_parameters.rope_type", "axial") + .set("vision_config.rope_parameters.rope_theta", "10000") + .set("vision_config.layer_types", + "window_attention window_attention window_attention full_attention") + .set("projector_hidden_size", "128") + .set("projector_hidden_act", "gelu") + .set("out_hidden_size", "384"); /* merge 2 squared x width 96 */ + return k; +} + +RadBuildCtx muse_ctx(int rank = 0, int world = 1, int64_t patches = 0) { + RadBuildCtx c = build_ctx(rank, world); + c.max_enc_patches = patches; + return c; +} + +/* One trunk layer's declared ops, in order: the double-norm block with its four norms, the gated + * attention, and the rotary only where the layer carries one. */ +std::vector layer_ops(bool rope, bool ar) { + std::vector v = { "rmsnorm", "gemm_nt", "gemm_nt", "gemm_nt", "gemm_nt", + "rmsnorm", "rmsnorm" }; + if (rope) { v.push_back("rope"); v.push_back("rope"); } + for (const char* s : { "attn_paged", "kv_store", "sigmoid", "mul", "gemm_nt" }) + v.push_back(s); + if (ar) v.push_back("all_reduce"); + for (const char* s : { "rmsnorm", "add", "rmsnorm", "gemm_nt", "silu_mul", "gemm_nt" }) + v.push_back(s); + if (ar) v.push_back("all_reduce"); + for (const char* s : { "rmsnorm", "add" }) v.push_back(s); + return v; +} + +/* The trunk's ops as DECLARED, from the embedding to the capped logits (attn_paged before + * kv_store, the family's declare convention). */ +std::vector trunk_decl(int n_layer, int world) { + std::vector want = { "embed_lookup" }; + if (world > 1) want.push_back("all_reduce"); + want.push_back("rmsnorm"); /* the weightless embedding norm */ + for (int l = 0; l < n_layer; ++l) { + const bool glob = l % 4 == 3; /* is_full_attention(l, 4) at 8 layers */ + for (const std::string& s : layer_ops(!glob, world > 1)) want.push_back(s); + } + want.push_back("rmsnorm"); /* the final norm */ + want.push_back("gather_rows"); + want.push_back("logits_gemm"); + want.push_back("logit_softcap"); + return want; +} + +/* The trunk's ops as ISSUED: kv_store runs before its layer's attention. */ +std::vector trunk_step(int n_layer, int world) { + std::vector want = trunk_decl(n_layer, world); + for (size_t i = 0; i + 1 < want.size(); ++i) + if (want[i] == "attn_paged" && want[i + 1] == "kv_store") + std::swap(want[i], want[i + 1]); + return want; +} + +} /* namespace */ + +/* ==================================================================== 1. the text graph */ + +/* Per layer the exact op row the family runs, the two KV groups with every layer bound to exactly + * one, the weightless norms, the logits' pre-scale and cap, and the gate/up concat in the + * checkpoint's row order. */ +TEST(museglimmer_declares_the_trunk_graph) { + MetaKV mk = muse_meta(); + for (int world : { 1, 4 }) { + const int rank = world - 1; + RadBuilder b; + RadBuildCtx ctx = muse_ctx(rank, world); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + + /* Two KV groups: the sliding layers' window pool and the full layers' pool. */ + REQUIRE_EQ(b.kv_groups.size(), (size_t)2); + CHECK_EQ(b.kv_groups[0].name, std::string("kv_sliding")); + CHECK_EQ(b.kv_groups[0].d.kind, RAD_KV_WINDOW); + CHECK_EQ(b.kv_groups[0].d.window, 4); + CHECK_EQ(b.kv_groups[0].d.n_head_kv, world == 1 ? 2 : 1); + CHECK_EQ(b.kv_groups[0].d.head_dim, 8); + CHECK_EQ(b.kv_groups[1].name, std::string("kv_full")); + CHECK_EQ(b.kv_groups[1].d.kind, RAD_KV_FULL); + CHECK_EQ(b.kv_groups[1].d.n_head_kv, world == 1 ? 2 : 1); + /* Every layer bound exactly once, to its group. */ + REQUIRE_EQ(b.binds.size(), (size_t)8); + const rad_kvgroup win = 1, full = 2; + for (int l = 0; l < 8; ++l) { + CHECK_EQ(b.binds[(size_t)l].first, l); + CHECK_EQ(b.binds[(size_t)l].second, (rad_kvgroup)((l % 4 == 3) ? full : win)); + } + + /* The whole graph, in declare order. */ + CHECK_EQ(join(op_names(b)), join(trunk_decl(8, world))); + + /* The embedding norm is weightless: no gain operand, no centered 1+. */ + const RecOp* en = find_op(b, "rmsnorm"); + REQUIRE(en != nullptr); + CHECK(en->w.empty()); + CHECK(param(en, "wadd") == nullptr); + CHECK(near(pflt(en, "eps"), 1e-5, 1e-12)); + CHECK_EQ(pint(en, "n"), 128); + + /* Layer 0 (sliding) end to end. The block's input norm carries the centered 1+. */ + const size_t at = (size_t)(std::find_if(b.ops.begin(), b.ops.end(), + [](const RecOp& o) { + return o.op == "rmsnorm" && o.w.size() == 1; + }) - b.ops.begin()); + REQUIRE(at + 9 < b.ops.size()); + const RecOp* norm = &b.ops[at]; + CHECK_EQ(norm->w.size(), (size_t)1); + CHECK_EQ(norm->w[0], w_h(b, "blk.0.attn_norm.weight")); + CHECK(near(pflt(norm, "wadd"), 1.0, 1e-12)); + CHECK(near(pflt(norm, "eps"), 1e-5, 1e-12)); + const RecOp* q = &b.ops[at + 1]; + CHECK_EQ(q->op, std::string("gemm_nt")); + CHECK_EQ(pint(q, "N"), world == 1 ? 32 : 8); /* q_dim, the rank's heads */ + CHECK_EQ(pint(q, "K"), 128); + CHECK(q->w == std::vector({ w_h(b, "blk.0.attn_q.weight") })); + /* The q/k norms are weightless; the query carries qk_scale_factor. */ + CHECK_EQ(pint(&b.ops[at + 5], "n"), 8); + CHECK(near(pflt(&b.ops[at + 5], "mult"), 3.87, 1e-6)); + CHECK(b.ops[at + 5].w.empty()); + CHECK_EQ(pint(&b.ops[at + 6], "n"), 8); + CHECK(param(&b.ops[at + 6], "mult") == nullptr); + CHECK(b.ops[at + 6].w.empty()); + /* The rotary, on the sliding layers only, at the sliding theta. */ + const RecOp* rq = find_op(b, "rope"); + REQUIRE(rq != nullptr); + CHECK(near(pflt(rq, "theta"), 500000.0, 1e-9)); + CHECK_EQ(pstr(rq, "mode"), std::string("neox")); + CHECK_EQ(pint(rq, "rotary_dim"), 8); + CHECK_EQ(pint(rq, "head_dim"), 8); + /* The paged attention: a window over the sliding pool, whole-context over the full. */ + const RecOp* sl_attn = find_op(b, "attn_paged"); + REQUIRE(sl_attn != nullptr); + CHECK_EQ(pint(sl_attn, "window"), 4); + CHECK_EQ(pint(sl_attn, "gqa"), world == 1 ? 2 : 1); + CHECK_EQ(pint(sl_attn, "causal"), 1); + int seen = 0; + for (const auto& o : b.ops) { + if (o.op != "attn_paged") continue; + if (seen++ == 3) CHECK_EQ(pint(&o, "window"), 0); + } + CHECK_EQ(seen, 8); + /* Four norms a layer: the two inputs at rms_norm_eps with the centered 1+, the two posts + * at post_norm_eps with it. */ + int post8 = 0; + for (const auto& o : b.ops) + if (o.op == "rmsnorm" && near(pflt(&o, "eps"), 1e-8, 1e-12)) { + CHECK(near(pflt(&o, "wadd"), 1.0, 1e-12)); + ++post8; + } + CHECK_EQ(post8, 16); + /* The concat map rows gate then up, and the weight's two row parts say so. */ + const RecMap* gu = find_map(b, "blk.0.ffn_gate_up.weight"); + REQUIRE(gu != nullptr); + CHECK_EQ(gu->mode, (int)RAD_MAP_CONCAT); + REQUIRE_EQ(gu->src.size(), (size_t)2); + CHECK_EQ(gu->src[0], std::string("model.language_model.layers.0.mlp.gate_proj.weight")); + CHECK_EQ(gu->src[1], std::string("model.language_model.layers.0.mlp.up_proj.weight")); + const RecWeight* guw = find_w(b, "blk.0.ffn_gate_up.weight"); + REQUIRE(guw != nullptr); + REQUIRE_EQ(guw->d.n_row_parts, 2); + CHECK_EQ(guw->d.row_parts[0], 256 / world); /* the rank's feed-forward width */ + CHECK_EQ(guw->d.row_parts[1], 256 / world); + CHECK_EQ(count_op(b, "silu_mul"), 8); + /* The final norm: a plain gain (wadd 0) carrying the logits' pre-scale. The embedding + * norm is the first rmsnorm, six a layer follow, the last is this one. */ + const RecOp* fn = find_op(b, "rmsnorm", 49); + REQUIRE(fn != nullptr); + CHECK(near(pflt(fn, "wadd"), 0.0, 1e-12)); + CHECK(near(pflt(fn, "mult"), 0.19611613513818404, 1e-6)); + /* The head and its cap. */ + const RecOp* cap = find_op(b, "logit_softcap"); + REQUIRE(cap != nullptr); + CHECK(near(pflt(cap, "cap"), 20.0, 1e-12)); + CHECK_EQ(pstr(cap, "dtype"), std::string("f32")); + } +} + +/* ==================================================================== 2. the text steps */ + +/* A decode batch and a prefill chunk: the issue order, and the head over the sampled rows only. */ +TEST(museglimmer_issues_decode_and_prefill_in_order) { + MetaKV mk = muse_meta(); + for (int world : { 1, 4 }) { + RadBuilder b; + RadBuildCtx ctx = muse_ctx(0, world); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + + auto dec = kit(b, { 1, 1, 1, 1 }, {}); + auto v = run_passes(b, museglimmer::step, { dec.get() }, 0, world); + CHECK_PASSES(b, v); + CHECK_EQ(join(issued_ops(b, *v[0])), join(trunk_step(8, world))); + /* The head ran over the four sampled rows, not the step's rows. */ + for (const char* name : { "gather_rows", "logits_gemm", "logit_softcap" }) { + const RecIssue* is = issue_of(b, *v[0], name); + REQUIRE(is != nullptr); + CHECK_EQ(is->n, 4); + } + CHECK_EQ(count_issued(issued_ops(b, *v[0]), "attn_paged"), 8); + CHECK_EQ(count_issued(issued_ops(b, *v[0]), "kv_store"), 8); + + /* A prefill chunk of two 8-token sequences: two sampled rows. */ + auto pf = kit(b, {}, { 8, 8 }); + auto p = run_passes(b, museglimmer::step, { pf.get() }, 0, world); + CHECK_PASSES(b, p); + const RecIssue* pg = issue_of(b, *p[0], "gather_rows"); + REQUIRE(pg != nullptr); + CHECK_EQ(pg->n, 2); + CHECK_EQ(count_issued(issued_ops(b, *p[0]), "logits_gemm"), 1); + } +} + +/* ==================================================================== 3. refusals */ + +/* A layer the schedule rule disagrees with, a rotary table of the wrong length, and a + * non-positive query scale are refused by name, not built into fluent wrong text. A missing + * qk_scale_factor takes the reference config's own default (3.87), which is the family. */ +TEST(museglimmer_refuses_a_trunk_it_does_not_serve) { + const struct { const char* key; const char* val; int rc; } kCases[] = { + /* layer 0 full, where the interval rule puts a window layer */ + { "text_config.layer_types", + "full_attention sliding_attention sliding_attention full_attention sliding_attention " + "sliding_attention sliding_attention full_attention", RAD_E_UNSUPPORTED }, + /* seven rotary bases for eight layers */ + { "text_config.layer_rope_theta", "500000 500000 500000 0 500000 500000 500000", + RAD_E_INVAL }, + { "text_config.qk_scale_factor", "0", RAD_E_INVAL }, + /* a vocabulary the trunk does not know */ + { "text_config.layer_types", + "window_attention sliding_attention sliding_attention full_attention sliding_attention " + "sliding_attention sliding_attention full_attention", RAD_E_UNSUPPORTED }, + }; + for (const auto& kc : kCases) { + MetaKV mk = muse_meta(); + mk.set(kc.key, kc.val); + RadBuilder b; + RadBuildCtx ctx = muse_ctx(0, 1); + const int rc = stderr_of_rc([&] { return museglimmer::declare(&b, mk.meta(), &ctx); }); + if (rc != kc.rc) fprintf(stderr, " %s = %s: rc %d\n", kc.key, kc.val, rc); + CHECK_EQ(rc, kc.rc); + } + /* A routed model is not this family. */ + MetaKV mk = muse_meta(); + RadModelMeta routed = *mk.meta(); + routed.n_expert = 8; + RadBuilder b; + RadBuildCtx ctx = muse_ctx(0, 1); + const int rc = stderr_of_rc([&] { return museglimmer::declare(&b, &routed, &ctx); }); + CHECK_EQ(rc, RAD_E_UNSUPPORTED); +} + +/* ==================================================================== 4. the media declare */ + +/* The tower is declared with the deployment's encoder budget, last, its weights replicated with + * the blocks in their own groups; the full-attention layer bands on the whole pass and the window + * layers on one window; the adapter folds the merge with a view and two activations. */ +TEST(museglimmer_declares_its_vision_tower_when_the_engine_asks_for_it) { + MetaKV mk = with_vision(muse_meta()); + /* Without a budget, nothing: the trunk's graph alone. The probe still names the merge, so + * --mm-max-patches auto rounds to whole merged rows. */ + { + RadBuilder b; + RadBuildCtx ctx = muse_ctx(0, 1, 0); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + CHECK(b.encoder_name.empty()); + CHECK(find_w(b, "v.patch.weight") == nullptr); + CHECK_EQ(count_op(b, "scatter_rows"), 0); + CHECK_EQ(count_op(b, "window_order"), 0); + RadArchProbe p{}; + CHECK_OK(museglimmer::probe(mk.meta(), &p)); + CHECK_EQ(p.enc_merge, 4); + RadArchProbe none{}; + CHECK_OK(museglimmer::probe(muse_meta().meta(), &none)); + CHECK_EQ(none.enc_merge, 0); + } + RadBuilder b; + RadBuildCtx ctx = muse_ctx(0, 1, 64); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + + CHECK_EQ(b.encoder_name, std::string("vision")); + CHECK_EQ(b.encoder.modalities, (uint32_t)(RAD_MM_IMAGE | RAD_MM_VIDEO)); + CHECK_EQ(b.encoder.patch_dim, 1176); /* 3 x patch_temporal 2 x patch 14 squared */ + CHECK_EQ(b.encoder.merge, 4); + CHECK_EQ(b.encoder.max_patches, 64); + CHECK_EQ(b.encoder.n_embd, 128); + const RecBuf* out = find_b(b, "v.out"); + REQUIRE(out != nullptr); + CHECK_EQ(out->d.shape[0], 16); /* 64 patches / merge 2 squared */ + CHECK_EQ(out->d.shape[1], 128); + CHECK_EQ(count_op(b, "scatter_rows"), 1); + + /* The tower's weights, replicated: every one mapped from its checkpoint name, blocks in their + * own groups past the trunk's. */ + for (const auto& w : b.weights) + if (w.name.rfind("v.", 0) == 0) { + const RecMap* mp = find_map(b, w.name); + REQUIRE(mp != nullptr); + for (const auto& s : mp->src) { + const bool tower = s.rfind("model.vision_tower.", 0) == 0; + const bool adapter = s.rfind("model.vision_adapter.", 0) == 0 || + s == "model.vision_projection.weight"; + CHECK(tower || adapter); + } + CHECK_EQ(w.d.shard, (int)RAD_SHARD_NONE); + CHECK(w.d.group.layer == -1 || w.d.group.layer >= 8); + } + const RecWeight* patch = find_w(b, "v.patch.weight"); + REQUIRE(patch != nullptr); + CHECK_EQ(patch->d.shape[0], 96); + CHECK_EQ(patch->d.shape[1], 1176); + const RecWeight* pos = find_w(b, "v.pos.weight"); + REQUIRE(pos != nullptr); + CHECK_EQ(pos->d.shape[0], 16); /* the 4 x 4 position table */ + CHECK_EQ(pos->d.shape[1], 96); + /* The reference's three biased projections, joined q | k | v. */ + const RecMap* qkv = find_map(b, "v.blk.0.qkv.weight"); + REQUIRE(qkv != nullptr); + REQUIRE_EQ(qkv->src.size(), (size_t)3); + CHECK_EQ(qkv->src[0], std::string("model.vision_tower.layers.0.attn.q_proj.weight")); + CHECK_EQ(qkv->src[1], std::string("model.vision_tower.layers.0.attn.k_proj.weight")); + CHECK_EQ(qkv->src[2], std::string("model.vision_tower.layers.0.attn.v_proj.weight")); + const RecWeight* qkvw = find_w(b, "v.blk.0.qkv.weight"); + REQUIRE(qkvw != nullptr); + REQUIRE_EQ(qkvw->d.n_row_parts, 3); + CHECK_EQ(qkvw->d.row_parts[0], 96); + CHECK_EQ(qkvw->d.row_parts[1], 96); + CHECK_EQ(qkvw->d.row_parts[2], 96); + const RecWeight* a1 = find_w(b, "v.mlp.fc1.weight"); + REQUIRE(a1 != nullptr); + CHECK_EQ(a1->d.shape[0], 128); + CHECK_EQ(a1->d.shape[1], 384); /* the merged width, the view's row */ + const RecWeight* a2 = find_w(b, "v.mlp.fc2.weight"); + REQUIRE(a2 != nullptr); + CHECK_EQ(a2->d.shape[0], 128); + CHECK_EQ(a2->d.shape[1], 128); + const RecWeight* vp = find_w(b, "v.proj.weight"); + REQUIRE(vp != nullptr); + CHECK_EQ(vp->d.shape[0], 128); /* the model's width */ + CHECK_EQ(vp->d.shape[1], 128); + const RecWeight* blk1 = find_w(b, "v.blk.1.norm1.weight"); + REQUIRE(blk1 != nullptr); + CHECK_EQ(blk1->d.group.layer, 9); /* the trunk's 8 groups, then the tower's */ + + /* The graph after the trunk: the stem, the order op, four blocks, the un-permute, ln_post and + * the adapter with its two activations. */ + std::vector want = { "gemm_nt", "grid_embed_pad", "layernorm", "window_order", + "gather_rows" }; + for (int l = 0; l < 4; ++l) + for (const char* s : { "layernorm", "gemm_nt_bias", "rope", "attn_dense", + "gemm_nt_bias", "layernorm", "gemm_nt_bias", "gemm_nt_bias" }) + want.push_back(s); + for (const char* s : { "gather_rows", "layernorm", "pixtral_merge", "gemm_nt", "gelu", + "gemm_nt", "gelu", "gemm_nt", "rmsnorm" }) + want.push_back(s); + std::vector tail; + bool trunk_done = false; + for (const auto& o : b.ops) { + if (!trunk_done && o.op == "logit_softcap") { trunk_done = true; continue; } + if (trunk_done) tail.push_back(&o); + } + REQUIRE_EQ(tail.size(), want.size()); + for (size_t i = 0; i < want.size(); ++i) + CHECK_EQ(tail[i]->op, want[i]); + + /* The stem: a bias-less patch GEMM and the padded position resample at ln_pre's epsilon. */ + CHECK_EQ(tail[0]->op, std::string("gemm_nt")); + CHECK_EQ(pint(tail[0], "N"), 96); + CHECK_EQ(pint(tail[0], "K"), 1176); + CHECK(tail[0]->w == std::vector({ w_h(b, "v.patch.weight") })); + const RecOp* gep = tail[1]; + CHECK_EQ(gep->op, std::string("grid_embed_pad")); + CHECK_EQ(pint(gep, "n"), 96); + CHECK_EQ(pint(gep, "side"), 4); + const RecOp* lpre = tail[2]; + CHECK_EQ(pint(lpre, "n"), 96); + CHECK_EQ(pflt(lpre, "eps"), 1e-05); + /* The order op: windows of 4 patches; it reads the batch's arrays and writes its four + * outputs. */ + const RecOp* wo = tail[3]; + CHECK_EQ(pint(wo, "window"), 4); + CHECK(wo->reads.empty()); + CHECK(wo->writes == std::vector({ b_h(b, "v.idx"), b_h(b, "v.inv"), b_h(b, "v.pos"), + b_h(b, "v.cuw") })); + + /* The rotary: axial over the whole head, sections 3 and 3, at the tower's theta. */ + int ropes = 0; + for (const RecOp* o : tail) + if (o->op == "rope") { + ++ropes; + CHECK_EQ(pstr(o, "mode"), std::string("axial")); + CHECK_EQ(pstr(o, "sections"), std::string("3 3")); + CHECK_EQ(pint(o, "head_dim"), 12); + CHECK_EQ(pint(o, "rotary_dim"), 12); + CHECK_EQ(pint(o, "n_head"), 8); + CHECK_EQ(pint(o, "n_head_kv"), 8); + CHECK_EQ(pflt(o, "theta"), 10000.0); + } + CHECK_EQ(ropes, 4); + + /* The attention: non-causal; the three window layers band on one window (4 x 4), the full + * layer on the whole pass. */ + int win_attn = 0, full_attn = 0; + for (const RecOp* o : tail) + if (o->op == "attn_dense") { + CHECK_EQ(pint(o, "causal"), 0); + CHECK_EQ(pint(o, "gqa"), 1); + if (pint(o, "max_seqlen") == 16) ++win_attn; + if (pint(o, "max_seqlen") == 64) ++full_attn; + } + CHECK_EQ(win_attn, 3); + CHECK_EQ(full_attn, 1); + + /* The blocks' MLP: exact-erf gelu in the first linear's epilogue; the adapter's two + * activations are gelu ops of their own. */ + int block_gelu = 0, plain = 0; + for (const RecOp* o : tail) { + if (o->op == "gemm_nt_bias" && pstr(o, "act") == "gelu") ++block_gelu; + if (o->op == "gemm_nt") ++plain; + } + CHECK_EQ(block_gelu, 4); + CHECK_EQ(plain, 4); /* patch, adapter fc1 and fc2, projection */ + CHECK_EQ(count_op(b, "gelu"), 2); + /* The perception norm: weightless, no centered 1+, at the text model's rms_norm_eps. */ + const RecOp* perc = tail.back(); + CHECK_EQ(perc->op, std::string("rmsnorm")); + CHECK(perc->w.empty()); + CHECK(param(perc, "wadd") == nullptr); + CHECK(near(pflt(perc, "eps"), 1e-5, 1e-12)); + CHECK_EQ(pint(perc, "n"), 128); +} + +/* A tower whose config leaves the family is refused by name. */ +TEST(museglimmer_refuses_a_vision_tower_it_does_not_serve) { + const struct { const char* key; const char* val; int rc; } kCases[] = { + { "vision_config.hidden_act", "gelu_pytorch_tanh", RAD_E_UNSUPPORTED }, + { "projector_hidden_act", "gelu_pytorch_tanh", RAD_E_UNSUPPORTED }, + { "vision_config.rope_parameters.rope_type", "linear", RAD_E_UNSUPPORTED }, + /* layer 0 full, where the family rule puts a window layer */ + { "vision_config.layer_types", "full_attention window_attention window_attention " + "window_attention", RAD_E_UNSUPPORTED }, + /* three entries for four blocks */ + { "vision_config.layer_types", "window_attention window_attention window_attention", + RAD_E_INVAL }, + /* the last layer window, where the rule puts the tower's one full layer past the thirds */ + { "vision_config.layer_types", "window_attention window_attention full_attention " + "window_attention", RAD_E_UNSUPPORTED }, + /* the merge op folds a 2x2 block */ + { "vision_config.merge_size", "4", RAD_E_UNSUPPORTED }, + { "out_hidden_size", "256", RAD_E_INVAL }, + { "vision_config.pos_emb_width", "8", RAD_E_INVAL }, + }; + for (const auto& kc : kCases) { + MetaKV mk = with_vision(muse_meta()); + mk.set(kc.key, kc.val); + RadBuilder b; + RadBuildCtx ctx = muse_ctx(0, 1, 64); + const int rc = stderr_of_rc([&] { return museglimmer::declare(&b, mk.meta(), &ctx); }); + if (rc != kc.rc) fprintf(stderr, " %s = %s: rc %d\n", kc.key, kc.val, rc); + CHECK_EQ(rc, kc.rc); + } +} + +/* ==================================================================== 5. the encoder step */ + +/* An encoder pass issues the tower and nothing else, over two 8 x 4 frames (two windows each); + * the rotary reads the order op's positions and each attention its own segment bounds. */ +TEST(a_museglimmer_encoder_pass_issues_the_tower_and_nothing_else) { + MetaKV mk = with_vision(muse_meta()); + RadBuilder b; + RadBuildCtx ctx = muse_ctx(0, 1, 64); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + static uint16_t pix[64 * 1176]; + static int32_t coord[4 * 64]; + for (int64_t i = 0; i < 64; ++i) { + const int64_t in = i % 32; + coord[i * 4 + 0] = (int32_t)(in / 4); /* row */ + coord[i * 4 + 1] = (int32_t)(in % 4); /* column */ + coord[i * 4 + 2] = 8; /* segment height in patches */ + coord[i * 4 + 3] = 4; /* segment width */ + } + static const int32_t cu[] = { 0, 32, 64 }; + static const int32_t sh[] = { 8, 8 }, sw[] = { 4, 4 }; + RadBatch batch{}; + batch.enc = 1; + batch.enc_n_patch = 64; + batch.enc_pixels = pix; + batch.enc_coord = coord; + batch.enc_n_seg = 2; + batch.enc_cu = cu; + batch.enc_seg_h = sh; + batch.enc_seg_w = sw; + batch.enc_max_seg = 32; + RadCtx c{ .b = &b, .batch = &batch }; + c.rank = 0; + c.world = 1; + museglimmer::step(&c, &batch); + CHECK_LINT(b, &c); + CHECK(c.step_fail.empty()); + + /* The issue order is the declare order: the stem, the order op, four blocks, the un-permute, + * ln_post and the adapter. */ + std::vector want = { "gemm_nt", "grid_embed_pad", "layernorm", "window_order", + "gather_rows" }; + for (int l = 0; l < 4; ++l) + for (const char* s : { "layernorm", "gemm_nt_bias", "rope", "attn_dense", "gemm_nt_bias", + "layernorm", "gemm_nt_bias", "gemm_nt_bias" }) + want.push_back(s); + for (const char* s : { "gather_rows", "layernorm", "pixtral_merge", "gemm_nt", "gelu", + "gemm_nt", "gelu", "gemm_nt", "rmsnorm" }) + want.push_back(s); + CHECK_EQ(join(issued_ops(b, c)), join(want)); + /* ln_post and the merge run over all 64 patches; the adapter, projection and perception norm + * over the 16 merged rows. */ + CHECK_EQ(c.issues[c.issues.size() - 8].n, 64); + CHECK_EQ(c.issues[c.issues.size() - 7].n, 64); + CHECK_EQ(c.issues[c.issues.size() - 7].opd[2].rows, 16); /* the merge's output */ + CHECK_EQ(c.issues[c.issues.size() - 2].n, 16); + CHECK_EQ(c.issues.back().n, 16); + + /* The order op reads the [4, P] coordinates and the frame bounds, and writes the four + * outputs; the rotary reads its positions. */ + const RecIssue* wo = issue_of(b, c, "window_order"); + REQUIRE(wo != nullptr); + CHECK_EQ(wo->n, 64); + CHECK(wo->opd[0].raw == coord); + CHECK_EQ(wo->opd[0].rows, 4); + CHECK_EQ(wo->opd[0].cols, 64); + CHECK(wo->opd[1].raw == cu); + CHECK_EQ(wo->opd[1].rows, 3); + CHECK_EQ(wo->opd[2].rows, 64); + CHECK_EQ(wo->opd[2].handle, b_h(b, "v.idx")); + CHECK_EQ(wo->opd[3].handle, b_h(b, "v.inv")); + CHECK_EQ(wo->opd[4].handle, b_h(b, "v.pos")); + CHECK_EQ(wo->opd[5].handle, b_h(b, "v.cuw")); + CHECK_EQ(wo->opd[5].rows, 5); /* four windows, plus the leading 0 */ + const RecIssue* rp = issue_of(b, c, "rope"); + REQUIRE(rp != nullptr); + CHECK_EQ(rp->opd[1].rows, 2); + CHECK_EQ(rp->opd[1].cols, 64); + CHECK_EQ(rp->opd[1].handle, wo->opd[4].handle); /* the order op's positions output */ + /* The window layers read the per-window bounds; the full layer the frame bounds. */ + int at = 0; + for (const auto& is : c.issues) { + const RecOp* o = b.op_of(is.op); + if (!o || o->op != "attn_dense") continue; + if (at < 3) { + CHECK_EQ(is.opd[3].handle, wo->opd[5].handle); + CHECK_EQ(is.opd[3].rows, 5); + } else { + CHECK(is.opd[3].raw == cu); + CHECK_EQ(is.opd[3].rows, 3); + } + CHECK_EQ(is.opd[0].cols, 96); + CHECK_EQ(is.opd[1].offset, 96); + CHECK_EQ(is.opd[2].offset, 192); + ++at; + } + CHECK_EQ(at, 4); + /* The un-permute reads the order op's inverse. */ + const RecIssue* gi = issue_of(b, c, "gather_rows", 1); + REQUIRE(gi != nullptr); + CHECK_EQ(gi->opd[1].handle, wo->opd[3].handle); + /* ln_post writes all 64 patch rows; the merge folds them into 16 rows for the adapter. */ + const RecIssue* lp = issue_of(b, c, "layernorm", 9); /* ln_pre, then two a block, then it */ + REQUIRE(lp != nullptr); + CHECK_EQ(lp->n, 64); + CHECK_EQ(lp->opd[3].rows, 64); + const RecIssue* mg = issue_of(b, c, "pixtral_merge"); + REQUIRE(mg != nullptr); + CHECK_EQ(mg->n, 64); + CHECK_EQ(mg->opd[1].raw, coord); /* the batch's coordinate planes */ + CHECK_EQ(mg->opd[2].rows, 16); + const RecIssue* m1 = issue_of(b, c, "gemm_nt", 1); /* the patch GEMM, then the adapter */ + REQUIRE(m1 != nullptr); + CHECK_EQ(m1->opd[0].rows, 16); + + /* A pass larger than the declaration is refused, not truncated. */ + RadBatch big = batch; + big.enc_n_patch = 2048; + RadCtx c2{ .b = &b, .batch = &big }; + museglimmer::step(&c2, &big); + CHECK(!c2.step_fail.empty()); + CHECK(c2.issues.empty()); +} + +/* A prefill chunk whose tokens 1..4 are a picture's rows: the trunk scatters them over the lookup + * before the embedding's reduction, so the reduction counts each row once. */ +TEST(a_museglimmer_step_with_a_picture_scatters_its_rows_before_the_reduction) { + MetaKV mk = with_vision(muse_meta()); + for (int world : { 1, 4 }) { + RadBuilder b; + RadBuildCtx ctx = muse_ctx(0, world, 64); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + static const int32_t rows[] = { 1, 2, 3, 4 }; + static uint16_t embd[4 * 128]; + auto pf = kit(b, {}, { 6 }); + pf->b.n_mm_rows = 4; + pf->b.mm_rows = rows; + pf->b.mm_embd = embd; + auto v = run_passes(b, museglimmer::step, { pf.get() }, 0, world); + CHECK_PASSES(b, v); + const std::vector ops = issued_ops(b, *v[0]); + REQUIRE(ops.size() > 3); + CHECK_EQ(ops[0], std::string("embed_lookup")); + CHECK_EQ(ops[1], std::string("scatter_rows")); + if (world > 1) CHECK_EQ(ops[2], std::string("all_reduce")); + const RecIssue* sc = issue_of(b, *v[0], "scatter_rows"); + REQUIRE(sc != nullptr); + CHECK_EQ(sc->n, 4); + CHECK(sc->opd[0].raw == embd); + CHECK_EQ(sc->opd[0].cols, 128); + CHECK(sc->opd[1].raw == rows); + CHECK_EQ(sc->opd[2].rows, 6); + /* A text-only step issues no scatter. */ + auto dc = kit(b, { 1, 1 }, {}); + auto t = run_passes(b, museglimmer::step, { dc.get() }, 0, world); + CHECK_PASSES(b, t); + CHECK(issue_of(b, *t[0], "scatter_rows") == nullptr); + } +} +/* ==================================================================== 6. compressed-tensors */ + +namespace { + +/* The quant tests need a wider attention: the asymmetric and int8 grids take K in whole 128s, and + * o_proj's K is the query width (4 heads x 8 = 32 at muse_meta's shape). 32 heads over the same + * 2 KV heads keeps every other line of the family's config. */ +MetaKV muse_meta_quant() { + MetaKV k = muse_meta(); + RadModelMeta m = *k.meta(); + m.n_head = 32; + /* Four KV heads: k and v's rows (heads x head_dim) must come in 16s on the quantised grids, + * and two heads give 8 a rank at world 2. */ + m.n_head_kv = 4; + k = MetaKV(m); + for (const char* pre : { "", "text_config." }) + k.set((std::string(pre) + "layer_types").c_str(), + "sliding_attention sliding_attention sliding_attention full_attention " + "sliding_attention sliding_attention sliding_attention full_attention") + .set((std::string(pre) + "layer_rope_theta").c_str(), + "500000 500000 500000 0 500000 500000 500000 0"); + return k; +} + +/* The asymmetric int4/int5 affine grid the compressed-tensors recipes write: codes u4 or u5, a + * u8 zero point and an f16 scale per [1 x 128] (libquant `codes=u4 zero=u8 group=128 scale=f16`). */ +RadEncoding muse_a4_enc(uint32_t codes) { + RadEncoding e = rad_enc_affine(codes, RAD_F16, 1, rad::arch::RAD_FP8_BLOCK); + rad_enc_add_plane(&e, "zero", RAD_U8, 1, rad::arch::RAD_FP8_BLOCK); + return e; +} + +/* The int8-a-128 grid: i8 codes, a bf16 scale per [1 x 128] (linear_is_w8). */ +RadEncoding muse_i8g_enc() { return rad_enc_affine(RAD_I8, RAD_BF16, 1, rad::arch::RAD_FP8_BLOCK); } + +/* The symmetric grid data/recipes/museglimmer-30b-w4a8.recipe writes: `codes=i4 group=128 + * scale=f16` (the int8 variant `codes=i8 group=128 scale=f16` for the rows int4 hurts). */ +RadEncoding muse_sym_enc(uint32_t codes) { return rad_enc_affine(codes, RAD_F16, 1, 128); } + +/* Every trunk linear's declared-name key, for b.encs. */ +std::vector> muse_linears(const RadEncoding& e) { + return { { "attn_q.", e }, { "attn_gate.", e }, { "attn_k.", e }, + { "attn_v.", e }, { "attn_output.", e }, { "ffn_gate_up.", e }, + { "ffn_down.", e } }; +} + +/* The recipe's rules verbatim: every trunk linear at `rtn codes=i4 group=128 scale=f16 + * rule=search`, attention value at `codes=i8 group=128 scale=f16`. */ +std::vector> muse_recipe_encs() { + std::vector> v = muse_linears(muse_sym_enc(RAD_I4)); + for (auto& [key, e] : v) + if (key == "attn_v.") e = muse_sym_enc(RAD_I8); + return v; +} + +/* The prefill GEMM of one linear: the gemm_nt_q whose codes weight is this weight's. */ +const RecOp* q_gemm_of(const RadBuilder& b, const char* base) { + const RecWeight* w = find_w(b, (std::string(base) + ".weight").c_str()); + if (!w) return nullptr; + for (const RecOp& o : b.ops) + if (o.op == "gemm_nt_q" && o.w.size() == 2 && o.w[0] == w_h(b, w->name.c_str())) + return &o; + return nullptr; +} + +} /* namespace */ + +/* Per layer seven linears, each on the asymmetric u4 grid: quant_act_i8g over the norm output, + * gemm_nt_q at w4a8i8_asym for prefill and the a16 split (an f16 cast, gemm_nt_q at + * w4a16_asym under 64 rows) for decode; the views' planes and shapes; gate, k and v keeping + * their own quantisers (an a4 q writes no pair below its decode band); the fused gate/up concat + * quantised in the checkpoint's row order; a decode step issuing only the f16 band and a 200-row + * prefill only the int8 one. */ +TEST(museglimmer_ct_declares_the_asymmetric_int4_form) { + const RadEncoding e = muse_a4_enc(RAD_U4); + for (int world : { 1, 2 }) { + RadBuilder b; + b.encs = muse_linears(e); + RadBuildCtx ctx = muse_ctx(world - 1, world); + REQUIRE_EQ(museglimmer_ct::declare(&b, muse_meta_quant().meta(), &ctx), RAD_OK); + + /* Per linear: the codes view, the joined scale+zero view, the quantiser, the int8 GEMM, + * the f16 cast and the decode GEMM. */ + CHECK_EQ(count_op(b, "quant_act_i8g"), 56); /* 7 linears x 8 layers */ + CHECK_EQ(count_op(b, "cast"), 56); + int a8 = 0, a16 = 0; + for (const RecOp& o : b.ops) { + if (o.op != "gemm_nt_q") continue; + const std::string dt = pstr(&o, "dtype"); + if (dt == "w4a8i8_asym") { + ++a8; + CHECK_EQ(pint(&o, "group"), (int)rad::arch::RAD_FP8_BLOCK); + } else if (dt == "w4a16_asym") { + ++a16; + const RecParam* m = param(&o, "M"); + REQUIRE(m != nullptr); + CHECK_EQ(m->ihi, 64LL); + } + CHECK(param(&o, "pb1") == nullptr); + } + CHECK_EQ(a8, 56); + CHECK_EQ(a16, 56); + + /* The views: codes u4, the joined scale+zero f16 over the same row. Row-sharded weights + * cut N; o_proj and down are cut along K in whole scale groups. */ + const struct { const char* base; int64_t n, k; bool col; } linears[] = { + { "blk.0.attn_q", 256, 128, false }, { "blk.0.attn_gate", 256, 128, false }, + { "blk.0.attn_k", 32, 128, false }, { "blk.0.attn_v", 32, 128, false }, + { "blk.0.attn_output", 128, 256, true }, { "blk.0.ffn_gate_up", 512, 128, false }, + { "blk.0.ffn_down", 128, 256, true }, + }; + for (const auto& ln : linears) { + const int64_t rows = ln.col ? ln.n : ln.n / world; + const int64_t cols = ln.col ? ln.k / world : ln.k; + const RecWeight* w = find_w(b, (std::string(ln.base) + ".weight").c_str()); + REQUIRE(w != nullptr); + CHECK_EQ(std::string(w->d.planes), std::string("codes")); + CHECK_EQ(w->d.dtype, (uint32_t)RAD_U4); + CHECK_EQ(w->d.shape[0], rows); + CHECK_EQ(w->d.shape[1], cols); + const RecWeight* ws = find_w(b, (std::string(ln.base) + ".scale").c_str()); + REQUIRE(ws != nullptr); + CHECK_EQ(std::string(ws->d.planes), std::string("scale,zero")); + CHECK_EQ(ws->d.dtype, (uint32_t)RAD_F16); + CHECK_EQ(ws->d.shape[0], rows); + CHECK_EQ(ws->d.shape[1], cols); + } + /* The concat map keeps the checkpoint's row order under quant, gate then up, and the + * weight's two row parts say so. */ + const RecMap* gu = find_map(b, "blk.0.ffn_gate_up.weight"); + REQUIRE(gu != nullptr); + REQUIRE_EQ(gu->src.size(), (size_t)2); + CHECK_EQ(gu->src[0], std::string("model.language_model.layers.0.mlp.gate_proj.weight")); + CHECK_EQ(gu->src[1], std::string("model.language_model.layers.0.mlp.up_proj.weight")); + const RecWeight* guw = find_w(b, "blk.0.ffn_gate_up.weight"); + REQUIRE(guw != nullptr); + REQUIRE_EQ(guw->d.n_row_parts, 2); + CHECK_EQ(guw->d.row_parts[0], 256 / world); + CHECK_EQ(guw->d.row_parts[1], 256 / world); + + /* Nothing else quantised: the norms stay f32 gains, the head reads at its codes' dtype + * (bf16 here), the tower is untouched (absent at no budget). */ + CHECK(find_w(b, "blk.0.attn_norm.weight") != nullptr); + CHECK_EQ(find_w(b, "blk.0.attn_norm.weight")->d.dtype, (uint32_t)RAD_F32); + CHECK(find_w(b, "v.patch.weight") == nullptr); + + /* The steps: a decode batch inside the a16 band issues only cast + w4a16_asym per linear; + * a 200-row prefill issues only quant_act_i8g + w4a8i8_asym. */ + auto dec = kit(b, { 1, 1, 1, 1 }, {}); + auto v = run_passes(b, museglimmer_ct::step, { dec.get() }, world - 1, world); + CHECK_PASSES(b, v); + CHECK_LINT(b, v[0].get()); + CHECK(v[0]->step_fail.empty()); + int casts = 0, gemms = 0, quants = 0; + for (const auto& i : v[0]->issues) { + const RecOp* o = b.op_of(i.op); + if (!o) continue; + if (o->op == "cast" && pstr(o, "to") == "f16") ++casts; + if (o->op == "quant_act_i8g") ++quants; + if (o->op == "gemm_nt_q") { + ++gemms; + CHECK_EQ(pstr(o, "dtype"), std::string("w4a16_asym")); + } + } + CHECK_EQ(casts, 56); + CHECK_EQ(gemms, 56); + CHECK_EQ(quants, 0); + + auto pf = kit(b, {}, { 200 }); + auto p = run_passes(b, museglimmer_ct::step, { pf.get() }, world - 1, world); + CHECK_PASSES(b, p); + CHECK_LINT(b, p[0].get()); + CHECK(p[0]->step_fail.empty()); + casts = gemms = quants = 0; + for (const auto& i : p[0]->issues) { + const RecOp* o = b.op_of(i.op); + if (!o) continue; + if (o->op == "cast" && pstr(o, "to") == "f16") ++casts; + if (o->op == "quant_act_i8g") ++quants; + if (o->op == "gemm_nt_q") { + ++gemms; + CHECK_EQ(pstr(o, "dtype"), std::string("w4a8i8_asym")); + } + } + CHECK_EQ(casts, 0); + CHECK_EQ(gemms, 56); + CHECK_EQ(quants, 56); + } +} + +/* gate, k and v quantise q's same norm output on the same per-row grid: on the int8-a-128 grid + * (where the shared pair is written at every height) the later three read q's int8 pair and the + * layer declares one quantiser for the four, k after q. */ +TEST(museglimmer_ct_shares_one_activation_pair_between_q_gate_k_and_v_on_i8g) { + const RadEncoding e = muse_i8g_enc(); + for (int world : { 1, 2 }) { + RadBuilder b; + b.encs = muse_linears(e); + RadBuildCtx ctx = muse_ctx(world - 1, world); + REQUIRE_EQ(museglimmer_ct::declare(&b, muse_meta_quant().meta(), &ctx), RAD_OK); + + /* q, o, gate_up and down keep quantisers; gate, k and v read q's pair. */ + CHECK_EQ(count_op(b, "quant_act_i8g"), 32); /* 4 quantisers x 8 layers */ + CHECK_EQ(count_op(b, "cast"), 0); + int i8 = 0; + for (const RecOp& o : b.ops) + if (o.op == "gemm_nt_q") { + ++i8; + CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8")); + CHECK_EQ(pint(&o, "group"), (int)rad::arch::RAD_FP8_BLOCK); + } + CHECK_EQ(i8, 56); + + /* The views: i8 codes, a bf16 scale per [1 x 128]. */ + const RecWeight* q = find_w(b, "blk.0.attn_q.weight"); + REQUIRE(q != nullptr); + CHECK_EQ(std::string(q->d.planes), std::string("codes")); + CHECK_EQ(q->d.dtype, (uint32_t)RAD_I8); + const RecWeight* qs = find_w(b, "blk.0.attn_q.scale"); + REQUIRE(qs != nullptr); + CHECK_EQ(std::string(qs->d.planes), std::string("scale")); + CHECK_EQ(qs->d.dtype, (uint32_t)RAD_BF16); + CHECK_EQ(qs->d.shape[1], 128 / (int64_t)rad::arch::RAD_FP8_BLOCK); + + /* k after q: k's GEMM reads the pair q's quantiser writes. */ + const RecOp* qdec = q_gemm_of(b, "blk.0.attn_q"); + REQUIRE(qdec != nullptr); + const RecOp* qg = [&] { + for (const RecOp& o : b.ops) + if (o.op == "quant_act_i8g" && o.writes.size() == 2 && + o.writes[0] == qdec->reads[0]) + return &o; + return (const RecOp*)nullptr; + }(); + REQUIRE(qg != nullptr); + CHECK_EQ(qg->writes[0], b_h(b, "blk.0.attn_q.q8")); + CHECK_EQ(qg->writes[1], b_h(b, "blk.0.attn_q.s8")); + for (const char* base : { "blk.0.attn_gate", "blk.0.attn_k", "blk.0.attn_v" }) { + const RecOp* g = q_gemm_of(b, base); + REQUIRE(g != nullptr); + CHECK_EQ(g->reads[0], qdec->reads[0]); + CHECK_EQ(g->reads[1], qdec->reads[1]); + } + /* o_proj, whose input is not q's norm output, keeps its own pair. */ + const RecOp* og = q_gemm_of(b, "blk.0.attn_output"); + REQUIRE(og != nullptr); + CHECK(og->reads[0] != qdec->reads[0]); + + /* The pair is issued once per layer step and all four GEMMs read it. */ + auto dec = kit(b, { 1, 1, 1, 1 }, {}); + auto v = run_passes(b, museglimmer_ct::step, { dec.get() }, world - 1, world); + CHECK_PASSES(b, v); + CHECK_LINT(b, v[0].get()); + CHECK(v[0]->step_fail.empty()); + CHECK_EQ(count_issued(issued_ops(b, *v[0]), "quant_act_i8g"), 32); + CHECK_EQ(count_issued(issued_ops(b, *v[0]), "gemm_nt_q"), 56); + } +} + +/* A container that holds bf16 through the ct plugin: the graph is the bf16 plugin's, op for op, + * every linear a plain gemm_nt -- the descriptor picks the plugin, the encodings pick the ops. */ +TEST(museglimmer_ct_serves_a_bf16_container_as_the_bf16_plugin_does) { + const RadEncoding e = rad_enc_plain(RAD_BF16); + for (int world : { 1, 4 }) { + RadBuilder b; + b.encs = muse_linears(e); + RadBuildCtx ctx = muse_ctx(world - 1, world); + REQUIRE_EQ(museglimmer_ct::declare(&b, muse_meta_quant().meta(), &ctx), RAD_OK); + CHECK_EQ(count_op(b, "gemm_nt"), 56); /* seven linears x eight layers */ + CHECK_EQ(count_op(b, "gemm_nt_q"), 0); + CHECK_EQ(count_op(b, "quant_act_i8g"), 0); + CHECK_EQ(join(op_names(b)), join(trunk_decl(8, world))); + auto dec = kit(b, { 1, 1, 1, 1 }, {}); + auto v = run_passes(b, museglimmer_ct::step, { dec.get() }, world - 1, world); + CHECK_PASSES(b, v); + CHECK_LINT(b, v[0].get()); + CHECK_EQ(join(issued_ops(b, *v[0])), join(trunk_step(8, world))); + } +} + +/* The same grid at five bits: u5 codes, gemm_nt_q at w5a8i8 and the a16 decode band at w5a16. */ +TEST(museglimmer_ct_declares_the_asymmetric_int5_form) { + RadBuilder b; + b.encs = muse_linears(muse_a4_enc(RAD_U5)); + RadBuildCtx ctx = muse_ctx(0, 1); + REQUIRE_EQ(museglimmer_ct::declare(&b, muse_meta_quant().meta(), &ctx), RAD_OK); + int a8 = 0, a16 = 0; + for (const RecOp& o : b.ops) { + if (o.op != "gemm_nt_q") continue; + const std::string dt = pstr(&o, "dtype"); + if (dt == "w5a8i8") ++a8; + if (dt == "w5a16") ++a16; + } + CHECK_EQ(a8, 56); + CHECK_EQ(a16, 56); + const RecWeight* w = find_w(b, "blk.0.attn_q.weight"); + REQUIRE(w != nullptr); + CHECK_EQ(w->d.dtype, (uint32_t)RAD_U5); + auto dec = kit(b, { 1 }, {}); + auto v = run_passes(b, museglimmer_ct::step, { dec.get() }, 0, 1); + CHECK_PASSES(b, v); + for (const auto& i : v[0]->issues) { + const RecOp* o = b.op_of(i.op); + if (o && o->op == "gemm_nt_q") CHECK_EQ(pstr(o, "dtype"), std::string("w5a16")); + } +} + +/* Block fp8 (at a bf16 or an f32 scale) and MXFP4 are forms no plugin of this build serves: a + * linear stored in one is refused by name at declare, as LinearFP8 refuses it elsewhere. */ +TEST(museglimmer_ct_refuses_block_fp8_and_mxfp4_by_name) { + const RadEncoding retired[] = { + rad_enc_affine(RAD_F8E4M3, RAD_BF16, rad::arch::RAD_FP8_BLOCK, rad::arch::RAD_FP8_BLOCK), + rad_enc_affine(RAD_F8E4M3, RAD_F32, rad::arch::RAD_FP8_BLOCK, rad::arch::RAD_FP8_BLOCK), + rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, 32), + }; + for (const RadEncoding& e : retired) { + RadBuilder b; + b.encs = { { "attn_q.", e } }; + RadBuildCtx ctx = muse_ctx(0, 1); + CHECK_EQ(museglimmer_ct::declare(&b, muse_meta_quant().meta(), &ctx), RAD_E_UNSUPPORTED); + CHECK(find_op(b, "gemm_nt_q", 0) == nullptr); + } +} + +/* What the encodings cannot serve is refused naming the weight: a grid outside the forms the + * plugin takes, and a container that quantised a tower weight the recipes never touch -- the + * tower stays bf16 whatever the trunk does. */ +TEST(museglimmer_ct_refuses_encodings_it_does_not_serve_by_name) { + { + RadBuilder b; + RadEncoding bad = rad_enc_affine(RAD_U3, RAD_F16, 1, 128); /* a 3-bit grid */ + b.encs = { { "attn_q.", bad } }; + RadBuildCtx ctx = muse_ctx(0, 1); + const int rc = stderr_of_rc( + [&] { return museglimmer_ct::declare(&b, muse_meta_quant().meta(), &ctx); }); + CHECK_EQ(rc, RAD_E_DTYPE); + } + { + RadBuilder b; + b.encs = { { "vision_tower", muse_a4_enc(RAD_U4) } }; + RadBuildCtx ctx = muse_ctx(0, 1, 64); + const int rc = stderr_of_rc([&] { + return museglimmer_ct::declare(&b, with_vision(muse_meta_quant()).meta(), &ctx); + }); + CHECK_EQ(rc, RAD_E_DTYPE); + } +} + +/* The selection key: this plugin claims (arch museglimmer, quant compressed-tensors). The test TU + * builds with RAD_ARCH_NO_EXPORTS, so the descriptor is asserted where the exports are linked -- + * tests/shipped_plugins_test.cpp wants { "museglimmer", "compressed-tensors" } beside the bf16 + * plugin's { "museglimmer", "" }, and the plugin macro here carries that exact pair. */ +TEST(museglimmer_ct_declares_the_same_family_graph_and_probe_as_the_bf16_plugin) { + RadBuilder b; + RadBuildCtx ctx = muse_ctx(0, 1); + REQUIRE_EQ(museglimmer_ct::declare(&b, muse_meta_quant().meta(), &ctx), RAD_OK); + /* The tower's probe, the family's merge of 4: identical to the bf16 plugin's. */ + RadArchProbe p{}; + CHECK_OK(museglimmer_ct::probe(muse_meta_quant().meta(), &p)); + CHECK_EQ(p.enc_merge, 0); + RadArchProbe pv{}; + CHECK_OK(museglimmer_ct::probe(with_vision(muse_meta_quant()).meta(), &pv)); + CHECK_EQ(pv.enc_merge, 4); + /* The weightless norms, the centered doubles, the soft cap: unchanged under quantisation. + * The first normed rmsnorm is a layer's input norm; its fifth op after is the q norm. */ + const size_t at = (size_t)(std::find_if(b.ops.begin(), b.ops.end(), + [](const RecOp& o) { + return o.op == "rmsnorm" && o.w.size() == 1; + }) - b.ops.begin()); + REQUIRE(at + 5 < b.ops.size()); + CHECK_EQ(b.ops[at + 5].op, std::string("rmsnorm")); + CHECK(b.ops[at + 5].w.empty()); + CHECK(near(pflt(&b.ops[at + 5], "mult"), 3.87, 1e-6)); + const RecOp* fn = find_op(b, "rmsnorm", 49); + REQUIRE(fn != nullptr); + CHECK(near(pflt(fn, "wadd"), 0.0, 1e-12)); + CHECK(near(pflt(fn, "mult"), 0.19611613513818404, 1e-6)); + const RecOp* cap = find_op(b, "logit_softcap"); + REQUIRE(cap != nullptr); + CHECK(near(pflt(cap, "cap"), 20.0, 1e-12)); + /* Two KV groups, every layer bound exactly once, to its group. */ + REQUIRE_EQ(b.binds.size(), (size_t)8); + const rad_kvgroup win = 1, full = 2; + for (int l = 0; l < 8; ++l) { + CHECK_EQ(b.binds[(size_t)l].first, l); + CHECK_EQ(b.binds[(size_t)l].second, (rad_kvgroup)((l % 4 == 3) ? full : win)); + } +} + +/* The recipe's grid, rule for rule (museglimmer-30b-w4a8.recipe): every trunk linear at + * `codes=i4 group=128 scale=f16`, attention value at `codes=i8 group=128 scale=f16`. Each linear + * is gemm_nt_q at w4a8 (w8a8 for v) over quant_act_i8's per-row int8 pair; gate, k and v read + * q's pair (one quantiser for the four, k after q); the views are codes at [out, in] and an f16 + * scale per 128 columns; a step issues the quantiser at every height (no decode band here). */ +TEST(museglimmer_ct_serves_the_w4a8_recipe_grid_symmetric_i4_and_i8) { + for (int world : { 1, 2 }) { + RadBuilder b; + b.encs = muse_recipe_encs(); + RadBuildCtx ctx = muse_ctx(world - 1, world); + REQUIRE_EQ(museglimmer_ct::declare(&b, muse_meta_quant().meta(), &ctx), RAD_OK); + + /* q, o, gate_up and down keep quantisers; gate, k and v read q's pair. */ + CHECK_EQ(count_op(b, "quant_act_i8"), 32); + CHECK_EQ(count_op(b, "quant_act_i8g"), 0); + CHECK_EQ(count_op(b, "cast"), 0); + int w4 = 0, w8 = 0; + for (const RecOp& o : b.ops) { + if (o.op != "gemm_nt_q") continue; + const std::string dt = pstr(&o, "dtype"); + if (dt == "w4a8") ++w4; + if (dt == "w8a8") ++w8; + CHECK_EQ(pint(&o, "group"), 128); + } + CHECK_EQ(w4, 48); /* six i4 linears x eight layers */ + CHECK_EQ(w8, 8); /* attention value, the recipe's int8 row */ + + /* The views: i4 codes for the i4 linears, i8 for v; an f16 scale per 128 columns. */ + const struct { const char* base; int64_t n, k; bool col; uint32_t dt; } linears[] = { + { "blk.0.attn_q", 256, 128, false, RAD_I4 }, + { "blk.0.attn_gate", 256, 128, false, RAD_I4 }, + { "blk.0.attn_k", 32, 128, false, RAD_I4 }, + { "blk.0.attn_v", 32, 128, false, RAD_I8 }, + { "blk.0.attn_output", 128, 256, true, RAD_I4 }, + { "blk.0.ffn_gate_up", 512, 128, false, RAD_I4 }, + { "blk.0.ffn_down", 128, 256, true, RAD_I4 }, + }; + for (const auto& ln : linears) { + const int64_t rows = ln.col ? ln.n : ln.n / world; + const int64_t cols = ln.col ? ln.k / world : ln.k; + const RecWeight* w = find_w(b, (std::string(ln.base) + ".weight").c_str()); + REQUIRE(w != nullptr); + CHECK_EQ(std::string(w->d.planes), std::string("codes")); + CHECK_EQ(w->d.dtype, (uint32_t)ln.dt); + CHECK_EQ(w->d.shape[0], rows); + CHECK_EQ(w->d.shape[1], cols); + const RecWeight* ws = find_w(b, (std::string(ln.base) + ".scale").c_str()); + REQUIRE(ws != nullptr); + CHECK_EQ(std::string(ws->d.planes), std::string("scale")); + CHECK_EQ(ws->d.dtype, (uint32_t)RAD_F16); + CHECK_EQ(ws->d.shape[0], rows); + CHECK_EQ(ws->d.shape[1], cols / 128); + } + + /* k after q: k's GEMM reads the pair q's quantiser writes. */ + const RecOp* qdec = q_gemm_of(b, "blk.0.attn_q"); + REQUIRE(qdec != nullptr); + for (const char* base : { "blk.0.attn_gate", "blk.0.attn_k", "blk.0.attn_v" }) { + const RecOp* g = q_gemm_of(b, base); + REQUIRE(g != nullptr); + CHECK_EQ(g->reads[0], qdec->reads[0]); + CHECK_EQ(g->reads[1], qdec->reads[1]); + } + + /* A step quantises at every height: the symmetric grid has no decode band. */ + auto dec = kit(b, { 1, 1, 1, 1 }, {}); + auto v = run_passes(b, museglimmer_ct::step, { dec.get() }, world - 1, world); + CHECK_PASSES(b, v); + CHECK_LINT(b, v[0].get()); + CHECK(v[0]->step_fail.empty()); + CHECK_EQ(count_issued(issued_ops(b, *v[0]), "quant_act_i8"), 32); + int gemms = 0; + for (const auto& i : v[0]->issues) { + const RecOp* o = b.op_of(i.op); + if (o && o->op == "gemm_nt_q") ++gemms; + } + CHECK_EQ(gemms, 56); + } +} + +/* The recipe's documented int8 variant (`codes=i8 group=128 scale=f16` for a whole trunk): every + * linear at w8a8 on the same views. */ +TEST(museglimmer_ct_serves_the_symmetric_int8_variant) { + RadBuilder b; + b.encs = muse_linears(muse_sym_enc(RAD_I8)); + RadBuildCtx ctx = muse_ctx(0, 1); + REQUIRE_EQ(museglimmer_ct::declare(&b, muse_meta_quant().meta(), &ctx), RAD_OK); + int w8 = 0; + for (const RecOp& o : b.ops) { + if (o.op != "gemm_nt_q") continue; + CHECK_EQ(pstr(&o, "dtype"), std::string("w8a8")); + ++w8; + } + CHECK_EQ(w8, 56); + const RecWeight* w = find_w(b, "blk.0.attn_q.weight"); + REQUIRE(w != nullptr); + CHECK_EQ(w->d.dtype, (uint32_t)RAD_I8); + auto dec = kit(b, { 1 }, {}); + auto v = run_passes(b, museglimmer_ct::step, { dec.get() }, 0, 1); + CHECK_PASSES(b, v); + for (const auto& i : v[0]->issues) { + const RecOp* o = b.op_of(i.op); + if (o && o->op == "gemm_nt_q") CHECK_EQ(pstr(o, "dtype"), std::string("w8a8")); + } +} + +/* ==================================================================== 6b. an IQ8R trunk */ + +namespace { + +/* IQ8R as libquant states it (`codes=i8 group=256 scale=u8 scale2=bf16 block2=1x* + * transform=fwht128`): int8 codes rotated 128 wide, a u8 scale per [1 x 256] of K under one bf16 + * scale a row (linear_is_iq8r). */ +RadEncoding muse_iq8r_enc() { + RadEncoding e = rad_enc_affine(RAD_I8, RAD_U8, 1, rad::arch::RAD_I8_GROUP_WIDE); + rad_enc_add_plane(&e, "scale.1", RAD_BF16, 1, 0); + rad_enc_copy_str(e.transform, "fwht128"); + return e; +} + +/* data/recipes/museglimmer-30b-iq8r.recipe's encodings by declared name: the seven trunk linears + * IQ8R, the head plain int8 at a bf16 scale per [1 x 128]. The head comes last because + * `output.weight` is in `attn_output.weight`. */ +std::vector> muse_iq8r_encs() { + std::vector> v = muse_linears(muse_iq8r_enc()); + v.push_back({ "output.weight", rad_enc_affine(RAD_I8, RAD_BF16, 1, rad::arch::RAD_FP8_BLOCK) }); + return v; +} + +/* The trunk at widths IQ8R's 256-column group divides at one rank and at two: hidden 256, + * attention 64 heads x 8 = 512, feed-forward 512; four KV heads keep k and v in 16-row tiles a + * rank. Every other line of the family's config is muse_meta_quant's. */ +MetaKV muse_meta_iq8r() { + MetaKV k = muse_meta(); + RadModelMeta m = *k.meta(); + m.n_embd = 256; + m.n_head = 64; + m.n_head_kv = 4; + m.n_ff = 512; + k = MetaKV(m); + for (const char* pre : { "", "text_config." }) + k.set((std::string(pre) + "layer_types").c_str(), + "sliding_attention sliding_attention sliding_attention full_attention " + "sliding_attention sliding_attention sliding_attention full_attention") + .set((std::string(pre) + "layer_rope_theta").c_str(), + "500000 500000 500000 0 500000 500000 500000 0"); + return k; +} + +/* The op that writes buffer `buf` first among the ops named `name`. */ +const RecOp* writer_of(const RadBuilder& b, const char* name, rad_buf buf) { + for (const RecOp& o : b.ops) + if (o.op == name && in(o.writes, buf)) return &o; + return nullptr; +} + +} /* namespace */ + +/* The IQ8R container at one rank and at two: every trunk linear gemm_nt_q at i8a8h, group 256, over + * the codes view (i8 [N, K]) and one "scale,scale.1" u8 view at the logical [N, K]; both pre-norms + * rmsnorm_had_quant_i8g (centered, at rms_norm_eps, no residual, no all-reduce form at two ranks: + * the collectives feed the post norms) writing the pair q, gate, k, v and gate/up read; the gated + * product gated_had_quant_i8g writing down_proj's pair and no bf16 product; o_proj's own + * had_quant_act_i8g over the gated attention output; the head plain int8. No other quantiser, no + * E4M3 plane, no bf16 GEMM. Decode and prefill issue that graph lint-clean. */ +TEST(museglimmer_ct_serves_an_iq8r_trunk) { + for (int world : { 1, 2 }) + for (int rank = 0; rank < world; ++rank) { + RadBuilder b; + b.encs = muse_iq8r_encs(); + RadBuildCtx ctx = muse_ctx(rank, world); + REQUIRE_EQ(museglimmer_ct::declare(&b, muse_meta_iq8r().meta(), &ctx), RAD_OK); + const museglimmer_ct::Model& m = museglimmer_ct::g_model[rad_build_slot(&ctx)]; + CHECK(m.iq8r); + CHECK(m.a_h.q8_fed); + CHECK(m.a_ffn.q8_fed); + CHECK(!m.a_attn.q8_fed); + + const int64_t E = 256, Q = 512 / world, KV = 32 / world, F = 512 / world; + const rad_buf hq = (rad_buf)b_h(b, "h.q8"), hs = (rad_buf)b_h(b, "h.s8"); + const rad_buf aq = (rad_buf)b_h(b, "attn_out.q8"), as = (rad_buf)b_h(b, "attn_out.s8"); + const rad_buf fq = (rad_buf)b_h(b, "ffn.q8"), fs = (rad_buf)b_h(b, "ffn.s8"); + REQUIRE(hq && hs && aq && as && fq && fs); + /* One f32 scale a (row, 256). */ + CHECK_EQ(find_b(b, "h.s8")->d.shape[1], E / 256); + CHECK_EQ(find_b(b, "attn_out.s8")->d.shape[1], Q / 256); + CHECK_EQ(find_b(b, "ffn.s8")->d.shape[1], F / 256); + for (const char* none : { "h.q", "h.s", "attn_out.q", "ffn.q" }) + CHECK(find_b(b, none) == nullptr); + + /* Seven GEMMs a layer, all i8a8h at group 256; nothing bf16 in the trunk. */ + CHECK_EQ(count_op(b, "gemm_nt_q"), 56); + CHECK_EQ(count_op(b, "gemm_nt"), 0); + for (const RecOp& o : b.ops) + if (o.op == "gemm_nt_q") { + CHECK_EQ(pstr(&o, "dtype"), std::string("i8a8h")); + CHECK_EQ(pint(&o, "group"), 256); + } + + /* The producers: two rotating norms, one gated quantiser and o_proj's quantiser a + * layer, each at group 256 over its row's width. */ + CHECK_EQ(count_op(b, "rmsnorm_had_quant_i8g"), 16); + CHECK_EQ(count_op(b, "ar_rmsnorm_had_quant_i8g"), 0); + CHECK_EQ(count_op(b, "gated_had_quant_i8g"), 8); + CHECK_EQ(count_op(b, "had_quant_act_i8g"), 8); + for (const char* op : { "quant_act_i8g", "quant_act_i8", "quant_act_fp8", + "rmsnorm_quant_fp8", "gated_quant_fp8", "silu_mul", "cast", + "gemm_nt_q_gated" }) + CHECK_EQ(count_op(b, op), 0); + const int64_t w_attn_norm = w_h(b, "blk.0.attn_norm.weight"); + const int64_t w_ffn_norm = w_h(b, "blk.0.ffn_norm.weight"); + int norms = 0; + for (const RecOp& o : b.ops) { + if (o.op == "rmsnorm_had_quant_i8g") { + CHECK_EQ(pint(&o, "n"), E); + CHECK_EQ(pint(&o, "group"), 256); + CHECK(near(pflt(&o, "wadd"), 1.0, 1e-12)); + CHECK(near(pflt(&o, "eps"), 1e-5, 1e-9)); + REQUIRE_EQ(o.reads.size(), (size_t)1); /* the stream, no residual */ + CHECK_EQ(o.reads[0], (rad_buf)b_h(b, "x")); + REQUIRE_EQ(o.writes.size(), (size_t)3); + CHECK_EQ(o.writes[0], hq); + CHECK_EQ(o.writes[1], hs); + CHECK_EQ(o.writes[2], (rad_buf)b_h(b, "h")); + if (norms == 0) CHECK_EQ((int64_t)o.w[0], w_attn_norm); + if (norms == 1) CHECK_EQ((int64_t)o.w[0], w_ffn_norm); + ++norms; + } + if (o.op == "gated_had_quant_i8g") { + CHECK_EQ(pint(&o, "n"), F); + CHECK_EQ(pint(&o, "group"), 256); + CHECK_EQ(pstr(&o, "act"), std::string("silu")); + CHECK(in(o.reads, (rad_buf)b_h(b, "gate_up"))); + REQUIRE_EQ(o.writes.size(), (size_t)2); /* codes only */ + CHECK_EQ(o.writes[0], fq); + CHECK_EQ(o.writes[1], fs); + } + if (o.op == "had_quant_act_i8g") { + CHECK_EQ(pint(&o, "n"), Q); + CHECK_EQ(pint(&o, "group"), 256); + CHECK(in(o.reads, (rad_buf)b_h(b, "attn_out"))); + CHECK(in(o.writes, aq)); + CHECK(in(o.writes, as)); + } + } + CHECK_EQ(norms, 16); + /* The post norms and the final norm stay plain rmsnorm (with the q/k norms). */ + for (const RecOp& o : b.ops) + if (o.op == "rmsnorm" && o.w.size() == 1) + CHECK((int64_t)o.w[0] != w_attn_norm && (int64_t)o.w[0] != w_ffn_norm); + + /* The views and the pair each GEMM reads. */ + const struct { const char* base; int64_t n, k; bool col; rad_buf q, s; } linears[] = { + { "blk.0.attn_q", 512, 256, false, hq, hs }, + { "blk.0.attn_gate", 512, 256, false, hq, hs }, + { "blk.0.attn_k", 32, 256, false, hq, hs }, + { "blk.0.attn_v", 32, 256, false, hq, hs }, + { "blk.0.attn_output", 256, 512, true, aq, as }, + { "blk.0.ffn_gate_up", 1024, 256, false, hq, hs }, + { "blk.0.ffn_down", 256, 512, true, fq, fs }, + }; + for (const auto& ln : linears) { + const int64_t rows = ln.col ? ln.n : ln.n / world; + const int64_t cols = ln.col ? ln.k / world : ln.k; + const RecWeight* w = find_w(b, (std::string(ln.base) + ".weight").c_str()); + REQUIRE(w != nullptr); + CHECK_EQ(std::string(w->d.planes), std::string("codes")); + CHECK_EQ(w->d.dtype, (uint32_t)RAD_I8); + CHECK_EQ(w->d.shape[0], rows); + CHECK_EQ(w->d.shape[1], cols); + const RecWeight* ws = find_w(b, (std::string(ln.base) + ".scale").c_str()); + REQUIRE(ws != nullptr); + CHECK_EQ(std::string(ws->d.planes), std::string("scale,scale.1")); + CHECK_EQ(ws->d.dtype, (uint32_t)RAD_U8); + CHECK_EQ(ws->d.shape[0], rows); + CHECK_EQ(ws->d.shape[1], cols); + const RecOp* gm = q_gemm_of(b, ln.base); + REQUIRE(gm != nullptr); + CHECK_EQ(pint(gm, "N"), rows); + CHECK_EQ(pint(gm, "K"), cols); + REQUIRE_EQ(gm->reads.size(), (size_t)2); + CHECK_EQ(gm->reads[0], ln.q); + CHECK_EQ(gm->reads[1], ln.s); + } + CHECK_EQ(Q, pint(q_gemm_of(b, "blk.0.attn_q"), "N")); + CHECK_EQ(KV, pint(q_gemm_of(b, "blk.0.attn_k"), "N")); + /* gate|up in the checkpoint's row order, two row parts a rank. */ + const RecMap* gu = find_map(b, "blk.0.ffn_gate_up.weight"); + REQUIRE(gu != nullptr); + REQUIRE_EQ(gu->src.size(), (size_t)2); + CHECK_EQ(gu->src[0], std::string("model.language_model.layers.0.mlp.gate_proj.weight")); + CHECK_EQ(gu->src[1], std::string("model.language_model.layers.0.mlp.up_proj.weight")); + const RecWeight* guw = find_w(b, "blk.0.ffn_gate_up.weight"); + REQUIRE(guw != nullptr); + REQUIRE_EQ(guw->d.n_row_parts, 2); + CHECK_EQ(guw->d.row_parts[0], F); + CHECK_EQ(guw->d.row_parts[1], F); + /* Layer 0's q is mapped once, by the trunk probe. */ + int qmaps = 0; + for (const RecMap& mp : b.maps) qmaps += mp.declared == "blk.0.attn_q.weight"; + CHECK_EQ(qmaps, 1); + + /* The head: plain int8, read by logits_gemm; the norms stay f32 gains. */ + const RecWeight* head = find_w(b, "output.weight"); + REQUIRE(head != nullptr); + CHECK_EQ(head->d.dtype, (uint32_t)RAD_I8); + const RecOp* lg = find_op(b, "logits_gemm"); + REQUIRE(lg != nullptr); + REQUIRE_EQ(lg->w.size(), (size_t)1); + CHECK_EQ((int64_t)lg->w[0], w_h(b, "output.weight")); + CHECK_EQ(find_w(b, "blk.0.attn_norm.weight")->d.dtype, (uint32_t)RAD_F32); + + /* Decode and a 200-row prefill issue every producer and GEMM once a layer. */ + for (int pass = 0; pass < 2; ++pass) { + auto k = pass == 0 ? kit(b, { 1, 1, 1, 1 }, {}) : kit(b, {}, { 200 }); + auto v = run_passes(b, museglimmer_ct::step, { k.get() }, rank, world); + CHECK_PASSES(b, v); + CHECK_LINT(b, v[0].get()); + CHECK(v[0]->step_fail.empty()); + const std::vector is = issued_ops(b, *v[0]); + CHECK_EQ(count_issued(is, "rmsnorm_had_quant_i8g"), 16); + CHECK_EQ(count_issued(is, "gated_had_quant_i8g"), 8); + CHECK_EQ(count_issued(is, "had_quant_act_i8g"), 8); + CHECK_EQ(count_issued(is, "gemm_nt_q"), 56); + CHECK_EQ(count_issued(is, "all_reduce"), world > 1 ? 1 + 16 : 0); + } + } +} + +/* Where no loaded library declares the rotating norm or the rotating gated product (the CPU + * kernels), the plain norm and silu_mul run and the first linear reading each input quantises it + * with had_quant_act_i8g at group 256: q (gate, k and v read its pair), gate/up, o_proj and + * down_proj, four a layer. */ +TEST(museglimmer_ct_iq8r_quantises_its_inputs_without_the_rotating_producers) { + for (int world : { 1, 2 }) { + RadBuilder b; + b.undeclared = { "rmsnorm_had_quant_i8g", "gated_had_quant_i8g" }; + b.encs = muse_iq8r_encs(); + RadBuildCtx ctx = muse_ctx(world - 1, world); + REQUIRE_EQ(museglimmer_ct::declare(&b, muse_meta_iq8r().meta(), &ctx), RAD_OK); + const museglimmer_ct::Model& m = museglimmer_ct::g_model[rad_build_slot(&ctx)]; + CHECK(m.iq8r); + CHECK(!m.a_h.q8_fed); + CHECK(!m.a_ffn.q8_fed); + CHECK_EQ(count_op(b, "rmsnorm_had_quant_i8g"), 0); + CHECK_EQ(count_op(b, "gated_had_quant_i8g"), 0); + CHECK_EQ(count_op(b, "silu_mul"), 8); + CHECK_EQ(count_op(b, "had_quant_act_i8g"), 32); + for (const RecOp& o : b.ops) + if (o.op == "had_quant_act_i8g") CHECK_EQ(pint(&o, "group"), 256); + CHECK_EQ(count_op(b, "gemm_nt_q"), 56); + + /* q's quantiser writes the pair gate, k and v read. */ + const rad_buf hq = (rad_buf)b_h(b, "h.q8"); + const RecOp* qq = writer_of(b, "had_quant_act_i8g", hq); + REQUIRE(qq != nullptr); + CHECK(in(qq->reads, (rad_buf)b_h(b, "h"))); + for (const char* base : { "blk.0.attn_q", "blk.0.attn_gate", "blk.0.attn_k", + "blk.0.attn_v", "blk.0.ffn_gate_up" }) { + const RecOp* gm = q_gemm_of(b, base); + REQUIRE(gm != nullptr); + CHECK_EQ(gm->reads[0], hq); + } + const RecOp* dq = writer_of(b, "had_quant_act_i8g", (rad_buf)b_h(b, "ffn.q8")); + REQUIRE(dq != nullptr); + CHECK(in(dq->reads, (rad_buf)b_h(b, "ffn"))); + + auto k = kit(b, { 1, 1, 1, 1 }, {}); + auto v = run_passes(b, museglimmer_ct::step, { k.get() }, world - 1, world); + CHECK_PASSES(b, v); + CHECK_LINT(b, v[0].get()); + CHECK_EQ(count_issued(issued_ops(b, *v[0]), "had_quant_act_i8g"), 32); + CHECK_EQ(count_issued(issued_ops(b, *v[0]), "gemm_nt_q"), 56); + } +} + +/* An IQ8R trunk is IQ8R in every trunk linear, and its widths take whole 256-column groups. Refused + * by name: an IQ8R trunk with one linear on the 128-group int8 grid or left bf16, an IQ8R linear + * under a trunk whose layer 0 q is not IQ8R, an IQ8R-shaped weight at the wrong group (not IQ8R, + * so no form matches), and a model whose hidden width 256 does not divide. */ +TEST(museglimmer_ct_refuses_a_mixed_or_malformed_iq8r_trunk) { + MetaKV mk = muse_meta_iq8r(); + auto declare_rc = [&](const std::vector>& encs, + const RadModelMeta* meta) { + RadBuilder b; + b.encs = encs; + RadBuildCtx ctx = muse_ctx(0, 1); + return stderr_of_rc([&] { return museglimmer_ct::declare(&b, meta, &ctx); }); + }; + { + auto e = muse_iq8r_encs(); + for (auto& [key, enc] : e) + if (key == "attn_v.") enc = muse_i8g_enc(); + CHECK_EQ(declare_rc(e, mk.meta()), RAD_E_DTYPE); + } + { + auto e = muse_iq8r_encs(); + for (auto& [key, enc] : e) + if (key == "ffn_down.") enc = rad_enc_plain(RAD_BF16); + CHECK_EQ(declare_rc(e, mk.meta()), RAD_E_DTYPE); + } + { + auto e = muse_linears(rad_enc_plain(RAD_BF16)); + for (auto& [key, enc] : e) + if (key == "attn_output.") enc = muse_iq8r_enc(); + CHECK_EQ(declare_rc(e, mk.meta()), RAD_E_DTYPE); + } + { + RadEncoding bad = rad_enc_affine(RAD_I8, RAD_U8, 1, rad::arch::RAD_FP8_BLOCK); + rad_enc_add_plane(&bad, "scale.1", RAD_BF16, 1, 0); + rad_enc_copy_str(bad.transform, "fwht128"); + CHECK_EQ(declare_rc(muse_linears(bad), mk.meta()), RAD_E_DTYPE); + } + CHECK_EQ(declare_rc(muse_iq8r_encs(), muse_meta_quant().meta()), RAD_E_UNSUPPORTED); +} + +/* ==================================================================== 6. the DFlash drafter */ + +/* The container's `draft.` config for the assistant (`muse-glimmer-assistant`): two plain + * attention layers that denoise a block of four (the anchor plus three masks, three drafts), the + * trunk's residual tapped after layers 1, 3 and 5. Heads run wider than the trunk fixture's so + * the recipe's quantised grids fit their scale blocks a rank at a time (the trunk fixture's two + * KV heads leave k and v eight rows a rank at tp 2, which no quantised form serves). */ +MetaKV muse_draft_meta() { + MetaKV k = muse_meta(); + k.set("draft.num_hidden_layers", "2") + .set("draft.head_dim", "32") + .set("draft.num_attention_heads", "32") + .set("draft.num_key_value_heads", "8") + .set("draft.intermediate_size", "512") + .set("draft.rms_norm_eps", "1e-5") + .set("draft.rope_theta", "500000") + .set("draft.block_size", "4") + .set("draft.target_layer_ids", "1 3 5") + .set("draft.mask_token_id", "511"); + return k; +} + +/* The recipe's drafter grid (the dspark rules of museglimmer-30b-modelopt-nvfp4.recipe, what the + * shipped `*-dflash-fp4.rad` carries): attention at block fp8 e4m3*bf16[128x128], fc and the + * MLPs at MXFP4 e2m1*e8m0[1x32], the head the trunk's own. */ +std::vector> muse_draft_encs() { + const RadEncoding fp8 = rad_enc_affine(RAD_F8E4M3, RAD_BF16, rad::arch::RAD_FP8_BLOCK, + rad::arch::RAD_FP8_BLOCK); + const RadEncoding mx = rad_enc_affine(RAD_FP4E2M1, RAD_E8M0, 1, rad::arch::RAD_MX_GROUP); + return { { "dspark.fc.", mx }, { "attn_q.", fp8 }, { "attn_k.", fp8 }, + { "attn_v.", fp8 }, { "attn_output.", fp8 }, { "ffn_gate_up.", mx }, + { "ffn_down.", mx } }; +} + +/* The block embeds from the trunk's vocab-sharded table, so its lookup is partial at tp > 1: + * every row whose token sits in another rank's slice reads zero -- and the block's rows are one + * sampled token plus masks whose one id lives on a single rank. So the query pass reduces the + * lookup exactly, right after `embed_lookup` (the trunk's own embedding reduce, and dflash2's and + * dspark's), and the context pass -- k and v from row-split weights over the replicated taps -- + * runs no collective at all. tp 1 declares none of it. */ +TEST(muse_dflash_reduces_the_sharded_embedding_before_the_block) { + MetaKV mk = muse_draft_meta(); + for (int world : { 1, 2 }) { + RadBuilder b; + RadBuildCtx ctx = spec_ctx(world - 1, world, 3); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + + /* One engine step, as the scheduler drives it: the trunk's step, the drafter's context + * pass over what the trunk committed, the query pass over the staged block. */ + auto trunk = kit(b, { 1, 1 }, {}); + auto hp = context_pass(b, *trunk); + auto qp = query_pass(b, 1, 4, 3); + auto v = run_passes(b, museglimmer::step, { trunk.get(), hp.get(), qp.get() }, + world - 1, world); + CHECK_PASSES(b, v); + + /* The context pass projects and stores k and v; nothing it runs is a partial sum. */ + const auto ci = issued_ops(b, *v[1]); + CHECK_EQ(count_issued(ci, "all_reduce"), 0); + CHECK_EQ(count_issued(ci, "embed_lookup"), 0); + + /* The query pass: the reduce directly after the lookup, before the block's layers; the + * per-layer reduces behind o and down; the ranks' logits gathered for the draft's argmax. + * At tp 1 none of it. */ + const auto qi = issued_ops(b, *v[2]); + REQUIRE(qi.size() >= 2); + CHECK_EQ(qi[0], std::string("embed_lookup")); + CHECK_EQ(qi[1], std::string(world > 1 ? "all_reduce" : "cast")); + CHECK_EQ(count_issued(qi, "all_reduce"), world > 1 ? 5 : 0); /* embed + 2 a layer */ + CHECK_EQ(count_issued(qi, "all_gather"), world > 1 ? 1 : 0); + if (world > 1) { + /* Exact, over the block's embedded rows, in place. */ + const RecIssue* ar = issue_of(b, *v[2], "all_reduce", 0); + REQUIRE(ar != nullptr); + const RecOp* o = b.op_of(ar->op); + REQUIRE(o != nullptr); + CHECK_EQ(pint(o, "exact"), 1); + CHECK_EQ(pint(o, "world_size"), world); + CHECK_EQ(pstr(o, "dtype"), std::string("bf16")); + REQUIRE(!o->reads.empty()); + CHECK_EQ(o->reads[0], b_h(b, "ds_h")); + CHECK_EQ(o->writes[0], b_h(b, "ds_h")); + } + /* The walk's winner lands in the proposal buffer the core reads. */ + const RecIssue* tk = issue_of(b, *v[2], "row_topk", 0); + REQUIRE(tk != nullptr); + CHECK_EQ(tk->opd[1].kind, (uint8_t)RAD_OPK_BUF); + CHECK_EQ(tk->opd[1].handle, b.drafter.proposal); + /* The head scores the rows `out_ids` names, gathered into `hg`: with several sequences + * staged, "the last S rows" of the block would drop each sequence's first mask row and + * score its neighbour's anchor, whose logits pose as that sequence's first draft. */ + CHECK_EQ(count_issued(qi, "gather_rows"), 1); + const RecIssue* lg = issue_of(b, *v[2], "logits_gemm", 0); + REQUIRE(lg != nullptr); + const RecOp* lgop = b.op_of(lg->op); + REQUIRE(lgop != nullptr); + REQUIRE(!lgop->reads.empty()); + CHECK_EQ(lgop->reads[0], b_h(b, "ds_hg")); + } + /* Two drafting sequences: the gather still takes the rows `out_ids` names -- the fake names + * rows 1..3 and 5..7 of the eight staged -- and the pass lints clean. */ + { + RadBuilder b; + RadBuildCtx ctx = spec_ctx(1, 2, 3); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + auto trunk = kit(b, { 1, 1 }, {}); + auto hp = context_pass(b, *trunk); + auto qp = query_pass(b, 2, 4, 3); + auto v = run_passes(b, museglimmer::step, { trunk.get(), hp.get(), qp.get() }, 1, 2); + CHECK_PASSES(b, v); + const auto qi = issued_ops(b, *v[2]); + CHECK_EQ(count_issued(qi, "gather_rows"), 1); + CHECK_EQ(count_issued(qi, "logits_gemm"), 1); + } +} + +/* A drafter converted to block fp8 attention and MXFP4 MLPs (the grid of the NVFP4 release's + * conversion) is refused with the trunk at declare: neither form is served. */ +TEST(muse_dflash_refuses_a_block_fp8_and_mxfp4_drafter) { + MetaKV mk = muse_draft_meta(); + for (int world : { 1, 2 }) { + RadBuilder b; + b.encs = muse_draft_encs(); + RadBuildCtx ctx = spec_ctx(world - 1, world, 3); + CHECK_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_E_UNSUPPORTED); + } +} + +/* Context extension. The family is unusually suited to it: only the 2048-wide sliding layers + * carry rotary and the full-attention layers are NoPE, so serving past the trained 131072 + * positions is `--max-model-len` alone (the engine warns; positions beyond training are + * extrapolated), and `--rope-scaling yarn:FACTOR` writes text_config.rope_parameters for a + * stronger stretch. The blend belongs to the sliding layers' rope ops only; the drafter reads its + * own draft.rope_parameters and does not inherit the target's. */ +TEST(museglimmer_carries_yarn_on_the_sliding_layers_rope) { + MetaKV mk = muse_meta(); + mk.set("text_config.rope_parameters.rope_type", "yarn") + .set("text_config.rope_parameters.factor", "8") + .set("text_config.rope_parameters.original_max_position_embeddings", "131072"); + RadBuilder b; + RadBuildCtx ctx = muse_ctx(0, 1); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + + /* Six sliding layers x (q, k): every rope op carries the blend, computed at the sliding + * layers' own theta 500000 over the 128 rotary dimensions. */ + const int ropes = count_op(b, "rope"); + CHECK_EQ(ropes, 12); + const RecOp* first = find_op(b, "rope", 0); + const RecOp* last = find_op(b, "rope", ropes - 1); + REQUIRE(first != nullptr); + REQUIRE(last != nullptr); + for (const RecOp* rp : { first, last }) { + CHECK(near(pflt(rp, "yarn_factor"), 8.0, 1e-9)); + CHECK(near(pflt(rp, "yarn_magnitude"), 1.0 + 0.1 * std::log(8.0), 1e-9)); + /* The fixture's rotary is 8 wide: the correction range is 1.98..3.03 at beta 32/1. */ + CHECK(near(pflt(rp, "yarn_low"), 1.0, 1e-9)); /* floor at beta_fast 32 */ + CHECK(near(pflt(rp, "yarn_high"), 4.0, 1e-9)); /* ceil at beta_slow 1 */ + } +} + +TEST(the_muse_dflash_drafter_reads_its_own_yarn_keys) { + MetaKV mk = muse_draft_meta(); + mk.set("draft.rope_parameters.rope_type", "yarn") + .set("draft.rope_parameters.factor", "4") + .set("draft.rope_parameters.original_max_position_embeddings", "131072"); + for (int world : { 1, 2 }) { + RadBuilder b; + RadBuildCtx ctx = spec_ctx(world - 1, world, 3); + REQUIRE_EQ(museglimmer::declare(&b, mk.meta(), &ctx), RAD_OK); + /* The drafter's three rope ops (context, query q and k) carry the blend at the drafter's + * head_dim 32 and theta 500000; the trunk's twelve stay unscaled. */ + const RecOp* dr = find_op(b, "rope", 12); + REQUIRE(dr != nullptr); + CHECK(near(pflt(dr, "yarn_factor"), 4.0, 1e-9)); + CHECK(near(pflt(dr, "yarn_magnitude"), 1.0 + 0.1 * std::log(4.0), 1e-9)); + CHECK(near(pflt(dr, "yarn_low"), 7.0, 1e-9)); + CHECK(near(pflt(dr, "yarn_high"), 13.0, 1e-9)); + const RecOp* tr = find_op(b, "rope", 0); + REQUIRE(tr != nullptr); + CHECK_EQ(pflt(tr, "yarn_factor"), -12345.0); /* absent: the trunk is unscaled */ + } +} + +RAD_TEST_MAIN() diff --git a/tests/oot_plugins.sh b/tests/oot_plugins.sh index 91ff0e6f..02b54825 100644 --- a/tests/oot_plugins.sh +++ b/tests/oot_plugins.sh @@ -1,5 +1,6 @@ #!/bin/sh -# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE [CXX_COMPILER]]] +# oot_plugins.sh BUILD SOURCE WORK [HIP_COMPILER HIP_TARGETS [VOPD_REPEATABLE [CXX_COMPILER +# [BUILD_TYPE]]]] # # THE PLUGINS RADIANCE SHIPS, BUILT THE WAY A THIRD PARTY BUILDS THEIRS. The tree's build is # installed into a prefix; then every plugin directory -- the kernel libraries, the quantisers, @@ -26,11 +27,15 @@ # has already checked what the out-of-tree build produced. set -eu B=$1; S=$2; W=$3 -HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}; CXXC=${7:-} +HIPC=${4:-}; HIPT=${5:-}; VOPD=${6:-OFF}; CXXC=${7:-}; BT=${8:-} # The tree's own C++ compiler, so the out-of-tree build does not depend on the host's default # (`c++` may be a different GCC than the one the installed ABI headers require). CCXX="" [ -n "$CXXC" ] && CCXX="-DCMAKE_CXX_COMPILER=$CXXC" +# The tree's build type too: a plugin configured without one takes RelWithDebInfo +# (rad_plugin_defaults), and a tree configured as anything else would then be compared with device +# code compiled at other flags. +[ -n "$BT" ] && CCXX="$CCXX -DCMAKE_BUILD_TYPE=$BT" GEN=${CMAKE_GENERATOR:-Ninja} J=${CMAKE_BUILD_PARALLEL_LEVEL:-$(nproc 2>/dev/null || echo 4)} @@ -49,10 +54,14 @@ run() { # run LOG CMD... -- quiet unless it fails say "installing $B into $P" run "$W/logs/install.log" cmake --install "$B" --prefix "$P" +# The libraries have many sources and build one at a time at the build's full width. An +# architecture or a bundled plugin is one or two large translation units, which no -j speeds up, and +# there are dozens of them: those are built several at a time (`small`, below). dirs="libref libquant" [ -d "$S/libavx" ] && [ -f "$B/radiance_home/kernels/libavx.so" ] && dirs="$dirs libavx" +small="" for d in "$S"/arch/*/ "$S"/plugin/*/; do - [ -f "$d/CMakeLists.txt" ] && dirs="$dirs $(basename "$(dirname "$d")")/$(basename "$d")" + [ -f "$d/CMakeLists.txt" ] && small="$small $(basename "$(dirname "$d")")/$(basename "$d")" done # The device libraries: built out of tree only with the tree's HIP compiler, and left out of every # comparison below without it. Each declares the family it serves, so a tree built for one family @@ -62,30 +71,74 @@ devlibs="" for d in libr4d libr3d; do [ -f "$S/$d/CMakeLists.txt" ] && [ -f "$B/radiance_home/kernels/$d.so" ] && devlibs="$devlibs $d" done -[ -n "$HIPC" ] && dirs="$dirs $devlibs" +devdirs="" +[ -n "$HIPC" ] && devdirs="$devlibs" is_dev() { case " $devlibs " in *" $1 "*) return 0 ;; esac; return 1; } # Each plugin installs its plugin file under $H and anything else it ships (libr4d's r4d_selftest) # under the package's prefix, as a third party installing into that radiance would. -for d in $dirs; do - n=$(basename "$d") - say "building $d against the installed package" +# +# The ROCm the environment names (the test sets ROCM_PATH to the one the tree links) goes on the +# prefix path beside the package: CMake otherwise takes the HIP runtime from wherever the HIP +# compiler sits, and a tree whose compiler comes from another ROCm build than its runtime would +# get a libr4d linked against that build's runtime, which then fails to load. +PP="$P" +[ -n "${ROCM_PATH:-}" ] && PP="$P;$ROCM_PATH" +build_one() { # build_one DIR JOBS -- configure and build one plugin directory + d=$1; n=$(basename "$d") extra="$CCXX" is_dev "$n" && extra="$extra -DCMAKE_HIP_COMPILER=$HIPC -DRAD_GPU_TARGETS=$HIPT -DRAD_HIP_VOPD_REPEATABLE=$VOPD" # A bundled plugin under plugin/ may carry device rows beside its host ones; it gets the tree's # HIP compiler as a third party would pass theirs. - case "$d" in plugin/*) [ -n "$HIPC" ] && extra="-DCMAKE_HIP_COMPILER=$HIPC" ;; esac + case "$d" in plugin/*) [ -n "$HIPC" ] && extra="$extra -DCMAKE_HIP_COMPILER=$HIPC" ;; esac # shellcheck disable=SC2086 run "$W/logs/$n.configure.log" cmake -S "$S/$d" -B "$W/b/$n" -G "$GEN" \ - -DCMAKE_PREFIX_PATH="$P" -DCMAKE_INSTALL_PREFIX="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra - run "$W/logs/$n.build.log" cmake --build "$W/b/$n" -j "$J" + -DCMAKE_PREFIX_PATH="$PP" -DCMAKE_INSTALL_PREFIX="$P" -DRAD_PLUGIN_INSTALL_HOME="$H" $extra + run "$W/logs/$n.build.log" cmake --build "$W/b/$n" -j "$2" +} +install_one() { # install_one DIR + n=$(basename "$1") # --prefix for the same reason as the tree install above: a plugin's own CMakeLists may install # companions (libr4d ships r4d_selftest) to relative destinations under CMAKE_INSTALL_PREFIX, and # the test must not need root. The plugins themselves ignore the prefix -- rad_add_plugin installs # them under the absolute RAD_PLUGIN_INSTALL_HOME given at configure time -- so the checks below, # which look in $H, are unaffected. run "$W/logs/$n.install.log" cmake --install "$W/b/$n" --prefix "$W/i" +} +for d in $dirs; do + say "building $d against the installed package" + build_one "$d" "$J" + install_one "$d" +done + +# OOT_JOBS of the small ones at a time (default half the build's width, at most 16: a plugin's +# compile holds about half a GiB), two compile jobs each; installed one after another, in order. +PJ=${OOT_JOBS:-$((J / 2))} +[ "$PJ" -gt 16 ] && PJ=16 +[ "$PJ" -lt 1 ] && PJ=1 +# shellcheck disable=SC2086 +set -- $small +say "building $# architectures and bundled plugins against the installed package, $PJ at a time" +while [ $# -gt 0 ]; do + batch=""; nb=0 + while [ $# -gt 0 ] && [ "$nb" -lt "$PJ" ]; do + batch="$batch $1"; nb=$((nb + 1)) + ( build_one "$1" 2 && : > "$W/logs/$(basename "$1").built" ) & + shift + done + wait + for d in $batch; do + [ -f "$W/logs/$(basename "$d").built" ] || + fail "$d did not build out of tree (logs: $W/logs/$(basename "$d").*.log)" + install_one "$d" + done +done + +for d in $devdirs; do + say "building $d against the installed package" + build_one "$d" "$J" + install_one "$d" done # 1. The same plugins, file for file. diff --git a/tests/r4d_emu/test_attn.cpp b/tests/r4d_emu/test_attn.cpp index e186388b..2ccb4153 100644 --- a/tests/r4d_emu/test_attn.cpp +++ b/tests/r4d_emu/test_attn.cpp @@ -306,15 +306,16 @@ int main(int argc, char** argv) { {"wmma h256 gqa2 i8 ahead w20 picture 90 of 300", 256, 2, 2, true, false, false, false, 20, {90}, {300}, -1, 0, 0, 0, 1, true}, /* LiLiCorr's drafter (attn_paged_sink): 32 query heads over 2 KV heads at h128 (16 over 1 at * TP 2), a block of 8 non-causal rows past the context, a 1024-token window; one sequence - * and a batch, unsplit and split, a bf16 and an int8 cache */ + * and a batch, unsplit and split, a bf16 and an int8 cache, and a prefill-shaped launch + * that takes the WMMA kernel (with and without int8 descales) */ {"sink h128 gqa16 kvh2 block8 w1024", 128, 16, 2, false, false, false, false, 1024, {8}, {1500}, -1, 0, 0, 0, -1, false, true}, {"sink h128 gqa16 kvh1 block8 x3 split", 128, 16, 1, false, false, true, false, 1024, {8, 8, 8}, {900, 40, 2100}, -1, 262144, s128, 0, -1, false, true}, {"sink h128 gqa16 kvh2 i8+descale split", 128, 16, 2, true, false, false, true, 1024, {8}, {1300}, -1, 262144, s128, 0, -1, false, true}, - {"sink h128 gqa16 prefill-shaped stays scalar", 128, 16, 1, false, false, false, false, 1024, {96}, - {400}, -1, 0, 0, 0, 0, false, true}, + {"sink h128 gqa16 prefill-shaped takes WMMA", 128, 16, 1, false, false, false, false, 1024, {96}, + {400}, -1, 0, 0, 0, 1, false, true}, {"sink h128 gqa16 missing-block", 128, 16, 1, false, false, false, false, 1024, {8}, {70}, 1, 0, 0, 0, -1, false, true}, /* and at TP 4, 8 query heads over the rank's replicated KV head */ @@ -324,8 +325,30 @@ int main(int argc, char** argv) { {900, 40, 2100}, -1, 262144, s128, 0, -1, false, true}, {"sink h128 gqa8 kvh1 i8+descale split", 128, 8, 1, true, false, false, true, 1024, {8}, {1300}, -1, 262144, s128, 0, -1, false, true}, - {"sink h128 gqa8 prefill-shaped stays scalar", 128, 8, 1, false, false, false, false, 1024, {96}, - {400}, -1, 0, 0, 0, 0, false, true}, + {"sink h128 gqa8 prefill-shaped takes WMMA", 128, 8, 1, false, false, false, false, 1024, {96}, + {400}, -1, 0, 0, 0, 1, false, true}, + {"sink h128 gqa8 prefill-shaped WMMA i8+descale", 128, 8, 1, true, false, false, true, 1024, + {96}, {400}, -1, 0, 0, 0, 1, false, true}, + {"sink h128 gqa16 prefill-shaped WMMA i8+descale", 128, 16, 1, true, false, false, true, 1024, + {96}, {400}, -1, 0, 0, 0, 1, false, true}, + /* Recursive Flint (arch/flint): 32 query heads over 4 KV heads at h128 (gqa 8 at TP 1 and + * 2), causal, a sink on every layer; the sliding layers' 513-token window and the full + * layers' none. Prefill on the WMMA kernel, ragged with decode rows beside it and with a + * missing block, and decode on the scalar kernel's split, at both caches. */ + {"sink h128 gqa8 kvh4 causal w513 prefill 300 of 1200", 128, 8, 4, false, true, false, false, + 513, {300}, {1200}, -1, 0, 0, 0, 1, false, true}, + {"sink h128 gqa8 kvh4 causal w513 prefill 300 of 1200 i8", 128, 8, 4, true, true, false, false, + 513, {300}, {1200}, -1, 0, 0, 0, 1, false, true}, + {"sink h128 gqa8 kvh2 causal full prefill 200 of 900 i8", 128, 8, 2, true, true, false, false, + 0, {200}, {900}, -1, 0, 0, 0, 1, false, true}, + {"sink h128 gqa8 kvh2 causal full ragged + decode rows", 128, 8, 2, false, true, true, false, + 0, {150, 1, 70}, {300, 50, 70}, -1, 0, 0, 0, 1, false, true}, + {"sink h128 gqa8 kvh2 causal w513 ragged missing-block i8", 128, 8, 2, true, true, true, false, + 513, {130, 70}, {700, 70}, 3, 0, 0, 0, 1, false, true}, + {"sink h128 gqa8 kvh4 causal w513 decode split i8", 128, 8, 4, true, true, true, false, 513, + {1, 1}, {1300, 40}, -1, 262144, s128, 0, -1, false, true}, + {"sink h128 gqa8 kvh4 causal full decode split", 128, 8, 4, false, true, true, false, 0, + {1, 1}, {1300, 40}, -1, 262144, s128, 0, -1, false, true}, /* and what must stay scalar: a verify batch, many sequences, a few rows each */ {"scalar: 8 x verify16, ragged", 512, 4, 1, false, true, true, false, 0, {16, 16, 16, 16, 16, 16, 16, 16}, {40, 50, 60, 70, 80, 90, 100, 110}, -1, 262144, s512, 0, 0}, diff --git a/tests/r4d_emu/test_vit.cpp b/tests/r4d_emu/test_vit.cpp new file mode 100644 index 00000000..a123ff5d --- /dev/null +++ b/tests/r4d_emu/test_vit.cpp @@ -0,0 +1,229 @@ +/* tests/r4d_emu: Muse Glimmer's vision-tower coordinate ops (r4d_vit_muse.hip) on the host SIMT + * emulator. + * + * grid_embed_pad: held to hand-computed constants -- a side-4 table resampled to an 8 x 8 grid, + * whose last row and column reach taps off the table (zero-weight, grid_sample's zeros padding), + * and an in-range 4 x 4 grid that reads the table whole. window_order: held to an independent host + * reference that sorts the patches by (segment, window row, window column, raster), which shares + * no arithmetic with the kernel's base-plus-rank slot formula; the inverse permutation, the rope + * positions and every cuw boundary follow from that order. + */ +#include "rad_abi.h" +#include "rad_plugin.h" +#include "r4d_plugin.h" +#include "ref_host.h" +#include +#include +#include +#include +#include + +static RadTensor rows(void* p, uint32_t dt, int64_t r0, int64_t r1, int64_t ld) { + RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 2; t.shape[0] = r0; t.shape[1] = r1; + t.stride[0] = ld; t.stride[1] = 1; + return t; +} +static RadTensor vec(void* p, uint32_t dt, int64_t n) { + RadTensor t{}; t.data = p; t.dtype = dt; t.rank = 1; t.shape[0] = n; t.stride[0] = 1; + return t; +} +static RadParam pi_(const char* k, long long v) { RadParam p{}; p.key = k; p.kind = RAD_P_INT; p.ival = v; return p; } +static RadParam ps_(const char* k, const char* v) { RadParam p{}; p.key = k; p.kind = RAD_P_STR; p.sval = v; return p; } + +// ------------------------------------------------------------------ grid_embed_pad + +static int test_pad() { + const int64_t n = 3, side = 4; + /* table[h * 4 + w] = (h * 4 + w + 1) / 4, three channels offset by 0.1 */ + std::vector tabf((size_t)(side * side * n)); + for (int h = 0; h < side; ++h) + for (int w = 0; w < side; ++w) + for (int c = 0; c < n; ++c) tabf[(size_t)((h * side + w) * n + c)] = (h * side + w + 1) * 0.25f + 0.1f * c; + std::vector tab((size_t)(side * side * n)); + for (size_t i = 0; i < tab.size(); ++i) tab[i] = f2b(tabf[i]); + + /* An 8 x 8 grid: src(i) = i / 2 - 0.25 on each axis; per axis the taps are floor(src) and + * floor(src) + 1 with hat weights, the off-table tap's weight zero. Row 0: taps -1 (masked) + * and 0 at 3/4; row 7: tap 3 at 3/4 and 4 (masked); interior rows blend two adjacent taps. */ + const int64_t M = 6; + /* Rows (0,0), (7,7), (1,3), (4,2), (7,0), (3,7) of the 8 x 8 grid. */ + const int rr[6] = { 0, 7, 1, 4, 7, 3 }, cc[6] = { 0, 7, 3, 2, 0, 7 }; + std::vector crd(4 * M); + for (int m = 0; m < 6; ++m) { + crd[m] = rr[m]; crd[M + m] = cc[m]; crd[2 * M + m] = 8; crd[3 * M + m] = 8; + } + std::vector x((size_t)(M * n)); + for (size_t i = 0; i < x.size(); ++i) x[i] = f2b(7.0f); + + RadTensor t[3] = { rows(x.data(), RAD_BF16, M, n, n), rows(tab.data(), RAD_BF16, side * side, n, n), + rows(crd.data(), RAD_I32, 4, M, M) }; + RadParam p[4] = { pi_("M", M), pi_("n", n), pi_("side", side), ps_("dtype", "bf16") }; + RadArgs a{}; a.t = t; a.n_t = 3; a.p = p; a.n_p = 4; + if (r4d_rad_grid_embed_pad(&a, nullptr) != RAD_OK) { std::puts("grid_embed_pad: launch failed"); return 1; } + + /* Hand-computed: each axis's in-range weight (the off-table tap contributes nothing), the + * joint weight the product h*w, the taps summed in libref's order (top-left, top-right, + * bottom-left, bottom-right). Channel 0; the others sit 0.1 apart, and x starts at 7. */ + /* (0,0): both axes tap 0 only, at 3/4 each -> 9/16 * 0.25 = 0.140625. */ + /* (7,7): both axes tap 3 only at 3/4 -> 9/16 * 4 = 2.25. */ + /* (1,3): rows 0,1 at 3/4, 1/4; cols 1,2 at 3/4, 1/4 -> 0.8125. */ + /* (4,2): rows 1,2 at 1/4, 3/4; cols 1,2 at 3/4, 1/4 -> 2.3125. */ + /* (7,0): row tap 3 at 3/4 (tap 4 masked), col tap 0 at 3/4 (tap -1 masked) -> 1.828125. */ + /* (3,7): rows 1,2 at 3/4, 1/4; col tap 3 at 3/4 (tap 4 masked) -> 1.6875. */ + /* Hand-derived per row: the literal taps and weights (channel 0 verified against the printed + * fractions, every channel against this table). Taps summed in libref's order: top-left, + * top-right, bottom-left, bottom-right, each joint weight the product h*w. */ + struct Taps { int th0, th1, tw0, tw1; float wh0, wh1, ww0, ww1; }; + const Taps taps[6] = { + { 0, 0, 0, 0, 0.0f, 0.75f, 0.0f, 0.75f }, /* (0,0): taps -1/4 masked, 0 at 3/4 */ + { 3, 3, 3, 3, 0.75f, 0.0f, 0.75f, 0.0f }, /* (7,7): taps 3 at 3/4, 4 masked */ + { 0, 1, 1, 2, 0.75f, 0.25f, 0.75f, 0.25f }, /* (1,3) */ + { 1, 2, 0, 1, 0.25f, 0.75f, 0.25f, 0.75f }, /* (4,2) */ + { 3, 3, 0, 0, 0.75f, 0.0f, 0.0f, 0.75f }, /* (7,0): row 4 and col -1 masked */ + { 1, 2, 3, 3, 0.75f, 0.25f, 0.75f, 0.0f }, /* (3,7): col 4 masked */ + }; + int bad = 0; + for (int m = 0; m < 6; ++m) { + const Taps& t6 = taps[m]; + for (int c = 0; c < n; ++c) { + const float acc = + b2f(tab[(size_t)((t6.th0 * side + t6.tw0) * n + c)]) * (t6.wh0 * t6.ww0) + + b2f(tab[(size_t)((t6.th0 * side + t6.tw1) * n + c)]) * (t6.wh0 * t6.ww1) + + b2f(tab[(size_t)((t6.th1 * side + t6.tw0) * n + c)]) * (t6.wh1 * t6.ww0) + + b2f(tab[(size_t)((t6.th1 * side + t6.tw1) * n + c)]) * (t6.wh1 * t6.ww1); + const float w = rb(7.0f + rb(acc)); + const float got = b2f(x[(size_t)(m * n + c)]); + if (got != w) { + ++bad; + std::printf("grid_embed_pad: row %d ch %d: got %g want %g\n", m, c, got, w); + } + } + } + + /* In range: a 4 x 4 grid on the side-4 table reads each row whole (src = i exactly). */ + const int64_t M2 = 2; + std::vector crd2(4 * M2); + crd2[0] = 2; crd2[1] = 3; crd2[4] = 4; crd2[5] = 4; crd2[6] = 4; crd2[7] = 4; + crd2[2] = 1; crd2[3] = 2; + std::vector x2((size_t)(M2 * n)); + for (size_t i = 0; i < x2.size(); ++i) x2[i] = f2b(0.0f); + RadTensor t2[3] = { rows(x2.data(), RAD_BF16, M2, n, n), + rows(tab.data(), RAD_BF16, side * side, n, n), + rows(crd2.data(), RAD_I32, 4, M2, M2) }; + RadParam p2[4] = { pi_("M", M2), pi_("n", n), pi_("side", side), ps_("dtype", "bf16") }; + RadArgs a2{}; a2.t = t2; a2.n_t = 3; a2.p = p2; a2.n_p = 4; + if (r4d_rad_grid_embed_pad(&a2, nullptr) != RAD_OK) { std::puts("grid_embed_pad in-range: launch failed"); return 1; } + for (int m = 0; m < 2; ++m) + for (int c = 0; c < n; ++c) { + const int h = m == 0 ? 2 : 3, w = m == 0 ? 1 : 2; + const float want = rb(rb(tabf[(size_t)((h * side + w) * n + c)]) + 0.0f); + if (b2f(x2[(size_t)(m * n + c)]) != want) { + ++bad; + std::printf("grid_embed_pad in-range: row %d ch %d: got %g want %g\n", m, c, + b2f(x2[(size_t)(m * n + c)]), want); + } + } + return bad ? 1 : 0; +} + +// ------------------------------------------------------------------ window_order + +/* The independent reference: sort patches by (segment, window row, window column, row, col). */ +struct Ord { int seg, wr, wc, r, c, p; }; +static int test_window(int window, const std::vector>& grids) { + /* Pack the grids back to back: segment s covers base .. base + gh*gw. */ + int P = 0; + std::vector cu{ 0 }; + std::vector gh_(grids.size()), gw_(grids.size()); + for (size_t s = 0; s < grids.size(); ++s) { + gh_[s] = grids[s].first; gw_[s] = grids[s].second; + P += gh_[s] * gw_[s]; + cu.push_back(P); + } + std::vector crd(4 * (size_t)P, 0); + std::vector ord; + for (size_t s = 0; s < grids.size(); ++s) { + const int base = cu[s]; + for (int r = 0; r < gh_[s]; ++r) + for (int c = 0; c < gw_[s]; ++c) { + const int p = base + r * gw_[s] + c; + crd[p] = r; crd[(size_t)P + p] = c; + crd[2 * (size_t)P + p] = gh_[s]; crd[3 * (size_t)P + p] = gw_[s]; + ord.push_back({ (int)s, window > 0 ? r / window : 0, window > 0 ? c / window : 0, + r, c, p }); + } + } + std::stable_sort(ord.begin(), ord.end(), [](const Ord& l, const Ord& r) { + if (l.seg != r.seg) return l.seg < r.seg; + if (l.wr != r.wr) return l.wr < r.wr; + if (l.wc != r.wc) return l.wc < r.wc; + if (l.r != r.r) return l.r < r.r; + return l.c < r.c; + }); + std::vector widx((size_t)P), winv((size_t)P), wpos(2 * (size_t)P), wcuw((size_t)P + 1, P); + for (int slot = 0; slot < P; ++slot) { + widx[(size_t)slot] = ord[(size_t)slot].p; + winv[(size_t)ord[(size_t)slot].p] = slot; + wpos[(size_t)slot] = ord[(size_t)slot].c + 1; /* pos[0][slot] = col + 1 */ + wpos[(size_t)P + (size_t)slot] = ord[(size_t)slot].r + 1; + } + if (window <= 0) { + for (int i = 0; i <= (int)grids.size() && i <= P; ++i) wcuw[(size_t)i] = cu[(size_t)i]; + } else { + /* cuw[k] is the base slot of window k: the patches before it in the permuted order. */ + int k = 0, base = 0; + for (size_t s = 0; s < grids.size(); ++s) { + const int nh = (gh_[s] + window - 1) / window, nw = (gw_[s] + window - 1) / window; + for (int wr = 0; wr < nh; ++wr) + for (int wc = 0; wc < nw; ++wc) { + wcuw[(size_t)k] = base; + int cnt = 0; + for (const Ord& o : ord) + if (o.seg == (int)s && o.wr == wr && o.wc == wc) ++cnt; + base += cnt; + ++k; + } + } + wcuw[(size_t)k] = P; + } + + std::vector idx((size_t)P, -1), inv((size_t)P, -1), pos(2 * (size_t)P, -1), + cuw((size_t)P + 1, -1); + RadTensor t[6] = { rows(crd.data(), RAD_I32, 4, P, P), rows(cu.data(), RAD_I32, 1, (int64_t)cu.size(), (int64_t)cu.size()), + rows(idx.data(), RAD_I32, 1, P, P), rows(inv.data(), RAD_I32, 1, P, P), + rows(pos.data(), RAD_I32, 2, P, P), rows(cuw.data(), RAD_I32, 1, P + 1, P + 1) }; + RadParam p[2] = { pi_("M", P), pi_("window", window) }; + RadArgs a{}; a.t = t; a.n_t = 6; a.p = p; a.n_p = 2; + if (r4d_rad_window_order(&a, nullptr) != RAD_OK) { + std::printf("window_order w=%d: launch failed\n", window); + return 1; + } + int bad = 0; + for (int i = 0; i < P; ++i) { + if (idx[(size_t)i] != widx[(size_t)i]) { ++bad; std::printf("window_order w=%d: idx[%d] %d want %d\n", window, i, idx[(size_t)i], widx[(size_t)i]); } + if (inv[(size_t)i] != winv[(size_t)i]) { ++bad; std::printf("window_order w=%d: inv[%d] %d want %d\n", window, i, inv[(size_t)i], winv[(size_t)i]); } + if (pos[(size_t)i] != wpos[(size_t)i]) { ++bad; std::printf("window_order w=%d: pos c[%d] %d want %d\n", window, i, pos[(size_t)i], wpos[(size_t)i]); } + if (pos[(size_t)P + (size_t)i] != wpos[(size_t)P + (size_t)i]) { ++bad; std::printf("window_order w=%d: pos r[%d] %d want %d\n", window, i, pos[(size_t)P + (size_t)i], wpos[(size_t)P + (size_t)i]); } + if (idx[(size_t)inv[(size_t)i]] != i) ++bad; /* the inverse property */ + } + for (size_t i = 0; i <= (size_t)P; ++i) + if (cuw[i] != wcuw[i]) { ++bad; std::printf("window_order w=%d: cuw[%zu] %d want %d\n", window, i, cuw[i], wcuw[i]); } + return bad ? 1 : 0; +} + +int main() { + int rc = 0; + rc |= test_pad(); + /* One 48 x 40 segment, window 32: ragged right and bottom, windows 32x32, 32x8, 16x32, 16x8. */ + rc |= test_window(32, { { 48, 40 } }); + /* Video-style: two segments back to back, window 16. */ + rc |= test_window(16, { { 20, 24 }, { 10, 12 } }); + /* Window-divisible. */ + rc |= test_window(8, { { 16, 24 } }); + /* A window larger than the grid: one window holding the whole segment. */ + rc |= test_window(64, { { 12, 10 } }); + /* window <= 0: the identity, cuw = cu. */ + rc |= test_window(0, { { 9, 7 }, { 5, 5 } }); + if (!rc) std::puts("r4d_emu_vit: ok"); + return rc; +} diff --git a/tests/radfile_keep_test.cpp b/tests/radfile_keep_test.cpp new file mode 100644 index 00000000..ee65bb07 --- /dev/null +++ b/tests/radfile_keep_test.cpp @@ -0,0 +1,185 @@ +/* radfile_keep_test.cpp -- what the load's page-cache drop keeps, and what it must not. + * + * The bug this guards: a container larger than RAM has its blob dropped from the page cache after + * the load, so the cache is not left full of weight pages nothing reads again. The mapped tier is + * the exception -- an n-gram table is read through its mapping for the engine's whole life -- and + * dropping it means every gather after a restart faults the rows back from disk (measured: 1 519 + * vs 1 998 tok/s prefill on a 24k prompt, 103 GiB table). Two things have to be right for the + * exception to work, and neither is visible from the outside: + * + * 1. the drop frees the blob MINUS the kept ranges, page-aligned so a page holding kept bytes is + * never dropped (rad_keep_complement); + * 2. only addresses inside the container become kept ranges: a copy in RAM + * (--ngram-placement ram) or a table read from its own file (disk=DIR) is not the blob, and + * recording one would keep pages that belong to something else (rad_blob_range). + * + * The second is the easier one to get wrong silently: an offset computed from a pointer that is + * not in the mapping is plausible arithmetic. + */ +#include "rad_test.h" +#include "format/radfile.h" + +#include +#include +#include + +using namespace rad; + +namespace { + +constexpr int64_t kPage = 4096; +constexpr int64_t kTables = 64 * 1024; /* where the blob starts */ +constexpr int64_t kBlob = 1 << 20; /* one MiB of blob */ +constexpr int64_t kSize = kTables + kBlob; /* the container's size */ + +using Ranges = std::vector>; /* (offset, length) */ + +Ranges complement(Ranges keep) { + return rad_keep_complement(kTables, kSize, std::move(keep)); +} + +/* Total bytes a set of ranges covers, which is what "freed" or "kept" means to a page cache. */ +int64_t covered(const Ranges& r) { + int64_t n = 0; + for (const auto& x : r) n += x.second; + return n; +} + +} // namespace + +/* ---- the drop's geometry ---------------------------------------------------------------- */ + +TEST(without_a_keep_list_the_whole_blob_is_dropped) { + const Ranges freed = complement({}); + CHECK_EQ(freed.size(), size_t(1)); + CHECK_EQ(freed.at(0).first, kTables); + CHECK_EQ(freed.at(0).second, kBlob); +} + +TEST(a_kept_range_splits_the_drop_around_it) { + const Ranges freed = complement({{kTables + 256 * 1024, 256 * 1024}}); + CHECK_EQ(freed.size(), size_t(2)); + CHECK_EQ(freed.at(0).first, kTables); + CHECK_EQ(freed.at(0).second, 256 * 1024); + CHECK_EQ(freed.at(1).first, kTables + 512 * 1024); + CHECK_EQ(freed.at(1).second, kBlob - 512 * 1024); + CHECK_EQ(covered(freed), kBlob - 256 * 1024); +} + +TEST(a_kept_range_at_the_start_leaves_one_range_behind_it) { + const Ranges freed = complement({{kTables, 128 * 1024}}); + CHECK_EQ(freed.size(), size_t(1)); + CHECK_EQ(freed.at(0).first, kTables + 128 * 1024); + CHECK_EQ(freed.at(0).second, kBlob - 128 * 1024); +} + +TEST(a_kept_range_at_the_end_leaves_one_range_before_it) { + const Ranges freed = complement({{kSize - 128 * 1024, 128 * 1024}}); + CHECK_EQ(freed.size(), size_t(1)); + CHECK_EQ(freed.at(0).first, kTables); + CHECK_EQ(freed.at(0).second, kBlob - 128 * 1024); +} + +TEST(a_keep_list_covering_the_blob_drops_nothing) { + CHECK(complement({{kTables, kBlob}}).empty()); + CHECK(complement({{kTables - kPage, kBlob + 2 * kPage}}).empty()); +} + +TEST(unsorted_and_overlapping_keep_ranges_are_merged) { + /* 250..310 KiB and 300..400 KiB merge to one 150 KiB keep; both are page-aligned at the ends + * after rounding, and the duplicate is the same range a second rank would send. */ + const Ranges freed = complement({ + {kTables + 300 * 1024, 100 * 1024}, /* second */ + {kTables + 250 * 1024, 60 * 1024}, /* overlaps and precedes it */ + {kTables + 250 * 1024, 60 * 1024}, /* the same range again, one per rank */ + }); + CHECK_EQ(freed.size(), size_t(2)); + CHECK_EQ(freed.at(0).first, kTables); + /* The gap ends at the page boundary below the keep's start: 250 KiB is 62.5 pages, so 62 + * pages (253 952 bytes) are freed and the half page holding kept bytes stays. */ + CHECK_EQ(freed.at(0).second, 253952); + CHECK_EQ(freed.at(1).first, kTables + 400 * 1024); /* merged end: 250 + 150 KiB */ + CHECK_EQ(freed.at(1).second, kBlob - 400 * 1024 + 0); + /* Freed plus kept is the blob, less the 2 KiB page the rounding gave back to the keep. */ + CHECK_EQ(covered(freed), kBlob - 150 * 1024 - 2048); +} + +TEST(keep_ranges_outside_the_blob_are_clamped_not_trusted) { + CHECK_EQ(covered(complement({{0, kTables}})), kBlob); /* entirely in the tables */ + CHECK_EQ(covered(complement({{kSize, 4096}})), kBlob); /* past the end */ + CHECK_EQ(covered(complement({{-4096, 4096}})), kBlob); /* before the mapping */ + CHECK_EQ(covered(complement({{0, 0}})), kBlob); /* empty */ + /* Half in, half out: only the part inside the blob is kept. */ + CHECK_EQ(covered(complement({{kSize - 8192, 16384}})), kBlob - 8192); +} + +TEST(a_gap_never_takes_a_page_that_holds_kept_bytes) { + /* The kept range starts four bytes into a page; the drop before it must stop at that page's + * boundary, not one byte before the kept range, or the kept bytes share a dropped page. */ + const Ranges freed = complement({{kTables + 100 * 1024 + 4, 4096}}); + CHECK_EQ(freed.size(), size_t(2)); + CHECK_EQ(freed.at(0).second % kPage, 0); + CHECK(freed.at(0).first + freed.at(0).second <= kTables + 100 * 1024 + 4); + CHECK_EQ(freed.at(1).first % kPage, 0); + CHECK(freed.at(1).first >= kTables + 100 * 1024 + 4 + 4096); +} + +TEST(a_container_with_no_blob_has_nothing_to_drop_or_keep) { + const auto none = rad_keep_complement(8192, 8192, {{8192, 4096}}); + CHECK(none.empty()); +} + +/* ---- which addresses are the blob -------------------------------------------------------- */ + +TEST(the_container_covers_its_own_bytes_and_nothing_else) { + const std::vector container(4 * kPage); + const uint8_t* base = container.data(); + const int64_t size = (int64_t)container.size(); + int64_t off = -1, len = -1; + + CHECK(rad_blob_range(base, size, base, 16, &off, &len)); + CHECK_EQ(off, int64_t(0)); + CHECK_EQ(len, int64_t(16)); + + CHECK(rad_blob_range(base, size, base + 2 * kPage + 7, 100, &off, &len)); + CHECK_EQ(off, 2 * kPage + 7); + CHECK_EQ(len, int64_t(100)); + + /* Up to and including the last byte. */ + CHECK(rad_blob_range(base, size, base + size - 1, 1, &off, &len)); + CHECK_EQ(off, size - 1); + + /* One byte past the end, or a range that overruns it. */ + CHECK(!rad_blob_range(base, size, base + size, 1, &off, &len)); + CHECK(!rad_blob_range(base, size, base + size - 1, 2, &off, &len)); + + /* A copy in RAM (the --ngram-placement ram case) is not the blob. */ + const std::vector copy(4 * kPage); + CHECK(!rad_blob_range(base, size, copy.data(), 16, &off, &len)); + + /* Degenerate input refuses rather than computing a range from nothing. */ + CHECK(!rad_blob_range(nullptr, size, base, 16, &off, &len)); + CHECK(!rad_blob_range(base, 0, base, 16, &off, &len)); + CHECK(!rad_blob_range(base, size, nullptr, 16, &off, &len)); + CHECK(!rad_blob_range(base, size, base, 0, &off, &len)); + CHECK(!rad_blob_range(base, size, base, -8, &off, &len)); +} + +TEST(the_recorded_range_is_what_the_drop_is_asked_to_keep) { + /* End to end on the two helpers alone: map a "table" inside a container, keep it, and check + * that the freed ranges are its complement. */ + const std::vector container(kSize); + const uint8_t* base = container.data(); + const void* table = base + kTables + 4096; + const int64_t n = 64 * 1024; + + int64_t off = 0, len = 0; + CHECK(rad_blob_range(base, kSize, table, n, &off, &len)); + const Ranges freed = rad_keep_complement(kTables, kSize, {{off, len}}); + CHECK_EQ(covered(freed), kBlob - n); + for (const auto& r : freed) { + CHECK(!(r.first < off + len && off < r.first + r.second)); /* no overlap with the keep */ + } +} + +RAD_TEST_MAIN() diff --git a/tests/recipe_test.cpp b/tests/recipe_test.cpp index bb7792f1..e3f6417f 100644 --- a/tests/recipe_test.cpp +++ b/tests/recipe_test.cpp @@ -247,4 +247,234 @@ TEST(the_sage_dflash2_recipes_decide_the_trunk_and_the_drafter) { } } +/* The Muse Glimmer recipes as they ship. The bf16 one is documentation only -- no rule, so every + * weight keeps the checkpoint's form. The w4a8 one routes every trunk linear to int4 on the +# 128-column grid (the value projection to int8), and nothing else: the layer norms, the + * embedding and the head match no rule. The patterns are the plugin's declared names: + * separate q and gate projections (this family's q_proj/gate_proj are two tensors), the gate|up + * concat, and the sliding/full two-group trunk. */ +TEST(the_museglimmer_recipes_decide_the_model_they_were_written_for) { + const std::string dir = std::string(__FILE__).substr( + 0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes"; + { + std::ifstream in(dir + "/museglimmer-30b-bf16.recipe"); + REQUIRE(in.good()); + std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + Recipe r; + std::string why; + REQUIRE_EQ(r.add_text(text, "museglimmer-30b-bf16.recipe", &why), RAD_OK); + CHECK_EQ(r.rules().size(), (size_t)0); + CHECK(r.match("blk.3.attn_q.weight") == nullptr); + } + { + std::ifstream in(dir + "/museglimmer-30b-w4a8.recipe"); + REQUIRE(in.good()); + std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + Recipe r; + std::string why; + REQUIRE_EQ(r.add_text(text, "museglimmer-30b-w4a8.recipe", &why), RAD_OK); + CHECK_EQ(r.rules().size(), (size_t)7); + const char* i4[] = { "blk.0.attn_q.weight", "blk.51.attn_k.weight", "blk.7.attn_gate.weight", + "blk.3.attn_output.weight", "blk.3.ffn_gate_up.weight", + "blk.3.ffn_down.weight" }; + for (const char* n : i4) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK_EQ(m->quantizer, std::string("rtn")); + CHECK(has_opt(m, "codes", "i4")); + CHECK(has_opt(m, "group", "128")); + CHECK(has_opt(m, "scale", "f16")); + CHECK(has_opt(m, "rule", "search")); + } + const RecipeRule* v = r.match("blk.3.attn_v.weight"); + REQUIRE(v != nullptr); + CHECK(has_opt(v, "codes", "i8")); + const char* kept[] = { "blk.3.attn_norm.weight", "blk.3.attn_post.weight", + "blk.3.ffn_norm.weight", "blk.3.ffn_post.weight", + "token_embd.weight", "output_norm.weight", "output.weight", + "model.vision_tower.layers.3.attn.q_proj.weight" }; + for (const char* n : kept) + CHECK(r.match(n) == nullptr); + } +} + +/* museglimmer-30b-iq8r as it ships: all seven trunk linears of every layer IQ8R, the head plain + * int8 (no rotation), and nothing else: the norms, the embedding, the vision tower and a merged + * drafter's `dspark.*` matrices match no rule. */ +TEST(the_museglimmer_iq8r_recipe_decides_the_model_it_was_written_for) { + const std::string dir = std::string(__FILE__).substr( + 0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes"; + std::ifstream in(dir + "/museglimmer-30b-iq8r.recipe"); + REQUIRE(in.good()); + std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + Recipe r; + std::string why; + REQUIRE_EQ(r.add_text(text, "museglimmer-30b-iq8r.recipe", &why), RAD_OK); + CHECK_EQ(r.rules().size(), (size_t)8); + const char* iq8r[] = { "blk.0.attn_q.weight", "blk.7.attn_gate.weight", "blk.51.attn_k.weight", + "blk.3.attn_v.weight", "blk.3.attn_output.weight", + "blk.0.ffn_gate_up.weight", "blk.51.ffn_down.weight" }; + for (const char* n : iq8r) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK_EQ(m->quantizer, std::string("rtn")); + CHECK(has_opt(m, "codes", "i8")); + CHECK(has_opt(m, "group", "256")); + CHECK(has_opt(m, "scale", "u8")); + CHECK(has_opt(m, "scale2", "bf16")); + CHECK(has_opt(m, "block2", "1x*")); + CHECK(has_opt(m, "transform", "fwht128")); + CHECK(has_opt(m, "clamp", "sym")); + CHECK(has_opt(m, "rule", "search")); + } + const RecipeRule* head = r.match("output.weight"); + REQUIRE(head != nullptr); + CHECK(has_opt(head, "codes", "i8")); + CHECK(has_opt(head, "group", "128")); + CHECK(has_opt(head, "scale", "bf16")); + CHECK(!has_opt(head, "transform", "fwht128")); + const char* kept[] = { "blk.3.attn_norm.weight", "blk.3.attn_post.weight", + "blk.3.ffn_norm.weight", "blk.3.ffn_post.weight", "token_embd.weight", + "output_norm.weight", "v.blk.0.attn.q_proj.weight", "v.proj.weight", + "dspark.fc.weight", "dspark.blk.0.attn_q.weight", + "dspark.blk.4.ffn_down.weight", + "model.vision_tower.layers.3.attn.q_proj.weight" }; + for (const char* n : kept) + CHECK(r.match(n) == nullptr); +} + +/* The Flint recipes as they ship, over arch/flint's declared names. flint-iq8r: every trunk linear + * (attention, the two dense layers, the shared expert's gate/up) IQ8R, the routed experts and the + * shared expert's down projection rotated int8 at a bf16 scale a (row, 128 of K), the head plain + * int8. flint-bf16-q4: u4 attention, signed int4 experts, plain int8 dense, shared and head. In + * both the norms, the sinks, the router and its zero correction, and the embedding match no rule. */ +TEST(the_flint_recipes_decide_the_model_they_were_written_for) { + const std::string dir = std::string(__FILE__).substr( + 0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes"; + const char* kept[] = { "blk.0.attn_norm.weight", "blk.0.attn_q_norm.weight", + "blk.7.attn_k_norm.weight", "blk.0.attn_sinks", "blk.3.ffn_norm.weight", + "blk.3.glm_router.weight", "blk.3.glm_router.correction", + "token_embd.weight", "output_norm.weight" }; + { + std::ifstream in(dir + "/flint-iq8r.recipe"); + REQUIRE(in.good()); + std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + Recipe r; + std::string why; + REQUIRE_EQ(r.add_text(text, "flint-iq8r.recipe", &why), RAD_OK); + CHECK_EQ(r.rules().size(), (size_t)13); + const char* iq8r[] = { "blk.0.attn_q.weight", "blk.48.attn_k.weight", "blk.3.attn_v.weight", + "blk.5.attn_output.weight", "blk.0.ffn_gate_up.weight", + "blk.1.ffn_down.weight", "blk.2.ffn_gate_up_shexp.weight" }; + for (const char* n : iq8r) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK_EQ(m->quantizer, std::string("rtn")); + CHECK(has_opt(m, "codes", "i8")); + CHECK(has_opt(m, "group", "256")); + CHECK(has_opt(m, "scale", "u8")); + CHECK(has_opt(m, "scale2", "bf16")); + CHECK(has_opt(m, "transform", "fwht128")); + } + const char* i8h[] = { "blk.2.ffn_gate_up_exps.0.weight", "blk.48.ffn_down_exps.255.weight", + "blk.17.ffn_down_shexp.weight" }; + for (const char* n : i8h) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK(has_opt(m, "codes", "i8")); + CHECK(has_opt(m, "group", "128")); + CHECK(has_opt(m, "scale", "bf16")); + CHECK(has_opt(m, "transform", "fwht128")); + } + const RecipeRule* head = r.match("output.weight"); + REQUIRE(head != nullptr); + CHECK(has_opt(head, "codes", "i8")); + CHECK(!has_opt(head, "transform", "fwht128")); + for (const char* n : kept) CHECK(r.match(n) == nullptr); + } + { + std::ifstream in(dir + "/flint-bf16-q4.recipe"); + REQUIRE(in.good()); + std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + Recipe r; + std::string why; + REQUIRE_EQ(r.add_text(text, "flint-bf16-q4.recipe", &why), RAD_OK); + const RecipeRule* a = r.match("blk.9.attn_output.weight"); + REQUIRE(a != nullptr); + CHECK(has_opt(a, "codes", "u4")); + CHECK(has_opt(a, "zero", "u8")); + const RecipeRule* e = r.match("blk.30.ffn_down_exps.7.weight"); + REQUIRE(e != nullptr); + CHECK(has_opt(e, "codes", "i4")); + for (const char* n : { "blk.1.ffn_gate_up.weight", "blk.40.ffn_down_shexp.weight", + "output.weight" }) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK(has_opt(m, "codes", "i8")); + } + for (const char* n : kept) CHECK(r.match(n) == nullptr); + } +} + +/* The Ling-3.0-tiny IQ8R recipe as it ships, over arch/bailing_hybrid's declared names: the KDA + * projections (fused q|k|v, forget, output gate, out), the MLA out projection, the dense layer's + * pair and the shared expert's gate/up IQ8R; the routed experts and the shared expert's down + * projection rotated int8 at a bf16 scale a (row, 128 of K). The KDA beta, the MLA's low-rank q + * and kv projections, its query parts and its head gate, the convolution taps, the router, the + * embedding and the head match no rule and keep the checkpoint's bf16; the norms, the KDA + * parameters and the router are cast to the f32 the plugin declares. */ +TEST(the_ling_tiny_iq8r_recipe_decides_the_model_it_was_written_for) { + const std::string dir = std::string(__FILE__).substr( + 0, std::string(__FILE__).find_last_of('/')) + "/../data/recipes"; + std::ifstream in(dir + "/ling-3.0-tiny-iq8r.recipe"); + REQUIRE(in.good()); + std::string text((std::istreambuf_iterator(in)), std::istreambuf_iterator()); + Recipe r; + std::string why; + REQUIRE_EQ(r.add_text(text, "ling-3.0-tiny-iq8r.recipe", &why), RAD_OK); + CHECK_EQ(r.rules().size(), (size_t)20); + const char* iq8r[] = { "blk.0.attn_qkv.weight", "blk.22.attn_forget.weight", + "blk.1.attn_gate.weight", "blk.2.attn_output.weight", + "blk.3.attn_output.weight", "blk.0.ffn_gate_up.weight", + "blk.0.ffn_down.weight", "blk.1.ffn_gate_up_shexp.weight", + "blk.23.ffn_gate_up_shexp.weight" }; + for (const char* n : iq8r) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK_EQ(m->quantizer, std::string("rtn")); + CHECK(has_opt(m, "codes", "i8")); + CHECK(has_opt(m, "group", "256")); + CHECK(has_opt(m, "scale", "u8")); + CHECK(has_opt(m, "scale2", "bf16")); + CHECK(has_opt(m, "transform", "fwht128")); + } + const char* i8h[] = { "blk.1.ffn_gate_up_exps.0.weight", "blk.23.ffn_down_exps.127.weight", + "blk.7.ffn_down_shexp.weight" }; + for (const char* n : i8h) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK(has_opt(m, "codes", "i8")); + CHECK(has_opt(m, "group", "128")); + CHECK(has_opt(m, "scale", "bf16")); + CHECK(has_opt(m, "transform", "fwht128")); + } + const char* f32[] = { "blk.0.attn_norm.weight", "blk.3.attn_q_a_norm.weight", + "blk.3.attn_kv_a_norm.weight", "blk.1.ffn_norm.weight", + "blk.0.ssm_norm.weight", "blk.0.ssm_a", "blk.0.ssm_dt_bias", + "blk.1.glm_router.weight", "blk.1.glm_router.correction", + "output_norm.weight" }; + for (const char* n : f32) { + const RecipeRule* m = r.match(n); + REQUIRE(m != nullptr); + CHECK_EQ(m->quantizer, std::string("cast")); + CHECK(has_opt(m, "dtype", "f32")); + } + const char* kept[] = { "blk.0.attn_beta.weight", "blk.3.attn_q_a.weight", + "blk.3.attn_q_rope.weight", "blk.3.attn_q_nope.weight", + "blk.3.attn_kv_a.weight", "blk.3.attn_kv_b.weight", + "blk.3.attn_head_gate.weight", "blk.0.ssm_conv.weight", + "token_embd.weight", "output.weight" }; + for (const char* n : kept) CHECK(r.match(n) == nullptr); +} + RAD_TEST_MAIN() diff --git a/tests/ref_test.cpp b/tests/ref_test.cpp index 664c6ac6..36cd6620 100644 --- a/tests/ref_test.cpp +++ b/tests/ref_test.cpp @@ -1052,6 +1052,42 @@ TEST(group_router_selects_only_inside_the_best_groups) { CHECK_EQ(run("router_sigmoid_group_topk", bad), RAD_E_SHAPE); } +TEST(group_router_at_the_tiny_geometry_keeps_four_of_eight_sixteen_expert_groups) { + T lg(RAD_F32, { 1, 128 }), bias(RAD_F32, { 128 }), ids(RAD_I32, { 1, 8 }), w(RAD_F32, { 1, 8 }); + // One planted expert a group (16 a group): p 0.90, 0.30, 0.85, 0.10, 0.80, 0.05, 0.75, 0.70, + // and a floor of 0.001 everywhere else. The planted sums lead, so topk_group 4 keeps groups + // 0, 2, 4 and 6: the four largest planted experts are in, groups 1, 3, 5 and 7 bring nothing. + const float planted[8] = { 0.90f, 0.30f, 0.85f, 0.10f, 0.80f, 0.05f, 0.75f, 0.70f }; + std::vector p(128, 0.001f), lgv; + for (int g = 0; g < 8; ++g) p[g * 16 + 2] = planted[g]; + for (size_t i = 0; i < p.size(); ++i) lgv.push_back(std::log(p[i] / (1 - p[i]))); + lg.f(lgv); + bias.f(std::vector(128, 0.0f)); + A a; + a.t(lg).t(bias).t(ids).t(w).i("M", 1).i("n_expert", 128).i("top_k", 8).i("n_group", 8) + .i("topk_group", 4).i("norm", 1).d("route_scale", 2.5).s("dtype", "f32"); + auto has = [&](int e) { + for (int i = 0; i < 8; ++i) + if (ids.iat(i) == e) return true; + return false; + }; + REQUIRE_EQ(run("router_sigmoid_group_topk", a), RAD_OK); + CHECK_EQ(ids.iat(0), 2); // the kept groups' planted experts, in score order: + CHECK_EQ(ids.iat(1), 34); // 0.90, 0.85, 0.80, 0.75 + CHECK_EQ(ids.iat(2), 66); + CHECK_EQ(ids.iat(3), 98); + for (int g : { 1, 3, 5, 7 }) CHECK(!has(g * 16 + 2)); // the dropped groups stay out + CHECK_NEAR(w.at(0), 2.5f * 0.90f / (0.90f + 0.85f + 0.80f + 0.75f + 0.004f), 1e-5); + // A correction bias ranks group 3's sum past group 6's and seats its expert; the weights + // stay the unbias'd sigmoid. + std::vector bs(128, 0.0f); + bs[3 * 16 + 2] = 0.9f; + bias.f(bs); + REQUIRE_EQ(run("router_sigmoid_group_topk", a), RAD_OK); + CHECK(has(50)); + CHECK(!has(98)); +} + TEST(paged_latent_attention_is_causal_adds_the_rotary_part_and_gates_per_head) { // One sequence of three tokens, the last two queried (positions 1 and 2). Token 0 and 1 sit // in page 1, token 2 in page 0; a row is the latent (2) then the rotary part (2). @@ -1253,7 +1289,7 @@ TEST(op_vocabulary) { "gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed", /* Runtime LoRA's two halves, issued by the core beside a trunk GEMM. */ "lora_shrink", "lora_expand", "lora_expand_mm", - "grid_embed_aa", "grid_embed_cpe", + "grid_embed_aa", "grid_embed_cpe", "grid_embed_pad", "window_order", "attn_paged", "attn_dense", "kv_store", "kv_store_streamed", "rope", "rope_table", "attn_paged_sink", "qk_norm_rope", "qsa_block_key", @@ -1289,7 +1325,7 @@ TEST(op_vocabulary) { "chan_split", "interleave2", "iota", "cu_repeat", "int_affine", "frame_store", /* Fish Audio drama-3's (arch/fishomni): the repetition-aware choice between two draws, * and its codec encoder's residual quantiser step. */ - "ras_pick", "vq_encode", + "ras_pick", "vq_encode", "vq_euclidean", "elu", /* The video generator's (MiniMax-H3): its DiT's modulated norm and sampler step, its * decoder's patch unfold, tiles, stitch and positions, and the vocoder's alias-free * activation. */ @@ -4502,6 +4538,160 @@ TEST(op_grid_embed) { CHECK_NEAR(x.at(4), want, 1e-4); } +/* grid_embed_pad: the half-pixel resample with grid_sample's zeros padding. A side-4 table onto + * rows of an 8 x 8 grid: src(i) = i / 2 - 0.25, so row 0 keeps only the in-range tap 0 (weight + * 3/4, the tap -1 masked), row 7 only tap 3 at 3/4 (tap 4 masked), and interior rows blend two. + * Table row h * 4 + w holds (4h + w + 1) and (4h + w + 1) / 2 in its two channels. */ +TEST(op_grid_embed_pad_zeroes_taps_beyond_the_table) { + const int64_t side = 4, n = 2; + std::vector tab((size_t)(side * side * n)); + for (int64_t r = 0; r < side * side; ++r) + for (int64_t i = 0; i < n; ++i) tab[(size_t)(r * n + i)] = (float)(r + 1) * (i ? 0.5f : 1.0f); + T table(RAD_F32, { side * side, n }); table.f(tab); + /* Rows (0,0), (7,7), (1,3), (4,2), (7,0), (3,7) of the 8 x 8 grid. */ + T x(RAD_F32, { 6, n }); x.f({ 100, 100, 100, 100, 100, 100, + 100, 100, 100, 100, 100, 100 }); + T crd(RAD_I32, { 4, 6 }); + crd.n({ 0, 7, 1, 4, 7, 3, 0, 7, 3, 2, 0, 7, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8 }); + A a; a.t(x).t(table).t(crd).i("M", 6).i("n", n).i("side", side).s("dtype", "f32"); + CHECK_OK(run("grid_embed_pad", a)); + /* Hand-computed: joint weight = the product of the axes' in-range hat weights (the off-table + * tap contributes nothing), v(h,w) = 4h + w + 1; channel 1 holds v / 2, x starts at 100. */ + /* (0,0): both axes tap 0 only, at 3/4 each -> 9/16 * 1 = 0.5625. */ + /* (7,7): both axes tap 3 only at 3/4 -> 9/16 * 16 = 9. */ + /* (1,3): rows 0,1 at 3/4, 1/4; cols 1,2 at 3/4, 1/4 -> 3.25. + (4,2): rows 1,2 at 1/4, 3/4; cols 0,1 at 1/4, 3/4 -> 8.75. */ + /* (7,0): row tap 3 at 3/4 (tap 4 masked), col tap 0 at 3/4 (tap -1 masked) -> 9/16 * 13 = 7.3125. */ + /* (3,7): rows 1,2; col tap 3 at 3/4 (tap 4 masked) -> 9/16 * 8 + 3/16 * 12 = 6.75. */ + const float want[6] = { 0.5625f, 9.0f, 3.25f, 8.75f, 7.3125f, 6.75f }; + for (int64_t m = 0; m < 6; ++m) { + CHECK_NEAR(x.at(m * n), 100.0f + want[m], 1e-5); + CHECK_NEAR(x.at(m * n + 1), 100.0f + want[m] * 0.5f, 1e-5); + } +} + +/* A grid no larger than the table never masks a tap, and at scale 1 the half-pixel form reads + * each row whole: a 4 x 4 grid on the side-4 table is the table itself. */ +TEST(op_grid_embed_pad_in_range_reads_the_table) { + const int64_t side = 4, n = 1; + std::vector tab((size_t)(side * side)); + for (int64_t r = 0; r < side * side; ++r) tab[(size_t)r] = (float)(r + 1); + T table(RAD_F32, { side * side, n }); table.f(tab); + T x(RAD_F32, { 2, n }); x.f({ 0, 0 }); + T crd(RAD_I32, { 4, 2 }); crd.n({ 2, 3, 1, 2, 4, 4, 4, 4 }); + A a; a.t(x).t(table).t(crd).i("M", 2).i("n", n).i("side", side).s("dtype", "f32"); + CHECK_OK(run("grid_embed_pad", a)); + CHECK_NEAR(x.at(0), 10.0f, 1e-6); /* table row 2 * 4 + 1 = 10 */ + CHECK_NEAR(x.at(1), 15.0f, 1e-6); /* table row 3 * 4 + 2 = 15 */ +} + +/* window_order: the permutation, its inverse, the rope positions and every cuw boundary, checked + * against an in-test reference that sorts the patches by (segment, window row, window column, + * raster) -- no arithmetic shared with the slot formula. The grids are laid out segment by + * segment, each a raster gh x gw block. */ +namespace { + +struct WinCase { + std::vector> grids; /* (height, width) per segment */ + int64_t window; +}; + +/* Builds the case, runs the op, checks the outputs against the sort reference and the hand-derived + * cuw boundaries. Returns the number of disagreements. */ +int64_t run_window_case(const char* name, const WinCase& c, const std::vector& cuw_want, + std::vector* idx_out = nullptr) { + int64_t P = 0; + std::vector cu{ 0 }; + for (const auto& g : c.grids) { P += g.first * g.second; cu.push_back((int64_t)P); } + std::vector crd(4 * (size_t)P, 0); + struct Ord { int64_t seg, wr, wc, r, cc, p; }; + std::vector ord; + for (size_t s = 0; s < c.grids.size(); ++s) { + const int64_t base = s ? cu[s] : 0; + for (int64_t r = 0; r < c.grids[s].first; ++r) + for (int64_t q = 0; q < c.grids[s].second; ++q) { + const int64_t p = base + r * c.grids[s].second + q; + crd[(size_t)p] = (int32_t)r; + crd[(size_t)P + (size_t)p] = (int32_t)q; + crd[2 * (size_t)P + (size_t)p] = (int32_t)c.grids[s].first; + crd[3 * (size_t)P + (size_t)p] = (int32_t)c.grids[s].second; + ord.push_back({ (int64_t)s, c.window > 0 ? r / c.window : 0, + c.window > 0 ? q / c.window : 0, r, q, p }); + } + } + std::stable_sort(ord.begin(), ord.end(), [](const Ord& l, const Ord& r) { + if (l.seg != r.seg) return l.seg < r.seg; + if (l.wr != r.wr) return l.wr < r.wr; + if (l.wc != r.wc) return l.wc < r.wc; + if (l.r != r.r) return l.r < r.r; + return l.cc < r.cc; + }); + T crd_t(RAD_I32, { 4, P }); crd_t.n(crd); + T cu_t(RAD_I32, { 1, (int64_t)cu.size() }); cu_t.n(cu); + T idx(RAD_I32, { 1, P }); T inv(RAD_I32, { 1, P }); + T pos(RAD_I32, { 2, P }); T cuw(RAD_I32, { 1, P + 1 }); + A a; a.t(crd_t).t(cu_t).t(idx).t(inv).t(pos).t(cuw).i("M", P).i("window", c.window); + CHECK_OK(run("window_order", a)); + int64_t bad = 0; + for (int64_t slot = 0; slot < P; ++slot) { + const int64_t src = idx.iat(slot), want = ord[(size_t)slot].p; + if (src != want) { ++bad; fprintf(stderr, " %s: idx[%lld] %lld want %lld\n", name, + (long long)slot, (long long)src, (long long)want); } + if (inv.iat(want) != slot) ++bad; + if (idx.iat(inv.iat(slot)) != slot) ++bad; /* idx and inv are inverses */ + /* pos: (col + 1, row + 1) of the slot's source patch, read off the reference's order. */ + if (pos.iat(slot) != ord[(size_t)slot].cc + 1) ++bad; + if (pos.iat(P + slot) != ord[(size_t)slot].r + 1) ++bad; + } + for (size_t i = 0; i < cuw_want.size(); ++i) + if (cuw.iat((int64_t)i) != cuw_want[i]) { + ++bad; + fprintf(stderr, " %s: cuw[%zu] %lld want %lld\n", name, i, + (long long)cuw.iat((int64_t)i), (long long)cuw_want[i]); + } + if (idx_out) for (int64_t i = 0; i < P; ++i) idx_out->push_back(idx.iat(i)); + return bad; +} + +} /* namespace */ + +/* One 48 x 40 segment, window 32: windows 32 x 32, 32 x 8, 16 x 32, 16 x 8 -- ragged right and + * bottom. The first patch of the second window is row 0, column 32, patch 256. */ +TEST(op_window_order_ragged_segment) { + std::vector gather; + const int64_t bad = run_window_case( + "48x40 w32", { { { 48, 40 } }, 32 }, { 0, 1024, 1280, 1792, 1920, 1920, 1920 }, &gather); + CHECK_EQ(bad, 0LL); + CHECK_EQ(gather[0], 0LL); + CHECK_EQ(gather[1024], 32LL); /* window (0,1) starts at row 0, column 32: patch 32 */ + CHECK_EQ(gather[1920 - 1], 48 * 40 - 1LL); +} + +/* Video-style: two segments back to back, windows never across the segment boundary. */ +TEST(op_window_order_two_segments) { + const int64_t bad = run_window_case( + "two segments w16", { { { 32, 32 }, { 16, 16 } }, 16 }, + { 0, 256, 512, 768, 1024, 1280, 1280, 1280, 1280 }); + CHECK_EQ(bad, 0LL); +} + +/* Window-divisible: every window exactly window x window. */ +TEST(op_window_order_divisible) { + const int64_t bad = run_window_case( + "16x24 w8", { { { 16, 24 } }, 8 }, { 0, 64, 128, 192, 256, 320, 384, 384 }); + CHECK_EQ(bad, 0LL); +} + +/* window 0: the identity, cuw = cu, the rope positions still swapped and offset by one. */ +TEST(op_window_order_window_zero_is_the_identity) { + const int64_t P = 9 * 7 + 5 * 5; + std::vector gather; + const int64_t bad = run_window_case("identity w0", { { { 9, 7 }, { 5, 5 } }, 0 }, + { 0, 63, 88, 88 }, &gather); + CHECK_EQ(bad, 0LL); + for (int64_t i = 0; i < P; ++i) CHECK_EQ(gather[(size_t)i], i); +} + TEST(op_qk_norm_rope) { /* At position 0 the rotation is the identity, so this isolates the per-head RMS norm. */ T qkv(RAD_F32, {1, 6}); qkv.f({3, 4, 3, 4, 7, 7}); @@ -8505,6 +8695,45 @@ TEST(vq_encode_takes_the_nearest_code_by_cosine_and_leaves_the_residual) { CHECK_EQ(run("vq_encode", b), RAD_E_SHAPE); } +TEST(breeze_euclidean_quantisation_preserves_distance_and_tie_order) { + T x(RAD_F32, {3, 2}); x.f({4, 0, 2, 0, 0, 3}); + T cb(RAD_F32, {3, 2}); cb.f({1, 0, 3, 0, 0, 2}); + T codes(RAD_I32, {3}); + A a; a.t(x).t(cb).t(codes).i("M", 3).i("n", 2).i("bins", 3).s("dtype", "f32"); + CHECK_OK(run("vq_euclidean", a)); + /* Cosine would choose 0 for [4, 0]; Euclidean must choose the longer centroid 1. + * [2, 0] is exactly equidistant from 0 and 1 and chooses the lower index. */ + CHECK_EQ(codes.iat(0), 1); CHECK_EQ(codes.iat(1), 0); CHECK_EQ(codes.iat(2), 2); + CHECK_EQ(x.at(0), 1.0f); CHECK_EQ(x.at(1), 0.0f); + CHECK_EQ(x.at(2), 1.0f); CHECK_EQ(x.at(3), 0.0f); + CHECK_EQ(x.at(4), 0.0f); CHECK_EQ(x.at(5), 1.0f); + CHECK_OK(run("vq_euclidean", a)); /* next residual step, not the original vector */ + CHECK_EQ(codes.iat(0), 0); CHECK_EQ(codes.iat(1), 0); CHECK_EQ(codes.iat(2), 2); + A bad; bad.t(x).t(cb).t(codes).i("M", 3).i("n", 2).i("bins", 4).s("dtype", "f32"); + CHECK_EQ(run("vq_euclidean", bad), RAD_E_SHAPE); +} + +TEST(breeze_elu_has_unit_alpha_and_works_in_place) { + T x(RAD_F32, {4, 1}); x.f({-1, 0, 2, -100}); + A a; a.t(x).t(x).i("M", 4).i("n", 1).s("dtype", "f32"); + CHECK_OK(run("elu", a)); + CHECK(std::abs(x.at(0) - (-0.6321205588f)) < 1e-7f); + CHECK_EQ(x.at(1), 0.0f); CHECK_EQ(x.at(2), 2.0f); CHECK_EQ(x.at(3), -1.0f); +} + +TEST(breeze_downsample_replication_is_a_prefix_and_crop) { + /* Original [1, 2, 3, 4], replicate left pad of 2 -> [1, 1, 1, 2, 3, 4]. + * An ordinary causal conv on the prefixed input gives one extra leading row. */ + T x(RAD_F32, {6, 1}); x.f({1, 1, 1, 2, 3, 4}); + T w(RAD_F32, {1, 1, 4}); w.f({1, 10, 100, 1000}); + T cu(RAD_I32, {2}); cu.n({0, 6}); + T y(RAD_F32, {3, 1}); + A a; a.t(x).t(w).t(cu).tnull().t(y).i("M", 6).i("cin", 1).i("cout", 1).i("k", 4) + .i("dil", 1).i("causal", 1).i("stride", 2).s("dtype", "f32"); + CHECK_OK(run("conv1d", a)); + CHECK_EQ(y.at(1), 2111.0f); CHECK_EQ(y.at(2), 4321.0f); +} + /* snake_aa's paddings, with the activation the identity (alpha 0: sin(0 u) = 0). Ratio 2, filters * of 4: P = 1. Sequence [10, 20, 40] pads to [10, 10, 20, 40, 40]; the transposed f_up [1, 2, 3, 4] * gives [10, 20, 40, 60, 50, 80, 100, 160, 160, 240, 120, 160], doubled and cropped by 3 a side: @@ -10065,6 +10294,8 @@ std::vector geometries() { G("hc_project", "M", 2, a.i("M", R).i("n", 8).i("hc", 2).d("scale", 1.0).s("dtype", "f32")), G("mtp_enter", "M", 2, a.i("M", R).i("n", 8).i("hc", 2).d("eps", 1e-6).s("dtype", "f32")), G("grid_embed", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")), + G("grid_embed_pad", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")), + G("window_order", "M", 12, a.i("M", R).i("window", 4)), G("grid_embed_aa", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")), G("grid_embed_cpe", "M", 3, a.i("M", R).i("n", 8).i("side", 4).s("dtype", "f32")), G("lili_cand", "M", 3, a.i("M", R).i("k", 4).i("world", 1).i("steps", 3).i("n", 8) @@ -10346,6 +10577,8 @@ std::vector geometries() { G("ras_pick", "M", 2, a.i("M", R).i("win", 4).i("lo", 1).i("hi", 9).i("rep", 1)), G("vq_encode", "M", 3, a.i("M", R).i("n", 16).i("dim", 4).i("bins", 24) .s("dtype", "f32")), + G("vq_euclidean", "M", 3, a.i("M", R).i("n", 16).i("bins", 24).s("dtype", "f32")), + G("elu", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("resample_nearest", "M", 6, a.i("M", R).i("n", 8).s("dtype", "f32")), G("fourier_embed", "M", 3, a.i("M", R).i("n", 8).s("dtype", "f32")), G("win_input", "M", 8, a.i("M", R).i("n_lat", 4).i("n_zero", 2).i("n_cond", 3) @@ -10444,7 +10677,10 @@ bool undrawable(const char* op) { return !std::strcmp(op, "sample_merge_topk") || !std::strcmp(op, "gather_rows2") || !std::strcmp(op, "pixtral_merge") || /* sample_logprobs rows (sorted pairs, positive sums): avx_check_hand.cpp builds them */ - !std::strcmp(op, "lili_cand"); + !std::strcmp(op, "lili_cand") || + /* Whole raster grids with segment boundaries: the window_order cases here and in + * avx_check_hand.cpp build them. */ + !std::strcmp(op, "window_order"); } uint32_t lcg(uint32_t* s) { *s = *s * 1664525u + 1013904223u; return *s >> 8; } diff --git a/tests/sched_test.cpp b/tests/sched_test.cpp index 659def1d..64faf60a 100644 --- a/tests/sched_test.cpp +++ b/tests/sched_test.cpp @@ -17,7 +17,6 @@ #include #include #include - #include using namespace rad; @@ -296,6 +295,29 @@ TEST(the_device_fakes_are_the_ones_linked) { rad_dev_free(p, RAD_MEM_DEVICE); } +/* THE STEP RECORD EXISTS ONLY FOR --diagnose. Sizing the ring at every init put 2.5 MiB and a + * record a step on the serving path for a report nobody asked for. Off: no ring, no record. On: + * the ring and one record each of the three steps. */ +TEST(the_step_record_exists_only_with_diagnose) { + for (const bool on : { false, true }) { + Fixture f; + f.build(); + if (on) f.cfg.diagnose = "/tmp/radiance-diagnose-not-written"; /* Scheduler only reads it */ + CHECK_OK(f.start()); + CHECK_EQ(f.sch.step_record_capacity(), on ? (size_t)(1u << 16) : (size_t)0); + f.submit(64, 8); + for (int i = 0; i < 3; ++i) { + CHECK(f.sch.step() != nullptr); + f.commit_plain(); + f.sch.step_finished(); + } + CHECK_EQ(f.sch.step_record_count(), on ? (uint64_t)3 : (uint64_t)0); + std::vector out; + CHECK_EQ(f.sch.step_records(0, &out), (uint64_t)0); + CHECK_EQ(out.size(), on ? (size_t)3 : (size_t)0); + } +} + /* ================================================================== geometry + chunking */ TEST(chunk_geometry_is_computed_not_configured) { Fixture f; @@ -3250,6 +3272,354 @@ TEST(an_explicit_busy_prefill_chunk_holds_the_chunk_to_it) { if (e.seq == a) CHECK_EQ(e.n_tokens, 128); } +TEST(the_mixed_step_target_controller_corrects_misses_and_grows_cautiously) { + MixedStepTarget d; + d.seed(300, 64, 2048); + CHECK_EQ(d.cap(), 256); + d.reset(); + /* 1024 rows taking four times the 100 ms target predicts a 256-row cap. */ + d.observe(1024, 400000000, 100000000, 64, 2048); + CHECK_EQ(d.cap(), 256); + CHECK_EQ(d.limit(2048, 64), 256); + + /* A step in the dead band does not chase noise. */ + d.observe(256, 80000000, 100000000, 64, 2048); + CHECK_EQ(d.cap(), 256); + + /* Three comfortably fast full-cap steps grow toward the measured 512 rows, one quarter at a + * time and on the model's quantum. */ + for (int i = 0; i < 3; ++i) d.observe(256, 50000000, 100000000, 64, 2048); + CHECK_EQ(d.cap(), 320); + /* A short tail cannot make the deployment's cap grow. */ + d.observe(64, 10000000, 100000000, 64, 2048, /*representative=*/false); + CHECK_EQ(d.cap(), 320); + /* A later miss corrects immediately. */ + d.observe(320, 200000000, 100000000, 64, 2048); + CHECK_EQ(d.cap(), 128); +} + +TEST(the_mixed_step_target_recovers_from_fixed_cost_backoff_and_ignores_short_tails) { + MixedStepTarget d; + d.seed(64, 64, 2048); + /* Fixed decode cost makes proportional scaling round back to 64, but sustained 80%-of-target + * steps still earn a one-quantum probe. */ + for (int i = 0; i < 3; ++i) d.observe(64, 160000000, 200000000, 64, 2048); + CHECK_EQ(d.cap(), 128); + /* A short tail can miss because of fixed cost; it did not exercise the cap and cannot lower + * the next full chunk. */ + d.observe(32, 260000000, 200000000, 64, 2048, /*representative=*/false); + CHECK_EQ(d.cap(), 128); + /* The same short row count is representative when a fixed policy or checkpoint boundary, + * rather than the end of a prompt, limited it. Repeated slow work must be able to lower the + * controller below that other limit. */ + d.seed(2048, 64, 8192); + d.observe(512, 400000000, 200000000, 64, 8192, /*representative=*/true); + CHECK_EQ(d.cap(), 256); + /* An impossible target bottoms out at one legal quantum without underflow. */ + d.observe(128, 1000000000, 1000000, 64, 2048); + CHECK_EQ(d.cap(), 64); + d.observe(64, 1000000000, 1000000, 64, 2048); + CHECK_EQ(d.cap(), 64); +} + +TEST(a_mixed_step_target_does_not_throttle_an_uncontended_prefill) { + Fixture f; + share_fixture(f, /*busy off=*/0); + f.cfg.mixed_step_target_ms = 200; + CHECK_OK(f.start()); + f.submit(3500, 64); + CHECK(f.sch.step() != nullptr); + CHECK_EQ((int)f.sch.plan().e.size(), 1); + CHECK_EQ(f.sch.plan().e[0].n_tokens, 512); + CHECK_EQ(f.sch.metrics().mixed_step_target_steps, 0); +} + +TEST(a_mixed_step_target_refuses_a_batch_that_cannot_mix_one_prefill_quantum) { + Fixture f; + share_fixture(f, /*busy off=*/0); + f.cfg.mixed_step_target_ms = 200; + f.cfg.max_seqs = 2; + f.cfg.max_tok = 64; /* quantum 64, no room for a decode row beside it */ + CHECK_EQ(f.start(), RAD_E_INVAL); +} + +TEST(a_mixed_step_target_validates_the_shared_budget_under_a_prefill_span) { + Fixture f; + f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/128, /*max_ctx=*/4096); + f.cfg.checkpoint_interval = 64; + f.cfg.prefill_span = 2; + f.cfg.max_seqs = 2; + f.cfg.mixed_step_target_ms = 200; + /* The lone-prefill budget is 128, but a mixed step uses shared_tok=64: too little for the + * 64-row quantum beside even one ordinary decode row. */ + CHECK_EQ(f.start(), RAD_E_INVAL); +} + +TEST(a_mixed_step_target_refuses_an_explicit_cap_below_the_prefill_quantum) { + Fixture f; + share_fixture(f, /*busy below the 64-row quantum=*/32); + f.cfg.mixed_step_target_ms = 200; + CHECK_EQ(f.start(), RAD_E_INVAL); +} + +TEST(a_mixed_step_target_keeps_decode_rows_in_both_priority_orders_and_busy_modes) { + for (int64_t busy : { -1ll, 128ll }) { + for (int prefill_priority : { -1, 1 }) { + Fixture f; + share_fixture(f, busy); + f.cfg.mixed_step_target_ms = 200; + f.cfg.max_seqs = 2; + f.cfg.max_tok = 128; + f.cfg.checkpoint_interval = 128; + CHECK_OK(f.start()); + + const uint64_t d = f.submit(100, 512, /*priority=*/0); + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + const uint64_t p = f.submit(3500, 64, prefill_priority); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED); + bool saw_d = false, saw_p = false; + for (const StepEntry& e : f.sch.plan().e) { + if (e.seq == d && !e.is_prefill) saw_d = true; + if (e.seq == p && e.is_prefill) saw_p = true; + } + CHECK(saw_d); + CHECK(saw_p); + } + } +} + +/* The scheduler feeds completed mixed-step timing into the controller. A deterministic timing + * sample stands in for step_finished's live bracket. The following step must use the learned cap + * even when --busy-prefill-chunk is off. */ +TEST(a_mixed_step_target_adapts_the_next_mixed_prefill_step) { + Fixture f; + share_fixture(f, /*busy off: the target controller stands on its own=*/0); + f.cfg.mixed_step_target_ms = 2; + CHECK_OK(f.start()); + + const uint64_t d = f.submit(100, 512, /*priority=*/0); + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + + const uint64_t p = f.submit(3500, 64, /*priority=*/1); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED); + /* This fixture's 512-row mixed capacity seeds at one quarter, on its 64-row quantum. */ + CHECK_EQ(f.sch.metrics().mixed_step_target_prefill_cap, 128); + int64_t first = 0; + for (const StepEntry& e : f.sch.plan().e) if (e.seq == p) first = e.n_tokens; + CHECK(first > 0); + f.commit_plain(12); + f.sch.note_mixed_step_cost(12000000); + const int64_t learned = f.sch.metrics().mixed_step_target_prefill_cap; + CHECK(learned >= 64); + CHECK(learned < first); + + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED); + int64_t next = 0; + for (const StepEntry& e : f.sch.plan().e) if (e.seq == p) next = e.n_tokens; + CHECK(next > 0); + CHECK(next <= learned); + CHECK(f.sch.find(d) != nullptr); +} + +/* The learned limit is a budget for the whole mixed step, not for each prefill independently. + * Otherwise a burst of N fresh requests can schedule N times the measured safe amount and miss + * the latency target precisely when the server is busiest. */ +TEST(a_mixed_step_target_caps_aggregate_mixed_prefill_rows) { + Fixture f; + share_fixture(f, /*busy off: the target controller stands on its own=*/0); + f.cfg.mixed_step_target_ms = 200; + f.cfg.max_seqs = 3; + CHECK_OK(f.start()); + + const uint64_t d = f.submit(100, 512, /*priority=*/0); + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + + f.submit(3500, 64, /*priority=*/1); + f.submit(3500, 64, /*priority=*/1); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED); + CHECK(f.sch.find(d) != nullptr); + + int64_t prefill_rows = 0; + int prefills = 0; + for (const StepEntry& e : f.sch.plan().e) { + if (!e.is_prefill) continue; + prefill_rows += e.n_tokens; + ++prefills; + } + /* The 128-row seed is shared as one 64-row quantum apiece. */ + CHECK_EQ(prefills, 2); + CHECK(prefill_rows <= f.sch.metrics().mixed_step_target_prefill_cap); + CHECK_EQ(f.sch.metrics().queue_depth, 0); +} + +TEST(a_mixed_step_target_gives_each_burst_prefill_one_quantum_when_the_target_cannot) { + Fixture f; + share_fixture(f, /*busy off=*/0); + f.cfg.mixed_step_target_ms = 200; + f.cfg.max_seqs = 4; + CHECK_OK(f.start()); + + f.submit(100, 512, /*priority=*/0); + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + for (int i = 0; i < 3; ++i) f.submit(3500, 64, /*priority=*/1); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED); + + int prefills = 0; + int64_t rows = 0; + for (const StepEntry& e : f.sch.plan().e) { + if (!e.is_prefill) continue; + ++prefills; + rows += e.n_tokens; + CHECK_EQ(e.n_tokens, 64); + } + CHECK_EQ(prefills, 3); + CHECK_EQ(rows, 192); + CHECK_EQ(f.sch.metrics().mixed_step_target_prefill_cap, 128); + CHECK_EQ(f.sch.metrics().queue_depth, 0); +} + +TEST(a_mixed_step_target_keeps_a_decoder_behind_a_bidirectional_text_prefill) { + Fixture f; + f.build(/*blocks=*/4096, /*states=*/64, /*max_tok=*/128, /*max_ctx=*/4096); + f.cfg.checkpoint_interval = 64; + f.cfg.busy_prefill_chunk = 0; + f.cfg.mixed_step_target_ms = 200; + f.cfg.max_seqs = 2; + f.prog.encoder.bidirectional = 1; + CHECK_OK(f.start()); + + const uint64_t d = f.submit(40, 512, /*priority=*/0); + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + const uint64_t p = f.submit(3500, 64, /*priority=*/1); + CHECK(f.sch.step() != nullptr); + + bool saw_decode = false, saw_prefill = false; + for (const StepEntry& e : f.sch.plan().e) { + if (e.seq == d && !e.is_prefill) saw_decode = true; + if (e.seq == p && e.is_prefill) saw_prefill = true; + } + CHECK(saw_decode); + CHECK(saw_prefill); +} + +TEST(a_cancelled_mixed_prefill_still_teaches_from_the_work_that_ran) { + Fixture f; + share_fixture(f, /*busy off=*/0); + f.cfg.mixed_step_target_ms = 2; + CHECK_OK(f.start()); + + f.submit(100, 512, /*priority=*/0); + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + const uint64_t p = f.submit(3500, 64, /*priority=*/1); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED); + const int64_t before = f.sch.metrics().mixed_step_target_prefill_cap; + CHECK_OK(f.sch.cancel(p)); + f.commit_plain(12); + f.sch.note_mixed_step_cost(12000000); + CHECK_EQ(f.sch.metrics().mixed_step_target_steps, 1); + CHECK_EQ(f.sch.metrics().mixed_step_target_misses, 1); + CHECK(f.sch.metrics().mixed_step_target_prefill_cap < before); + REQUIRE(f.sch.find(p) != nullptr); + CHECK_EQ((int)f.sch.find(p)->state, (int)ReqState::Cancelled); + if (f.sch.has_deferred()) f.sch.release_deferred(); + CHECK(!f.kv.has_sequence(p)); + CHECK_OK(f.sch.reap(p)); + CHECK(f.sch.find(p) == nullptr); +} + +TEST(a_mixed_step_target_preserves_speculative_verification_in_a_mixed_step) { + Fixture f; + share_fixture(f, /*busy off=*/0); + f.cfg.mixed_step_target_ms = 200; + f.cfg.n_spec = 4; + CHECK_OK(f.start()); + + const uint64_t d = f.submit(100, 512, /*priority=*/0); + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + int32_t draft[4] = { 21, 22, 23, 24 }; + CHECK_OK(f.sch.set_draft(d, draft, 4)); + f.submit(3500, 64, /*priority=*/1); + const RadBatch* b = f.sch.step(); + REQUIRE(b != nullptr); + CHECK_EQ(b->phase, RAD_PHASE_MIXED); + CHECK_EQ(b->n_spec, 4); + CHECK_EQ(b->n_seq_decode, 1); + CHECK_OK(f.commit(12, 0, [](const StepEntry& e) { return e.is_prefill ? 0 : 2; })); + f.sch.step_finished(); + CHECK_EQ(f.sch.metrics().mixed_step_target_steps, 1); + const Request* rd = f.sch.find(d); + REQUIRE(rd != nullptr); + CHECK_EQ((int)rd->output.size(), 4); + CHECK_EQ(rd->output[1], 21); + CHECK_EQ(rd->output[2], 22); + CHECK_EQ(rd->output[3], 12); + CHECK_EQ(rd->n_computed, 103); + CHECK_EQ(rd->n_accepted, 2); +} + +TEST(a_mixed_step_target_composes_with_auto_interleave_and_burst_prefills) { + Fixture f; + share_fixture(f, /*busy off: the target controller stands on its own=*/0); + f.cfg.mixed_step_target_ms = 2; + f.cfg.prefill_interleave = -1; + f.cfg.prefill_interleave_share = 1.0; + f.cfg.max_seqs = 3; + CHECK_OK(f.start()); + /* One decode-only step after each mixed chunk, deterministically. */ + f.sch.note_step_cost(true, 0.4); + f.sch.note_step_cost(false, 0.4); + + const uint64_t d = f.submit(100, 512, /*priority=*/0); + CHECK(f.sch.step() != nullptr); + f.commit_plain(11); + + const uint64_t p1 = f.submit(3500, 64, /*priority=*/1); + const uint64_t p2 = f.submit(3500, 64, /*priority=*/1); + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED); + int first_prefills = 0; + for (const StepEntry& e : f.sch.plan().e) + if (e.is_prefill && (e.seq == p1 || e.seq == p2)) ++first_prefills; + CHECK_EQ(first_prefills, 2); + f.commit_plain(12); + f.sch.note_mixed_step_cost(12000000); + CHECK_EQ(f.sch.metrics().mixed_step_target_steps, 1); + CHECK_EQ(f.sch.metrics().mixed_step_target_prefill_cap, 64); + + CHECK(f.sch.step() != nullptr); /* auto interleave: decoder alone */ + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_DECODE); + CHECK_EQ((int)f.sch.plan().e.size(), 1); + CHECK_EQ(f.sch.plan().e[0].seq, d); + f.commit_plain(13); + f.sch.note_mixed_step_cost(12000000); /* a held step teaches nothing */ + CHECK_EQ(f.sch.metrics().mixed_step_target_steps, 1); + CHECK_EQ(f.sch.metrics().steps_held, 1); + + CHECK(f.sch.step() != nullptr); + CHECK_EQ(f.sch.plan().phase, RAD_PHASE_MIXED); + int next_prefills = 0; + for (const StepEntry& e : f.sch.plan().e) { + if (!e.is_prefill || (e.seq != p1 && e.seq != p2)) continue; + CHECK_EQ(e.n_tokens, 64); + ++next_prefills; + } + CHECK_EQ(next_prefills, 2); /* neither burst prompt starves */ + CHECK(f.sch.find(d) != nullptr); +} + /* ================================================================== decode-only steps between chunks */ /* --prefill-interleave. A sequence decodes while a 2000-token prompt prefills in 256-token chunks * (the checkpoint interval). Each step's shape is 'C' when it carries a chunk of the prompt and diff --git a/tests/server_test.cpp b/tests/server_test.cpp index aef607e6..781581cf 100644 --- a/tests/server_test.cpp +++ b/tests/server_test.cpp @@ -2615,6 +2615,24 @@ TEST(the_steps_a_prefill_interleave_held_are_counted) { CHECK(it != d.samples.end() && it->second == 6.0); } +TEST(the_mixed_step_target_controller_is_observable) { + Metrics m("m", 1024); + server::SchedMetrics s; + s.mixed_step_target_steps = 9; + s.mixed_step_target_misses = 2; + s.mixed_step_target_prefill_cap = 384; + m.sample(s); + PromDoc d = parse_prom(m.render()); + CHECK_EQ((int)d.errors.size(), 0); + CHECK_EQ(d.type["radiance:mixed_step_target_steps_total"], std::string("counter")); + CHECK_EQ(d.type["radiance:mixed_step_target_misses_total"], std::string("counter")); + CHECK_EQ(d.type["radiance:mixed_step_target_prefill_cap"], std::string("gauge")); + const auto cap = d.samples.find( + "radiance:mixed_step_target_prefill_cap{model_name=\"m\",engine=\"0\"}"); + CHECK(cap != d.samples.end()); + if (cap != d.samples.end()) CHECK_NEAR(cap->second, 384.0, 1e-9); +} + /* Each draft position's acceptances are a counter next to its reach. At a fixed depth position * j+1's reach is j's acceptances, but an adaptive window can end at j with j taken, so a ratio * over a window needs both. Here two verifies end at position 1 with it accepted. */ diff --git a/tests/shipped_plugins_test.cpp b/tests/shipped_plugins_test.cpp index a09d0d04..8e01fecc 100644 --- a/tests/shipped_plugins_test.cpp +++ b/tests/shipped_plugins_test.cpp @@ -91,13 +91,18 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) { } const std::set> want = { { "anima", "" }, { "bailinghybrid", "" }, { "breeze", "" }, { "clef", "" }, + { "bailinghybrid", "gguf_ftype_7" }, { "bailinghybrid", "gguf_ftype_15" }, + { "bailinghybrid", "gguf_ftype_17" }, { "bailinghybrid", "gguf_ftype_18" }, + { "bailinghybrid", "gguf_ftype_25" }, { "clef", "fp8_e4m3" }, { "embeddinggemma2", "" }, - { "fishomni", "bsgemm-moe" }, { "flux3", "" }, { "flux3distilled", "" }, + { "fishomni", "bsgemm-moe" }, { "flint", "" }, { "flux3", "" }, { "flux3distilled", "" }, { "gemma3", "" }, { "gemma4", "" }, { "gemma4", "compressed-tensors" }, { "glm5next", "" }, { "hunyuan3d2", "" }, { "hyv3", "" }, { "hyv3", "fp8" }, { "hyv3", "gguf_ftype_15" }, { "laya", "" }, { "lfm2", "" }, { "llama", "" }, { "mistral3", "" }, { "llama", "fp8_e4m3" }, { "nemotronh", "" }, { "nomicbert", "" }, { "qwen35", "" }, + { "museglimmer", "" }, + { "museglimmer", "compressed-tensors" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, { "qwen35moe", "w8a8_fwht128" }, { "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" }, diff --git a/tests/speech_test.cpp b/tests/speech_test.cpp index 15892228..bca1c979 100644 --- a/tests/speech_test.cpp +++ b/tests/speech_test.cpp @@ -311,6 +311,60 @@ TEST(a_cloning_model_takes_references_as_clips_and_transcripts_in_its_prompt) { } /* ================================================================== the response */ +TEST(breeze_cloning_uses_one_reference_and_direction_is_opt_in) { + if (!mm::decoder_available()) { SKIP("audio decoder unavailable"); return; } + Speech s; + auto& info = s.gen.inf; + info.max_prompt = 512; + info.tmpl_plain = "[S0]{input}"; + info.tmpl = "[S0]{instructions}{input}"; + info.neg_tmpl = info.tmpl_plain; + info.tmpl_ref = "{references}[S0]{input}"; + info.ref_item = "[S0]{text}{audio}<|audio_eos|>"; + info.ref_rate = 24000; + info.ref_hop = 1920; + info.ref_max_samples = 240000; + info.ref_max = 1; + info.branches = 2; + info.default_steps = 0; + const std::string wav = wav_of(std::vector(2000, 1000), 24000); + const std::string audio = base64_encode((const uint8_t*)wav.data(), wav.size()); + const json ref = {{"audio", audio}, {"text", "reference words"}}; + json body = {{"input", "new words"}, {"references", json::array({ref})}, {"guidance_scale", 1}}; + CHECK_EQ(s.post(body).status, 200); + const auto& q = s.last(); + CHECK_EQ(q.ref_audio.size(), (size_t)3840); + CHECK_EQ(q.ref_cu.size(), (size_t)2); + CHECK_EQ(std::count_if(q.ref_frame.begin(), q.ref_frame.end(), [](int v) { return v >= 0; }), 2); + CHECK_EQ(q.ref_frame.size(), q.tokens.size()); + CHECK_EQ(q.cfg, 1.0f); + body["guidance_scale"] = 4; + CHECK_EQ(s.refused(body), std::string("guidance_scale")); + body["guidance_scale"] = 1; + body["instructions"] = "a different voice"; + CHECK_EQ(s.refused(body), std::string("instructions")); + info.tmpl_ref_instruct = "{references}[S0]{instructions}{input}"; + info.neg_tmpl_ref = info.tmpl_ref; + body["guidance_scale"] = 4; + CHECK_EQ(s.post(body).status, 200); + const auto& directed = s.last(); + CHECK_EQ(directed.cfg, 4.0f); + CHECK_EQ(directed.neg_ref_frame.size(), directed.neg_tokens.size()); + CHECK_EQ(std::count(directed.ref_frame.begin(), directed.ref_frame.end(), 0), 1); + CHECK_EQ(std::count(directed.neg_ref_frame.begin(), directed.neg_ref_frame.end(), 0), 1); + CHECK(directed.tokens.size() > directed.neg_tokens.size()); + const auto text_of = [](const std::vector& ids) { + std::string text; for (int32_t i : ids) if (i) text.push_back((char)i); return text; + }; + CHECK(has(text_of(directed.tokens), "a different voicenew words")); + CHECK(!has(text_of(directed.neg_tokens), "a different voice")); + CHECK(has(text_of(directed.neg_tokens), "reference words")); + body.erase("instructions"); + body["references"].push_back(ref); + CHECK_EQ(s.refused(body), std::string("references")); + body["references"] = json::array({{{"audio", audio}, {"text", " "}}}); + CHECK_EQ(s.refused(body), std::string("references[0].text")); +} /* The whole piece: the windows in order whatever order they were played in, as a WAV whose header * states the rate, channels and length, or as the same samples raw. */