Compare commits

...
1 Commits
Author SHA1 Message Date
Deadcode 2a2b756371 radiance 2.1.0
New models. Recursive Flint (39.8B, about 2.5B active) by everplays (#422): `arch/flint`, as an
IQ8R container with rotated int8 experts or a four-bit one, with a sink-aware WMMA prefill
attention and the fused attention prologue at `rotary_dim` 0. Meta Muse Glimmer 30B by
launch80_assets (#423): bf16, an int4 trunk or IQ8R, its windowed vision tower, its DFlash
drafter, the ATEM tool dialect and context extension. Ling-3.0-tiny by RikshaDriver (#441):
served from its GGUF releases or as IQ8R on `bailing_hybrid`, with six more libr3d kernels. Block
FP8, MXFP4 and NVFP4 conversions of the three are not served. IQ8R containers of all three
(round to nearest, no calibration) are on Hugging Face under StillDeadcode: flint-iq8r,
muse-glimmer-30b-iq8r-dflash and ling-3.0-tiny-iq8r. They were checked for sane answers on two
R9700; nothing was benchmarked, and Muse Glimmer's pictures, video and tool calls were not tried.

Speech. Breeze-TTS-2 clones a voice from a reference recording and its transcript, with an
optional delivery direction, by farcryjohn (#436). The published Breeze container needs
converting again with the updated recipe before it can.

Tools. A model entry with `diagnose: DIR` runs a fixed workload on the engine instead of serving
and writes a report: step times, tokens a step, draft acceptance, TTFT and prefill rates by
category, concurrency and prompt length, and with `diagnose-baseline` a token-for-token comparison
against an earlier report (docs/DIAGNOSE.md), by Code000 (#418).

Scheduler. `mixed-step-target-ms` holds a mixed prefill and decode step to a service time, off by
default, by tnhnyzc (#413). `scheduler.stuck-exit` (60s by default, 0 never) ends the process when
the device has advanced nothing for that long, so a restart policy brings a hung server back
(#409, #415, #428).

Fixed. Draft trees with the int8 KV cache, which stopped Gemma 4 31B with DFlash2 on its first
request (#454, diagnosed by aelfwyne). The expert loan held at zero by a few leftover cache blocks
after long sessions (#455, diagnosed by thekk1). The mapped tier's pages kept in the page cache
across a load and a restore, by C_Tamas (#421). Replayed tool calls with blank arguments, and
arguments that are not JSON refused naming the call, by dschmitz (#444). The dashboard's card
temperature reads the junction sensor, by dschmitz (#453). The VRAM shortfall report says what the
KL mode needs, by baKon (#448). The out-of-tree plugin test builds its plugins in parallel and
takes its toolchain from the tree.

Plugin ABI 40: out-of-tree plugins need to be rebuilt.

Thanks to @everplays, @launch80_assets, @RikshaDriver, @farcryjohn, @Code000, @tnhnyzc, @C_Tamas, @dschmitz, @baKon, @aelfwyne and @thekk1.
2026-11-15 16:00:05 +01:00
166 changed files with 20749 additions and 327 deletions

No files matched your search

+1 -1
View File
@@ -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)
+29 -14
View File
@@ -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.
+17
View File
@@ -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 |
+1 -1
View File
@@ -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:
+4
View File
@@ -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)
+17 -1
View File
@@ -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. */
+3
View File
@@ -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
+363 -73
View File
@@ -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<double> 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<Layer> 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<int64_t> 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
+10
View File
@@ -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=<radiance prefix>`); 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)
@@ -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)
@@ -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=<radiance prefix>`); 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)
@@ -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)
@@ -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=<radiance prefix>`); 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)
@@ -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)
@@ -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=<radiance prefix>`); 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)
@@ -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)
@@ -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=<radiance prefix>`); 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)
@@ -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)
+138 -30
View File
@@ -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}<bos>[S0]{input}";
d.tmpl_ref_instruct = "{references}<bos>[S0]<ins_bos>{instructions}<ins_eos>{input}";
d.neg_tmpl_ref = d.tmpl_ref;
d.ref_item = "<bos>[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 : {"<bos>", "<eos>", "<|AUDIO|>", "<|audio_eos|>",
"<ins_bos>", "<ins_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);
+281
View File
@@ -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<rad_buf> in, std::initializer_list<rad_buf> 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<int64_t> 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);
}
}
}
File diff suppressed because it is too large. Load diff
+571
View File
@@ -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 <cmath>
#include <cstdio>
#include <cstring>
#include <vector>
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<Layer> 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<int> 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<int64_t>(P, ctx->max_tok);
P = std::max<int64_t>(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<int64_t> 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<rad_buf>{ b_qkv }
: std::initializer_list<rad_buf>{ 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.<tag>.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<uint16_t> 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 */
+9
View File
@@ -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)
+544
View File
@@ -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 <arch/rad_arch.h>
#include "flint_attention.h"
#include <arch/rad_block_mlp_fp8.h>
#include <arch/rad_block_moe_fp8.h>
#include "rad_abi_layout.h"
#include <algorithm>
#include <climits>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
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<Layer> 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<int64_t>(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[] = { "<tool_call>" };
static const RadChatFormat kFlintChatFormat = {
.struct_size = sizeof(RadChatFormat),
.name = "flint",
.reasoning_open = "<think>",
.reasoning_close = "</think>",
.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 = "<tool_call>",
.name_suffix = "",
.call_end = "</tool_call>",
.arg_prefix = "<arg_key>",
.arg_name_suffix = "</arg_key>",
.arg_value_prefix = "<arg_value>",
.arg_value_suffix = "</arg_value>",
.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
+272
View File
@@ -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 <arch/rad_fp8.h>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
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 */
+10
View File
@@ -0,0 +1,10 @@
# Built in radiance's tree, or standalone against an installed radiance
# (`cmake -S arch/museglimmer -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); 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)
+71
View File
@@ -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: `<to=self>` 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|>
* <atem:function_calls>
* <atem:invoke name="NAME">
* <atem:parameter name="k">value</atem:parameter>
* </atem:invoke>
* </atem:function_calls>
*
* 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[] = {"<atem:function_calls>"};
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 = "<atem:function_calls>";
x.section_close = "</atem:function_calls>";
x.call_open = "<atem:invoke ";
x.name_prefix = "name=\"";
x.name_suffix = "\">";
x.call_end = "</atem:invoke>";
x.arg_prefix = "<atem:parameter name=\"";
x.arg_name_suffix = "\">";
x.arg_value_suffix = "</atem:parameter>";
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 */
+847
View File
@@ -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 <arch/rad_arch.h>
#include <arch/rad_block_museglimmer_vision.h>
#include <arch/rad_block_muse_dflash.h>
#include <arch/rad_calib_full.h>
#include "chat.h"
#include <cmath>
#include <cstdlib>
#include <vector>
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<Layer> 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<int> 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<float> 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
+10
View File
@@ -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=<radiance prefix>`); 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)
File diff suppressed because it is too large. Load diff
+30 -6
View File
@@ -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) {
+93
View File
@@ -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<int>* out) {
std::vector<int> 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); } },
+35 -1
View File
@@ -943,6 +943,36 @@ void report_running(int card) {
}
}
int64_t stuck_ms();
std::atomic<bool> 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;
+7
View File
@@ -12,6 +12,7 @@
#include "rad_abi.h"
#include "rad_device.h"
#include <atomic>
#include <cstdint>
#include <map>
#include <functional>
@@ -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<int64_t> 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
+1
View File
@@ -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<int64_t> dev_stuck_exit_ms{60000};
int64_t dev_stuck_ms() {
const auto f = dev()->stuck_ms;
return f ? f() : 0;
+16
View File
@@ -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<std::string>* 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<CardSample> sample_cards(const std::string& root, const std::vector<std::string>& 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);
File diff suppressed because it is too large. Load diff
+279
View File
@@ -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 <cstddef>
#include <cstdint>
#include <string>
#include <vector>
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<StepRecord>* out) const;
private:
std::vector<StepRecord> 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<double> 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<int32_t> 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<StepRecord> steps; /* the steps the phase ran, in order */
uint64_t steps_lost = 0; /* records the ring overwrote before they were read */
std::vector<RequestTiming> 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<StepRecord>& 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<json>& 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<json>& runs);
/* The same over the numbers at the given JSON pointers, keyed by the pointer with '/' as '.'. */
json summarize_paths(const std::vector<json>& runs, const std::vector<std::string>& 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<CardSample>& 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<Finding>& 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<StepRecord>& 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<CorpusEntry> 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<CorpusEntry>* 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_<anything>` is a
* name the report would print. A name the engine does not read as configuration is not reported. */
std::vector<std::string> 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 */
+42
View File
@@ -423,6 +423,48 @@ Facts collect(const std::string& root, const std::vector<std::string>* managed)
return f;
}
std::vector<CardSample> sample_cards(const std::string& root, const std::vector<std::string>& 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<CardSample> 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)
+16 -4
View File
@@ -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<StallWatch> 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;
+8
View File
@@ -788,6 +788,10 @@ private:
std::vector<std::unique_ptr<server::Sink>>& sinks, bool fit_pool,
const char* tag, int every_s,
const std::function<void(size_t, double)>& 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> kld_;
std::vector<float*> 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. */
+12 -5
View File
@@ -3551,8 +3551,11 @@ static int sweep_container(RadFile* file, std::vector<LoadRun>& 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;
}
+698
View File
@@ -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 <algorithm>
#include <chrono>
#include <cmath>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <filesystem>
#include <functional>
#include <fstream>
#include <memory>
#include <thread>
#include <vector>
extern char** environ;
namespace rad {
namespace {
using json = diag::json;
int64_t steady_ns() {
return std::chrono::duration_cast<std::chrono::nanoseconds>(
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<int32_t> 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<diag::Finding> findings = diag::check(facts0, rfacts);
std::vector<std::string> 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<diag::CardSample> 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<int32_t>* 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<std::string>() + "\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<int32_t>* 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<int64_t>(8, want / 50)) return RAD_OK;
chars = std::max<int64_t>(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<Job>& early,
const std::vector<Job>& 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<diag::CardSample> cards0 = diag::sample_cards("", serving_bdfs);
const SchedMetrics before = sched_.metrics();
const uint64_t seq0 = sched_.step_record_count();
std::vector<std::unique_ptr<server::Sink>> sinks;
auto submit = [&](const std::vector<Job>& jobs) -> int {
std::vector<std::unique_ptr<Request>> reqs;
for (const Job& jb : jobs) {
sinks.push_back(std::make_unique<server::Sink>((size_t)jb.max_tokens + 64));
auto r = std::make_unique<Request>();
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<int> 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<bool()>& 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<diag::CardSample> 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<server::SinkToken> toks((size_t)std::max<int64_t>(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<int(bool warm, std::vector<Job>*)>& make,
std::vector<json>* out) -> int {
diag::PhaseInput in;
std::vector<Job> 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<diag::CorpusEntry> 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<std::string> 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<const diag::CorpusEntry*> es;
for (const auto& e : corpus)
if (e.category == cat) es.push_back(&e);
std::vector<json> 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<Job>* 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<json>(rs.begin() + (std::ptrdiff_t)from, rs.end())) } });
}
int64_t reqs = 0, stopped = 0;
for (const json& r : rs) {
reqs += r["requests"]["count"].get<int64_t>();
stopped += r["requests"]["stopped_on_eos"].get<int64_t>();
}
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<json> rs;
RAD_TRY(measure("concurrency " + std::to_string(n), diag::PhaseKind::Decode,
[&](bool warm, std::vector<Job>* 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<json> rs;
int64_t got = 0;
RAD_TRY(measure("prefill " + std::to_string(want), diag::PhaseKind::Prefill,
[&](bool warm, std::vector<Job>* 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<int64_t>(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<int>() <= 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<int>();
/* 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<int64_t>(1 << 16, ctx_limit / 2);
const int after = 16;
std::vector<json> rs;
for (int r = -1; r < runs; ++r) {
std::vector<Job> 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<std::string>().c_str(), u["metric"].get<std::string>().c_str(),
u["spread_pct"].get<double>(), 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<std::string>());
}
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<std::string>().c_str(), (long long)cmp["identical"].get<int64_t>(),
(long long)cmp["compared"].get<int64_t>(), cmp["acceptance_verdict"].get<std::string>().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 */
+1 -1
View File
@@ -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);
+1
View File
@@ -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 */
+4 -1
View File
@@ -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"
+3
View File
@@ -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). */
+20 -1
View File
@@ -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());
+244 -13
View File
@@ -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<float>& 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<int64_t> shape,
std::vector<float>&& 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<float> 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<float> 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<float> 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<float> 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) {
+11
View File
@@ -49,6 +49,10 @@ struct SrcTensor {
std::vector<int64_t> 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<float> 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_;
+62 -3
View File
@@ -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<std::pair<int64_t, int64_t>> rad_keep_complement(
int64_t tables, int64_t size, std::vector<std::pair<int64_t, int64_t>> 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<std::pair<int64_t, int64_t>> 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<std::pair<int64_t, int64_t>> 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
+23 -1
View File
@@ -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<std::pair<int64_t, int64_t>> keep_; /* keep_cached: (blob offset, bytes) */
int fd_ = -1;
const RadFileHeader* hdr_ = nullptr;
@@ -168,6 +175,21 @@ private:
std::unordered_map<std::string_view, int64_t> 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<std::pair<int64_t, int64_t>> rad_keep_complement(
int64_t tables, int64_t size, std::vector<std::pair<int64_t, int64_t>> 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
+2
View File
@@ -71,6 +71,8 @@ struct AudioRequest {
std::vector<float> ref_audio;
std::vector<int32_t> ref_cu;
std::vector<int32_t> ref_frame;
/* Reference-direction guidance: the negative prompt's own map into the same clips. */
std::vector<int32_t> 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 */
+23 -3
View File
@@ -292,7 +292,10 @@ int AudioDriver::submit(std::unique_ptr<AudioRequest> 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<AudioRequest> 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<float>(R_RAUD), q.ref_audio.data(), q.ref_audio.size() * 4);
std::memcpy(hptr<int32_t>(R_RCU), q.ref_cu.data(), q.ref_cu.size() * 4);
std::memcpy(hptr<int32_t>(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<int32_t>(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();
+3 -3
View File
@@ -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",
+16
View File
@@ -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;
}
+12
View File
@@ -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) ----------------
*
+13 -2
View File
@@ -356,8 +356,10 @@ void IdleTiers::plan_writeback(int64_t max_entries, std::vector<TierJob>* 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<BlockHash>* 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);
+4
View File
@@ -156,6 +156,10 @@ public:
void take_clean(std::vector<BlockHash>* 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);
+50 -2
View File
@@ -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;
}
+16 -2
View File
@@ -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<BlockHash> drop_wait_;
std::vector<BlockHash> 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<int64_t> 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_. */
+9
View File
@@ -152,6 +152,14 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& 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<VramFacts>& 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;
+9 -1
View File
@@ -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<MemFile*>(op);
const int64_t end = f->pos + n;
if (end > (int64_t)f->data.size()) f->data.resize((size_t)end);
+389 -8
View File
@@ -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<int64_t>(f2, (int64_t)std::max(1, max_image_tokens) * f2);
video_max_pixels = std::max<int64_t>(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<int64_t> 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<int64_t>(1, pyround(ih));
gw = std::max<int64_t>(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<int64_t> 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<int64_t>(std::min<int64_t>(n, num_frames), total);
n = std::max<int64_t>(temporal, (n / temporal) * temporal);
n = std::min<int64_t>(n, total);
std::vector<int64_t> 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<int32_t>* bounds,
std::vector<int32_t>* kk, bool torch, int* prec) {
std::vector<int32_t>* 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<double> 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<int32_t>* 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<int32_t> 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<const Frame*>& 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<const Frame*>& 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<Item>* 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<Item>* 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<Item>();
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<const Frame*> 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<Item>* 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<const Frame*> frames;
std::vector<int64_t> 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<Item>();
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<Frame> 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<const Frame*> 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<int32_t> tt = encode_text_ ? encode_text_(ts) : std::vector<int32_t>{};
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<Item>* 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<Item>* 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<Item>* 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<int64_t> sample_cb(const VideoInfo& info, const void* user) {
const SampleArgs* a = static_cast<const SampleArgs*>(user);
return a->gemma4 ? sample_frames_gemma4(info, a->fps, a->hi)
: sample_frames(info, a->fps, a->lo, a->hi);
}
std::vector<int64_t> muse_sample_cb(const VideoInfo& info, const void* user) {
const SampleArgs* a = static_cast<const SampleArgs*>(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<Item>* out,
@@ -2434,8 +2810,13 @@ int Processor::video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* 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);
}
+39 -2
View File
@@ -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 <img> placeholders </img>; 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 <image_start> <|patch|>*N
* <image_end>; a video one <vid_start>, then per temporal group the text `Time: T s`
* and <|video|>*N rows, the groups separated by <|vid_frame_separator|> and closed by
* <vid_end>, 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, <vid_start>, <vid_end> 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<Item>* out, std::string* why) const;
int image_pixtral(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int image_radio(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int image_muse(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
int video_radio(const Video& v, std::shared_ptr<Item>* 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<int32_t> tok_tiles_;
int video_gemma4(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
int video_muse(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
VisionConfig cfg_{};
AudioConfig acfg_{};
@@ -494,6 +513,21 @@ std::vector<int64_t> 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<int64_t> 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<float>* 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);
+20
View File
@@ -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<int> diagnose_concurrency = { 1, 2, 4, 8 }; /* --diagnose-concurrency */
std::vector<int> 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
+1 -1
View File
@@ -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) {
+7 -2
View File
@@ -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];
}
}
+88 -2
View File
@@ -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<int64_t>(q, max_rows / q * q);
rows = std::max<int64_t>(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<int64_t>(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 */
+175 -14
View File
@@ -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<int64_t>(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<int64_t>(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<int64_t>(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<int64_t>(reserve, 0);
const int64_t Q = std::max<int64_t>(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<int64_t>(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<int64_t>(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<int64_t>(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<int64_t>(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>(
(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>((int64_t)waiting_.size(), std::max<int64_t>(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>(
(int64_t)waiting_.size() - (int64_t)at - 1,
std::min<int64_t>(
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<int64_t>(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<int64_t>(0, mixed_target_prefill_planned_ - had);
const int64_t left = std::max<int64_t>(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<std::mutex> 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<std::chrono::nanoseconds>(step_end - step_start_).count();
m_.step_ns += ns;
mixed_target_observe_locked(ns);
(this->*record_step_)(ns, std::chrono::duration_cast<std::chrono::nanoseconds>(
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<int64_t>(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<std::mutex> lk(mu_);
mixed_target_observe_locked(ns);
}
uint64_t Scheduler::step_record_count() const {
std::lock_guard<std::mutex> lk(mu_);
return step_ring_.count();
}
size_t Scheduler::step_record_capacity() const {
std::lock_guard<std::mutex> lk(mu_);
return step_ring_.capacity();
}
uint64_t Scheduler::step_records(uint64_t from, std::vector<diag::StepRecord>* out) const {
std::lock_guard<std::mutex> 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
+37 -2
View File
@@ -17,6 +17,7 @@
#include "lookup.h"
#include "metrics.h"
#include "ngram.h"
#include "diag/diagnose.h"
#include <chrono>
#include <condition_variable>
@@ -230,6 +231,17 @@ public:
void take_completed(std::vector<uint64_t>* 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<diag::StepRecord>* 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;
+3
View File
@@ -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;
+23 -11
View File
@@ -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<int32_t>* ids_out) {
auto render_ref = [&](size_t i, std::vector<int32_t>* ids_out,
std::vector<int32_t>* 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<int32_t>* ids_out) {
auto render = [&](const std::string& t, std::vector<int32_t>* ids_out,
std::vector<int32_t>* 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) +
+3
View File
@@ -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;
+4
View File
@@ -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;
};
+13
View File
@@ -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());
+2
View File
@@ -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_;
+41 -2
View File
@@ -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<const std::string&>().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: <why>", 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<const std::string&>());
} 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());
+2 -1
View File
@@ -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;
+4 -1
View File
@@ -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<std::string> chat_format_markers(const ChatFormat& f) {
std::vector<std::string> 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,
+3
View File
@@ -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
+149 -9
View File
@@ -1063,7 +1063,8 @@ int ReplyParser::create(std::shared_ptr<const ReplyFormat> 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);
+61
View File
@@ -0,0 +1,61 @@
{%- macro flint_text(t) -%}
{%- if t is string -%}
{{- t | replace("<think>", "") | replace("</think>", "") | replace("<|begin_of_text|>", "&lt;|begin_of_text|&gt;") | replace("<|end_of_text|>", "&lt;|end_of_text|&gt;") | replace("<|system|>", "&lt;|system|&gt;") | replace("<|developer|>", "&lt;|developer|&gt;") | replace("<|user|>", "&lt;|user|&gt;") | replace("<|assistant|>", "&lt;|assistant|&gt;") | replace("<|observation|>", "&lt;|observation|&gt;") -}}
{%- 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 <tools></tools> XML tags:
<tools>
{%- for tool in tools %}
{%- set fn = tool.function if tool.function is defined else tool %}
{{ fn | tojson(ensure_ascii=False) }}
{%- endfor %}
</tools>
For each function call, output the function name and arguments within the following XML format:
<tool_call>{function-name}<arg_key>{arg-key-1}</arg_key><arg_value>{arg-value-1}</arg_value>...</tool_call>
{% 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 %}<think>{{ m.reasoning_content }}</think>{% 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 -%}
<tool_call>{{ fn.name }}
{%- for k, v in fn.arguments.items() -%}
<arg_key>{{ k }}</arg_key><arg_value>{{ v | tojson(ensure_ascii=False) if v is not string else v }}</arg_value>
{%- endfor -%}
</tool_call>
{%- endfor -%}
{%- endif -%}
{%- elif m.role == 'tool' -%}
<|observation|><tool_response>{{ flint_text(m.content) }}</tool_response>
{%- endif -%}
{%- endfor -%}
{%- if ns.tools_pending -%}
{{ tool_preamble }}
{%- endif -%}
{%- if add_generation_prompt -%}
<|assistant|>
{%- endif -%}
Binary file not shown.
+2
View File
@@ -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
+32
View File
@@ -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 <flint checkpoint> --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
+43
View File
@@ -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 <flint checkpoint> --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
@@ -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
+20
View File
@@ -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
+44
View File
@@ -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 <Ling-3.0-tiny bf16 checkpoint> --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
+10
View File
@@ -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 <Muse-Glimmer-30B> --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.
+35
View File
@@ -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 <Muse-Glimmer-30B> --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
+22
View File
@@ -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 <Muse-Glimmer-30B> --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
+305 -5
View File
@@ -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 `<bos>[S0]transcript`, the reference frames, an audio EOS frame (sixteen
codebook EOS indices, all zero), then `<bos>[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
`<bos>[S0]<ins_bos>instructions<ins_eos>input`; 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,
+90
View File
@@ -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.
+186
View File
@@ -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
`<think>...</think>`.
- 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.
+86 -5
View File
@@ -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]
+4 -2
View File
@@ -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.<name>:` | 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
+41
View File
@@ -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`
+46
View File
@@ -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
Loaded 100 of 166 files, more files were not shown because too many files have changed in this diff. Show more