diff --git a/CMakeLists.txt b/CMakeLists.txt index 7067f941..e8104369 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -1,7 +1,7 @@ cmake_minimum_required(VERSION 3.21) # VERSION is the server release that /version reports. The plugin ABI version is separate and is # read from abi/rad_abi.h below. -project(radiance VERSION 1.10.0 LANGUAGES C CXX) +project(radiance VERSION 1.12.0 LANGUAGES C CXX) set(CMAKE_CXX_STANDARD 20) set(CMAKE_CXX_STANDARD_REQUIRED ON) @@ -305,6 +305,9 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$") add_subdirectory(libavx) endif() add_subdirectory(arch) +# spechub: the linear-MTP coupling kernels (--draft-coupling). Built by default; without the flag +# no op resolves to its rows. +add_subdirectory(plugin/spechub) add_subdirectory(tools) if(RAD_BUILD_TESTS) enable_testing() diff --git a/NOTICE b/NOTICE index 46f0ffd9..58d10852 100644 --- a/NOTICE +++ b/NOTICE @@ -15,10 +15,12 @@ Written by Deadcode, with contributions from: adaptive draft window, the MoE prefill forms, the sorted operand's decode kernel, two K blocks a pass for up to 80 routed rows, --prefill-span, the towers' lookup tables counted once, and for Gemma 4 its assistant head as a drafter that reads the trunk's cache, bf16 checkpoints, the fused - w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, and the - Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files + w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, the + Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, and Gemma 4's E2B/E4B form (KV-shared + layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B - mechkbfan: the token embedding in the pinned host pool -- Code000: the n-gram gather on the card and the MTP head's history-pass skip +- Code000: the n-gram gather on the card and the MTP head's history-pass skip, and the MTP draft + coupling with its cooperative verify (--draft-coupling) - 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 @@ -33,7 +35,10 @@ Written by Deadcode, with contributions from: - Perire: Gemma 4 26B-A4B with z-lab's DFlash drafter -- its plugin, its kernels in libr4d (the windowed paged attention, pair_argmax, the fused sandwich joins and expert_scale) and the host emulator that tests them, the prefill split into two slices with their all-reduces beside the - compute, and the vocabulary-sharded draft head + compute, and the vocabulary-sharded draft head; Gemma 4 31B on four cards (its all-reduces fused + with the junctions, overlapped with the compute and sent compressed, chained launches with block + drafters), the embedding scale rounded as Hugging Face rounds it, and block drafters' drafts + accepted on the card - redxherring: --model taking a Hugging Face repo id - Smellyyyy: the idea behind --prefill-interleave - gearwave00001: /v1/messages as Claude Code sends it @@ -41,25 +46,43 @@ Written by Deadcode, with contributions from: - sfjes: Gemma 4 31B dense -- its plugin, its two attention classes and their kernels, and prefix reuse that leaves a windowed group alone -- and --host-headroom-mib - zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg - PR 50, and Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime + PR 50, Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime, and Fish Audio drama-3 -- its + plugin, its codec encoder and decoder, voice cloning from reference clips, and the torch.save + reader - mici81: Gemma 3 dense (TranslateGemma 27B) -- its plugin, the windowed h128 attention, the sandwich junction's all-reduce and its DFlash2 drafter -- the fp8_v4 and k6_v4 KV caches, GPTQ's factorisations through LAPACK and a column-split linear's Hessian from per-rank parts, - R4D_AR_MAX_BLOCKS for two engines on one set of cards, and added tokens decoded as HuggingFace - decodes them + R4D_AR_MAX_BLOCKS for two engines on one set of cards, added tokens decoded as HuggingFace + decodes them, the MXFP4 GEMM rows for one to 64 rows and the tiled prefill GEMM's TN=4 form, the + fp8 and int8 heads read once up to 128 rows, the pipelined prefill of one sequence on a second + lane, Gemma 3's junctions under a lossy wire, the block drafter's short block + (--draft-short-from) and the f16 delta-net state cache - eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the - out-of-tree test at the tree's VOPD setting + out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8 + linears' operands directly - davetha: JSON Schema patterns read unanchored, with their shorthand classes and escapes - Nunze: the eight-rank all-reduce's bands, weighted shards from the PCIe links and pieces, the sampler's candidate width at eight ranks, the image test stage's parallelism, budgets and exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose - name the opener opens + name the opener opens, GLM-5.3-Flash's vision tower and processor, its decode at a few rows and + its DSA indexer split over the ranks, a host-tier restore that makes room as pressure does, KV + groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA + row form (--tp-attn-split rows) and DELETE /sessions - John McDonough: GLM-5.3-Flash -- its plugin, its blocks (mHC streams, KDA, the DSA indexer and sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the one-sequence KV floor over the live plan, and prefill staging paid by expert residency - Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and - the bringup time in /stats + the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped + rotation +- C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual + projection +- 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) +- lortht: Krea 2's rebalance of the text taps +- 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 +- gostar: snapshot-backed prefix KV kept across recomputes This product includes software from the following projects, each under the MIT License. The license text is in the file named beside each. diff --git a/README.md b/README.md index 62139355..40c3cf3d 100644 --- a/README.md +++ b/README.md @@ -34,6 +34,8 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (22 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash) | `gemma4-31b-w4a8-df.yaml` | | Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` | | Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` | +| NVIDIA-Nemotron-3.5-Bolt-E4B bf16 (Gemma 4 E4B), NVIDIA's DFlash drafter, vision, one card | `nemotron-3.5-bolt-e4b-bf16.rad` (16 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-bf16) | `nemotron-3.5-bolt-e4b-bf16.yaml` | +| NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, one card | `nemotron-3.5-bolt-e4b-i8g.rad` (12 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-i8g) | `nemotron-3.5-bolt-e4b-i8g.yaml` | | Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` | | Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` | | Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` | @@ -45,7 +47,9 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` | | FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` | | MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` | +| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | `unlimited-ocr-bf16.yaml` | | Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` | +| Fish Audio drama-3: speech with speaker tags and inline direction, voices cloned from reference clips, whole, streamed or live; block-FP8 experts, two cards | `drama3-fp8.rad` (36 GiB) | [convert](#convert-a-checkpoint) | `drama3.yaml` | | Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` | | TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` | | GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, vision, eight cards | `glm53-flash-mxfp4.rad` (172 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` | @@ -120,7 +124,12 @@ from lyrics and a description, 44.1 kHz stereo, made at about the speed it plays speech in a voice the request describes, made in 0.6 of its playing time on one card, its first streamed audio 0.21 s after the request. Breeze-TTS-2 also speaks text while it is being written, over the `/v1/audio/speech/stream` WebSocket; it is licensed for research and non-commercial use -only. +only. Fish Audio's drama-3 speaks a script whose speakers and direction are written in it +(`<|speaker:1|>`, `[laughs]`), each speaker in the model's voice or one cloned from a reference +clip and its transcript, at 0.3 of its playing time on two cards, its first streamed audio +0.23 s after the request; under the Fish Audio Community License a service that lets others +generate speech with it needs a licence from Fish Audio, and imitating a real person's voice needs +their consent. ## Run with Docker @@ -205,6 +214,7 @@ four-rank rows have no compose file. The other models' flags are in their compos | MiniMax-H3 and FastH3 | `--tp 2 --vision-tower-placement ram` | | MiniMax-Music3 | `--tp 2` | | Breeze-TTS-2 | `--tp 1` | +| Fish Audio drama-3 | `--tp 2` | Every model here runs at up to 32 sequences a step. The Flash-Next rows (except the bf16 reference) and the 27B in bf16 keep 8: on a hybrid model each sequence holds its own recurrent state, and 32 of @@ -308,27 +318,6 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out o `CMakePresets.json` names the same runs (`ctest --preset fast`, `host`, `gpu`, `full`, `asan`), and [`docs/GUIDE.md`](docs/GUIDE.md) §1.3 describes the tiers and the test binaries' options. -## Draft acceptance - -Speculative decoding drafts up to `--num-speculative-tokens` tokens a step; the target model -verifies them in one pass, and a draft survives only if it matches what the target would have -produced. A position is verified only when every earlier position survived, so the same events -admit two ratios, and they differ only in the denominator: - -- **Conditional** -- accepted / *reached*: of the drafts actually verified at a position, how - many passed. The dashboard's live "conditionally accepted" figure and the per-position bars are - conditional. Always the higher number, and it moves with the workload. -- **Marginal** -- accepted / *drafted*: of everything the drafter proposed, how much survived. - The engine's `draft_accept` (/stats, and `radiance:draft_acceptance_ratio` on /metrics) is - marginal, cumulative over the life of the process. Lower by construction, and slow to move. - -They cannot agree, and neither is the other one broken. At depth 3 a step drafts three tokens -but reaches position 3 only when 1 and 2 both passed, so marginal is roughly the product of the -conditionals: bars reading 56/75/77% give (0.56 + 0.56x0.75 + 0.56x0.75x0.77) / 3 = 43%. A live -63% beside a lifetime 43% is one lane, two questions. Quote the conditional when asking "how -good is the drafter right now"; quote the marginal when asking "what fraction of draft work -became text." Never compare the two across that boundary. - ## Documentation | | | diff --git a/abi/rad_abi.h b/abi/rad_abi.h index ed4eefa7..fe7d8223 100644 --- a/abi/rad_abi.h +++ b/abi/rad_abi.h @@ -13,11 +13,12 @@ extern "C" { #endif /* Bumped whenever anything a plugin compiles against changes shape: this header, rad_types.h, - * rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h or rad_sample.h. Every + * rad_builder.h, rad_runtime.h, rad_device.h, rad_encoding.h, rad_quant.h, rad_sample.h or + * rad_spechub.h. Every * kind of plugin reports it, and a plugin that does not report exactly this version is refused at * load with both versions printed. 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 26u +#define RAD_ABI_VERSION 27u /* ================================================================== plugin identity */ /* One value per plugin, not flags (QUANT is 3). RAD_PLUGIN_QUANT is a quantiser plugin: @@ -549,9 +550,21 @@ typedef int (*RadKernelCollectiveFn)(int i); * - the engine refuses to serve a model with an op only a reference library implements, unless * given --debug-accept-reference-kernels; * - rad-kbench checks every other library against it. - * Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`. */ + * Without the symbol, or with 0, it is an ordinary library. Symbol name: `rad_plugin_reference`. + * + * It is a whole-library answer, because a library is usually one implementation of one thing. A + * plugin that ships a device row AND the host oracle beside it is not: marking the library would + * mark its device rows too, and the engine would refuse to serve an op that has a real kernel. + * Such a plugin exports `rad_kernel_reference` below and leaves this one 0. */ typedef int (*RadPluginReferenceFn)(void); +/* Optional, per row: nonzero says kernel `i` of rad_kernel_at is that row's reference + * implementation. Overrides `rad_plugin_reference` for the rows it is exported for, so one + * library can declare a device row (0) and its host oracle (1) side by side. A plugin that + * exports neither leaves every row classified by `rad_plugin_reference`. Symbol name: + * `rad_kernel_reference`. */ +typedef int (*RadKernelReferenceFn)(int i); + #ifdef __cplusplus } /* extern "C" */ #endif diff --git a/abi/rad_builder.h b/abi/rad_builder.h index 0ecd215e..870a75f3 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -80,6 +80,13 @@ enum { RAD_KVQ_K6V4 = 2 }; +/* The products of the prefill attention a deployment accepts in e4m3 (RadBuildCtx:: + * attn_prefill_fp8, `attn_paged`'s `prefill_fp8`): bits, so both is 3. */ +enum { + RAD_ATTN_FP8_QK = 1, /* Q.K^T, the query rounded to e4m3 after the softmax scale */ + RAD_ATTN_FP8_PV = 2 /* P.V, the probabilities rounded to e4m3 */ +}; + typedef struct RadBuildCtx { int rank; /* declare runs once per rank; the plugin declares dimensions */ int world_size; /* already divided -- the core inserts no collectives (spec §9) */ @@ -174,6 +181,17 @@ typedef struct RadBuildCtx { * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ int kv_quant; + /* ---- appended in ABI 26 (fp8 prefill attention) */ + /* RAD_ATTN_FP8_* bits from --attn-prefill-fp8: the attention products the deployment accepts + * in e4m3 rather than exactly. 0 (the zero-initialised default) is exact. A plugin passes a + * nonzero value on as `attn_paged`'s `prefill_fp8` (docs/OPS.md) and omits the parameter at + * 0, so an exact declare is unchanged. The engine refuses to start when no resolved kernel + * takes it, so a plugin that ignores the field is refused rather than silently exact. + * + * Zero-defaulted and in the padding after kv_quant, so no other field moves and a plugin built + * against the older struct is unchanged. */ + int attn_prefill_fp8; + /* ---- appended in ABI 26 (control vectors) */ /* A control vector loaded from a GGUF `controlvector` file found for this model, or null. * @@ -190,6 +208,38 @@ typedef struct RadBuildCtx { * * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ const struct RadControlVector* cvec; + + /* ---- appended in ABI 27 (row-split prefill attention) */ + /* 1 from --tp-attn-split rows: from the plugin's split threshold, a prefill-sized step under + * tensor parallelism runs attention by rows, each rank all heads of its run of the step's + * rows and an all_gather of the runs, instead of by heads. It is faster where the attention + * dominates, costs the full-width projections on every rank, and is not bit-identical to the + * head split. 0 (the zero-initialised default) is the head split. The engine sets it only + * above one rank and only for a plugin whose probe sets RadArchProbe::tp_attn_rows_ok, and + * refuses the flag otherwise. + * + * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ + int tp_attn_rows; + + /* ---- appended in ABI 27 (recurrent state at f16) */ + /* RAD_F16 from --state-cache-dtype f16: the recurrent state caches (RAD_KV_LINEAR groups) are + * stored at f16 instead of the plugin's f32, which halves the state pool, its checkpoints and + * its traffic and changes the generated text. 0 (the zero-initialised default) is the + * plugin's own width. The engine sets it only for a plugin whose probe has + * RadArchProbe::state_f16_ok and refuses the flag otherwise. + * + * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ + uint32_t state_dtype; + + /* ---- appended in ABI 27 (draft coupling) */ + /* Nonzero from --draft-coupling on: a linear serial drafter samples each round's proposal from + * its own shortlist law and declares the planes and ops the coupled verify reads + * (abi/rad_spechub.h, docs/OPS.md `mtp_couple_propose`). 0, the zero-initialised default, + * declares the greedy drafter. A plugin that cannot couple returns RAD_E_UNSUPPORTED from + * declare when it is set; the engine refuses a model whose program carries no coupled planes. + * + * Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */ + int draft_coupling; } RadBuildCtx; /* ================================================================== control vectors */ @@ -351,13 +401,20 @@ enum { RAD_KV_FULL = 0, /* paged, per-token, growing -- full attention */ RAD_KV_WINDOW = 1, /* paged, per-token, bounded by the window */ RAD_KV_LINEAR = 2, /* per-sequence, fixed size -- GDN recurrent state */ - RAD_KV_CONV = 3 /* per-sequence, a rolling window of width-1 + num_spec entries */ + RAD_KV_CONV = 3, /* per-sequence, a rolling window of width-1 + num_spec entries */ + /* Paged exactly like RAD_KV_WINDOW, but the window's floor is per sequence and set at + * runtime (R-SWA, spec §7.2): `window` is the ring's W, and a sequence keeps everything from + * position 0 up to its own prompt (prefill and image rows) plus a ring of W slots after it, + * rewritten in place. So the group is sized for the whole context plus one ring a sequence, + * never checkpointed, and never reused from the prefix cache. A model that serves a fixed + * sliding window declares RAD_KV_WINDOW instead. */ + RAD_KV_RING = 4 }; typedef struct RadKVGroupDecl { int kind; /* RAD_KV_* */ uint32_t dtype; - int64_t window; /* RAD_KV_WINDOW: the window; 0 otherwise */ + int64_t window; /* RAD_KV_WINDOW: the window; RAD_KV_RING: the ring's W; 0 otherwise */ int64_t n_head_kv; int64_t head_dim; int64_t state_dim[2]; /* RAD_KV_LINEAR: the per-head state geometry, e.g. {128,128} */ @@ -421,6 +478,17 @@ int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n); * A no-op for a PERSIST or DERIVED buffer, which is live everywhere already. */ int rad_buf_concurrent(RadBuilder* b, rad_buf buf); +/* ---- appended in ABI 27 (the second lane's window) */ +/* The second lane's window: every op the architecture issues on lane 1 is declared between + * rad_lane1_window_begin and rad_lane1_window_end. With a window a rad_buf_concurrent buffer is live + * over the window and its own declared uses instead of the whole program, so buffers used only + * outside the window (a drafter's, the heads') can share its bytes. The runtime holds the + * architecture to it: an op issued on lane 1 outside the window fails the step by name, and an op + * issued on lane 0 outside the window joins lane 1 first when lane 1 has work pending. Optional, one + * window a program; call both at declare, in order. */ +int rad_lane1_window_begin(RadBuilder* b); +int rad_lane1_window_end(RadBuilder* b); + /* An uneven shard: this rank's slice of a RAD_SHARD_ROW or RAD_SHARD_COL weight's split dimension * is [lo, hi) rather than an even 1/tp. Rows of each stacked row part for ROW, columns for COL, in * the container's unsharded units. The declared extent must already be `hi - lo` (per row part, @@ -601,7 +669,8 @@ typedef struct RadDrafterDecl { /* Where a pass leaves its proposal. 0 = the sampler's token buffer. */ rad_buf proposal; - int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1 */ + int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1, and for a BLOCK + * drafter `depth` (less is refused) */ /* BLOCK only. `mask_token` is the id every unfilled block position embeds; a block drafter * without one cannot run. `window` is the drafter's own sliding window over its own cache, 0 @@ -654,14 +723,24 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d); int rad_drafter_shared_kv(RadBuilder* b, int pos_offset); /* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on - * the AQL backend only, which keeps a completion counter per queue -- by default where the model's - * plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter - * decodes speculatively, or as RADIANCE_CHAIN says. A plugin that places work by whether a kernel - * waits in its prologue behind the one before it -- a weight read issued on lane 0 right after its - * GEMM -- asks this instead of reading the environment, so it follows that decision. Additive - * export; RAD_ABI_VERSION does not move. */ + * the AQL backend only, which keeps a completion counter per queue, where the model's plugin + * measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes + * speculatively. A plugin that places work by whether a kernel waits in its prologue behind the + * one before it -- a weight read issued on lane 0 right after its GEMM -- asks this, so it follows + * that decision. Additive export; RAD_ABI_VERSION does not move. */ int rad_chain_on(void); +/* A block drafter that also serves a shorter block: the plugin declared its query pass at `block` + * rows a sequence as well as at RadDrafterDecl::block, with the same anchor convention, so the + * core may stage a step's block at either. The short block proposes + * `block - (RadDrafterDecl::block - depth)` tokens. Called once, after rad_declare_drafter. + * + * The block is proposed whole, so its length is paid for by every drafting sequence whatever each + * verifies: at one sequence a long block's extra drafts pay, at many its rows and its weaker first + * positions cost more than they bring. The core picks per step (--draft-short-from). */ +/* ---- appended in ABI 27 (a block drafter's short block) */ +int rad_drafter_short_block(RadBuilder* b, int64_t block); + /* ================================================================== the encoder */ /* A media encoder the plugin runs on an encoder pass (RadBatch::enc). The core drives the pass and * reads its result, so the plugin declares it. A plugin that declares none serves text only, and @@ -692,6 +771,12 @@ typedef struct RadEncoderDecl { * the pass and before any other pass runs, so the planner may share its bytes with buffers * no encoder pass touches. */ rad_buf out; + + /* ---- appended in ABI 26 (one grid a pass) */ + /* 1: every segment of a pass has one grid (Item segment height), for an encoder whose + * position tables or kernels are per geometry; the core ends a pass where the grid changes. + * 0 packs segments of any grid into a pass. */ + int32_t one_grid; } RadEncoderDecl; int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d); @@ -866,6 +951,11 @@ typedef struct RadGeneratorDecl { * `cond_rows` a whole number of windows. */ int32_t chunk_tokens; int32_t chunk_bos, chunk_eos; + + /* ---- appended in ABI 26 (Krea 2's rebalance) */ + /* The RAD_GEN_COND_* options (rad_runtime.h) the plugin's COND pass serves, as a mask; a + * request asking for another is refused. 0: none. */ + uint32_t cond_opts; } RadGeneratorDecl; /* RadGeneratorDecl::beta_schedule: betas linear in sqrt(beta) (Stable Diffusion's @@ -962,7 +1052,8 @@ typedef struct RadAudioGenDecl { /* The prompt, as text the core tokenises: `{instructions}` is replaced by the request's * instructions (a piece's description, a voice's) and `{input}` by its input text (lyrics, the * words to speak), each first rewritten by the plugin's rad_arch_text_prepare when it exports - * one. Special tokens are spelled as text. */ + * one. Special tokens are spelled as text. NULL for a model that takes no instructions, which + * then declares `tmpl_plain` and has a request's instructions refused. */ const char* tmpl; /* The unconditional branch is the conditional prompt with every token but the first * `neg_keep_head` and the last `neg_keep_tail` replaced by `neg_token`, so the two branches @@ -1023,6 +1114,36 @@ typedef struct RadAudioGenDecl { * latent: `lat_num` = `lat_den` = 1, `samples_per_latent` samples a frame. */ int64_t voc_chunk; int64_t voc_context; + + /* ---- appended in ABI 27 (one-branch speech over a hybrid model, references) */ + /* Sequences a request runs: 0 or 2, the conditional and unconditional branches above; 1, the + * conditional one alone, for a model without guidance (no unconditional prompt is rendered, + * a request's guidance must be 1, and every per-entry array of a PROMPT or FRAME pass has one + * entry a lane, its `slot` the lane itself). The KV, the prompt's rows and a frame's rows then + * cost half. */ + int32_t branches; + /* Nonzero: the `{input}` slot is tokenised with its special tokens, which the template's own + * text always is, so a caller can write the model's speaker tags. The plugin's + * rad_arch_text_prepare then refuses the control tokens a caller must not write. */ + int32_t input_special; + /* References (voice cloning): with `tmpl_ref`, a request may carry up to `ref_max` of them, + * each a transcript and a clip of the voice saying it, which the plugin encodes into frames + * in the request's PROMPT pass (whole prompts only: `prompt_whole`). `tmpl_ref` is the prompt + * of a request with references, `{references}` each of them rendered from `ref_item` in turn + * and `{input}` as in `tmpl_plain`. `ref_item` is one reference: `{index}` its number from 1, + * `{text}` its transcript (rewritten by rad_arch_text_prepare as RAD_TEXT_REFERENCE) and + * `{audio}` its frames, one prompt row each (RadAudioGenBatch::ref_frame); the text before + * `{audio}` is tokenised as one segment with its special tokens (the transcript's own, which + * 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. */ + 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; } RadAudioGenDecl; int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d); @@ -1477,12 +1598,28 @@ typedef struct RadArchProbe { * libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at * startup with the plugin named. */ int32_t kv_quant_ok; + + /* ---- appended in ABI 26 (chained launches, control vectors) */ /* Nonzero when this plugin measured its speculative step faster with chained launches * (RadKernelChainFn: a dependent kernel waits in its own prologue rather than behind the * queue's barrier bit). With a drafter decoding speculatively on the AQL backend, the core - * then takes them by default; RADIANCE_CHAIN overrides either way. Zero keeps them off: plain - * decode measured slower chained, and a plugin that never measured them asks for nothing. */ + * then takes them. Zero keeps them off: plain decode measured slower chained, and a plugin + * that never measured them asks for nothing. */ int32_t chain_pays; + /* Nonzero when the plugin applies RadBuildCtx::cvec for this model. --control-vector is + * refused at startup with the plugin named when this is 0. */ + int32_t control_vector_ok; + + /* ---- appended in ABI 27 (row-split prefill attention) */ + /* Nonzero when the plugin serves RadBuildCtx::tp_attn_rows for this model. --tp-attn-split + * rows is refused at startup with the plugin named when this is 0. */ + int32_t tp_attn_rows_ok; + + /* ---- appended in ABI 27 (recurrent state at f16) */ + /* Nonzero when the plugin declares its recurrent state at f16 under RadBuildCtx::state_dtype + * and its kernels read that width. --state-cache-dtype f16 is refused at startup with the + * plugin named when this is 0. */ + int32_t state_f16_ok; } RadArchProbe; int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out); @@ -1661,11 +1798,13 @@ const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta); * as given. Training data has conventions a client does not know -- section tags on lines of * their own and lower case, no markdown in a description -- and only the plugin knows them. * - * `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8. Writes at most `cap` bytes, the NUL included, - * and returns the length the whole result needs without its NUL (call again with more room when - * it is >= cap), or a negative status for text the model cannot take. Called on HTTP threads, so - * it keeps no state. */ -enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2 }; + * `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8: the instructions, the input, or a + * reference's transcript (RadAudioGenDecl::ref_item's `{text}`). Writes at most `cap` bytes, the + * NUL included, and returns the length the whole result needs without its NUL (call again with + * more room when it is >= cap), or a negative status for text the model cannot take, with the + * reason in `out` (NUL-terminated within `cap`) when it has one to give the caller. Called on + * HTTP threads, so it keeps no state. */ +enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2, RAD_TEXT_REFERENCE = 3 }; int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap); /* The layout of a video generator's passes (rad_declare_video_generator), which only the model diff --git a/abi/rad_runtime.h b/abi/rad_runtime.h index c1cd07f6..afe5317c 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -243,6 +243,19 @@ typedef struct RadBatch { /* A video generator's pass (rad_declare_video_generator; `gen` is one of its * RAD_GEN_PASS_*): its payload. Null on every other step. */ const struct RadVideoGenBatch* vgen_b; + + /* ---- appended in ABI 26 (control vectors) */ + /* Host-side: nonzero when some row of this pass takes the loaded control vector (its + * `projection_on_rows` entry is 1). A projection skips a zero row anyway, so a block issues + * no projection op when this is 0 and the pass is the one a deployment without a vector runs. */ + int32_t control_vector; + + /* ---- appended in ABI 26 (per-segment encoder grids) */ + /* host: [enc_n_seg] each segment's grid in patches, the same values enc_coord planes 2 and 3 + * carry. A plugin that has to pick a geometry before it issues ops (a tower with one set of + * position tables per grid) reads them here; they live as long as the pass. */ + const int32_t* enc_seg_h; + const int32_t* enc_seg_w; } RadBatch; /* What a generator pass carries beside the step batch's own fields, which keep their meanings: @@ -379,13 +392,15 @@ typedef struct RadGenBatch { * where a window's end-of-text marker sits. */ const int32_t* tokens_h; /* ---- appended in ABI 26 (Krea 2's rebalance) */ - /* COND: the request's RAD_GEN_COND_* options, 0 for none. */ + /* COND: the request's RAD_GEN_COND_* options, 0 for none and on every other pass. Only + * options the plugin declares (RadGeneratorDecl::cond_opts) are set. */ int32_t cond_opts; } RadGenBatch; /* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */ enum { - RAD_GEN_COND_REBALANCE = 1 /* Krea 2: the text taps at the plugin's fixed rebalance gains */ + RAD_GEN_COND_REBALANCE = 1 /* the conditioning at the plugin's fixed rebalance gains (the + * request field `rebalance`; Krea 2: its text taps) */ }; /* An entry's flags on a DENOISE pass. */ @@ -474,6 +489,30 @@ typedef struct RadAudioGenBatch { /* VOCODE with RadAudioGenDecl::voc_chunk: the lane's first frame the pass reads, counted * from the first kept frame. 64 bits so that it starts past the struct's ABI 18 end. */ int64_t voc_frame0; + + /* ---- appended in ABI 27 (a frame head at the previous row, references) */ + /* FRAME, one value per entry ([n_seq]): the row before the frame's own row -- the one whose + * hidden state the frame is sampled from -- as its KV slot, its position, and the context + * through it (position + 1). A model whose frame head attends at that row (Fish Audio + * drama-3's codebook tower, layers bound to the language model's full-attention group) issues + * those layers there, before the language model runs at the frame's own row. */ + const int32_t* prev_slot; + const int32_t* prev_pos; + const int32_t* prev_used; + + /* PROMPT of a request with references (RadAudioGenDecl::tmpl_ref; n_ref 0 without): its + * clips' samples end to end (`ref_samples` f32 on the device), the clips' bounds in samples + * ([n_ref + 1], each a whole number of RadAudioGenDecl::ref_hop), and for every row of the + * pass the frame of the clips it is or -1 for a token row ([n_tok]), frames counted over the + * clips in order, frame f the samples [f ref_hop, (f + 1) ref_hop). A frame's row stages + * token 0; the plugin embeds the frame there instead. */ + int64_t n_ref; + int64_t ref_samples; + const float* ref_audio; + const int32_t* ref_cu; + const int32_t* ref_cu_h; + const int32_t* ref_frame; + const int32_t* ref_frame_h; } RadAudioGenBatch; /* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear @@ -738,7 +777,8 @@ int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n) * the all-reduce numbers its scratch slots per launch and the ranks must agree; a kernel with a * device-wide arrival counter must key it on the stream (libr4d's split-K GEMM does), or it may * not run here; and every buffer the second lane touches must be named to rad_buf_concurrent, - * because the planner packs transients from one linear order. */ + * because the planner packs transients from one linear order (live for the whole program, or across + * the second lane's window where the architecture declares one, abi/rad_builder.h). */ int rad_lane(RadCtx* c, int lane); int rad_lane_join(RadCtx* c, int from, int to); diff --git a/abi/rad_spechub.h b/abi/rad_spechub.h new file mode 100644 index 00000000..ca8b3fa9 --- /dev/null +++ b/abi/rad_spechub.h @@ -0,0 +1,267 @@ +/* rad_spechub.h -- the linear-MTP coupling: wire rows and the shared arithmetic. + * + * The core writes these rows and a kernel plugin reads them, so their layout is ABI. The helpers + * are header-only and stateless, so the host reference, the device kernel and the sampler share + * one definition of the wire and of the arithmetic that turns it into a token. + * + * A row lives in a U32 plane whose base and row stride are eight-byte aligned, so a state can be + * loaded whole on the device. + */ +#ifndef RAD_SPECHUB_H +#define RAD_SPECHUB_H + +#include +#include +#include + +/* The verify reads a RadSampleParams row. */ +#include "rad_sample.h" + +/* Linear MTP coupling (--draft-coupling on). One draw per drafting row, staged before the + * serial passes; one state per (temporal round, row). `base` is the request's PRE-commit output + * size, so (base, round) names one draft stream that no later step reuses. `card` is the step slot + * the advance writes, checked against RadBatch::seq_ids. `mode` 1 samples x~Q; 0 keeps the greedy + * proposal (temperature 0 or top_k 1). */ +typedef struct RadMtpCoupleDraw { + uint64_t seed, base, seq; + int32_t card; + uint32_t mode; +} RadMtpCoupleDraw; +/* status 1: x sampled from the exact q[] stored here; 0: greedy proposal kept; -1: malformed + * shortlist or row identity, greedy proposal kept. `pos` is the verify row's output position, bound + * by the host after commit; the device writes 0. ids[count..7] = -1, q[count..7] = 0. */ +typedef struct RadMtpCoupleState { + RadMtpCoupleDraw draw; + uint64_t pos; + int32_t status, round, x, count; + int32_t ids[8]; + double q[8]; +} RadMtpCoupleState; +#define RAD_MTP_COUPLE_DRAW_WORDS (sizeof(RadMtpCoupleDraw) / 4) +#define RAD_MTP_COUPLE_STATE_WORDS (sizeof(RadMtpCoupleState) / 4) +#define RAD_MTP_COUPLE_MAX_ROUNDS 8 +/* Draft stream of round r: seed ^ (KEY_DRAFT + r) at coordinate `base`. Acceptance and the + * residual draw use RAD_SAMPLE_KEY_ACCEPT / RAD_SAMPLE_KEY_RESID at the verify position. */ +#define RAD_MTP_COUPLE_KEY_DRAFT 0x4d5450434f55504cull +#ifdef __cplusplus +static_assert(sizeof(RadMtpCoupleDraw) == 32, "MTP coupling draw wire"); +static_assert(sizeof(RadMtpCoupleState) == 152, "MTP coupling state wire"); +static_assert(offsetof(RadMtpCoupleState, q) % 8 == 0, "MTP coupling q alignment"); +#endif + +/* ================================================================== the shared arithmetic + * + * Q is the FP64 softmax of an FP32 shortlist at temperature 1; P is the FP64 softmax of the + * sampler's FP32 candidate logits; uniforms are 53-bit. A coupled row therefore realises the + * filtered target law to FP64 rounding rather than sample_pick's FP32/24-bit law, and is not + * seed-identical to the ordinary pick. + */ +#ifdef __cplusplus + +#if defined(__HIPCC__) +#define RAD_SPECHUB_HD __host__ __device__ +#else +#define RAD_SPECHUB_HD +#endif + +static inline RAD_SPECHUB_HD double rad_spechub_positive(double a) { return a > 0 ? a : 0; } +static inline RAD_SPECHUB_HD bool rad_spechub_finite(double x) { + return x == x && x <= 1.7976931348623157e308 && x >= -1.7976931348623157e308; +} + +/* A 53-bit uniform in [0, 1): splitmix64 over (seed ^ key, pos), top 53 bits scaled by 2^-53. */ +static inline RAD_SPECHUB_HD double rad_spechub_uniform(uint64_t seed, uint64_t pos, uint64_t key) { + uint64_t z = (seed ^ key) * 0x9e3779b97f4a7c15ull + pos + 0x9e3779b97f4a7c15ull; + z = (z ^ (z >> 30)) * 0xbf58476d1ce4e5b9ull; + z = (z ^ (z >> 27)) * 0x94d049bb133111ebull; + z ^= z >> 31; + return (double)(z >> 11) * 0x1p-53; +} + +/* Is `s` a state the coupling's propose kernel could have written for a sampled row? The verifier + * and the engine's bind check refuse a row by this rule, on the device and on the host. */ +static inline RAD_SPECHUB_HD bool rad_mtp_couple_state_valid(const RadMtpCoupleState& s, + int64_t vocab) { + if (s.status != 1 || s.draw.mode != 1 || s.count < 1 || s.count > 8 || s.round < 1 || + s.round > RAD_MTP_COUPLE_MAX_ROUNDS) + return false; + double sum = 0; + bool has_x = false; + for (int i = 0; i < 8; ++i) { + if (i >= s.count) { + if (s.ids[i] != -1 || s.q[i] != 0) return false; + continue; + } + if (s.ids[i] < 0 || s.ids[i] >= vocab || !rad_spechub_finite(s.q[i]) || !(s.q[i] > 0) || + s.q[i] > 1) + return false; + for (int j = 0; j < i; ++j) + if (s.ids[j] == s.ids[i]) return false; + sum += s.q[i]; + has_x |= s.ids[i] == s.x; + } + return has_x && (sum - 1) <= 1e-12 && (1 - sum) <= 1e-12; +} + +/* The verify position of coupled round r (1-based): the coordinate the engine's bind and the + * sampler's row check must agree on. + * + * The sampler stages row k of a request at output position `n_out + k`, where `n_out` is the + * request's committed output length when the step is built; round r is verified at row r - 1. The + * acceptance and residual uniforms are drawn at this position. + * + * `n_out` is read from the request after the drafting step's commit. It is not rebuilt from the + * draft's pre-commit `base` plus the accepted count: the two differ when the commit emits fewer + * tokens than the card accepted (a max_tokens or context cut) or a step is carried. */ +static inline RAD_SPECHUB_HD uint64_t rad_mtp_couple_verify_pos(uint64_t n_out, int round) { + return n_out + (round > 0 ? (uint64_t)(round - 1) : 0); +} + +/* Would the verify row for draft index `k` (0-based) of a request with committed output length + * `n_out` take `c` as its coupled state? Same request and seed, the round this row's draft came + * from, the position it samples, the very token it proposes, and a state the proposer could have + * written. Anything else is a stale state from another step, and coupling against it would apply a + * law this step never drew. + * + * Asked by the sampler's step build, against the state the engine bound. The engine's own bind + * does not call it: it checks the readback against the card (draw, round, x, status) and writes + * the position with rad_mtp_couple_verify_pos, the formula here that both sides must agree on. */ +static inline RAD_SPECHUB_HD bool rad_mtp_couple_binds(const RadMtpCoupleState& c, uint64_t seq, + uint64_t seed, uint64_t n_out, int k, + int32_t draft_x, int64_t vocab) { + return c.status == 1 && c.draw.seq == seq && c.draw.seed == seed && c.round == k + 1 && + c.pos == rad_mtp_couple_verify_pos(n_out, k + 1) && c.x == draft_x && + rad_mtp_couple_state_valid(c, vocab); +} + +/* Build the stored Q from a shortlist of eight (id, score) slots. + * + * Holes (id < 0) and -inf scores carry no mass. An entry whose FP64 weight or normalized q + * underflows to zero is dropped, so the stored q[] is exactly the law the draw walks. False on an + * out-of-range id, NaN/+inf score, duplicate id or empty support (s->count = 0). */ +static inline RAD_SPECHUB_HD bool rad_mtp_couple_build_q(const int32_t* ids, const float* val, + int64_t vocab, RadMtpCoupleState* s) { + int32_t kid[8]; + float kv[8]; + int n = 0; + s->count = 0; + for (int i = 0; i < 8; ++i) { s->ids[i] = -1; s->q[i] = 0; } + for (int i = 0; i < 8; ++i) { + if (ids[i] < 0) continue; + if (ids[i] >= vocab || val[i] != val[i] || val[i] == INFINITY) return false; + if (val[i] == -INFINITY) continue; + for (int j = 0; j < n; ++j) + if (kid[j] == ids[i]) return false; + kid[n] = ids[i]; + kv[n++] = val[i]; + } + if (!n) return false; + float top = kv[0]; + for (int j = 1; j < n; ++j) + if (kv[j] > top) top = kv[j]; + double w[8], sum = 0; + for (int j = 0; j < n; ++j) { w[j] = ::exp((double)kv[j] - top); sum += w[j]; } + for (int j = 0; j < n; ++j) { + const double q = w[j] / sum; + if (q > 0) { s->ids[s->count] = kid[j]; s->q[s->count++] = q; } + } + return s->count > 0; +} + +/* Inverse CDF over the stored q with a uniform in [0, 1); index into ids. */ +static inline RAD_SPECHUB_HD int rad_mtp_couple_pick(const RadMtpCoupleState& s, double u) { + double total = 0; + for (int i = 0; i < s.count; ++i) total += s.q[i]; + double c = u * total; + for (int i = 0; i < s.count; ++i) { c -= s.q[i]; if (c < 0) return i; } + return s.count - 1; +} + +/* Residual mass r(y) = max(0, P(y) - Q(y)) of one candidate. Q tokens use their P aggregated over + * duplicate candidates, counted once at the first occurrence (`seen`). */ +static inline RAD_SPECHUB_HD double rad_mtp_couple_mass(const RadMtpCoupleState& s, const double* pq, + int32_t id, float v, float top, double sum, + unsigned* seen) { + if (id < 0 || v == -INFINITY) return 0; + for (int k = 0; k < s.count; ++k) + if (s.ids[k] == id) { + if (*seen & (1u << k)) return 0; + *seen |= 1u << k; + return rad_spechub_positive(pq[k] - s.q[k]); + } + return ::exp((double)v - top) / sum; +} + +/* The maximal coupling of the target's law P (over the surviving candidates) with the draft's Q. + * Writes the emitted token to *out and returns true, or returns false for an invalid or empty + * target. u_accept and u_resid are independent uniforms in [0, 1). + * + * The draft x is kept when P dominates Q on every Q token or when u_accept * Q(x) < P(x); otherwise + * the token is drawn from the residual (P - Q)+. The emitted token is distributed as P, and it + * equals x with probability sum min(P, Q). + * + * If FP64 cancellation leaves the residual total R at 0 while some Q token has P < Q, P is sampled + * directly in FP64 with u_resid. That branch depends on (P, Q) only, never on x or a uniform. + * + * R sums r over every candidate including x. The residual walk runs only when P(x) < Q(x), where + * r(x) is exactly +0, so skipping x in the walk leaves its total equal to R bit for bit. */ +static inline RAD_SPECHUB_HD bool rad_mtp_couple_decide(const RadMtpCoupleState& s, + const int32_t* ids, const float* val, + int64_t n, int64_t vocab, double u_accept, + double u_resid, int32_t* out) { + float top = -INFINITY; + for (int64_t j = 0; j < n; ++j) { + if (ids[j] < 0) continue; + if (ids[j] >= vocab || val[j] != val[j] || val[j] == INFINITY) return false; + if (val[j] > top) top = val[j]; + } + if (top == -INFINITY) return false; + double sum = 0, pq[8] = {}; + for (int64_t j = 0; j < n; ++j) { + if (ids[j] < 0 || val[j] == -INFINITY) continue; + const double w = ::exp((double)val[j] - top); + sum += w; + for (int k = 0; k < s.count; ++k) + if (ids[j] == s.ids[k]) { pq[k] += w; break; } + } + if (!(sum > 0) || !rad_spechub_finite(sum)) return false; + int ix = -1; + bool dominated = true; + for (int k = 0; k < s.count; ++k) { + pq[k] /= sum; + dominated = dominated && pq[k] >= s.q[k]; + if (s.ids[k] == s.x) ix = k; + } + if (ix < 0) return false; /* unreachable for a rad_mtp_couple_state_valid state */ + unsigned seen = 0; + double resid = 0; + for (int64_t j = 0; j < n; ++j) + resid += rad_mtp_couple_mass(s, pq, ids[j], val[j], top, sum, &seen); + if (!dominated && !(resid > 0 && rad_spechub_finite(resid))) { + double c = u_resid * sum; + int32_t last = -1; + for (int64_t j = 0; j < n; ++j) + if (ids[j] >= 0 && val[j] != -INFINITY) { + const double w = ::exp((double)val[j] - top); + if (w > 0) { last = ids[j]; c -= w; if (c < 0) { *out = last; return true; } } + } + *out = last; + return true; + } + if (pq[ix] >= s.q[ix] || u_accept * s.q[ix] < pq[ix]) { *out = s.x; return true; } + /* Rejected, so P(x) < Q(x): not dominated, resid > 0, and some y != x has mass > 0 below. */ + double c = u_resid * resid; + int32_t last = -1; + seen = 0; + for (int64_t j = 0; j < n; ++j) { + if (ids[j] == s.x) continue; + const double m = rad_mtp_couple_mass(s, pq, ids[j], val[j], top, sum, &seen); + if (m > 0) { last = ids[j]; c -= m; if (c < 0) { *out = last; return true; } } + } + *out = last; + return true; +} + +#undef RAD_SPECHUB_HD +#endif /* __cplusplus */ +#endif /* RAD_SPECHUB_H */ diff --git a/arch/common/rad_arch.h b/arch/common/rad_arch.h index 330743bf..aa20f665 100644 --- a/arch/common/rad_arch.h +++ b/arch/common/rad_arch.h @@ -596,25 +596,30 @@ inline rad_op rw(RadBuilder* b, rad_op h, * (core/runtime/ctx.h): it is no collective, keeps no counter and touches no arena byte. * * Only at decode and verify heights, up to kPrefetchRows rows: a DFlash2 verify's 8 a sequence, a - * z-lab DFlash verify's 16, a plain decode's one. With the ceiling at 64, a prompt's prefill steps - * (40 rows on the 31B's test prompt) took the reads too, and a freshly started 31B server's first - * greedy reply then differed on 4 of 6 starts (4x R9700, the cards' memory scribbled before each - * start); at 16, and with no reads at all, 0 of 6. Per-op output hashes later located that - * divergence at the prefill all-reduce's first reuse of a double-buffered slot: a race in the - * all-reduce, which its full fence on prefill-sized messages (libr4d) cures, not in anything the - * reads touch. The reads stay off prompt steps all the same. */ + * z-lab DFlash verify's 16, a plain decode's one. Prompt steps never take the reads: beside the + * prefill all-reduces they made a fresh server's first greedy reply differ, the slot-reuse race + * that libr4d's full fence on prefill-sized four-rank messages (kArFenceFromElems) also cures. */ constexpr int64_t kPrefetchRows = 16; -/* The read goes on lane 0 itself, right after the GEMM, where its chained form (libr4d - * r4dchain_prefetch) waits for that GEMM and then reads beside the collective after it without - * holding the collective: no join between the lanes, so no record on the GEMM and no barrier bit - * on it, and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1. On - * 4x R9700 (31B DFlash2, three rounds, every reply identical): code 385-386 tok/s against 363-365, - * prose 284-286 against 269-270, decode after a 6.4k prompt 580-583 against 538-541. Only where - * launches chain (rad_chain_on, the core's decision), since a plain launch would read in series - * there; elsewhere the read goes on lane 1, behind a join from lane 0. */ +/* Where launches chain (rad_chain_on, the core's decision) the read goes on lane 0 itself, right + * after the GEMM: its chained form (libr4d r4dchain_prefetch) waits for that GEMM and then reads + * beside the collective after it without holding the collective, so there is no join between the + * lanes and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1 (on + * 4x R9700, the 31B with DFlash2 decoded 6-8% faster than with the read on lane 1). A plain launch + * would read in series on lane 0, so elsewhere the read goes on lane 1, behind a join from lane + * 0. */ inline bool prefetch_lane0() { return rad_chain_on() != 0; } +/* RADIANCE_PREFETCH_BESIDE=0 issues none of these reads. Beside another server on the same card + * the lane-1 form costs more than it gains: the card has fewer hardware queue slots than the two + * servers have queues, and the join puts a queue switch into every decode step. */ +inline bool prefetch_beside_on() { + static const bool on = [] { + const char* e = std::getenv("RADIANCE_PREFETCH_BESIDE"); + return !(e && e[0] == '0' && e[1] == 0); + }(); + return on; +} inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) { - if (!op || T > kPrefetchRows) return; + if (!op || T > kPrefetchRows || !prefetch_beside_on()) return; if (prefetch_lane0()) { RAD_ISSUE(c, op, RAD_W(w)); return; @@ -622,15 +627,9 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) { if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w)); rad_lane(c, 0); } -/* RADIANCE_PREFETCH=0 declares no reads at all (docs/GUIDE.md); read at declare. */ -inline bool prefetch_enabled() { - const char* e = std::getenv("RADIANCE_PREFETCH"); - return !(e && !std::strcmp(e, "0")); -} -/* The `prefetch` of `w`'s first `bytes`, where a library serves it and the reads are on; 0 - * otherwise. */ +/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. */ inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) { - if (!w || bytes <= 0 || !prefetch_enabled() || !rad_op_declared(b, "prefetch")) return 0; + if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0; return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w)); } @@ -687,6 +686,9 @@ struct Geom { /* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as * `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */ int64_t wire_min_bytes = 0; + /* RAD_ATTN_FP8_* bits: the attention products accepted in e4m3 (RadBuildCtx describes it). + * decl_attn passes it on as `attn_paged`'s `prefill_fp8`. */ + int attn_prefill_fp8 = 0; float eps = 1e-6f; /* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and * store `w` near 0.1, so reading it as a plain gain shrinks every normed activation 5-10x. An @@ -957,6 +959,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c, g.world = c->world_size ? c->world_size : 1; g.wire_exact= c->tp_wire_lossy ? 0 : 1; g.wire_min_bytes = c->tp_wire_min_bytes; + g.attn_prefill_fp8 = c->attn_prefill_fp8; g.eps = m->rms_eps; g.theta = m->rope_theta; g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */ @@ -1163,6 +1166,16 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name, return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw); } +/* An `attn_paged` op with the deployment's `prefill_fp8` appended (docs/OPS.md). At 0 the + * parameters are passed unchanged, so op identities and tune keys do not change. */ +inline rad_op decl_attn(RadBuilder* b, const Geom& g, const char* name, + const RadParam* params, int n, const rad_weight* weights, int nw) { + if (g.attn_prefill_fp8 == 0) return rad_decl_op(b, name, params, n, weights, nw); + std::vector p(params, params + n); + p.push_back(RAD_INT("prefill_fp8", g.attn_prefill_fp8)); + return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw); +} + /* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it * after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the * free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would diff --git a/arch/common/rad_block_attn.h b/arch/common/rad_block_attn.h index 6ee4a50c..cfe1b4c8 100644 --- a/arch/common/rad_block_attn.h +++ b/arch/common/rad_block_attn.h @@ -139,7 +139,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, /* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention * kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */ - op_attn = rw(b, RAD_OP(b, "attn_paged", + op_attn = rw(b, decl_attn(b, g, "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", 0), RAD_INT("n_head", g.n_head), diff --git a/arch/common/rad_block_attn_fp8.h b/arch/common/rad_block_attn_fp8.h index ada9ae17..765a5a53 100644 --- a/arch/common/rad_block_attn_fp8.h +++ b/arch/common/rad_block_attn_fp8.h @@ -124,7 +124,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r /* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h * explains declare vs issue order). */ - op_attn = rw(b, RAD_OP(b, "attn_paged", + op_attn = rw(b, decl_attn(b, g, "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", 0), RAD_INT("n_head", g.n_head), diff --git a/arch/common/rad_block_attn_gated.h b/arch/common/rad_block_attn_gated.h index 2b7b09dc..4e247199 100644 --- a/arch/common/rad_block_attn_gated.h +++ b/arch/common/rad_block_attn_gated.h @@ -195,7 +195,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in * * The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in * a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */ - op_attn = rw(b, RAD_OP(b, "attn_paged", + op_attn = rw(b, decl_attn(b, g, "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", 0), diff --git a/arch/common/rad_block_attn_gated_fp8.h b/arch/common/rad_block_attn_gated_fp8.h index 7c6a2352..47a01531 100644 --- a/arch/common/rad_block_attn_gated_fp8.h +++ b/arch/common/rad_block_attn_gated_fp8.h @@ -157,6 +157,21 @@ struct AttnGatedFP8 { /* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */ int ar_overlap = 0; rad_op op_ar_ov = 0; + + /* Whether step() with `own_ar` false runs the dense path a piece at a time over a caller's + * normed pieces (ArPieces::in_ready): one prefill sequence in two pieces, each the chunk a + * span of 1 makes, on the unfused prologue with one rotary component per token (every token's + * components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and + * the gate quantised by gate_quant_fp8. */ + bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const { + const int64_t T = batch->n_tok; + const RadKVGroupBatch* kvb = kv_batch(batch, kv); + return pieces && pieces->in_ready && pieces->cu && pieces->cuts(T) && + T <= 2 * pieces->rows && !op_add && !op_fill && op_gq && !op_sig && !qsa_sel && + batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL && + !(T <= fused_rows) && batch->positions && !rope_mixed(batch) && + kvb && kvb->slot_mapping && kvb->block_table && kvb->seqused; + } }; inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, @@ -293,7 +308,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int /* Declared before kv_store, which reads back the resolved `block_size` * (rad_block_attn_gated.h). */ - op_attn = RAD_OP(b, "attn_paged", + op_attn = decl_attn(b, g, "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", 0), @@ -477,6 +492,51 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, const int64_t T = batch->n_tok; + /* One prefill sequence in two pieces over the caller's normed input (takes_pieces): the + * projections, prologue, cache store, attention, gate and out projection of the first piece, + * then the second's, so the first piece's reduction runs beside all of the second piece's + * work. Each piece is the chunk a span of 1 makes: its rows, its positions, its slots, and an + * attention over its own query bounds (ArPieces::cu) that sees the cache up to its own end -- + * the first piece's position after its last row, the step's seqused for the second, which + * reads the first piece's keys from the cache as a later chunk would. */ + if (!own_ar && takes_pieces(batch, pieces)) { + const int64_t R = pieces->rows, hd = g.head_dim, qw = g.q_dim(); + const int64_t qgw = g.n_head * 2 * hd, kvw = g.n_head_kv * hd; + const int64_t tpitch = kvb->block_table_pitch; + for (int64_t p = 0; p < 2; ++p) { + const int64_t r0 = p == 0 ? 0 : R; + const int64_t n = p == 0 ? R : T - R; + const int32_t* pos = (batch->rope_pos ? batch->rope_pos : batch->positions) + r0; + qg.step(c, w.h, w.qg, T, r0, n); + kp.step(c, w.h, w.k, T, r0, n); + vp.step(c, w.h, w.v, T, r0, n); + RAD_ISSUE_N(c, op_q_norm, n * g.n_head, + bcol_at(w.qg, r0, qgw, 0, hd, n), RAD_W(w_q_norm), + brow_slice(w.q, r0, n, qw)); + RAD_ISSUE_N(c, op_k_norm, n * g.n_head_kv, + brow_slice(w.k, r0, n, kvw), RAD_W(w_k_norm), + brow_slice(w.k, r0, n, kvw)); + RAD_ISSUE_N(c, op_rope_q, n, brow_slice(w.q, r0, n, qw), praw(pos, RAD_I32, n)); + RAD_ISSUE_N(c, op_rope_k, n, brow_slice(w.k, r0, n, kvw), praw(pos, RAD_I32, n)); + RAD_ISSUE_N(c, op_kv_store, n, + brow_slice(w.k, r0, n, kvw), brow_slice(w.v, r0, n, kvw), + praw(slot + r0, RAD_I32, n), kv_cache(kv, layer)); + RAD_ISSUE_N(c, op_attn, n, + brows(w.q, T), kv_cache(kv, layer), praw2(table, RAD_I32, 1, tpitch), + praw(p == 0 ? batch->positions + R : used, RAD_I32, 1), + RAD_NONE, RAD_NONE, praw(pieces->cu + p, RAD_I32, 2), + brows(w.attn.x, T)); + RAD_ISSUE_N(c, op_gq, n * g.n_head, + bcol_at(w.qg, r0, qgw, hd, hd, n), brow_slice(w.attn.x, r0, n, qw), + brow_slice(w.attn.cq(), r0, n, qw), + brow_slice(w.attn.cs(), r0, n, fp8_blocks(qw)), + brow_slice(w.attn.x, r0, n, qw)); + o.step(c, w.attn, w.h.x, T, r0, n); + if (p == 0) pieces->hand(r0, n); + } + return; + } + if (!ext_in) nq_h.step(c, T); if (op_fill) { /* Attention-zero rank: zero output, then the reduce and the residual. */ diff --git a/arch/common/rad_block_dflash2.h b/arch/common/rad_block_dflash2.h index d26bf7ad..0dc7a52e 100644 --- a/arch/common/rad_block_dflash2.h +++ b/arch/common/rad_block_dflash2.h @@ -130,6 +130,11 @@ struct Dflash2 { /* Bytes of the next GEMM's weight read into the cache beside each all-reduce of the query * pass (prefetch_beside, rad_arch.h); 0 reads none. */ int64_t prefetch = 0; + + /* Also declare the short block's query pass (kShortBlock rows) for --draft-short-from; an + * architecture that does not call rad_drafter_short_block leaves it off and its graph as + * it was. */ + int short_block = 0; int64_t steps() const { return block - 1; } int64_t ng(int64_t n_embd) const { return group ? n_embd / group : 0; } /* The kernel projection emits [2, taps, NG] per token (prepare's set, then finish's); @@ -260,6 +265,10 @@ struct Dflash2 { rad_op op_gu[MAX_LAYERS] = {}, op_dn[MAX_LAYERS] = {}; rad_op op_gug[MAX_LAYERS] = {}; /* the gate_up|silu|quant fold; 0 when nothing serves it */ rad_op op_aconv[MAX_LAYERS] = {}, op_fconv[MAX_LAYERS] = {}; + /* The short block's (block_lo rows a sequence): the convolutions mask at the block's first row + * and the selector strides by it, so each has an op of its own; every other op is per row. */ + rad_op op_aconv_lo[MAX_LAYERS] = {}, op_fconv_lo[MAX_LAYERS] = {}, op_sel_lo = 0; + int64_t block_lo = 0; rad_op op_qrope = 0, op_krope = 0, op_store = 0, op_attn = 0; rad_op op_act = 0, op_ar = 0, op_add = 0, op_final = 0; /* The residual add folded into the norm after it (add_rmsnorm), issued in place of op_add and @@ -287,6 +296,9 @@ struct Dflash2 { static constexpr int64_t kRerankR = 32; int64_t top_w = 0; /* the coarse top-K's width: kRerankR or sel_topk */ rad_op op_hp = 0, op_sel = 0; + /* The short block: kShortBlock rows (depth 3, the window that pays at many sequences), when + * the drafter's own block is longer (rad_drafter_short_block). */ + static constexpr int64_t kShortBlock = 4; int declare(RadBuilder* b, Names& nm, const Geom& geom, const Config& c, int base_layer, rad_kvgroup group, rad_weight tok_embd, const char* ck_prefix, @@ -695,7 +707,26 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co * layers. Planned from those alone, its range would end before the coefficients' begins and * the plan could lay one over the other. Read by the last convolution as well, it is live * wherever the coefficients are. */ + block_lo = cfg.short_block && cfg.block > kShortBlock ? kShortBlock : 0; + for (int64_t l = 0; block_lo && l < g.n_layer; ++l) { + const int i = (int)l; + op_aconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv", + RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd), + RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group), + RAD_INT("NG", NG), RAD_INT("block_size", block_lo), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_acb[i])), + {w.h, w.coef}, {w.h2}); + op_fconv_lo[i] = rw(b, RAD_OP(b, "dflash_conv", + RAD_PARAMS(RAD_RANGE("T", 1, qrows), RAD_INT("hidden_size", g.n_embd), + RAD_INT("taps", cfg.taps), RAD_INT("group_size", cfg.group), + RAD_INT("NG", NG), RAD_INT("block_size", block_lo), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_fcb[i])), + {w.h, w.coef}, {w.h2}); + } if (rad_op_reads(b, op_fconv[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL; + if (block_lo && rad_op_reads(b, op_fconv_lo[g.n_layer - 1], &w.attn, 1) < 0) return RAD_E_INVAL; op_qrope = rope(qrows, g.n_head, w.q); op_krope = rope(qrows, g.n_head_kv, w.k); op_store = rw(b, RAD_OP(b, "kv_store", @@ -909,6 +940,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co RAD_INT("anchor_stride", cfg.block), RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(w_pred, w_succ)), {w.cand, w.unary, w.hp}, {w.tokens}); + if (block_lo) + op_sel_lo = rw(b, RAD_OP(b, "dflash_select", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("steps", block_lo - 1), + RAD_INT("top_k", cfg.sel_topk), RAD_INT("rank", cfg.sel_rank), + RAD_INT("n_vocab", g.n_vocab_all), + RAD_INT("anchor_stride", block_lo), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_pred, w_succ)), + {w.cand, w.unary, w.hp}, {w.tokens}); /* The reads beside the all-reduces, after every weight they read is declared. */ if (op_ar && cfg.prefetch > 0) @@ -983,6 +1022,17 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { const int64_t NG = cfg.ng(g.n_embd); const int64_t half = cfg.taps * NG; /* prepare's coefficients, then finish's */ + /* The block this pass was staged at: every drafting sequence carries the same number of rows, + * the drafter's own block or its short one (rad_drafter_short_block). */ + const int64_t blk = batch->n_seq > 0 && T % batch->n_seq == 0 ? T / batch->n_seq : 0; + const bool lo = block_lo > 0 && blk == block_lo; + if (!lo && blk != cfg.block) { + rad_step_fail(c, "dflash2: a query pass staged at a block this drafter has no ops for"); + return; + } + const rad_op* aconv = lo ? op_aconv_lo : op_aconv; + const rad_op* fconv = lo ? op_fconv_lo : op_fconv; + RAD_ISSUE_N(c, op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(w_tok), brows(w.x, T)); if (op_embed_ar) RAD_ISSUE_N(c, op_embed_ar, (int64_t)T * g.n_embd, brows(w.x, T), RAD_NONE); @@ -1005,7 +1055,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { /* ---- attention, wrapped in the two halves of one convolution */ norm(op_anorm[i], op_aan[i], w_anorm[i]); RAD_ISSUE_N(c, op_acoef[i], T, brows(w.h, T), RAD_W(w_acp[i]), brows(w.coef, T)); - RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T), + RAD_ISSUE_N(c, aconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T), wrow_slice(w_acb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T)); RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T)); @@ -1044,14 +1094,14 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { * replicated norm, so either order gives the same result; reducing first keeps x's * update agreed across ranks. */ if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - RAD_ISSUE_N(c, op_aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T), + RAD_ISSUE_N(c, aconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T), wrow_slice(w_acb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T)); add_pending = true; /* ---- the feed-forward, wrapped in the other convolution */ norm(op_fnorm[i], op_afn[i], w_fnorm[i]); RAD_ISSUE_N(c, op_fcoef[i], T, brows(w.h, T), RAD_W(w_fcp[i]), brows(w.coef, T)); - RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T), + RAD_ISSUE_N(c, fconv[i], T, brows(w.h, T), bcol(w.coef, 0, half, T), wrow_slice(w_fcb[i], 0, 1, cfg.taps * g.n_embd), brows(w.h2, T)); RAD_ISSUE_N(c, op_qh2, T, brows(w.h2, T), brows(w.h2q, T), brows(w.h2s, T)); if (op_gug[i] && T <= gated_rows) { @@ -1068,7 +1118,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { RAD_W(w_dn[i].w), RAD_W(w_dn[i].s), brows(w.h, T), RAD_NONE, w_dn[i].bref()); for (int j = 0; j < 2; ++j) prefetch_beside(c, op_pff[i][j], pff_w[i][j], T); if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); - RAD_ISSUE_N(c, op_fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T), + RAD_ISSUE_N(c, fconv[i], T, brows(w.h, T), bcol(w.coef, half, half, T), wrow_slice(w_fcb[i], 1, 1, cfg.taps * g.n_embd), brows(w.h2, T)); add_pending = true; } @@ -1107,7 +1157,7 @@ inline void Dflash2::step(RadCtx* c, const RadBatch* batch) const { } RAD_ISSUE_N(c, op_hp, S, brows(w.sel_h, S), RAD_W(w_selp), brows(w.hp, S)); - RAD_ISSUE_N(c, op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S), + RAD_ISSUE_N(c, lo ? op_sel_lo : op_sel, batch->n_seq, bcol(w.cand, 0, cfg.sel_topk, S), bcol(w.unary, 0, cfg.sel_topk, S), brows(w.hp, S), praw(batch->token_ids, RAD_I32, T), RAD_W(w_pred), RAD_W(w_succ), brows(w.tokens, batch->n_seq)); diff --git a/arch/common/rad_block_gdn_fp8.h b/arch/common/rad_block_gdn_fp8.h index 7a8f0d34..78e08c58 100644 --- a/arch/common/rad_block_gdn_fp8.h +++ b/arch/common/rad_block_gdn_fp8.h @@ -139,6 +139,13 @@ struct GdnFP8 { * trailing add, which would read the delta before the reduction. */ void step(RadCtx* c, const RadBatch* batch, bool own_ar = true, ArPieces* pieces = nullptr) const; + /* Whether step() with `own_ar` false runs the whole block a piece at a time over `pieces` + * (its piece path), asked by a caller that must know before it commits to a schedule. */ + bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const { + return pieces && pieces->cu && pieces->cuts(batch->n_tok) && + batch->n_tok <= 2 * pieces->rows && (ext_in || pieces->in_ready) && !op_add && + batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL; + } /* Whether a step of T rows issues the all-reduce itself, asked by a caller before taking it * over; and that all-reduce over rows [r0, r0 + rows) of the output. */ bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); } @@ -389,10 +396,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, * piece the chunk a span of 1 makes (the projection over its rows; the convolution, solve and * scan over its bounds, with the state handed on through the cache; the gated norm, quantiser * and out projection), so the first piece's reduction runs beside all of the second piece's - * work. The second piece reads the history the first left in the convolution slot: a spanned - * step is past the prompt's first interval, so its context length is never zero. */ - if (!own_ar && pieces && pieces->cu && pieces->cuts(T) && T <= 2 * pieces->rows && ext_in && - !op_add && S == 1 && batch->phase == RAD_PHASE_PREFILL) { + * work. The second piece reads the history the first left in the convolution slot, so each + * piece passes its own context length, its first row's position: the step's would tell the + * second piece of a prompt's first chunk that it has none. */ + if (!own_ar && takes_pieces(batch, pieces)) { const int64_t in_w = conv_dim + v_dim; for (int64_t p = 0; p < 2; ++p) { const int64_t r0 = p * pieces->rows; @@ -405,7 +412,7 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar, bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log), RAD_W(w_dt_bias), kv_cache(kv_conv, layer), praw(cu, RAD_I32, 2), bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T), - praw(cv_idx, RAD_I32, 1), praw(batch->ctx_lens, RAD_I32, 1), + praw(cv_idx, RAD_I32, 1), praw(batch->positions + r0, RAD_I32, 1), brows(w.q, T), brows(w.k, T), brows(w.v, T), brows(w.gdec, T), brows(w.beta, T)); RAD_ISSUE_N(c, op_kkt, n, diff --git a/arch/common/rad_block_gemma4_vision.h b/arch/common/rad_block_gemma4_vision.h index 6b3c8d6f..d64875c5 100644 --- a/arch/common/rad_block_gemma4_vision.h +++ b/arch/common/rad_block_gemma4_vision.h @@ -19,6 +19,15 @@ * replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the * image rows are not scaled). * + * Clipped linears (vision_config.use_clipped_linears, Gemma 4 E2B/E4B): every projection clamps its + * input and its output to bounds the checkpoint stores (`.input_min/max`, `output_min/max`; + * transformers' Gemma4ClippableLinear). The tower keeps its fused q|k|v and gate|up GEMMs, so it + * takes the input bounds of q_proj (and of gate_proj) for the fused input, q_proj's output bounds for + * q's columns, k_proj's for k's and v's, and gate_proj's output bounds for gate|up. That is exact + * where the fused parts share their bounds, as NVIDIA's E4B does in all 16 layers (k and v share the + * input bounds of q and their output bounds, up shares gate's). The bound weights are one bf16 + * element each, read by `clamp`. + * * One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an * image, or one frame of a video). Every rank runs the whole tower (engine_mm.cpp), so its weights * are replicated (RAD_SHARD_NONE) and each rank writes the rows into its own copy of the embedding @@ -41,8 +50,12 @@ struct Gemma4Vision { rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0; rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0; rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0; + /* clipped linears: the bounds (lo, hi) of the nine clamps, and the clamps */ + enum { C_QKV_IN, C_Q_OUT, C_KV_OUT, C_O_IN, C_O_OUT, C_GU_IN, C_GU_OUT, C_DN_IN, C_DN_OUT, C_N }; + rad_weight lo[C_N] = {}, hi[C_N] = {}; + rad_op op_c[C_N] = {}; }; - bool on = false, standardize = false; + bool on = false, standardize = false, clip = false; int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0; int64_t npos = 0, n_embd = 0; rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0; @@ -88,15 +101,14 @@ struct Gemma4Vision { (long long)pool, (long long)depth); return RAD_E_INVAL; } - /* Clipped linears (their bounds are buffers the vision checkpoint states as infinite) and - * any rotary or activation other than the 2-D one and gelu-tanh are refused by name. */ - if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) || - (std::strcmp(rt, "default") && std::strcmp(rt, "axial")) || + /* Any rotary or activation other than the 2-D one and gelu-tanh is refused by name. */ + if ((std::strcmp(rt, "default") && std::strcmp(rt, "axial")) || std::strcmp(act, "gelu_pytorch_tanh")) { - fprintf(stderr, "radiance: %s: this vision tower uses clipped linears, a '%s' rotary or " - "a '%s' activation, which it does not serve\n", who, rt, act); + fprintf(stderr, "radiance: %s: this vision tower uses a '%s' rotary or a '%s' " + "activation, which it does not serve\n", who, rt, act); return RAD_E_UNSUPPORTED; } + clip = rad_meta_geti(m, "vision_config.use_clipped_linears", 0) != 0; n_embd = model_embd; patch_dim = 3 * patch * patch; const int64_t kk = pool * pool; @@ -154,6 +166,27 @@ struct Gemma4Vision { l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g); l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g); l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g); + if (clip) { + /* clamp k -> the checkpoint projection whose bound it takes, and which bound */ + static const char* const proj[Layer::C_N] = { + "self_attn.q_proj", "self_attn.q_proj", "self_attn.k_proj", "self_attn.o_proj", + "self_attn.o_proj", "mlp.gate_proj", "mlp.gate_proj", "mlp.down_proj", + "mlp.down_proj" }; + static const bool in_side[Layer::C_N] = { true, false, false, true, false, true, + false, true, false }; + for (int k = 0; k < Layer::C_N; ++k) { + const char* side = in_side[k] ? "input" : "output"; + const char* lo_n = nm.f("v.blk.%lld.clip%d.lo", li, k); + const char* hi_n = nm.f("v.blk.%lld.clip%d.hi", li, k); + RAD_ARCH_TRY(map_copy(b, lo_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_min", V, li, + proj[k], side))); + RAD_ARCH_TRY(map_copy(b, hi_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_max", V, li, + proj[k], side))); + l.lo[k] = decl_w(b, lo_n, RAD_BF16, {1}, A, N, g); + l.hi[k] = decl_w(b, hi_n, RAD_BF16, {1}, A, N, g); + if (!l.lo[k] || !l.hi[k]) return RAD_E_INVAL; + } + } } b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width}); @@ -198,6 +231,11 @@ struct Gemma4Vision { RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)), RAD_WEIGHTS(w)); }; + auto clamp = [&](int64_t n, rad_weight lo, rad_weight hi) { + return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(lo, hi)); + }; auto gain = [&](rad_weight w) { return RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width), RAD_STR("dtype", "bf16"), RAD_INT("scalar", 0)), @@ -212,6 +250,19 @@ struct Gemma4Vision { char sec[48]; std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4)); for (Layer& l : L) { + /* the clamps, each in place on the one buffer its linear reads or writes (each of those + * is read by that linear alone, or by what follows it) */ + if (clip) { + using C = Layer; + const struct { int k; int64_t n; rad_buf buf; } cl[C::C_N] = { + { C::C_QKV_IN, width, b_h }, { C::C_Q_OUT, width, b_qkv }, + { C::C_KV_OUT, 2 * width, b_qkv }, { C::C_O_IN, width, b_att }, + { C::C_O_OUT, width, b_o }, { C::C_GU_IN, width, b_h }, + { C::C_GU_OUT, 2 * ff, b_gu }, { C::C_DN_IN, ff, b_ff }, + { C::C_DN_OUT, width, b_o } }; + for (const auto& e : cl) + l.op_c[e.k] = rw(b, clamp(e.n, l.lo[e.k], l.hi[e.k]), {e.buf}, {e.buf}); + } l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h}); l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv}); l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope", @@ -272,10 +323,11 @@ struct Gemma4Vision { e.out = b_out; RAD_ARCH_TRY(rad_declare_encoder(b, &e)); rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, " - "pooled %lldx%lld%s; %lld patches a pass -> %lld rows of %lld", + "pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld", (long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff, (long long)patch, (long long)pool, (long long)pool, - standardize ? ", standardised" : "", (long long)P, (long long)R, + standardize ? ", standardised" : "", clip ? ", clipped linears" : "", + (long long)P, (long long)R, (long long)n_embd); on = true; return RAD_OK; @@ -299,20 +351,33 @@ struct Gemma4Vision { RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn)); RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn)); RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn)); + /* a clamp of operand `x` in place, when the tower clips */ + auto cl = [&](const Layer& l, int k, RadOperand x) { + if (clip) RAD_ISSUE_N(c, l.op_c[k], Pn, x, RAD_W(l.lo[k]), RAD_W(l.hi[k]), x); + }; for (const Layer& l : L) { RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn)); + cl(l, Layer::C_QKV_IN, brows(b_h, Pn)); RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn)); + cl(l, Layer::C_Q_OUT, bcol(b_qkv, 0, width, Pn)); + cl(l, Layer::C_KV_OUT, bcol(b_qkv, width, 2 * width, Pn)); RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm)); RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn), bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn)); + cl(l, Layer::C_O_IN, brows(b_att, Pn)); RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn)); + cl(l, Layer::C_O_OUT, brows(b_o, Pn)); RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn)); RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn)); RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn)); + cl(l, Layer::C_GU_IN, brows(b_h, Pn)); RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn)); + cl(l, Layer::C_GU_OUT, brows(b_gu, Pn)); RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn), brows(b_ff, Pn)); + cl(l, Layer::C_DN_IN, brows(b_ff, Pn)); RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn)); + cl(l, Layer::C_DN_OUT, brows(b_o, Pn)); RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn)); RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn)); } diff --git a/arch/common/rad_block_glm_kda.h b/arch/common/rad_block_glm_kda.h index feacfde7..cd983606 100644 --- a/arch/common/rad_block_glm_kda.h +++ b/arch/common/rad_block_glm_kda.h @@ -151,7 +151,8 @@ struct GlmKda { !w.input || !w.forget_low || !w.gate_low || !w.out || w.input == w.out || w.forget_low == w.gate_low) return RAD_E_INVAL; - // All seven projections are plain BF16 in the pinned checkpoint. + // All seven projections are plain bf16 in the pinned checkpoint; under w_bf16, + // LinearFP8::declare refuses a quantised one by name. Geom bg = g; bg.w_bf16 = true; const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world); @@ -193,9 +194,6 @@ struct GlmKda { RAD_ARCH_TRY(output.declare(b, nm, bg, nm.f("blk.%d.attn_output", layer), 4096, width, RAD_SHARD_COL, group, { nm.ckpt("%s.o_proj.weight", prefix) }, act(w.core.out), w.out)); - if (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 || - !gate_b.bf16 || !output.bf16) - return RAD_E_UNSUPPORTED; if (reduce) op_ar = GlmTp::reduce(b, g, w.out); return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK; } diff --git a/arch/common/rad_block_glm_mla.h b/arch/common/rad_block_glm_mla.h index 7c54e67d..ac209466 100644 --- a/arch/common/rad_block_glm_mla.h +++ b/arch/common/rad_block_glm_mla.h @@ -3,14 +3,23 @@ * complete heads shard as rows of the shared K/V weight. prepare() exposes the normalized q latent * for the indexer; finish() consumes the indexer's selection. The caller owns the mHC residual. * - * Under tensor parallelism the 64 heads split over the ranks (GlmTp::heads): the rows of q_b and - * kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent cache are - * replicated. */ + * Under tensor parallelism the head form splits the 64 heads over the ranks (GlmTp::heads): the + * rows of q_b and kv_b, the columns of o, an all_reduce of the output; q_a, kv_a and the latent + * cache are replicated. From GlmTp::kSplitRows a prefill-sized step takes the row form instead + * (Wire::rows, Form::rows): each rank runs its run of the step's rows (GlmTp::run_of) through q_b, + * absorption, attention, expansion and the output projection with all 64 heads, then an + * all_gather lays the runs out as the whole step. The latent cache and the selection are whole on + * every rank already, so the split needs no other exchange. The gather moves half the bytes of + * the head form's all-reduce, and the attention loads each key once for all 64 heads of a row. + * The price is the three projections at full width on every rank (126 MB a layer); RowsWire::q + * unset declares neither them nor the form. */ #ifndef RAD_BLOCK_GLM_MLA_H #define RAD_BLOCK_GLM_MLA_H #include "rad_fp8.h" #include "rad_glm_tp.h" +#include #include +#include namespace rad { namespace arch { @@ -88,11 +97,28 @@ struct MlaLatent { }; struct GlmMla { + /* How a prefill-sized step under tensor parallelism runs: `heads` keeps the head form at every + * step size and spares the full-width weights' VRAM; `rows` is the row form. The plugin + * chooses (RadBuildCtx::tp_attn_rows); the block takes the choice through whether it is given + * RowsWire buffers. */ + enum class Form { heads, rows }; + /* The row form's buffers, `rows_for(max_tok)` rows each. `out` (Wire::out) must hold + * world * rows_for(T) rows, since every rank's run is gathered at full length. */ + struct RowsWire { + rad_buf q = 0, q_latent = 0, attn_latent = 0, out = 0; + ActFP8 attn{}; + }; struct Wire { ActFP8 input{}, q_low{}, attn{}; rad_buf q_raw = 0, kv_raw = 0, latent = 0, out = 0; MlaLatent::Wire core{}; + RowsWire rows{}; }; + /* The gathered row of the row form: 4096 bf16, so a run is ceil(T / world) rows. */ + static constexpr int64_t kOutRowBytes = 4096 * 2; + static int64_t rows_for(int64_t T, int world) { + return GlmTp::run_rows(T, world, kOutRowBytes); + } Geom g{}; Wire w{}; int layer = 0; @@ -103,6 +129,10 @@ struct GlmMla { MlaLatent core{}; rad_weight q_gain = 0, kv_gain = 0; rad_op op_kv_norm = 0, op_store = 0, op_ar = 0; + LinearFP8 rows_q_b{}, rows_output{}; + QuantFP8 rows_quant{}; + rad_weight rows_kv_b = 0; + rad_op op_rows_absorb = 0, op_rows_attn = 0, op_rows_expand = 0, op_rows_gather = 0; int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, const char* prefix, rad_kvgroup group, bool reduce = true, bool defer_finish = false) { @@ -160,7 +190,69 @@ struct GlmMla { GlmTp::mla_width(g.world), RAD_SHARD_COL, grp_layer(layer), { nm.ckpt("%s.o_proj.weight", prefix) }, w.attn, w.out)); if (reduce) op_ar = GlmTp::reduce(b, g, w.out); - return op_store && (!(reduce && g.world > 1) || op_ar) ? RAD_OK : RAD_E_INVAL; + if (!op_store || ((reduce && g.world > 1) && !op_ar)) return RAD_E_INVAL; + return reduce ? declare_rows(b, nm, prefix) : RAD_OK; + } + /* Declared whatever the step size, as every TP split here is: arena levels declare again at a + * smaller max_tok and must get the same graph. The gather's message bound is the all-reduce's, + * so both share one exchange instance and its scratch. */ + int declare_rows(RadBuilder* b, Names& nm, const char* prefix) { + const auto& r = w.rows; + if (!r.q || g.world < 2) return RAD_OK; + if (!r.q_latent || !r.attn_latent || !r.out || !r.attn.x || r.attn.x == r.q) return RAD_E_INVAL; + const int64_t R = rows_for(g.max_tok, g.world); + const auto wg = grp_layer(layer); + /* Whole views of the head form's container entries: one stored weight each, whose + * encoding (block fp8 at f32 scales, the decoded bf16 kv_b) the views inherit. */ + rows_q_b.stored = nm.f("blk.%d.attn_q_b.weight", layer); + RAD_ARCH_TRY(rows_q_b.declare(b, nm, g, nm.f("blk.%d.attn_q_b_rows", layer), 16384, 1536, + RAD_SHARD_NONE, wg, { nm.ckpt("%s.q_b_proj.weight", prefix) }, + w.q_low, r.q, R)); + rows_kv_b = decl_view(b, nm.f("blk.%d.attn_kv_b_rows.weight", layer), + nm.f("blk.%d.attn_kv_b.weight", layer), nullptr, RAD_BF16, + { 64 * 2 * 256, 512 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, wg); + if (!rows_kv_b) return RAD_E_INVAL; + auto project = [&](const char* mode, rad_buf in, rad_buf out) { + return rw(b, + RAD_OP(b, "mla_project", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("heads", 64), + RAD_INT("head_dim", 256), RAD_INT("latent_dim", 512), + RAD_STR("mode", mode), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(rows_kv_b)), + { in }, { out }); + }; + op_rows_absorb = project("absorb", r.q, r.q_latent); + op_rows_attn = + rw(b, + RAD_OP(b, "mla_attn", + RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("latent_dim", 512), + RAD_INT("heads", 64), RAD_INT("blocks", core.c.blocks), + RAD_INT("block_size", 4), RAD_F64("scale", 1.0 / std::sqrt(256.0)), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { r.q_latent, w.core.selected, w.core.length }, { r.attn_latent }); + op_rows_expand = project("expand", r.attn_latent, r.attn.x); + RAD_ARCH_TRY(rows_quant.declare(b, g, r.attn, 16384)); + rows_output.stored = nm.f("blk.%d.attn_output.weight", layer); + RAD_ARCH_TRY(rows_output.declare(b, nm, g, nm.f("blk.%d.attn_output_rows", layer), 4096, + 16384, RAD_SHARD_NONE, wg, + { nm.ckpt("%s.o_proj.weight", prefix) }, r.attn, r.out, + R)); + op_rows_gather = rw(b, + RAD_OP(b, "all_gather", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", 4096, g.max_tok * 4096), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { r.out }, { w.out }); + return op_rows_absorb && op_rows_attn && op_rows_expand && op_rows_gather ? RAD_OK + : RAD_E_INVAL; + } + /* From the TP split threshold, and while the last rank's run is not empty (always at that + * threshold for up to 8 ranks); the same answer on every rank, as the gather needs. */ + bool rows_take(int64_t T) const { + return op_rows_gather && GlmTp::splits(T, g.world) && + (g.world - 1) * rows_for(T, g.world) < T; } void prepare(RadCtx* ctx, const RadBatch* batch) const { const auto* kb = kv_batch(batch, kv); @@ -173,17 +265,39 @@ struct GlmMla { kv_a.step(ctx, w.input, w.kv_raw, T); q_norm.step(ctx, T); RAD_ISSUE_N(ctx, op_kv_norm, T, brows(w.kv_raw, T), RAD_W(kv_gain), brows(w.latent, T)); - q_b.step(ctx, w.q_low, w.core.q, T); + if (!rows_take(T)) q_b.step(ctx, w.q_low, w.core.q, T); RAD_ISSUE_N(ctx, op_store, T, bcol(w.latent, 0, 256, T), bcol(w.latent, 256, 256, T), praw(kb->slot_mapping, RAD_I32, T), kv_cache(kv, layer)); } void finish(RadCtx* ctx, const RadBatch* batch) const { const int64_t T = batch->n_tok; + if (rows_take(T)) { + finish_rows(ctx, T); + return; + } core.step(ctx, T); attn_quant.step(ctx, T); output.step(ctx, w.attn, w.out, T); if (op_ar) RAD_ISSUE_N(ctx, op_ar, T * 4096, brows(w.out, T), RAD_NONE); } + /* This rank's rows [first, first + n) end to end; the last rank's run may be short, and the + * gather sends its unwritten tail rows, which land past T. */ + void finish_rows(RadCtx* ctx, int64_t T) const { + const auto& r = w.rows; + const GlmTp::Run run = GlmTp::run_of(T, g.world, g.rank, kOutRowBytes); + const int64_t first = run.first, n = run.rows; + rows_q_b.step(ctx, w.q_low, r.q, T, first, n, 0); + RAD_ISSUE_N(ctx, op_rows_absorb, n, brows(r.q, n), RAD_W(rows_kv_b), brows(r.q_latent, n)); + RAD_ISSUE_N(ctx, op_rows_attn, n, brows(r.q_latent, n), kv_cache(kv, layer), + brow_slice(w.core.selected, first, n, core.c.blocks), + brow_slice(w.core.length, first, n, 1), brows(r.attn_latent, n)); + RAD_ISSUE_N(ctx, op_rows_expand, n, brows(r.attn_latent, n), RAD_W(rows_kv_b), + brows(r.attn.x, n)); + rows_quant.step(ctx, n); + rows_output.step(ctx, r.attn, r.out, n); + RAD_ISSUE_N(ctx, op_rows_gather, run.run * 4096, brows(r.out, run.run), + brows(w.out, g.world * run.run)); + } }; } } // namespace rad::arch diff --git a/arch/common/rad_block_glm_vision.h b/arch/common/rad_block_glm_vision.h index 83b85ec6..f5278552 100644 --- a/arch/common/rad_block_glm_vision.h +++ b/arch/common/rad_block_glm_vision.h @@ -1,7 +1,7 @@ /* rad_block_glm_vision.h -- GLM-5.3's vision tower (transformers' Glm5NextVisionModel), served by * glm5next. * - * WHAT IT COMPUTES, per encoder pass (RadBatch::enc): + * What it computes, per encoder pass (RadBatch::enc): * * x = patches @ Wp^T + bp the Conv3d patch embedding as a linear layer; a * patch row is (channel, frame, y, x), no position diff --git a/arch/common/rad_block_hc.h b/arch/common/rad_block_hc.h index 523f1f3d..3a602e5f 100644 --- a/arch/common/rad_block_hc.h +++ b/arch/common/rad_block_hc.h @@ -365,36 +365,25 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE); } -/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to: - * every block leaves its delta in the activation its norm produced, and the input is dead by - * then. */ /* ================================================================== the control-vector projection * - * A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). Turned on - * for a request, a steered layer's wide stream is projected off that layer's direction right after - * the feed-forward's write: + * A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). For a + * request that takes it, a steered layer's wide stream loses its component along that layer's + * direction right after the feed-forward's write: * - * h[s] -= scale * (h[s] . v) * v for each of the hc streams s + * h[s] -= scale * (h[s] . v) * v for each of the hc streams s * - * which is llama.cpp's `--cvec-mode project` and the operation the Qwen3.8-Flash-Next package - * documents. The dot is per stream, not on the stream mean: the patch applies it to the - * [n_embd, hc, tokens] view where `mul_mat(v, cur)` reduces over dim 0 alone. + * This is llama.cpp's `--cvec-mode project`. The dot is per stream, not on the stream mean, as + * llama.cpp's `mul_mat(v, cur)` over the [n_embd, hc, tokens] view reduces dim 0 alone. * - * Two properties the architecture plugin does not have to think about, both here: + * The switch is per request: `on` is a derived buffer of one int32 per row + * (core/sched/derive.cpp, `projection_on_rows`), so a step that mixes a projected conversation + * with a stock one projects only the rows that asked. The kernel neither reads nor writes a zero + * row, and a pass with no row on issues nothing (RadBatch::control_vector). `scale` is the norm + * the file stored for the layer times the package's own scale. * - * - **the switch is per request.** `on` is a derived buffer of one int32 per token row - * (core/sched/derive.cpp's `projection_on_rows`), so a step that mixes a projected - * conversation with a stock one projects exactly the rows that asked for it. All zeros is the - * stock model: the kernel skips a zero row without reading or writing it, so an unprojected - * request's stream is the one the stock model computes. (The *deployment* is not bit-identical - * to one with no vector: the direction table's VRAM can move an expert or a KV block, which is - * the tie-level variance radiance documents elsewhere. Measured, docs/GUIDE.md 4.10.) - * - **the parameters travel with the file.** `scale` is the norm the file stored for that layer - * (times the package's own `scale`, read from its JSON), and the direction row is sliced from - * the table at issue, so nothing is configured per deployment or scanned per layer. - * - * One instance per layer: `declare` emits an op only when the vector steers that layer, so a - * deployment without a vector declares no op, no buffer and no branch in the step. */ + * One instance per layer; `declare` emits an op only where the vector steers, so a deployment + * without a vector declares no op and no buffer. */ struct HcProject { rad_op op = 0; /* 0: this layer is not steered (or there is no vector) */ const float* dir = nullptr; /* this layer's row of the device direction table */ @@ -456,9 +445,10 @@ struct HcProject { } /* Rows [r0, r0 + rows) of the stream. The whole step is r0 = 0; the pipelined step issues one - * call per piece, in the same place in the graph. */ - void step(RadCtx* c_, int64_t r0, int64_t rows) const { - if (!op) return; + * call per piece, in the same place in the graph. Nothing is issued on a pass where no row + * takes the vector (RadBatch::control_vector): every row would be skipped. */ + void step(RadCtx* c_, const RadBatch* batch, int64_t r0, int64_t rows) const { + if (!op || !batch || !batch->control_vector) return; RAD_ISSUE_N(c_, op, rows, brow_slice(h, r0, rows, hc * n), praw(dir, RAD_F32, n), @@ -466,6 +456,9 @@ struct HcProject { } }; +/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to: + * every block leaves its delta in the activation its norm produced, and the input is dead by + * then. */ inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const { if (!op_write) return; if (takes_gather(T)) { diff --git a/arch/common/rad_block_mlp_fp8.h b/arch/common/rad_block_mlp_fp8.h index 3ffb8448..27ef1fce 100644 --- a/arch/common/rad_block_mlp_fp8.h +++ b/arch/common/rad_block_mlp_fp8.h @@ -75,6 +75,20 @@ struct MlpFP8 { void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); } /* One row slice of the whole block; `rows <= 0` means the rest of the step. */ void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const; + /* The slice in its parts, for a caller that runs the norm and the tail elsewhere (qwen35_fp8's + * pipelined prefill puts both on the second lane): the projections from the normed input to + * the delta in `w.h.x`, then the all-reduce and add this block issues itself. */ + void body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const; + void tail(RadCtx* c, int64_t r0, int64_t rows) const; + /* The block's all-reduce over rows [r0, r0 + rows) of the output, at `overlap` where declared + * (a caller that runs it beside other work). */ + void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const { + RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd, + brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE); + } + /* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */ + int ar_overlap = 0; + rad_op op_ar_ov = 0; }; inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire, @@ -129,6 +143,17 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co RAD_INT("min_bytes", g.wire_min_bytes)), RAD_NOWEIGHTS), {w.h.x}, {w.h.x}); + /* The same collective for a caller that runs it beside other work (issue_ar): at `overlap` 1 + * it gets the rows that hold fewer CUs while waiting on the link. */ + if (g.world > 1 && ar_overlap > 0) + op_ar_ov = 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_INT("overlap", ar_overlap)), + RAD_NOWEIGHTS), + {w.h.x}, {w.h.x}); /* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */ if (add_out) @@ -149,6 +174,11 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const { if (rows <= 0) rows = T - r0; nq_h.step(c, T, r0, rows); + body(c, T, r0, rows); + tail(c, r0, rows); +} + +inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const { if (op_gated && rows <= gated_rows) { RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd), brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w), @@ -160,6 +190,9 @@ inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const gq_ffn.step(c, w.gate_up, T, r0, rows); } down.step(c, w.ffn, w.h.x, T, r0, rows); +} + +inline void MlpFP8::tail(RadCtx* c, int64_t r0, int64_t rows) const { if (op_ar && !(ar_out && ar_fused_ok(g, rows))) RAD_ISSUE_N(c, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE); if (op_add) diff --git a/arch/common/rad_block_mtp_hc.h b/arch/common/rad_block_mtp_hc.h index 6f1fe749..be59f389 100644 --- a/arch/common/rad_block_mtp_hc.h +++ b/arch/common/rad_block_mtp_hc.h @@ -73,6 +73,7 @@ #include "rad_block_hc.h" #include "rad_block_moe_fp8.h" #include "rad_block_mtp_fp8.h" /* mtp_draft_head_q2(): one reading of the 2-bit head */ +#include "rad_spechub.h" /* RAD_MTP_COUPLE_*: the coupling wire */ #include "rad_qsa.h" #include "rad_block_vit.h" @@ -108,6 +109,9 @@ struct MtpHcBlock { /* Vocab-parallel pairs, declared only when the head is sharded: (int32 id, f32 value) * pairs stored as f32, this rank's top-R and the all-gathered world * R. */ rad_buf dpair = 0, dgath = 0; + /* --draft-coupling: [max_seqs] draws and [depth, max_seqs] states, both PERSIST across + * the serial passes (round 1 resets the logical stream, not the plane). */ + rad_buf couple_draws = 0, couple_state = 0; AttnGatedFP8::Wire attn{}; MoeFP8::Wire mlp{}; QsaIndexer::Wire qsa{}; @@ -158,6 +162,9 @@ struct MtpHcBlock { rad_op op_dsel = 0, op_dback = 0; rad_op op_logits = 0, op_dquant = 0, op_dlogits = 0, op_dtopk = 0, op_drerank = 0; rad_op op_dgather = 0, op_dmerge = 0; + /* --draft-coupling: one op a round. The ABI freezes `round` as a parameter, so a round + * cannot be an operand and each gets its own declared op. */ + rad_op op_couple[RAD_MTP_COUPLE_MAX_ROUNDS] = {}; /* rad_arch.h's vocab-head rule, asked through the block by whoever sizes `dlog` and the pair * planes. */ @@ -422,6 +429,25 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l if (!op_dgather || !op_dmerge) return RAD_E_INVAL; } if (!op_dquant || !op_dlogits || !op_dtopk) return RAD_E_INVAL; + /* The coupled proposal: one op a round, after the final rerank/merge, over the shortlist + * whose column 0 is the proposal. Linear chains only: x is a token, while a tree reads + * column 0 as a parent index. The engine refuses other drafters; this check keeps a + * mismatched declaration from writing tokens into a tree plane. */ + if (w.couple_draws || w.couple_state) { + if (!w.couple_draws || !w.couple_state || depth < 1 || + depth > RAD_MTP_COUPLE_MAX_ROUNDS || !op_drerank || (g.world > 1 && !op_dmerge)) + return RAD_E_UNSUPPORTED; + for (int round = 1; round <= depth; ++round) { + op_couple[round - 1] = rw(b, RAD_OP(b, "mtp_couple_propose", + /* The whole vocabulary: `row_topk` reports global ids and the merge keeps + * them, while `g.n_vocab` is this rank's shard. */ + RAD_PARAMS(RAD_RANGE("M", 1, g.max_seqs), RAD_INT("n_vocab", g.n_vocab_all), + RAD_INT("round", round), RAD_INT("max_rounds", depth)), + RAD_NOWEIGHTS), + { w.didx, w.dval, w.couple_draws }, { w.didx, w.couple_state }); + if (!op_couple[round - 1]) return RAD_E_INVAL; + } + } } /* Keep the carry `hin` live through the head's last op: it is written before the mixer and * lm_head run, and the planner could otherwise give its bytes to them (silently lowering @@ -429,6 +455,7 @@ inline int MtpHcBlock::declare(RadBuilder* b, Names& nm, const Geom& geom, int l { rad_op last = op_logits; if (q2) last = op_dmerge ? op_dmerge : op_drerank ? op_drerank : op_dtopk; + if (op_couple[0]) last = op_couple[depth - 1]; if (rad_op_reads(b, last, &w.hin, 1) < 0) return RAD_E_INVAL; } return RAD_OK; @@ -524,6 +551,19 @@ inline void MtpHcBlock::step(RadCtx* c, const RadBatch* batch) const { RAD_ISSUE_N(c, op_drerank, L, brows(w.hout, L), RAD_W(w_lm), brows(w.didx, L), brows(w.didx, L), brows(w.dval, L), RAD_NONE); } + /* After the final reranked shortlist: column 0 is what ADV_TAKE reads, and a sampled row + * replaces it with its x. Round 1 runs in the history pass (r < 0), later rounds in their + * own passes. */ + if (op_couple[0]) { + const int round = r < 0 ? 1 : r; + if (round < 1 || round > depth) { + rad_step_fail(c, "MTP coupled round exceeds the declared draft depth"); + return; + } + RAD_ISSUE_N(c, op_couple[round - 1], L, brows(w.didx, L), brows(w.dval, L), + praw(batch->seq_ids, RAD_I32, batch->n_seq), + brows(w.couple_draws, L), RAD_B(w.couple_state)); + } } else { RAD_ISSUE_N(c, op_logits, L, brows(w.hout, L), RAD_W(w_lm), brows(w.logits, L)); } diff --git a/arch/common/rad_block_sam.h b/arch/common/rad_block_sam.h new file mode 100644 index 00000000..e9453205 --- /dev/null +++ b/arch/common/rad_block_sam.h @@ -0,0 +1,1457 @@ +/* rad_block_sam.h -- Unlimited-OCR's DeepEncoder: SAM ViT-B/16, then CLIP ViT-L/14 on its map. + * + * The reference is the checkpoint's own deepencoder.py, used by + * modeling_unlimitedocr.py's image branch: + * + * sam_model(SxS picture, S in {1024, 640}) -> [1, S/64, S/64, 1024] + * patch_embed: conv 16x16 stride 16 (768 out), + pos_embed resampled to the patch grid: + * get_abs_pos_sam returns the [1,64,64,768] table unchanged at 64, and bicubic-antialias + * resamples it (fp32, cast back to the model dtype) at any other grid -- 40 for a 640 tile + * 12 blocks, w 768, 12 heads x 64: LayerNorm, qkv, attention with DECOMPOSED RELATIVE + * POSITION (rel_pos_h/rel_pos_w, 27 rows) inside a 14x14 window of the patch grid + * (padded to a multiple of 14: 70x70 for a 64 grid, 42x42 for a 40 grid), and one + * whole-grid window on blocks 2, 5, 8 and 11 (tables of 2*grid-1 rows; get_rel_pos + * resizes the 127-row table to 79 linearly at a 40 grid -- the `sam_attn` op does it); + * proj; LayerNorm; mlp 3072 exact gelu; mlp proj + * neck: conv 1x1 256 (no bias), LayerNorm2d 256, conv 3x3 256 (no bias), LayerNorm2d 256 + * net_2: conv 3x3 stride 2 -> 512 at half (no bias); net_3: -> 1024 at a quarter (no bias) + * vision_model(patches=the sam map) -> CLIP ViT-L/14, M*M+1 tokens + * class token + the map as patch_embeds (NO pixels) + position_embedding, whose 257 rows + * (cls + a 16x16 grid) get_abs_pos resamples bicubic-antialias to the map's grid (cls row 0 + * passthrough) -> 101 rows at a 640 tile; + * pre_layrnorm eps 1e-5; 24 layers, w 1024, 16 heads x 64: LayerNorm, fused qkv, dense + * attention over all tokens, out_proj; LayerNorm; fc1 4096 quick_gelu; fc2 + * fuse: cat(clip rows 1:, the map) -> 2048 -> the projector linear -> 1280 + * layout: every map line of M rows is closed by `image_newline`, the view by + * `view_seperator` -> M*(M+1)+1 rows (273 for a 1024 view, 110 for a 640 tile) + * + * ============================== The one op the engine must add ============================== + * + * SAM's attention logits are + * + * scale * q.k + q.Rh[i_h, j_h] + q.Rw[i_w, j_w] + * + * with Rh/Rw read from the relative-position tables at the (query, key) grid offsets. The + * per-pair term is a dot of the query with a vector that depends on BOTH rows, so it folds into + * neither q, k nor v, and no declared op takes a bias operand (attn_dense's operands are + * q, k, v, cu, out). This block therefore declares its attention as `sam_attn`: + * + * params M(range), head_dim, n_head, grid_h, grid_w, window, scale(f64), dtype + * operands q, k, v, cu_seqlens (i32), out -- rows n_head*head_dim each + * weights rel_pos_h, rel_pos_w -- [2*win-1 or 2*grid-1, head_dim] + * for each cu segment of grid_h*grid_w rows in row-major order: with `window` > 0 pad the grid + * to multiples of `window` with zero rows (deepencoder's window_partition pads AFTER norm1; + * the pad rows take part in the softmax exactly as the reference's do), cut it into + * window x window tiles, each tile attending to all of its rows; with `window` 0 one tile is + * the whole segment. logits as above, softmax in f32 over the tile's keys, out = sum_j p v_j, + * written back in the segment's row order with the pad rows dropped. Rh is deepencoder's + * get_rel_pos(table, q_h, k_h): the table at (i_h - j_h + len - 1), linearly interpolated when + * its length is not 2*max(q_h,k_h)-1 (the 127-row global table resizes to 79 at a 40 grid). + * + * probe() answers whether that op resolves. When it does not, declare() still maps and declares + * every weight (a converted container carries the tower) but declares NO tower op and NO encoder, + * which leaves the plugin text-only. Dropping the tables instead is not a usable + * approximation: without them the tower's rows reach only cosine 0.35-0.77 to the reference's. + * + * ============================== Rows and patches: two geometries ============================== + * + * core/mm stages one view as a G x (G + 4) grid of 16x16 patch rows (G = 64 for a 1024 view, + * 40 for a 640 tile; a gundam page stages its tiles and its global view in one item): the last + * kDown = 4 patch columns of every row are zeros the encoder must not read. The patch embed + * therefore runs one grid row at a time -- a G-row GEMM reading that row's first G staged patch + * rows where they lie -- so the tower sees exactly the reference's raster GxG grid. A view's + * rows are then written with an `image_newline` row closing each map line, and the view + * separator's segment (an empty kDown x kDown grid) one `view_seperator` row. + * + * The two geometries are declared as two towers over the same weights (`Geom64`, `Geom40`); + * step() picks one per pass from the pass's segment heights, which the pass packer keeps + * uniform (core/engine_mm.cpp breaks a pass when a segment's grid differs). The 40 tower's + * absolute position tables are the 64/16 tables resampled bicubic+antialias (arch/common/ + * rad_resample.h, pinned by tests/resample_golden.py against torch), computed host-side on a + * rank's first tile pass from its own `sam.pos_embed` / `clip.pos_embed` weight planes and + * staged into PERSIST buffers; everything else is the same graph at a G of 40. + */ +#ifndef RAD_BLOCK_SAM_H +#define RAD_BLOCK_SAM_H + +#include +#include + +#include +#include +#include +#include +#include + +namespace rad { +namespace arch { + +struct DeepEncoder { + /* ---- the reference's geometry, shared by both view sizes. */ + static constexpr int64_t kPatch = 16; /* SAM's patch size in pixels */ + static constexpr int64_t kDown = 4; /* patch columns per map token (net_2 x net_3) */ + static constexpr int64_t kWin = 14; /* SAM's window on the patch grid */ + static constexpr int64_t kSamW = 768; + static constexpr int64_t kSamHeads = 12; + static constexpr int64_t kSamHd = 64; + static constexpr int64_t kSamDepth = 12; + static constexpr int64_t kSamFf = 3072; /* mlp_ratio 4 */ + static constexpr int64_t kClipW = 1024; + static constexpr int64_t kClipHeads = 16; + static constexpr int64_t kClipHd = 64; + static constexpr int64_t kClipDepth = 24; + static constexpr int64_t kClipFf = 4096; + static constexpr int64_t kClipSrcMap = 16; /* the checkpoint's 16x16 CLIP table grid */ + static constexpr int64_t kClipSrcTok = kClipSrcMap * kClipSrcMap + 1; /* 257 */ + static constexpr int64_t kFused = 2048; + static constexpr int64_t kNEmbd = 1280; + static constexpr int64_t kPatchDim = 3 * kPatch * kPatch; /* 768: a staged patch row */ + static constexpr int64_t kMerge = kDown * kDown; /* 16 patches a row */ + /* Tiles one tower invocation batches. max_patches/kSamTok bounds a pass (10 at the 40 grid, + * 4 at 64 for the 16384-patch default); the cap keeps the activation set modest. */ + static constexpr int64_t kBatchCap = 8; + + static bool global_block(int64_t i) { return i == 2 || i == 5 || i == 8 || i == 11; } + + /* ---- one view geometry. The 1024 view is the checkpoint's trained grid; the 640 tile is + * the gundam mode's crop / the base mode's page, whose position tables are resampled. */ + struct Geom64 { + static constexpr int64_t kGrid = 64; /* 1024 / 16 patches a side */ + static constexpr int64_t kMap = kGrid / kDown; /* 16 */ + static constexpr int64_t kPadCols = (kWin - kGrid % kWin) % kWin; /* 6 */ + static constexpr int64_t kGridP = kGrid + kPadCols; /* 70 */ + static constexpr int64_t kSamTok = kGrid * kGrid; /* 4096 */ + static constexpr int64_t kSamTokP = kGridP * kGridP; /* 4900 */ + static constexpr int64_t kClipTok = kMap * kMap + 1; /* 257 */ + static constexpr int64_t kRowsView = kMap * (kMap + 1) + 1; /* 273 */ + static constexpr int64_t kPatchView = kGrid * (kGrid + kDown); /* 4352 */ + static constexpr int64_t kSegView = kPatchView + kDown * kDown; /* 4368 */ + }; + struct Geom40 { + static constexpr int64_t kGrid = 40; /* 640 / 16 patches a side */ + static constexpr int64_t kMap = kGrid / kDown; /* 10 */ + static constexpr int64_t kPadCols = (kWin - kGrid % kWin) % kWin; /* 2 */ + static constexpr int64_t kGridP = kGrid + kPadCols; /* 42 */ + static constexpr int64_t kSamTok = kGrid * kGrid; /* 1600 */ + static constexpr int64_t kSamTokP = kGridP * kGridP; /* 1764 */ + static constexpr int64_t kClipTok = kMap * kMap + 1; /* 101 */ + static constexpr int64_t kRowsView = kMap * (kMap + 1) + 1; /* 111: 110 + sep row */ + static constexpr int64_t kPatchView = kGrid * (kGrid + kDown); /* 1760 */ + static constexpr int64_t kSegView = kPatchView + kDown * kDown; /* 1776 */ + }; + + template + struct SamLayerT { + rad_weight w_n1 = 0, b_n1 = 0, w_qkv = 0, b_qkv = 0, w_proj = 0, b_proj = 0; + rad_weight w_rh = 0, w_rw = 0; + rad_weight w_n2 = 0, b_n2 = 0, w_l1 = 0, b_l1 = 0, w_l2 = 0, b_l2 = 0; + rad_op op_n1 = 0, op_qkv = 0, op_attn = 0, op_proj = 0, op_n2 = 0, op_l1 = 0, op_l2 = 0; + rad_op op_padd = 0, op_ladd = 0; /* the residual adds, rounded apart from the GEMM */ + rad_op op_qkvw = 0, op_attnw = 0; /* the windowed path, over the padded grid */ + rad_op op_gpad = 0, op_greal = 0; /* into window_partition's order, and back */ + int64_t rel_rows = 0; + int64_t window = 0; /* 0 = the whole grid */ + /* The 40 tower's layers read the same checkpoint weights as the 64 tower's. */ + void copy_weights_from(const SamLayerT& o) { + w_n1 = o.w_n1; b_n1 = o.b_n1; w_qkv = o.w_qkv; b_qkv = o.b_qkv; w_proj = o.w_proj; + b_proj = o.b_proj; w_rh = o.w_rh; w_rw = o.w_rw; w_n2 = o.w_n2; b_n2 = o.b_n2; + w_l1 = o.w_l1; b_l1 = o.b_l1; w_l2 = o.w_l2; b_l2 = o.b_l2; + rel_rows = o.rel_rows; window = o.window; + } + }; + template + struct ClipLayerT { + rad_weight w_n1 = 0, b_n1 = 0, w_qkv = 0, b_qkv = 0, w_out = 0, b_out = 0; + rad_weight w_n2 = 0, b_n2 = 0, w_fc1 = 0, b_fc1 = 0, w_fc2 = 0, b_fc2 = 0; + rad_op op_n1 = 0, op_qkv = 0, op_attn = 0, op_out = 0; + rad_op op_cadd = 0, op_madd = 0; /* the residual adds, rounded apart from the GEMM */ + rad_op op_n2 = 0, op_fc1 = 0, op_qg = 0, op_fc2 = 0; + void copy_weights_from(const ClipLayerT& o) { + w_n1 = o.w_n1; b_n1 = o.b_n1; w_qkv = o.w_qkv; b_qkv = o.b_qkv; w_out = o.w_out; + b_out = o.b_out; w_n2 = o.w_n2; b_n2 = o.b_n2; w_fc1 = o.w_fc1; b_fc1 = o.b_fc1; + w_fc2 = o.w_fc2; b_fc2 = o.b_fc2; + } + }; + + /* ------------------------------------------------------------------ one tower a geometry + * All of the tower's OPS and ACTIVATIONS; the weights live in DeepEncoder (one checkpoint + * tensor a name, both geometries read the same planes). */ + /* One staged tile of a pass: segment `patch0`/`gw`, tile `t` of `n` in it, its output row + * block, and whether this tile closes a line (the newline row follows its map). */ + struct Tile { + int64_t patch0 = 0, gw = 0, t = 0, n = 0, rowbase = 0; + bool nl = false; + }; + + template + struct Tower { + std::vector> sam; + std::vector> clip; + + /* pass constants */ + rad_op op_cu_sam = 0, op_cu_clip = 0, op_cu_pad = 0; /* segment bounds tables */ + rad_buf b_cu_sam = 0, b_cu_clip = 0, b_cu_pad = 0; + + /* stem, neck, layout ops */ + rad_op op_patch = 0, op_sampos = 0, op_sampadd = 0; + rad_op op_neck0 = 0, op_nk1 = 0, op_unf3 = 0, op_nk2 = 0, op_nk3 = 0; + rad_op op_unf_net2 = 0, op_net2 = 0, op_unf_net3 = 0, op_net3 = 0; + rad_op op_cls = 0, op_cmap = 0, op_cpos = 0, op_cadd = 0, op_playr = 0; + rad_op op_ccopy = 0; /* pre_layrnorm output into the residual stream */ + rad_op op_fuse_clip = 0, op_fuse_sam = 0, op_proj = 0; + rad_op op_dbg1024 = 0, op_dbg1280 = 0, op_dbg768 = 0, op_dbg256 = 0; + rad_op op_newline = 0, op_sep = 0; + + /* activations, one batched run's: `B` tiles, tile-major (tile t's rows at + * [t*kSamTok, (t+1)*kSamTok)). */ + rad_buf b_x = 0, b_h = 0, b_qkv = 0, b_att = 0, b_ff = 0, b_sampos = 0; + rad_buf b_nlrow = 0; /* the newline row, computed once, pitched into the layout */ + rad_buf b_pixstg = 0; /* a tile's patch rows, packed for the single patch-embed GEMM */ + /* The windowed path's padded grid: h gathered into window_partition's order with the pad + * rows zero (so the qkv linear yields the reference's bias on them), then qkv, then + * attention. `hw`/`attw` hold kSamTokP rows. */ + rad_buf b_hw = 0, b_qkvw = 0, b_attw = 0; + rad_buf b_ids_pad = 0, b_ids_real = 0; /* pad position -> real row (-1 pad); the inverse */ + rad_buf b_n0 = 0, b_n1 = 0, b_unf3 = 0, b_n2 = 0, b_n3 = 0; + rad_buf b_unf_2 = 0, b_map2 = 0, b_unf_3 = 0, b_map = 0; + rad_buf b_c = 0, b_ch = 0, b_cq = 0, b_ca = 0, b_cf = 0, b_cg2 = 0; + rad_buf b_cpos = 0, b_fuse = 0, b_projbuf = 0; + rad_buf b_ct = 0; /* a CLIP block's projection output, before its residual add */ + /* CLIP's pre_layrnorm output: the first layer's norm1 reads this, every later one the + * residual stream (deepencoder's VitModel normalises once, before the transformer). */ + rad_buf b_cp = 0; + rad_buf b_ids_sam = 0, b_ids_clip = 0; + + /* The 40 tower's resampled absolute tables (PERSIST, staged once a rank by fill_tables; + * the gathers read them as plain operands). The 64 tower gathers straight from the + * checkpoint's weight planes and leaves these null. */ + rad_buf b_pos_tab = 0, b_cpos_tab = 0; + rad_buf p_one = 0, p_one_c = 0, p_out = 0; /* shared planes, set by declare */ + + mutable uint32_t tabs_done = 0; /* bit per rank: the resampled tables are staged */ + mutable uint32_t ids_done = 0; /* bit per rank: the position/index tables are staged */ + int64_t Bmax = 1; /* tiles one invocation batches; every per-view plane is Bmax of them */ + + static constexpr int64_t kGrid = G::kGrid; + static constexpr int64_t kMap = G::kMap; + static constexpr int64_t kGridP = G::kGridP; + static constexpr int64_t kSamTok = G::kSamTok; + static constexpr int64_t kSamTokP = G::kSamTokP; + static constexpr int64_t kClipTok = G::kClipTok; + static constexpr int64_t kRowsView = G::kRowsView; + static constexpr int64_t kPatchView = G::kPatchView; + static constexpr int64_t kSegView = G::kSegView; + + int declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad_buf out, + rad_buf one, rad_buf one_c); + void fill_tables(RadCtx* c, const DeepEncoder& w) const; + void stage_ids(RadCtx* c) const; + /* One batched tower run over `nt` (<= Bmax) staged tiles. */ + void batch(RadCtx* c, const RadBatch* batch, const Tile* tiles, int64_t nt, + bool tap, const DeepEncoder& w); + }; + + Tower t64; + Tower t40; + + /* stems, neck, projector, layout -- one checkpoint tensor a name, read by both towers. */ + rad_weight w_patch = 0, b_patch = 0, w_pos = 0; + rad_weight w_neck0 = 0, w_nk1 = 0, b_nk1 = 0, w_nk2 = 0, w_nk3 = 0, b_nk3 = 0; + rad_weight w_net2 = 0, w_net3 = 0; + rad_weight w_cls = 0, w_cpos = 0, w_playr = 0, b_playr = 0; + rad_weight w_proj = 0, b_proj = 0, w_newline = 0, w_sep = 0; + + /* shared constants: the three 1-row planes and their fills, issued by every pass. */ + rad_op op_fill_one = 0, op_fill_one_c = 0; + rad_buf b_one = 0, b_one_c = 0; + rad_buf b_out = 0; + int64_t max_patches = 0; + int64_t max_views40 = 0; + int64_t max_views64 = 0; + bool on = false; + /* The stage taps belong to the first pass only. step()/fill_tables() run on the rank's own + * step thread (one thread per DeepEncoder), so the check-then-set is safe as it stands; the + * atomic makes it safe by construction too (debug-only path, so the cost is irrelevant). The + * holder wraps the assignment in a relaxed store so the struct stays assignable: declare() + * resets a rank's Model with `m = Model{}`, which a bare std::atomic member deletes. */ + struct TapFlag { + mutable std::atomic v{false}; + TapFlag() = default; + TapFlag(const TapFlag& o) : v(o.v.load(std::memory_order_relaxed)) {} + TapFlag& operator=(const TapFlag& o) { + v.store(o.v.load(std::memory_order_relaxed), std::memory_order_relaxed); + return *this; + } + TapFlag& operator=(bool x) { + v.store(x, std::memory_order_relaxed); + return *this; + } + operator bool() const { return v.load(std::memory_order_relaxed); } + }; + mutable TapFlag tapped_; + + /* ------------------------------------------------------------------ stage taps + * RADIANCE_DEBUG_MM_BUFFERS names intermediate stages (comma separated; a name matches a tag + * by substring) and RADIANCE_DEBUG_MM_DUMP's directory receives .bf16: raw bf16 rows, one + * file a stage, for a stage-by-stage comparison against a reference encoder. The copy is + * issued on the pass's stream behind the producing op and synced, so it reads the op's output + * (unlike the after-pass dump in core/engine_mm.cpp, which sees each buffer's last writer). */ + static const char* tap_dir() { + static const char* const dir = std::getenv("RADIANCE_DEBUG_MM_DUMP"); + return dir; + } + static bool tap_names(const char** list, size_t* n) { + static const char* const env = std::getenv("RADIANCE_DEBUG_MM_BUFFERS"); + const char* const dir = tap_dir(); + *list = env; + *n = 0; + if (!env || !*env || !dir || !*dir) return false; + return true; + } + static bool tap_wants(const char* tag) { + const char* list; size_t n; + if (!tap_names(&list, &n)) return false; + const size_t tl = std::strlen(tag); + for (const char* s = list; *s; ) { + const char* e = s; + while (*e && *e != ',') ++e; + const size_t l = (size_t)(e - s); + if (l) { + for (size_t i = 0; i + l <= tl; ++i) + if (std::strncmp(tag + i, s, l) == 0) return true; + } + s = *e ? e + 1 : e; + } + return false; + } + void tap(RadCtx* c, const char* tag, rad_buf b, int64_t rows, int64_t cols, + int64_t off = 0) const { + if (rows <= 0 || cols <= 0 || rad_rank(c) != 0 || !tap_wants(tag)) return; + void* p = rad_buf_ptr(c, b); + if (!p) return; + std::vector h((size_t)(rows * cols)); + if (rad_memcpy_async(h.data(), (const char*)p + off * cols * 2, + (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", tap_dir(), tag); + if (FILE* f = std::fopen(path, "wb")) { + std::fwrite(h.data(), sizeof(uint16_t), h.size(), f); + std::fclose(f); + } + } + + /* ------------------------------------------------------------------ probe / weights */ + /* SAM's attention has no op unless one is added (the note above states it). */ + static bool probe(RadBuilder* b) { return rad_op_declared(b, "sam_attn") != 0; } + + static int wcopy(RadBuilder* b, const char* dn, const char* ck, + std::initializer_list sh, rad_weight* w, RadWeightGroup g, + int access = RAD_ACCESS_PER_REQUEST) { + RAD_ARCH_TRY(map_copy(b, dn, ck)); + *w = decl_w(b, dn, RAD_BF16, sh, access, RAD_SHARD_NONE, g); + return *w ? RAD_OK : RAD_E_INVAL; + } + + /* Every vision tensor, at the checkpoint's names. Always declared, whether or not the tower + * runs, so a converted container is complete for the pass that will. */ + int declare_weights(RadBuilder* b, Names& nm, int grp_base) { + int rc; + const RadWeightGroup gm = grp_model(); + if ((rc = wcopy(b, nm.f("sam.patch_embed.weight"), + nm.ckpt("model.sam_model.patch_embed.proj.weight"), {kSamW, kPatchDim}, + &w_patch, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.patch_embed.bias"), + nm.ckpt("model.sam_model.patch_embed.proj.bias"), {kSamW}, &b_patch, + gm)) != RAD_OK) return rc; + /* pos_embed is [1, 64, 64, 768]: one bf16 plane reshaped, which decl_weight admits. + * VOCAB access (never streamed out): the 40 tower reads it back host-side to resample + * its tile table. */ + if ((rc = wcopy(b, nm.f("sam.pos_embed"), nm.ckpt("model.sam_model.pos_embed"), + {Geom64::kSamTok, kSamW}, &w_pos, gm, RAD_ACCESS_VOCAB)) != RAD_OK) + return rc; + + t64.sam.assign((size_t)kSamDepth, SamLayerT{}); + t40.sam.assign((size_t)kSamDepth, SamLayerT{}); + for (int64_t i = 0; i < kSamDepth; ++i) { + SamLayerT& l = t64.sam[(size_t)i]; + SamLayerT& l40 = t40.sam[(size_t)i]; + const RadWeightGroup g = grp_layer(grp_base + (int)i); + const long long L = (long long)i; + /* The windowed blocks' 27-row tables are exact at any grid padded to 14; the global + * blocks' 127-row tables resize to 2*G-1 (79 at a 40 grid) inside sam_attn. */ + l.rel_rows = global_block(i) ? 2 * Geom64::kGrid - 1 : 2 * kWin - 1; + l.window = global_block(i) ? 0 : kWin; + /* One checkpoint tensor, its declared name and shape, shared by both towers. */ + auto SW = [&](const char* dn, const char* ck, std::initializer_list sh, + rad_weight* w) -> int { + char d[96], k[160]; + std::snprintf(d, sizeof d, "sam.blk.%lld.%s", L, dn); + std::snprintf(k, sizeof k, "model.sam_model.blocks.%lld.%s", L, ck); + return wcopy(b, nm.f("%s", d), nm.ckpt("%s", k), sh, w, g); + }; + if ((rc = SW("attn_norm.weight", "norm1.weight", {kSamW}, &l.w_n1)) != RAD_OK) return rc; + if ((rc = SW("attn_norm.bias", "norm1.bias", {kSamW}, &l.b_n1)) != RAD_OK) return rc; + if ((rc = SW("attn.qkv.weight", "attn.qkv.weight", {3 * kSamW, kSamW}, + &l.w_qkv)) != RAD_OK) return rc; + if ((rc = SW("attn.qkv.bias", "attn.qkv.bias", {3 * kSamW}, &l.b_qkv)) != RAD_OK) + return rc; + if ((rc = SW("attn.proj.weight", "attn.proj.weight", {kSamW, kSamW}, + &l.w_proj)) != RAD_OK) return rc; + if ((rc = SW("attn.proj.bias", "attn.proj.bias", {kSamW}, &l.b_proj)) != RAD_OK) + return rc; + if ((rc = SW("attn.rel_pos_h", "attn.rel_pos_h", {l.rel_rows, kSamHd}, + &l.w_rh)) != RAD_OK) return rc; + if ((rc = SW("attn.rel_pos_w", "attn.rel_pos_w", {l.rel_rows, kSamHd}, + &l.w_rw)) != RAD_OK) return rc; + if ((rc = SW("mlp_norm.weight", "norm2.weight", {kSamW}, &l.w_n2)) != RAD_OK) return rc; + if ((rc = SW("mlp_norm.bias", "norm2.bias", {kSamW}, &l.b_n2)) != RAD_OK) return rc; + if ((rc = SW("mlp.lin1.weight", "mlp.lin1.weight", {kSamFf, kSamW}, + &l.w_l1)) != RAD_OK) return rc; + if ((rc = SW("mlp.lin1.bias", "mlp.lin1.bias", {kSamFf}, &l.b_l1)) != RAD_OK) return rc; + if ((rc = SW("mlp.lin2.weight", "mlp.lin2.weight", {kSamW, kSamFf}, + &l.w_l2)) != RAD_OK) return rc; + if ((rc = SW("mlp.lin2.bias", "mlp.lin2.bias", {kSamW}, &l.b_l2)) != RAD_OK) return rc; + l40.copy_weights_from(l); + } + + if ((rc = wcopy(b, nm.f("sam.neck.0.weight"), nm.ckpt("model.sam_model.neck.0.weight"), + {256, kSamW}, &w_neck0, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.neck.1.weight"), nm.ckpt("model.sam_model.neck.1.weight"), + {256}, &w_nk1, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.neck.1.bias"), nm.ckpt("model.sam_model.neck.1.bias"), + {256}, &b_nk1, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.neck.2.weight"), nm.ckpt("model.sam_model.neck.2.weight"), + {256, 256 * 9}, &w_nk2, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.neck.3.weight"), nm.ckpt("model.sam_model.neck.3.weight"), + {256}, &w_nk3, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.neck.3.bias"), nm.ckpt("model.sam_model.neck.3.bias"), + {256}, &b_nk3, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.net_2.weight"), nm.ckpt("model.sam_model.net_2.weight"), + {512, 256 * 9}, &w_net2, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("sam.net_3.weight"), nm.ckpt("model.sam_model.net_3.weight"), + {1024, 512 * 9}, &w_net3, gm)) != RAD_OK) return rc; + + const char* cp = "model.vision_model."; + if ((rc = wcopy(b, nm.f("clip.cls"), nm.ckpt("%sembeddings.class_embedding", cp), + {kClipW}, &w_cls, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("clip.pos_embed"), + nm.ckpt("%sembeddings.position_embedding.weight", cp), + {kClipSrcTok, kClipW}, &w_cpos, gm, RAD_ACCESS_VOCAB)) != RAD_OK) + return rc; + if ((rc = wcopy(b, nm.f("clip.pre_norm.weight"), nm.ckpt("%spre_layrnorm.weight", cp), + {kClipW}, &w_playr, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("clip.pre_norm.bias"), nm.ckpt("%spre_layrnorm.bias", cp), + {kClipW}, &b_playr, gm)) != RAD_OK) return rc; + + t64.clip.assign((size_t)kClipDepth, ClipLayerT{}); + t40.clip.assign((size_t)kClipDepth, ClipLayerT{}); + for (int64_t i = 0; i < kClipDepth; ++i) { + ClipLayerT& l = t64.clip[(size_t)i]; + ClipLayerT& l40 = t40.clip[(size_t)i]; + const RadWeightGroup g = grp_layer(grp_base + 32 + (int)i); + const long long L = (long long)i; + auto CW = [&](const char* dn, const char* ck, std::initializer_list sh, + rad_weight* w) -> int { + char d[96], k[192]; + std::snprintf(d, sizeof d, "clip.blk.%lld.%s", L, dn); + std::snprintf(k, sizeof k, "model.vision_model.transformer.layers.%lld.%s", L, ck); + return wcopy(b, nm.f("%s", d), nm.ckpt("%s", k), sh, w, g); + }; + if ((rc = CW("attn_norm.weight", "layer_norm1.weight", {kClipW}, &l.w_n1)) != RAD_OK) + return rc; + if ((rc = CW("attn_norm.bias", "layer_norm1.bias", {kClipW}, &l.b_n1)) != RAD_OK) + return rc; + if ((rc = CW("attn.qkv.weight", "self_attn.qkv_proj.weight", {3 * kClipW, kClipW}, + &l.w_qkv)) != RAD_OK) return rc; + if ((rc = CW("attn.qkv.bias", "self_attn.qkv_proj.bias", {3 * kClipW}, + &l.b_qkv)) != RAD_OK) return rc; + if ((rc = CW("attn.out.weight", "self_attn.out_proj.weight", {kClipW, kClipW}, + &l.w_out)) != RAD_OK) return rc; + if ((rc = CW("attn.out.bias", "self_attn.out_proj.bias", {kClipW}, &l.b_out)) != RAD_OK) + return rc; + if ((rc = CW("mlp_norm.weight", "layer_norm2.weight", {kClipW}, &l.w_n2)) != RAD_OK) + return rc; + if ((rc = CW("mlp_norm.bias", "layer_norm2.bias", {kClipW}, &l.b_n2)) != RAD_OK) + return rc; + if ((rc = CW("mlp.fc1.weight", "mlp.fc1.weight", {kClipFf, kClipW}, &l.w_fc1)) != RAD_OK) + return rc; + if ((rc = CW("mlp.fc1.bias", "mlp.fc1.bias", {kClipFf}, &l.b_fc1)) != RAD_OK) return rc; + if ((rc = CW("mlp.fc2.weight", "mlp.fc2.weight", {kClipW, kClipFf}, &l.w_fc2)) != RAD_OK) + return rc; + if ((rc = CW("mlp.fc2.bias", "mlp.fc2.bias", {kClipW}, &l.b_fc2)) != RAD_OK) return rc; + l40.copy_weights_from(l); + } + + if ((rc = wcopy(b, nm.f("proj.weight"), nm.ckpt("model.projector.layers.weight"), + {kNEmbd, kFused}, &w_proj, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("proj.bias"), nm.ckpt("model.projector.layers.bias"), + {kNEmbd}, &b_proj, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("layout.image_newline"), nm.ckpt("model.image_newline"), + {kNEmbd}, &w_newline, gm)) != RAD_OK) return rc; + if ((rc = wcopy(b, nm.f("layout.view_seperator"), nm.ckpt("model.view_seperator"), + {kNEmbd}, &w_sep, gm)) != RAD_OK) return rc; + return RAD_OK; + } + + /* ------------------------------------------------------------------ op builders */ + static rad_op gemm_b(RadBuilder* b, int64_t max_m, int64_t N, int64_t K, const char* act, + rad_weight w, rad_weight bias) { + return RAD_OP(b, "gemm_nt_bias", + RAD_PARAMS(RAD_RANGE("M", 1, max_m), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("act", act), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + } + static rad_op gemm_u(RadBuilder* b, int64_t max_m, int64_t N, int64_t K, rad_weight w) { + return RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, max_m), RAD_INT("N", N), RAD_INT("K", K), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)); + } + static rad_op lnorm(RadBuilder* b, int64_t max_m, int64_t n, float eps, rad_weight w, + rad_weight bias) { + return RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, max_m), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w, bias)); + } + /* A bias-free 3x3 convolution as conv2d_unfold + gemm_nt: the unfolded rows are exactly what + * a GEMM against the checkpoint's [cout, cin, 3, 3] weight (read as [cout, cin*9]) needs. */ + static rad_op unfold(RadBuilder* b, int64_t h, int64_t w, int64_t cin, int64_t stride, + int64_t cu_div) { + return RAD_OP(b, "conv2d_unfold", + RAD_PARAMS(RAD_INT("M", h), RAD_INT("width", w), RAD_INT("cin", cin), + RAD_INT("kh", 3), RAD_INT("kw", 3), RAD_INT("stride", stride), + RAD_INT("pad", 1), RAD_INT("cu_div", cu_div), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS); + } + + /* ------------------------------------------------------------------ declare */ + /* Maps and declares the tower's weights always; declares the ops and the encoder only when + * SAM's attention op exists. `grp_base` is a free movement-group number. */ + int declare(RadBuilder* b, const RadBuildCtx* ctx, Names& nm, int64_t n_embd_model, + int grp_base) { + RAD_ARCH_TRY(declare_weights(b, nm, grp_base)); + if (n_embd_model != kNEmbd) { + fprintf(stderr, "radiance: unlimitedocr: the decoder's hidden size %lld is not the " + "DeepEncoder's %lld\n", (long long)n_embd_model, (long long)kNEmbd); + return RAD_E_UNSUPPORTED; + } + if (!probe(b)) { + rad_note(b, "the DeepEncoder tower is NOT declared: SAM's attention needs the " + "`sam_attn` op (windowed 14x14 / global grid-wide attention with decomposed " + "rel_pos_h/rel_pos_w), which no loaded kernel library provides. Its " + "weights are mapped and declared, so a converted container carries them; " + "images are refused until the op lands"); + on = false; + return RAD_OK; + } + max_patches = ctx->max_enc_patches; + if (max_patches < Geom64::kSegView) { + /* --mm-max-patches 0 (text only) or a bound below one 1024x1024 view: the tower stays + * off and the trunk serves text, which is what the flag asks for. */ + rad_note(b, "the DeepEncoder tower is NOT declared: one 1024x1024 view is %lld staged " + "patches and --mm-max-patches is %lld; images are refused", + (long long)Geom64::kSegView, (long long)max_patches); + on = false; + return RAD_OK; + } + /* The towers size their activations for the tiles one invocation batches. A pass is + * max_patches/(G::kSamTok) whole tiles at most; kBatchCap keeps the set modest. */ + max_views64 = max_patches / Geom64::kSamTok; + max_views40 = max_patches / Geom40::kSamTok; + if (max_views64 > kBatchCap) max_views64 = kBatchCap; + if (max_views40 > kBatchCap) max_views40 = kBatchCap; + if (max_views64 < 1) max_views64 = 1; + if (max_views40 < 1) max_views40 = 1; + b_out = decl_b(b, "v.out", RAD_BF16, {max_patches / kMerge, kNEmbd}); + + /* The pass's shared constants, declared FIRST because they are issued first. Liveness is + * computed over this op order, so an op declared after its readers leaves its buffer with + * a live range that begins at the reader: the packer then aliases that buffer with an + * activation written in between, and the value is gone by the time it is read (this is + * exactly what corrupted the cu_seqlens tables while they were declared at the bottom). */ + b_one = decl_b(b, "v.one", RAD_BF16, {1, kNEmbd}); + b_one_c = decl_b(b, "v.one.clip", RAD_BF16, {1, kClipW}); + op_fill_one = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", kNEmbd), + RAD_STR("dtype", "bf16"), RAD_F64("value", 1.0)), + RAD_NOWEIGHTS), + {}, {b_one}); + op_fill_one_c = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", kClipW), + RAD_STR("dtype", "bf16"), RAD_F64("value", 1.0)), + RAD_NOWEIGHTS), + {}, {b_one_c}); + RAD_ARCH_TRY(t64.declare(b, nm, *this, b_out, b_one, b_one_c)); + RAD_ARCH_TRY(t40.declare(b, nm, *this, b_out, b_one, b_one_c)); + if (!ctx->shape_probe) { + RadEncoderDecl e{}; + e.name = "deepencoder"; + e.modalities = RAD_MM_IMAGE; + e.patch_dim = kPatchDim; + e.merge = kMerge; + e.max_patches = max_patches; + e.n_embd = kNEmbd; + e.out = b_out; + /* Each pass runs one of the two towers, chosen by the segment grid. */ + e.one_grid = 1; + RAD_ARCH_TRY(rad_declare_encoder(b, &e)); + } + on = true; + rad_note(b, "DeepEncoder: SAM ViT-B/16 on two grids (%lld blocks of %lld, %lld heads x " + "%lld, window %lld on a 64x64/40x40 grid, global on 2/5/8/11, rel_pos tables " + "27/127 rows, the 127 resizing to 79 at a 40 grid) -> map -> CLIP ViT-L/14 " + "(%lld layers of %lld, %lld heads x %lld, 257/101 tokens) -> %lld -> " + "projector -> %lld; a view is 4368 (1024) or 1776 (640) staged patches -> " + "273/111 rows; the 40 grid's position tables are bicubic+antialias resamples", + (long long)kSamDepth, (long long)kSamW, (long long)kSamHeads, (long long)kSamHd, + (long long)kWin, (long long)kClipDepth, (long long)kClipW, (long long)kClipHeads, + (long long)kClipHd, (long long)kFused, (long long)kNEmbd); + return RAD_OK; + } + + /* ------------------------------------------------------------------ step */ + /* A pass is one view grid plus the square one-cell separators that close its views. A view + * segment is G x (n*G + kDown) patches: n tiles of G real patch rows side by side, with the + * reference's single newline patch column at the end of the line (only the first G patches of + * a row are read). Its output is kMap lines of n*kMap features plus one newline cell. The + * separator segment (kDown x kDown patches, no pixels) is one learned view_seperator row. */ + void step(RadCtx* c, const RadBatch* batch) { + if (!on) { + rad_step_fail(c, "unlimitedocr: an image pass reached the DeepEncoder, which this " + "program did not declare"); + return; + } + const int64_t n_patch = batch->enc_n_patch; + const int64_t n_seg = batch->enc_n_seg; + const int32_t* sh = batch->enc_seg_h; + const int32_t* sw = batch->enc_seg_w; + if (n_patch <= 0 || n_seg <= 0 || !sh || !sw) { + rad_step_fail(c, "unlimitedocr: an encoder pass the DeepEncoder does not serve: it " + "wants its segments' grids"); + return; + } + /* Validate the pass: every view segment one grid, every separator exactly one merged + * cell. A view row is a line chunk: n = w/h tiles, its last chunk carrying the line's + * newline column (w = n*h + kDown), an earlier chunk not (w = n*h). */ + int64_t n_tiles = 0; + int32_t grid = 0; + for (int64_t s = 0; s < n_seg; ++s) { + const int32_t h = sh[s], w = sw[s]; + if (h <= 0 || w <= 0) { + rad_step_fail(c, "unlimitedocr: an encoder pass with an empty segment grid"); + return; + } + if (h == kDown && w == kDown) continue; /* the one-cell view separator */ + const int32_t rem = w % h; + if (w < h || (rem != 0 && rem != (int32_t)kDown)) { + char msg[192]; + std::snprintf(msg, sizeof msg, + "unlimitedocr: a %dx%d-patch view segment is not a line of whole " + "%d-patch tiles (optionally plus the newline column)", (int)h, + (int)w, (int)h); + rad_step_fail(c, msg); + return; + } + if (grid == 0) grid = h; + if (h != grid) { + rad_step_fail(c, "unlimitedocr: an encoder pass mixed view grids; the pass packer " + "must break a pass at a geometry change"); + return; + } + n_tiles += w / h; + } + if (n_tiles > 0 && grid != Geom64::kGrid && grid != Geom40::kGrid) { + char msg[192]; + std::snprintf(msg, sizeof msg, + "unlimitedocr: an encoder pass at a %d-patch grid the DeepEncoder " + "does not serve (it declares 64 and 40)", (int)grid); + rad_step_fail(c, msg); + return; + } + /* Shared constants. */ + RAD_ISSUE(c, op_fill_one, RAD_B(b_one)); + RAD_ISSUE(c, op_fill_one_c, RAD_B(b_one_c)); + /* Walk the segments into a flat tile list. Every view tile is batched with the pass's + * other tiles (chunked at the tower's Bmax); only the separator rows are issued on their + * own. */ + std::vector tiles; + std::vector sep_rows; + int64_t pc = 0; + for (int64_t s = 0; s < n_seg; ++s) { + const int64_t h = sh[s], sw_ = sw[s]; + const int64_t rowbase = pc / kMerge; + if (h == kDown && sw_ == kDown) { + sep_rows.push_back(rowbase); + pc += h * sw_; + continue; + } + const int64_t n = sw_ / h; + const bool nl = (sw_ % h) != 0; /* the line's last chunk holds the newline col */ + for (int64_t t = 0; t < n; ++t) { + Tile tl; + tl.patch0 = pc; + tl.gw = sw_; + tl.t = t; + tl.n = n; + tl.rowbase = rowbase; + tl.nl = nl && t == n - 1; + tiles.push_back(tl); + } + pc += h * sw_; + } + const bool do_tap = !tapped_; + bool tapped_view = false; + for (size_t i = 0; i < tiles.size(); ) { + const int64_t bm = (grid == Geom64::kGrid) ? t64.Bmax : t40.Bmax; + int64_t nb = (int64_t)(tiles.size() - i); + if (nb > bm) nb = bm; + const bool tap0 = do_tap && !tapped_view; + if (grid == Geom64::kGrid) + t64.batch(c, batch, &tiles[i], nb, tap0, *this); + else + t40.batch(c, batch, &tiles[i], nb, tap0, *this); + tapped_view = true; + i += (size_t)nb; + } + /* One learned separator row; geometry-independent, so the 64 tower carries the op. */ + for (int64_t rowbase : sep_rows) + RAD_ISSUE(c, t64.op_sep, RAD_B(b_one), RAD_W(w_sep), + brow_slice(b_out, rowbase, 1, kNEmbd)); + if (tapped_view) tapped_ = true; + } +}; + +/* ------------------------------------------------------------------ tower declare */ +template +int DeepEncoder::Tower::declare(RadBuilder* b, Names& nm, DeepEncoder& w, rad_buf out, + rad_buf one, rad_buf one_c) { + static_assert(G::kGrid == DeepEncoder::Geom64::kGrid || + G::kGrid == DeepEncoder::Geom40::kGrid, "the tower serves two grids"); + const bool is40 = G::kGrid == DeepEncoder::Geom40::kGrid; + const char* sfx = is40 ? "40" : "64"; + p_one = one; p_one_c = one_c; p_out = out; + char bn[64]; +#define RAD_VN(fmtv) std::snprintf(bn, sizeof bn, fmtv, sfx) + + /* Tiles one invocation batches: the pass bound over this grid's tokens, capped. */ + Bmax = w.max_patches / kSamTok; + if (Bmax < 1) Bmax = 1; + if (Bmax > DeepEncoder::kBatchCap) Bmax = DeepEncoder::kBatchCap; + const int64_t B = Bmax; + + /* ---- activations, B tiles' worth, tile-major. */ + RAD_VN("v%s.sam.x"); b_x = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.h"); b_h = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.qkv"); b_qkv = decl_b(b, bn, RAD_BF16, {B * kSamTok, 3 * DeepEncoder::kSamW}); + RAD_VN("v%s.sam.att"); b_att = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.ff"); b_ff = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kSamFf}); + RAD_VN("v%s.sam.pos"); b_sampos = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.ids"); b_ids_sam = decl_b(b, bn, RAD_I32, {B * kSamTok}, RAD_BUF_PERSIST); + RAD_VN("v%s.sam.hw"); b_hw = decl_b(b, bn, RAD_BF16, {B * kSamTokP, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.qkvw"); b_qkvw = decl_b(b, bn, RAD_BF16, {B * kSamTokP, 3 * DeepEncoder::kSamW}); + RAD_VN("v%s.sam.attw"); b_attw = decl_b(b, bn, RAD_BF16, {B * kSamTokP, DeepEncoder::kSamW}); + RAD_VN("v%s.sam.idsp"); b_ids_pad = decl_b(b, bn, RAD_I32, {B * kSamTokP}, RAD_BUF_PERSIST); + RAD_VN("v%s.sam.idsr"); b_ids_real = decl_b(b, bn, RAD_I32, {B * kSamTok}, RAD_BUF_PERSIST); + + RAD_VN("v%s.n0"); b_n0 = decl_b(b, bn, RAD_BF16, {B * kSamTok, 256}); + RAD_VN("v%s.n1"); b_n1 = decl_b(b, bn, RAD_BF16, {B * kSamTok, 256}); + RAD_VN("v%s.nfu"); b_unf3 = decl_b(b, bn, RAD_BF16, {B * kSamTok, 256 * 9}); + RAD_VN("v%s.n2"); b_n2 = decl_b(b, bn, RAD_BF16, {B * kSamTok, 256}); + RAD_VN("v%s.n3"); b_n3 = decl_b(b, bn, RAD_BF16, {B * kSamTok, 256}); + RAD_VN("v%s.n2u"); b_unf_2 = decl_b(b, bn, RAD_BF16, {B * kSamTok / 4, 256 * 9}); + RAD_VN("v%s.m2"); b_map2 = decl_b(b, bn, RAD_BF16, {B * kSamTok / 4, 512}); + RAD_VN("v%s.n3u"); b_unf_3 = decl_b(b, bn, RAD_BF16, {B * kMap * kMap, 512 * 9}); + RAD_VN("v%s.map"); b_map = decl_b(b, bn, RAD_BF16, {B * kMap * kMap, DeepEncoder::kClipW}); + + RAD_VN("v%s.cx"); b_c = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.ch"); b_ch = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.cq"); b_cq = decl_b(b, bn, RAD_BF16, {B * kClipTok, 3 * DeepEncoder::kClipW}); + RAD_VN("v%s.ca"); b_ca = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.cf"); b_cf = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipFf}); + RAD_VN("v%s.cg2"); b_cg2 = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipFf}); + RAD_VN("v%s.ct"); b_ct = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.cp"); b_cp = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + RAD_VN("v%s.cids"); b_ids_clip = decl_b(b, bn, RAD_I32, {B * kClipTok}, RAD_BUF_PERSIST); + RAD_VN("v%s.cpos"); b_cpos = decl_b(b, bn, RAD_BF16, {B * kClipTok, DeepEncoder::kClipW}); + + RAD_VN("v%s.fuse"); b_fuse = decl_b(b, bn, RAD_BF16, {B * kMap * kMap, DeepEncoder::kFused}); + RAD_VN("v%s.proj"); b_projbuf = decl_b(b, bn, RAD_BF16, {B * kMap * kMap, DeepEncoder::kNEmbd}); + RAD_VN("v%s.nlrow"); b_nlrow = decl_b(b, bn, RAD_BF16, {1, DeepEncoder::kNEmbd}); + RAD_VN("v%s.pixstg"); b_pixstg = decl_b(b, bn, RAD_BF16, {B * kSamTok, DeepEncoder::kPatchDim}); + + /* One cu_seqlens table each, a bound a tile: the batched SAM/CLIP attention reads B segments + * and the three unfolds divide by kGrid (net_3 by 2*kGrid). */ + RAD_VN("v%s.cus"); + b_cu_sam = decl_b(b, bn, RAD_I32, {B + 1}); + op_cu_sam = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 2, B + 1), RAD_INT("start", 0), + RAD_INT("step", kSamTok)), + RAD_NOWEIGHTS), + {}, {b_cu_sam}); + RAD_VN("v%s.cuc"); + b_cu_clip = decl_b(b, bn, RAD_I32, {B + 1}); + op_cu_clip = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 2, B + 1), RAD_INT("start", 0), + RAD_INT("step", kClipTok)), + RAD_NOWEIGHTS), + {}, {b_cu_clip}); + RAD_VN("v%s.cup"); + b_cu_pad = decl_b(b, bn, RAD_I32, {B + 1}); + op_cu_pad = rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 2, B + 1), RAD_INT("start", 0), + RAD_INT("step", kSamTokP)), + RAD_NOWEIGHTS), + {}, {b_cu_pad}); + + /* The 40 tower stages its resampled absolute tables into PERSIST planes (never packed, + * never aliased); fill_tables() writes them once on the rank's first tile pass and the + * gathers below read them as plain operands. The 64 tower gathers straight from the + * checkpoint's weight planes. */ + if (is40) { + RAD_VN("v%s.pos40"); + b_pos_tab = decl_b(b, bn, RAD_BF16, {kSamTok, DeepEncoder::kSamW}, RAD_BUF_PERSIST); + RAD_VN("v%s.cpos40"); + b_cpos_tab = decl_b(b, bn, RAD_BF16, {kClipTok, DeepEncoder::kClipW}, RAD_BUF_PERSIST); + } + + /* ---- SAM stem. The patch embed is one GEMM over the whole staged tile (the processor + * stages kDown zero patch columns at the end of each row, skipped by the pitched pack into + * `pixstg`), then the position table added in: a row gather, from the 64x64 plane at the 64 + * grid (exact, unchanged) and the staged 40x40 resample at 40. */ + op_patch = rw(b, gemm_b(b, B * kSamTok, DeepEncoder::kSamW, DeepEncoder::kPatchDim, "none", + w.w_patch, w.b_patch), {b_pixstg}, {b_x}); + if (!is40) + op_sampos = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), + RAD_INT("n_embd", DeepEncoder::kSamW), + RAD_INT("n_vocab", kSamTok), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w.w_pos)), + {b_ids_sam}, {b_sampos}); + else + op_sampos = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), + RAD_INT("n", DeepEncoder::kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_pos_tab, b_ids_sam}, {b_sampos}); + op_sampadd = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), + RAD_INT("n", DeepEncoder::kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_x, b_sampos}, {b_x}); + + for (size_t i = 0; i < sam.size(); ++i) { + SamLayerT& l = sam[i]; + l.op_n1 = rw(b, lnorm(b, B * kSamTok, DeepEncoder::kSamW, 1e-6f, l.w_n1, l.b_n1), + {b_x}, {b_h}); + /* The windowed path: `h` into window_partition's padded order with zero pad rows + * (a negative gather index is a zero row), so the qkv linear gives the pad rows the + * reference's bias -- deepencoder pads AFTER norm1 and runs the whole attention on the + * padded window, so a pad key's k and v are the qkv bias, not zero. */ + l.op_gpad = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTokP), RAD_INT("n", DeepEncoder::kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_h, b_ids_pad}, {b_hw}); + l.op_qkv = rw(b, gemm_b(b, B * kSamTok, 3 * DeepEncoder::kSamW, DeepEncoder::kSamW, "none", + l.w_qkv, l.b_qkv), {b_h}, {b_qkv}); + l.op_qkvw = rw(b, gemm_b(b, B * kSamTokP, 3 * DeepEncoder::kSamW, DeepEncoder::kSamW, "none", + l.w_qkv, l.b_qkv), {b_hw}, {b_qkvw}); + l.op_attn = rw(b, RAD_OP(b, "sam_attn", + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), + RAD_INT("head_dim", DeepEncoder::kSamHd), + RAD_INT("n_head", DeepEncoder::kSamHeads), + RAD_INT("grid_h", kGrid), RAD_INT("grid_w", kGrid), + RAD_INT("window", l.window), + RAD_F64("scale", 1.0 / 8.0), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(l.w_rh, l.w_rw)), + {b_qkv, b_cu_sam}, {b_att}); + l.op_attnw = rw(b, RAD_OP(b, "sam_attn", + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTokP), + RAD_INT("head_dim", DeepEncoder::kSamHd), + RAD_INT("n_head", DeepEncoder::kSamHeads), + RAD_INT("grid_h", kGridP), RAD_INT("grid_w", kGridP), + RAD_INT("window", DeepEncoder::kWin), + RAD_F64("scale", 1.0 / 8.0), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(l.w_rh, l.w_rw)), + {b_qkvw, b_cu_pad}, {b_attw}); + l.op_greal = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), RAD_INT("n", DeepEncoder::kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_attw, b_ids_real}, {b_att}); + l.op_proj = rw(b, gemm_b(b, B * kSamTok, DeepEncoder::kSamW, DeepEncoder::kSamW, "none", + l.w_proj, l.b_proj), {b_att}, {b_h}); + /* deepencoder rounds the projection before adding the shortcut (`x + attn(norm(x))` + * is two bf16 operations), so the residual add is its own op: fusing it into the + * GEMM's f32 accumulator skips a rounding and drifts from the reference. */ + l.op_padd = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), RAD_INT("n", DeepEncoder::kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_h, b_x}, {b_x}); + l.op_n2 = rw(b, lnorm(b, B * kSamTok, DeepEncoder::kSamW, 1e-6f, l.w_n2, l.b_n2), + {b_x}, {b_h}); + l.op_l1 = rw(b, gemm_b(b, B * kSamTok, DeepEncoder::kSamFf, DeepEncoder::kSamW, "gelu", + l.w_l1, l.b_l1), {b_h}, {b_ff}); + l.op_l2 = rw(b, gemm_b(b, B * kSamTok, DeepEncoder::kSamW, DeepEncoder::kSamFf, "none", + l.w_l2, l.b_l2), {b_ff}, {b_h}); + l.op_ladd = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, B * kSamTok), RAD_INT("n", DeepEncoder::kSamW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_h, b_x}, {b_x}); + } + + /* ---- neck. The 1x1 is a GEMM; the 3x3s are unfold + gemm because they carry no bias and + * conv2d_nhwc's `b` is required. LayerNorm2d is a layernorm across a pixel's channels, + * which are innermost. */ + op_neck0 = rw(b, gemm_u(b, B * kSamTok, 256, DeepEncoder::kSamW, w.w_neck0), {b_x}, {b_n0}); + op_nk1 = rw(b, lnorm(b, B * kSamTok, 256, 1e-6f, w.w_nk1, w.b_nk1), {b_n0}, {b_n1}); + op_unf3 = rw(b, unfold(b, kGrid, kGrid, 256, 1, kGrid), {b_n1, b_cu_sam}, {b_unf3}); + op_nk2 = rw(b, gemm_u(b, B * kSamTok, 256, 256 * 9, w.w_nk2), {b_unf3}, {b_n2}); + op_nk3 = rw(b, lnorm(b, B * kSamTok, 256, 1e-6f, w.w_nk3, w.b_nk3), {b_n2}, {b_n3}); + op_unf_net2 = rw(b, unfold(b, kGrid, kGrid, 256, 2, kGrid), {b_n3, b_cu_sam}, {b_unf_2}); + op_net2 = rw(b, gemm_u(b, B * kSamTok / 4, 512, 256 * 9, w.w_net2), {b_unf_2}, {b_map2}); + op_unf_net3 = rw(b, unfold(b, kGrid / 2, kGrid / 2, 512, 2, kGrid * 2), + {b_map2, b_cu_sam}, {b_unf_3}); + op_net3 = rw(b, gemm_u(b, B * kMap * kMap, DeepEncoder::kClipW, 512 * 9, w.w_net3), + {b_unf_3}, {b_map}); + + /* ---- CLIP. The class row goes first and the map's rows below it: absolute position + * pairs row for row, and attention is permutation-equivariant, so the class row's place + * is free. (The reference cats class first too.) The 40 tower gathers its staged 101-row + * table; the 64 tower the checkpoint's 257 rows. */ + op_cls = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", DeepEncoder::kClipW), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w.w_cls)), + {p_one_c}, {b_c}); + op_cmap = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", kMap * kMap), RAD_INT("n", DeepEncoder::kClipW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_map}, {b_c}); + if (!is40) + op_cpos = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), + RAD_INT("n_embd", DeepEncoder::kClipW), + RAD_INT("n_vocab", kClipTok), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w.w_cpos)), + {b_ids_clip}, {b_cpos}); + else + op_cpos = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), + RAD_INT("n", DeepEncoder::kClipW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_cpos_tab, b_ids_clip}, {b_cpos}); + op_cadd = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), + RAD_INT("n", DeepEncoder::kClipW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_c, b_cpos}, {b_c}); + op_playr = rw(b, lnorm(b, B * kClipTok, DeepEncoder::kClipW, 1e-5f, w.w_playr, w.b_playr), + {b_c}, {b_cp}); + /* deepencoder normalises the embedding once (pre_layrnorm) and the transformer's residual + * stream starts there, not at the embedding: layer 0's norm1 and its residual add both + * read the pre_layrnorm output. */ + op_ccopy = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", kClipTok), RAD_INT("n", DeepEncoder::kClipW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_cp}, {b_c}); + + for (ClipLayerT& l : clip) { + l.op_n1 = rw(b, lnorm(b, B * kClipTok, DeepEncoder::kClipW, 1e-5f, l.w_n1, l.b_n1), + {b_c}, {b_ch}); + l.op_qkv = rw(b, gemm_b(b, B * kClipTok, 3 * DeepEncoder::kClipW, DeepEncoder::kClipW, + "none", l.w_qkv, l.b_qkv), {b_ch}, {b_cq}); + l.op_attn = rw(b, RAD_OP(b, "attn_dense", + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), + RAD_INT("head_dim", DeepEncoder::kClipHd), + RAD_INT("gqa", 1), RAD_INT("causal", 0), + RAD_F64("scale", 1.0 / 8.0), RAD_INT("cu_div", 1), + RAD_INT("max_seqlen", kClipTok), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_cq, b_cu_clip}, {b_ca}); + l.op_out = rw(b, gemm_b(b, B * kClipTok, DeepEncoder::kClipW, DeepEncoder::kClipW, "none", + l.w_out, l.b_out), {b_ca}, {b_ct}); + l.op_cadd = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), + RAD_INT("n", DeepEncoder::kClipW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_ct, b_c}, {b_c}); + l.op_n2 = rw(b, lnorm(b, B * kClipTok, DeepEncoder::kClipW, 1e-5f, l.w_n2, l.b_n2), + {b_c}, {b_ch}); + l.op_fc1 = rw(b, gemm_b(b, B * kClipTok, DeepEncoder::kClipFf, DeepEncoder::kClipW, "none", + l.w_fc1, l.b_fc1), {b_ch}, {b_cf}); + /* quick_gelu: fc1's output times sigmoid(1.702 * itself), fused into one act. The + * kernel rounds the scaled value to bf16 before the sigmoid, which is exactly the + * store the unfused mul did, so the fusion is bit-identical to the pair it replaces + * (and saves a 257x4096 bf16 round-trip per layer x 24 layers x tile). */ + l.op_qg = rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), + RAD_INT("n", DeepEncoder::kClipFf), + RAD_STR("act", "quick_gelu"), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_cf, b_cf}, {b_cg2}); + l.op_fc2 = rw(b, gemm_b(b, B * kClipTok, DeepEncoder::kClipW, DeepEncoder::kClipFf, + "none", l.w_fc2, l.b_fc2), {b_cg2}, {b_ct}); + l.op_madd = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, B * kClipTok), + RAD_INT("n", DeepEncoder::kClipW), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {b_ct, b_c}, {b_c}); + } + + /* ---- fuse, project. */ + op_fuse_clip = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", kMap * kMap), + RAD_INT("n", DeepEncoder::kClipW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_c}, {b_fuse}); + op_fuse_sam = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", kMap * kMap), + RAD_INT("n", DeepEncoder::kClipW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_map}, {b_fuse}); + op_proj = rw(b, gemm_b(b, B * kMap * kMap, DeepEncoder::kNEmbd, DeepEncoder::kFused, "none", + w.w_proj, w.b_proj), {b_fuse}, {b_projbuf}); + /* Declared and never issued: they name the stage buffers as read and the out plane as + * written, and removing them changes the buffer plan, while the layout below fills the out + * plane with copies outside the op stream. */ + op_dbg1024 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", 256), RAD_INT("n", DeepEncoder::kClipW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_map, b_c, b_unf_2}, {p_out}); + op_dbg768 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", 256), RAD_INT("n", DeepEncoder::kSamW), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_x, b_att}, {p_out}); + op_dbg256 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", 256), RAD_INT("n", 256), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_n0, b_n1, b_n2, b_n3, b_map2, b_unf_2}, {p_out}); + op_dbg1280 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_INT("M", 256), RAD_INT("n", DeepEncoder::kNEmbd), + RAD_STR("from", "bf16"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {b_projbuf}, {p_out}); + + /* ---- the two layout rows. A projected map line reaches its layout rows as a pitched + * copy in view(); the newline row is computed once here and pitched out by segment(). */ + op_newline = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", DeepEncoder::kNEmbd), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w.w_newline)), + {p_one}, {b_nlrow}); + op_sep = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_INT("M", 1), RAD_INT("n", DeepEncoder::kNEmbd), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w.w_sep)), + {p_one}, {p_out}); +#undef RAD_VN + return RAD_OK; +} + +/* ------------------------------------------------------------------ tile position tables + * The 40 tower's absolute position planes, computed once a rank on its first tile pass: the + * checkpoint's bf16 tables read back, resampled fp32 bicubic+antialias exactly as the + * reference's get_abs_pos_sam / get_abs_pos do (torch interpolates in fp32 and casts back), + * staged into the PERSIST planes the gathers read. The CLIP table's class row passes through + * (the reference cats it first). */ +template +void DeepEncoder::Tower::fill_tables(RadCtx* c, const DeepEncoder& w) const { + const int rk = rad_rank(c); + if (rk < 0 || rk >= 32) return; + if (tabs_done & (1u << rk)) return; + void* pw = rad_weight_ptr(c, w.w_pos); + void* cw = rad_weight_ptr(c, w.w_cpos); + void* pt = rad_buf_ptr(c, b_pos_tab); + void* ct = rad_buf_ptr(c, b_cpos_tab); + if (!pw || !cw || !pt || !ct) { + rad_step_fail(c, "unlimitedocr: a position table of the DeepEncoder did not bind"); + return; + } + const int64_t src_grid = DeepEncoder::Geom64::kGrid; /* SAM's 64x64 table */ + const int64_t csrc = DeepEncoder::kClipSrcMap; /* CLIP's 16x16 grid */ + std::vector hpos((size_t)(src_grid * src_grid * DeepEncoder::kSamW)); + std::vector hclip((size_t)(csrc * csrc + 1) * DeepEncoder::kClipW); + if (rad_memcpy_async(hpos.data(), pw, hpos.size() * sizeof(uint16_t), rad_stream(c)) < 0 || + rad_memcpy_async(hclip.data(), cw, hclip.size() * sizeof(uint16_t), rad_stream(c)) < 0 || + rad_stream_sync(rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the DeepEncoder's position tables could not be read back"); + return; + } + /* SAM: [64,64,768] -> [40,40,768], fp32, cast back to bf16. */ + std::vector f((size_t)(src_grid * src_grid * DeepEncoder::kSamW)), + g((size_t)(kGrid * kGrid * DeepEncoder::kSamW)); + for (size_t i = 0; i < f.size(); ++i) f[i] = rad_bf16_to_f32(hpos[i]); + resample_bicubic_aa(f.data(), (int)src_grid, (int)src_grid, (int)kGrid, (int)kGrid, + (int)DeepEncoder::kSamW, g.data()); + std::vector out(g.size()); + for (size_t i = 0; i < g.size(); ++i) out[i] = rad_f32_to_bf16(g[i]); + + if (rad_memcpy_async(pt, out.data(), out.size() * sizeof(uint16_t), rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the SAM tile position table could not be staged"); + return; + } + + /* CLIP: row 0 is the class row, rows 1: are the 16x16 grid -> cls + a 10x10 resample. + * f/g are the SAM resample's buffers, reused here as the CLIP resample's scratch; that is + * safe only while SAM's f covers CLIP's source grid and SAM's g covers CLIP's map. Pinned + * so retuning a geometry fails at compile time, not as a heap overrun. */ + static_assert((size_t)DeepEncoder::Geom64::kGrid * DeepEncoder::Geom64::kGrid * + DeepEncoder::kSamW >= + (size_t)DeepEncoder::kClipSrcMap * DeepEncoder::kClipSrcMap * + DeepEncoder::kClipW, + "fill_tables reuses SAM's f scratch for the CLIP source grid"); + static_assert((size_t)kGrid * kGrid * DeepEncoder::kSamW >= + (size_t)kMap * kMap * DeepEncoder::kClipW, + "fill_tables reuses SAM's g scratch for the CLIP map grid"); + std::vector cout((size_t)kClipTok * DeepEncoder::kClipW); + std::memcpy(cout.data(), hclip.data(), (size_t)DeepEncoder::kClipW * sizeof(uint16_t)); + const size_t ngrid = (size_t)(csrc * csrc * DeepEncoder::kClipW); + for (size_t i = 0; i < ngrid; ++i) f[i] = rad_bf16_to_f32(hclip[DeepEncoder::kClipW + i]); + resample_bicubic_aa(f.data(), (int)csrc, (int)csrc, (int)kMap, (int)kMap, + (int)DeepEncoder::kClipW, g.data()); + for (size_t i = 0; i < (size_t)kMap * kMap * DeepEncoder::kClipW; ++i) + cout[(size_t)DeepEncoder::kClipW + i] = rad_f32_to_bf16(g[i]); + if (rad_memcpy_async(ct, cout.data(), cout.size() * sizeof(uint16_t), rad_stream(c)) < 0 || + rad_stream_sync(rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the CLIP tile position table could not be staged"); + return; + } + tabs_done |= (1u << rk); +} + +/* ------------------------------------------------------------------ tower batch step */ +/* The position and window tables do not depend on the pass: tile t reads its own copy of the + * same kSamTok (kClipTok) rows, so Bmax copies are staged once a rank and every batch run + * gathers the first B copies. The window tables carry the tile's own row offset. */ +template +void DeepEncoder::Tower::stage_ids(RadCtx* c) const { + const int rk = rad_rank(c); + if (rk < 0 || rk >= 32 || (ids_done & (1u << rk))) return; + std::vector ids_s((size_t)(Bmax * kSamTok)); + std::vector ids_c((size_t)(Bmax * kClipTok)); + std::vector pad((size_t)(Bmax * kSamTokP), -1); + std::vector real((size_t)(Bmax * kSamTok)); + for (int64_t t = 0; t < Bmax; ++t) { + for (int64_t r = 0; r < kSamTok; ++r) + ids_s[(size_t)(t * kSamTok + r)] = (int32_t)r; + for (int64_t r = 0; r < kClipTok; ++r) + ids_c[(size_t)(t * kClipTok + r)] = (int32_t)r; + for (int64_t r = 0; r < kGrid; ++r) + for (int64_t cc = 0; cc < kGrid; ++cc) { + pad[(size_t)(t * kSamTokP + r * kGridP + cc)] = + (int32_t)(t * kSamTok + r * kGrid + cc); + real[(size_t)(t * kSamTok + r * kGrid + cc)] = + (int32_t)(t * kSamTokP + r * kGridP + cc); + } + } + void* p_ids_s = rad_buf_ptr(c, b_ids_sam); + void* p_ids_c = rad_buf_ptr(c, b_ids_clip); + void* p_pad = rad_buf_ptr(c, b_ids_pad); + void* p_real = rad_buf_ptr(c, b_ids_real); + if (!p_ids_s || !p_ids_c || !p_pad || !p_real) { + rad_step_fail(c, "unlimitedocr: a staged index table of the DeepEncoder did not bind"); + return; + } + if (rad_memcpy_async(p_ids_s, ids_s.data(), (int64_t)(ids_s.size() * sizeof(int32_t)), + rad_stream(c)) < 0 || + rad_memcpy_async(p_ids_c, ids_c.data(), (int64_t)(ids_c.size() * sizeof(int32_t)), + rad_stream(c)) < 0 || + rad_memcpy_async(p_pad, pad.data(), (int64_t)(pad.size() * sizeof(int32_t)), + rad_stream(c)) < 0 || + rad_memcpy_async(p_real, real.data(), (int64_t)(real.size() * sizeof(int32_t)), + rad_stream(c)) < 0 || + rad_stream_sync(rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the staged index tables of the DeepEncoder could not be " + "filled"); + return; + } + ids_done |= (1u << rk); +} + +/* One batched tower run over `nt` staged tiles. Tile t's rows are [t*kSamTok, (t+1)*kSamTok) of + * every SAM plane (and its CLIP block at [t*kClipTok, (t+1)*kClipTok)); the segment-bounded ops + * read a B+1-entry cu table, so attention and the unfolds never see across a tile. */ +template +void DeepEncoder::Tower::batch(RadCtx* c, const RadBatch* batch, const Tile* tiles, + int64_t nt, bool tap, const DeepEncoder& w) { + if (nt < 1 || nt > Bmax) { + rad_step_fail(c, "unlimitedocr: a DeepEncoder batch exceeded the declared tile bound"); + return; + } + /* The 40 tower stages its resampled position tables once on the rank's first tile pass. */ + if (b_pos_tab) fill_tables(c, w); + stage_ids(c); + + const int64_t BT = nt * kSamTok; + const int64_t BTP = nt * kSamTokP; + const int64_t BCT = nt * kClipTok; + const int64_t BM = nt * kMap * kMap; + + /* The patch embed: one pitched copy a tile packs its grid rows out of the line's rows (the + * kDown zero patch columns at each row's end are the copy's dead space), then ONE GEMM over + * all B tiles. The copies ride the pass's stream, ordered with the ops. */ + char* stg = (char*)rad_buf_ptr(c, b_pixstg); + const int64_t rowb = kGrid * DeepEncoder::kPatchDim * 2; + if (!stg) { + rad_step_fail(c, "unlimitedocr: the patch rows of the DeepEncoder could not be packed"); + return; + } + for (int64_t t = 0; t < nt; ++t) { + const char* pix = (const char*)batch->enc_pixels + + (tiles[t].patch0 + tiles[t].t * kGrid) * DeepEncoder::kPatchDim * 2; + char* dst = stg + t * kSamTok * DeepEncoder::kPatchDim * 2; + if (rad_memcpy_2d_async(dst, rowb, pix, tiles[t].gw * DeepEncoder::kPatchDim * 2, + rowb, kGrid, rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the patch rows of the DeepEncoder could not be packed"); + return; + } + } + RAD_ISSUE_N(c, op_patch, BT, + RAD_P_T2(stg, RAD_BF16, BT, DeepEncoder::kPatchDim), + RAD_W(w.w_patch), RAD_W(w.b_patch), RAD_NONE, + brow_slice(b_x, 0, BT, DeepEncoder::kSamW)); + + /* The pass's segment tables: B tiles, a bound each. */ + RAD_ISSUE_N(c, op_cu_sam, nt + 1, brows(b_cu_sam, nt + 1)); + RAD_ISSUE_N(c, op_cu_clip, nt + 1, brows(b_cu_clip, nt + 1)); + RAD_ISSUE_N(c, op_cu_pad, nt + 1, brows(b_cu_pad, nt + 1)); + + /* The position table, a row for a token (a gather, exact at 64 and from the staged + * resample at 40), added in. The ids repeat per tile, so every tile sees the same table. */ + if (tap) w.tap(c, "st_emb", b_x, 256, DeepEncoder::kSamW); + if (b_pos_tab) + RAD_ISSUE_N(c, op_sampos, BT, RAD_B(b_pos_tab), brows(b_ids_sam, BT), + brows(b_sampos, BT)); + else + RAD_ISSUE_N(c, op_sampos, BT, brows(b_ids_sam, BT), RAD_W(w.w_pos), + brows(b_sampos, BT)); + if (tap) w.tap(c, "st_sampos", b_sampos, 256, DeepEncoder::kSamW); + RAD_ISSUE_N(c, op_sampadd, BT, brows(b_x, BT), brows(b_sampos, BT), brows(b_x, BT)); + if (tap) w.tap(c, "st_x0", b_x, 256, DeepEncoder::kSamW); + + + for (size_t li = 0; li < sam.size(); ++li) { + const SamLayerT& l = sam[li]; + RAD_ISSUE_N(c, l.op_n1, BT, brows(b_x, BT), RAD_W(l.w_n1), RAD_W(l.b_n1), + brows(b_h, BT)); + if (l.window > 0) { + /* The reference's window path: pad the normed grid to a multiple of 14, run qkv + * over the pad rows too (they carry the qkv bias), attend inside each 14x14 window, + * and take the real rows back out. The pad rows take softmax mass with the bias as v. */ + RAD_ISSUE_N(c, l.op_gpad, BTP, brows(b_h, BT), brows(b_ids_pad, BTP), + brows(b_hw, BTP)); + RAD_ISSUE_N(c, l.op_qkvw, BTP, brows(b_hw, BTP), RAD_W(l.w_qkv), + RAD_W(l.b_qkv), RAD_NONE, brows(b_qkvw, BTP)); + RAD_ISSUE_N(c, l.op_attnw, BTP, + bcol(b_qkvw, 0, DeepEncoder::kSamW, BTP), + bcol(b_qkvw, DeepEncoder::kSamW, DeepEncoder::kSamW, BTP), + bcol(b_qkvw, 2 * DeepEncoder::kSamW, DeepEncoder::kSamW, BTP), + brows(b_cu_pad, nt + 1), brows(b_attw, BTP), + RAD_W(l.w_rh), RAD_W(l.w_rw)); + RAD_ISSUE_N(c, l.op_greal, BT, brows(b_attw, BTP), brows(b_ids_real, BT), + brows(b_att, BT)); + } else { + RAD_ISSUE_N(c, l.op_qkv, BT, brows(b_h, BT), RAD_W(l.w_qkv), + RAD_W(l.b_qkv), RAD_NONE, brows(b_qkv, BT)); + RAD_ISSUE_N(c, l.op_attn, BT, + bcol(b_qkv, 0, DeepEncoder::kSamW, BT), + bcol(b_qkv, DeepEncoder::kSamW, DeepEncoder::kSamW, BT), + bcol(b_qkv, 2 * DeepEncoder::kSamW, DeepEncoder::kSamW, BT), + brows(b_cu_sam, nt + 1), brows(b_att, BT), + RAD_W(l.w_rh), RAD_W(l.w_rw)); + } + char tag[40]; + std::snprintf(tag, sizeof tag, "sam_att%lld_raw", (long long)li); + if (tap) w.tap(c, tag, b_att, 256, DeepEncoder::kSamW); + RAD_ISSUE_N(c, l.op_proj, BT, brows(b_att, BT), RAD_W(l.w_proj), + RAD_W(l.b_proj), RAD_NONE, brows(b_h, BT)); + RAD_ISSUE_N(c, l.op_padd, BT, brows(b_h, BT), brows(b_x, BT), brows(b_x, BT)); + std::snprintf(tag, sizeof tag, "st_pre%lld", (long long)li); + if (tap) w.tap(c, tag, b_x, 256, DeepEncoder::kSamW); + RAD_ISSUE_N(c, l.op_n2, BT, brows(b_x, BT), RAD_W(l.w_n2), RAD_W(l.b_n2), + brows(b_h, BT)); + RAD_ISSUE_N(c, l.op_l1, BT, brows(b_h, BT), RAD_W(l.w_l1), RAD_W(l.b_l1), + RAD_NONE, brows(b_ff, BT)); + RAD_ISSUE_N(c, l.op_l2, BT, brows(b_ff, BT), RAD_W(l.w_l2), RAD_W(l.b_l2), + RAD_NONE, brows(b_h, BT)); + RAD_ISSUE_N(c, l.op_ladd, BT, brows(b_h, BT), brows(b_x, BT), brows(b_x, BT)); + std::snprintf(tag, sizeof tag, "st_b%lld", (long long)li); + if (tap) w.tap(c, tag, b_x, 256, DeepEncoder::kSamW); + if (li < 3) { + std::snprintf(tag, sizeof tag, "st_full%lld", (long long)li); + if (tap) w.tap(c, tag, b_x, kSamTok, DeepEncoder::kSamW); + } + } + + /* neck + net_2 + net_3. The 3x3s are a dense view of the map rows, unfolded; the cu table + * gives each tile its own grid. */ + RAD_ISSUE_N(c, op_neck0, BT, brows(b_x, BT), RAD_W(w.w_neck0), brows(b_n0, BT)); + if (tap) w.tap(c, "st_n0", b_n0, 256, 256); + RAD_ISSUE_N(c, op_nk1, BT, brows(b_n0, BT), RAD_W(w.w_nk1), RAD_W(w.b_nk1), + brows(b_n1, BT)); + if (tap) w.tap(c, "st_n1", b_n1, 256, 256); + RAD_ISSUE(c, op_unf3, + RAD_P_T2(rad_buf_ptr(c, b_n1), RAD_BF16, nt * kGrid, kGrid * 256), + brows(b_cu_sam, nt + 1), RAD_NONE, brows(b_unf3, BT)); + RAD_ISSUE_N(c, op_nk2, BT, brows(b_unf3, BT), RAD_W(w.w_nk2), brows(b_n2, BT)); + if (tap) w.tap(c, "st_n2", b_n2, 256, 256); + RAD_ISSUE_N(c, op_nk3, BT, brows(b_n2, BT), RAD_W(w.w_nk3), RAD_W(w.b_nk3), + brows(b_n3, BT)); + if (tap) w.tap(c, "st_n3", b_n3, 256, 256); + RAD_ISSUE(c, op_unf_net2, + RAD_P_T2(rad_buf_ptr(c, b_n3), RAD_BF16, nt * kGrid, kGrid * 256), + brows(b_cu_sam, nt + 1), RAD_NONE, brows(b_unf_2, nt * kSamTok / 4)); + RAD_ISSUE_N(c, op_net2, nt * kSamTok / 4, brows(b_unf_2, nt * kSamTok / 4), + RAD_W(w.w_net2), brows(b_map2, nt * kSamTok / 4)); + if (tap) w.tap(c, "st_map2", b_map2, 256, 512); + RAD_ISSUE(c, op_unf_net3, + RAD_P_T2(rad_buf_ptr(c, b_map2), RAD_BF16, nt * kGrid / 2, (kGrid / 2) * 512), + brows(b_cu_sam, nt + 1), RAD_NONE, brows(b_unf_3, BM)); + RAD_ISSUE_N(c, op_net3, BM, brows(b_unf_3, BM), RAD_W(w.w_net3), brows(b_map, BM)); + if (tap) w.tap(c, "st_map", b_map, kMap * kMap, DeepEncoder::kClipW); + + /* CLIP: the class row and the map, tile by tile (each block's rows are strided in the + * tile-major plane), then the batched transformer and absolute table. */ + for (int64_t t = 0; t < nt; ++t) { + RAD_ISSUE(c, op_cls, RAD_B(p_one_c), RAD_W(w.w_cls), + brow_slice(b_c, t * kClipTok, 1, DeepEncoder::kClipW)); + RAD_ISSUE(c, op_cmap, + brow_slice(b_map, t * kMap * kMap, kMap * kMap, DeepEncoder::kClipW), + brow_slice(b_c, t * kClipTok + 1, kMap * kMap, DeepEncoder::kClipW)); + } + if (b_cpos_tab) + RAD_ISSUE_N(c, op_cpos, BCT, RAD_B(b_cpos_tab), brows(b_ids_clip, BCT), + brows(b_cpos, BCT)); + else + RAD_ISSUE_N(c, op_cpos, BCT, brows(b_ids_clip, BCT), RAD_W(w.w_cpos), + brows(b_cpos, BCT)); + RAD_ISSUE_N(c, op_cadd, BCT, brows(b_c, BCT), brows(b_cpos, BCT), brows(b_c, BCT)); + if (tap) w.tap(c, "clip_x", b_c, kClipTok, DeepEncoder::kClipW); + RAD_ISSUE_N(c, op_playr, BCT, brows(b_c, BCT), RAD_W(w.w_playr), + RAD_W(w.b_playr), brows(b_cp, BCT)); + RAD_ISSUE_N(c, op_ccopy, BCT, brows(b_cp, BCT), brows(b_c, BCT)); + + for (size_t ci = 0; ci < clip.size(); ++ci) { + const ClipLayerT& l = clip[ci]; + char ctag[40]; + RAD_ISSUE_N(c, l.op_n1, BCT, brows(b_c, BCT), RAD_W(l.w_n1), + RAD_W(l.b_n1), brows(b_ch, BCT)); + std::snprintf(ctag, sizeof ctag, "clip_pre%lld", (long long)ci); + if (tap) w.tap(c, ctag, b_ch, kClipTok, DeepEncoder::kClipW); + RAD_ISSUE_N(c, l.op_qkv, BCT, brows(b_ch, BCT), RAD_W(l.w_qkv), + RAD_W(l.b_qkv), RAD_NONE, brows(b_cq, BCT)); + RAD_ISSUE_N(c, l.op_attn, BCT, + bcol(b_cq, 0, DeepEncoder::kClipW, BCT), + bcol(b_cq, DeepEncoder::kClipW, DeepEncoder::kClipW, BCT), + bcol(b_cq, 2 * DeepEncoder::kClipW, DeepEncoder::kClipW, BCT), + brows(b_cu_clip, nt + 1), brows(b_ca, BCT)); + std::snprintf(ctag, sizeof ctag, "clip_att%lld", (long long)ci); + if (tap) w.tap(c, ctag, b_ca, kClipTok, DeepEncoder::kClipW); + RAD_ISSUE_N(c, l.op_out, BCT, brows(b_ca, BCT), RAD_W(l.w_out), + RAD_W(l.b_out), RAD_NONE, brows(b_ct, BCT)); + RAD_ISSUE_N(c, l.op_cadd, BCT, brows(b_ct, BCT), brows(b_c, BCT), brows(b_c, BCT)); + std::snprintf(ctag, sizeof ctag, "clip_h%lld", (long long)ci); + if (tap) w.tap(c, ctag, b_c, kClipTok, DeepEncoder::kClipW); + RAD_ISSUE_N(c, l.op_n2, BCT, brows(b_c, BCT), RAD_W(l.w_n2), + RAD_W(l.b_n2), brows(b_ch, BCT)); + RAD_ISSUE_N(c, l.op_fc1, BCT, brows(b_ch, BCT), RAD_W(l.w_fc1), + RAD_W(l.b_fc1), RAD_NONE, brows(b_cf, BCT)); + RAD_ISSUE_N(c, l.op_qg, BCT, brows(b_cf, BCT), brows(b_cf, BCT), + brows(b_cg2, BCT)); + RAD_ISSUE_N(c, l.op_fc2, BCT, brows(b_cg2, BCT), RAD_W(l.w_fc2), + RAD_W(l.b_fc2), RAD_NONE, brows(b_ct, BCT)); + RAD_ISSUE_N(c, l.op_madd, BCT, brows(b_ct, BCT), brows(b_c, BCT), brows(b_c, BCT)); + std::snprintf(ctag, sizeof ctag, "clip_b%lld", (long long)ci); + if (tap) w.tap(c, ctag, b_c, kClipTok, DeepEncoder::kClipW); + } + + if (tap) w.tap(c, "clip_out", b_c, kMap * kMap, DeepEncoder::kClipW, 1); + + /* Fuse (CLIP's patch rows | the map) and project, tile by tile into the tile-major fuse. */ + for (int64_t t = 0; t < nt; ++t) { + RAD_ISSUE(c, op_fuse_clip, + brow_slice(b_c, t * kClipTok + 1, kMap * kMap, DeepEncoder::kClipW), + bcol_at(b_fuse, t * kMap * kMap, DeepEncoder::kFused, 0, + DeepEncoder::kClipW, kMap * kMap)); + RAD_ISSUE(c, op_fuse_sam, + brow_slice(b_map, t * kMap * kMap, kMap * kMap, DeepEncoder::kClipW), + bcol_at(b_fuse, t * kMap * kMap, DeepEncoder::kFused, DeepEncoder::kClipW, + DeepEncoder::kClipW, kMap * kMap)); + } + if (tap) w.tap(c, "fuse", b_fuse, kMap * kMap, DeepEncoder::kFused); + RAD_ISSUE_N(c, op_proj, BM, brows(b_fuse, BM), RAD_W(w.w_proj), + RAD_W(w.b_proj), RAD_NONE, brows(b_projbuf, BM)); + if (tap) w.tap(c, "proj", b_projbuf, kMap * kMap, DeepEncoder::kNEmbd); + + + /* The layout: each tile's map goes to columns [t*kMap, (t+1)*kMap) of every map row -- a + * pitched copy of the projected tile into the plane (the layout pitch is the line's row + * count plus the newline column), one copy replacing kMap cast-launches. The newline cell + * after a line's last tile belongs to the line and follows that tile's copy. */ + char* po = (char*)rad_buf_ptr(c, p_out); + const char* proj = (const char*)rad_buf_ptr(c, b_projbuf); + const int64_t wbytes = kMap * DeepEncoder::kNEmbd * 2; + if (!po || !proj) { + rad_step_fail(c, "unlimitedocr: a layout plane of the DeepEncoder did not bind"); + return; + } + for (int64_t t = 0; t < nt; ++t) { + const int64_t rowbase = tiles[t].rowbase; + const int64_t tt = tiles[t].t, n = tiles[t].n; + if (rad_memcpy_2d_async(po + (rowbase + tt * kMap) * DeepEncoder::kNEmbd * 2, + (n * kMap + 1) * DeepEncoder::kNEmbd * 2, + proj + t * kMap * kMap * DeepEncoder::kNEmbd * 2, + wbytes, wbytes, kMap, rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the projected map of the DeepEncoder could not be " + "laid out"); + return; + } + if (tiles[t].nl) { + /* The reference expands image_newline over every map row of the line + * (modeling_unlimitedocr.py: `image_newline.expand(h, 1, n_dim)`), so the one + * learned row is replicated into each newline cell. Copy one cell at a time: + * b_nlrow is a single row, and a 2D copy with a zero source pitch is not a + * portable device operation. */ + RAD_ISSUE(c, op_newline, RAD_B(p_one), RAD_W(w.w_newline), RAD_B(b_nlrow)); + const char* nl = (const char*)rad_buf_ptr(c, b_nlrow); + if (!nl) { + rad_step_fail(c, "unlimitedocr: the newline row of the DeepEncoder did not bind"); + return; + } + for (int64_t r = 0; r < kMap; ++r) { + char* dst = po + ((rowbase + n * kMap) + r * (n * kMap + 1)) * + DeepEncoder::kNEmbd * 2; + if (rad_memcpy_async(dst, nl, DeepEncoder::kNEmbd * 2, rad_stream(c)) < 0) { + rad_step_fail(c, "unlimitedocr: the newline row of the DeepEncoder could " + "not be laid out"); + return; + } + } + } + } +} + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* RAD_BLOCK_SAM_H */ diff --git a/arch/common/rad_fp8.h b/arch/common/rad_fp8.h index 53eaea2a..793bf104 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -296,6 +296,10 @@ struct ArPieces { * chunk a span of 1 makes, the state carried through the cache) and hand off the first * piece's reduction before the second piece's projection. Null for any other step. */ const int32_t* cu = nullptr; + /* The caller normed each piece's input itself (qwen35_fp8's pipelined prefill, on the second + * lane behind the previous block's piece), so a block with its own norm takes the piece path + * as one with an external input does and skips that norm. */ + bool in_ready = false; bool cuts(int64_t T) const { return done && rows > 0 && T > rows; } void hand(int64_t r0, int64_t n) { done(u, r0, n); ++handed; } }; @@ -395,6 +399,9 @@ struct NormQuantFP8 { } /* Asked by the preceding block before issuing its own collective. */ bool takes_ar(int64_t T) const { return pick(T) != op; } + /* The plain op whatever the wire, for a caller that issued the preceding all-reduce itself + * (qwen35_fp8's pipelined prefill, which runs it narrow beside compute). */ + void step_plain(RadCtx* c, int64_t T, int64_t r0 = 0, int64_t rows = 0) const; }; inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, rad_buf x, @@ -472,6 +479,16 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, return RAD_OK; } +/* step() below with the plain op, whatever the wire. */ +inline void NormQuantFP8::step_plain(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const { + if (rows <= 0) rows = T - r0; + RAD_ISSUE_N(c, op, rows, brow_slice(src, r0, rows, n), + res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w), + brow_slice(a.q, r0, rows, n), + brow_slice(a.s, r0, rows, n / RAD_FP8_BLOCK), + brow_slice(a.x, r0, rows, n)); +} + /* `r0`/`rows` select a row slice, defaulting to the whole step (`brow_slice` at offset 0 equals * `brows`). Slicing lets a block run in passes (the routed feed-forward). Each slice must land in * the same bucket-table band as the whole (core/runtime/ctx.h), or a different kernel with a @@ -755,6 +772,10 @@ struct LinearFP8 { * this is set; otherwise the linear reads unwritten arena bytes. */ bool reads_x = false; bool mapped = false; /* probe() made the name map; declare() does not make it again */ + /* The stored weight this linear's views take when it is not `.weight`: a second linear + * over one container entry, e.g. a whole projection beside its tensor-parallel slice. Set + * before declare(); no name map is made, and only block fp8 is served this way. */ + const char* stored = nullptr; /* The weight's access class (rad_builder.h): read every pass by default; a linear run once a * request (an encoder's) says so, which lets placement keep it off the card. Set before * declare(). */ @@ -808,8 +829,10 @@ struct LinearFP8 { rad_weight decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc, int64_t K, RadWeightGroup grp); + /* Rows [r0, r0 + rows) of the input into the same rows of `y`, or from row `y0` of `y` when + * that is set: a rank's run of a step's rows written to a buffer sized for the run. */ void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0, - int64_t rows = 0) const; + int64_t rows = 0, int64_t y0 = -1) const; /* A span per stacked row part (rad_weight_shard_span_parts), in weight rows; the scale plane * gets the same spans in its rows. Call after declare(). With a 1/128 plane every span and * total must be whole scale blocks. */ @@ -1047,9 +1070,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha /* Name map first: the weight's encoding, looked up through it, picks the branch below. */ const char* wn = nm.f("%s.weight", base); - if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src)); + if (!mapped && !stored) RAD_ARCH_TRY(map_linear(b, wn, src)); + const char* sw = stored ? stored : wn; RadEncoding enc{}; - const bool known = weight_enc(b, wn, &enc); + const bool known = weight_enc(b, sw, &enc); const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 && enc.plane[0].dtype == RAD_BF16; @@ -1059,11 +1083,17 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * constraints. */ bf16 = g.w_bf16 || plain; if (bf16) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (known && !plain) { char en[256]; rad_enc_format(&enc, en, sizeof en); - fprintf(stderr, "radiance: '%s' is %s and this model's linears are plain bf16; a " - "bf16 container is served bf16 throughout\n", wn, en); + fprintf(stderr, "radiance: '%s' is %s, but this linear runs as a plain bf16 GEMM " + "(a bf16 model, or a block that keeps its linears bf16); the " + "container must store it bf16\n", wn, en); return RAD_E_DTYPE; } /* A bf16 weight needs the input's bf16 plane, which a quantised model's producer may not @@ -1097,6 +1127,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha const bool rot8 = known && linear_is_w8h(enc); i8 = known && (linear_is_w8(enc) || rot8); if (i8) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } /* Upstream's rot guard: fed codes must match the weight's rotation form. */ if (a.q8_fed && rot8 != a.q8_rot) { fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its " @@ -1161,6 +1196,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * codes, and (scale, zero) as `b_scale`. */ paro5 = known && linear_is_paro_w5(enc); if (paro5) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } const int bits = enc.plane[0].dtype == RAD_U4 ? 4 : 5; if (!a.x) { fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight, rotated from its input's " @@ -1227,6 +1267,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * whole 128s, the scale group. */ w4 = known && linear_is_w4(enc); if (w4) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (!a.x) { fprintf(stderr, "radiance: '%s' is a 4-bit weight, read from its input's bf16 plane, " "and its input has none\n", wn); @@ -1297,6 +1342,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha paro = known && linear_is_paro_mxfp4(enc); mx = known && (linear_is_mxfp4(enc) || paro); if (mx) { + if (stored) { + fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear " + "may\n", wn, stored); + return RAD_E_INVAL; + } if (paro) { /* The rotation is applied to the activation, so this linear needs the input's bf16 * plane (probe() set reads_x) and quantises it itself. */ @@ -1408,10 +1458,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32; /* One stored weight, two operands: the codes and scale plane of `.weight`, block fp8 in * the checkpoint or made so by rad-convert's recipe. */ - w = decl_view(b, wn, nullptr, "codes", RAD_F8E4M3, { N, K }, + w = decl_view(b, wn, stored, "codes", RAD_F8E4M3, { N, K }, access, shard, grp, rp.w, rp.n); ws_row_div = RAD_FP8_BLOCK; - ws = decl_view(b, sn, wn, "scale", f32_scale ? RAD_F32 : RAD_BF16, + ws = decl_view(b, sn, sw, "scale", f32_scale ? RAD_F32 : RAD_BF16, { fp8_blocks(N), fp8_blocks(K) }, access, shard, grp, rp.s, rp.n); if (!w || !ws) return RAD_E_INVAL; /* An uneven slice; the scale plane takes the same slice in blocks. */ @@ -1443,10 +1493,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha * asymmetric integer and mxfp4 grids) are passed as RAD_NONE when unused, since the runtime checks * the operand count against the schema (core/runtime/issue.cpp). */ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0, - int64_t rows) const { + int64_t rows, int64_t y0) const { if (rows <= 0) rows = T - r0; + const int64_t yr = y0 < 0 ? r0 : y0; if (bf16) { - RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, r0, rows, N)); + RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, yr, rows, N)); return; } if (i8) { @@ -1455,7 +1506,7 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK)); RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K), brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK), - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } /* The 4-bit weight's copies of the input start at their buffers' first row: they live only @@ -1465,13 +1516,13 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK)); RAD_ISSUE_N(c, op2, rows, brow_slice(a8q, 0, rows, K), brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK), RAD_W(w), RAD_W(ws), - brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } if (w4) { RAD_ISSUE_N(c, op_a16, rows, brow_slice(a.x, r0, rows, K), brow_slice(a16, 0, rows, K)); RAD_ISSUE_N(c, op, rows, brow_slice(a16, 0, rows, K), RAD_NONE, RAD_W(w), RAD_W(ws), - brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } if (paro5 && rot_split && rows > rot_split) { @@ -1480,14 +1531,14 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK))); RAD_ISSUE_N(c, op2, rows, brow_slice(rot_q2, r0, rows, rot_parts * K), brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)), - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } if (paro5) { RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs), RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q, r0, rows, rot_parts * K)); RAD_ISSUE_N(c, op, rows, brow_slice(rot_q, r0, rows, rot_parts * K), RAD_NONE, - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); return; } if (mx) { @@ -1501,12 +1552,12 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK)); RAD_ISSUE_N(c, op, rows, brow_slice(aq, r0, rows, ak), brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK), - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref)); + RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_W(wref)); return; } RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K), brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK), - RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE); + RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE); } /* ================================================== an fp8 weight with no op of its own diff --git a/arch/common/rad_gemma4_dflash.h b/arch/common/rad_gemma4_dflash.h index b6660921..3a1fee71 100644 --- a/arch/common/rad_gemma4_dflash.h +++ b/arch/common/rad_gemma4_dflash.h @@ -40,7 +40,8 @@ * The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names * four sliding layers and one full one, and the PR's test pins `causal True` on the sliding * layers and `False` on the full one, so this block declares two attention ops and issues the one - * each layer's type names. + * each layer's type names. A config that states `dflash_config.causal` (NVIDIA's E4B drafter: + * false, all five layers sliding) sets the sliding layers' causality. * * The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and * cap * tanh(x / cap) is strictly increasing. @@ -115,18 +116,15 @@ inline double embed_scale(int64_t hidden) { /* prefetch where a library serves it: the 31B trunk reading the next GEMM's leading weight bytes * into the on-die cache beside the all-reduce in front of that GEMM, at decode heights (on lane 0 * as a chained read, or on the second lane: rad_arch.h prefetch_lane0), and the DFlash2 drafter's - * reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB. With - * the reads on lane 0 (two rounds on 4x R9700): 20 MB 391 / 391 code tok/s, 289 / 288 prose; - * 16 MB 386 / 384, 285 / 283; 24 MB 388 / 387; 12 MB 368 / 369. */ + * reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB: on 4x + * R9700 with the reads on lane 0, 16 and 24 MB decoded 1-2% slower and 12 MB about 6%. */ constexpr int64_t kPrefetchBytes = (int64_t)20 << 20; -/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention. It - * took the place of o_proj's read there: the 31B at tp 4 on 4x R9700, two rounds, every reply - * identical, 380 / 281 / 203 tok/s against 367 / 271 / 196 with o_proj's 16 MB; 10, 11, 12, 14 - * and 20 MB of down_proj 379, 377, 373, 373 and 362; down_proj beside o_proj's read, or beside the - * feed-forward reduction, slower than either alone. The reads beside a reduction are one queue, - * and a longer one beside the attention pushes gate_up's read past the reduction it should hide - * in. */ +/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention, in + * place of a read of o_proj there (about 3.5% faster on the 31B at tp 4 on 4x R9700; 10-20 MB of + * down_proj were slower, as were two reads beside one reduction). The reads beside a reduction + * are one queue, and a longer one beside the attention pushes gate_up's read past the reduction + * it should hide in. */ constexpr int64_t kPrefetchDownBytes = (int64_t)9 << 20; /* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no @@ -166,8 +164,8 @@ inline long long dflash_block(const RadModelMeta* meta) { /* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less * the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). True when the - * container carries one and `out` now names its depth. Chained launches measured a gain with it - * (the 26B-A4B's speculative step, +1% on 4x R9700), so the probe asks for them + * container carries one and `out` names its depth. Chained launches pay with it (the 26B-A4B's + * speculative step is 1% faster on 4x R9700), so the probe asks for them * (RadArchProbe::chain_pays). */ inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) { if (dflash_kind(meta) != 1) return false; @@ -181,8 +179,8 @@ inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) { /* The same for a DFlash2 drafter, for a plugin that serves rad_block_dflash2.h (the 31B's): its * anchor predicts nothing either, so the depth is the trained block less one, 7 for RedHatAI's - * gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches measured a gain with it (the - * 31B's speculative step, +13% on 4x R9700), so the probe asks for them. */ + * gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches pay with it (the 31B's + * speculative step is 13% faster on 4x R9700), so the probe asks for them. */ inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) { if (dflash_kind(meta) != 2) return false; const long long bs = dflash_block(meta); @@ -238,6 +236,7 @@ struct Dflash1 { int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */ int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */ int64_t window = 0; /* the sliding layers' window; 0 for none */ + int causal = 1; /* the sliding layers: causal (z-lab) or not (dflash_config.causal) */ int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */ double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */ int64_t kv_rep = 1; /* how many times the cache holds each kv head (kv_rep_for) */ @@ -519,7 +518,12 @@ inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int int64_t p[RAD_MAX_ROW_PARTS] = {0}; int np = 0; for (int64_t q : row_parts) { - if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL; + if (np >= RAD_MAX_ROW_PARTS || q % 16) { + fprintf(stderr, "radiance: '%s' has a %lld-row part per rank; an int8 weight takes at " + "most %d parts, each a multiple of 16 rows.\n", base, (long long)q, + (int)RAD_MAX_ROW_PARTS); + return RAD_E_INVAL; + } p[np++] = q; } w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp, p, np); @@ -582,7 +586,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta, return RAD_E_UNSUPPORTED; } dc.block = trained; - if (dg.n_layer > MAX_LAYERS) return RAD_E_UNSUPPORTED; + if (dg.n_layer > MAX_LAYERS) { + fprintf(stderr, "radiance: gemma4: the DFlash drafter has %lld layers; this block carries " + "at most %d\n", (long long)dg.n_layer, MAX_LAYERS); + return RAD_E_UNSUPPORTED; + } { std::vector full; const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr); @@ -610,6 +618,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta, "window\n"); return RAD_E_INVAL; } + /* z-lab's configs state no causality and train the sliding layers causal; NVIDIA's + * (Nemotron-3.5-Bolt-E4B's DFlash) states `dflash_config.causal: false`, every layer + * sliding and non-causal over its window. */ + dc.causal = rad_meta_geti(meta, "draft.dflash_config.causal", + rad_meta_geti(meta, "draft.is_causal", 1)) != 0 ? 1 : 0; } } if (!head_sharded(dg) && dg.world > 1) { @@ -664,11 +677,12 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta, int nfull = 0; for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l]; rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld " - "sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the " + "sliding over %lld, %s), %lld heads / %lld kv x %lld, ffn %lld, reading the " "trunk at %lld tap(s); linears %s. One forward over %lld rows proposes %lld " "tokens; the head is %s, argmax %s", (long long)dg.n_layer, t.base_layer, t.base_layer + (int)dg.n_layer - 1, nfull, - (long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head, + (long long)(dg.n_layer - nfull), (long long)dc.window, + dc.causal ? "causal" : "non-causal", (long long)dg.n_head, (long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff, (long long)t.n_taps, df->i8 ? "int8 (w8a8, an int8 activation per row)" : "on the E4M3 grid (fp8a8 / mxfp4a8)", @@ -849,7 +863,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co }; bool any_full = false, any_swa = false; for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true; - if (any_swa) op_attn_swa = attn(1, cfg.window); + if (any_swa) op_attn_swa = attn(cfg.causal, cfg.window); if (any_full) op_attn_full = attn(0, 0); /* The copies into the cache's layout (rep_kv), a head-wide strided row copy each. Each pass's diff --git a/arch/common/rad_glm_tp.h b/arch/common/rad_glm_tp.h index 39a3d589..64d93c16 100644 --- a/arch/common/rad_glm_tp.h +++ b/arch/common/rad_glm_tp.h @@ -13,9 +13,10 @@ * row-interleaved all_gather, bit for bit the replicated projection * * The one rule for a run: ceil(T / world) rows, rounded up to whole 16-byte words of the gathered - * row, because an all_gather moves whole words. The indexer gathers one i32 length a row beside - * its page tables, so its runs are multiples of four rows. The last rank's run may be short, or - * lie wholly past a small step (`run_of`). */ + * row, because an all_gather moves whole words. The MLA gathers 4096-wide bf16 rows, so its runs + * are ceil(T / world); the indexer gathers one i32 length a row beside its page tables, so its + * runs are multiples of four rows. The last rank's run may be short, or lie wholly past a small + * step (`run_of`). */ #ifndef RAD_GLM_TP_H #define RAD_GLM_TP_H #include "rad_arch.h" diff --git a/arch/common/rad_resample.h b/arch/common/rad_resample.h new file mode 100644 index 00000000..68e9a7d5 --- /dev/null +++ b/arch/common/rad_resample.h @@ -0,0 +1,167 @@ +/* rad_resample.h -- fp32 bicubic resampling reproducing torch's + * F.interpolate(x, size=(n, m), mode="bicubic", antialias=True) on the CPU float32 kernel, + * operation for operation, for the Unlimited-OCR DeepEncoder's position tables. + * + * The reference resamples two fixed tables (deepencoder.py): + * get_abs_pos_sam() permutes SAM's pos_embed [1,64,64,768] to (0,3,1,2), casts fp32 and + * interpolates to 40x40; get_abs_pos() takes CLIP position_embedding rows 1: as a 16x16 grid, + * interpolates to 10x10, and cats row 0 (cls) in front. Here the table is row-major [h, w, C] + * with C innermost and each of the C channels is interpolated over the (h, w) grid + * independently; the cls split/catenation is the caller's job. + * + * The float32 antialias path (upsample_bicubic2d_aa_kernel_impl -> + * upsample_separable_Nd_kernel_impl -> _compute_index_ranges_weights with antialias=true, + * aten/src/ATen/native/cpu/UpSampleKernel.cpp, torch v2.14.0) is mirrored operation for + * operation, scalar_t = float: + * per axis scale = (float)(in / out); support = scale >= 1 ? (interp_size/2) * scale = + * 2 * scale : 2; invscale = scale >= 1 ? 1 / scale : 1; + * the output-pixel centre center = scale * (i + 0.5f); + * the taps run over xmin = max((int64)(center - support + 0.5), 0) .. + * min((int64)(center + support + 0.5), in) - 1 -- truncating casts, so a negative + * start truncates toward zero before the clamp to 0; border taps are simply absent, + * the row normalization below absorbs the lost mass; + * each tap weight is aa_filter((j + xmin - center + 0.5) * invscale), the Keys cubic + * with a = -0.5 (torch's antialias filter is the Pillow-compatible -0.5 kernel; the + * -0.75 OpenCV-compatible one belongs to the non-antialias path); + * the axis weights are normalized by their float running sum total_w, exactly as + * _compute_indices_min_size_weights_aa divides wt_ptr[j] /= total_w; + * the resize is separable: the width pass over every input row first, then the height + * pass (the order upsample_separable_Nd_kernel_impl walks the dims), each tap + * accumulating acc = (float)(acc + w * v) in float. + * Golden-checked by tests/resample_golden.py (geometries 64->40, 24->20, 8->5, 16->10, + * 16x20->10x13, and both checkpoint tables). + */ +#pragma once +#ifndef RAD_RESAMPLE_H +#define RAD_RESAMPLE_H + +#include +#include +#include +#include + +namespace rad { +namespace arch { + +namespace resample_detail { + +/* aa_filter, the Keys cubic with a = -0.5 that torch's antialias path uses (the -0.75 + * OpenCV-compatible kernel belongs to the non-antialias path), in float. */ +inline float cubic_aa(float x) { + const float ax = std::fabs(x); + if (ax < 1.0f) return ((1.5f * ax - 2.5f) * ax) * ax + 1.0f; + if (ax < 2.0f) return (((-0.5f * ax + 2.5f) * ax - 4.0f) * ax) + 2.0f; + return 0.0f; +} + +struct Axis { + int n = 0; /* tap slots per output pixel (max_interp_size) */ + std::vector size; /* [out] taps this output pixel reads */ + std::vector idx; /* [out*n] input index per tap (xmin + j) */ + std::vector w; /* [out*n] weights, normalized by the tap sum */ +}; + +/* One axis of _compute_indices_min_size_weights_aa, float32 expression for expression. */ +inline Axis make_axis(int in, int out) { + Axis a; + const float scale = (float)((double)in / (double)out); + const float support = scale >= 1.0f ? (float)(2.0 * (double)scale) : 2.0f; + const float invscale = scale >= 1.0f ? (float)(1.0 / (double)scale) : 1.0f; + a.n = (int)std::ceil((double)support) * 2 + 1; /* max_interp_size */ + a.size.resize((size_t)out, 0); + a.idx.assign((size_t)out * (size_t)a.n, 0); + a.w.assign((size_t)out * (size_t)a.n, 0.0f); + for (int i = 0; i < out; ++i) { + const float c = ((float)i + 0.5f) * scale; + int xmin = (int)(c - support + 0.5f); + if (xmin < 0) xmin = 0; + int xsize = (int)(c + support + 0.5f); + if (xsize > in) xsize = in; + xsize -= xmin; + if (xsize < 0) xsize = 0; + /* ATen's own `xsize = min(xsize, n)`, kept for parity. It cannot bind here: with + * xmin > 0 the window spans 2*support + 1 taps, at most a.n = 2*ceil(support) + 1 + * (the bound ATen sized the slots from), and with xmin == 0 it spans fewer. So the + * clamp is a no-op safety net, never a silent tap truncation. */ + if (xsize > a.n) xsize = a.n; + int* idx = &a.idx[(size_t)i * (size_t)a.n]; + float* w = &a.w[(size_t)i * (size_t)a.n]; + float total = 0.0f; + for (int j = 0; j < xsize; ++j) { + w[j] = cubic_aa(((float)(xmin + j) - c + 0.5f) * invscale); + idx[j] = xmin + j; + total = (float)(total + w[j]); + } + a.size[i] = xsize; + if (total != 0.0f) + for (int j = 0; j < xsize; ++j) w[j] = (float)(w[j] / total); + } + return a; +} + +/* One 1D resize pass. `rows` scans travel `src_row_stride` floats apart, taps step + * `tap_stride` floats along the resized axis, and outputs land at + * dst + r * dst_row_stride + i * out_stride + channel; tap order and float accumulation + * follow ATen's separable 1D resize. */ +inline void resize_axis(const float* src, int64_t src_row_stride, int64_t tap_stride, + float* dst, int64_t dst_row_stride, int64_t out_stride, int rows, + const Axis& ax, int out_n, int channels) { + for (int r = 0; r < rows; ++r) { + const float* srow = src + (size_t)r * (size_t)src_row_stride; + float* drow = dst + (size_t)r * (size_t)dst_row_stride; + for (int i = 0; i < out_n; ++i) { + const int n = ax.size[i]; + const int32_t* idx = &ax.idx[(size_t)i * (size_t)ax.n]; + const float* w = &ax.w[(size_t)i * (size_t)ax.n]; + for (int c = 0; c < channels; ++c) { + if (n == 0) { drow[(size_t)i * (size_t)out_stride + (size_t)c] = 0.0f; continue; } + float acc = (float)(srow[(size_t)idx[0] * (size_t)tap_stride + (size_t)c] * w[0]); + for (int j = 1; j < n; ++j) + acc = (float)(acc + + srow[(size_t)idx[j] * (size_t)tap_stride + (size_t)c] * w[j]); + drow[(size_t)i * (size_t)out_stride + (size_t)c] = acc; + } + } + } +} + +} // namespace resample_detail + +/* Resample an [in_h, in_w, channels] fp32 table (channels innermost) to + * [out_h, out_w, channels] with torch's bicubic + antialias interpolation: the width pass + * over every input row, then the height pass. Runs once at load. */ +inline void resample_bicubic_aa(const float* src, int in_h, int in_w, int out_h, int out_w, + int channels, float* dst) { + if (!src || !dst || in_h <= 0 || in_w <= 0 || out_h <= 0 || out_w <= 0 || channels <= 0) + return; + if (in_h == out_h && in_w == out_w) { + std::memcpy(dst, src, (size_t)in_h * (size_t)in_w * (size_t)channels * sizeof(float)); + return; + } + const resample_detail::Axis ay = resample_detail::make_axis(in_h, out_h); + const resample_detail::Axis ax = resample_detail::make_axis(in_w, out_w); + const float* work = src; + int work_w = in_w; + std::vector wide; + if (in_w != out_w) { /* width pass first, the order upsample_separable_Nd walks the dims */ + wide.assign((size_t)in_h * (size_t)out_w * (size_t)channels, 0.0f); + resample_detail::resize_axis(src, (int64_t)in_w * channels, channels, wide.data(), + (int64_t)out_w * channels, channels, in_h, ax, out_w, + channels); + work = wide.data(); + work_w = out_w; + } + if (in_h == out_h) { + if (work != dst) + std::memcpy(dst, work, (size_t)out_h * (size_t)out_w * (size_t)channels * sizeof(float)); + return; + } + /* height pass over the widened rows: one scan per output-width column */ + resample_detail::resize_axis(work, channels, (int64_t)work_w * channels, dst, channels, + (int64_t)out_w * channels, work_w, ay, out_h, channels); +} + +} // namespace arch +} // namespace rad + +#endif // RAD_RESAMPLE_H diff --git a/arch/fishomni/CMakeLists.txt b/arch/fishomni/CMakeLists.txt new file mode 100644 index 00000000..1894797a --- /dev/null +++ b/arch/fishomni/CMakeLists.txt @@ -0,0 +1,10 @@ +# Built in radiance's tree, or standalone against an installed radiance +# (`cmake -S arch/fishomni -B build -DCMAKE_PREFIX_PATH=`); see cmake/RadAddPlugin.cmake. +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(fishomni LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(fishomni architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/fishomni.cpp) diff --git a/arch/fishomni/fishomni.cpp b/arch/fishomni/fishomni.cpp new file mode 100644 index 00000000..9d424cd4 --- /dev/null +++ b/arch/fishomni/fishomni.cpp @@ -0,0 +1,2359 @@ +/* fishomni -- Fish Audio drama-3 (FishOmniModel): speech from text, 44.1 kHz mono. + * + * ============================== THE MODEL ============================== + * + * Three networks (fish-speech's fish_speech/models/text2semantic/fish_omni/, Fish Audio's own + * reference, and its S2 codec): + * + * Backbone: the language model of Qwen3.5-35B-A3B, unchanged -- 40 layers of 2048, three gated + * delta-net layers to one gated attention layer (16 query heads over 2 KV heads of 256, NeoX + * rotary on 64 dims at theta 1e7), a routed feed-forward in every layer (256 experts of 512, 8 a + * token, and a gated shared expert of 512), (1 + w) norms. Only the routed experts are fp8 + * (`quant_method: bsgemm-moe`, E4M3 with an f32 scale a 128 x 128 block); everything else is + * bf16. A prompt row is a token; an audio row is one frame of the codec's ten codes, embedded as + * (E_lm[248099 + c0] + E_cb[4096 + c1]) / sqrt 2: the first code through its semantic token, + * the second through section 1 of the codebook table. + * + * Tower: 13 MTP-style layers that write a frame's codes 1..9 from the backbone's hidden state: + * four "shared" layers that inject code 0, then nine "per-codebook" layers, layer k injecting + * code k - 1 and its head drawing code k. Each layer is m = eh_proj([enorm(e); hnorm(h)]), one + * pre-norm block (gated attention with (1 + w) q/k norms and GPT-J rotary on 64 dims at 1e7, a + * SwiGLU of 6144), and a final norm. The attention is causal across time, over a cache of its + * own at the backbone's positions: the layers are bound as layers 40..52 of the backbone's + * full-attention KV group. The first shared layer also adds the summed embeddings of the input + * frame's codes 2..9, the ones the backbone never saw. + * + * Codec: Fish S2's modified DAC decoder: ten codebooks of dimension 8 (one of 4096, nine of + * 1024), each projected to 1024 and summed; an 8-layer transformer (16 heads of 64, a causal + * window of 128 frames); two 2x upsamplings with ConvNeXt blocks; four transposed convolutions + * (8, 8, 4, 2) with snake residual units; 2048 samples a frame. Its encoder, for a reference + * clip, mirrors it: four blocks of snake residual units and strided causal convolutions (2, 4, + * 8, 8) with a 4-layer transformer (window 512 rows) after the last, two 2x downsamplings with + * ConvNeXt blocks, an 8-layer transformer (window 128 frames), and a residual quantiser, + * nearest code by cosine, the semantic codebook first. + * + * ============================== THE PASSES ============================== + * + * The core's audio generator in its chunked form, one branch a request (no guidance): + * + * PROMPT the backbone over the whole prompt; the last row's hidden state into the lane; the + * tower teacher-forced over every row. A text prompt's labels are all text, so every + * layer's code embedding is zero; the tower still runs, because its attention reads + * those rows' keys and values from every later frame. With references the codec's + * encoder first turns their clips into frames, each a prompt row embedded as a made + * frame is; a row before a frame is labelled with it, a frame's row carries its unseen + * codes, and the window of main picks starts with the prompt's last frames. The last + * row's tower pass is the first frame's, and FRAME 0 overwrites it. + * FRAME frame j of every lane in flight. The main token is drawn from the hidden state of the + * row before the frame's (the prompt's last row for frame 0) over 4097 candidates (the + * end of speech and the 4096 semantic tokens), with Fish's repetition-aware choice + * between two draws; then the tower at that row's position draws codes 1..9; then the + * frame goes into the lane's history and the backbone runs over its embedding at the + * frame's own row. + * VOCODE a few kept frames of one lane through the codec, re-decoding the frames its outputs + * reach back to (every layer is causal), so no state is carried between chunks. + * + * ============================== TENSOR PARALLEL ============================== + * + * Two ranks. The backbone splits as Qwen3.6-35B-A3B does (heads, delta-net heads, expert width). + * The tower splits by heads and feed-forward width, an all-reduce after each output projection. + * The candidate head, the code tables, the nine heads, the samplers and the codec are + * replicated: every rank draws the same codes from the same logits and seeds, and plays the same + * samples. + */ +#include +#include +#include +#include + +#include +#include +#include +#include +#include +#include + +namespace fishomni { + +using namespace rad::arch; + +/* ================================================================== the model's constants */ +constexpr int64_t kMaxLanes = 4; +/* References (voice cloning): at most 8 clips of 30 s together. fish-speech's server takes each + * up to 60 s; here the encoder's first stages, 64 and 128 channels at the samples' rate, hold + * about 170 MB a buffer at 30 s. A clip's frames are prompt rows. */ +constexpr int64_t kMaxRefFrames = 646; +constexpr int32_t kMaxRefs = 8; +/* The longest prompt and speech. fish-speech's default request is 2048 frames (95 s); a plain + * prompt is a few dozen rows a sentence, and the references add a row a frame. */ +constexpr int64_t kMaxPrompt = 3072, kMaxFrames = 2048; +/* A frame: ten codes, code 0 of 4096 (the semantic band), codes 1..9 drawn from heads of 4096 and + * read by the codec through 1024-entry codebooks. */ +constexpr int64_t kCodes = 10, kVocab = 4096, kResVocab = 1024; +/* Token ids: the end of speech (<|im_end|>) and the semantic band <|semantic:0..4095|>. The main + * token is drawn over those 4097, in id order, so candidate 0 is the end and candidate c + 1 is + * semantic code c. */ +constexpr int64_t kEos = 248046, kSemBegin = 248099, kSemEnd = 252194, kCand = kVocab + 1; +/* The tower: four shared layers, then one a codebook after the first. */ +constexpr int kShared = 4, kTower = kShared + (int)kCodes - 1; +/* The draws: temperature 1.0 and top-p 0.9, the settings of Fish Audio's model card, for the main + * token and every head; the main token uncapped (256, cfg_topk_sample's widest) and each head at + * top-k 30, as SGLang-Omni draws them. fish-speech's server defaults (0.7, 0.7, 30 for both) make + * the model fall silent after a tag or a speaker's line and never come back: over 40 takes of + * four short scripts, 8 ran to their length in silence against none here (docs/ARCHITECTURES.md). */ +constexpr int64_t kMainTopK = 256, kHeadTopK = 30; +static const double kTemp = 1.0, kTopP = 0.9; +/* The repetition-aware redraw, fixed by the training recipe (tower.py): when the first draw is + * semantic and among the last 16 main tokens, a second draw at temperature 1, top-p 0.95, + * top-k 30 is taken instead. */ +constexpr int64_t kRasWin = 16, kRasTopK = 30; +static const double kRasTemp = 1.0, kRasTopP = 0.95; + +/* The codec: 2048 samples a frame at 44.1 kHz. A chunk is at most kVocChunk frames; its outputs + * reach back about nine frames through the convolutions after the transformer (kConvCtx, rounded + * up), whose rows reach back kAttnWin - 1 frames. The dequantiser is per frame. */ +constexpr int64_t kSamplesPerFrame = 2048, kSampleRate = 44100; +constexpr int64_t kMaxRefSamples = kMaxRefFrames * kSamplesPerFrame; /* 30.0 s */ +constexpr int64_t kVocChunk = 16, kConvCtx = 12, kAttnWin = 128; +constexpr int64_t kVocContext = (kAttnWin - 1) + kConvCtx; +constexpr int64_t kConvFrames = kConvCtx + kVocChunk; +constexpr int64_t kCbDim = 8, kLat = 1024, kDec = 1536; +/* The codec transformer: 8 layers of 1024, 16 heads of 64, a SwiGLU of 3072. */ +constexpr int64_t kCtLayers = 8, kCtHeads = 16, kCtHeadDim = 64, kCtFf = 3072; +static const double kCtTheta = 10000.0, kCtEps = 1e-5; +/* The encoder (modded_dac.py's Encoder): four blocks, each three residual units and a strided + * causal conv (kernel two strides), a 4-layer transformer over a window of 512 rows after the + * last; the quantiser then halves the rate twice to the frames (rvq.py). Its rows are 1, 2, 8, 64 + * and 512 samples, then 1024 and 2048. */ +static const int64_t kEncStride[4] = { 2, 4, 8, 8 }; +constexpr int64_t kEncWin = 512, kEncLayers = 4; +/* 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, 8, 4, 2 times). */ +constexpr int kRates = 8; +static const int64_t kRate[kRates] = { 1, 1, 2, 4, 32, 256, 1024, 2048 }; + +/* The prompt (reference-bracket-v1, the plain form: generate.py's build_drama3_prompt with no + * references). Every literal there is tokenised on its own; at these seams the joined text + * tokenises the same, since each one falls at a special token or a newline. The input gets its + * speaker tag in text_prepare. */ +static const char* kPlain = + "<|im_start|>system\nconvert the provided text to speech<|im_end|>\n" + "<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n<|voice|>"; +/* With references: the system turn's instruction for them, then each one's numbered header, its + * transcript and its frames (the core tokenises the instruction apart from the first header, as + * fish-speech does: joined, ":\n\n" is one token), then the user turn as kPlain's. The + * transcript's speaker tag comes first in it, from text_prepare. */ +static const char* kRefPlain = + "<|im_start|>system\nconvert the provided text to speech reference to the following:" + "{references}<|im_end|>\n<|im_start|>user\n{input}<|im_end|>\n<|im_start|>assistant\n" + "<|voice|>"; +static const char* kRefItem = "\n\n[Reference {index}]\nText: {text}\nSpeech: {audio}"; + +/* Weight groups (movement units): the backbone's layers are 0..39 (the blocks' own), the tower's + * 40..52 like their KV layers, then the frame's tables and the codec. */ +enum : int { kGrpTower = 40, kGrpFrame = 53, kGrpCodec = 100 }; + +/* ================================================================== the networks */ +struct Layer { + int full = 0; + AttnGatedFP8 attn; + GdnFP8 gdn; + MoeFP8 mlp; +}; + +/* A tower layer (tower.py's TowerLayer): the code embedding and the two norms into eh_proj, the + * gated attention block over the paged cache, the SwiGLU, the final norm; a per-codebook layer's + * head and its draw. q, gate, k and v are four projections of the checkpoint's [Q | G | K | V] + * rows (paged attention reads a contiguous query, and the gate is not interleaved per head as the + * backbone's is). */ +struct TowerLayer { + rad_weight w_emb = 0, w_en = 0, w_hn = 0, w_eh = 0, w_an = 0; + rad_weight w_q = 0, w_g = 0, w_k = 0, w_v = 0, w_qn = 0, w_kn = 0, w_o = 0; + rad_weight w_fn = 0, w_gu = 0, w_down = 0, w_fin = 0, w_head = 0; + rad_op op_emb = 0, op_eadd = 0, op_en = 0, op_hn = 0, op_eh = 0, op_an = 0; + rad_op op_q = 0, op_g = 0, op_k = 0, op_v = 0, op_qn = 0, op_kn = 0, op_rq = 0, op_rk = 0; + rad_op op_attn = 0, op_kv = 0, op_sig = 0, op_mul = 0, op_o = 0, op_ar1 = 0, op_add1 = 0; + rad_op op_fn = 0, op_gu = 0, op_act = 0, op_down = 0, op_ar2 = 0, op_add2 = 0, op_fin = 0; + rad_op op_head = 0, op_samp = 0; + /* PROMPT with references: the label embedding over the prompt's rows (and layer 0's unseen + * codes), and its norm. */ + rad_op op_pemb = 0, op_peadd = 0, op_pen = 0; +}; + +/* The codec transformer's layer: fused q|k|v with rotary at the frames' positions, causal + * attention over a 128-frame window, layer scales on both residual branches. */ +struct CodecLayer { + rad_weight w_n1 = 0, w_n2 = 0, w_qkv = 0, w_o = 0, w_gu = 0, w_down = 0, w_ls1 = 0, w_ls2 = 0; + rad_op op_n1 = 0, op_qkv = 0, op_rope = 0, op_attn = 0, op_o = 0, op_ls1 = 0, op_add1 = 0; + rad_op op_n2 = 0, op_gu = 0, op_act = 0, op_down = 0, op_ls2 = 0, op_add2 = 0; +}; + +/* A 2x upsampling and its ConvNeXt block. */ +struct Upsample { + rad_weight w_t = 0, b_t = 0, w_dw = 0, b_dw = 0, w_ln = 0, b_ln = 0, w_p1 = 0, b_p1 = 0; + rad_weight w_p2 = 0, b_p2 = 0, w_g = 0; + rad_op op_t = 0, op_dw = 0, op_ln = 0, op_p1 = 0, op_gelu = 0, op_p2 = 0, op_g = 0; + rad_op op_add = 0; +}; + +/* A causal weight-normalised conv with its bias. */ +struct VConv { + rad_weight w = 0, b = 0; + rad_op op = 0; +}; +struct VRes { + rad_weight a1 = 0, a2 = 0; + rad_op op_s1 = 0, op_s2 = 0; + VConv c1{}, c2{}; +}; +struct VBlock { + rad_weight a = 0, wt = 0, bt = 0; + rad_op op_s = 0, op_t = 0; + VRes res[3]; +}; +/* An encoder block: three residual units, a snake, the strided conv. */ +struct EBlock { + VRes res[3]; + rad_weight a = 0; + rad_op op_s = 0; + VConv down{}; +}; +/* The quantiser's 2x downsampling: a strided causal conv (plain weights) and a ConvNeXt block. */ +struct EDown { + VConv c{}; + rad_weight w_dw = 0, b_dw = 0, w_ln = 0, b_ln = 0, w_p1 = 0, b_p1 = 0, w_p2 = 0, b_p2 = 0; + rad_weight w_g = 0; + rad_op op_dw = 0, op_ln = 0, op_p1 = 0, op_gelu = 0, op_p2 = 0, op_g = 0, op_add = 0; +}; +/* A residual quantiser step's weights, f32: the in-projection, the codebook, the out-projection. */ +struct EQuant { + rad_weight in_w = 0, in_b = 0, cb = 0, out_w = 0, out_b = 0; + rad_op op = 0; +}; +/* A codec transformer's working set: its residual stream and scratch. */ +struct CtSet { rad_buf x = 0, h = 0, qkv = 0, attn = 0, o = 0, gu = 0, ff = 0; }; + +struct Model { + Names nm{""}; + Geom g{}; /* the backbone's */ + Geom gt{}; /* the tower's */ + GdnFP8::Config gcfg{}; + MoeFP8::Config moecfg{}; + int64_t n_rot = 0, n_rot_t = 0, n_main = 0, lanes = 0; + rad_kvgroup kv_full = 0, kv_state = 0, kv_conv = 0; + + /* ---- the backbone: the residual stream, its normed copy, and the blocks' working set */ + rad_buf b_x = 0; + ActFP8 a_h{}; + rad_buf b_qg = 0, b_k = 0, b_v = 0, b_q = 0, b_rope_cs = 0; + ActFP8 a_attn{}; + ActFP8 a_in{}, a_go{}; + rad_buf b_ab = 0, b_gq = 0, b_gk = 0, b_gv = 0, b_gdec = 0, b_beta = 0, b_kkt = 0; + rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_sorted = 0, b_eoff = 0, b_ecnt = 0; + rad_buf b_egu = 0, b_edn = 0, b_emoe = 0; + ActFP8 a_eff{}; + rad_buf b_sgu = 0, b_sout = 0, b_sgate = 0; + ActFP8 a_sff{}; + rad_weight w_tok = 0, w_out_norm = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_final_norm = 0, op_rope_cs = 0; + std::vector layers; + + /* ---- a lane's state (PERSIST) */ + rad_buf b_hid = 0; /* [lanes, 2048] the last row's final-norm hidden state */ + rad_buf b_status = 0; /* [lanes] i32 */ + rad_buf b_hist = 0; /* [lanes * 10, kMaxFrames] i32: each lane's codes, codebook rows */ + rad_buf b_ras = 0; /* [lanes, 16] i32: the last 16 main picks (candidate indices) */ + rad_buf b_u = 0; /* [lanes, 2048] the last frame's codes 2..9, embedded and summed */ + + /* ---- the frame */ + rad_weight w_cand = 0; /* [4097, 2048] the lm_head's candidate rows */ + rad_weight w_cemb = 0; /* [4097, 2048] the embedding's candidate rows */ + rad_weight w_cb = 0; /* [9 * 4096, 2048] codebook table sections 1..9 */ + rad_buf b_plane = 0, b_slog = 0, b_first = 0, b_alt = 0, b_codes = 0, b_ug = 0, b_unew = 0; + rad_buf b_last = 0, b_hlog = 0; + rad_op op_hsel = 0, op_head = 0, op_samp = 0, op_samp_ras = 0, op_ras = 0, op_status = 0; + rad_op op_ugather = 0, op_plast = 0, op_pstore = 0, op_uzero = 0, op_rasinit = 0; + rad_op op_efill = 0, op_store = 0, op_u = 0, op_uscat = 0, op_fb = 0, op_fstore = 0; + + /* ---- the tower */ + TowerLayer tw[kTower]; + rad_buf b_te = 0, b_tcat = 0, b_tm = 0, b_th = 0, b_tq = 0, b_tg = 0, b_tk = 0, b_tv = 0; + rad_buf b_tattn = 0, b_to = 0, b_tgu = 0, b_tff = 0, b_tho = 0; + + /* ---- the codec (VOCODE) */ + rad_weight w_cbk[kCodes] = {}; + rad_op op_rq[kCodes] = {}; + VConv qo[kCodes]; + std::vector ct; + rad_weight w_cn = 0; + rad_op op_cn = 0, op_cnst = 0, op_ccu[kRates] = {}, op_fcast = 0; + Upsample up[2]; + VConv dec0{}; + VBlock vb[4]; + int64_t v_ups[4] = { 8, 8, 4, 2 }; + rad_weight w_fa = 0; + rad_op op_fs = 0; + VConv fin{}; + rad_buf b_rq = 0, b_cx = 0, b_ch = 0, b_cqkv = 0, b_cattn = 0, b_co = 0, b_cgu = 0, b_cff = 0; + rad_buf b_cconst = 0, b_ccu[kRates] = {}; + rad_buf b_ux[3] = {}, b_ua = 0, b_ub = 0, b_uh = 0, b_ug2 = 0; + rad_buf b_vs[5] = {}, b_vt[5] = {}, b_va[5] = {}, b_vb[5] = {}; + rad_buf b_vout = 0, b_audio = 0; + + /* ---- the codec's encoder (PROMPT with references): the clips in, their frames' codes out + * into b_pc, the prompt rows' codes ([10, kMaxPrompt + 1] code-major, -2 and -1 at a token's + * row), from which the rows' embeddings and the tower's labels are read */ + rad_op op_ecast = 0, op_epos = 0, op_e5 = 0, op_etn = 0, op_pqn = 0; + VConv e0{}, e6{}; + EBlock eb[4]; + std::vector et, pq; + rad_weight w_etn = 0, w_e5 = 0, w_pqn = 0; + EDown ed[2]; + EQuant eq[kCodes]; + rad_op op_pc0 = 0, op_pc1 = 0, op_pfb = 0, op_pufill = 0, op_pu = 0, op_ptefill = 0; + rad_op op_rascopy = 0; + rad_buf b_ein = 0, b_ex[4] = {}, b_et[4] = {}, b_ea[4] = {}, b_ex4 = 0, b_et4 = 0, b_ea4 = 0; + CtSet ecs{}; + rad_buf b_epos = 0, b_ed1 = 0, b_ez = 0, b_dua = 0, b_dub = 0, b_duh = 0, b_dug = 0; + rad_buf b_pc = 0, b_pte = 0, b_pu = 0; +}; + +/* The width of the prompt rows' code plane: every row and one past the last, a token's (the last + * row's label). */ +constexpr int64_t kPcW = kMaxPrompt + 1; + +static Model g_model[MAX_RANKS]; + +/* ================================================================== declare helpers */ +static rad_op norm_op(RadBuilder* b, int64_t rows, int64_t n, double eps, double wadd, + rad_weight w, std::initializer_list x, rad_buf y) { + return rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), RAD_F64("eps", eps), + RAD_F64("wadd", wadd), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + x, { y }); +} + +static rad_op add_op(RadBuilder* b, int64_t rows, int64_t n, rad_buf a, rad_buf c, rad_buf y) { + return rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a, c }, { y }); +} + +static rad_op gemm_op(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", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +static rad_op gemm_bias_op(RadBuilder* b, int64_t rows, int64_t N, int64_t K, rad_weight w, + rad_weight bias, rad_buf x, rad_buf y) { + return rw(b, 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_WEIGHTS(w, bias)), + { x }, { y }); +} + +static rad_op rows_op(RadBuilder* b, const char* op, int64_t rows, int64_t n, + std::initializer_list in, std::initializer_list out) { + return rw(b, RAD_OP(b, op, + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + in, out); +} + +static rad_op mulw_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight w, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(w)), + { x }, { y }); +} + +static rad_op iota_op(RadBuilder* b, int64_t rows, int64_t start, int64_t step, rad_buf y) { + return rw(b, RAD_OP(b, "iota", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("start", start), + RAD_INT("step", step)), + RAD_NOWEIGHTS), + {}, { y }); +} + +static rad_op cu_op(RadBuilder* b, int64_t mult, rad_buf len, rad_buf y) { + return rw(b, RAD_OP(b, "cu_repeat", + RAD_PARAMS(RAD_RANGE("M", 1, 2), RAD_INT("mult", mult)), + RAD_NOWEIGHTS), + { len }, { y }); +} + +static rad_op ar_op(RadBuilder* b, const Geom& g, rad_buf x) { + if (g.world <= 1) return 0; + return 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), + { x }, { x }); +} + +/* A frame draw: `k` largest, Fish's nucleus over the whole candidate set first (rad OPS.md, + * cfg_topk_sample's top_p), one row a lane, no guidance. */ +static rad_op draw_op(RadBuilder* b, int64_t lanes, int64_t n, int64_t k, double temp, + double top_p, int stream, rad_buf logits, rad_buf ids) { + return rw(b, RAD_OP(b, "cfg_topk_sample", + RAD_PARAMS(RAD_RANGE("M", 1, lanes), RAD_INT("n_vocab", n), + RAD_INT("k", k), RAD_INT("rep", 1), RAD_F64("cfg", 1.0), + RAD_F64("temp", temp), RAD_INT("stream", stream), + RAD_STR("dtype", "f32"), RAD_F64("top_p", top_p)), + RAD_NOWEIGHTS), + { logits }, { ids }); +} + +/* A plain weight copied from the checkpoint, declared at `dtype`, replicated. */ +static rad_weight wcopy(RadBuilder* b, const char* dn, const char* src, uint32_t dtype, + std::initializer_list shape, int group) { + if (map_copy(b, dn, src) < 0) return 0; + return decl_w(b, dn, dtype, shape, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(group)); +} + +/* ================================================================== check_format */ +/* The container's statement of what it is. Every mismatch below would still make sound -- a + * different template, another codebook layout, an fp8 format read as this one -- so each is a + * refusal by name rather than a silent default. */ +static int check_format(const RadModelMeta* meta) { + const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr); + const char* block = rad_meta_gets(meta, "quantization_config.weight_block_size", nullptr); + if (!method || std::strcmp(method, "bsgemm-moe") != 0) { + fprintf(stderr, "radiance: fishomni serves Fish Audio's released drama-3, whose routed " + "experts are block-scaled fp8 (quant_method 'bsgemm-moe'); this container " + "says '%s'\n", method ? method : "(none)"); + return RAD_E_UNSUPPORTED; + } + if (block) { + long long b0 = 0, b1 = 0; + if (std::sscanf(block, "%lld %lld", &b0, &b1) != 2) { b0 = 0; b1 = 0; } + if (b0 != RAD_FP8_BLOCK || b1 != RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: fishomni refuses weight_block_size [%lld, %lld]: libr4d's " + "block-scaled GEMMs are compiled at %d in both dimensions\n", + b0, b1, RAD_FP8_BLOCK); + return RAD_E_UNSUPPORTED; + } + } + const char* tv = rad_meta_gets(meta, "speech_template_version", ""); + if (std::strcmp(tv, "reference-bracket-v1") != 0) { + fprintf(stderr, "radiance: fishomni builds the reference-bracket-v1 prompt and this " + "checkpoint asks for '%s'\n", tv); + return RAD_E_UNSUPPORTED; + } + const char* ad = "audio_decoder_config"; + char k[96]; + auto ai = [&](const char* key, long long dflt) { + std::snprintf(k, sizeof k, "%s.%s", ad, key); + return rad_meta_geti(meta, k, dflt); + }; + auto as = [&](const char* key) { + std::snprintf(k, sizeof k, "%s.%s", ad, key); + return rad_meta_gets(meta, k, ""); + }; + if (rad_meta_geti(meta, "semantic_start_token_id", 0) != kSemBegin || + rad_meta_geti(meta, "semantic_end_token_id", 0) != kSemEnd || + rad_meta_geti(meta, "eos_token_id", 0) != kEos || + std::strcmp(as("decoder_type"), "codebook_mtp_shared") != 0 || + ai("num_codebooks", 0) != kCodes || ai("vocab_size", 0) != kVocab || + ai("vq_backbone_codebooks", 0) != 1 || ai("shared_enrichment_layers", 0) != kShared || + std::strcmp(as("vq_feature_placement"), "backbone_partial") != 0 || + std::strcmp(as("vq_feature_scope"), "all_vq") != 0) { + fprintf(stderr, "radiance: fishomni: not the released drama-3 layout (semantic tokens " + "%lld..%lld, end %lld, a codebook_mtp_shared tower of %d shared layers " + "over %lld codebooks of %lld, one codebook into the backbone)\n", + (long long)kSemBegin, (long long)kSemEnd, (long long)kEos, kShared, + (long long)kCodes, (long long)kVocab); + return RAD_E_UNSUPPORTED; + } + return RAD_OK; +} + +/* ================================================================== the backbone */ +/* qwen35moe_fp8's trunk, written out (arch/qwen35_fp8/qwen35_fp8.cpp, QWEN35_MOE): the same + * blocks, metadata and names, without its drafters, vision tower and int8 build. Its bf16 linears + * (attention, delta net, shared expert) are served by LinearFP8's plain branch beside the fp8 + * experts. */ +static int declare_trunk(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx, + Model& m) { + Geom& g = m.g; + Names& nm = m.nm; + if (meta->n_expert <= 0) { + fprintf(stderr, "radiance: fishomni: the backbone declares no experts; drama-3's is " + "routed\n"); + return RAD_E_UNSUPPORTED; + } + bool have_interval = false; + const int64_t interval = meta_int2(meta, "qwen35.full_attention_interval", + "full_attention_interval", 4, &have_interval); + if (interval <= 0) return RAD_E_INVAL; + RAD_ARCH_TRY(check_layer_schedule("fishomni", meta_text_gets(meta, "layer_types", nullptr), + g.n_layer, interval, {"full_attention"})); + m.n_main = g.n_layer; + + /* GemmaRMSNorm everywhere but the delta net's output norm (rad_block_gdn_fp8.h). */ + g.wadd = 1.0f; + g.wadd_qk = 1.0f; + + double prf = rad_meta_getf(meta, "partial_rotary_factor", 0.0); + if (!(prf > 0.0)) prf = rad_meta_getf(meta, "rope_parameters.partial_rotary_factor", 0.0); + m.n_rot = prf > 0.0 ? (int64_t)(g.head_dim * prf) : 0; + if (m.n_rot <= 0 || m.n_rot > g.head_dim || (m.n_rot & 1)) { + fprintf(stderr, "radiance: fishomni: no usable rotary width (head_dim %lld)\n", + (long long)g.head_dim); + return RAD_E_INVAL; + } + RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot)); + + GdnFP8::Config& gc = m.gcfg; + const int64_t n_head_k_all = meta_int2(meta, "qwen35.ssm.group_count", + "linear_num_key_heads", 0); + const int64_t n_head_v_all = meta_int2(meta, "qwen35.ssm.time_step_rank", + "linear_num_value_heads", 0); + gc.head_k = meta_int2(meta, "qwen35.ssm.state_size", "linear_key_head_dim", 0); + gc.head_v = meta_int2(meta, "qwen35.ssm.value_head_dim", "linear_value_head_dim", 0); + gc.conv_width = meta_int2(meta, "qwen35.ssm.conv_kernel", "linear_conv_kernel_dim", 0); + if (n_head_k_all <= 0 || n_head_v_all <= 0 || gc.head_k <= 0 || gc.head_v <= 0 || + gc.conv_width <= 0) { + fprintf(stderr, "radiance: fishomni: the container does not describe the delta-net " + "layers\n"); + return RAD_E_INVAL; + } + gc.chunk = 64; + RAD_ARCH_TRY(divide_or_fail(n_head_k_all, g.world, "linear_num_key_heads", &gc.n_head_k)); + RAD_ARCH_TRY(divide_or_fail(n_head_v_all, g.world, "linear_num_value_heads", &gc.n_head_v)); + + const int64_t q_dim = g.q_dim(), kv_dim = g.kv_dim(); + const int64_t v_dim = gc.v_dim(), conv_dim = gc.conv_dim(); + + /* ---- the KV groups. The full-attention group also holds the tower's 13 layers, bound below + * at 40..52 (declare_tower). */ + RadKVGroupDecl fd{}; + fd.kind = RAD_KV_FULL; + fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + fd.n_head_kv = g.n_head_kv; + fd.head_dim = g.head_dim; + m.kv_full = rad_decl_kv_group(b, nm.f("kv_attn"), &fd); + g.kv_dtype = rad_dtype_name(fd.dtype); + + RadKVGroupDecl sd{}; + sd.kind = RAD_KV_LINEAR; + sd.dtype = RAD_F32; + sd.n_head_kv = gc.n_head_v; + sd.state_dim[0] = gc.head_v; + sd.state_dim[1] = gc.head_k; + m.kv_state = rad_decl_kv_group(b, nm.f("kv_gdn_state"), &sd); + + RadKVGroupDecl cd{}; + cd.kind = RAD_KV_CONV; + cd.dtype = RAD_BF16; + cd.n_head_kv = 2 * gc.n_head_k + gc.n_head_v; + cd.head_dim = gc.head_k; + cd.conv_width = gc.conv_width; + m.kv_conv = rad_decl_kv_group(b, nm.f("kv_gdn_conv"), &cd); + if (!m.kv_full || !m.kv_state || !m.kv_conv) return RAD_E_INVAL; + + /* ---- activations (qwen35_fp8.cpp says what each is) */ + m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd}); + m.a_h.x = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd}); + RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", g.n_embd)); + m.b_qg = decl_b(b, nm.f("attn_qg"), g.act_dtype, {g.max_tok, g.n_head, 2 * g.head_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_q = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, q_dim}); + m.a_attn.x = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, q_dim}); + m.b_rope_cs = decl_b(b, nm.f("rope_cs"), RAD_F32, {rope_table_rows(g), m.n_rot}, + RAD_BUF_PERSIST); + RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", q_dim)); + m.a_in.x = decl_b(b, nm.f("gdn_in"), g.act_dtype, {g.max_tok, conv_dim + v_dim}); + RAD_ARCH_TRY(m.a_in.declare_qs(b, nm, g, "gdn_in", conv_dim + v_dim)); + m.b_ab = decl_b(b, nm.f("gdn_ab"), g.act_dtype, {g.max_tok, gc.ab_dim()}); + m.b_gq = decl_b(b, nm.f("gdn_q"), g.act_dtype, {g.max_tok, gc.n_head_k, gc.head_k}); + m.b_gk = decl_b(b, nm.f("gdn_k"), g.act_dtype, {g.max_tok, gc.n_head_k, gc.head_k}); + m.b_gv = decl_b(b, nm.f("gdn_v"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v}); + m.b_gdec = decl_b(b, nm.f("gdn_g"), RAD_F32, {g.max_tok, gc.n_head_v}); + m.b_beta = decl_b(b, nm.f("gdn_beta"), RAD_F32, {g.max_tok, gc.n_head_v}); + m.b_kkt = decl_b(b, nm.f("gdn_kkt"), RAD_BF16, {g.max_tok, gc.n_head_v, gc.chunk}); + m.a_go.x = decl_b(b, nm.f("gdn_o"), g.act_dtype, {g.max_tok, gc.n_head_v, gc.head_v}); + RAD_ARCH_TRY(m.a_go.declare_qs(b, nm, g, "gdn_o", v_dim)); + + /* ---- the routing geometry; `n_ff` is already the per-rank expert width */ + { + MoeFP8::Config& mc = m.moecfg; + mc.n_expert = meta->n_expert; + mc.top_k = meta->n_expert_used > 0 ? meta->n_expert_used + : meta_int2(meta, "qwen35.expert_used_count", + "num_experts_per_tok", 0); + mc.n_ff_exp = g.n_ff; + mc.norm_topk = (int)meta_int2(meta, "qwen35.expert_weights_norm", "norm_topk_prob", 1); + const int64_t sh_all = meta_int2(meta, "qwen35.expert_shared_feed_forward_length", + "shared_expert_intermediate_size", 0); + if (sh_all > 0) + RAD_ARCH_TRY(divide_or_fail(sh_all, g.world, "shared_expert_intermediate_size", + &mc.n_ff_shared)); + const int64_t moe_rows = 2048; + mc.rows = g.max_tok < moe_rows ? g.max_tok : moe_rows; + if (mc.top_k <= 0 || mc.top_k > mc.n_expert) { + fprintf(stderr, "radiance: fishomni: top_k %lld is not in [1, %lld]\n", + (long long)mc.top_k, (long long)mc.n_expert); + return RAD_E_INVAL; + } + const int64_t R = g.max_tok, K = mc.rows * mc.top_k; + m.b_rlogits = decl_b(b, nm.f("moe_logits"), g.act_dtype, {R, mc.n_expert}); + m.b_eids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, mc.top_k}); + m.b_ew = decl_b(b, nm.f("moe_w"), g.act_dtype, {R, mc.top_k}); + m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {K}); + m.b_eoff = decl_b(b, nm.f("moe_off"), RAD_I32, {mc.n_expert + 1}); + m.b_ecnt = decl_b(b, nm.f("moe_cnt"), RAD_I32, {mc.n_expert}, RAD_BUF_PERSIST); + m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp}); + m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp}); + m.a_eff.q = decl_b(b, nm.f("moe_ffn.q"), RAD_F8E4M3, {K, mc.n_ff_exp}); + m.a_eff.s = decl_b(b, nm.f("moe_ffn.s"), RAD_F32, {K, fp8_blocks(mc.n_ff_exp)}); + m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd}); + if (mc.n_ff_shared > 0) { + m.b_emoe = decl_b(b, nm.f("moe_out"), g.act_dtype, {R, g.n_embd}); + m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * mc.n_ff_shared}); + m.a_sff.x = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, mc.n_ff_shared}); + m.a_sff.q = decl_b(b, nm.f("shexp_ffn.q"), RAD_F8E4M3, {R, mc.n_ff_shared}); + m.a_sff.s = decl_b(b, nm.f("shexp_ffn.s"), RAD_F32, {R, fp8_blocks(mc.n_ff_shared)}); + m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd}); + m.b_sgate = decl_b(b, nm.f("shexp_gate"), g.act_dtype, {R, 1}); + } + } + + /* ---- the vocabulary edge. The embedding is row-sharded with the vocabulary and summed by the + * all-reduce below; there is no lm_head here, only its 4097 candidate rows (declare_frame). */ + 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"))); + 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()); + 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.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}); + /* Always issued by PROMPT, never folded into layer 0's norm: a frame's embedding is the same + * on every rank (replicated tables), and a reduction there would sum it world times. Exact: + * it sums disjoint rows. */ + 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}); + m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table", + RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), RAD_INT("rot", m.n_rot), + RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale), + RAD_STR("dtype", "f32")), + RAD_NOWEIGHTS), + {}, {m.b_rope_cs}); + + AttnGatedFP8::Wire aw{}; + aw.x = m.b_x; aw.h = m.a_h; aw.qg = m.b_qg; aw.k = m.b_k; aw.v = m.b_v; + aw.q = m.b_q; aw.attn = m.a_attn; + aw.cos_sin = m.op_rope_cs ? m.b_rope_cs : 0; + + GdnFP8::Wire gw{}; + gw.x = m.b_x; gw.h = m.a_h; gw.in = m.a_in; gw.ab = m.b_ab; + gw.q = m.b_gq; gw.k = m.b_gk; gw.v = m.b_gv; + gw.gdec = m.b_gdec; gw.beta = m.b_beta; gw.kkt = m.b_kkt; gw.o = m.a_go; + + MoeFP8::Wire mw{}; + mw.x = m.b_x; mw.h = m.a_h; + mw.logits = m.b_rlogits; mw.ids = m.b_eids; mw.ew = m.b_ew; + mw.sorted = m.b_sorted; mw.eoff = m.b_eoff; mw.ecnt = m.b_ecnt; + mw.egu = m.b_egu; mw.eff = m.a_eff; mw.edn = m.b_edn; mw.moe = m.b_emoe; + mw.sgu = m.b_sgu; mw.sff = m.a_sff; mw.sout = m.b_sout; mw.sgate = m.b_sgate; + + m.layers.resize((size_t)m.n_main); + for (int64_t l = 0; l < m.n_main; ++l) { + Layer& lay = m.layers[(size_t)l]; + lay.full = is_full_attention(l, interval) ? 1 : 0; + /* embed_ar false: layer 0's norm takes no reduction (see op_embed_ar). */ + const LayerFold f = layer_fold(g, l, m.n_main, nullptr, 0, false); + const char* pre = "model.language_model.layers"; + if (lay.full) { + AttnGatedFP8::Src as{}; + as.norm = nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l); + as.qg = nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l); + as.k = nm.ckpt("%s.%lld.self_attn.k_proj.weight", pre, (long long)l); + as.v = nm.ckpt("%s.%lld.self_attn.v_proj.weight", pre, (long long)l); + as.q_norm = nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l); + as.k_norm = nm.ckpt("%s.%lld.self_attn.k_norm.weight", pre, (long long)l); + as.o = nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l); + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_full)); + RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv_full, m.n_rot, aw, as, + f.mix_fold, false, f.mix_ar_in, f.mix_ar_out)); + } else { + GdnFP8::Src gs{}; + gs.norm = nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l); + gs.in_qkv = nm.ckpt("%s.%lld.linear_attn.in_proj_qkv.weight", pre, (long long)l); + gs.in_a = nm.ckpt("%s.%lld.linear_attn.in_proj_a.weight", pre, (long long)l); + gs.in_b = nm.ckpt("%s.%lld.linear_attn.in_proj_b.weight", pre, (long long)l); + gs.in_z = nm.ckpt("%s.%lld.linear_attn.in_proj_z.weight", pre, (long long)l); + gs.conv1d = nm.ckpt("%s.%lld.linear_attn.conv1d.weight", pre, (long long)l); + gs.a_log = nm.ckpt("%s.%lld.linear_attn.A_log", pre, (long long)l); + gs.dt_bias = nm.ckpt("%s.%lld.linear_attn.dt_bias", pre, (long long)l); + gs.out_norm = nm.ckpt("%s.%lld.linear_attn.norm.weight", pre, (long long)l); + gs.out = nm.ckpt("%s.%lld.linear_attn.out_proj.weight", pre, (long long)l); + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_state)); + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv_conv)); + RAD_ARCH_TRY(lay.gdn.declare(b, nm, g, gc, (int)l, m.kv_state, m.kv_conv, gw, gs, + f.mix_fold, false, f.mix_ar_in, f.mix_ar_out)); + } + MoeFP8::Src ms{}; + ms.cfg = m.moecfg; + ms.norm = nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l); + ms.router = nm.ckpt("%s.%lld.mlp.gate.weight", pre, (long long)l); + ms.experts = nm.ckpt("%s.%lld.mlp.experts", pre, (long long)l); + if (m.moecfg.n_ff_shared > 0) { + ms.shared = nm.ckpt("%s.%lld.mlp.shared_expert", pre, (long long)l); + ms.shared_gate = nm.ckpt("%s.%lld.mlp.shared_expert_gate.weight", pre, (long long)l); + } + /* The experts' stored format, read from the layer's first: the release's scale planes are + * f32 (fp8a8f32), not the bf16 Qwen3.6's are. */ + RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)l, ms, &ms.cfg)); + RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms, true, f.mlp_add, + f.mlp_ar_in, f.mlp_ar_out)); + } + for (int64_t l = 0; l + 1 < m.n_main; ++l) + m.layers[(size_t)l].mlp.xp_next = &m.layers[(size_t)l + 1].mlp; + + m.op_final_norm = norm_op(b, g.max_tok, g.n_embd, g.eps, 1.0, m.w_out_norm, {m.b_x}, + m.a_h.x); + if (!have_interval) + rad_note(b, "the container did not state full_attention_interval; assuming %lld, which " + "makes layers 3,7,... full attention", (long long)interval); + return m.op_embed && m.op_final_norm ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== the frame's head */ +/* The lane state, the candidate head and the main token's two draws (FRAME, before the tower), + * and what PROMPT leaves in the lane. Declared in the order a frame issues them: buffer liveness + * follows declaration order. */ +static int declare_frame_head(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t S = m.lanes, D = m.g.n_embd, T = m.g.max_tok; + m.b_hid = decl_b(b, nm.f("frame.hid"), RAD_BF16, { S, D }, RAD_BUF_PERSIST); + m.b_status = decl_b(b, nm.f("frame.status"), RAD_I32, { S }, RAD_BUF_PERSIST); + m.b_hist = decl_b(b, nm.f("frame.history"), RAD_I32, { S * kCodes, kMaxFrames }, + RAD_BUF_PERSIST); + m.b_ras = decl_b(b, nm.f("frame.ras"), RAD_I32, { S, kRasWin }, RAD_BUF_PERSIST); + m.b_u = decl_b(b, nm.f("frame.unseen"), RAD_BF16, { S, D }, RAD_BUF_PERSIST); + m.b_plane = decl_b(b, nm.f("frame.plane"), RAD_BF16, { S, D }); + m.b_slog = decl_b(b, nm.f("frame.slog"), RAD_F32, { S, kCand }); + m.b_first = decl_b(b, nm.f("frame.first"), RAD_I32, { S }); + m.b_alt = decl_b(b, nm.f("frame.alt"), RAD_I32, { S }); + m.b_codes = decl_b(b, nm.f("frame.codes"), RAD_I32, { kCodes, S }); + m.b_ug = decl_b(b, nm.f("frame.ug"), RAD_BF16, { S, D }); + m.b_last = decl_b(b, nm.f("frame.last"), RAD_BF16, { S, D }); + + /* The main token's candidates: the lm_head's rows for the end of speech and the semantic band, + * in id order, replicated (the full head is vocab-sharded and 1 GB). The same rows of the + * embedding feed a frame back to the backbone, indexed by the same candidate. */ + const char* lm = nm.ckpt("lm_head.weight"); + const char* et = nm.ckpt("model.language_model.embed_tokens.weight"); + RAD_ARCH_TRY(map_rows(b, nm.f("frame.cand.weight"), + { { lm, (int)kEos, 1 }, { lm, (int)kSemBegin, kVocab } })); + m.w_cand = decl_w(b, nm.f("frame.cand.weight"), RAD_BF16, { kCand, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(kGrpFrame)); + RAD_ARCH_TRY(map_rows(b, nm.f("frame.cemb.weight"), + { { et, (int)kEos, 1 }, { et, (int)kSemBegin, kVocab } })); + m.w_cemb = decl_w(b, nm.f("frame.cemb.weight"), RAD_BF16, { kCand, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_layer(kGrpFrame)); + /* The codebook table's sections 1..9; section 0 is never read (tower.py, embedding_sum). */ + RAD_ARCH_TRY(map_rows(b, nm.f("frame.cb.weight"), + { { nm.ckpt("audio_decoder.codebook_embeddings.weight"), (int)kVocab, + (kCodes - 1) * kVocab } })); + m.w_cb = decl_w(b, nm.f("frame.cb.weight"), RAD_BF16, { (kCodes - 1) * kVocab, D }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(kGrpFrame)); + if (!m.w_cand || !m.w_cemb || !m.w_cb) return RAD_E_INVAL; + + /* ---- FRAME: the hidden states, the candidates' logits, the two draws and the choice */ + m.op_hsel = rows_op(b, "gather_rows", S, D, { m.b_hid }, { m.b_plane }); + m.op_head = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_vocab", kCand), + RAD_INT("n_embd", D), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_cand)), + { m.b_plane }, { m.b_slog }); + m.op_samp = draw_op(b, S, kCand, kMainTopK, kTemp, kTopP, 0, m.b_slog, m.b_first); + m.op_samp_ras = draw_op(b, S, kCand, kRasTopK, kRasTemp, kRasTopP, 1, m.b_slog, m.b_alt); + /* The redraw: only a semantic first draw (candidates 1..4096), and only one the lane's last + * 16 picks hold; the prompt's rows are text, so its window starts empty (op_rasinit). */ + m.op_ras = rw(b, RAD_OP(b, "ras_pick", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("win", kRasWin), + RAD_INT("lo", 1), RAD_INT("hi", kCand), RAD_INT("rep", 1)), + RAD_NOWEIGHTS), + { m.b_first, m.b_alt, m.b_ras }, { m.b_codes, m.b_ras }); + m.op_status = rw(b, RAD_OP(b, "end_status", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("end", 0), + RAD_INT("rep", 1)), + RAD_NOWEIGHTS), + { m.b_codes }, { m.b_status }); + m.op_ugather = rows_op(b, "gather_rows", S, D, { m.b_u }, { m.b_ug }); + + /* ---- PROMPT: the last row's hidden state into the lane, an empty window and no unseen codes + * (the prompt's last row is text), and the tower's code embeddings, all zero for text labels */ + m.op_plast = rows_op(b, "gather_rows", S, D, { m.a_h.x }, { m.b_last }); + m.op_pstore = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_last }, { m.b_hid }); + m.op_uzero = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, 1), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_u }); + m.op_rasinit = iota_op(b, kRasWin, -1, 0, m.b_ras); + m.b_tcat = decl_b(b, nm.f("tower.cat"), RAD_BF16, { T, 2 * D }); + m.op_efill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_tcat }); + return m.op_hsel && m.op_head && m.op_samp && m.op_samp_ras && m.op_ras && m.op_status && + m.op_ugather && m.op_plast && m.op_pstore && m.op_uzero && m.op_rasinit && + m.op_efill + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the tower */ +static int declare_tower(RadBuilder* b, const RadModelMeta* meta, Model& m) { + Names& nm = m.nm; + Geom& g = m.gt; + g = m.g; + const char* ad = "audio_decoder_config"; + char key[96]; + auto ai = [&](const char* k, long long d) { + std::snprintf(key, sizeof key, "%s.%s", ad, k); + return (int64_t)rad_meta_geti(meta, key, d); + }; + auto af = [&](const char* k, double d) { + std::snprintf(key, sizeof key, "%s.%s", ad, k); + return rad_meta_getf(meta, key, d); + }; + g.n_head_all = ai("n_head", 0); + g.n_head_kv_all = ai("n_local_heads", 0); + g.head_dim = ai("head_dim", 0); + g.n_ff_all = ai("intermediate_size", 0); + const double rot_frac = af("rotary_percent", 0.0); + g.eps = (float)af("norm_eps", 1e-6); + g.theta = (float)af("rope_base", 0.0); + if (ai("dim", 0) != g.n_embd || g.n_head_all <= 0 || g.n_head_kv_all <= 0 || + g.head_dim <= 0 || g.n_ff_all <= 0 || !(g.theta > 0.0f) || !(rot_frac > 0.0)) { + fprintf(stderr, "radiance: fishomni: the audio decoder config does not describe the " + "tower (dim %lld, %lld heads over %lld of %lld, ffn %lld)\n", + (long long)ai("dim", 0), (long long)g.n_head_all, (long long)g.n_head_kv_all, + (long long)g.head_dim, (long long)g.n_ff_all); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(divide_or_fail(g.n_head_all, g.world, "the tower's heads", &g.n_head)); + RAD_ARCH_TRY(divide_or_fail(g.n_head_kv_all, g.world, "the tower's KV heads", &g.n_head_kv)); + RAD_ARCH_TRY(divide_or_fail(g.n_ff_all, g.world, "the tower's feed-forward", &g.n_ff)); + g.rope_scale = 1.0f; + g.yarn = RadYarn{}; + g.rope_mc = false; + m.n_rot_t = (int64_t)(g.head_dim * rot_frac); + /* One KV group for the backbone's ten attention layers and these: the cache rows must match. */ + if (g.n_head_kv != m.g.n_head_kv || g.head_dim != m.g.head_dim) { + fprintf(stderr, "radiance: fishomni: the tower's KV heads (%lld of %lld) differ from the " + "backbone's (%lld of %lld), and they share one cache group\n", + (long long)g.n_head_kv, (long long)g.head_dim, (long long)m.g.n_head_kv, + (long long)m.g.head_dim); + return RAD_E_UNSUPPORTED; + } + + const int64_t T = g.max_tok, S = m.lanes, D = g.n_embd, hd = g.head_dim; + const int64_t qd = g.n_head * hd, kd = g.n_head_kv * hd, ff = g.n_ff; + const int64_t qd_all = g.n_head_all * hd, kd_all = g.n_head_kv_all * hd; + m.b_te = decl_b(b, nm.f("tower.e"), RAD_BF16, { S, D }); + m.b_tm = decl_b(b, nm.f("tower.m"), RAD_BF16, { T, D }); + m.b_th = decl_b(b, nm.f("tower.h"), RAD_BF16, { T, D }); + m.b_tq = decl_b(b, nm.f("tower.q"), RAD_BF16, { T, qd }); + m.b_tg = decl_b(b, nm.f("tower.g"), RAD_BF16, { T, qd }); + m.b_tk = decl_b(b, nm.f("tower.k"), RAD_BF16, { T, kd }); + m.b_tv = decl_b(b, nm.f("tower.v"), RAD_BF16, { T, kd }); + m.b_tattn = decl_b(b, nm.f("tower.attn"), RAD_BF16, { T, qd }); + m.b_to = decl_b(b, nm.f("tower.o"), RAD_BF16, { T, D }); + m.b_tgu = decl_b(b, nm.f("tower.gu"), RAD_BF16, { T, 2 * ff }); + m.b_tff = decl_b(b, nm.f("tower.ff"), RAD_BF16, { T, ff }); + m.b_tho = decl_b(b, nm.f("tower.out"), RAD_BF16, { T, D }); + m.b_hlog = decl_b(b, nm.f("tower.hlog"), RAD_F32, { S, kVocab }); + /* PROMPT with references: every row's label embedding, and its unseen codes (2..9 of the + * row's own frame, zero at a token's row), summed in f32 and rounded once as op_u's. */ + m.b_pte = decl_b(b, nm.f("tower.pe"), RAD_BF16, { T, D }); + m.b_pu = decl_b(b, nm.f("tower.pu"), RAD_BF16, { T, D }); + m.op_ptefill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_pte }); + m.op_pufill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_pu }); + m.op_pu = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", D), + RAD_INT("n_codes", kCodes - 2), RAD_INT("vocab", kVocab), + RAD_INT("off0", 0), RAD_F64("scale", 1.0), + RAD_STR("dtype", "bf16"), RAD_INT("round", 1)), + RAD_WEIGHTS(m.w_cb, m.w_cb)), + { m.b_pc }, { m.b_pu }); + if (!m.op_ptefill || !m.op_pufill || !m.op_pu) return RAD_E_INVAL; + + for (int i = 0; i < kTower; ++i) { + TowerLayer& L = m.tw[i]; + const bool shared = i < kShared; + const int k = i - kShared; /* the per-codebook index, -1.. for shared */ + const int grp = kGrpTower + i, kvl = (int)m.n_main + i; + const char* pre = shared ? nm.ckpt("audio_decoder_mtp_shared.layers.%d", i) + : nm.ckpt("audio_decoder_mtp.layers.%d", k); + auto src = [&](const char* s) { return nm.ckpt("%s.%s", pre, s); }; + auto dn = [&](const char* s) { return nm.f("tower.%d.%s", i, s); }; + auto gain = [&](const char* d, const char* s, int64_t n) { + return wcopy(b, dn(d), src(s), RAD_F32, { n }, grp); + }; + + /* The code embedding. A layer that injects code 0 reads it by candidate (row 0 the end of + * speech, row c + 1 code c), so its table is the checkpoint's with row 0 again in front: + * fish-speech clamps the end's c0 to 0. The others read the code a head drew. */ + const char* tsrc = src(shared ? "semantic_embedding.weight" : "codebook_embedding.weight"); + const bool by_cand = shared || k == 0; + if (by_cand) RAD_ARCH_TRY(map_rows(b, dn("emb.weight"), { { tsrc, 0, 1 }, + { tsrc, 0, kVocab } })); + else RAD_ARCH_TRY(map_copy(b, dn("emb.weight"), tsrc)); + L.w_emb = decl_w(b, dn("emb.weight"), RAD_BF16, { by_cand ? kCand : kVocab, D }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(grp)); + L.w_en = gain("enorm.weight", "enorm.weight", D); + L.w_hn = gain("hnorm.weight", "hnorm.weight", D); + L.w_an = gain("attn_norm.weight", "transformer_layer.attention_norm.weight", D); + L.w_fn = gain("ffn_norm.weight", "transformer_layer.ffn_norm.weight", D); + L.w_fin = gain("final_norm.weight", "final_layernorm.weight", D); + L.w_qn = gain("q_norm.weight", "transformer_layer.attention.q_norm.weight", hd); + L.w_kn = gain("k_norm.weight", "transformer_layer.attention.k_norm.weight", hd); + L.w_eh = wcopy(b, dn("eh.weight"), src("eh_proj.weight"), RAD_BF16, { D, 2 * D }, grp); + + /* wqkv rows [Q | G | K | V], each a projection of its own, split by heads. */ + const char* wqkv = src("transformer_layer.attention.wqkv.weight"); + auto proj = [&](const char* d, int64_t first, int64_t rows, int64_t local) -> rad_weight { + if (map_rows(b, dn(d), { { wqkv, (int)first, rows } }) < 0) return 0; + return decl_w(b, dn(d), RAD_BF16, { local, D }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, + grp_layer(grp)); + }; + L.w_q = proj("q.weight", 0, qd_all, qd); + L.w_g = proj("g.weight", qd_all, qd_all, qd); + L.w_k = proj("k.weight", 2 * qd_all, kd_all, kd); + L.w_v = proj("v.weight", 2 * qd_all + kd_all, kd_all, kd); + RAD_ARCH_TRY(map_copy(b, dn("o.weight"), src("transformer_layer.attention.wo.weight"))); + L.w_o = decl_w(b, dn("o.weight"), RAD_BF16, { D, qd }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_COL, grp_layer(grp)); + RAD_ARCH_TRY(map_concat(b, dn("gate_up.weight"), + { src("transformer_layer.feed_forward.w1.weight"), + src("transformer_layer.feed_forward.w3.weight") })); + L.w_gu = decl_w(b, dn("gate_up.weight"), RAD_BF16, { 2 * ff, D }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_ROW, grp_layer(grp), 0, { ff, ff }); + RAD_ARCH_TRY(map_copy(b, dn("down.weight"), src("transformer_layer.feed_forward.w2.weight"))); + L.w_down = decl_w(b, dn("down.weight"), RAD_BF16, { D, ff }, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_COL, grp_layer(grp)); + if (!L.w_emb || !L.w_en || !L.w_hn || !L.w_an || !L.w_fn || !L.w_fin || !L.w_qn || + !L.w_kn || !L.w_eh || !L.w_q || !L.w_g || !L.w_k || !L.w_v || !L.w_o || !L.w_gu || + !L.w_down) + return RAD_E_INVAL; + + /* ---- the ops, in the order a pass issues them. The embedding and its norm run in FRAME + * only; PROMPT's labels are text, whose embedding is zero, and so is its norm (op_efill + * zeroes that half of the concatenation once a prompt). */ + L.op_emb = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", D), + RAD_INT("n_codes", 1), RAD_INT("vocab", kVocab), + RAD_INT("off0", 0), RAD_F64("scale", 1.0), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_emb, L.w_emb)), + { m.b_codes }, { m.b_te }); + if (i == 0) L.op_eadd = add_op(b, S, D, m.b_te, m.b_ug, m.b_te); + L.op_en = norm_op(b, S, D, g.eps, 1.0, L.w_en, { m.b_te }, m.b_tcat); + /* PROMPT with references: the label is the next row's frame, off the prompt rows' code + * plane a row on. Code 0 there is the frame's own c0, so a by-candidate table reads it + * one row on; a token row's code (-2 for code 0, -1 for the others) reads nothing, and + * its embedding stays the zero the fill leaves. */ + L.op_pemb = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n_embd", D), + RAD_INT("n_codes", 1), RAD_INT("vocab", kVocab), + RAD_INT("off0", by_cand ? 1 : 0), + RAD_F64("scale", 1.0), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_emb, L.w_emb)), + { m.b_pc }, { m.b_pte }); + if (i == 0) L.op_peadd = add_op(b, T, D, m.b_pte, m.b_pu, m.b_pte); + L.op_pen = norm_op(b, T, D, g.eps, 1.0, L.w_en, { m.b_pte }, m.b_tcat); + if (!L.op_pemb || !L.op_pen || (i == 0 && !L.op_peadd)) return RAD_E_INVAL; + /* Layer 0's hidden state is the backbone's: the prompt's rows (PROMPT) or the frame's + * plane (FRAME); both stay live to here. */ + L.op_hn = i == 0 ? norm_op(b, T, D, g.eps, 1.0, L.w_hn, { m.a_h.x, m.b_plane }, m.b_tcat) + : norm_op(b, T, D, g.eps, 1.0, L.w_hn, { m.b_tho }, m.b_tcat); + L.op_eh = gemm_op(b, T, D, 2 * D, L.w_eh, m.b_tcat, m.b_tm); + L.op_an = norm_op(b, T, D, g.eps, 1.0, L.w_an, { m.b_tm }, m.b_th); + L.op_q = gemm_op(b, T, qd, D, L.w_q, m.b_th, m.b_tq); + L.op_g = gemm_op(b, T, qd, D, L.w_g, m.b_th, m.b_tg); + L.op_k = gemm_op(b, T, kd, D, L.w_k, m.b_th, m.b_tk); + L.op_v = gemm_op(b, T, kd, D, L.w_v, m.b_th, m.b_tv); + /* (1 + w) per head, always: the exporter never wrote attention_qk_norm (tower.py). */ + L.op_qn = norm_op(b, T * g.n_head, hd, g.eps, 1.0, L.w_qn, { m.b_tq }, m.b_tq); + L.op_kn = norm_op(b, T * g.n_head_kv, hd, g.eps, 1.0, L.w_kn, { m.b_tk }, m.b_tk); + /* Adjacent pairs (GPT-J), unlike the backbone's halves, over the first 64 dims. */ + L.op_rq = rw(b, decl_rope(b, g, T, hd, g.n_head, 0, m.n_rot_t, "gptj"), { m.b_tq }, + { m.b_tq }); + L.op_rk = rw(b, decl_rope(b, g, T, hd, g.n_head_kv, 0, m.n_rot_t, "gptj"), { m.b_tk }, + { m.b_tk }); + RAD_ARCH_TRY(rad_bind_layer_kv(b, kvl, m.kv_full)); + /* Declared before kv_store, which reads back the resolved block size. */ + L.op_attn = rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", hd), + RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), + RAD_INT("window", 0), 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", m.g.kv_dtype)), + RAD_NOWEIGHTS), + { m.b_tq }, { m.b_tattn }); + L.op_kv = rw(b, RAD_OP(b, "kv_store", + RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("head_dim", hd), + RAD_INT("n_head_kv", g.n_head_kv), + RAD_INT("block_size", rad_kv_block_size(b, m.kv_full)), + RAD_STR("kv_dtype", m.g.kv_dtype)), + RAD_NOWEIGHTS), + { m.b_tk, m.b_tv }, {}); + L.op_sig = rows_op(b, "sigmoid", T, qd, { m.b_tg }, { m.b_tg }); + L.op_mul = rows_op(b, "mul", T, qd, { m.b_tattn, m.b_tg }, { m.b_tattn }); + L.op_o = gemm_op(b, T, D, qd, L.w_o, m.b_tattn, m.b_to); + L.op_ar1 = ar_op(b, g, m.b_to); + L.op_add1 = add_op(b, T, D, m.b_tm, m.b_to, m.b_tm); + L.op_fn = norm_op(b, T, D, g.eps, 1.0, L.w_fn, { m.b_tm }, m.b_th); + L.op_gu = gemm_op(b, T, 2 * ff, D, L.w_gu, m.b_th, m.b_tgu); + L.op_act = rows_op(b, "silu_mul", T, ff, { m.b_tgu }, { m.b_tff }); + L.op_down = gemm_op(b, T, D, ff, L.w_down, m.b_tff, m.b_to); + L.op_ar2 = ar_op(b, g, m.b_to); + L.op_add2 = add_op(b, T, D, m.b_tm, m.b_to, m.b_tm); + L.op_fin = norm_op(b, T, D, g.eps, 1.0, L.w_fin, { m.b_tm }, m.b_tho); + if (!L.op_emb || !L.op_en || !L.op_hn || !L.op_eh || !L.op_an || !L.op_q || !L.op_g || + !L.op_k || !L.op_v || !L.op_qn || !L.op_kn || !L.op_rq || !L.op_rk || !L.op_attn || + !L.op_kv || !L.op_sig || !L.op_mul || !L.op_o || !L.op_add1 || !L.op_fn || + !L.op_gu || !L.op_act || !L.op_down || !L.op_add2 || !L.op_fin || + (i == 0 && !L.op_eadd) || (g.world > 1 && (!L.op_ar1 || !L.op_ar2))) + return RAD_E_INVAL; + + /* A per-codebook layer's head draws code k + 1 (FRAME only). */ + if (!shared) { + L.w_head = wcopy(b, nm.f("tower.head.%d.weight", k), + nm.ckpt("audio_decoder_mtp.heads.%d.weight", k), RAD_BF16, + { kVocab, D }, grp); + L.op_head = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_vocab", kVocab), + RAD_INT("n_embd", D), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(L.w_head)), + { m.b_tho }, { m.b_hlog }); + L.op_samp = draw_op(b, S, kVocab, kHeadTopK, kTemp, kTopP, 2 + k, m.b_hlog, m.b_codes); + if (!L.w_head || !L.op_head || !L.op_samp) return RAD_E_INVAL; + } + } + /* The codes stay live through the last layer: every layer's embedding reads them. */ + RAD_ARCH_TRY(rad_op_reads(b, m.tw[kTower - 1].op_samp, &m.b_codes, 1)); + return RAD_OK; +} + +/* ================================================================== the frame's tail */ +/* The frame into the lane's history, its unseen codes into the lane, and its embedding into the + * backbone's stream; after the backbone, the frame row's hidden state into the lane. */ +static int declare_frame_tail(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t S = m.lanes, D = m.g.n_embd; + m.b_unew = decl_b(b, nm.f("frame.unew"), RAD_BF16, { S, D }); + m.op_store = rw(b, RAD_OP(b, "frame_store", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_codes", kCodes), + RAD_INT("stride", kMaxFrames), RAD_INT("rep", 1), + RAD_INT("skip", 0)), + RAD_NOWEIGHTS), + { m.b_codes, m.b_status }, { m.b_hist }); + /* Codes 2..9 summed in f32 and rounded once, as embedding_bag does: sections 2..9. */ + m.op_u = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", D), + RAD_INT("n_codes", kCodes - 2), RAD_INT("vocab", kVocab), + RAD_INT("off0", 0), RAD_F64("scale", 1.0), + RAD_STR("dtype", "bf16"), RAD_INT("round", 1)), + RAD_WEIGHTS(m.w_cb, m.w_cb)), + { m.b_codes }, { m.b_unew }); + m.op_uscat = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.b_unew }, { m.b_u }); + /* (E_lm[candidate] + E_cb[4096 + c1]) / sqrt 2, each sum rounded to bf16 as the reference's + * tensors are (tower.py, embed_backbone). */ + m.op_fb = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n_embd", D), + RAD_INT("n_codes", 2), RAD_INT("vocab", kVocab), + RAD_INT("off0", 0), RAD_F64("scale", 1.0 / std::sqrt(2.0)), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_cemb, m.w_cb)), + { m.b_codes }, { m.b_x }); + m.op_fstore = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, S), RAD_INT("n", D), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { m.a_h.x }, { m.b_hid }); + /* PROMPT with references: a frame's row embedded as a made frame's is, off the rows' code + * plane (code 0 its own c0, so the candidate table is read one row on); a token's row, whose + * code 0 is -2, keeps its token's embedding. */ + m.op_pfb = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, m.g.max_tok), RAD_INT("n_embd", D), + RAD_INT("n_codes", 2), RAD_INT("vocab", kVocab), + RAD_INT("off0", 1), RAD_F64("scale", 1.0 / std::sqrt(2.0)), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(m.w_cemb, m.w_cb)), + { m.b_pc }, { m.b_x }); + /* ... and the lane's window of main picks starts with the prompt's last 16 rows', a frame's + * as its candidate (c0 + 1) and a token's as no pick (-2 + 1). */ + std::string src, one; + for (int64_t i = 0; i < kRasWin; ++i) { + src += (i ? " " : "") + std::to_string(i); + one += i ? " 1" : "1"; + } + m.op_rascopy = rw(b, RAD_OP(b, "int_affine", + RAD_PARAMS(RAD_RANGE("M", 1, kRasWin), RAD_STR("src", src.c_str()), + RAD_STR("mul", one.c_str()), + RAD_STR("add", one.c_str())), + RAD_NOWEIGHTS), + { m.b_pc }, { m.b_ras }); + return m.op_store && m.op_u && m.op_uscat && m.op_fb && m.op_fstore && m.op_pfb && + m.op_rascopy + ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the codec */ +/* A causal conv whose weight the checkpoint keeps weight-normalised (folded at convert). */ +static int vconv(RadBuilder* b, Names& nm, VConv& v, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t k, int64_t dil, int64_t rows, rad_buf x, rad_buf res, + rad_buf y, rad_buf cu, const char* act = "none") { + const char* wn = nm.f("%s.weight", dn); + RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.parametrizations.weight.original0", src), + nm.ckpt("%s.parametrizations.weight.original1", src))); + v.w = decl_w(b, wn, RAD_BF16, { cout, cin, k }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + v.b = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { cout }, kGrpCodec); + if (!v.w || !v.b) return RAD_E_INVAL; + const RadParam ps[] = { RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), RAD_INT("cout", cout), + RAD_INT("k", k), RAD_INT("dil", dil), RAD_STR("act", act), + RAD_STR("dtype", "bf16"), RAD_INT("causal", 1) }; + const rad_weight ws[] = { v.w, v.b }; + v.op = res ? rw(b, rad_decl_op(b, "conv1d", ps, 8, ws, 2), { x, cu, res }, { y }) + : rw(b, rad_decl_op(b, "conv1d", ps, 8, ws, 2), { x, cu }, { y }); + return v.op ? RAD_OK : RAD_E_INVAL; +} + +static rad_weight valpha(RadBuilder* b, Names& nm, const char* dn, const char* src, int64_t n) { + return wcopy(b, nm.f("%s.alpha", dn), nm.ckpt("%s.alpha", src), RAD_F32, { 1, n, 1 }, + kGrpCodec); +} + +static rad_op snake_op(RadBuilder* b, int64_t rows, int64_t n, rad_weight a, rad_buf x, rad_buf y) { + return rw(b, RAD_OP(b, "snake", + RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("n", n), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(a)), + { x }, { y }); +} + +/* An encoder's causal conv over the pass's clips: their bounds in samples, an input row holding + * `rate` of them (cu_div), `stride` input rows an output row. */ +static rad_op econv_op(RadBuilder* b, int64_t rows, int64_t cin, int64_t cout, int64_t k, + int64_t dil, int64_t stride, int64_t rate, rad_weight w, rad_weight bias, + rad_buf x, rad_buf res, rad_buf y) { + const RadParam ps[] = { RAD_RANGE("M", 1, rows), RAD_INT("cin", cin), RAD_INT("cout", cout), + RAD_INT("k", k), RAD_INT("dil", dil), RAD_STR("act", "none"), + RAD_STR("dtype", "bf16"), RAD_INT("causal", 1), + RAD_INT("cu_div", rate), RAD_INT("stride", stride) }; + const int np = stride > 1 ? 10 : 9; + const rad_weight ws[] = { w, bias }; + return res ? rw(b, rad_decl_op(b, "conv1d", ps, np, ws, 2), { x, res }, { y }) + : rw(b, rad_decl_op(b, "conv1d", ps, np, ws, 2), { x }, { y }); +} + +/* An encoder conv, weight-normalised as vconv's. */ +static int econv(RadBuilder* b, Names& nm, VConv& v, const char* dn, const char* src, int64_t cin, + int64_t cout, int64_t k, int64_t dil, int64_t stride, int64_t rate, int64_t rows, + rad_buf x, rad_buf res, rad_buf y) { + const char* wn = nm.f("%s.weight", dn); + RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.parametrizations.weight.original0", src), + nm.ckpt("%s.parametrizations.weight.original1", src))); + v.w = decl_w(b, wn, RAD_BF16, { cout, cin, k }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + v.b = wcopy(b, nm.f("%s.bias", dn), nm.ckpt("%s.bias", src), RAD_BF16, { cout }, kGrpCodec); + if (!v.w || !v.b) return RAD_E_INVAL; + v.op = econv_op(b, rows, cin, cout, k, dil, stride, rate, v.w, v.b, x, res, y); + return v.op ? RAD_OK : RAD_E_INVAL; +} + +/* A codec transformer of `n` layers (modded_dac.py's WindowLimitedTransformer): plain-gain RMS + * norms at eps 1e-5, fused q|k|v with adjacent-pair rotary over all 64 dims at the rows' + * positions, causal attention over a window of `win` rows within each sequence, layer scales on + * both residual branches, over `rows` rows of B.x in place. Layer l's weights are `dn`.l.* from + * `src`.layers.l. The sequences are the buffer `cu`, or with none the pass's clips in samples, + * `cdiv` of them a row; the positions the buffer `pos`, or with none the pass's own. */ +static int declare_ct(RadBuilder* b, Names& nm, std::vector& ls, const char* dn, + const char* src, int n, int64_t rows, int64_t win, int64_t cdiv, + const CtSet& B, rad_buf cu, rad_buf pos) { + const int64_t qd = kCtHeads * kCtHeadDim; + ls.assign((size_t)n, CodecLayer{}); + for (int l = 0; l < n; ++l) { + CodecLayer& L = ls[(size_t)l]; + auto sr = [&](const char* x) { return nm.ckpt("%s.layers.%d.%s", src, l, x); }; + auto d = [&](const char* x) { return nm.f("%s.%d.%s", dn, l, x); }; + L.w_n1 = wcopy(b, d("n1.weight"), sr("attention_norm.weight"), RAD_F32, { kLat }, + kGrpCodec); + L.w_n2 = wcopy(b, d("n2.weight"), sr("ffn_norm.weight"), RAD_F32, { kLat }, kGrpCodec); + L.w_ls1 = wcopy(b, d("ls1.weight"), sr("attention_layer_scale.gamma"), RAD_F32, + { kLat }, kGrpCodec); + L.w_ls2 = wcopy(b, d("ls2.weight"), sr("ffn_layer_scale.gamma"), RAD_F32, { kLat }, + kGrpCodec); + L.w_qkv = wcopy(b, d("qkv.weight"), sr("attention.wqkv.weight"), RAD_BF16, + { 3 * qd, kLat }, kGrpCodec); + L.w_o = wcopy(b, d("o.weight"), sr("attention.wo.weight"), RAD_BF16, { kLat, qd }, + kGrpCodec); + if (map_concat(b, d("gate_up.weight"), + { sr("feed_forward.w1.weight"), sr("feed_forward.w3.weight") }) < 0) + return RAD_E_INVAL; + L.w_gu = decl_w(b, d("gate_up.weight"), RAD_BF16, { 2 * kCtFf, kLat }, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(kGrpCodec)); + L.w_down = wcopy(b, d("down.weight"), sr("feed_forward.w2.weight"), RAD_BF16, + { kLat, kCtFf }, kGrpCodec); + /* Plain-gain RMS norms at eps 1e-5 (the codec's own RMSNorm, not the backbone's). */ + L.op_n1 = norm_op(b, rows, kLat, kCtEps, 0.0, L.w_n1, { B.x }, B.h); + L.op_qkv = gemm_op(b, rows, 3 * qd, kLat, L.w_qkv, B.h, B.qkv); + /* Adjacent pairs over all 64 dims, positions the rows' own: a piece's frames as a whole + * decode restarting at 0 would see them, a clip's rows in the pass (attention reads only + * their differences). */ + L.op_rope = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, rows), + RAD_INT("head_dim", kCtHeadDim), + RAD_INT("n_head", kCtHeads), + RAD_INT("n_head_kv", kCtHeads), + RAD_F64("theta", kCtTheta), RAD_F64("scale", 1.0), + RAD_STR("mode", "gptj")), + RAD_NOWEIGHTS), + { B.qkv }, { B.qkv }); + const RadParam ap[] = { RAD_RANGE("M", 1, rows), RAD_INT("head_dim", kCtHeadDim), + RAD_INT("gqa", 1), RAD_INT("causal", 1), RAD_STR("dtype", "bf16"), + RAD_F64("scale", 1.0 / std::sqrt((double)kCtHeadDim)), + RAD_INT("max_seqlen", rows), RAD_INT("window", win), + RAD_INT("cu_div", cdiv) }; + L.op_attn = rw(b, rad_decl_op(b, "attn_dense", ap, cdiv > 1 ? 9 : 8, nullptr, 0), + { B.qkv }, { B.attn }); + L.op_o = gemm_op(b, rows, kLat, qd, L.w_o, B.attn, B.o); + L.op_ls1 = mulw_op(b, rows, kLat, L.w_ls1, B.o, B.o); + L.op_add1 = add_op(b, rows, kLat, B.x, B.o, B.x); + L.op_n2 = norm_op(b, rows, kLat, kCtEps, 0.0, L.w_n2, { B.x }, B.h); + L.op_gu = gemm_op(b, rows, 2 * kCtFf, kLat, L.w_gu, B.h, B.gu); + L.op_act = rows_op(b, "silu_mul", rows, kCtFf, { B.gu }, { B.ff }); + L.op_down = gemm_op(b, rows, kLat, kCtFf, L.w_down, B.ff, B.o); + L.op_ls2 = mulw_op(b, rows, kLat, L.w_ls2, B.o, B.o); + L.op_add2 = add_op(b, rows, kLat, B.x, B.o, B.x); + if (!L.w_n1 || !L.w_n2 || !L.w_ls1 || !L.w_ls2 || !L.w_qkv || !L.w_o || !L.w_gu || + !L.w_down || !L.op_n1 || !L.op_qkv || !L.op_rope || !L.op_attn || !L.op_o || + !L.op_ls1 || !L.op_add1 || !L.op_n2 || !L.op_gu || !L.op_act || !L.op_down || + !L.op_ls2 || !L.op_add2) + return RAD_E_INVAL; + if (cu) RAD_ARCH_TRY(rad_op_reads(b, L.op_attn, &cu, 1)); + if (pos) RAD_ARCH_TRY(rad_op_reads(b, L.op_rope, &pos, 1)); + } + return RAD_OK; +} + +static int declare_codec(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t NL = kVocContext + kVocChunk; /* frames through the transformer */ + const int64_t NC = kConvFrames; /* frames through the convolutions */ + const int64_t qd = kCtHeads * kCtHeadDim; + const char* q = "codec.quantizer"; + + /* ---- the dequantiser: each codebook's raw row (dimension 8) through its own 1x1 projection + * to 1024, summed into the transformer's stream. Code 0 is a candidate index (c0 + 1); codes + * 1..9 come from heads of 4096 and read 1024-entry codebooks clamped at 1023 (rvq.py). */ + m.b_rq = decl_b(b, nm.f("codec.rq"), RAD_BF16, { NL, kCbDim }); + m.b_cx = decl_b(b, nm.f("codec.x"), RAD_BF16, { NL, kLat }); + m.b_cconst = decl_b(b, nm.f("codec.nconv"), RAD_I32, { 1 }); + m.op_cnst = iota_op(b, 1, NC, 0, m.b_cconst); + for (int s = 0; s < kRates; ++s) { + m.b_ccu[s] = decl_b(b, nm.f("codec.cu%d", s), RAD_I32, { 2 }); + m.op_ccu[s] = s == 0 ? cu_op(b, 1, 0, m.b_ccu[0]) : cu_op(b, kRate[s], m.b_cconst, m.b_ccu[s]); + if (!m.op_ccu[s]) return RAD_E_INVAL; + } + for (int k = 0; k < kCodes; ++k) { + const char* qs = k == 0 ? nm.ckpt("%s.semantic_quantizer.quantizers.0", q) + : nm.ckpt("%s.quantizer.quantizers.%d", q, k - 1); + const int64_t bins = k == 0 ? kVocab : kResVocab; + m.w_cbk[k] = wcopy(b, nm.f("codec.cb%d.weight", k), nm.ckpt("%s.codebook.weight", qs), + RAD_BF16, { bins, kCbDim }, kGrpCodec); + m.op_rq[k] = rw(b, RAD_OP(b, "rvq_embed", + RAD_PARAMS(RAD_RANGE("M", 1, NL), RAD_INT("n_embd", kCbDim), + RAD_INT("n_codes", 1), RAD_INT("vocab", bins), + RAD_INT("off0", k == 0 ? -1 : 0), + RAD_F64("scale", 1.0), RAD_STR("dtype", "bf16"), + RAD_INT("clamp", k == 0 ? 0 : kResVocab)), + RAD_WEIGHTS(m.w_cbk[k], m.w_cbk[k])), + { m.b_hist }, { m.b_rq }); + /* The out-projection is the old-style weight norm (weight_g, weight_v). */ + VConv& v = m.qo[k]; + const char* wn = nm.f("codec.q%d.weight", k); + RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.out_proj.weight_g", qs), + nm.ckpt("%s.out_proj.weight_v", qs))); + v.w = decl_w(b, wn, RAD_BF16, { kLat, kCbDim, 1 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + v.b = wcopy(b, nm.f("codec.q%d.bias", k), nm.ckpt("%s.out_proj.bias", qs), RAD_BF16, + { kLat }, kGrpCodec); + if (!m.w_cbk[k] || !m.op_rq[k] || !v.w || !v.b) return RAD_E_INVAL; + const RadParam ps[] = { RAD_RANGE("M", 1, NL), RAD_INT("cin", kCbDim), + RAD_INT("cout", kLat), RAD_INT("k", 1), RAD_INT("dil", 1), + RAD_STR("act", "none"), RAD_STR("dtype", "bf16"), + RAD_INT("causal", 1) }; + const rad_weight ws[] = { v.w, v.b }; + v.op = k == 0 ? rw(b, rad_decl_op(b, "conv1d", ps, 8, ws, 2), { m.b_rq, m.b_ccu[0] }, + { m.b_cx }) + : rw(b, rad_decl_op(b, "conv1d", ps, 8, ws, 2), + { m.b_rq, m.b_ccu[0], m.b_cx }, { m.b_cx }); + if (!v.op) return RAD_E_INVAL; + } + + /* ---- the post-quantiser transformer (modded_dac.py, WindowLimitedTransformer) */ + const char* pt = "codec.quantizer.post_module"; + m.b_ch = decl_b(b, nm.f("codec.h"), RAD_BF16, { NL, kLat }); + m.b_cqkv = decl_b(b, nm.f("codec.qkv"), RAD_BF16, { NL, 3 * qd }); + m.b_cattn = decl_b(b, nm.f("codec.attn"), RAD_BF16, { NL, qd }); + m.b_co = decl_b(b, nm.f("codec.o"), RAD_BF16, { NL, kLat }); + m.b_cgu = decl_b(b, nm.f("codec.gu"), RAD_BF16, { NL, 2 * kCtFf }); + m.b_cff = decl_b(b, nm.f("codec.ff"), RAD_BF16, { NL, kCtFf }); + { + CtSet B; + B.x = m.b_cx; B.h = m.b_ch; B.qkv = m.b_cqkv; B.attn = m.b_cattn; B.o = m.b_co; + B.gu = m.b_cgu; B.ff = m.b_cff; + RAD_ARCH_TRY(declare_ct(b, nm, m.ct, "codec", pt, (int)kCtLayers, NL, kAttnWin, 1, B, + m.b_ccu[0], 0)); + } + /* The final norm over only the frames the convolutions read: the last nc. */ + m.w_cn = wcopy(b, nm.f("codec.norm.weight"), nm.ckpt("%s.norm.weight", pt), RAD_F32, { kLat }, + kGrpCodec); + m.b_ux[0] = decl_b(b, nm.f("codec.ux0"), RAD_BF16, { NC, kLat }); + m.op_cn = norm_op(b, NC, kLat, kCtEps, 0.0, m.w_cn, { m.b_cx }, m.b_ux[0]); + + /* ---- two 2x upsamplings, each a transposed conv of kernel 2 and a ConvNeXt block */ + m.b_ua = decl_b(b, nm.f("codec.ua"), RAD_BF16, { 4 * NC, kLat }); + m.b_ub = decl_b(b, nm.f("codec.ub"), RAD_BF16, { 4 * NC, kLat }); + m.b_uh = decl_b(b, nm.f("codec.uh"), RAD_BF16, { 4 * NC, 4 * kLat }); + m.b_ug2 = decl_b(b, nm.f("codec.ug"), RAD_BF16, { 4 * NC, 4 * kLat }); + for (int i = 0; i < 2; ++i) { + Upsample& U = m.up[i]; + const int64_t rin = NC << i, rout = NC << (i + 1); + const char* us = nm.ckpt("%s.upsample.%d", q, i); + auto w = [&](const char* dn, const char* s, uint32_t dt, + std::initializer_list sh) { + return wcopy(b, nm.f("codec.up%d.%s", i, dn), nm.ckpt("%s.%s", us, s), dt, sh, + kGrpCodec); + }; + U.w_t = w("t.weight", "0.conv.weight", RAD_BF16, { kLat, kLat, 2 }); + U.b_t = w("t.bias", "0.conv.bias", RAD_BF16, { kLat }); + U.w_dw = w("dw.weight", "1.dwconv.conv.weight", RAD_BF16, { kLat, 1, 7 }); + U.b_dw = w("dw.bias", "1.dwconv.conv.bias", RAD_BF16, { kLat }); + U.w_ln = w("ln.weight", "1.norm.weight", RAD_F32, { kLat }); + U.b_ln = w("ln.bias", "1.norm.bias", RAD_F32, { kLat }); + U.w_p1 = w("p1.weight", "1.pwconv1.weight", RAD_BF16, { 4 * kLat, kLat }); + U.b_p1 = w("p1.bias", "1.pwconv1.bias", RAD_BF16, { 4 * kLat }); + U.w_p2 = w("p2.weight", "1.pwconv2.weight", RAD_BF16, { kLat, 4 * kLat }); + U.b_p2 = w("p2.bias", "1.pwconv2.bias", RAD_BF16, { kLat }); + U.w_g = w("gamma", "1.gamma", RAD_F32, { kLat }); + m.b_ux[i + 1] = decl_b(b, nm.f("codec.ux%d", i + 1), RAD_BF16, { rout, kLat }); + U.op_t = rw(b, RAD_OP(b, "conv_t1d", + RAD_PARAMS(RAD_RANGE("M", 1, rin), RAD_INT("cin", kLat), + RAD_INT("cout", kLat), RAD_INT("stride", 2), + RAD_STR("dtype", "bf16"), RAD_INT("pad", 0), + RAD_INT("k", 2)), + RAD_WEIGHTS(U.w_t, U.b_t)), + { m.b_ux[i], m.b_ccu[1 + i] }, { m.b_ux[i + 1] }); + U.op_dw = rw(b, RAD_OP(b, "conv1d_dw", + RAD_PARAMS(RAD_RANGE("M", 1, rout), RAD_INT("n", kLat), + RAD_INT("k", 7), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(U.w_dw, U.b_dw)), + { m.b_ux[i + 1], m.b_ccu[2 + i] }, { m.b_ua }); + U.op_ln = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, rout), RAD_INT("n", kLat), + RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(U.w_ln, U.b_ln)), + { m.b_ua }, { m.b_ub }); + U.op_p1 = gemm_bias_op(b, rout, 4 * kLat, kLat, U.w_p1, U.b_p1, m.b_ub, m.b_uh); + U.op_gelu = rows_op(b, "gelu", rout, 4 * kLat, { m.b_uh }, { m.b_ug2 }); + U.op_p2 = gemm_bias_op(b, rout, kLat, 4 * kLat, U.w_p2, U.b_p2, m.b_ug2, m.b_ua); + U.op_g = mulw_op(b, rout, kLat, U.w_g, m.b_ua, m.b_ua); + U.op_add = add_op(b, rout, kLat, m.b_ux[i + 1], m.b_ua, m.b_ux[i + 1]); + if (!U.w_t || !U.b_t || !U.w_dw || !U.b_dw || !U.w_ln || !U.b_ln || !U.w_p1 || !U.b_p1 || + !U.w_p2 || !U.b_p2 || !U.w_g || !U.op_t || !U.op_dw || !U.op_ln || !U.op_p1 || + !U.op_gelu || !U.op_p2 || !U.op_g || !U.op_add) + return RAD_E_INVAL; + } + + /* ---- the decoder: a conv into 1536 channels, four upsampling blocks, the output conv */ + const int64_t R0 = 4 * NC; /* rows at 4 a frame */ + int64_t rows[5], ch[5]; + rows[0] = R0; + ch[0] = kDec; + for (int i = 0; i < 4; ++i) { + rows[i + 1] = rows[i] * m.v_ups[i]; + ch[i + 1] = kDec >> (i + 1); + } + for (int s = 0; s < 5; ++s) { + m.b_vs[s] = decl_b(b, nm.f("codec.s%d", s), RAD_BF16, { rows[s], ch[s] }); + m.b_vt[s] = decl_b(b, nm.f("codec.t%d", s), RAD_BF16, { rows[s], ch[s] }); + if (s > 0) { + m.b_va[s] = decl_b(b, nm.f("codec.a%d", s), RAD_BF16, { rows[s], ch[s] }); + m.b_vb[s] = decl_b(b, nm.f("codec.b%d", s), RAD_BF16, { rows[s], ch[s] }); + } + } + const char* dd = "codec.decoder.model"; + RAD_ARCH_TRY(vconv(b, nm, m.dec0, "codec.dec0", nm.ckpt("%s.0.conv", dd), kLat, kDec, 7, 1, + R0, m.b_ux[2], 0, m.b_vs[0], m.b_ccu[3])); + static const int64_t kDil[3] = { 1, 3, 9 }; + for (int i = 0; i < 4; ++i) { + VBlock& B = m.vb[i]; + const int64_t ci = ch[i], co = ch[i + 1], s = m.v_ups[i]; + const char* bn = nm.f("codec.b%d", i); + const char* bs = nm.ckpt("%s.%d.block", dd, i + 1); + B.a = valpha(b, nm, nm.f("%s.snake", bn), nm.ckpt("%s.0", bs), ci); + B.op_s = snake_op(b, rows[i], ci, B.a, m.b_vs[i], m.b_vt[i]); + /* The transposed conv's weight norm is per input channel: its weight is [in, out, k]. */ + const char* wn = nm.f("%s.t.weight", bn); + RAD_ARCH_TRY(map_wnorm(b, wn, nm.ckpt("%s.1.conv.parametrizations.weight.original0", bs), + nm.ckpt("%s.1.conv.parametrizations.weight.original1", bs))); + B.wt = decl_w(b, wn, RAD_BF16, { ci, co, 2 * s }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + B.bt = wcopy(b, nm.f("%s.t.bias", bn), nm.ckpt("%s.1.conv.bias", bs), RAD_BF16, { co }, + kGrpCodec); + B.op_t = rw(b, RAD_OP(b, "conv_t1d", + RAD_PARAMS(RAD_RANGE("M", 1, rows[i]), RAD_INT("cin", ci), + RAD_INT("cout", co), RAD_INT("stride", s), + RAD_STR("dtype", "bf16"), RAD_INT("pad", 0), + RAD_INT("k", 2 * s)), + RAD_WEIGHTS(B.wt, B.bt)), + { m.b_vt[i], m.b_ccu[3 + i] }, { m.b_vs[i + 1] }); + if (!B.a || !B.wt || !B.bt || !B.op_t || !B.op_s) return RAD_E_INVAL; + /* Three residual units (dilations 1, 3, 9): x + conv2(snake2(conv1(snake1(x)))), x the + * stage buffer, written back in place by conv2's residual. */ + for (int r = 0; r < 3; ++r) { + VRes& U = B.res[r]; + const char* un = nm.f("%s.res%d", bn, r); + const char* ub = nm.ckpt("%s.%d.block", bs, r + 2); + const int64_t R = rows[i + 1]; + U.a1 = valpha(b, nm, nm.f("%s.act1", un), nm.ckpt("%s.0", ub), co); + U.a2 = valpha(b, nm, nm.f("%s.act2", un), nm.ckpt("%s.2", ub), co); + U.op_s1 = snake_op(b, R, co, U.a1, m.b_vs[i + 1], m.b_vt[i + 1]); + RAD_ARCH_TRY(vconv(b, nm, U.c1, nm.f("%s.conv1", un), nm.ckpt("%s.1.conv", ub), co, co, + 7, kDil[r], R, m.b_vt[i + 1], 0, m.b_va[i + 1], m.b_ccu[4 + i])); + U.op_s2 = snake_op(b, R, co, U.a2, m.b_va[i + 1], m.b_vb[i + 1]); + RAD_ARCH_TRY(vconv(b, nm, U.c2, nm.f("%s.conv2", un), nm.ckpt("%s.3.conv", ub), co, co, + 1, 1, R, m.b_vb[i + 1], m.b_vs[i + 1], m.b_vs[i + 1], + m.b_ccu[4 + i])); + if (!U.a1 || !U.a2 || !U.op_s1 || !U.op_s2) return RAD_E_INVAL; + } + } + m.w_fa = valpha(b, nm, "codec.snake_out", nm.ckpt("%s.5", dd), ch[4]); + m.op_fs = snake_op(b, rows[4], ch[4], m.w_fa, m.b_vs[4], m.b_vt[4]); + m.b_vout = decl_b(b, nm.f("codec.out"), RAD_BF16, { rows[4], 1 }); + RAD_ARCH_TRY(vconv(b, nm, m.fin, "codec.conv_out", nm.ckpt("%s.6.conv", dd), ch[4], 1, 7, 1, + rows[4], m.b_vt[4], 0, m.b_vout, m.b_ccu[7], "tanh")); + m.b_audio = decl_b(b, nm.f("codec.audio"), RAD_F32, { kVocChunk * kSamplesPerFrame, 1 }, + RAD_BUF_PERSIST); + m.op_fcast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, kVocChunk * kSamplesPerFrame), + RAD_INT("n", 1), RAD_STR("from", "bf16"), + RAD_STR("to", "f32")), + RAD_NOWEIGHTS), + { m.b_vout }, { m.b_audio }); + return m.w_cn && m.op_cn && m.w_fa && m.op_fs && m.op_fcast && m.op_cnst ? RAD_OK + : RAD_E_INVAL; +} + +/* ================================================================== the codec's encoder */ +/* Voice cloning: the PROMPT pass's reference clips to the codec's ten codes a frame + * (modded_dac.py's Encoder, then rvq.py's DownsampleResidualVectorQuantize), every clip at once, + * each a sequence of the pass's bounds, which are in samples and read at each rate through cu_div. + * In bf16, as fish-speech's server encodes a reference, every quantiser step in f32 (vq_encode) + * into the prompt rows' code plane at the clip's rows. + * + * Declared first: the clips are encoded before anything else of the pass runs, so the encoder's + * buffers are dead by the backbone's, and only the code plane, which the tower reads, lives on. */ +static int declare_encoder(RadBuilder* b, Model& m) { + Names& nm = m.nm; + const int64_t L = kMaxRefSamples, D = kLat, qd = kCtHeads * kCtHeadDim; + const char* es = "codec.encoder.block"; + static const int64_t kDil[3] = { 1, 3, 9 }; + + m.b_ein = decl_b(b, nm.f("enc.in"), RAD_BF16, { L, 1 }); + m.op_ecast = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, L), RAD_INT("n", 1), + RAD_STR("from", "f32"), RAD_STR("to", "bf16")), + RAD_NOWEIGHTS), + {}, { m.b_ein }); + int64_t rows = L, ch = 64, rate = 1; + for (int s = 0; s < 4; ++s) { + m.b_ex[s] = decl_b(b, nm.f("enc.x%d", s), RAD_BF16, { rows, ch }); + m.b_et[s] = decl_b(b, nm.f("enc.t%d", s), RAD_BF16, { rows, ch }); + m.b_ea[s] = decl_b(b, nm.f("enc.a%d", s), RAD_BF16, { rows, ch }); + rows /= kEncStride[s]; + ch *= 2; + } + const int64_t R4 = rows, R5 = R4 / 2, F = R5 / 2; /* 512, 1024 and 2048 samples a row */ + m.b_ex4 = decl_b(b, nm.f("enc.x4"), RAD_BF16, { R4, D }); + m.b_et4 = decl_b(b, nm.f("enc.t4"), RAD_BF16, { R4, D }); + m.b_ea4 = decl_b(b, nm.f("enc.a4"), RAD_BF16, { R4, D }); + RAD_ARCH_TRY(econv(b, nm, m.e0, "codec.enc.0", nm.ckpt("%s.0.conv", es), 1, 64, 7, 1, 1, 1, L, + m.b_ein, 0, m.b_ex[0])); + if (!m.op_ecast) return RAD_E_INVAL; + + /* ---- four blocks: three residual units (dilations 1, 3, 9: x + conv2(snake2(conv1(snake1 + * (x))))), a snake and the strided conv into the next block's rows */ + rows = L; + ch = 64; + for (int s = 0; s < 4; ++s) { + EBlock& B = m.eb[s]; + const char* bn = nm.f("codec.enc.b%d", s); + const char* bs = nm.ckpt("%s.%d.block", es, s + 1); + const rad_buf X = m.b_ex[s], T = m.b_et[s], A = m.b_ea[s]; + for (int r = 0; r < 3; ++r) { + VRes& U = B.res[r]; + const char* un = nm.f("%s.res%d", bn, r); + const char* ub = nm.ckpt("%s.%d.block", bs, r); + U.a1 = valpha(b, nm, nm.f("%s.act1", un), nm.ckpt("%s.0", ub), ch); + U.a2 = valpha(b, nm, nm.f("%s.act2", un), nm.ckpt("%s.2", ub), ch); + U.op_s1 = snake_op(b, rows, ch, U.a1, X, T); + RAD_ARCH_TRY(econv(b, nm, U.c1, nm.f("%s.conv1", un), nm.ckpt("%s.1.conv", ub), ch, ch, + 7, kDil[r], 1, rate, rows, T, 0, A)); + U.op_s2 = snake_op(b, rows, ch, U.a2, A, T); + RAD_ARCH_TRY(econv(b, nm, U.c2, nm.f("%s.conv2", un), nm.ckpt("%s.3.conv", ub), ch, ch, + 1, 1, 1, rate, rows, T, X, X)); + if (!U.a1 || !U.a2 || !U.op_s1 || !U.op_s2) return RAD_E_INVAL; + } + B.a = valpha(b, nm, nm.f("%s.snake", bn), nm.ckpt("%s.3", bs), ch); + B.op_s = snake_op(b, rows, ch, B.a, X, T); + if (!B.a || !B.op_s) return RAD_E_INVAL; + const int64_t st = kEncStride[s]; + RAD_ARCH_TRY(econv(b, nm, B.down, nm.f("%s.down", bn), nm.ckpt("%s.4.conv", bs), ch, + 2 * ch, 2 * st, 1, st, rate, rows, T, 0, + s < 3 ? m.b_ex[s + 1] : m.b_ex4)); + rows /= st; + ch *= 2; + rate *= st; + } + + /* ---- the last block's transformer (window 512 rows) and its norm, a snake, a conv */ + m.ecs.x = m.b_ex4; + m.ecs.h = decl_b(b, nm.f("enc.h"), RAD_BF16, { R4, D }); + m.ecs.qkv = decl_b(b, nm.f("enc.qkv"), RAD_BF16, { R4, 3 * qd }); + m.ecs.attn = decl_b(b, nm.f("enc.attn"), RAD_BF16, { R4, qd }); + m.ecs.o = decl_b(b, nm.f("enc.o"), RAD_BF16, { R4, D }); + m.ecs.gu = decl_b(b, nm.f("enc.gu"), RAD_BF16, { R4, 2 * kCtFf }); + m.ecs.ff = decl_b(b, nm.f("enc.ff"), RAD_BF16, { R4, kCtFf }); + m.b_epos = decl_b(b, nm.f("enc.pos"), RAD_I32, { R4 }); + m.op_epos = iota_op(b, R4, 0, 1, m.b_epos); + const char* tsrc = nm.ckpt("%s.4.block.5", es); + RAD_ARCH_TRY(declare_ct(b, nm, m.et, "codec.enc.t", tsrc, (int)kEncLayers, R4, kEncWin, 512, + m.ecs, 0, m.b_epos)); + m.w_etn = wcopy(b, nm.f("codec.enc.t.norm.weight"), nm.ckpt("%s.norm.weight", tsrc), RAD_F32, + { D }, kGrpCodec); + m.op_etn = norm_op(b, R4, D, kCtEps, 0.0, m.w_etn, { m.b_ex4 }, m.b_et4); + m.w_e5 = valpha(b, nm, "codec.enc.snake_out", nm.ckpt("%s.5", es), D); + m.op_e5 = snake_op(b, R4, D, m.w_e5, m.b_et4, m.b_ea4); + RAD_ARCH_TRY(econv(b, nm, m.e6, "codec.enc.conv_out", nm.ckpt("%s.6.conv", es), D, D, 3, 1, 1, + 512, R4, m.b_ea4, 0, m.b_ex4)); + if (!m.op_epos || !m.w_etn || !m.op_etn || !m.w_e5 || !m.op_e5) return RAD_E_INVAL; + + /* ---- the quantiser's two 2x downsamplings: a strided conv (plain weights), a ConvNeXt + * block (causal depthwise conv, layer norm, GELU feed-forward, layer scale, residual) */ + m.b_ed1 = decl_b(b, nm.f("enc.d1"), RAD_BF16, { R5, D }); + m.b_ez = decl_b(b, nm.f("enc.z"), RAD_BF16, { F, D }); + m.b_dua = decl_b(b, nm.f("enc.dua"), RAD_BF16, { R5, D }); + m.b_dub = decl_b(b, nm.f("enc.dub"), RAD_BF16, { R5, D }); + m.b_duh = decl_b(b, nm.f("enc.duh"), RAD_BF16, { R5, 4 * D }); + m.b_dug = decl_b(b, nm.f("enc.dug"), RAD_BF16, { R5, 4 * D }); + for (int i = 0; i < 2; ++i) { + EDown& E = m.ed[i]; + const int64_t rin = i ? R5 : R4, rout = rin / 2, rr = i ? 1024 : 512; + const rad_buf xin = i ? m.b_ed1 : m.b_ex4, y = i ? m.b_ez : m.b_ed1; + const char* ds = nm.ckpt("codec.quantizer.downsample.%d", i); + auto w = [&](const char* dn, const char* sr, uint32_t dt, + std::initializer_list sh) { + return wcopy(b, nm.f("codec.enc.down%d.%s", i, dn), nm.ckpt("%s.%s", ds, sr), dt, sh, + kGrpCodec); + }; + E.c.w = w("weight", "0.conv.weight", RAD_BF16, { D, D, 2 }); + E.c.b = w("bias", "0.conv.bias", RAD_BF16, { D }); + E.w_dw = w("dw.weight", "1.dwconv.conv.weight", RAD_BF16, { D, 1, 7 }); + E.b_dw = w("dw.bias", "1.dwconv.conv.bias", RAD_BF16, { D }); + E.w_ln = w("ln.weight", "1.norm.weight", RAD_F32, { D }); + E.b_ln = w("ln.bias", "1.norm.bias", RAD_F32, { D }); + E.w_p1 = w("p1.weight", "1.pwconv1.weight", RAD_BF16, { 4 * D, D }); + E.b_p1 = w("p1.bias", "1.pwconv1.bias", RAD_BF16, { 4 * D }); + E.w_p2 = w("p2.weight", "1.pwconv2.weight", RAD_BF16, { D, 4 * D }); + E.b_p2 = w("p2.bias", "1.pwconv2.bias", RAD_BF16, { D }); + E.w_g = w("gamma", "1.gamma", RAD_F32, { D }); + if (!E.c.w || !E.c.b || !E.w_dw || !E.b_dw || !E.w_ln || !E.b_ln || !E.w_p1 || !E.b_p1 || + !E.w_p2 || !E.b_p2 || !E.w_g) + return RAD_E_INVAL; + E.c.op = econv_op(b, rin, D, D, 2, 1, 2, rr, E.c.w, E.c.b, xin, 0, y); + E.op_dw = rw(b, RAD_OP(b, "conv1d_dw", + RAD_PARAMS(RAD_RANGE("M", 1, rout), RAD_INT("n", D), RAD_INT("k", 7), + RAD_INT("cu_div", 2 * rr), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(E.w_dw, E.b_dw)), + { y }, { m.b_dua }); + E.op_ln = rw(b, RAD_OP(b, "layernorm", + RAD_PARAMS(RAD_RANGE("M", 1, rout), RAD_INT("n", D), + RAD_F64("eps", 1e-6), RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(E.w_ln, E.b_ln)), + { m.b_dua }, { m.b_dub }); + E.op_p1 = gemm_bias_op(b, rout, 4 * D, D, E.w_p1, E.b_p1, m.b_dub, m.b_duh); + E.op_gelu = rows_op(b, "gelu", rout, 4 * D, { m.b_duh }, { m.b_dug }); + E.op_p2 = gemm_bias_op(b, rout, D, 4 * D, E.w_p2, E.b_p2, m.b_dug, m.b_dua); + E.op_g = mulw_op(b, rout, D, E.w_g, m.b_dua, m.b_dua); + E.op_add = add_op(b, rout, D, y, m.b_dua, y); + if (!E.c.op || !E.op_dw || !E.op_ln || !E.op_p1 || !E.op_gelu || !E.op_p2 || !E.op_g || + !E.op_add) + return RAD_E_INVAL; + } + + /* ---- the pre-quantiser transformer (8 layers, window 128 frames) and its norm, over the + * encoder's working set */ + const char* psrc = "codec.quantizer.pre_module"; + CtSet P = m.ecs; + P.x = m.b_ez; + RAD_ARCH_TRY(declare_ct(b, nm, m.pq, "codec.enc.pre", nm.ckpt("%s", psrc), (int)kCtLayers, F, + kAttnWin, kSamplesPerFrame, P, 0, m.b_epos)); + m.w_pqn = wcopy(b, nm.f("codec.enc.pre.norm.weight"), nm.ckpt("%s.norm.weight", psrc), + RAD_F32, { D }, kGrpCodec); + m.op_pqn = norm_op(b, F, D, kCtEps, 0.0, m.w_pqn, { m.b_ez }, m.b_ez); + if (!m.w_pqn || !m.op_pqn) return RAD_E_INVAL; + + /* ---- the prompt rows' codes: -2 for code 0 and -1 for the others at every row, then each + * clip's frames at their rows, the semantic step first and the nine residual ones after it, + * every step quantising what the last left of z */ + m.b_pc = decl_b(b, nm.f("enc.codes"), RAD_I32, { kCodes, kPcW }); + m.op_pc0 = iota_op(b, kPcW, -2, 0, m.b_pc); + m.op_pc1 = iota_op(b, (kCodes - 1) * kPcW, -1, 0, m.b_pc); + for (int k = 0; k < kCodes; ++k) { + EQuant& Q = m.eq[k]; + const char* qs = k == 0 ? nm.ckpt("codec.quantizer.semantic_quantizer.quantizers.0") + : nm.ckpt("codec.quantizer.quantizer.quantizers.%d", k - 1); + const int64_t bins = k == 0 ? kVocab : kResVocab; + const char* iw = nm.f("codec.enc.vq%d.in.weight", k); + const char* ow = nm.f("codec.enc.vq%d.out.weight", k); + RAD_ARCH_TRY(map_wnorm(b, iw, nm.ckpt("%s.in_proj.weight_g", qs), + nm.ckpt("%s.in_proj.weight_v", qs))); + RAD_ARCH_TRY(map_wnorm(b, ow, nm.ckpt("%s.out_proj.weight_g", qs), + nm.ckpt("%s.out_proj.weight_v", qs))); + Q.in_w = decl_w(b, iw, RAD_F32, { kCbDim, D, 1 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + Q.in_b = wcopy(b, nm.f("codec.enc.vq%d.in.bias", k), nm.ckpt("%s.in_proj.bias", qs), + RAD_F32, { kCbDim }, kGrpCodec); + Q.cb = wcopy(b, nm.f("codec.enc.vq%d.codebook", k), nm.ckpt("%s.codebook.weight", qs), + RAD_F32, { bins, kCbDim }, kGrpCodec); + Q.out_w = decl_w(b, ow, RAD_F32, { D, kCbDim, 1 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, + grp_layer(kGrpCodec)); + Q.out_b = wcopy(b, nm.f("codec.enc.vq%d.out.bias", k), nm.ckpt("%s.out_proj.bias", qs), + RAD_F32, { D }, kGrpCodec); + if (!Q.in_w || !Q.in_b || !Q.cb || !Q.out_w || !Q.out_b) return RAD_E_INVAL; + Q.op = rw(b, RAD_OP(b, "vq_encode", + RAD_PARAMS(RAD_RANGE("M", 1, F), RAD_INT("n", D), + RAD_INT("dim", kCbDim), RAD_INT("bins", bins), + RAD_STR("dtype", "bf16")), + RAD_WEIGHTS(Q.in_w, Q.in_b, Q.cb, Q.out_w, Q.out_b)), + { m.b_ez }, { m.b_ez, m.b_pc }); + if (!Q.op) return RAD_E_INVAL; + } + return m.op_pc0 && m.op_pc1 ? RAD_OK : RAD_E_INVAL; +} + +/* ================================================================== declare */ +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(check_format(meta)); + if (ctx->world_size > 2) { + fprintf(stderr, "radiance: fishomni: drama-3 is served on one or two cards (--tp 1 or 2): " + "its two KV heads and the tower's split stop at two ranks\n"); + return RAD_E_UNSUPPORTED; + } + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + m.lanes = std::min(kMaxLanes, std::max(1, ctx->max_seqs)); + if (m.g.max_tok < kVocContext + kVocChunk) { + fprintf(stderr, "radiance: fishomni: a pass carries %lld rows; a codec chunk needs %lld\n", + (long long)m.g.max_tok, (long long)(kVocContext + kVocChunk)); + return RAD_E_INVAL; + } + + /* Declared in the order the passes issue them where it matters for liveness: the codec's + * encoder first (PROMPT runs it before everything else when the request has references), the + * backbone, then the frame head, the tower, the frame's tail, and the codec. The rows' code + * plane the encoder leaves is named by the tower's ops too, so it lives across the backbone. + * FRAME runs the head and the tower before the backbone; the buffers that cross that seam + * (`x`, `h`, the codes, the plane) are named by the ops on both sides, so their live ranges + * span it. */ + RAD_ARCH_TRY(declare_encoder(b, m)); + RAD_ARCH_TRY(declare_trunk(b, meta, ctx, m)); + RAD_ARCH_TRY(declare_frame_head(b, m)); + RAD_ARCH_TRY(declare_tower(b, meta, m)); + RAD_ARCH_TRY(declare_frame_tail(b, m)); + RAD_ARCH_TRY(declare_codec(b, m)); + + if (!ctx->shape_probe) { + RadAudioGenDecl d{}; + d.name = "drama-3"; + d.tmpl = nullptr; + d.tmpl_plain = kPlain; + d.prompt_whole = 1; + d.first_frame = 0; + d.max_prompt = kMaxPrompt; + d.max_frames = kMaxFrames; + d.frame_rate_num = kSampleRate; + d.frame_rate_den = kSamplesPerFrame; + d.lat_num = 1; + d.lat_den = 1; + d.samples_per_latent = kSamplesPerFrame; + d.sample_rate = kSampleRate; + d.channels = 1; + d.default_cfg = 1.0; + d.max_lanes = m.lanes; + d.status = m.b_status; + d.audio_out = m.b_audio; + d.voc_chunk = kVocChunk; + d.voc_context = kVocContext; + d.branches = 1; + d.input_special = 1; + d.tmpl_ref = kRefPlain; + d.ref_item = kRefItem; + d.ref_rate = kSampleRate; + d.ref_hop = kSamplesPerFrame; + d.ref_max_samples = kMaxRefSamples; + d.ref_max = kMaxRefs; + RAD_ARCH_TRY(rad_declare_audio_generator(b, &d)); + } + rad_note(b, "rank %d/%d: drama-3 -- backbone %lld layers (%lld heads, %lld KV a rank; %lld " + "experts of %lld a rank, %lld a token), tower %d layers at KV layers %lld..%lld " + "(%lld heads a rank, ffn %lld), codec transformer %d layers, %lld lanes", + m.g.rank, m.g.world, (long long)m.n_main, (long long)m.g.n_head, + (long long)m.g.n_head_kv, (long long)m.moecfg.n_expert, (long long)m.moecfg.n_ff_exp, + (long long)m.moecfg.top_k, kTower, (long long)m.n_main, + (long long)(m.n_main + kTower - 1), (long long)m.gt.n_head, (long long)m.gt.n_ff, + (int)kCtLayers, (long long)m.lanes); + rad_note(b, "sampling: temperature %.2f, top-p %.2f for every draw, top-k %lld for the main " + "token and %lld for each head; a semantic first draw among the lane's last %lld " + "picks is redrawn at temperature %.2f, top-p %.2f, top-k %lld", + kTemp, kTopP, (long long)kMainTopK, (long long)kHeadTopK, (long long)kRasWin, + kRasTemp, kRasTopP, (long long)kRasTopK); + return RAD_OK; +} + +/* ================================================================== step */ +/* A codec transformer (declare_ct) over R rows of B.x. */ +static void step_ct(RadCtx* c, const std::vector& ls, int64_t R, const CtSet& B, + RadOperand pos, RadOperand cu) { + const int64_t qd = kCtHeads * kCtHeadDim; + for (const CodecLayer& Ly : ls) { + RAD_ISSUE_N(c, Ly.op_n1, R, brows(B.x, R), RAD_W(Ly.w_n1), brows(B.h, R)); + RAD_ISSUE_N(c, Ly.op_qkv, R, brows(B.h, R), RAD_W(Ly.w_qkv), brows(B.qkv, R)); + RAD_ISSUE_N(c, Ly.op_rope, R, brows(B.qkv, R), pos); + RAD_ISSUE_N(c, Ly.op_attn, R, bcol(B.qkv, 0, qd, R), bcol(B.qkv, qd, qd, R), + bcol(B.qkv, 2 * qd, qd, R), cu, brows(B.attn, R)); + RAD_ISSUE_N(c, Ly.op_o, R, brows(B.attn, R), RAD_W(Ly.w_o), brows(B.o, R)); + RAD_ISSUE_N(c, Ly.op_ls1, R, brows(B.o, R), RAD_W(Ly.w_ls1), brows(B.o, R)); + RAD_ISSUE_N(c, Ly.op_add1, R, brows(B.x, R), brows(B.o, R), brows(B.x, R)); + RAD_ISSUE_N(c, Ly.op_n2, R, brows(B.x, R), RAD_W(Ly.w_n2), brows(B.h, R)); + RAD_ISSUE_N(c, Ly.op_gu, R, brows(B.h, R), RAD_W(Ly.w_gu), brows(B.gu, R)); + RAD_ISSUE_N(c, Ly.op_act, R, brows(B.gu, R), brows(B.ff, R)); + RAD_ISSUE_N(c, Ly.op_down, R, brows(B.ff, R), RAD_W(Ly.w_down), brows(B.o, R)); + RAD_ISSUE_N(c, Ly.op_ls2, R, brows(B.o, R), RAD_W(Ly.w_ls2), brows(B.o, R)); + RAD_ISSUE_N(c, Ly.op_add2, R, brows(B.x, R), brows(B.o, R), brows(B.x, R)); + } +} + +/* A PROMPT pass's clips through the encoder (declare_encoder), their frames' codes into the + * prompt rows' code plane at the rows that name them. */ +static void step_encode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t L = A->ref_samples, D = kLat; + const RadOperand cu = praw(A->ref_cu, RAD_I32, A->n_ref + 1); + auto conv = [&](const VConv& v, rad_buf x, rad_buf res, rad_buf y, int64_t R, int64_t Ry) { + RAD_ISSUE_N(c, v.op, R, brows(x, R), RAD_W(v.w), cu, res ? brows(res, R) : RAD_NONE, + brows(y, Ry), RAD_W(v.b)); + }; + RAD_ISSUE_N(c, m.op_ecast, L, praw(A->ref_audio, RAD_F32, L), brows(m.b_ein, L)); + conv(m.e0, m.b_ein, 0, m.b_ex[0], L, L); + int64_t R = L; + for (int s = 0; s < 4; ++s) { + const EBlock& B = m.eb[s]; + const rad_buf X = m.b_ex[s], T = m.b_et[s], Ab = m.b_ea[s]; + for (const VRes& U : B.res) { + RAD_ISSUE_N(c, U.op_s1, R, brows(X, R), RAD_W(U.a1), brows(T, R), RAD_NONE); + conv(U.c1, T, 0, Ab, R, R); + RAD_ISSUE_N(c, U.op_s2, R, brows(Ab, R), RAD_W(U.a2), brows(T, R), RAD_NONE); + conv(U.c2, T, X, X, R, R); + } + RAD_ISSUE_N(c, B.op_s, R, brows(X, R), RAD_W(B.a), brows(T, R), RAD_NONE); + conv(B.down, T, 0, s < 3 ? m.b_ex[s + 1] : m.b_ex4, R, R / kEncStride[s]); + R /= kEncStride[s]; + } + /* The last block's transformer, at the clips' rows of 512 samples; the snake and the conv. */ + RAD_ISSUE_N(c, m.op_epos, R, brows(m.b_epos, R)); + step_ct(c, m.et, R, m.ecs, brows(m.b_epos, R), cu); + RAD_ISSUE_N(c, m.op_etn, R, brows(m.b_ex4, R), RAD_W(m.w_etn), brows(m.b_et4, R)); + RAD_ISSUE_N(c, m.op_e5, R, brows(m.b_et4, R), RAD_W(m.w_e5), brows(m.b_ea4, R), RAD_NONE); + conv(m.e6, m.b_ea4, 0, m.b_ex4, R, R); + /* The quantiser's two downsamplings. */ + for (int i = 0; i < 2; ++i) { + const EDown& E = m.ed[i]; + const rad_buf xin = i ? m.b_ed1 : m.b_ex4, y = i ? m.b_ez : m.b_ed1; + const int64_t ro = R / 2; + conv(E.c, xin, 0, y, R, ro); + RAD_ISSUE_N(c, E.op_dw, ro, brows(y, ro), RAD_W(E.w_dw), cu, brows(m.b_dua, ro), + RAD_W(E.b_dw)); + RAD_ISSUE_N(c, E.op_ln, ro, brows(m.b_dua, ro), RAD_W(E.w_ln), RAD_W(E.b_ln), + brows(m.b_dub, ro)); + RAD_ISSUE_N(c, E.op_p1, ro, brows(m.b_dub, ro), RAD_W(E.w_p1), RAD_W(E.b_p1), RAD_NONE, + brows(m.b_duh, ro)); + RAD_ISSUE_N(c, E.op_gelu, ro, brows(m.b_duh, ro), brows(m.b_dug, ro)); + RAD_ISSUE_N(c, E.op_p2, ro, brows(m.b_dug, ro), RAD_W(E.w_p2), RAD_W(E.b_p2), RAD_NONE, + brows(m.b_dua, ro)); + RAD_ISSUE_N(c, E.op_g, ro, brows(m.b_dua, ro), RAD_W(E.w_g), brows(m.b_dua, ro)); + RAD_ISSUE_N(c, E.op_add, ro, brows(y, ro), brows(m.b_dua, ro), brows(y, ro)); + R = ro; + } + /* The pre-quantiser transformer and its norm at the frames: z. */ + const int64_t F = R; + CtSet P = m.ecs; + P.x = m.b_ez; + RAD_ISSUE_N(c, m.op_epos, F, brows(m.b_epos, F)); + step_ct(c, m.pq, F, P, brows(m.b_epos, F), cu); + RAD_ISSUE_N(c, m.op_pqn, F, brows(m.b_ez, F), RAD_W(m.w_pqn), brows(m.b_ez, F)); + + /* The rows' codes: a token's everywhere, then each run of rows naming consecutive frames + * quantised step by step into its columns. */ + RAD_ISSUE_N(c, m.op_pc0, kPcW, brow_slice(m.b_pc, 0, 1, kPcW)); + RAD_ISSUE_N(c, m.op_pc1, (kCodes - 1) * kPcW, brow_slice(m.b_pc, 1, kCodes - 1, kPcW)); + const int64_t T = batch->n_tok; + for (int64_t t = 0; t < T;) { + const int32_t f = A->ref_frame_h[t]; + if (f < 0 || f >= F) { ++t; continue; } + int64_t n = 1; + while (t + n < T && A->ref_frame_h[t + n] == f + n && f + n < F) ++n; + for (int k = 0; k < kCodes; ++k) { + const EQuant& Q = m.eq[k]; + RAD_ISSUE_N(c, Q.op, n, brow_slice(m.b_ez, f, n, D), RAD_W(Q.in_w), RAD_W(Q.in_b), + RAD_W(Q.cb), RAD_W(Q.out_w), RAD_W(Q.out_b), + bcol_at(m.b_pc, k, kPcW, t, n, 1)); + } + t += n; + } +} + +static void step_trunk(RadCtx* c, const RadBatch* batch, const Model& m) { + const int64_t T = batch->n_tok; + if (m.op_rope_cs && T <= qk_fuse_rows(m.g) && !rope_mixed(batch)) + RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs)); + for (const Layer& l : m.layers) { + if (l.full) l.attn.step(c, batch); + else l.gdn.step(c, batch); + l.mlp.step(c, batch); + } + RAD_ISSUE_N(c, m.op_final_norm, T, brows(m.b_x, T), RAD_W(m.w_out_norm), brows(m.a_h.x, T)); +} + +/* Where the tower runs: its rows' positions and cache slots, the sequences' block tables, + * context lengths and bounds, and its first layer's hidden state. FRAME also embeds codes. */ +struct TowerAt { + int64_t R = 0; + int64_t max_q = 0; + RadOperand pos{}, slot{}, bt{}, used{}, cu{}; + rad_buf h0 = 0; + bool frame = false; + RadOperand seed{}, fidx{}; + bool labels = false; /* PROMPT with references: labels off the rows' code plane */ +}; + +static void step_tower(RadCtx* c, const Model& m, const TowerAt& at) { + const Geom& g = m.gt; + const int64_t R = at.R, D = g.n_embd, hd = g.head_dim, Sx = m.lanes; + const int64_t qd = g.n_head * hd; + /* Row k of the code-major [10, lanes] plane, narrowed to this pass's lanes. */ + auto code = [&](int k) { + RadOperand o = brow_slice(m.b_codes, k, 1, Sx); + o.cols = R; + return o; + }; + for (int i = 0; i < kTower; ++i) { + const TowerLayer& L = m.tw[i]; + const int k = i - kShared; + if (at.frame) { + RAD_ISSUE_N(c, L.op_emb, R, code(k < 0 ? 0 : k), RAD_W(L.w_emb), RAD_W(L.w_emb), + brows(m.b_te, R)); + if (L.op_eadd) + RAD_ISSUE_N(c, L.op_eadd, R, brows(m.b_te, R), brows(m.b_ug, R), brows(m.b_te, R)); + RAD_ISSUE_N(c, L.op_en, R, brows(m.b_te, R), RAD_W(L.w_en), bcol(m.b_tcat, 0, D, R)); + } + if (at.labels) { + /* Row r's label: the code plane's column r + 1. */ + RAD_ISSUE_N(c, m.op_ptefill, R, brows(m.b_pte, R)); + RAD_ISSUE_N(c, L.op_pemb, R, bcol_at(m.b_pc, k < 0 ? 0 : k, kPcW, 1, R, 1), + RAD_W(L.w_emb), RAD_W(L.w_emb), brows(m.b_pte, R)); + if (L.op_peadd) + RAD_ISSUE_N(c, L.op_peadd, R, brows(m.b_pte, R), brows(m.b_pu, R), + brows(m.b_pte, R)); + RAD_ISSUE_N(c, L.op_pen, R, brows(m.b_pte, R), RAD_W(L.w_en), + bcol(m.b_tcat, 0, D, R)); + } + RAD_ISSUE_N(c, L.op_hn, R, brows(i == 0 ? at.h0 : m.b_tho, R), RAD_W(L.w_hn), + bcol(m.b_tcat, D, D, R)); + RAD_ISSUE_N(c, L.op_eh, R, brows(m.b_tcat, R), RAD_W(L.w_eh), brows(m.b_tm, R)); + RAD_ISSUE_N(c, L.op_an, R, brows(m.b_tm, R), RAD_W(L.w_an), brows(m.b_th, R)); + RAD_ISSUE_N(c, L.op_q, R, brows(m.b_th, R), RAD_W(L.w_q), brows(m.b_tq, R)); + RAD_ISSUE_N(c, L.op_g, R, brows(m.b_th, R), RAD_W(L.w_g), brows(m.b_tg, R)); + RAD_ISSUE_N(c, L.op_k, R, brows(m.b_th, R), RAD_W(L.w_k), brows(m.b_tk, R)); + RAD_ISSUE_N(c, L.op_v, R, brows(m.b_th, R), RAD_W(L.w_v), brows(m.b_tv, R)); + RAD_ISSUE_N(c, L.op_qn, R * g.n_head, brows(m.b_tq, R), RAD_W(L.w_qn), brows(m.b_tq, R)); + RAD_ISSUE_N(c, L.op_kn, R * g.n_head_kv, brows(m.b_tk, R), RAD_W(L.w_kn), + brows(m.b_tk, R)); + RAD_ISSUE_N(c, L.op_rq, R, brows(m.b_tq, R), at.pos); + RAD_ISSUE_N(c, L.op_rk, R, brows(m.b_tk, R), at.pos); + RAD_ISSUE_N(c, L.op_kv, R, brows(m.b_tk, R), brows(m.b_tv, R), at.slot, + kv_cache(m.kv_full, (int)m.n_main + i)); + RAD_ISSUE_N(c, L.op_attn, at.max_q, brows(m.b_tq, R), + kv_cache(m.kv_full, (int)m.n_main + i), at.bt, at.used, RAD_NONE, RAD_NONE, + at.cu, brows(m.b_tattn, R)); + RAD_ISSUE_N(c, L.op_sig, R, brows(m.b_tg, R), brows(m.b_tg, R)); + RAD_ISSUE_N(c, L.op_mul, R, brows(m.b_tattn, R), brows(m.b_tg, R), brows(m.b_tattn, R)); + RAD_ISSUE_N(c, L.op_o, R, brows(m.b_tattn, R), RAD_W(L.w_o), brows(m.b_to, R)); + if (L.op_ar1) RAD_ISSUE_N(c, L.op_ar1, R * D, brows(m.b_to, R), RAD_NONE); + RAD_ISSUE_N(c, L.op_add1, R, brows(m.b_tm, R), brows(m.b_to, R), brows(m.b_tm, R)); + RAD_ISSUE_N(c, L.op_fn, R, brows(m.b_tm, R), RAD_W(L.w_fn), brows(m.b_th, R)); + RAD_ISSUE_N(c, L.op_gu, R, brows(m.b_th, R), RAD_W(L.w_gu), brows(m.b_tgu, R)); + RAD_ISSUE_N(c, L.op_act, R, brows(m.b_tgu, R), brows(m.b_tff, R)); + RAD_ISSUE_N(c, L.op_down, R, brows(m.b_tff, R), RAD_W(L.w_down), brows(m.b_to, R)); + if (L.op_ar2) RAD_ISSUE_N(c, L.op_ar2, R * D, brows(m.b_to, R), RAD_NONE); + RAD_ISSUE_N(c, L.op_add2, R, brows(m.b_tm, R), brows(m.b_to, R), brows(m.b_tm, R)); + RAD_ISSUE_N(c, L.op_fin, R, brows(m.b_tm, R), RAD_W(L.w_fin), brows(m.b_tho, R)); + if (at.frame && L.op_head) { + RAD_ISSUE_N(c, L.op_head, R, brows(m.b_tho, R), RAD_W(L.w_head), brows(m.b_hlog, R)); + RAD_ISSUE_N(c, L.op_samp, R, brows(m.b_hlog, R), at.seed, at.fidx, code(k + 1), + RAD_NONE, RAD_NONE, RAD_NONE); + } + } + (void)qd; +} + +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, D = m.g.n_embd; + /* References: their clips encoded into the rows' code plane first. */ + const bool refs = A->n_ref > 0; + if (refs) step_encode(c, batch, m); + RAD_ISSUE_N(c, m.op_embed, T, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), + brows(m.b_x, T)); + if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, T * D, brows(m.b_x, T), RAD_NONE); + RadOperand sec1 = RAD_W(m.w_cb), sec2 = RAD_W(m.w_cb), sec3 = RAD_W(m.w_cb); + sec1.rows = kVocab; + sec2.offset = kVocab * D; + sec2.rows = kVocab; + sec3.offset = 2 * kVocab * D; + sec3.rows = (kCodes - 3) * kVocab; + if (refs) + RAD_ISSUE_N(c, m.op_pfb, T, bcol_at(m.b_pc, 0, kPcW, 0, T, 2), RAD_W(m.w_cemb), sec1, + brows(m.b_x, T)); + step_trunk(c, batch, m); + + /* The lane: the prompt's last hidden state, an empty window, no unseen codes. */ + const int64_t S = batch->n_seq, lane = A->lane_h[0]; + RAD_ISSUE_N(c, m.op_plast, S, brows(m.a_h.x, T), praw(A->last_row, RAD_I32, S), + brows(m.b_last, S)); + RAD_ISSUE_N(c, m.op_pstore, S, brows(m.b_last, S), praw(A->slot, RAD_I32, S), + brows(m.b_hid, m.lanes)); + RAD_ISSUE_N(c, m.op_uzero, 1, brow_slice(m.b_u, lane, 1, D)); + { + RadOperand w = brow_slice(m.b_ras, lane, 1, kRasWin); + RAD_ISSUE_N(c, m.op_rasinit, kRasWin, w); + /* A reference's frames among the last rows are picks the window has seen. */ + if (refs && T >= kRasWin) + RAD_ISSUE_N(c, m.op_rascopy, kRasWin, + bcol_at(m.b_pc, 0, kPcW, T - kRasWin, kRasWin, 1), w); + } + + /* The tower over every prompt row. A text prompt's labels are all text, so every code + * embedding is 0; with references a row before a frame is labelled with it, and a frame's row + * also carries its unseen codes (tower.py, prefill). The last row's pass is FRAME 0's, which + * writes its cache rows again. */ + const RadKVGroupBatch* kvb = kv_batch(batch, m.kv_full); + if (!refs) { + RAD_ISSUE_N(c, m.op_efill, T, bcol(m.b_tcat, 0, D, T)); + } else { + RAD_ISSUE_N(c, m.op_pufill, T, brows(m.b_pu, T)); + RAD_ISSUE_N(c, m.op_pu, T, bcol_at(m.b_pc, 2, kPcW, 0, T, kCodes - 2), sec2, sec3, + brows(m.b_pu, T)); + } + TowerAt at{}; + at.R = T; + at.max_q = batch->max_q_len; + at.pos = praw(batch->positions, RAD_I32, T); + at.slot = praw(kvb->slot_mapping, RAD_I32, T); + at.bt = praw2(kvb->block_table, RAD_I32, batch->n_seq, kvb->block_table_pitch); + at.used = praw(kvb->seqused, RAD_I32, batch->n_seq); + at.cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + at.h0 = m.a_h.x; + at.labels = refs; + step_tower(c, m, at); +} + +static void step_frame(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t S = A->n_lane, Sx = m.lanes; + const RadOperand seed = praw(A->seed, RAD_U32, 2 * S), frame = praw(A->frame, RAD_I32, S); + const RadOperand lanes = praw(A->lane, RAD_I32, S), slot = praw(A->slot, RAD_I32, S); + auto code = [&](int k) { + RadOperand o = brow_slice(m.b_codes, k, 1, Sx); + o.cols = S; + return o; + }; + + /* 1. the main token, from the hidden state of the row before the frame's */ + RAD_ISSUE_N(c, m.op_hsel, S, brows(m.b_hid, m.lanes), slot, brows(m.b_plane, S)); + RAD_ISSUE_N(c, m.op_head, S, brows(m.b_plane, S), RAD_W(m.w_cand), brows(m.b_slog, S)); + RAD_ISSUE_N(c, m.op_samp, S, brows(m.b_slog, S), seed, frame, brows(m.b_first, S), RAD_NONE, + RAD_NONE, RAD_NONE); + RAD_ISSUE_N(c, m.op_samp_ras, S, brows(m.b_slog, S), seed, frame, brows(m.b_alt, S), + RAD_NONE, RAD_NONE, RAD_NONE); + RAD_ISSUE_N(c, m.op_ras, S, brows(m.b_first, S), brows(m.b_alt, S), lanes, + brows(m.b_ras, m.lanes), code(0)); + RAD_ISSUE_N(c, m.op_status, S, code(0), lanes, brows(m.b_status, m.lanes)); + RAD_ISSUE_N(c, m.op_ugather, S, brows(m.b_u, m.lanes), slot, brows(m.b_ug, S)); + + /* 2. the tower at that row: its position, slot and context, the frame's own sequences */ + const RadKVGroupBatch* kvb = kv_batch(batch, m.kv_full); + TowerAt at{}; + at.R = S; + at.max_q = 1; + at.pos = praw(A->prev_pos, RAD_I32, S); + at.slot = praw(A->prev_slot, RAD_I32, S); + at.bt = praw2(kvb->block_table, RAD_I32, batch->n_seq, kvb->block_table_pitch); + at.used = praw(A->prev_used, RAD_I32, S); + at.cu = praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1); + at.h0 = m.b_plane; + at.frame = true; + at.seed = seed; + at.fidx = frame; + step_tower(c, m, at); + + /* 3. the frame into the lane's history and the lane's unseen codes; the backbone over its + * embedding at the frame's own row */ + RAD_ISSUE_N(c, m.op_store, S, bcol_at(m.b_codes, 0, Sx, 0, S, kCodes), lanes, frame, + brows(m.b_status, m.lanes), brows(m.b_hist, m.lanes * kCodes)); + RadOperand sec2 = RAD_W(m.w_cb), sec3 = RAD_W(m.w_cb), sec1 = RAD_W(m.w_cb); + const int64_t D = m.g.n_embd; + sec1.rows = kVocab; + sec2.offset = kVocab * D; + sec2.rows = kVocab; + sec3.offset = 2 * kVocab * D; + sec3.rows = (kCodes - 3) * kVocab; + RAD_ISSUE_N(c, m.op_u, S, bcol_at(m.b_codes, 2, Sx, 0, S, kCodes - 2), sec2, sec3, + brows(m.b_unew, S)); + RAD_ISSUE_N(c, m.op_uscat, S, brows(m.b_unew, S), slot, brows(m.b_u, m.lanes)); + RAD_ISSUE_N(c, m.op_fb, S, bcol_at(m.b_codes, 0, Sx, 0, S, 2), RAD_W(m.w_cemb), sec1, + brows(m.b_x, S)); + step_trunk(c, batch, m); + RAD_ISSUE_N(c, m.op_fstore, S, brows(m.a_h.x, S), slot, brows(m.b_hid, m.lanes)); +} + +static void step_vocode(RadCtx* c, const RadBatch* batch, const Model& m) { + const RadAudioGenBatch* A = batch->agen_b; + const int64_t nl = A->voc_latents, n = nl - A->voc_left, L = A->voc_lane; + /* The convolutions run over the last kConvFrames frames, or all of them when fewer. */ + const int64_t nc = std::min(nl, kConvFrames), c0 = nl - nc; + const RadOperand nlen = praw(batch->cu_seqlens + 1, RAD_I32, 1); + const RadOperand clen = nc == nl ? nlen : brows(m.b_cconst, 1); + + /* 1. the bounds at each rate: the transformer's frames, then the convolutions' */ + if (nc != nl) RAD_ISSUE_N(c, m.op_cnst, 1, brows(m.b_cconst, 1)); + RAD_ISSUE_N(c, m.op_ccu[0], 2, nlen, brows(m.b_ccu[0], 2)); + for (int s = 1; s < kRates; ++s) RAD_ISSUE_N(c, m.op_ccu[s], 2, clen, brows(m.b_ccu[s], 2)); + + /* 2. the codes, dequantised: the lane's frames [voc_frame0, + nl) of each codebook */ + for (int k = 0; k < kCodes; ++k) { + RadOperand codes = bcol_at(m.b_hist, L * kCodes + k, kMaxFrames, A->voc_frame0, nl, 1); + RAD_ISSUE_N(c, m.op_rq[k], nl, codes, RAD_W(m.w_cbk[k]), RAD_W(m.w_cbk[k]), + brows(m.b_rq, nl)); + RAD_ISSUE_N(c, m.qo[k].op, nl, brows(m.b_rq, nl), RAD_W(m.qo[k].w), brows(m.b_ccu[0], 2), + k == 0 ? RAD_NONE : brows(m.b_cx, nl), brows(m.b_cx, nl), RAD_W(m.qo[k].b)); + } + + /* 3. the transformer over every frame of the pass */ + { + CtSet B; + B.x = m.b_cx; B.h = m.b_ch; B.qkv = m.b_cqkv; B.attn = m.b_cattn; B.o = m.b_co; + B.gu = m.b_cgu; B.ff = m.b_cff; + step_ct(c, m.ct, nl, B, praw(batch->positions, RAD_I32, nl), brows(m.b_ccu[0], 2)); + } + RAD_ISSUE_N(c, m.op_cn, nc, brow_slice(m.b_cx, c0, nc, kLat), RAD_W(m.w_cn), + brows(m.b_ux[0], nc)); + + /* 4. the upsamplings, at 2 and 4 rows a frame */ + for (int i = 0; i < 2; ++i) { + const Upsample& U = m.up[i]; + const int64_t rin = nc << i, rout = nc << (i + 1); + RAD_ISSUE_N(c, U.op_t, rin, brows(m.b_ux[i], rin), RAD_W(U.w_t), RAD_W(U.b_t), + brows(m.b_ccu[1 + i], 2), brows(m.b_ux[i + 1], rout)); + RAD_ISSUE_N(c, U.op_dw, rout, brows(m.b_ux[i + 1], rout), RAD_W(U.w_dw), + brows(m.b_ccu[2 + i], 2), brows(m.b_ua, rout), RAD_W(U.b_dw)); + RAD_ISSUE_N(c, U.op_ln, rout, brows(m.b_ua, rout), RAD_W(U.w_ln), RAD_W(U.b_ln), + brows(m.b_ub, rout)); + RAD_ISSUE_N(c, U.op_p1, rout, brows(m.b_ub, rout), RAD_W(U.w_p1), RAD_W(U.b_p1), RAD_NONE, + brows(m.b_uh, rout)); + RAD_ISSUE_N(c, U.op_gelu, rout, brows(m.b_uh, rout), brows(m.b_ug2, rout)); + RAD_ISSUE_N(c, U.op_p2, rout, brows(m.b_ug2, rout), RAD_W(U.w_p2), RAD_W(U.b_p2), + RAD_NONE, brows(m.b_ua, rout)); + RAD_ISSUE_N(c, U.op_g, rout, brows(m.b_ua, rout), RAD_W(U.w_g), brows(m.b_ua, rout)); + RAD_ISSUE_N(c, U.op_add, rout, brows(m.b_ux[i + 1], rout), brows(m.b_ua, rout), + brows(m.b_ux[i + 1], rout)); + } + + /* 5. the decoder */ + int64_t rows[5]; + rows[0] = 4 * nc; + for (int i = 0; i < 4; ++i) rows[i + 1] = rows[i] * m.v_ups[i]; + auto conv = [&](const VConv& v, rad_buf x, rad_buf res, rad_buf y, int64_t R, rad_buf cub) { + RAD_ISSUE_N(c, v.op, R, brows(x, R), RAD_W(v.w), brows(cub, 2), + res ? brows(res, R) : RAD_NONE, brows(y, R), RAD_W(v.b)); + }; + conv(m.dec0, m.b_ux[2], 0, m.b_vs[0], rows[0], m.b_ccu[3]); + for (int i = 0; i < 4; ++i) { + const VBlock& B = m.vb[i]; + const int64_t r0 = rows[i], r1 = rows[i + 1]; + RAD_ISSUE_N(c, B.op_s, r0, brows(m.b_vs[i], r0), RAD_W(B.a), brows(m.b_vt[i], r0), + RAD_NONE); + RAD_ISSUE_N(c, B.op_t, r0, brows(m.b_vt[i], r0), RAD_W(B.wt), RAD_W(B.bt), + brows(m.b_ccu[3 + i], 2), brows(m.b_vs[i + 1], r1)); + for (int r = 0; r < 3; ++r) { + const VRes& U = B.res[r]; + RAD_ISSUE_N(c, U.op_s1, r1, brows(m.b_vs[i + 1], r1), RAD_W(U.a1), + brows(m.b_vt[i + 1], r1), RAD_NONE); + conv(U.c1, m.b_vt[i + 1], 0, m.b_va[i + 1], r1, m.b_ccu[4 + i]); + RAD_ISSUE_N(c, U.op_s2, r1, brows(m.b_va[i + 1], r1), RAD_W(U.a2), + brows(m.b_vb[i + 1], r1), RAD_NONE); + conv(U.c2, m.b_vb[i + 1], m.b_vs[i + 1], m.b_vs[i + 1], r1, m.b_ccu[4 + i]); + } + } + RAD_ISSUE_N(c, m.op_fs, rows[4], brows(m.b_vs[4], rows[4]), RAD_W(m.w_fa), + brows(m.b_vt[4], rows[4]), RAD_NONE); + conv(m.fin, m.b_vt[4], 0, m.b_vout, rows[4], m.b_ccu[7]); + /* 6. the chunk's own samples: its last n frames */ + const int64_t ns = n * kSamplesPerFrame; + RAD_ISSUE_N(c, m.op_fcast, ns, brow_slice(m.b_vout, rows[4] - ns, ns, 1), brows(m.b_audio, ns)); +} + +static void step(RadCtx* c, const RadBatch* batch) { + const Model& m = g_model[rad_rank(c)]; + if (!batch->gen || !batch->agen_b) { + rad_step_fail(c, "fishomni is an audio generator and runs generator passes only"); + return; + } + switch (batch->gen) { + case RAD_GEN_PASS_PROMPT: step_prompt(c, batch, m); return; + case RAD_GEN_PASS_FRAME: step_frame(c, batch, m); return; + case RAD_GEN_PASS_VOCODE: step_vocode(c, batch, m); return; + default: + rad_step_fail(c, "fishomni: a generator pass of a kind this plugin does not know"); + } +} + +/* ================================================================== the probe */ +static int probe(const RadModelMeta* meta, RadArchProbe* out) { + if (!meta || !out) return RAD_E_INVAL; + out->gen_rows = kMaxPrompt; + out->gen_audio = 1; + out->gen_ctx = kMaxPrompt + kMaxFrames + 1; + return RAD_OK; +} + +/* ================================================================== the request's text */ +/* A Unicode White_Space code point's length at `s`, else 0. Python's str.strip() without + * arguments also strips U+001C..U+001F, which fish-speech avoids (generate.py, + * UNICODE_WHITE_SPACE); so does this. */ +static size_t white_space_at(const unsigned char* s, size_t n) { + if (n >= 1 && ((s[0] >= 0x09 && s[0] <= 0x0D) || s[0] == 0x20)) return 1; + if (n >= 2 && s[0] == 0xC2 && (s[1] == 0x85 || s[1] == 0xA0)) return 2; + if (n >= 3 && s[0] == 0xE1 && s[1] == 0x9A && s[2] == 0x80) return 3; /* U+1680 */ + if (n >= 3 && s[0] == 0xE2 && s[1] == 0x80 && + ((s[2] >= 0x80 && s[2] <= 0x8A) || s[2] == 0xA8 || s[2] == 0xA9 || s[2] == 0xAF)) + return 3; /* U+2000..200A, 2028, 2029, 202F */ + if (n >= 3 && s[0] == 0xE2 && s[1] == 0x81 && s[2] == 0x9F) return 3; /* U+205F */ + if (n >= 3 && s[0] == 0xE3 && s[1] == 0x80 && s[2] == 0x80) return 3; /* U+3000 */ + return 0; +} + +/* The length of a canonical speaker tag at `s` (`<|speaker:N|>`, N 0..15 without a leading + * zero), else 0. */ +static size_t speaker_tag_at(const char* s, size_t n) { + static const char kHead[] = "<|speaker:"; + const size_t h = sizeof kHead - 1; + if (n < h || std::strncmp(s, kHead, h) != 0) return 0; + size_t i = h; + while (i < n && s[i] >= '0' && s[i] <= '9') ++i; + const size_t digits = i - h; + if (digits == 0 || digits > 2 || i + 1 >= n || s[i] != '|' || s[i + 1] != '>') return 0; + if (digits == 2 && s[h] == '0') return 0; + const int v = digits == 1 ? s[h] - '0' : (s[h] - '0') * 10 + (s[h + 1] - '0'); + return v <= 15 ? i + 2 : 0; +} + +static int64_t refuse(char* out, int64_t cap, const char* why) { + if (out && cap > 0) std::snprintf(out, (size_t)cap, "%s", why); + return RAD_E_INVAL; +} + +/* `s` without the Unicode White_Space at either end. */ +static std::string strip_white(const std::string& s) { + const unsigned char* u = (const unsigned char*)s.data(); + size_t a = 0, z = s.size(); + for (size_t w; a < z && (w = white_space_at(u + a, z - a)) > 0;) a += w; + /* From the back: a White_Space code point is one to three bytes, so try each ending. */ + for (bool more = true; more && z > a;) { + more = false; + for (size_t w = 1; w <= 3 && w <= z - a; ++w) + if (white_space_at(u + z - w, w) == w) { + z -= w; + more = true; + break; + } + } + return s.substr(a, z - a); +} + +/* What fish-speech's server hands the model (chunking.py, split_drama3_text): each speaker's turn + * as "<|speaker:N|> " and its text stripped of white space at both ends, turns joined by a newline, + * text before the first tag speaker 0's; untagged text stripped and given speaker 0 + * (generate.py, with_speaker_tag). Its model was trained on that form: the same two turns joined + * by a space instead are spoken through less often. `r` is validated already. */ +static std::string speaker_turns(const std::string& r) { + if (r.find("<|speaker") == std::string::npos) return "<|speaker:0|> " + strip_white(r); + std::string outs, id = "0"; + size_t at = 0; + auto turn = [&](const std::string& who, size_t a, size_t z) { + const std::string body = strip_white(r.substr(a, z - a)); + if (body.empty()) return; + if (!outs.empty()) outs += "\n"; + outs += "<|speaker:" + who + "|> " + body; + }; + for (size_t t = r.find("<|speaker"); t != std::string::npos;) { + turn(id, at, t); + const size_t len = speaker_tag_at(r.data() + t, r.size() - t); + id = r.substr(t + 10, len - 12); /* the digits between "<|speaker:" and "|>" */ + at = t + len; + t = r.find("<|speaker", at); + } + turn(id, at, r.size()); + return outs; +} + +/* generate.py's build_drama3_prompt for a reference's transcript: speaker 0's tag and a space in + * front unless a tag leads after white space (with_speaker_tag), and white space ahead of a + * leading tag moved behind it, so the tag follows "Text: " directly. `r` is validated already. */ +static std::string reference_text(const std::string& r) { + const unsigned char* u = (const unsigned char*)r.data(); + size_t lead = 0; + for (size_t w; lead < r.size() && (w = white_space_at(u + lead, r.size() - lead)) > 0;) + lead += w; + const size_t tag = speaker_tag_at(r.data() + lead, r.size() - lead); + if (!tag) return "<|speaker:0|> " + r; + return r.substr(lead, tag) + r.substr(0, lead) + r.substr(lead + tag); +} + +/* generate.py's validate_drama3_text: the input, or a reference's transcript, is not empty, holds + * none of the tokens only the prompt builder writes, and names speakers only as <|speaker:0|> to + * <|speaker:15|>; then the input's speaker turns are written as the reference's server writes + * them (speaker_turns), and a transcript is tagged as its prompt builder tags it. */ +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_INPUT || field == RAD_TEXT_REFERENCE) { + const bool ref = field == RAD_TEXT_REFERENCE; + const unsigned char* u = (const unsigned char*)r.data(); + const size_t n = r.size(); + size_t lead = 0; + for (size_t w; lead < n && (w = white_space_at(u + lead, n - lead)) > 0;) lead += w; + bool blank = true; + for (size_t i = lead; i < n && blank;) { + const size_t w = white_space_at(u + i, n - i); + if (w == 0) blank = false; + else i += w; + } + if (blank) + return refuse(out, cap, ref ? "the reference's text is empty: it is what its clip says" + : "the input is empty: there is nothing to speak"); + static const char* kStructural[] = { "<|im_start|>", "<|im_end|>", "<|voice|>", + "<|text|>", "<|interleave|>", "<|semantic:" }; + for (const char* t : kStructural) + if (r.find(t) != std::string::npos) { + char why[128]; + std::snprintf(why, sizeof why, "%s is written by the prompt builder, not %s", t, + ref ? "a reference's text" : "the input"); + return refuse(out, cap, why); + } + for (size_t at = r.find("<|speaker"); at != std::string::npos; + at = r.find("<|speaker", at + 1)) + if (!speaker_tag_at(r.data() + at, n - at)) + return refuse(out, cap, "speaker tags are <|speaker:0|> to <|speaker:15|>"); + r = ref ? reference_text(r) : speaker_turns(r); + if (r.empty()) return refuse(out, cap, "the input is empty: there is nothing to speak"); + } + if ((int64_t)r.size() < cap) { + std::memcpy(out, r.data(), r.size()); + out[r.size()] = 0; + } + return (int64_t)r.size(); +} + +} /* namespace fishomni */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PROBE(fishomni) +extern "C" int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap) { + return fishomni::text_prepare(field, in, out, cap); +} +RAD_ARCH_PLUGIN(fishomni, "fishomni", "bsgemm-moe", "0.1.0", + "Fish Audio drama-3: the Qwen3.5-35B-A3B backbone (block-scaled fp8 experts), a " + "13-layer codebook tower over its full-attention cache, and Fish S2's modified " + "DAC; 44.1 kHz mono speech") +#endif diff --git a/arch/gemma3/gemma3.cpp b/arch/gemma3/gemma3.cpp index 6580ff94..f9efb790 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -22,6 +22,7 @@ #include #include +#include #include #include #include @@ -94,7 +95,18 @@ struct G3Linear { bool i8g = false; bool mx = false; bool a4 = false; /* asymmetric int4 over the per-(row, 128) int8 activation */ + /* a4 at decode heights, as LinearFP8's w4 (rad_fp8.h): up to kA4Split rows the bf16 input is + * cast to f16 (`a16`) for w4a16_asym's skinny kernel; w4a8i8_asym has only a prefill kernel, + * which at one row does 16 times the matrix work. */ + static constexpr int64_t kA4Split = 64; + int64_t a4_split = 0; + rad_buf a16 = 0; + rad_op op_a16 = 0, op_dec = 0; bool shared_in = false; + /* Set before declare: an E4M3 (MXFP4) linear's input pair given by the caller (the pipelined + * prefill's one pair for every block) instead of one of its own. It keeps its own quantiser + * into it, so a step that does not write the pair by a fused junction still fills it. */ + rad_buf q8_into = 0, s8_into = 0; int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, std::initializer_list src, @@ -104,6 +116,9 @@ struct G3Linear { const G3Linear* in_from = nullptr); void step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const; void gemm(RadCtx* c, rad_buf y, int64_t T) const; + /* The same over rows [r0, r0 + n) of an E4M3 (MXFP4) linear, for the pipelined prefill. */ + void step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const; + void gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const; }; inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base, @@ -198,7 +213,8 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); if (!w || !ws) return RAD_E_INVAL; - if (in_from && (in_from->i8g || in_from->a4) && in_from->q8 && in_from->K == K) { + /* not an a4 linear's pair: below its decode band it writes none */ + if (in_from && in_from->i8g && in_from->q8 && in_from->K == K) { q8 = in_from->q8; s8 = in_from->s8; shared_in = true; @@ -218,7 +234,21 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a8i8_asym")), RAD_WEIGHTS(w, ws)), { q8, s8 }, { y }); - return op ? RAD_OK : RAD_E_INVAL; + if (!op) return RAD_E_INVAL; + a4_split = std::min(kA4Split, g.max_tok); + a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { a4_split, K }); + if (!a16) return RAD_E_INVAL; + op_a16 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("n", K), + RAD_STR("from", g.dtype), RAD_STR("to", "f16")), + RAD_NOWEIGHTS), + { a }, { a16 }); + op_dec = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a16_asym")), + RAD_WEIGHTS(w, ws)), + { a16 }, { y }); + return (op_a16 && op_dec) ? RAD_OK : RAD_E_INVAL; } if (i8g || mx) { if (N % 16 || K % RAD_FP8_BLOCK) { @@ -239,13 +269,13 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); if (!w || !ws) return RAD_E_INVAL; } - if (in_from && in_from->mx == mx && (in_from->i8g || in_from->a4) == i8g && in_from->q8 && in_from->K == K) { + if (in_from && in_from->mx == mx && in_from->i8g == i8g && !in_from->a4 && in_from->q8 && in_from->K == K) { q8 = in_from->q8; s8 = in_from->s8; shared_in = true; } else { - q8 = decl_b(b, nm.f("%s.q8", base), mx ? RAD_F8E4M3 : RAD_I8, { g.max_tok, K }); - s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK }); + q8 = mx && q8_into ? q8_into : decl_b(b, nm.f("%s.q8", base), mx ? RAD_F8E4M3 : RAD_I8, { g.max_tok, K }); + s8 = mx && s8_into ? s8_into : decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK }); if (!q8 || !s8) return RAD_E_INVAL; op_q = rw(b, RAD_OP(b, mx ? "quant_act_fp8" : "quant_act_i8g", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K), @@ -281,6 +311,10 @@ inline void G3Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const { if (!shared_in) RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE); gemm(c, y, T); + } else if (a4 && T <= a4_split) { + RAD_ISSUE_N(c, op_a16, T, brows(a, T), brows(a16, T)); + RAD_ISSUE_N(c, op_dec, T, brows(a16, T), RAD_NONE, RAD_W(w), RAD_W(ws), brows(y, T), + RAD_NONE, RAD_NONE); } else if (i8g || mx || a4) { /* quant_act_i8g / quant_act_fp8 take x, q, scale: no optional `asum`. */ if (!shared_in) @@ -295,6 +329,24 @@ inline void G3Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const { brows(y, T), RAD_NONE, mx ? RAD_W(wref) : RAD_NONE); } +inline void G3Linear::gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const { + RAD_ISSUE_N(c, op, n, brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, K / RAD_FP8_BLOCK), + RAD_W(w), RAD_W(ws), brow_slice(y, r0, n, N), RAD_NONE, RAD_W(wref)); +} + +inline void G3Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const { + if (a4 && n <= a4_split) { + RAD_ISSUE_N(c, op_a16, n, brow_slice(a, r0, n, K), brows(a16, n)); + RAD_ISSUE_N(c, op_dec, n, brows(a16, n), RAD_NONE, RAD_W(w), RAD_W(ws), + brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE); + return; + } + if (!shared_in) + RAD_ISSUE_N(c, op_q, n, brow_slice(a, r0, n, K), brow_slice(q8, r0, n, K), + brow_slice(s8, r0, n, K / RAD_FP8_BLOCK)); + gemm_rows(c, y, r0, n); +} + /* ---- the GPTQ calibration tap (rad_arch.h's calib_*): the Gram of one linear's bf16 input, * summed over the corpus in a PERSIST [K, K] f32 buffer. Declared only with RADIANCE_CALIB_DIR set, * for the layers RADIANCE_G3_CALIB_LAYERS names ("lo:hi", default every layer): a down projection's @@ -343,6 +395,12 @@ struct Gemma3Attn { /* Calibration: q|k|v's shared input and o_proj's (this rank's columns). */ G3Tap tap_in{}, tap_o{}; const bool* tap_live = nullptr; + /* Set before declare by a pipelined deployment: the all-reduce a second time at `overlap` 1 (a + * launch that leaves the CUs to the compute beside it), and q|k|v's input pair shared by every + * block (the junctions write it a piece at a time on the second lane). */ + int ar_overlap = 0; + rad_op op_ar_ov = 0; + const G3Linear* pipe_in = nullptr; int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, rad_kvgroup group, const Wire& wire, double scale); @@ -352,6 +410,17 @@ struct Gemma3Attn { void post(RadCtx* c, int64_t T) const { RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); } + /* The pipelined prefill (step_pipelined): the block over one prefill sequence in two pieces, + * its input pair already written; hands the first piece behind its out projection. */ + void step_pieces(RadCtx* c, const RadBatch* batch, ArPieces* pc, const int32_t* used0) const; + /* The tail a piece at a time on the second lane: the overlap all-reduce and the post-norm. */ + void ar_rows(RadCtx* c, int64_t r0, int64_t n) const { + RAD_ISSUE_N(c, op_ar_ov, n * g.n_embd, brow_slice(w.h, r0, n, g.n_embd), RAD_NONE); + } + void post_rows(RadCtx* c, int64_t r0, int64_t n) const { + RAD_ISSUE_N(c, op_post, n, brow_slice(w.h, r0, n, g.n_embd), RAD_W(w_post), + brow_slice(w.h, r0, n, g.n_embd)); + } }; int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, @@ -359,6 +428,7 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const g = geom; cls = cgeo; layer = l; kv = group; w = wire; attn_scale = scale; const int64_t qd = cls.q_dim(), kvd = cls.kv_dim(); const char* pre = kLayers; + if (pipe_in) { ln_q.q8_into = pipe_in->q8; ln_q.s8_into = pipe_in->s8; } RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l))); RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l))); @@ -460,6 +530,13 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const RAD_INT("min_bytes", g.wire_min_bytes)), RAD_NOWEIGHTS), {w.h}, {w.h}); + if (g.world > 1 && ar_overlap > 0) + op_ar_ov = 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_INT("overlap", ar_overlap)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); op_post = rw(b, RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), @@ -474,6 +551,49 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const return RAD_OK; } +/* Each piece is the chunk a span of 1 makes: its rows, positions and slots, and an attention over + * its own query bounds (ArPieces::cu) seeing the cache up to its own end -- `used0`, the group's + * seqused less the second piece's rows, for the first; the step's seqused for the second, which + * reads the first piece's keys from the cache as a later chunk would (the sliding window included: + * a window group's seqused counts from its rebased first block). */ +void Gemma3Attn::step_pieces(RadCtx* c, const RadBatch* batch, ArPieces* pc, + const int32_t* used0) 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, R = pc->rows; + const int64_t qd = cls.q_dim(), kvd = cls.kv_dim(); + const int64_t tpitch = kvb ? kvb->block_table_pitch : 0; + for (int64_t p = 0; p < 2; ++p) { + const int64_t r0 = p == 0 ? 0 : R; + const int64_t n = p == 0 ? R : T - R; + const int32_t* pos = batch->positions + r0; + ln_q.gemm_rows(c, w.q, r0, n); + ln_k.gemm_rows(c, w.k, r0, n); + ln_v.gemm_rows(c, w.v, r0, n); + if (op_qnr) { + RAD_ISSUE_N(c, op_qnr, n, brow_slice(w.q, r0, n, qd), brow_slice(w.k, r0, n, kvd), + brow_slice(w.v, r0, n, kvd), praw(pos, RAD_I32, n), RAD_W(w_qn), RAD_W(w_kn)); + } else { + RAD_ISSUE_N(c, op_qn, n * cls.n_head, brow_slice(w.q, r0, n, qd), RAD_W(w_qn), + brow_slice(w.q, r0, n, qd)); + RAD_ISSUE_N(c, op_kn, n * cls.n_head_kv, brow_slice(w.k, r0, n, kvd), RAD_W(w_kn), + brow_slice(w.k, r0, n, kvd)); + RAD_ISSUE_N(c, op_rq, n, brow_slice(w.q, r0, n, qd), praw(pos, RAD_I32, n)); + RAD_ISSUE_N(c, op_rk, n, brow_slice(w.k, r0, n, kvd), praw(pos, RAD_I32, n)); + } + RAD_ISSUE_N(c, op_kv, n, brow_slice(w.k, r0, n, kvd), brow_slice(w.v, r0, n, kvd), + praw(slot + r0, RAD_I32, n), kv_cache(kv, layer)); + RAD_ISSUE_N(c, op_attn, n, brows(w.q, T), kv_cache(kv, layer), + praw2(table, RAD_I32, 1, tpitch), + praw(p == 0 ? used0 : used, RAD_I32, 1), + RAD_NONE, RAD_NONE, praw(pc->cu + p, RAD_I32, 2), brows(w.attn, T)); + ln_o.step_rows(c, w.attn, w.h, r0, n); + if (p == 0) pc->hand(r0, n); + } +} + void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused, bool ar_fused) const { const RadKVGroupBatch* kvb = kv_batch(batch, kv); @@ -538,6 +658,10 @@ struct Gemma3Mlp { /* Calibration: gate|up's input and down's (this rank's columns). */ G3Tap tap_gu{}, tap_dn{}; const bool* tap_live = nullptr; + /* Set before declare by a pipelined deployment, as Gemma3Attn's. */ + int ar_overlap = 0; + rad_op op_ar_ov = 0; + const G3Linear* pipe_in = nullptr; int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire); void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false, @@ -545,11 +669,30 @@ struct Gemma3Mlp { void post(RadCtx* c, int64_t T) const { RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T)); } + /* The pipelined prefill: the block over rows [r0, r0 + n), its input pair already written, up + * to the down projection; then the tail a piece at a time on the second lane. */ + void body_rows(RadCtx* c, int64_t r0, int64_t n) const { + ln_gu.gemm_rows(c, w.gu, r0, n); + RAD_ISSUE_N(c, op_act, n, brow_slice(w.gu, r0, n, 2 * g.n_ff), brow_slice(w.ffn, r0, n, g.n_ff)); + ln_down.step_rows(c, w.ffn, w.h, r0, n); + } + void ar_rows(RadCtx* c, int64_t r0, int64_t n) const { + RAD_ISSUE_N(c, op_ar_ov, n * g.n_embd, brow_slice(w.h, r0, n, g.n_embd), RAD_NONE); + } + void post_rows(RadCtx* c, int64_t r0, int64_t n) const { + RAD_ISSUE_N(c, op_post, n, brow_slice(w.h, r0, n, g.n_embd), RAD_W(w_post), + brow_slice(w.h, r0, n, g.n_embd)); + } + void add_rows(RadCtx* c, int64_t r0, int64_t n) const { + RAD_ISSUE_N(c, op_add, n, brow_slice(w.x, r0, n, g.n_embd), brow_slice(w.h, r0, n, g.n_embd), + brow_slice(w.x, r0, n, g.n_embd)); + } }; int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire) { g = geom; layer = l; w = wire; const char* pre = kLayers; + if (pipe_in) { ln_gu.q8_into = pipe_in->q8; ln_gu.s8_into = pipe_in->s8; } RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_norm.weight", l), nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l))); RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_post_norm.weight", l), nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l))); @@ -589,6 +732,13 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const RAD_INT("min_bytes", g.wire_min_bytes)), RAD_NOWEIGHTS), {w.h}, {w.h}); + if (g.world > 1 && ar_overlap > 0) + op_ar_ov = 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_INT("overlap", ar_overlap)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); op_post = rw(b, RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), @@ -651,7 +801,7 @@ struct G3Junction { const rad_buf wr[3] = { q8, s8, res }; rad_op_reads (b, op, rd, res ? 2 : 1); rad_op_writes(b, op, wr, res ? 3 : 2); - if (res && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_quant_i8")) { + if (res && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_quant_i8")) { const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_F64("eps", g.eps), RAD_INT("world_size", g.world), RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) }; @@ -678,8 +828,11 @@ struct G3Junction { * embedding stream. */ struct G3JunctionFP8 { rad_op op = 0; - /* At two ranks on the exact wire: the branch's all-reduce and post-norm folded in front - * (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. */ + /* At two ranks: the branch's all-reduce and post-norm folded in front + * (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. The kernel + * sends the exact wire only, so under --tp-wire it is declared all the same and taken by the + * steps whose message goes out exact anyway (ar_wire_is_exact: a decode step of a few rows, + * under --tp-wire-min-kb); a wider step keeps the lossy all-reduce, unfused. */ rad_op op_ar = 0; rad_buf x = 0, res = 0, q = 0, s = 0; rad_weight w = 0, wp = 0; @@ -700,7 +853,7 @@ struct G3JunctionFP8 { const rad_buf wr[3] = { q, s, res }; rad_op_reads (b, op, rd, res ? 2 : 1); rad_op_writes(b, op, wr, res ? 3 : 2); - if (res && wp && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_post_quant_fp8")) { + if (res && wp && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_post_quant_fp8")) { const rad_weight ws[2] = { w, wp }; const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_F64("eps", g.eps), RAD_INT("group", RAD_FP8_BLOCK), RAD_INT("world_size", g.world), @@ -723,6 +876,12 @@ struct G3JunctionFP8 { RAD_ISSUE_N(c, op, T, brows(x, T), res ? brows(res, T) : RAD_NONE, RAD_W(w), brows(q, T), brows(s, T), RAD_NONE); } + /* Rows [r0, r0 + n), without the all-reduce: the pipelined prefill's second lane. */ + void step_rows(RadCtx* c, int64_t r0, int64_t rows) const { + RAD_ISSUE_N(c, op, rows, brow_slice(x, r0, rows, n), res ? brow_slice(res, r0, rows, n) : RAD_NONE, + RAD_W(w), brow_slice(q, r0, rows, n), brow_slice(s, r0, rows, n / RAD_FP8_BLOCK), + RAD_NONE); + } }; struct Layer { @@ -773,10 +932,31 @@ struct Model { bool calib = false, tap_live = false; int64_t calib_lo = 0, calib_hi = 0; long long calib_rows = 0; + + /* The pipelined prefill (step_pipelined): on where declare allowed it; the input pair every + * block's q|k|v and gate|up read (the junctions write it); the bounds buffer and its pinned + * table of {0, pipe_rows(T), T}; whether rank 0 has said it pipelines, or why not. */ + bool pipe_on = false; + G3Linear pipe_in{}; + rad_buf b_pipe_cu = 0; + /* Each KV group's seqused for the first piece, [2] (sliding, global): the step's less the + * second piece's rows (sub_i32 from b_pipe_cu[3] = T - R). A window group's seqused counts from + * its rebased first block, not from position 0, so the first piece's position cannot stand in. */ + rad_buf b_pipe_used = 0; + rad_op op_pipe_used = 0; + int32_t* pipe_tbl = nullptr; + bool pipe_tbl_tried = false; + bool pipe_noted = false; + bool pipe_serial_noted = false; }; static Model g_model[MAX_RANKS]; +/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up + * to 64 rows (qwen35_fp8 says why). */ +static const int64_t kPipeMinRows = 1024; +static int64_t pipe_rows(int64_t T) { return ((T + 1) / 2 + 63) / 64 * 64; } + /* ================================================================== the DFlash2 drafter * * A second model at absolute layers n_layer.. with its own KV group (rad_block_dflash2.h), as @@ -793,6 +973,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma3 DFlash2")); Dflash2::Config dc{}; + dc.short_block = 1; /* rad_drafter_short_block below */ dc.n_taps = m.n_taps; dc.block = ctx->max_spec + 1; dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2); @@ -904,6 +1085,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui return RAD_E_FORMAT; } RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + if (m.df.block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, m.df.block_lo)); rad_note(b, "DFlash2 drafter: %lld layers at absolute %d.., %lld heads / %lld kv x %lld, ffn %lld, " "%s attention with a %lld-token window, %d trunk taps, embedding x %g, %s head", (long long)dg.n_layer, base_layer, (long long)dg.n_head, (long long)dg.n_head_kv, @@ -917,6 +1099,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; Model& m = g_model[ctx->rank]; + if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED); m = Model{}; m.nm = Names(ctx->scope); RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); @@ -1034,6 +1217,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_F64("mult", emult)), RAD_WEIGHTS(m.w_tok)), {}, {m.b_x}); + /* The second lane's window (rad_lane1_window_begin): from the embedding's reduction to the final + * norm, where the pipelined prefill runs its boundaries; the drafter and the heads lie outside it + * and can share the concurrent buffers' bytes. */ + RAD_ARCH_TRY(rad_lane1_window_begin(b)); if (g.world > 1) m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world), @@ -1042,6 +1229,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_NOWEIGHTS), {m.b_x}, {m.b_x}); + /* The pipelined prefill (step_pipelined), at two ranks wherever a step can be wide enough, on + * an MXFP4 trunk with fused junctions (decided below); two ranks only, as in qwen35_fp8. Its + * second lane touches the stream, the branch output, the shared input pair and the bounds, so + * those leave the sharing pool (Ctx::lane1_; the drafter taps are copied on the first lane, + * pipe_taps). The pair is one for every block so that this costs one pair, not one a + * linear. */ + m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows && !calib_dir(); + if (m.pipe_on) { + m.pipe_in.mx = true; + m.pipe_in.K = g.n_embd; + m.pipe_in.q8 = decl_b(b, nm.f("pipe_in.q8"), RAD_F8E4M3, {g.max_tok, g.n_embd}); + m.pipe_in.s8 = decl_b(b, nm.f("pipe_in.s8"), RAD_F32, {g.max_tok, g.n_embd / RAD_FP8_BLOCK}); + if (!m.pipe_in.q8 || !m.pipe_in.s8) return RAD_E_INVAL; + } + Gemma3Attn::Wire aw{}; aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn; Gemma3Mlp::Wire mw{}; mw.x = m.b_x; mw.h = m.b_h; mw.gu = m.b_gu; mw.ffn = m.b_ffn; @@ -1052,6 +1254,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c const ClassGeom& cgeo = lay.global ? m.cg : m.cs; const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s; RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg)); + if (m.pipe_on) { + lay.attn.ar_overlap = lay.mlp.ar_overlap = 1; + lay.attn.pipe_in = lay.mlp.pipe_in = &m.pipe_in; + } RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, attn_scale)); RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw)); } @@ -1119,6 +1325,38 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } m.fuse_mx_ar = ar; } + /* The pipeline needs the fused fp8 junctions and every block's overlap all-reduce. */ + if (m.pipe_on) { + bool ok = m.fuse_mx; + /* ... and the pieces' row-sliced linears are the E4M3 (MXFP4) path throughout. */ + for (const Layer& lay : m.layers) + ok = ok && lay.attn.op_ar_ov && lay.mlp.op_ar_ov && lay.attn.ln_o.mx && lay.mlp.ln_down.mx; + if (!ok) + rad_note(b, "the pipelined prefill is off: it needs an MXFP4 trunk with the fused fp8 " + "junctions and an overlap all-reduce for every block"); + m.pipe_on = ok; + } + if (m.pipe_on) { + RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_x)); + RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h)); + RAD_ARCH_TRY(rad_buf_concurrent(b, m.pipe_in.q8)); + RAD_ARCH_TRY(rad_buf_concurrent(b, m.pipe_in.s8)); + m.b_pipe_cu = decl_b(b, nm.f("pipe_cu"), RAD_I32, {4}); + RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_cu)); + m.b_pipe_used = decl_b(b, nm.f("pipe_used"), RAD_I32, {2}); + RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_used)); + m.op_pipe_used = rad_op_declared(b, "sub_i32") + ? RAD_OP(b, "sub_i32", RAD_PARAMS(RAD_RANGE("M", 1, 1)), RAD_NOWEIGHTS) : 0; + if (m.op_pipe_used) { + const rad_buf rd[1] = { m.b_pipe_cu }; + const rad_buf wr[1] = { m.b_pipe_used }; + rad_op_reads (b, m.op_pipe_used, rd, 1); + rad_op_writes(b, m.op_pipe_used, wr, 1); + } else { + m.pipe_on = false; /* no way to put the first piece's seqused on the card */ + rad_note(b, "the pipelined prefill is off: no plugin serves sub_i32"); + } + } /* ---- the calibration tap. It reads the bf16 input of every linear, which the fused junctions * never write, so under it none is declared (above): any container calibrates, unfused. */ @@ -1154,6 +1392,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(m.w_out)), {m.b_x}, {m.b_h}); + RAD_ARCH_TRY(rad_lane1_window_end(b)); 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), @@ -1180,6 +1419,191 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c return RAD_OK; } +/* ============================== A prefill step in two pieces ============================== + * + * qwen35_fp8's step_pipelined on Gemma 3's trunk: at two ranks every layer of a prefill chunk makes + * two all-reduces, each in a hard chain behind its block (all-reduce, post-norm, the junction's add + * and next norm, then the next block). A step of one prefill sequence of at least kPipeMinRows tokens + * is cut into two pieces of about half; every block runs a piece at a time on the first lane, and + * the work between two blocks -- the block's all-reduce at `overlap` 1, its post-norm and the fp8 + * junction, and after the last block its add and the final norm -- runs a + * piece at a time on the second; the drafter taps run on the first (pipe_taps). The ops are the serial step's at a narrower width, so a pipelined + * step is bit for bit the serial one where a chunk's rows do not depend on its width. + * + * The second lane's requirements (Ctx::lane1_) hold as in qwen35_fp8: every collective of the step + * is on it, the embedding's included; none carries a device-wide arrival counter; the buffers it + * touches left the sharing pool at declare, the per-linear input pairs replaced by one shared pair. */ + +template +static void pipe_on1(RadCtx* c, const F& issue) { + rad_lane(c, 1); + rad_lane_join(c, 0, 1); + issue(); + rad_lane(c, 0); +} +static void pipe_wait1(RadCtx* c) { rad_lane_join(c, 1, 0); } + +/* The work after block `s` (2l the attention of layer l, 2l + 1 its feed-forward), rows + * [r0, r0 + n). */ +static void pipe_boundary(RadCtx* c, const Model& m, int64_t s, int64_t r0, int64_t n) { + const Geom& g = m.g; + const int64_t li = s / 2; + const Layer& l = m.layers[(size_t)li]; + const bool last = li + 1 == (int64_t)m.layers.size(); + if (s % 2 == 0) { + l.attn.ar_rows(c, r0, n); + l.attn.post_rows(c, r0, n); + l.jf_am.step_rows(c, r0, n); + return; + } + l.mlp.ar_rows(c, r0, n); + l.mlp.post_rows(c, r0, n); + if (!last) l.jf_ma.step_rows(c, r0, n); + else l.mlp.add_rows(c, r0, n); + if (last) + RAD_ISSUE_N(c, m.op_final, n, brow_slice(m.b_x, r0, n, g.n_embd), RAD_W(m.w_out), + brow_slice(m.b_h, r0, n, g.n_embd)); +} + +/* Layer `li`'s drafter taps of rows [r0, r0 + n), on lane 0. Issued once lane 0 has waited for that + * piece's feed-forward boundary (its junction is the last write to those rows of x before the next + * block's boundary, which lane 1 starts only behind lane 0's next issues), so the taps buffer is + * never touched from lane 1 and stays in the sharing pool: rad_buf_concurrent would hold its + * [max_tok, n_taps * n_embd] for the whole program. */ +static void pipe_taps(RadCtx* c, const Model& m, int64_t li, int64_t r0, int64_t n) { + for (int t = 0; t < m.n_taps; ++t) { + if (m.tap_layer[t] != (int)li) continue; + RAD_ISSUE_N(c, m.op_tap, n, brow_slice(m.b_x, r0, n, m.g.n_embd), + bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * m.g.n_embd, (int64_t)t * m.g.n_embd, + m.g.n_embd, n)); + } +} + +/* An attention block's first piece is done (ArPieces): lane 0 takes the previous block's second + * boundary before the second piece (and the previous layer's second-piece taps behind it), and + * lane 1 this block's first behind it. */ +struct PipeHand { + RadCtx* c = nullptr; + const Model* m = nullptr; + int64_t s = 0; + int64_t T = 0; +}; +static void pipe_hand(void* u, int64_t r0, int64_t n) { + const PipeHand& h = *(const PipeHand*)u; + pipe_wait1(h.c); + if (h.s >= 2) { + const int64_t R = pipe_rows(h.T); + pipe_taps(h.c, *h.m, h.s / 2 - 1, R, h.T - R); + } + pipe_on1(h.c, [&] { pipe_boundary(h.c, *h.m, h.s, r0, n); }); +} + +/* The bounds of this step's pieces on the card, {0, pipe_rows(T), T}, if the step is pipelined; + * null for a serial step, and null with `failed` set when the step has been failed (a rank-local + * failure past the batch's own conditions: the other rank would pipeline). */ +static const int32_t* pipe_ready(RadCtx* c, const RadBatch* batch, Model& m, bool* failed) { + const int64_t T = batch->n_tok; + if (!m.pipe_on || !m.b_pipe_cu || T < kPipeMinRows || T > m.g.max_tok || + batch->phase != RAD_PHASE_PREFILL) + return nullptr; + auto serial = [&](const char* why) -> const int32_t* { + if (!m.pipe_serial_noted && m.g.rank == 0) + fprintf(stderr, "radiance: gemma3: a %lld-row prefill step runs serially: %s\n", + (long long)T, why); + m.pipe_serial_noted = true; + return nullptr; + }; + if (batch->n_seq != 1 || batch->n_seq_decode != 0) return serial("more than one sequence"); + if (!batch->positions || batch->rope_pos) return serial("no one-component positions"); + const RadKVGroupBatch* kvs = kv_batch(batch, m.kv_s); + const RadKVGroupBatch* kvg = kv_batch(batch, m.kv_g); + if (!kvs || !kvg || !kvs->slot_mapping || !kvg->slot_mapping || !kvs->block_table || + !kvg->block_table || !kvs->seqused || !kvg->seqused) + return serial("a KV group without slots, tables or lengths"); + int32_t* d = (int32_t*)rad_buf_ptr(c, m.b_pipe_cu); + if (!d || !rad_buf_ptr(c, m.b_pipe_used)) { + rad_step_fail(c, "gemma3: the pipelined prefill's bounds have no storage"); + *failed = true; + return nullptr; + } + if (!m.pipe_tbl_tried) { + m.pipe_tbl_tried = true; + const int64_t n = m.g.max_tok + 1; + m.pipe_tbl = (int32_t*)rad_dev_alloc(4 * n * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED); + if (m.pipe_tbl) + for (int64_t t = 0; t < n; ++t) { + m.pipe_tbl[4 * t] = 0; + m.pipe_tbl[4 * t + 1] = (int32_t)pipe_rows(t); + m.pipe_tbl[4 * t + 2] = (int32_t)t; + m.pipe_tbl[4 * t + 3] = (int32_t)(t - pipe_rows(t)); + } + } + if (!m.pipe_tbl || + rad_memcpy_async(d, m.pipe_tbl + 4 * T, 4 * (int64_t)sizeof(int32_t), rad_stream(c)) != + RAD_OK) { + rad_step_fail(c, "gemma3: the pipelined prefill's piece bounds could not be put on the card " + "(no pinned host memory, or the copy failed)"); + *failed = true; + return nullptr; + } + int32_t* u = (int32_t*)rad_buf_ptr(c, m.b_pipe_used); + RAD_ISSUE_N(c, m.op_pipe_used, 1, praw(kvs->seqused, RAD_I32, 1), praw(d + 3, RAD_I32, 1), + praw(u, RAD_I32, 1)); + RAD_ISSUE_N(c, m.op_pipe_used, 1, praw(kvg->seqused, RAD_I32, 1), praw(d + 3, RAD_I32, 1), + praw(u + 1, RAD_I32, 1)); + return d; +} + +static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) { + const Geom& g = m.g; + const int64_t T = batch->n_tok, R = pipe_rows(T); + const int64_t L = (int64_t)m.layers.size(); + if (!m.pipe_noted) { + m.pipe_noted = true; + if (g.rank == 0) + fprintf(stderr, "radiance: gemma3: prefill steps of one sequence from %lld rows are " + "pipelined: two pieces, block boundaries on the second lane\n", + (long long)kPipeMinRows); + } + RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T)); + /* The embedding's reduction and layer 0's norm over the whole step, on lane 1 with every other + * collective. */ + pipe_on1(c, [&] { + if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.b_x, T), RAD_NONE); + m.jf0.step(c, T); + }); + pipe_wait1(c); + for (int64_t li = 0; li < L; ++li) { + const Layer& l = m.layers[(size_t)li]; + PipeHand h{c, &m, 2 * li, T}; + ArPieces pc{}; + pc.rows = R; pc.done = pipe_hand; pc.u = &h; pc.cu = pcu; pc.in_ready = true; + const int32_t* used0 = (const int32_t*)rad_buf_ptr(c, m.b_pipe_used) + (l.global ? 1 : 0); + l.attn.step_pieces(c, batch, &pc, used0); + if (pc.handed != 1) { + rad_step_fail(c, "gemma3: an attention block did not run its two pieces"); + return; + } + pipe_wait1(c); + pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li, R, T - R); }); + l.mlp.body_rows(c, 0, R); + pipe_wait1(c); + pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li + 1, 0, R); }); + l.mlp.body_rows(c, R, T - R); + pipe_wait1(c); + pipe_taps(c, m, li, 0, R); + pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li + 1, R, T - R); }); + } + pipe_wait1(c); + if (L > 0) pipe_taps(c, m, L - 1, R, T - R); + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T), + praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out)); + RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out), RAD_W(m.w_lm), + brows(m.b_logits, batch->n_out)); + } +} + static void step(RadCtx* c, const RadBatch* batch) { Model& m = g_model[rad_rank(c)]; if (batch->enc) { @@ -1197,6 +1621,14 @@ static void step(RadCtx* c, const RadBatch* batch) { else m.df.context(c, batch); return; } + { + bool pipe_failed = false; + if (const int32_t* pcu = pipe_ready(c, batch, m, &pipe_failed)) { + step_pipelined(c, batch, m, pcu); + return; + } + if (pipe_failed) return; + } const int64_t T = batch->n_tok; /* The drafter conditions on a tapped layer's output, which the next layer overwrites: copy it * into the tap's column slice once the layer's residual is complete. */ @@ -1217,7 +1649,8 @@ static void step(RadCtx* c, const RadBatch* batch) { for (size_t li = 0; li < m.layers.size(); ++li) { const Layer& l = m.layers[li]; const bool last = li + 1 == m.layers.size(); - const bool far = m.fuse_mx_ar; + /* Per step: the fused junction sends the exact wire only (G3JunctionFP8::op_ar). */ + const bool far = m.fuse_mx_ar && ar_wire_is_exact(m.g, T); l.attn.step(c, batch, true, true, far); if (!far) l.attn.post(c, T); l.jf_am.step(c, T, far); @@ -1233,10 +1666,11 @@ static void step(RadCtx* c, const RadBatch* batch) { for (size_t li = 0; !m.fuse_mx && li < m.layers.size(); ++li) { const Layer& l = m.layers[li]; const bool last = li + 1 == m.layers.size(); - l.attn.step(c, batch, m.fuse, m.fuse, m.fuse_ar); - if (m.fuse) l.j_am.step(c, T, m.fuse_ar); - l.mlp.step(c, batch, m.fuse, m.fuse && !last, m.fuse_ar); - if (m.fuse && !last) l.j_ma.step(c, T, m.fuse_ar); + const bool ar = m.fuse_ar && ar_wire_is_exact(m.g, T); /* exact wire only, as above */ + l.attn.step(c, batch, m.fuse, m.fuse, ar); + if (m.fuse) l.j_am.step(c, T, ar); + l.mlp.step(c, batch, m.fuse, m.fuse && !last, ar); + if (m.fuse && !last) l.j_ma.step(c, T, ar); tap(li); } /* With fused junctions the last layer's tail ran unfused (tail_fused false), so the stream is diff --git a/arch/gemma4_bf16/gemma4_bf16.cpp b/arch/gemma4_bf16/gemma4_bf16.cpp index 65d5e0e6..382e99f6 100644 --- a/arch/gemma4_bf16/gemma4_bf16.cpp +++ b/arch/gemma4_bf16/gemma4_bf16.cpp @@ -8,11 +8,11 @@ * norm on the value, and a GELU (not SwiGLU) feed-forward. The final logits are soft-capped to * cap * tanh(x / cap). * - * Two draft models, whichever the container carries under `draft.`: Google's assistant head (a - * serial head over the trunk's own cache, the Gemma4Head below) or z-lab's DFlash drafter (a + * Three draft models, whichever the container carries under `draft.`: Google's assistant head (a + * serial head over the trunk's own cache, the Gemma4Head below), z-lab's DFlash drafter (a * five-layer block drafter with its own cache, reading the trunk's residual stream at six layers, - * arch/common/rad_gemma4_dflash.h) -- the 31B's z-lab/gemma-4-31B-it-DFlash proposes 15 tokens a - * pass where the assistant proposes one a round. + * arch/common/rad_gemma4_dflash.h; 15 tokens a pass on the 31B), or a DFlash2 drafter such as + * RedHatAI's gemma-4-31B-it-speculator.dflash2 (arch/common/rad_block_dflash2.h; 7 a pass). */ #include #include @@ -104,7 +104,25 @@ struct G4Linear { rad_op op = 0, op_q = 0; /* the quantised GEMM and, for w4a8, its activation quantiser */ rad_buf q8 = 0, s8 = 0; /* the int8 pair (i8 codes + f32 row scale) the quantiser writes */ int64_t N = 0, K = 0; - bool quant = false; /* true: w4a8 */ + bool quant = false; /* true: w4a8 / w8a8 over a per-row int8 activation */ + /* true: i8a8 as arch/gemma3's G3Linear: int8 codes with a bf16 scale per [1 x 128] (libquant + * `codes=i8 group=128 scale=bf16`) over quant_act_i8g, an activation scale per (row, 128). + * Gemma 4 E4B's activations carry a few channels 40-200 times the row's median (the down + * projection's input most), and one int8 scale a row spends its codes on them. There is no + * fused norm/quantiser at this grid, so the junctions stay off for a model that uses it. */ + bool i8g = false; + /* true: asymmetric int4 as arch/gemma3's G3Linear: u4 codes, a u8 zero point and an f16 scale + * per [1 x 128] (libquant `codes=u4 zero=u8 group=128 scale=f16`), gemm_nt_q at w4a8i8_asym + * over the same per-(row, 128) int8 activation as i8g. */ + bool a4 = false; + bool grouped() const { return i8g || a4; } + /* a4 at decode heights, as LinearFP8's w4 (rad_fp8.h): up to kA4Split rows the bf16 input is + * cast to f16 (`a16`) for w4a16_asym's skinny kernel; w4a8i8_asym has only a prefill kernel, + * which at one row does 16 times the matrix work and reads its weight a quarter as fast. */ + static constexpr int64_t kA4Split = 64; + int64_t a4_split = 0; /* rows up to which op_dec serves; 0: no decode band */ + rad_buf a16 = 0; + rad_op op_a16 = 0, op_dec = 0; /* Reads another linear's int8 pair. q, k and v quantise the same norm output on the same * per-row grid, so with `in_from` set at declare this linear reads that linear's pair and * declares no quantiser of its own: one dispatch instead of three. */ @@ -175,6 +193,73 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char * at w8a8 reads the same int8 activation and per-row scale as w4a8, so the quantiser is * shared. A recipe uses it for linears int4 hurts (attention, down_proj). */ const uint32_t cdt = known && enc.n_planes > 0 ? enc.plane[0].dtype : 0; + i8g = known && linear_is_w8(enc); + { + const RadEncPlane* sp = rad_enc_plane(&enc, "scale"); + const RadEncPlane* zp = rad_enc_plane(&enc, "zero"); + a4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 3 && !enc.transform[0] && + cdt == RAD_U4 && enc.plane[0].block[1] == 1 && sp && sp->dtype == RAD_F16 && + sp->block[0] == 1 && sp->block[1] == RAD_FP8_BLOCK && zp && zp->dtype == RAD_U8 && + zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK; + } + if (i8g || a4) { + if (N % 16 || K % RAD_FP8_BLOCK) { + fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; it takes rows in 16s and K in " + "whole %d-column activation scale groups\n", base, (long long)N, + (long long)K, RAD_FP8_BLOCK); + return RAD_E_INVAL; + } + if (a4) { + w = decl_view(b, wn, nullptr, "codes", RAD_U4, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K }, + RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + } else { + w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + ws = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, + RAD_ACCESS_PER_TOKEN, shard, grp, parts, np); + } + if (!w || !ws) return RAD_E_INVAL; + /* not an a4 linear's pair: below its decode band it writes none */ + if (in_from && in_from->grouped() && !in_from->a4 && in_from->q8 && in_from->K == K) { + q8 = in_from->q8; + s8 = in_from->s8; + shared_in = true; + } else { + q8 = decl_b(b, nm.f("%s.q8", base), RAD_I8, { g.max_tok, K }); + s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK }); + if (!q8 || !s8) return RAD_E_INVAL; + op_q = rw(b, RAD_OP(b, "quant_act_i8g", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + { a }, { q8, s8 }); + if (!op_q) return RAD_E_INVAL; + } + op = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), + RAD_STR("dtype", a4 ? "w4a8i8_asym" : "i8a8")), + RAD_WEIGHTS(w, ws)), + { q8, s8 }, { y }); + if (!op) return RAD_E_INVAL; + if (a4) { + a4_split = std::min(kA4Split, g.max_tok); + a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { a4_split, K }); + if (!a16) return RAD_E_INVAL; + op_a16 = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("n", K), + RAD_STR("from", g.dtype), RAD_STR("to", "f16")), + RAD_NOWEIGHTS), + { a }, { a16 }); + op_dec = rw(b, RAD_OP(b, "gemm_nt_q", + RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("N", N), RAD_INT("K", K), + RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a16_asym")), + RAD_WEIGHTS(w, ws)), + { a16 }, { y }); + if (!op_a16 || !op_dec) return RAD_E_INVAL; + } + return RAD_OK; + } if (known && g4_grid_w4(enc)) { if (N % 16 || K % 128) { fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a w4 weight takes rows in " @@ -216,8 +301,8 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char char en[256]; rad_enc_format(&enc, en, sizeof en); - fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16, w4a8 or w8a8 -- " - "neither matches\n", wn, en); + fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16, w4a8, w8a8, " + "int8 a 128 (i8a8) or asymmetric int4 a 128 -- none matches\n", wn, en); return RAD_E_DTYPE; } @@ -229,6 +314,16 @@ inline void G4Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const { if (!shared_in) RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE); gemm(c, y, T); + } else if (a4 && T <= a4_split) { + /* the decode band: f16 copy of the input, the skinny kernel; operands as LinearFP8's w4 */ + RAD_ISSUE_N(c, op_a16, T, brows(a, T), brows(a16, T)); + RAD_ISSUE_N(c, op_dec, T, brows(a16, T), RAD_NONE, RAD_W(w), RAD_W(ws), brows(y, T), + RAD_NONE, RAD_NONE); + } else if (grouped()) { + /* quant_act_i8g takes x, q, scale: no optional `asum`. */ + if (!shared_in) + RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T)); + gemm(c, y, T); } else RAD_ISSUE(c, op, brows(a, T), RAD_W(w), brows(y, T)); } @@ -239,18 +334,29 @@ inline void G4Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const { } inline void G4Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const { - if (!quant) { + if (a4 && n <= a4_split) { + RAD_ISSUE_N(c, op_a16, n, brow_slice(a, r0, n, K), brows(a16, n)); + RAD_ISSUE_N(c, op_dec, n, brows(a16, n), RAD_NONE, RAD_W(w), RAD_W(ws), + brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE); + return; + } + if (!quant && !grouped()) { RAD_ISSUE_N(c, op, n, brow_slice(a, r0, n, K), RAD_W(w), brow_slice(y, r0, n, N)); return; } - if (!shared_in) + const int64_t sw = grouped() ? K / RAD_FP8_BLOCK : 1; /* the scale plane's row width */ + if (!shared_in && grouped()) + RAD_ISSUE_N(c, op_q, n, brow_slice(a, r0, n, K), brow_slice(q8, r0, n, K), + brow_slice(s8, r0, n, sw)); + else if (!shared_in) RAD_ISSUE_N(c, op_q, n, brow_slice(a, r0, n, K), brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, 1), RAD_NONE); gemm_rows(c, y, r0, n); } inline void G4Linear::gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const { - RAD_ISSUE_N(c, op, n, brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, 1), RAD_W(w), RAD_W(ws), + const int64_t sw = grouped() ? K / RAD_FP8_BLOCK : 1; + RAD_ISSUE_N(c, op, n, brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, sw), RAD_W(w), RAD_W(ws), brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE); } @@ -265,6 +371,11 @@ struct Gemma4Attn { ClassGeom cls{}; int layer = 0; rad_kvgroup kv = 0; + /* KV sharing (num_kv_shared_layers, Gemma 4 E2B/E4B): a shared layer has no k or v of its own + * and attends over the cache of `kv_layer`, the last earlier layer of its class that keeps + * one. A layer with its own cache has kv_layer == layer. */ + bool shared = false; + int kv_layer = 0; rad_weight w_norm = 0, w_qn = 0, w_kn = 0, w_post = 0; /* the norms (always bf16) */ G4Linear ln_q{}, ln_k{}, ln_v{}, ln_o{}; /* the GEMM weights (bf16 or w4a8) */ @@ -297,12 +408,16 @@ struct Gemma4Attn { /* The linear whose int8 pair a junction writes, and whether every projection reads it. */ const G4Linear& ln_in() const { return fused ? ln_qkv : ln_q; } bool reads_pair() const { + if (shared) return ln_q.quant; return fused ? ln_qkv.quant : ln_q.quant && ln_k.shared_in && (!cls.has_v || ln_v.shared_in); } + /* `kv_src` < 0: the layer keeps its own cache; else the layer whose cache it reads. */ int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, - rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot); + rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot, + int kv_src = -1); + int declare_shared(RadBuilder* b, Names& nm, const char* pre); /* `entry_done`: a junction op already wrote this block's quantised input (ln_q's pair). * `tail_fused`: the caller issues the post-norm and the add as a junction op. */ void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false, @@ -323,8 +438,12 @@ struct Gemma4Attn { }; int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo, - rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot) { + rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot, + int kv_src) { g = geom; cls = cgeo; layer = l; kv = group; w = wire; + shared = kv_src >= 0; + kv_layer = shared ? kv_src : l; + if (shared) return declare_shared(b, nm, pre); const int64_t qd = cls.q_dim(), kvd = cls.kv_dim(); const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0); @@ -363,13 +482,18 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const if (cls.has_v) RAD_ARCH_TRY(map_concat(b, qkv_wn, { q_src, k_src, v_src })); else RAD_ARCH_TRY(map_concat(b, qkv_wn, { q_src, k_src })); { + /* one q|k|v GEMM wherever the weight is on a quantised grid: w4a8 / w8a8, i8a8 or a4 */ RadEncoding e{}; - fused = weight_enc(b, qkv_wn, &e) && g4_grid_w4(e); + fused = weight_enc(b, qkv_wn, &e) && (g4_grid_w4(e) || linear_is_w8(e) || + (rad_enc_is(&e, "affine") && e.n_planes == 3 && + e.plane[0].dtype == RAD_U4)); } if (fused) { if (!qkv_slot) return RAD_E_INVAL; if (!*qkv_slot) - *qkv_slot = decl_b(b, nm.f(cls.has_v ? "attn_qkvs" : "attn_qkvg"), g.act_dtype, + /* named by class, not by the value path: a global class with its own v (E2B/E4B, + * attention_k_eq_v false) has one too, and the two rows differ in width */ + *qkv_slot = decl_b(b, nm.f(cls.head_ladder ? "attn_qkvg" : "attn_qkvs"), g.act_dtype, {g.max_tok, qkvd}); w.qkv = *qkv_slot; if (cls.has_v) @@ -589,6 +713,78 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const return RAD_OK; } +/* A KV-shared layer (transformers' Gemma4TextAttention with is_kv_shared_layer): q_proj, the per-head + * q norm and the class's rotary, attention over the source layer's cache, o_proj and the two norms. + * No k or v projection, no k or v norm and no cache store: the source layer, earlier in the same + * step, wrote the keys and values these queries read. The checkpoint's k_proj / v_proj / k_norm of + * these layers (the "frozen shared kv" file) are unused, as in the reference. */ +int Gemma4Attn::declare_shared(RadBuilder* b, Names& nm, const char* pre) { + const int l = layer; + const int64_t qd = cls.q_dim(); + fused = false; + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l))); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_post_norm.weight", l), nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l))); + w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_qn = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_BF16, {cls.head_dim}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + w_post = decl_w(b, nm.f("blk.%d.attn_post_norm.weight", l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + RAD_ARCH_TRY(ln_q.declare(b, nm, g, nm.f("blk.%d.attn_q", l), + { nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l) }, + qd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.q)); + RAD_ARCH_TRY(ln_o.declare(b, nm, g, nm.f("blk.%d.attn_o", l), + { nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l) }, + g.n_embd, qd, RAD_SHARD_COL, grp_layer(l), w.attn, w.h)); + op_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + op_qn = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * cls.n_head), RAD_INT("n", cls.head_dim), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_qn)), + {w.q}, {w.q}); + op_rq = rw(b, RAD_OP(b, "rope", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim), + RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", 0), + RAD_F64("theta", cls.theta), RAD_F64("scale", cls.scale), + RAD_STR("mode", "neox"), RAD_INT("rotary_dim", cls.n_rot), + RAD_STR("ladder", cls.head_ladder ? "head" : "rotary")), + RAD_NOWEIGHTS), + {w.q}, {w.q}); + op_attn = rw(b, RAD_OP(b, "attn_paged", + RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), + RAD_INT("head_dim", cls.head_dim), + RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1), + RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head), + RAD_INT("block_size", RAD_KV_BLOCK), + RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx), + RAD_F64("scale", 1.0), + RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)), + RAD_NOWEIGHTS), + {w.q}, {w.attn}); + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + op_post = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_post)), + {w.h}, {w.h}); + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + return (op_norm && op_qn && op_rq && op_attn && op_post && op_add) ? RAD_OK : RAD_E_INVAL; +} + /* ---- Prefetch beside the reductions (prefetch_beside, rad_arch.h). The all-reduce in front of * each GEMM leaves the card's memory idle for its round trip (~20 us at a DFlash2 verify's rows on * 4x R9700), so the trunk reads the next GEMM's leading bytes in that window -- gate_up's after @@ -609,7 +805,13 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta bool ar_fused) const { const int64_t T = batch->n_tok; - if (fused) { + if (shared) { + if (entry_done) ln_q.gemm(c, w.q, T); + else { + RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + ln_q.step(c, w.h, w.q, T); + } + } else if (fused) { if (!entry_done) RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); if (entry_done) ln_qkv.gemm(c, w.qkv, T); else ln_qkv.step(c, w.h, w.qkv, T); @@ -637,6 +839,10 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta } void Gemma4Attn::project(RadCtx* c, int64_t r0, int64_t n) const { + if (shared) { + ln_q.gemm_rows(c, w.q, r0, n); + return; + } if (fused) { ln_qkv.gemm_rows(c, w.qkv, r0, n); return; @@ -657,6 +863,19 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const { const int32_t* used = kvb ? kvb->seqused : nullptr; const int64_t T = batch->n_tok; const int64_t qd = cls.q_dim(), kvd = cls.kv_dim(); + if (shared) { + /* q only: its norm and rotary, then attention over the source layer's cache. */ + RAD_ISSUE_N(c, op_qn, T * cls.n_head, brows(w.q, T), RAD_W(w_qn), brows(w.q, T)); + RAD_ISSUE(c, op_rq, brows(w.q, T), rope_posmc(g, batch, T)); + RAD_ISSUE_N(c, op_attn, batch->max_q_len, + brows(w.q, T), kv_cache(kv, kv_layer), + praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), + praw(used, RAD_I32, batch->n_seq), + RAD_NONE, RAD_NONE, + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), + brows(w.attn, T)); + return; + } /* q, k and v where the prologue works on them: their own buffers, or on a fused layer with the * one-op prologue the row's column slices (a k_eq_v class's v is its own buffer either way). */ const bool row = fused && op_qnr; @@ -869,43 +1088,24 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai /* ---- one residual junction as one op: [post-norm of the branch `x`, the add into `res`, the * layer scalar,] the next block's norm and its int8 quantiser (libr4d `rmsnorm_quant_i8`). With * `res` null it is the plain norm of `x`, the first block's entry. */ -/* The four-rank fold's band. libr4d's exact all-reduce is a one-shot up to this many elements - * (R4D_AR_WIDE_ONESHOT_MAX_ELEMS) and a two-shot above, and the fused junction at four ranks is - * that one-shot with the junction as its epilogue: three times the message per rank on the link, - * which pays at decode heights and not at a prefill's. So at four ranks op_ar serves the rows a - * one-shot would, 97 at 5376, and a taller step issues the all-reduce and the junction apart. - * - * Within that band the fold pays only at the bottom. On 4x R9700 (2026-10-17, same image) a plain - * decode step (1 row) ran 5.6% slower without it (89 against 94 tok/s), and a DFlash verify - * (16 rows) 9% faster (300 against 276): at 16 rows the standalone all-reduce is the exact - * two-shot, while the fold's one block a row each takes a fenced handshake. The per-row costs - * cross near 4-5 rows. From 5 rows libr4d's four-rank row takes its tail form instead (axis - * `tail`): the standalone two-shot with the junction run after it in the same launch, behind a - * card-local count, so the junction costs neither a handshake nor a launch. With it a DFlash2 - * verify (8 rows) folds and gains ~1% (348 / 258 / 187 / 516 against 345 / 255 / 185 / 511 tok/s, - * code / prose / story / long, 4x R9700; replies identical), where the one-shot fold there lost - * 6%. So the fold serves up to kAr4FoldRows rows, a z-lab DFlash verify's 16 included, and a - * taller step issues the pair. */ -static constexpr int64_t kArOneShotElems = 524288; +/* The four-rank fold's band. libr4d's four-rank row serves it in three forms, all byte-identical + * to all_reduce + rmsnorm_quant_i8. Up to 4 rows it is the exact one-shot with the junction as its + * epilogue: three times the message per rank and one fenced handshake a row, which wins at one row + * (plain decode about 5% faster on 4x R9700) and loses to the standalone two-shot by 16. From 5 + * rows it is that two-shot with the junction as its tail (axis `tail`), behind a card-local count, + * so the junction costs neither a handshake nor a launch. Above kAr4FoldRows a step issues the + * pair. */ static constexpr int64_t kAr4FoldRows = 16; -/* From kArSpMinRows rows to the same band's top, libr4d's four-rank row takes `sp` instead: the - * all-reduce split around the junction. Each rank reduces only the rows it owns (a quarter, in - * rank order), runs the junction on them and gathers the int8 codes the next GEMM reads, so the - * second hop carries a byte a column instead of two and the junction a quarter of the rows. The - * fold and the sums are the whole form's, so q and the scales are byte for byte the same; the - * residual stream then holds this rank's rows only, which is all the next junction reads. A - * junction whose stream anything else reads next asks for the residual on every row too (sp 2): +/* From kArSpMinRows rows to kArSpMaxRows, libr4d's four-rank row takes `sp`: the all-reduce split + * around the junction. Each rank reduces only the rows it owns (a quarter, in rank order), runs the + * junction on them and gathers the int8 codes the next GEMM reads, so the second hop carries a byte + * a column instead of two and the junction runs on a quarter of the rows. q and the scales are + * the whole form's bytes; the residual stream then holds this rank's rows only, which is all the + * next junction reads. A junction whose stream anything else reads next asks for every row (sp 2): * the layers the drafter taps, and the last layer's attention junction, since that layer's - * feed-forward closes with its own all-reduce, post-norm and add over every row. One launch at a - * time on 4x R9700 (2026-10-19): 19.8 against 21.9 us at 4 rows of 5376 (the one-shot fold), 22.9 - * against 24.5 at 8 and 30.8 against 34.9 at 16 (the tail), 72.3 against 89.2 at 64. Below 4 rows - * a rank would idle (31.7 against 18.7 us at one). - * - * In the engine it pays only where it replaces the fold: a DFlash2 verify (8 rows) ran 402 / 297 / - * 216 / 603 tok/s code / prose / story / long against 392 / 290 / 210 / 585, replies identical, - * but steps of 24-64 rows, where the pair runs instead, lost ~10% under load (4 users 588 against - * 698 aggregate, 8 users 781 against 867; 12 users even; 4x R9700, 2026-10-19). So it serves to - * kArSpMaxRows, the fold's band, within the one-shot's. */ + * feed-forward closes with its own all-reduce, post-norm and add over every row. Below 4 rows a + * rank would idle (on 4x R9700, 31.7 against 18.7 us at one row); at 24-64 rows, where the pair + * runs, the split form lost about 10% of aggregate throughput under load. */ static constexpr int64_t kArSpMinRows = 4; static constexpr int64_t kArSpMaxRows = 16; @@ -941,11 +1141,10 @@ struct G4Junction { rad_op_writes(b, op, wr, res ? 3 : 2); /* With the all-reduce in front, at two or four ranks on the exact wire: `x` is then a * rank's partial sum of a column-sharded linear. With the lossy wire allowed, the - * standalone all-reduce is kept, since it may choose that wire. At four ranks the fold is - * the one-shot's and serves only its band (kArOneShotElems, kAr4FoldRows). */ + * standalone all-reduce is kept, since it may choose that wire. At four ranks the fold + * serves steps of up to kAr4FoldRows rows. */ const bool four = g.world == 4; - const int64_t hi = four ? std::min(kAr4FoldRows, std::min(g.max_tok, kArOneShotElems / g.n_embd)) - : g.max_tok; + const int64_t hi = four ? std::min(kAr4FoldRows, g.max_tok) : g.max_tok; if (res && g.wire_exact && (g.world == 2 || four) && hi >= 1 && rad_op_declared(b, "ar_rmsnorm_quant_i8")) { const RadParam pa[] = { RAD_RANGE("M", 1, hi), RAD_INT("n", g.n_embd), @@ -960,8 +1159,7 @@ struct G4Junction { } /* The split form from kArSpMinRows to kArSpMaxRows rows. It needs the post-norm, as * every trunk junction past the first has; `x` is declared written, as the fold's. */ - const int64_t top = std::min( - std::min(g.max_tok, kArOneShotElems / g.n_embd), kArSpMaxRows); + const int64_t top = std::min(g.max_tok, kArSpMaxRows); if (op_ar && four && wp && top >= kArSpMinRows) { const RadParam ps[] = { RAD_RANGE("M", 1, top), RAD_INT("n", g.n_embd), RAD_F64("eps", g.eps), RAD_INT("world_size", g.world), @@ -1468,6 +1666,11 @@ struct Layer { Gemma4Mlp mlp{}; rad_weight w_scalar = 0; /* the per-layer [1] residual scalar, `cur = cur * scalar` */ rad_op op_scale = 0; + /* Per-layer embeddings (Gemma 4 E2B/E4B), after the feed-forward's residual add and before the + * scalar: x += norm(proj(gelu(gate(x)) * pli[l])). `ple_post` is the norm's gain. */ + G4Linear ln_pg{}, ln_pp{}; + rad_weight w_ple_post = 0; + rad_op op_ple_act = 0, op_ple_post = 0, op_ple_add = 0; /* The fused junctions (see "Residual junctions" above): attention -> this layer's * feed-forward, and this layer's feed-forward -> the next layer's attention, scalar included. * The last layer has no j_ma: its stream goes to the final norm, which feeds the lm_head, not @@ -1506,6 +1709,22 @@ struct Model { rad_weight w_tok = 0, w_out = 0, w_lm = 0; rad_op op_embed = 0, op_embed_ar = 0, op_final = 0, op_gather = 0, op_logits = 0, op_cap = 0; + /* Per-layer embeddings (hidden_size_per_layer_input > 0): the token-identity table + * (embed_tokens_per_layer, n_layer x n_ple wide), the context projection of the scaled + * embedding and its per-(token, layer) norm, combined into `b_ple` [max_tok, n_layer * n_ple] + * that every layer reads its slice of. */ + int64_t n_ple = 0; + rad_weight w_ple_tok = 0, w_ple_norm = 0; + G4Linear ln_ple_proj{}; + rad_buf b_ple = 0, b_ple_tok = 0, b_pg = 0; + rad_op op_ple_tok = 0, op_ple_norm = 0, op_ple_add = 0; + /* An image's placeholder positions take the token-identity row of pad_token_id, as the + * reference looks them up (Gemma4Model.forward: llm_input_ids = pad where multimodal): that row + * times sqrt(n_ple), made as fill(sqrt(n_ple)) * the row, scattered over the image rows. */ + rad_weight w_ple_pad = 0; + rad_buf b_ple_pad = 0; + rad_op op_ple_pfill = 0, op_ple_pmul = 0, op_ple_pscat = 0; + std::vector layers; /* The assistant head, declared only when the container carries one and the deployment @@ -1768,7 +1987,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c Names& nm = m.nm; /* ---- geometry RadModelMeta does not name. */ - const int64_t kv_g_all = meta_text_geti(meta, "num_global_key_value_heads", 0); + /* num_global_key_value_heads may be null (Gemma 4 E2B/E4B): the global layers then take the + * model's num_key_value_heads, as transformers' per-layer config does. */ + const int64_t kv_g_all = meta_text_geti(meta, "num_global_key_value_heads", + meta_text_geti(meta, "num_key_value_heads", 0)); const int64_t head_g = meta_text_geti(meta, "global_head_dim", 0); const int64_t sliding_win = meta_text_geti(meta, "sliding_window", 0); const int64_t kv_shared = meta_text_geti(meta, "num_kv_shared_layers", 0); @@ -1798,12 +2020,28 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } if (!(softcap > 0.0)) { fprintf(stderr, "radiance: gemma4: final_logit_softcapping is required\n"); return RAD_E_INVAL; } if (kv_shared < 0) { fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld is negative\n", (long long)kv_shared); return RAD_E_INVAL; } - if (kv_shared > 0) { - fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld needs a shared-KV reuse path; refusing\n", - (long long)kv_shared); - return RAD_E_UNSUPPORTED; + if (kv_shared >= g.n_layer) { + fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld leaves no layer with a cache of " + "its own (%lld layers)\n", (long long)kv_shared, (long long)g.n_layer); + return RAD_E_INVAL; } if (sliding_win <= 0) { fprintf(stderr, "radiance: gemma4: sliding_window %lld is required\n", (long long)sliding_win); return RAD_E_INVAL; } + m.n_ple = meta_text_geti(meta, "hidden_size_per_layer_input", 0); + if (m.n_ple < 0) { fprintf(stderr, "radiance: gemma4: hidden_size_per_layer_input %lld is negative\n", (long long)m.n_ple); return RAD_E_INVAL; } + if (m.n_ple > 0) { + const int64_t v_ple = meta_text_geti(meta, "vocab_size_per_layer_input", g.n_vocab_all); + if (g.world > 1) { + fprintf(stderr, "radiance: gemma4: per-layer embeddings (hidden_size_per_layer_input %lld) " + "are served at one rank only; this model is small enough for one card\n", + (long long)m.n_ple); + return RAD_E_UNSUPPORTED; + } + if (v_ple != g.n_vocab_all) { + fprintf(stderr, "radiance: gemma4: vocab_size_per_layer_input %lld differs from the " + "vocabulary (%lld)\n", (long long)v_ple, (long long)g.n_vocab_all); + return RAD_E_UNSUPPORTED; + } + } if (!(prf > 0.0)) prf = 1.0; const int64_t n_rot_g = (int64_t)(head_g * prf + 0.5); if (n_rot_g <= 0 || n_rot_g > head_g || (n_rot_g & 1)) { @@ -1828,6 +2066,26 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c int n_global = 0; for (int v : is_global) n_global += v; + /* KV sharing: from layer n_layer - num_kv_shared_layers on, a layer keeps no cache and reads the + * last earlier non-shared layer of its own class (transformers' store_full_length_kv; E4B: + * sliding layers read 22, full layers 23). kv_src[l] is that layer, or -1 for an own cache. */ + const int64_t first_shared = g.n_layer - kv_shared; + std::vector kv_src((size_t)g.n_layer, -1); + if (kv_shared > 0) { + int last_s = -1, last_f = -1; + for (int64_t l = 0; l < first_shared; ++l) (is_global[(size_t)l] ? last_f : last_s) = (int)l; + for (int64_t l = first_shared; l < g.n_layer; ++l) { + const int src = is_global[(size_t)l] ? last_f : last_s; + if (src < 0) { + fprintf(stderr, "radiance: gemma4: KV-shared layer %lld is %s and no earlier layer of " + "that class keeps a cache\n", (long long)l, + is_global[(size_t)l] ? "full" : "sliding"); + return RAD_E_INVAL; + } + kv_src[(size_t)l] = src; + } + } + /* The sliding class comes from geom_from (head_dim 256, 16 kv heads, full rotation, theta_s); * the global class is built from the container header. */ m.cs.n_head = g.n_head; m.cs.n_head_kv = g.n_head_kv; m.cs.head_dim = g.head_dim; @@ -1929,6 +2187,78 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_NOWEIGHTS), {m.b_x}, {m.b_x}); + /* ---- per-layer embeddings (transformers' get_per_layer_inputs / project_per_layer_inputs): + * tok = embed_tokens_per_layer[id] * sqrt(n_ple) (bf16, sqrt(256) = 16) + * ctx = rmsnorm( (e @ W_proj^T) * n_embd^-0.5 ) per (token, layer) over n_ple, gain w_norm + * pli = (ctx + tok) * 2^-0.5 + * `e` is the scaled embedding (after any image rows are scattered in). The projection's scale + * is folded into the norm's eps, as embgemma2 does: rmsnorm(s x, eps) = rmsnorm(x, eps / s^2), + * so no bf16 rounding of s x. The table is read a row a token, so the placement puts it in the + * pinned host pool by default (--embedding-placement ram), off the card. */ + if (m.n_ple > 0) { + const int64_t P = g.n_layer * m.n_ple; + RAD_ARCH_TRY(map_copy(b, nm.f("ple_token_embd.weight"), + nm.ckpt("model.language_model.embed_tokens_per_layer.weight"))); + RAD_ARCH_TRY(map_copy(b, nm.f("ple_proj_norm.weight"), + nm.ckpt("model.language_model.per_layer_projection_norm.weight"))); + m.w_ple_tok = decl_w(b, nm.f("ple_token_embd.weight"), RAD_BF16, {g.n_vocab, P}, + RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model()); + m.w_ple_norm = decl_w(b, nm.f("ple_proj_norm.weight"), RAD_BF16, {m.n_ple}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model()); + m.b_ple = decl_b(b, nm.f("ple_in"), g.act_dtype, {g.max_tok, P}); + m.b_ple_tok = decl_b(b, nm.f("ple_tok"), g.act_dtype, {g.max_tok, P}); + m.b_pg = decl_b(b, nm.f("ple_gate"), g.act_dtype, {g.max_tok, m.n_ple}); + if (!m.w_ple_tok || !m.w_ple_norm || !m.b_ple || !m.b_ple_tok || !m.b_pg) return RAD_E_INVAL; + m.op_ple_tok = rw(b, RAD_OP(b, "embed_lookup", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", P), + RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype), + RAD_INT("vocab_offset", g.vocab_off), + RAD_F64("mult", std::sqrt((double)m.n_ple))), + RAD_WEIGHTS(m.w_ple_tok)), + {}, {m.b_ple_tok}); + RAD_ARCH_TRY(m.ln_ple_proj.declare(b, nm, g, nm.f("ple_model_proj"), + { nm.ckpt("model.language_model.per_layer_model_projection.weight") }, + P, g.n_embd, RAD_SHARD_NONE, grp_model(), m.b_x, m.b_ple)); + m.op_ple_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_layer), RAD_INT("n", m.n_ple), + RAD_F64("eps", (double)g.eps * (double)g.n_embd), + RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_ple_norm)), + {m.b_ple}, {m.b_ple}); + m.op_ple_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P), + RAD_STR("dtype", g.dtype), RAD_F64("div", std::sqrt(2.0))), + RAD_NOWEIGHTS), + {m.b_ple, m.b_ple_tok}, {m.b_ple}); + if (!m.op_ple_tok || !m.op_ple_norm || !m.op_ple_add) return RAD_E_INVAL; + if (m.op_mm) { + const int pad = (int)meta_text_geti(meta, "pad_token_id", 0); + RAD_ARCH_TRY(map_slice(b, nm.f("ple_pad_row.weight"), + nm.ckpt("model.language_model.embed_tokens_per_layer.weight"), pad)); + m.w_ple_pad = decl_w(b, nm.f("ple_pad_row.weight"), RAD_BF16, {P}, RAD_ACCESS_PER_TOKEN, + RAD_SHARD_NONE, grp_model()); + m.b_ple_pad = decl_b(b, nm.f("ple_pad"), g.act_dtype, {g.max_tok, P}); + if (!m.w_ple_pad || !m.b_ple_pad) return RAD_E_INVAL; + m.op_ple_pfill = rw(b, RAD_OP(b, "fill", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P), + RAD_STR("dtype", g.dtype), + RAD_F64("value", std::sqrt((double)m.n_ple))), + RAD_NOWEIGHTS), + {}, {m.b_ple_pad}); + m.op_ple_pmul = rw(b, RAD_OP(b, "mul_weight", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P), + RAD_STR("dtype", g.dtype), RAD_INT("scalar", 0)), + RAD_WEIGHTS(m.w_ple_pad)), + {m.b_ple_pad}, {m.b_ple_pad}); + m.op_ple_pscat = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_ple_pad, m.b_ple_tok}, {m.b_ple_tok}); + if (!m.op_ple_pfill || !m.op_ple_pmul || !m.op_ple_pscat) return RAD_E_INVAL; + } + } + /* ---- the layers. */ Gemma4Attn::Wire sw{}; sw.x = m.b_x; sw.h = m.b_h; sw.q = m.b_qs; sw.k = m.b_ks; sw.v = m.b_vs; sw.attn = m.b_attns; Gemma4Attn::Wire gw{}; gw.x = m.b_x; gw.h = m.b_h; gw.q = m.b_qg; gw.k = m.b_kg; gw.v = m.b_vg; gw.attn = m.b_atting; @@ -1941,9 +2271,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c const ClassGeom& cgeo = lay.global ? m.cg : m.cs; const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s; const Gemma4Attn::Wire& aw = lay.global ? gw : sw; - RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg)); + /* A KV-shared layer is not bound: the group's pages hold only the layers that write. */ + if (kv_src[(size_t)l] < 0) RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg)); RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre, - lay.global ? &m.b_qkvg : &m.b_qkvs)); + lay.global ? &m.b_qkvg : &m.b_qkvs, kv_src[(size_t)l])); RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, pre)); /* The per-layer scalar: `cur = cur * scalar`, a [1] bf16 over the residual stream. */ @@ -1957,11 +2288,48 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_WEIGHTS(lay.w_scalar)), {mw.x}, {mw.x}); + /* The per-layer embedding branch (transformers' Gemma4TextDecoderLayer, after the + * feed-forward's residual add): gate n_embd -> n_ple, gelu_tanh times this layer's slice of + * `ple_in`, projection back to n_embd into `h`, its norm, the residual add. The scalar + * follows it. */ + if (m.n_ple > 0) { + RAD_ARCH_TRY(lay.ln_pg.declare(b, nm, g, nm.f("blk.%d.ple_gate", (int)l), + { nm.ckpt("%s.%lld.per_layer_input_gate.weight", pre, (long long)l) }, + m.n_ple, g.n_embd, RAD_SHARD_NONE, grp_layer((int)l), + m.b_x, m.b_pg)); + RAD_ARCH_TRY(lay.ln_pp.declare(b, nm, g, nm.f("blk.%d.ple_proj", (int)l), + { nm.ckpt("%s.%lld.per_layer_projection.weight", pre, (long long)l) }, + g.n_embd, m.n_ple, RAD_SHARD_NONE, grp_layer((int)l), + m.b_pg, m.b_h)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_post_norm.weight", (int)l), + nm.ckpt("%s.%lld.post_per_layer_input_norm.weight", pre, (long long)l))); + lay.w_ple_post = decl_w(b, nm.f("blk.%d.ple_post_norm.weight", (int)l), RAD_BF16, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer((int)l)); + lay.op_ple_act = rw(b, RAD_OP(b, "act_mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", m.n_ple), + RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_pg, m.b_ple}, {m.b_pg}); + lay.op_ple_post = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_ple_post)), + {m.b_h}, {m.b_h}); + lay.op_ple_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}); + if (!lay.w_ple_post || !lay.op_ple_act || !lay.op_ple_post || !lay.op_ple_add) + return RAD_E_INVAL; + } + /* The tap: a row copy of the layer's output (after the scalar, HF's hidden_states[l + 1]) * into the column slice the tap owns. It is declared here, in the layer it is issued - * after, because the buffer planner's liveness is declaration order. A tap declared once - * after the trunk made `dflash_src` look born at its end and free to share with what every - * layer writes, which on arch/gemma4 cost 98% of the drafts with the reply still fluent. */ + * after, because the buffer planner's liveness is declaration order. Declared after the + * trunk, `dflash_src` would look born at its end and free to share with what every layer + * writes: the drafts would fail while the reply stays fluent. */ for (int t = 0; t < m.n_taps; ++t) if (m.tap_layer[t] == (int)l && !lay.op_tap) lay.op_tap = rw(b, RAD_OP(b, "cast", @@ -1996,7 +2364,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c ok = lay.j_am.op != 0; if (ok && l + 1 < m.n_main) { const Layer& nx = m.layers[(size_t)l + 1]; - RAD_ARCH_TRY(lay.j_ma.declare(b, g, m.b_h, m.b_x, nx.attn.w_norm, lay.mlp.w_post, + /* With per-layer embeddings the junction closes the PLE branch instead of the + * feed-forward (whose post-norm and add then run apart): the branch's norm, + * its add, the scalar, the next norm and quantiser, in the reference's order. */ + RAD_ARCH_TRY(lay.j_ma.declare(b, g, m.b_h, m.b_x, nx.attn.w_norm, + m.n_ple > 0 ? lay.w_ple_post : lay.mlp.w_post, lay.w_scalar, nx.attn.ln_in(), tapped)); ok = lay.j_ma.op != 0; } @@ -2019,8 +2391,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * attention block's all-reduce and the next layer's q|k|v's (q alone, unfused; after the last * layer, the lm_head's) beside the feed-forward's (gemma4::kPrefetchBytes), then down_proj's * first 9 MB beside the attention (gemma4::kPrefetchDownBytes). Only at more than one rank, - * where there are reductions to sit beside. RADIANCE_PREFETCH=0 declares none - * (decl_prefetch). */ + * where there are reductions to sit beside. */ if (g.world > 1 && rad_op_declared(b, "prefetch")) { for (size_t l = 0; l < m.layers.size(); ++l) { Layer& lay = m.layers[l]; @@ -2046,9 +2417,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * the bits it gives the whole. The buffer the second lane reduces in place is taken out of the * arena's sharing, which the runtime asks of every buffer a second lane touches; it lives * across the whole trunk already. */ - const char* ov = std::getenv("RADIANCE_GEMMA4_OVERLAP"); /* 0: every step whole */ - const bool ov_off = ov && !std::strcmp(ov, "0"); - m.overlap = !ov_off && g.world > 1 && g.wire_exact && m.fuse && g.max_tok >= 2 * kOverlapRows; + m.overlap = g.world > 1 && g.wire_exact && m.fuse && g.max_tok >= 2 * kOverlapRows; for (const Layer& lay : m.layers) m.overlap = m.overlap && lay.attn.op_ar && lay.mlp.op_ar; if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h)); @@ -2081,11 +2450,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * feed-forward reduction only slice A's junction and q|k|v. Per slice (A's projection, * prologue, attention and o_proj, then B's), each of the four reductions sits beside a whole * block: on 4x R9700 the exact two-shot of a 1024-row slice takes ~1.05 ms alone and ~1.4x - * that beside any card-filling compute (a four-card microbenchmark, 2026-10-18). Slice A's - * attention reads its context end from kv_len_trim, one a KV group. A one-sequence step only - * (the slices' rows are then one sequence's), with the one-launch prologue and no - * multi-component rotary. Byte-identical: every greedy reply matches the whole attention's - * (4x R9700, two rounds, and 16 of 16 fresh starts on a 5310-token prompt); prefill +5%. */ + * that beside card-filling compute, so the reductions want whole blocks to hide behind. Slice + * A's attention reads its context end from kv_len_trim, one a KV group. A one-sequence step + * only (the slices' rows are then one sequence's), with the one-launch prologue and no + * multi-component rotary. A slice's attention rows see exactly the keys they see in the whole + * step, so the output is the whole attention's byte for byte. */ if (m.overlap) { bool ok = !g.rope_mc && rad_op_declared(b, "kv_len_trim"); for (const Layer& lay : m.layers) ok = ok && lay.attn.slicable(); @@ -2136,7 +2505,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * the deployment speculates; otherwise its ~0.5 GB of weights stay off the card. */ if (ctx->max_spec > 0 && has_assistant(meta)) { int last_s = -1, last_f = -1; - for (int64_t l = 0; l < m.n_main; ++l) (is_global[(size_t)l] ? last_f : last_s) = (int)l; + /* the last layer of each class that keeps a cache (a KV-shared layer reads another's) */ + for (int64_t l = 0; l < m.n_main; ++l) + if (kv_src[(size_t)l] < 0) (is_global[(size_t)l] ? last_f : last_s) = (int)l; RAD_ARCH_TRY(m.head.declare(b, nm, meta, g, m.cs, m.cg, m.kv_s, m.kv_g, last_s, last_f, m.n_main, m.w_tok, m.b_h, m.b_logits)); m.have_head = true; @@ -2196,6 +2567,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c g.rank, g.world, (long long)g.n_layer, (long long)n_global, (long long)(g.n_layer - n_global), (long long)sliding_win, (long long)g.n_head, (long long)g.head_dim, (long long)g.n_head, (long long)head_g); + if (kv_shared > 0) { + int src_s = -1, src_f = -1; + for (int64_t l = first_shared; l < g.n_layer; ++l) + (is_global[(size_t)l] ? src_f : src_s) = kv_src[(size_t)l]; + rad_note(b, "KV sharing: layers %lld..%lld keep no cache and read the last earlier layer of " + "their class (sliding %d, full %d); %lld of %lld layers hold KV", + (long long)first_shared, (long long)(g.n_layer - 1), src_s, src_f, + (long long)first_shared, (long long)g.n_layer); + } { int64_t n_fused = 0, n_row = 0, n_dec = 0, dec_hi = 0; for (const Layer& lay : m.layers) { @@ -2220,8 +2600,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c (long long)(2 * kOverlapRows)); else rad_note(b, "prefill overlap: off (%s)", - ov_off ? "RADIANCE_GEMMA4_OVERLAP=0" - : !g.wire_exact ? "the lossy all-reduce wire" + !g.wire_exact ? "the lossy all-reduce wire" : !m.fuse ? "the residual junctions are not fused" : "a step holds fewer than two slices"); } @@ -2445,6 +2824,23 @@ static void step(RadCtx* c, const RadBatch* batch) { praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, batch->n_tok)); const int64_t T = batch->n_tok; + if (m.n_ple > 0) { + RAD_ISSUE(c, m.op_ple_tok, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_ple_tok), + brows(m.b_ple_tok, T)); + if (m.op_ple_pscat && batch->n_mm_rows > 0) { + const int64_t nm_rows = batch->n_mm_rows; + RAD_ISSUE_N(c, m.op_ple_pfill, nm_rows, brows(m.b_ple_pad, nm_rows)); + RAD_ISSUE_N(c, m.op_ple_pmul, nm_rows, brows(m.b_ple_pad, nm_rows), RAD_W(m.w_ple_pad), + brows(m.b_ple_pad, nm_rows)); + RAD_ISSUE_N(c, m.op_ple_pscat, nm_rows, brows(m.b_ple_pad, nm_rows), + praw(batch->mm_rows, RAD_I32, nm_rows), brows(m.b_ple_tok, T)); + } + m.ln_ple_proj.step(c, m.b_x, m.b_ple, T); + /* [T, n_layer * n_ple] read as [T * n_layer, n_ple]: one norm row per (token, layer). */ + RAD_ISSUE_N(c, m.op_ple_norm, T * m.g.n_layer, brows(m.b_ple, T), RAD_W(m.w_ple_norm), + brows(m.b_ple, T)); + RAD_ISSUE(c, m.op_ple_add, brows(m.b_ple, T), brows(m.b_ple_tok, T), brows(m.b_ple, T)); + } const int64_t cut = split_at(m, T); if (cut > 0) trunk_overlap(c, m, batch, cut); else if (m.fuse) m.j0.step(c, T); @@ -2455,7 +2851,18 @@ static void step(RadCtx* c, const RadBatch* batch) { const bool last = li + 1 == m.layers.size(); l.attn.step(c, batch, m.fuse, m.fuse, far); if (m.fuse) l.j_am.step(c, T, far); - l.mlp.step(c, batch, m.fuse, m.fuse && !last, far); + const bool ple = m.n_ple > 0; + l.mlp.step(c, batch, m.fuse, m.fuse && !last && !ple, far); + if (ple) { + l.ln_pg.step(c, m.b_x, m.b_pg, T); + RAD_ISSUE(c, l.op_ple_act, brows(m.b_pg, T), + bcol(m.b_ple, (int64_t)li * m.n_ple, m.n_ple, T), brows(m.b_pg, T)); + l.ln_pp.step(c, m.b_pg, m.b_h, T); + if (!(m.fuse && !last)) { + RAD_ISSUE(c, l.op_ple_post, brows(m.b_h, T), RAD_W(l.w_ple_post), brows(m.b_h, T)); + RAD_ISSUE(c, l.op_ple_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T)); + } + } if (m.fuse && !last) { /* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */ l.j_ma.step(c, T, far); @@ -2521,7 +2928,7 @@ RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0", "Gemma 4 dense (text and images), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) " "release: sliding-window and proportional-RoPE global attention over a plain " "RMSNorm stream with GELU feed-forward, per-layer scalar scaling and soft-capped " - "logits; Google's assistant head or z-lab's DFlash drafter") + "logits; Google's assistant head, z-lab's DFlash drafter or a DFlash2 drafter") RAD_ARCH_CHAT_FORMAT(gemma4_bf16) RAD_ARCH_PROBE(gemma4_bf16) #endif diff --git a/arch/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index e2cfdc04..299a64dc 100644 --- a/arch/glm5next/glm5next.cpp +++ b/arch/glm5next/glm5next.cpp @@ -46,6 +46,10 @@ struct Layer { struct Model { Names nm{}; Geom g{}; + /* The MLA's split of a prefill-sized step under TP (RadBuildCtx::tp_attn_rows). The head + * form declares none of the row form's full-width weights (1.29 GiB a card at eight ranks); + * the row form is opt-in because it is not bit-identical to it (docs/ARCHITECTURES.md). */ + GlmMla::Form form = GlmMla::Form::heads; std::vector layers; rad_kvgroup latent = 0, index = 0, tail = 0, state = 0, conv = 0; /* The streams and the step's stream-wide buffers. */ @@ -102,7 +106,11 @@ static int stream_buffers(RadBuilder* b, Model& m) { m.h0 = decl_b(b, nm.f("manifold"), RAD_BF16, { T, 16384 }); m.h1 = decl_b(b, nm.f("manifold_mid"), RAD_BF16, { T, 16384 }); m.x = decl_b(b, nm.f("collapsed"), RAD_BF16, { T, 4096 }); - m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, { T, 4096 }); + /* The MLA row form gathers every rank's run at full length, so its output is rounded up to + * whole runs; the head form keeps the step's rows. */ + const bool rows = g.world > 1 && m.form == GlmMla::Form::rows; + m.y = decl_b(b, nm.f("attn_delta"), RAD_BF16, + { rows ? g.world * GlmMla::rows_for(T, g.world) : T, 4096 }); m.post = decl_b(b, nm.f("post"), RAD_F32, { T, 4 }); m.comb = decl_b(b, nm.f("mix"), RAD_F32, { T, 16 }); m.act.x = decl_b(b, nm.f("normalized"), RAD_BF16, { T, 4096 }); @@ -132,9 +140,9 @@ static int kda_buffers(RadBuilder* b, Model& m) { kw.core.out = bf("recurrent_out", W); return RAD_OK; } -/* The head form's buffers, then the selection planes the indexer writes and the MLA reads. Under - * TP the selection planes hold every rank's run of rows, which can reach past the step - * (DsaCache::part_rows). */ +/* The head form's buffers, then the selection planes the indexer writes and the MLA reads, then + * the row form's (Model::form). Under TP the selection planes hold every rank's run of rows, + * which can reach past the step (DsaCache::part_rows). */ static int mla_buffers(RadBuilder* b, Model& m) { auto& g = m.g; auto& nm = m.nm; @@ -160,6 +168,16 @@ static int mla_buffers(RadBuilder* b, Model& m) { const int64_t TQ = g.world > 1 ? std::max(T, g.world * part) : T; aw.core.selected = decl_b(b, nm.f("selected"), RAD_I32, { TQ, 513 }); aw.core.length = decl_b(b, nm.f("length"), RAD_I32, { TQ }); + if (g.world > 1 && m.form == GlmMla::Form::rows) { + auto& rows = aw.rows; + const int64_t R = GlmMla::rows_for(T, g.world); + rows.q = decl_b(b, nm.f("rows_query"), RAD_BF16, { R, 16384 }); + rows.q_latent = decl_b(b, nm.f("rows_q_latent"), RAD_BF16, { R, 64, 512 }); + rows.attn_latent = decl_b(b, nm.f("rows_attn_latent"), RAD_BF16, { R, 64, 512 }); + rows.attn.x = decl_b(b, nm.f("rows_expanded"), RAD_BF16, { R, 16384 }); + RAD_ARCH_TRY(rows.attn.declare_qs(b, nm, g, "rows_expanded", 16384, R)); + rows.out = decl_b(b, nm.f("rows_out"), RAD_BF16, { R, 4096 }); + } return RAD_OK; } static int indexer_buffers(RadBuilder* b, Model& m) { @@ -292,7 +310,10 @@ static int layer(RadBuilder* b, Model& m, Layer& lay, Names& nm, int l, bool dra decl_w(b, nn, RAD_F32, { 4096 }, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); RAD_ARCH_TRY(lay.norm.declare(b, g, gain, input, m.act, 4096)); if (lay.full) { - RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, m.aw, ap, m.latent, true, true)); + // The MTP layer keeps the head form: its row form would cost another 126 MB a card. + auto aw = m.aw; + if (draft) aw.rows = {}; + RAD_ARCH_TRY(lay.mla.declare(b, nm, g, l, aw, ap, m.latent, true, true)); DsaCache::Config c; c.blocks = (g.max_ctx + 3) / 4 + 1; c.work = (g.max_tok + 3) / 4 + g.max_seqs; @@ -386,18 +407,50 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; const int world = ctx->world_size ? ctx->world_size : 1; - if (!GlmTp::world_ok(world) || meta->n_embd != 4096 || meta->n_layers != 45 || - meta->n_vocab != 154880 || cfg(meta, "num_nextn_predict_layers", 0) != 1 || - cfg(meta, "hc_mult", 0) != 4 || cfg(meta, "n_routed_experts", 0) != 288 || - cfg(meta, "index_topk", 0) != 2048 || ctx->max_spec > 31 || - (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16)) + if (!GlmTp::world_ok(world)) { + fprintf(stderr, "radiance: glm5next: --tp %d; the head, KDA channel and expert splits of " + "this plugin are built for 1, 2, 4 or 8 ranks\n", world); return RAD_E_UNSUPPORTED; + } + /* The graph is written for the released GLM-5.3-Flash and reads none of these from the + * checkpoint, so a checkpoint that differs in any of them is refused by name. */ + const struct { + const char* what; + int64_t got, want; + } shape[] = { { "hidden_size", meta->n_embd, 4096 }, + { "num_hidden_layers", meta->n_layers, 45 }, + { "vocab_size", meta->n_vocab, 154880 }, + { "num_nextn_predict_layers", cfg(meta, "num_nextn_predict_layers", 0), 1 }, + { "hc_mult", cfg(meta, "hc_mult", 0), 4 }, + { "n_routed_experts", cfg(meta, "n_routed_experts", 0), 288 }, + { "index_topk", cfg(meta, "index_topk", 0), 2048 } }; + for (const auto& s : shape) + if (s.got != s.want) { + fprintf(stderr, "radiance: glm5next: the checkpoint's %s is %lld; this plugin serves " + "the GLM-5.3-Flash geometry, where it is %lld\n", + s.what, (long long)s.got, (long long)s.want); + return RAD_E_UNSUPPORTED; + } + if (ctx->max_spec > 31) { + fprintf(stderr, "radiance: glm5next: --num-speculative-tokens %d; the KDA verify pass " + "takes at most 32 rows a sequence, so the MTP depth is at most 31\n", + ctx->max_spec); + return RAD_E_UNSUPPORTED; + } + if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) { + fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin keeps its latent " + "attention, index tail and KDA caches in bf16 and has no fp8 cache, so " + "run it with --kv-cache-dtype bf16\n", + ctx->kv_dtype == RAD_F8E4M3 ? "fp8" : rad_dtype_name(ctx->kv_dtype)); + return RAD_E_UNSUPPORTED; + } auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank]; slot = std::make_unique(); auto& m = *slot; auto& g = m.g; m.nm = Names(ctx->scope); auto& nm = m.nm; + m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads; RAD_ARCH_TRY(geometry(g, meta, ctx, world)); RAD_ARCH_TRY(stream_buffers(b, m)); RAD_ARCH_TRY(kda_buffers(b, m)); @@ -547,6 +600,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (k > 0) out->enc_merge = k * k; } out->shape_probe_ok = 1; + out->tp_attn_rows_ok = 1; return RAD_OK; } } // namespace glm5next diff --git a/arch/krea2/krea2.cpp b/arch/krea2/krea2.cpp index e143ca61..42497eda 100644 --- a/arch/krea2/krea2.cpp +++ b/arch/krea2/krea2.cpp @@ -139,6 +139,7 @@ struct Model { std::vector te; rad_buf b_taps = 0; /* [T * 12, n_embd]: token t's tap i at row 12 t + i */ std::string tap_mul[kNTaps]; /* chan_affine's `mul` for each tap's rebalance gain */ + std::string tap_add; /* chan_affine's `add`: zeros */ /* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks * over the mixed rows `b_ft` */ @@ -383,7 +384,12 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { * scaled copy goes through te.h2, free between a layer's add and the next layer's projections, * so the residual stream itself is never scaled. */ enum { kGainCh = 64 }; - if (g.n_embd % kGainCh) return RAD_E_INVAL; + if (g.n_embd % kGainCh) { + fprintf(stderr, "radiance: krea2: the text encoder's hidden size %lld is not a multiple of " + "%d, the rows the rebalance gains are applied in\n", (long long)g.n_embd, + (int)kGainCh); + return RAD_E_UNSUPPORTED; + } for (int t = 0; t < kNTaps; ++t) { char v[32]; std::snprintf(v, sizeof v, "%.9g", kRebalance[t]); @@ -393,9 +399,8 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { m.tap_mul[t] += v; } } - static std::string zeros64; - if (zeros64.empty()) - for (int k = 0; k < kGainCh; ++k) zeros64 += k ? " 0" : "0"; + m.tap_add.clear(); + for (int k = 0; k < kGainCh; ++k) m.tap_add += k ? " 0" : "0"; /* Layers up to the last tap only. */ const int n_run = kTaps[kNTaps - 1]; @@ -480,7 +485,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) { L.op_gain = rw(b, RAD_OP(b, "chan_affine", RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", kGainCh), RAD_STR("mul", m.tap_mul[L.tap].c_str()), - RAD_STR("add", zeros64.c_str()), + RAD_STR("add", m.tap_add.c_str()), RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"), RAD_INT("round", 0)), RAD_NOWEIGHTS), @@ -1181,6 +1186,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c d.cond_rows = kCondRows; d.rope_hw_scale = 1.0; d.rope_text_l = 0; + d.cond_opts = RAD_GEN_COND_REBALANCE; RAD_ARCH_TRY(rad_declare_generator(b, &d)); } rad_note(b, "rank %d/%d: Krea 2%s -- text encoder %d of %lld layers, text fusion %zu + %zu " diff --git a/arch/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index b781fe71..25570fed 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -193,10 +193,28 @@ struct Model { MediaRows mrows{}; std::vector layers; + + /* The pipelined prefill (step_pipelined): on where declare allowed it; the bounds buffer it + * cuts a step by, rewritten by every pipelined step from the pinned table `pipe_tbl` of + * {0, pipe_rows(T), T} for every T, made once; and whether rank 0 has said it pipelines. */ + bool pipe_on = false; + rad_buf b_pipe_cu = 0; + int32_t* pipe_tbl = nullptr; + bool pipe_tbl_tried = false; + bool pipe_noted = false; + bool pipe_serial_noted = false; }; static Model g_model[MAX_RANKS]; +#if !QWEN35_MOE +/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up + * to 64 rows, so both pieces sit in one bucket band (core/runtime/ctx.h) and the second is never + * wider than the first. */ +static const int64_t kPipeMinRows = 1024; +static int64_t pipe_rows(int64_t T) { return ((T + 1) / 2 + 63) / 64 * 64; } +#endif + /* Checks the container's statement of its format, since every mismatch is silent: a * `weight_block_size` of [64,64] against kernels that shift by 7 reads the right bytes with the * wrong gain, and e5m2 decoded as e4m3 gives merely implausible numbers. A container that states @@ -264,6 +282,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "DFlash2")); Dflash2::Config dc{}; + dc.short_block = 1; /* rad_drafter_short_block below */ dc.n_taps = m.n_taps; dc.block = ctx->max_spec + 1; dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2); @@ -414,6 +433,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui return RAD_E_FORMAT; } RAD_ARCH_TRY(rad_declare_drafter(b, &drf)); + if (m.df.block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, m.df.block_lo)); rad_note(b, "DFlash2 drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, " "ffn %lld, %s attention with a %lld-token window, %d trunk tap(s); one forward " @@ -430,6 +450,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; Model& m = g_model[ctx->rank]; + if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED); m = Model{}; m.nm = Names(ctx->scope); RAD_ARCH_TRY(check_format(meta)); @@ -583,17 +604,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c "and head instead of %lld", kvq_name, kvq == RAD_KVQ_V4 ? "E4M3" : "int6", (long long)(g.head_dim * row16 / 16), (long long)(2 * g.head_dim)); - /* The SSM state cache is f32. + /* The SSM state cache is f32, or f16 under --state-cache-dtype f16 (RadBuildCtx::state_dtype). * * State reads and writes dominate the two GDN kernels: one [128,128] state is 64 KiB at f32, - * and a speculative step writes one per candidate token per head, since the surviving - * candidate is unknown until after the layer. At depth 7 that is hundreds of MB per rank per - * step; f16 would halve it. libr4d compiles both widths (`SDT`) and the f16 round-trip error is - * ~5e-4 relative (elements are O(0.1)); vLLM's `--mamba-ssm-cache-dtype` is commonly float16. - * It stays f32 because f16 changes the generated text. */ + * and a step reads a sequence's state and writes it back (under the anchor form once, whatever + * the draft depth). libr4d compiles both widths (`SDT`, from the cache's dtype); the f16 + * round trip is ~5e-4 relative (elements are O(0.1)). f16 halves the state pool, its host + * checkpoints and the state traffic, and changes the generated text, so f32 is the default. */ RadKVGroupDecl sd{}; sd.kind = RAD_KV_LINEAR; - sd.dtype = RAD_F32; + sd.dtype = ctx->state_dtype == RAD_F16 ? RAD_F16 : RAD_F32; + if (sd.dtype == RAD_F16) rad_note(b, "GDN state cache f16 (--state-cache-dtype f16)"); sd.n_head_kv = gc.n_head_v; sd.state_dim[0] = gc.head_v; sd.state_dim[1] = gc.head_k; @@ -717,6 +738,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c } /* GPTQ calibration run (MoeFP8::Config::calib), on when the output directory is set. */ mc.calib = calib_dir() != nullptr ? 1 : 0; + /* Each rank holds a width slice of every expert (n_ff is per rank), so its down + * projection's Hessian would be of the slice, without the cross terms between slices. */ + if (mc.calib && g.world > 1) { + fprintf(stderr, "radiance: qwen35moe: calibration (RADIANCE_CALIB_DIR) runs at one " + "rank; at %d ranks each holds a slice of every expert's width, and " + "the down projection's Hessian would be of the slice\n", g.world); + return RAD_E_UNSUPPORTED; + } /* The experts' stored format, read from layer 0's first expert as qwen4exp does, so a * container with four-bit experts is served in that format. */ { @@ -846,7 +875,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x)); /* Always exact, not g.wire_exact: this all_reduce sums disjoint rows (each token's embedding * comes from one rank, the others contribute zero), so a lossy wire would only add error. - * min_bytes stays 0 for the same reason. */ + * min_bytes stays 0 for the same reason. + * + * The second lane's window opens here and closes after the final norm (rad_lane1_window_begin): + * the embedding's reduction and the pipelined prefill's boundaries are declared inside it, so + * the concurrent buffers stay live only there and the drafter and the heads can share their + * bytes. */ + RAD_ARCH_TRY(rad_lane1_window_begin(b)); if (g.world > 1) m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world), @@ -854,6 +889,35 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)), RAD_NOWEIGHTS), {m.b_x}, {m.b_x}); +#if !QWEN35_MOE + /* The pipelined prefill (step_pipelined), at two ranks wherever a step can be wide enough. + * Its second lane needs a narrow `overlap` all-reduce beside the GEMMs; two ranks is the only + * rank count where the step has been timed against the serial one, so elsewhere prefill stays + * serial. The second lane touches the residual stream, the normed input in both forms and the + * bounds, so those leave the sharing pool (Ctx::lane1_; the drafter taps are copied on the + * first lane, pipe_taps); the bounds also because no declared op reads them, which would leave + * a transient dead before the kernels that take them raw. + * + * Not on a trunk whose norms write rotated int8 codes (qwen35_w8a8 where libr4d serves the + * `_had_quant_i8g` forms, a_h.q8_fed): the boundary norms on the second lane + * (NormQuantFP8::step_plain) issue the E4M3 pair only, so such a trunk prefills serially. */ + if (m.a_h.q8_fed) { + if (g.world == 2 && g.max_tok >= kPipeMinRows && ctx->rank == 0) + fprintf(stderr, "radiance: qwen35: the pipelined prefill stays off on this trunk: its norms " + "write rotated int8 codes, which the pipeline's boundary norms do not\n"); + } else { + m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows; + } + if (m.pipe_on) { + RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_x)); + RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.x)); + RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.q)); + RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.s)); + m.b_pipe_cu = decl_b(b, nm.f("pipe_cu"), RAD_I32, {4}); + RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_cu)); + } +#endif + /* ---- the layers. */ /* The rope table's fill, declared before the layers that read it. If it does not resolve, * `aw.cos_sin` is cleared and every attention block uses its unfused norm + rope pair. Its band @@ -896,6 +960,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c for (int64_t l = 0; l < m.n_main; ++l) { Layer& lay = m.layers[(size_t)l]; lay.full = is_full_attention(l, interval) ? 1 : 0; +#if !QWEN35_MOE + /* The pipelined prefill runs every block's all-reduce beside the other piece's work, so + * each declares its collective a second time at `overlap` 1, a launch that leaves the CUs + * to that work (the lane rows of libr4d/r4d_rows.cpp); the fused all-reduce and norm + * would hold the card while it waits on the link. */ + lay.attn.ar_overlap = lay.gdn.ar_overlap = lay.mlp.ar_overlap = m.pipe_on ? 1 : 0; +#endif const LayerFold f = layer_fold(g, l, m.n_main, m.tap_layer, m.n_taps, m.op_embed_ar != 0); @@ -960,6 +1031,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_F64("eps", g.eps), RAD_F64("wadd", final_wadd), RAD_STR("dtype", g.dtype)), RAD_WEIGHTS(m.w_out_norm)), {m.b_x}, {m.a_h.x}); + RAD_ARCH_TRY(rad_lane1_window_end(b)); m.op_gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), @@ -1130,6 +1202,235 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c return RAD_OK; } +#if !QWEN35_MOE +/* ============================== A prefill step in two pieces ============================== + * + * At two ranks every layer of a prefill chunk makes two all-reduces, each folded into the next + * block's norm (layer_fold) and each in a hard chain on one stream: block -> all-reduce + norm -> + * block. On a 2048-token chunk they are about a fifth of the step, nearly all of it the link, with + * nothing beside them. + * + * A step of one prefill sequence of at least kPipeMinRows tokens is cut into two pieces of about + * half (pipe_rows), each the chunk a narrower batch makes. Every block runs a piece at a time on + * the first lane, and the work between two blocks runs a piece at a time on the second: the + * block's all-reduce at `overlap` 1 (a narrow launch that leaves the CUs to the compute beside it; + * the fused all-reduce and norm would hold its blocks on the card while it waits on the link and + * slow the GEMM beside it by a third), then the next block's plain norm, and after a feed-forward + * that keeps its add, the add and the final norm (the drafter taps go on the first lane, pipe_taps). + * + * mixer the delta net and the dense attention run whole a piece at a time and hand the + * first piece off behind its out projection (ArPieces), so its boundary runs beside + * the second piece's mixer; + * ffn its first piece runs beside the mixer's second boundary, its second beside its own + * first boundary; the next mixer's first piece runs beside its second. + * + * A piece computes the bytes the narrower chunk does: every op is per row, both pieces sit in the + * band of a whole step (pipe_rows), the all-reduce reduces within a row, the delta net carries its + * state through the cache as between two chunks, and each attention piece sees the cache up to its + * own end. The narrow all-reduce and the plain norm write the fused op's bytes, so a pipelined + * step is bit for bit the serial one. + * + * The second lane's requirements (Ctx::lane1_) hold: every collective of the step is on it, the + * embedding's included; none carries a device-wide arrival counter (the all-reduce's sequence + * counters order its own launches, which one lane keeps in order); and the buffers it touches left + * the sharing pool at declare (the drafter taps it does not touch: pipe_taps). */ + +template +static void pipe_on1(RadCtx* c, const F& issue) { + rad_lane(c, 1); + rad_lane_join(c, 0, 1); + issue(); + rad_lane(c, 0); +} +/* Lane 0 waits for everything issued on lane 1 so far. */ +static void pipe_wait1(RadCtx* c) { rad_lane_join(c, 1, 0); } + +/* The work after block `s` (2l the mixer of layer l, 2l + 1 its feed-forward) for rows + * [r0, r0 + n). */ +static void pipe_boundary(RadCtx* c, const Model& m, int64_t T, int64_t s, int64_t r0, int64_t n) { + const Geom& g = m.g; + const int64_t li = s / 2; + const Layer& l = m.layers[(size_t)li]; + if (s % 2 == 0) { + if (l.full) l.attn.issue_ar(c, r0, n); + else l.gdn.issue_ar(c, r0, n); + l.mlp.nq_h.step_plain(c, T, r0, n); + return; + } + l.mlp.issue_ar(c, r0, n); + if (l.mlp.op_add) + RAD_ISSUE_N(c, l.mlp.op_add, n, brow_slice(m.b_x, r0, n, g.n_embd), + brow_slice(m.a_h.x, r0, n, g.n_embd), brow_slice(m.b_x, r0, n, g.n_embd)); + if (li + 1 < (int64_t)m.layers.size()) { + const Layer& nx = m.layers[(size_t)li + 1]; + (nx.full ? nx.attn.nq_h : nx.gdn.nq_h).step_plain(c, T, r0, n); + } else { + RAD_ISSUE_N(c, m.op_final_norm, n, brow_slice(m.b_x, r0, n, g.n_embd), RAD_W(m.w_out_norm), + brow_slice(m.a_h.x, r0, n, g.n_embd)); + } +} + +/* Layer `li`'s drafter taps of rows [r0, r0 + n), on lane 0. Issued once lane 0 has waited for that + * piece's feed-forward boundary (its add is the last write to those rows of x before the next + * block's boundary, which lane 1 starts only behind lane 0's next issues), so the taps buffer is + * never touched from lane 1 and stays in the sharing pool: rad_buf_concurrent would hold its + * [max_tok, n_taps * n_embd] for the whole program. */ +static void pipe_taps(RadCtx* c, const Model& m, int64_t li, int64_t r0, int64_t n) { + for (int t = 0; t < m.n_taps; ++t) { + if (m.tap_layer[t] != (int)li) continue; + RAD_ISSUE_N(c, m.op_tap, n, brow_slice(m.b_x, r0, n, m.g.n_embd), + bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * m.g.n_embd, (int64_t)t * m.g.n_embd, + m.g.n_embd, n)); + } +} + +/* A mixer's first piece is done (ArPieces): lane 0 takes the previous block's second boundary + * before the second piece (and the previous layer's second-piece taps behind it), and lane 1 this + * block's first behind it. */ +struct PipeHand { + RadCtx* c = nullptr; + const Model* m = nullptr; + int64_t T = 0, s = 0; +}; +static void pipe_hand(void* u, int64_t r0, int64_t n) { + const PipeHand& h = *(const PipeHand*)u; + pipe_wait1(h.c); + if (h.s >= 2) { + const int64_t R = pipe_rows(h.T); + pipe_taps(h.c, *h.m, h.s / 2 - 1, R, h.T - R); + } + pipe_on1(h.c, [&] { pipe_boundary(h.c, *h.m, h.T, h.s, r0, n); }); +} + +/* The bounds of this step's pieces on the card, {0, pipe_rows(T), T}, if the step is pipelined; + * null for a serial step, and null with `failed` set when the step has been failed. Copied on the + * step's stream ahead of every layer from the pinned table, whose rows never change, so a captured + * step replays the same copy. */ +static const int32_t* pipe_ready(RadCtx* c, const RadBatch* batch, Model& m, bool* failed) { + const int64_t T = batch->n_tok; + if (!m.pipe_on || !m.b_pipe_cu || T < kPipeMinRows || T > m.g.max_tok || + batch->phase != RAD_PHASE_PREFILL) + return nullptr; + /* A prefill step wide enough that runs serially says why, once, so a deployment that never + * pipelines does not look like one that gains nothing from it. */ + auto serial = [&](const char* why) -> const int32_t* { + if (!m.pipe_serial_noted && m.g.rank == 0) + fprintf(stderr, "radiance: qwen35: a %lld-row prefill step runs serially: %s\n", + (long long)T, why); + m.pipe_serial_noted = true; + return nullptr; + }; + if (batch->n_seq != 1 || batch->n_seq_decode != 0) return serial("more than one sequence"); + if (!batch->positions) return serial("no positions"); + if (rope_mixed(batch) || batch->n_mm_rows > 0) return serial("media rows in the step"); + if (dbg_resid_on()) return serial("residual debugging is on"); + int32_t* d = (int32_t*)rad_buf_ptr(c, m.b_pipe_cu); + if (!d) { + /* Not a rank-local fallback to the serial step: the other rank would pipeline, and the two + * would issue different collectives. Fail the step, as gemma3 does. */ + rad_step_fail(c, "qwen35: the pipelined prefill's bounds have no storage"); + *failed = true; + return nullptr; + } + const int64_t R = pipe_rows(T); + ArPieces pc{}; + pc.rows = R; pc.done = pipe_hand; pc.cu = d; pc.in_ready = true; + for (const Layer& l : m.layers) { + if (!(l.full ? l.attn.takes_pieces(batch, &pc) : l.gdn.takes_pieces(batch, &pc))) + return serial(l.full ? "an attention block cannot run in pieces" + : "a delta-net block cannot run in pieces"); + /* Every boundary issues its block's all-reduce itself, narrow, then the plain norm. */ + if (!(l.full ? l.attn.op_ar_ov : l.gdn.op_ar_ov) || !l.mlp.op_ar_ov) + return serial("a block declares no overlap all-reduce"); + } + if (!m.pipe_tbl_tried) { + m.pipe_tbl_tried = true; + const int64_t n = m.g.max_tok + 1; + m.pipe_tbl = (int32_t*)rad_dev_alloc(3 * n * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED); + if (m.pipe_tbl) { + for (int64_t t = 0; t < n; ++t) { + m.pipe_tbl[3 * t] = 0; + m.pipe_tbl[3 * t + 1] = (int32_t)pipe_rows(t); + m.pipe_tbl[3 * t + 2] = (int32_t)t; + } + } + } + /* Everything above depends only on the batch and the build, the same on every rank; what + * follows is this rank's own, and falling back to the serial step here would leave the other + * rank pipelining, the two issuing different collectives on the shared all-reduce instance + * (a hang or a wrong sum). So it fails the step. */ + if (!m.pipe_tbl || + rad_memcpy_async(d, m.pipe_tbl + 3 * T, 3 * (int64_t)sizeof(int32_t), rad_stream(c)) != + RAD_OK) { + rad_step_fail(c, "qwen35: the pipelined prefill's piece bounds could not be put on the card " + "(no pinned host memory, or the copy failed)"); + *failed = true; + return nullptr; + } + return d; +} + +static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) { + const Geom& g = m.g; + const int64_t T = batch->n_tok, R = pipe_rows(T); + const int64_t L = (int64_t)m.layers.size(); + if (!m.pipe_noted) { + m.pipe_noted = true; + if (g.rank == 0) + fprintf(stderr, "radiance: qwen35: prefill steps of one sequence from %lld rows are " + "pipelined: two pieces, block boundaries on the second lane\n", + (long long)kPipeMinRows); + } + + RAD_ISSUE(c, m.op_embed, + praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T)); + /* The embedding's reduction and layer 0's norm over the whole step, on lane 1 with every + * other collective (the norm takes the reduction where the wire is exact). */ + pipe_on1(c, [&] { + if (m.op_embed_ar && !ar_wire_is_exact(g, T)) + RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.b_x, T), RAD_NONE); + if (L > 0) (m.layers[0].full ? m.layers[0].attn.nq_h : m.layers[0].gdn.nq_h).step(c, T); + }); + pipe_wait1(c); + if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch)) + RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs)); + + for (int64_t li = 0; li < L; ++li) { + const Layer& l = m.layers[(size_t)li]; + PipeHand h{c, &m, T, 2 * li}; + ArPieces pc{}; + pc.rows = R; pc.done = pipe_hand; pc.u = &h; pc.cu = pcu; pc.in_ready = true; + if (l.full) l.attn.step(c, batch, false, &pc); + else l.gdn.step(c, batch, false, &pc); + if (pc.handed != 1) { + rad_step_fail(c, "qwen35: a mixer did not run its two pieces in a pipelined prefill " + "step (pipe_ready and the block's takes_pieces disagree)"); + return; + } + pipe_wait1(c); + pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li, R, T - R); }); + l.mlp.body(c, T, 0, R); + pipe_wait1(c); + pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li + 1, 0, R); }); + l.mlp.body(c, T, R, T - R); + pipe_wait1(c); + pipe_taps(c, m, li, 0, R); + pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li + 1, R, T - R); }); + } + pipe_wait1(c); + if (L > 0) pipe_taps(c, m, L - 1, R, T - R); + + if (batch->n_out > 0) { + RAD_ISSUE_N(c, m.op_gather, batch->n_out, + brows(m.a_h.x, T), 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)); + } +} +#endif + static void step(RadCtx* c, const RadBatch* batch) { Model& m = g_model[rad_rank(c)]; @@ -1168,6 +1469,15 @@ static void step(RadCtx* c, const RadBatch* batch) { return; } +#if !QWEN35_MOE + bool pipe_failed = false; + if (const int32_t* pcu = pipe_ready(c, batch, m, &pipe_failed)) { + step_pipelined(c, batch, m, pcu); + return; + } + if (pipe_failed) return; +#endif + 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)); @@ -1242,6 +1552,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (hd == 256 && nkv > 0 && meta->n_head == 6 * nkv) out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4); } + /* The delta-net state cache is declared at RadBuildCtx::state_dtype. */ + out->state_f16_ok = 1; const char* da = rad_meta_gets(meta, "draft.architectures", ""); if (da && std::strstr(da, "DFlash2")) { const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8); diff --git a/arch/qwen3asr_bf16/qwen3asr_bf16.cpp b/arch/qwen3asr_bf16/qwen3asr_bf16.cpp index 1930ed6f..b4d65770 100644 --- a/arch/qwen3asr_bf16/qwen3asr_bf16.cpp +++ b/arch/qwen3asr_bf16/qwen3asr_bf16.cpp @@ -9,7 +9,7 @@ * input_audio part. The reference is transformers' modeling_qwen3_asr (5.18) with its * Qwen3ASRFeatureExtractor, which core/mm reproduces (AudioFamily::Qwen3ASR). * - * ============================== THE SHAPE, AT 1.7B ============================== + * ============================== The shape, at 1.7B ============================== * * audio encoder: log-mel [frames, 128], convolved one second (100 frames) at a time: three * Conv2d 3x3 / stride 2 / pad 1 over [mel, time] with 480 channels and exact gelu, 128 mel -> @@ -23,7 +23,7 @@ * q/k RMS norms, NeoX rope over the whole head at theta 1e6, SwiGLU 6144, RMS eps 1e-6, * vocab 151936, the lm_head tied to the embedding. * - * ============================== WHAT IS EASY TO GET WRONG ============================== + * ============================== What is easy to get wrong ============================== * * Each second is convolved on its own. The core lays a clip out so one convolution over it does * that (core/mm/processor.h, AudioFamily::Qwen3ASR): a whole second is staged as 104 frames whose diff --git a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index 002d48f9..0beb8561 100644 --- a/arch/qwen4exp_fp8/qwen4exp_fp8.cpp +++ b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp @@ -174,6 +174,10 @@ struct Model { rad_buf b_mtp_hin = 0, b_mtp_hw = 0, b_mtp_e = 0, b_mtp_hout = 0; rad_buf b_mtp_dq = 0, b_mtp_ds = 0, b_mtp_dsum = 0; rad_buf b_mtp_dlog = 0, b_mtp_didx = 0, b_mtp_dval = 0; + /* --draft-coupling: [max_seqs] draws staged before the serial passes and [max_spec, + * max_seqs] states read back after them. PERSIST: the engine writes them from the host and the + * head writes the states on the card, across a step boundary. */ + rad_buf b_mtp_couple_draws = 0, b_mtp_couple_state = 0; rad_buf b_mtp_dpair = 0, b_mtp_dgath = 0; HcEnter enter; @@ -1261,6 +1265,30 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * vocab-parallel all-gather a 16-byte row (rad_block_mtp_hc.h, kDraftTopR). */ m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32, {g.max_logit_rows, kDraftTopR}); m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32, {g.max_logit_rows, kDraftTopR}); + + /* --draft-coupling (RadBuildCtx::draft_coupling). Q is the law of the 2-bit candidate + * head's reranked top-8; a plain bf16 head leaves one candidate and nothing to couple + * over. The engine checks the drafter shape (a linear serial chain). */ + if (ctx->draft_coupling) { + if (!m.b_mtp_didx || g.max_spec < 1 || g.max_spec > RAD_MTP_COUPLE_MAX_ROUNDS) { + rad_note(b, "--draft-coupling on requires the 2-bit candidate head's reranked " + "top8 and max_spec 1..%d", + RAD_MTP_COUPLE_MAX_ROUNDS); + return RAD_E_UNSUPPORTED; + } + m.b_mtp_couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32, + {g.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS}, + RAD_BUF_PERSIST); + m.b_mtp_couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32, + {g.max_spec, g.max_seqs, + RAD_MTP_COUPLE_STATE_WORDS}, + RAD_BUF_PERSIST); + if (!m.b_mtp_couple_draws || !m.b_mtp_couple_state) return RAD_E_INVAL; + rad_note(b, "MTP coupled: the head samples x~Q from its reranked top8 each round " + "(FP64), and the sampler couples the target's own draw to it; %lld " + "round(s), fixed-seed tokens are NOT preserved", + (long long)g.max_spec); + } } MtpHcBlock::Wire tw{}; @@ -1270,6 +1298,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c tw.dq = m.b_mtp_dq; tw.ds = m.b_mtp_ds; tw.dsum = m.b_mtp_dsum; tw.dlog = m.b_mtp_dlog; tw.didx = m.b_mtp_didx; tw.dval = m.b_mtp_dval; tw.dpair = m.b_mtp_dpair; tw.dgath = m.b_mtp_dgath; + tw.couple_draws = m.b_mtp_couple_draws; tw.couple_state = m.b_mtp_couple_state; /* The head reuses the trunk's working buffers, all dead by the time a draft round runs (a * second set would be 150 MiB). Only the wide stream and the carry are its own, since * they must survive the round that produced them. */ @@ -1555,7 +1584,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int if (p == K - 1) wait1(); l.hc_ffn.write(c, T, r0(p), rn(p)); /* The projection of this piece, before the next layer reads it. */ - l.proj.step(c, r0(p), rn(p)); + l.proj.step(c, batch, r0(p), rn(p)); if (nx && !ple_next) nx->hc_mix.read(c, T, r0(p), rn(p)); } if (ple_next) { @@ -1600,7 +1629,7 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_ l.mlp.step(c, batch); l.hc_ffn.write(c, T, 0, T); /* The request's control vector, on the stream the write just finished. */ - l.proj.step(c, 0, T); + l.proj.step(c, batch, 0, T); dbg_resid(c, (int)li, "ffn", g.n_embd, m.b_h, m.a_x.x); } } @@ -1677,6 +1706,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) { if (hd == 256 && nkv > 0 && meta->n_head == 12 * nkv) out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4); } + /* The gated residual applies a control vector after every block's write (HcProject). */ + out->control_vector_ok = 1; return RAD_OK; } diff --git a/arch/unlimitedocr_bf16/CMakeLists.txt b/arch/unlimitedocr_bf16/CMakeLists.txt new file mode 100644 index 00000000..b413ff05 --- /dev/null +++ b/arch/unlimitedocr_bf16/CMakeLists.txt @@ -0,0 +1,12 @@ +# A plugin like any other: built here inside radiance's tree, or on its own against an installed +# radiance (`cmake -S arch/unlimitedocr_bf16 -B build -DCMAKE_PREFIX_PATH=`) -- the +# same rad_add_plugin either way (cmake/RadAddPlugin.cmake). +if(NOT COMMAND rad_add_plugin) + cmake_minimum_required(VERSION 3.21) + project(unlimitedocr_bf16 LANGUAGES CXX) + find_package(radiance REQUIRED) + rad_plugin_defaults() +endif() + +rad_add_plugin(unlimitedocr_bf16 architectures + SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/unlimitedocr_bf16.cpp) diff --git a/arch/unlimitedocr_bf16/attn_llama.h b/arch/unlimitedocr_bf16/attn_llama.h new file mode 100644 index 00000000..0a63f4df --- /dev/null +++ b/arch/unlimitedocr_bf16/attn_llama.h @@ -0,0 +1,247 @@ +/* attn_llama.h -- one plain multi-head attention block, bf16 operands, paged KV. PRIVATE to + * arch/unlimitedocr_bf16 (the arch/qwen35_bf16 + siglip2.h precedent: a header beside the plugin + * that composes it). + * + * rmsnorm -> q gemm, k gemm, v gemm -> rope(q), rope(k) + * -> kv_store -> paged attention (causal) -> o gemm -> [all_reduce] -> residual add + * + * It is rad_block_attn_gated.h with the Qwen3.5-specific parts removed, and the removals are the + * model: Unlimited-OCR's decoder is a plain Llama-MoE (modeling_deepseekv2.py's + * SlidingWindowLlamaAttention is MHA with `use_mla: false`), so + * + * * there is NO output gate: `q_proj` is [n_embd, n_head*head_dim] and holds only the query, so + * no de-interleaving, no `sigmoid`, no `mul`; + * * there is NO per-head q/k norm: the config's `qk_nope_head_dim`/`qk_rope_head_dim` are 0 and + * the reference rotates the projections straight; + * * the rotary is FULL head_dim (rot = head_dim = 128) and NeoX-half (`rotate_half` in the + * reference), not partial, not mrope; + * * q, k and v are three [1280, 1280] projections fused into ONE stacked-rows GEMM: the + * rank-local q|k|v weight rows are staged once into a PERSIST plane, and q, k and v are + * column views of one fused output plane (RadOperand::cols, abi/rad_runtime.h) that the + * rope, kv_store and attention readers walk by row pitch -- the rad_block_attn_gated.h + * argument against a fused [k|v] row does not apply to the stacked-rows form. + * + * Everything the gated block gets right about paged KV is copied through unchanged: the attention + * declared BEFORE the store so block_size derives from the resolved kernel, the ranged `q_len` + * band, the ragged-step cu_seqlens, the collective emitted by the plugin and not the core. + */ +#ifndef UNLIMITEDOCR_ATTN_LLAMA_H +#define UNLIMITEDOCR_ATTN_LLAMA_H + +#include + +namespace rad { +namespace arch { + +struct AttnLlamaBF16 { + struct Wire { + rad_buf x = 0; /* [max_tok, n_embd] the residual stream */ + rad_buf h = 0; /* [max_tok, n_embd] normed input, then the o output */ + rad_buf q = 0; /* [max_tok, q_dim + 2*kv_dim] fused q|k|v plane; q, k, v are the + * column views [0, q_dim), [q_dim, q_dim+kv_dim), [q_dim+kv_dim, ...) */ + rad_buf qs = 0; /* [max_tok, q_dim] dense q lifted out of the fused plane for + * attn_paged, whose kernels read q only contiguous (see step) */ + rad_buf k = 0; /* the same plane: the rope/kv_store readers take the k columns */ + rad_buf v = 0; /* the same plane: the v columns */ + rad_buf attn = 0; /* [max_tok, q_dim] */ + }; + + struct Src { + const char* norm = nullptr; /* input_layernorm.weight */ + const char* q = nullptr; + const char* k = nullptr; + const char* v = nullptr; + const char* o = nullptr; + }; + + Geom g{}; + Wire w{}; + int layer = 0; + rad_kvgroup kv = 0; + int64_t n_rot = 0; + + rad_weight w_norm = 0, w_qkv = 0, w_o = 0; + rad_op op_norm = 0, op_qkv = 0; + rad_op op_rope_q = 0, op_rope_k = 0; + rad_op op_qs = 0; /* cast: lift the fused plane's q slice into dense qs */ + int qrow = 0; /* attn_paged_qrow served: q is read in place at its pitch */ + rad_op op_attn = 0, op_kv_store = 0, op_o = 0, op_ar = 0, op_add = 0; + + int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group, + int64_t rotary_dim, const Wire& wire, const Src& src); + void step(RadCtx* c, const RadBatch* batch) const; +}; + +inline int AttnLlamaBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, + rad_kvgroup group, int64_t rotary_dim, const Wire& wire, + const Src& src) { + g = geom; w = wire; layer = l; kv = group; n_rot = rotary_dim; + + const int64_t q_dim = g.q_dim(); + const int64_t kv_dim = g.kv_dim(); + + if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) { + fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n", + (long long)n_rot, (long long)g.head_dim); + return RAD_E_INVAL; + } + /* The KV-head-replication refusal rad_block_attn_gated.h states: this block declares its k/v + * with the plain even row-shard and passes no row span, so a world above the KV head count + * would hand a rank half of one KV head. Say so at declare. */ + if (g.world > g.n_head_kv_all) { + fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d " + "with n_head_kv = %lld.\n", __func__, 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)); + /* The convert-time q|k|v fusion, the gate_up form rad_block_mlp.h states: one weight, one + * GEMM, one movement unit; `row_parts` keeps the row-shard on q_local|k_local|v_local + * boundaries so the column views stay exact per rank. */ + RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.attn_qkv.weight", l), { src.q, src.k, src.v }, 0)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), src.o)); + + 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_qkv = decl_w(b, nm.f("blk.%d.attn_qkv.weight", l), RAD_BF16, + {q_dim + 2 * kv_dim, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0, + {q_dim, kv_dim, kv_dim}); + 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)); + + op_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_norm)), + {w.x}, {w.h}); + + /* One GEMM over the fused [q|k|v] rows: N = q_dim + 2*kv_dim, the readers below take the + * q, k and v column views of `w.q`. Same K, same per-column tile as the three-GEMM form, + * so the bf16 outputs are bit-identical; the win is one launch, not arithmetic. */ + op_qkv = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim + 2 * kv_dim), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(w_qkv)), + {w.h}, {w.q}); + + /* Full-head rotary, NeoX halves: the reference's rotate_half. The q call names n_head query + * heads and no kv heads (the buffers are separate); the k call names the kv heads. */ + op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, "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, n_rot, "neox"), + {w.k}, {w.k}); + + /* attn_paged's prefill kernels read q only contiguous, and here q is a column slice of the + * fused q|k|v plane (row pitch q_dim + 2*kv_dim). attn_paged_qrow reads that pitch in place + * (libr4d's qrow rows cover head_dim 128/256/512). It is a separate op so no `--kernels` order + * can hand the slice to a kernel that reads q only dense (gemma4.cpp:1001-1023). Where the op + * is not declared or does not resolve, the slice is lifted into dense qs first. The cast is + * always declared but issued only in the fallback. */ + op_qs = rw(b, RAD_OP(b, "cast", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim), + RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)), + RAD_NOWEIGHTS), + {w.q}, {w.qs}); + auto declare_attn = [&](const char* op, rad_buf q) { + /* Declared before kv_store so block_size derives from the resolved attention kernel (spec + * §7.2), pinned to RAD_KV_BLOCK for the same reason rad_arch.h states. This op keeps the + * plain causal rule through the R-SWA ring: the ring's visible set is the block table's + * job (the runtime window prunes the table, not the kernel), so no re-declaration. */ + return rw(b, RAD_OP(b, op, + 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", 0), + 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), + {q}, {w.attn}); + }; + if (rad_op_declared(b, "attn_paged_qrow") != 0) + op_attn = declare_attn("attn_paged_qrow", w.q); + if (op_attn) { + qrow = 1; + } else { + qrow = 0; + op_attn = declare_attn("attn_paged", w.qs); + } + + 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}, {}); + + 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(w_o)), + {w.attn}, {w.h}); + + if (g.world > 1) + op_ar = rw(b, RAD_OP(b, "all_reduce", + RAD_PARAMS(RAD_INT("world_size", g.world), + RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd), + RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact), + RAD_INT("min_bytes", g.wire_min_bytes)), + RAD_NOWEIGHTS), + {w.h}, {w.h}); + + op_add = rw(b, RAD_OP(b, "add", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {w.x, w.h}, {w.x}); + + return RAD_OK; +} + +inline void AttnLlamaBF16::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; + + RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T)); + RAD_ISSUE(c, op_qkv, brows(w.h, T), RAD_W(w_qkv), brows(w.q, T)); + + /* q, k and v are column views of the fused plane, walked by its row pitch: the rope and + * kv_store kernels take the slice's pitch (r4d_rows_pitch). Attention reads the q slice in + * place when attn_paged_qrow is served; otherwise it needs q dense, so the slice is lifted + * into qs after rope and before the store. */ + RAD_ISSUE(c, op_rope_q, bcol(w.q, 0, g.q_dim(), T), rope_posmc(g, batch, T)); + RAD_ISSUE(c, op_rope_k, bcol(w.q, g.q_dim(), g.kv_dim(), T), rope_posmc(g, batch, T)); + + if (op_qs) RAD_ISSUE(c, op_qs, bcol(w.q, 0, g.q_dim(), T), brows(w.qs, T)); + + RAD_ISSUE(c, op_kv_store, + bcol(w.q, g.q_dim(), g.kv_dim(), T), + bcol(w.q, g.q_dim() + g.kv_dim(), g.kv_dim(), T), + praw(slot, RAD_I32, T), kv_cache(kv, layer)); + + RAD_ISSUE_N(c, op_attn, batch->max_q_len, + qrow ? bcol(w.q, 0, g.q_dim(), T) : brows(w.qs, T), kv_cache(kv, layer), + praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0), + praw(used, RAD_I32, batch->n_seq), + RAD_NONE, RAD_NONE, + praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), + brows(w.attn, T)); + + RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T)); + if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE); + RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T)); +} + +} /* namespace arch */ +} /* namespace rad */ + +#endif /* UNLIMITEDOCR_ATTN_LLAMA_H */ diff --git a/arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp b/arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp new file mode 100644 index 00000000..eac26671 --- /dev/null +++ b/arch/unlimitedocr_bf16/unlimitedocr_bf16.cpp @@ -0,0 +1,553 @@ +/* unlimitedocr_bf16 -- baidu/Unlimited-OCR's decoder: a small Llama-MoE, bf16 weights and bf16 + * activations. + * + * Scope: the text trunk plus the DeepEncoder vision tower + * (arch/common/rad_block_sam.h: SAM ViT-B/16 -> map -> CLIP ViT-L/14 -> the projector + * -> the 273-row layout of a 1024 view / 110 rows of a 640 tile, declared with + * rad_declare_encoder(RAD_MM_IMAGE), patch_dim 768 = 3*16*16, merge 16, n_embd 1280). The tower + * serves both view geometries the processor stages -- the gundam mode's 640 tiles and global + * view, and the base mode's pages -- as two op sets over the same weights, the 40 grid's absolute + * position tables bicubic+antialias resamples of the checkpoint's (arch/common/rad_resample.h). + * The tower's weights are mapped always; its ops and the encoder pass are declared only when + * SAM's `sam_attn` op resolves, because no existing op + * can carry the decomposed rel_pos_h/rel_pos_w attention bias (rad_block_sam.h's header states the + * op and why). Without it this plugin is the text-only trunk and refuses images by name. The + * decoder's KV is one RAD_KV_RING group with the checkpoint's `sliding_window_size` (128), the + * reference's own R-SWA: prefill is fully causal, and from the end of the prefill the ring of the + * last W generated tokens is appended to the prompt (`SlidingWindowLlamaAttention`, which keeps + * the prompt as reference and overwrites ring slots in place). The checkpoint's windowed + * no-repeat-ngram ban is the sampler's `sample_ngram_ban` stage. + * + * ============================== THE SHAPE (config.json) ============================== + * + * 12 layers, hidden 1280, 10 heads x 128 head_dim, 10 kv-heads (MHA, `use_mla: false` -- the + * DeepseekV2 class names in the repo are packaging, the graph is Llama) + * full rotary over head_dim, theta 10000, plain RMSNorm eps 1e-6 (NOT 1 + w) + * vocab 129280, lm_head TIED to embed_tokens (the checkpoint ships both tensors) + * layer 0 dense (first_k_dense_replace 1, inter 6848); layers 1..11 MoE: + * 64 routed experts (moe_intermediate_size 896), top-6, scoring softmax, + * norm_topk_prob False, routed_scaling_factor 1.0 -- an ordinary softmax gate, + * 2 shared experts packed as ONE dense MLP 2x896 = 1792 wide, summed ungated + * + * The MoE block is arch/common/rad_block_moe_fp8.h in its plain-bf16 expert mode (probe() reads + * format 3 off the first expert's encoding), declared EXTERNAL-INPUT (src.norm null): its + * post-attention norm is declared by this plugin because the shared expert reads the SAME normed + * input and the block's gather overwrites that input with the routed delta (`h.x` is the + * fold target). The shared arm therefore lives here: gate|up -> silu_mul -> down -> add, beside + * the routed arm, exactly `y = y + shared_experts(x)` in modeling_deepseekv2.py:627. + * + * The attention is this plugin's private attn_llama.h: the gated bf16 block minus the output gate + * and the q/k head norms, which this model does not have. + */ +#include +#include +#include +#include + +#include "attn_llama.h" + +#include + +namespace unlimitedocr_bf16 { + +using namespace rad::arch; + +struct Layer { + int dense = 0; /* 1 = the first_k_dense layer, plain SwiGLU */ + AttnLlamaBF16 attn; + MlpBF16 mlp; /* dense layers */ + MoeFP8 moe; /* routed layers */ + /* The routed layer's external norm and the plugin-owned shared arm: the gain, the two dense + * linears' weights, and the ops. Per layer -- the ACTIVATION buffers are shared across the + * layers (spec §8) and the ops are declared per layer, as every block here does. */ + rad_weight w_norm = 0, w_sh_gate_up = 0, w_sh_down = 0; + rad_op op_moe_norm = 0; /* x -> h.x, the MoE block's external prepared input */ + rad_op op_sh_gu = 0, op_sh_act = 0, op_sh_down = 0, op_sh_ar = 0, op_sh_add = 0; +}; + +struct Model { + Names nm{""}; + Geom g{}; + int64_t n_rot = 0; + int64_t first_dense = 1; /* layers [0, first_dense) are dense MLPs */ + + rad_kvgroup kv = 0; + + /* the residual stream and the vocabulary edges */ + rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0; + /* attention */ + rad_buf b_qkv = 0, b_qs = 0, b_attn = 0; + /* dense feed-forward (layer 0) */ + rad_buf b_gate_up = 0, b_ffn = 0; + /* routing -- one row per token */ + rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_eoff = 0, b_ecnt = 0; + /* expert planes -- one row per (token, slot), a pass tall */ + rad_buf b_sorted = 0, b_egu = 0, b_edn = 0; + ActFP8 a_eff{}; + /* the shared arm reads the block's prepared input (h) before the gather overwrites it, then + * the dense linear's planes */ + rad_buf b_sgu = 0, b_sff = 0, b_sout = 0; + + MoeFP8::Config moecfg{}; + /* The DeepEncoder vision tower (arch/common/rad_block_sam.h). Its weights are mapped always; + * its ops and the encoder pass only when SAM's attention op resolves. */ + DeepEncoder enc; + + rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0; + rad_op op_embed = 0, op_embed_ar = 0, op_mm = 0, op_final_norm = 0, op_gather = 0, + op_logits = 0; + + std::vector layers; +}; + +static Model g_model[MAX_RANKS]; + +/* The per-MoE-layer norm and shared arm. The MoE block declares no norm in external-input mode, + * and the shared expert must read the same normed row the routed experts do; the block's gather + * folds the routed delta into h.x, so the shared arm is issued while h.x still holds the normed + * row, BEFORE the block. */ +static int declare_moe_norm_and_shared(RadBuilder* b, Model& m, int l) { + Geom& g = m.g; + Names& nm = m.nm; + Layer& lay = m.layers[(size_t)l]; + + const char* wname = nm.f("blk.%d.ffn_norm.weight", l); + RAD_ARCH_TRY(map_copy(b, wname, nm.ckpt("model.layers.%lld.post_attention_layernorm.weight", + (long long)l))); + lay.w_norm = decl_w(b, wname, RAD_F32, {g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l)); + + const int64_t n_ff_sh = m.moecfg.n_ff_shared; + RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ffn_gate_up_shexp.weight", l), + { nm.ckpt("model.layers.%lld.mlp.shared_experts.gate_proj.weight", + (long long)l), + nm.ckpt("model.layers.%lld.mlp.shared_experts.up_proj.weight", + (long long)l) }, 0)); + RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_down_shexp.weight", l), + nm.ckpt("model.layers.%lld.mlp.shared_experts.down_proj.weight", + (long long)l))); + lay.w_sh_gate_up = decl_w(b, nm.f("blk.%d.ffn_gate_up_shexp.weight", l), RAD_BF16, + {2 * n_ff_sh, g.n_embd}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0, + {n_ff_sh, n_ff_sh}); + lay.w_sh_down = decl_w(b, nm.f("blk.%d.ffn_down_shexp.weight", l), RAD_BF16, + {g.n_embd, n_ff_sh}, + RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l)); + + /* The routed arm's own norm: x -> h.x, the buffer the block takes as its prepared input and + * the buffer its gather writes the routed delta back into. */ + lay.op_moe_norm = rw(b, RAD_OP(b, "rmsnorm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), + RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_norm)), + {m.b_x}, {m.b_h}); + + lay.op_sh_gu = rw(b, RAD_OP(b, "gemm_nt", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 2 * n_ff_sh), + RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_sh_gate_up)), + {m.b_h}, {m.b_sgu}); + lay.op_sh_act = rw(b, RAD_OP(b, "silu_mul", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n_ff_sh), + RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_sgu}, {m.b_sff}); + lay.op_sh_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", n_ff_sh), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(lay.w_sh_down)), + {m.b_sff}, {m.b_sout}); + /* Column-sharded like the dense MLP's down_proj: every rank holds a partial sum, reduced + * once per step before the residual add. */ + if (g.world > 1) + lay.op_sh_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_sout}, {m.b_sout}); + lay.op_sh_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_sout}, {m.b_x}); + return RAD_OK; +} + +static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) { + if (!b || !meta || !ctx) return RAD_E_INVAL; + if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL; + + Model& m = g_model[ctx->rank]; + m = Model{}; + m.nm = Names(ctx->scope); + RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16)); + Geom& g = m.g; + Names& nm = m.nm; + + /* Plain RMSNorm (DeepseekV2RMSNorm is x_hat * w), not the GemmaRMSNorm `1 + w`. */ + g.wadd = 0.0f; + /* The linears are the checkpoint's own bf16: no scale planes, no quantised activations. The + * MoeFP8 block in particular requires it (its external-input check reads it). */ + g.w_bf16 = true; + + /* ---- geometry RadModelMeta does not name. */ + const int64_t n_expert_all = meta->n_expert > 0 + ? meta->n_expert : rad_meta_geti(meta, "n_routed_experts", 0); + const int64_t top_k = meta->n_expert_used > 0 + ? meta->n_expert_used : rad_meta_geti(meta, "num_experts_per_tok", 0); + const int64_t moe_ff = rad_meta_geti(meta, "moe_intermediate_size", 0); + const int64_t n_shared = rad_meta_geti(meta, "n_shared_experts", 0); + m.first_dense = rad_meta_geti(meta, "first_k_dense_replace", 1); + if (n_expert_all <= 0 || top_k <= 0 || top_k > n_expert_all || moe_ff <= 0 || + m.first_dense < 0 || m.first_dense >= g.n_layer) { + fprintf(stderr, "radiance: unlimitedocr: the container does not describe the routed " + "decoder (n_routed_experts %lld, num_experts_per_tok %lld, " + "moe_intermediate_size %lld, first_k_dense_replace %lld of %lld layers)\n", + (long long)n_expert_all, (long long)top_k, (long long)moe_ff, + (long long)m.first_dense, (long long)g.n_layer); + return RAD_E_INVAL; + } + /* The gate is an ordinary softmax top-k. A container that states a scheme this plugin does not + * serve is refused by name rather than served as a softmax gate (spec §17). */ + if (const char* sf = rad_meta_gets(meta, "scoring_func", nullptr); sf && *sf && + std::strcmp(sf, "softmax") != 0) { + fprintf(stderr, "radiance: unlimitedocr: scoring_func '%s' is not implemented; the gate " + "this plugin declares is the softmax top-k\n", sf); + return RAD_E_UNSUPPORTED; + } + const double rsf = rad_meta_getf(meta, "routed_scaling_factor", 1.0); + if (!(rsf > 0.0) || rsf != 1.0) { + fprintf(stderr, "radiance: unlimitedocr: routed_scaling_factor %g is not 1.0 and this " + "plugin declares no router output scale\n", rsf); + return RAD_E_UNSUPPORTED; + } + const int64_t topk_group = rad_meta_geti(meta, "topk_group", 1); + const int64_t n_group = rad_meta_geti(meta, "n_group", 1); + if (topk_group != 1 || n_group != 1) { + fprintf(stderr, "radiance: unlimitedocr: grouped routing (n_group %lld, topk_group %lld) " + "is not implemented; the reference's greedy top-k over one group is\n", + (long long)n_group, (long long)topk_group); + return RAD_E_UNSUPPORTED; + } + if (rad_meta_geti(meta, "use_mla", 0)) { + fprintf(stderr, "radiance: unlimitedocr: use_mla is set; this decoder is the MHA graph " + "(q/k/v projections), not the DeepSeek MLA\n"); + return RAD_E_UNSUPPORTED; + } + /* The full-head rotary: no rope_parameters object is present, so yarn_from answers + * "default" and theta stays the container's (the reference default 10000). */ + m.n_rot = g.head_dim; + RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot)); + + /* ---- the routed geometry. n_expert is NOT divided (every rank holds every expert and routes + * identically); the intermediate width is. */ + MoeFP8::Config& mc = m.moecfg; + mc.n_expert = n_expert_all; + mc.n_expert_all = n_expert_all; + mc.top_k = top_k; + int s; + if ((s = divide_or_fail(moe_ff, g.world, "moe_intermediate_size", &mc.n_ff_exp)) < 0) + return s; + /* The shared experts are packed as ONE dense MLP n_shared x moe_ff wide (DeepseekV2Model: + * `intermediate_size = moe_intermediate_size * n_shared_experts`), summed ungated. The + * MoeFP8 shared arm is the SIGMOID-gated family's shape; this model's arm is declared by the + * plugin (declare_moe_norm_and_shared) and the block declares none. */ + const int64_t sh_all = n_shared * moe_ff; + mc.n_ff_shared = 0; + int64_t n_ff_sh = 0; + if (sh_all > 0 && (s = divide_or_fail(sh_all, g.world, "n_shared_experts width", + &n_ff_sh)) < 0) + return s; + mc.norm_topk = rad_meta_geti(meta, "norm_topk_prob", 0) ? 1 : 0; + const int64_t moe_rows = 2048; + mc.rows = g.max_tok < moe_rows ? g.max_tok : moe_rows; + + /* ---- KV: one R-SWA ring group. + * + * The reference's `SlidingWindowLlamaAttention` keeps the prefill as reference and from the + * prefill's end keeps the last `sliding_window_size` generated tokens in a ring it overwrites + * in place, attending over both. RAD_KV_RING is that: paged like a window group, but the floor + * is per sequence and armed at admission (`visible_lo = prefill length`), so a decode query + * sees [0, prefill) U [prefill, prefill + W). Prefill itself stays fully causal, which is why + * the attention op keeps `causal=1` and `window=0`: the visible set is the block table's job, + * and `causal=0` would make a prefill chunk non-causal. + * + * A checkpoint that states no window gets the plain full cache, so the text trunk still + * serves. Prefix caching and speculation switch off for the group automatically (a runtime + * window's KV before the prompt end is not reusable and a draft cannot know where the ring + * starts). */ + const int64_t sw_size = rad_meta_geti(meta, "sliding_window_size", 0); + const int64_t win = sw_size > 0 ? sw_size : rad_meta_geti(meta, "sliding_window", 0); + RadKVGroupDecl fd{}; + fd.kind = win > 0 ? RAD_KV_RING : RAD_KV_FULL; + fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16); + fd.window = win > 0 ? win : 0; + fd.n_head_kv = g.n_head_kv; + fd.head_dim = g.head_dim; + m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &fd); + g.kv_dtype = rad_dtype_name(fd.dtype); + + /* ---- activation buffers. */ + 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_qkv = decl_b(b, nm.f("attn_qkv"), g.act_dtype, + {g.max_tok, g.q_dim() + 2 * g.kv_dim()}); + /* The dense q lifted out of the fused plane for attn_paged (attn_llama.h's cast). */ + m.b_qs = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, g.q_dim()}); + m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, g.q_dim()}); + + m.b_gate_up = 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}); + + const int64_t R = g.max_tok, K = mc.rows * mc.top_k; + m.b_rlogits = decl_b(b, nm.f("moe_logits"), g.act_dtype, {R, mc.n_expert_all}); + m.b_eids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, mc.top_k}); + m.b_ew = decl_b(b, nm.f("moe_w"), g.act_dtype, {R, mc.top_k}); + m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {K}); + m.b_eoff = decl_b(b, nm.f("moe_off"), RAD_I32, {mc.n_expert_all + 1}); + /* PERSIST: its only reader, rad_route_report, is not a declared op. See qwen4exp_fp8. */ + m.b_ecnt = decl_b(b, nm.f("moe_cnt"), RAD_I32, {mc.n_expert}, RAD_BUF_PERSIST); + m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp}); + m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp}); + m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd}); + + if (n_ff_sh > 0) { + mc.n_ff_shared = n_ff_sh; /* sizes nothing in the block (arm null there); kept for + the shared-arm ops below */ + m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * n_ff_sh}); + m.b_sff = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, n_ff_sh}); + m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd}); + } + + 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)); + + /* ---- vocabulary edges. The lm_head is TIED: the checkpoint ships lm_head.weight, and a + * release that ships only the embedding is served by the same map (first source present + * wins). Both edges are row-sharded with the vocabulary (spec §9). */ + 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.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()); + 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 expert format: the checkpoint's plain bf16, read off the first routed layer's + * first expert. A quantised container would be a sibling plugin's. */ + { + MoeFP8::Src probe_src{}; + probe_src.experts = nm.ckpt("model.layers.%lld.mlp.experts", + (long long)m.first_dense); + RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)m.first_dense, probe_src, &mc)); + if (!mc.expert_bf16) { + fprintf(stderr, "radiance: unlimitedocr_bf16 serves plain bf16 experts; layer %lld's " + "expert 0 is quantised. Serve that container with its quantised " + "plugin.\n", (long long)m.first_dense); + return RAD_E_UNSUPPORTED; + } + } + + /* ---- the DeepEncoder tower: map and declare its weights, then (when `sam_attn` resolves) its + * ops and the encoder pass. Without that op the tower stays off and images are refused. */ + RAD_ARCH_TRY(m.enc.declare(b, ctx, nm, g.n_embd, (int)g.n_layer + 64)); + + /* A picture's rows overwrite its placeholders' embeddings after the (all-reduced) lookup and + * before the first block. Declared only when the tower is, since otherwise no step can carry + * media rows. */ + if (m.enc.on) + m.op_mm = rw(b, RAD_OP(b, "scatter_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), + RAD_STR("dtype", "bf16")), + RAD_NOWEIGHTS), + {m.b_x}, {m.b_x}); + + AttnLlamaBF16::Wire aw{}; + aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_qkv; aw.k = m.b_qkv; aw.v = m.b_qkv; + aw.qs = m.b_qs; + aw.attn = m.b_attn; + + MlpBF16::Wire mw{}; + mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn; + + MoeFP8::Wire fw{}; + fw.x = m.b_x; + fw.h.x = m.b_h; /* external input: the plugin's own rmsnorm writes it */ + fw.logits = m.b_rlogits; fw.ids = m.b_eids; fw.ew = m.b_ew; + fw.eoff = m.b_eoff; fw.ecnt = m.b_ecnt; + fw.sorted = m.b_sorted; fw.egu = m.b_egu; + fw.eff.x = m.a_eff.x; + fw.edn = m.b_edn; /* moe, sgu, sff, sout, sgate stay null: no block arm */ + + 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.dense = (l < m.first_dense) ? 1 : 0; + + AttnLlamaBF16::Src as{}; + as.norm = nm.ckpt("model.layers.%lld.input_layernorm.weight", (long long)l); + as.q = nm.ckpt("model.layers.%lld.self_attn.q_proj.weight", (long long)l); + as.k = nm.ckpt("model.layers.%lld.self_attn.k_proj.weight", (long long)l); + as.v = nm.ckpt("model.layers.%lld.self_attn.v_proj.weight", (long long)l); + as.o = nm.ckpt("model.layers.%lld.self_attn.o_proj.weight", (long long)l); + RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv)); + RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv, m.n_rot, aw, as)); + + if (lay.dense) { + MlpBF16::Src ms{}; + ms.norm = nm.ckpt("model.layers.%lld.post_attention_layernorm.weight", (long long)l); + ms.gate = nm.ckpt("model.layers.%lld.mlp.gate_proj.weight", (long long)l); + ms.up = nm.ckpt("model.layers.%lld.mlp.up_proj.weight", (long long)l); + ms.down = nm.ckpt("model.layers.%lld.mlp.down_proj.weight", (long long)l); + RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms)); + } else { + /* The block's norm, the shared arm and its linears, then the block. The block's norm + * is declared by the plugin (external input) because its gather folds the routed + * delta into h.x, and the shared arm reads its own copy of the normed row. */ + RAD_ARCH_TRY(declare_moe_norm_and_shared(b, m, (int)l)); + + MoeFP8::Src fs{}; + fs.cfg = mc; + fs.norm = nullptr; /* external: declared above */ + fs.router = nm.ckpt("model.layers.%lld.mlp.gate.weight", (long long)l); + fs.experts = nm.ckpt("model.layers.%lld.mlp.experts", (long long)l); + fs.shared = nullptr; /* the ungated shared arm lives in the plugin */ + RAD_ARCH_TRY(lay.moe.declare(b, nm, g, (int)l, fw, fs)); + } + } + + 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_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_out_norm)), + {m.b_x}, {m.b_h}); + + m.op_gather = rw(b, RAD_OP(b, "gather_rows", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), + RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_NOWEIGHTS), + {m.b_h}, {m.b_hout}); + + m.op_logits = rw(b, RAD_OP(b, "logits_gemm", + RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), + RAD_INT("n_vocab", g.n_vocab), + RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)), + RAD_WEIGHTS(m.w_lm_head)), + {m.b_hout}, {m.b_logits}); + + rad_note(b, "rank %d/%d: %lld layers, layer 0 dense (n_ff %lld), layers %lld..%lld MoE: " + "%lld experts top-%lld (softmax, norm_topk %d), shared arm %lld wide, " + "n_head=%lld n_head_kv=%lld head_dim=%lld vocab=[%lld,%lld) tied head", + g.rank, g.world, (long long)g.n_layer, (long long)g.n_ff, + (long long)m.first_dense, (long long)(g.n_layer - 1), + (long long)mc.n_expert_all, (long long)mc.top_k, mc.norm_topk, + (long long)mc.n_ff_shared, + (long long)g.n_head, (long long)g.n_head_kv, (long long)g.head_dim, + (long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab)); + if (win > 0) + rad_note(b, "R-SWA: the KV group is a runtime ring (RAD_KV_RING), window %lld tokens from " + "the prefill's end (the reference's SlidingWindowLlamaAttention); prefill is " + "fully causal, and prefix cache and speculation are off for it", (long long)win); + else + rad_note(b, "R-SWA: the checkpoint states no sliding_window_size, so the KV group is a " + "plain full cache"); + /* Only when the container states the processor: gen-convert copies the checkpoint's + * generation_config into `generation.*`, so a checkpoint without it gets no note. */ + const int64_t ng_n = rad_meta_geti(meta, "generation.no_repeat_ngram_size", 0); + if (ng_n > 0) + rad_note(b, "generation_config asks for SlidingWindowNoRepeatNgramProcessor n=%lld over " + "the last %lld tokens -- served by the sample_ngram_ban stage, overridable " + "per request (ngram_ban_n / ngram_window); temp-0 parity checks run with it off", + (long long)ng_n, + (long long)rad_meta_geti(meta, "generation.no_repeat_ngram_window_size", 0)); + return RAD_OK; +} + +static void step(RadCtx* c, const RadBatch* batch) { + Model& m = g_model[rad_rank(c)]; + + if (batch->enc) { + m.enc.step(c, batch); + return; + } + + RAD_ISSUE(c, m.op_embed, + praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok), + brows(m.b_x, batch->n_tok)); + if (m.op_embed_ar) + RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd, + brows(m.b_x, batch->n_tok), RAD_NONE); + if (m.op_mm && batch->n_mm_rows > 0) + RAD_ISSUE_N(c, m.op_mm, batch->n_mm_rows, + praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, m.g.n_embd), + praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, batch->n_tok)); + + for (const Layer& l : m.layers) { + l.attn.step(c, batch); + if (l.dense) { + l.mlp.step(c, batch); + } else { + const int64_t T = batch->n_tok; + /* The MoE block's norm (x -> h.x), then the shared arm beside the routed arm: both + * read the same prepared input, so the shared arm is issued while h.x still holds the + * normed row and BEFORE the block's gather overwrites it with the routed delta. The + * two residual adds commute: x += shared, then the block's x += routed. */ + RAD_ISSUE(c, l.op_moe_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T)); + RAD_ISSUE(c, l.op_sh_gu, brows(m.b_h, T), RAD_W(l.w_sh_gate_up), + brows(m.b_sgu, T)); + RAD_ISSUE(c, l.op_sh_act, brows(m.b_sgu, T), brows(m.b_sff, T)); + RAD_ISSUE(c, l.op_sh_down, brows(m.b_sff, T), RAD_W(l.w_sh_down), + brows(m.b_sout, T)); + if (l.op_sh_ar) + RAD_ISSUE_N(c, l.op_sh_ar, T * m.g.n_embd, brows(m.b_sout, T), RAD_NONE); + RAD_ISSUE(c, l.op_sh_add, brows(m.b_x, T), brows(m.b_sout, T), brows(m.b_x, T)); + l.moe.step(c, batch); + } + } + + 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)); + + 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)); + } +} + +} /* namespace unlimitedocr_bf16 */ + +#ifndef RAD_ARCH_NO_EXPORTS +RAD_ARCH_PLUGIN(unlimitedocr_bf16, "unlimitedocr", "", "0.1.0", + "baidu/Unlimited-OCR decoder: 12-layer Llama-MoE (64 experts top-6 + 2 shared), " + "bf16 weights and activations, full rotary MHA, with the DeepEncoder " + "(SAM ViT-B + CLIP ViT-L) vision tower") +#endif diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 23ea6682..e606e7e1 100644 --- a/core/build/rad_build.h +++ b/core/build/rad_build.h @@ -128,6 +128,7 @@ public: int lora_root(const char* native, const char* spellings); int lora_alias(const char* native, const char* from, const char* to, int64_t from_lo, int64_t from_hi, int64_t to_lo); + int drafter_short_block(int64_t block); int declare_encoder(const RadEncoderDecl* d); int declare_generator(const RadGeneratorDecl* d); int declare_audio_generator(const RadAudioGenDecl* d); @@ -140,6 +141,7 @@ public: int op_reads (rad_op h, const rad_buf* b, int n); int op_writes(rad_op h, const rad_buf* b, int n); int buf_concurrent(rad_buf b); + int lane1_window(bool end); int weight_shard_span(rad_weight w, int64_t lo, int64_t hi); int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi, const int64_t* total, int n); @@ -220,6 +222,8 @@ private: /* Buffers touched from the second lane (rad_buf_concurrent). Their declared op range does not * bound when their bytes are in use, so they are live for the whole program. */ std::set concurrent_bufs_; + /* The second lane's window (rad_lane1_window_begin), first and last op handle; -1 when none. */ + int32_t lane1_w0_ = -1, lane1_w1_ = -1; /* Parallel to prog_.kv_groups: where in the op list the group was declared, and the op found * to consume it. Declaration order is the only link between an op and a group; see @@ -254,7 +258,5 @@ std::string dump_graph_str(const Program& p, const std::vector* err /* The same walk as JSON, for the server's Model view, grouped by (op, band table): an op declared * once per layer with one bucket table is one row with a count. */ std::string dump_graph_json(const Program& p); -void dump_graph (const Program& p, FILE* out, - const std::vector* errors = nullptr); } /* namespace rad */ diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index 5de8deb5..2fa9d950 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -87,6 +87,7 @@ const char* bld_kv_kind_name(int k) { case RAD_KV_WINDOW: return "window"; case RAD_KV_LINEAR: return "linear"; case RAD_KV_CONV: return "conv"; + case RAD_KV_RING: return "ring"; default: return "?"; } } @@ -336,7 +337,7 @@ rad_buf Builder::decl_buffer(const char* name, const RadBufDecl* d) { rad_kvgroup Builder::decl_kv_group(const char* name, const RadKVGroupDecl* d) { if (finished_) return err(RAD_E_STATE, "decl_kv_group('%s') after declare finished", name ? name : ""); if (!name || !*name || !d) return err(RAD_E_INVAL, "decl_kv_group: null name or declaration"); - if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_CONV) + if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_RING) return err(RAD_E_INVAL, "kv group '%s': unknown kind %d", name, d->kind); std::string n = scoped(name); @@ -840,6 +841,26 @@ int Builder::buf_concurrent(rad_buf b) { return RAD_OK; } +/* See rad_lane1_window_begin. The window is the ops declared between the two calls. */ +int Builder::lane1_window(bool end) { + if (finished_) { err(RAD_E_STATE, "rad_lane1_window after declare finished"); return RAD_E_STATE; } + const int32_t next = (int32_t)prog_.ops.size(); /* the next op's handle */ + if (!end) { + if (lane1_w0_ >= 0) { + err(RAD_E_STATE, "rad_lane1_window_begin called twice: one window a program"); + return RAD_E_STATE; + } + lane1_w0_ = next; + } else { + if (lane1_w0_ < 0 || lane1_w1_ >= 0 || next - 1 < lane1_w0_) { + err(RAD_E_STATE, "rad_lane1_window_end without a begin, twice, or around no op"); + return RAD_E_STATE; + } + lane1_w1_ = next - 1; + } + return RAD_OK; +} + /* See rad_weight_shard_span. Checked against the declaration here, where the plugin can be named; * the loader checks it against the container. */ int Builder::weight_shard_span(rad_weight h, int64_t lo, int64_t hi) { @@ -923,7 +944,7 @@ int Builder::kv_group_zero(rad_kvgroup h) { * state is saved and cleared on every rank, so a zero-sized one would mismatch those * copies. */ const int kind = prog_.kv_groups[h].decl.kind; - if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) { + if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW && kind != RAD_KV_RING) { err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group that is not paged", prog_.kv_groups[h].name.c_str()); return RAD_E_INVAL; @@ -942,7 +963,10 @@ int Builder::kv_group_replicated(rad_kvgroup h) { err(RAD_E_STATE, "kv_group_replicated after declare finished"); return RAD_E_STATE; } - if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL; + if (h == 0 || h >= prog_.kv_groups.size()) { + err(RAD_E_INVAL, "kv_group_replicated: %u is not a declared KV group", (unsigned)h); + return RAD_E_INVAL; + } /* Paged groups only: the tiers move blocks. A linear or conv group's state travels in the * checkpoint store, which has no such window. */ const int kind = prog_.kv_groups[h].decl.kind; @@ -1204,6 +1228,11 @@ int Builder::declare_encoder(const RadEncoderDecl* d) { (long long)d->n_embd); return RAD_E_INVAL; } + if (d->one_grid != 0 && d->one_grid != 1) { + err(RAD_E_INVAL, "declare_encoder '%s': one_grid %d is neither 0 nor 1", nm, + (int)d->one_grid); + return RAD_E_INVAL; + } slot = *d; slot_name = nm; slot.name = nullptr; /* the plugin's storage; the name is the copy */ @@ -1389,7 +1418,12 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { : prog_.generator.layout != 0 ? "an image generator" : "a video generator"); return RAD_E_STATE; } - if (!d->tmpl || !std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}")) { + if (!d->tmpl && !d->tmpl_plain) { + err(RAD_E_INVAL, "declare_audio_generator '%s': no prompt template (tmpl or tmpl_plain)", + nm); + return RAD_E_INVAL; + } + if (d->tmpl && (!std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}"))) { err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl needs {instructions} and {input}", nm); return RAD_E_INVAL; } @@ -1399,6 +1433,45 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { "instructions and needs {input} alone", nm); 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). */ + if (d->tmpl_ref) { + auto once = [](const char* t, const char* k) { + const char* a = t ? std::strstr(t, k) : nullptr; + return a && !std::strstr(a + 1, k); + }; + const char* au = d->ref_item ? std::strstr(d->ref_item, "{audio}") : nullptr; + const char* tx = d->ref_item ? std::strstr(d->ref_item, "{text}") : nullptr; + if (!once(d->tmpl_ref, "{references}") || !once(d->tmpl_ref, "{input}") || + std::strstr(d->tmpl_ref, "{instructions}") || !once(d->ref_item, "{audio}") || + !once(d->ref_item, "{text}") || !au || !tx || tx > au) { + err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl_ref needs {references} and " + "{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 " + "%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->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); + return RAD_E_INVAL; + } + /* One branch has no unconditional prompt to render and no guidance to apply. */ + if (d->branches == 1 && (d->neg_tmpl || d->default_cfg != 1.0)) { + err(RAD_E_INVAL, "declare_audio_generator '%s': a model of one branch has no " + "unconditional template and no guidance (default_cfg %g)", nm, + d->default_cfg); + return RAD_E_INVAL; + } if (d->neg_tmpl && !d->prompt_whole) { err(RAD_E_INVAL, "declare_audio_generator '%s': an unconditional template makes branches " "of different lengths, which step together only as whole prompts; set " @@ -1476,15 +1549,24 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) { !buf_ok(d->audio_out, RAD_F32, win_samples * d->channels, "audio_out")) return RAD_E_INVAL; prog_.agen_str.name = nm; - prog_.agen_str.tmpl = d->tmpl; + prog_.agen_str.tmpl = d->tmpl ? d->tmpl : ""; 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.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. */ prog_.audio_gen.name = nullptr; prog_.audio_gen.tmpl = nullptr; prog_.audio_gen.tmpl_plain = nullptr; prog_.audio_gen.neg_tmpl = nullptr; + prog_.audio_gen.tmpl_ref = nullptr; + prog_.audio_gen.ref_item = nullptr; + /* Without references the clips' geometry is nothing: the driver stages none. */ + if (!d->tmpl_ref) { + prog_.audio_gen.ref_rate = prog_.audio_gen.ref_hop = prog_.audio_gen.ref_max_samples = 0; + prog_.audio_gen.ref_max = 0; + } return RAD_OK; } @@ -1771,6 +1853,13 @@ int Builder::declare_drafter(const RadDrafterDecl* d) { (long long)d->proposal_pitch); return RAD_E_INVAL; } + if (d->kind == RAD_DRAFT_BLOCK && d->proposal_pitch > 0 && d->proposal_pitch < d->depth) { + err(RAD_E_INVAL, "declare_drafter '%s': proposal_pitch %lld under depth %d. A block pass " + "writes each sequence's %d proposals into one row of the proposal buffer, " + "so a row must hold them.", nm, (long long)d->proposal_pitch, d->depth, + d->depth); + return RAD_E_INVAL; + } /* A block pass embeds the mask id at every unfilled position, so it needs one. */ if (d->kind == RAD_DRAFT_BLOCK && d->mask_token < 0) { err(RAD_E_INVAL, "declare_drafter '%s': RAD_DRAFT_BLOCK with no mask_token. Every " @@ -1814,7 +1903,11 @@ int Builder::declare_drafter(const RadDrafterDecl* d) { prog_.drafter_name = nm; prog_.drafter.name = nullptr; prog_.drafter.block = block; - if (prog_.drafter.proposal_pitch == 0) prog_.drafter.proposal_pitch = 1; + /* A block drafter's proposal row holds its whole block's tokens, and the engine reads row s + * at s * pitch (a short block fills only its front), so its pitch defaults to depth; a serial + * one writes a token a pass, at pitch 1 by default. */ + if (prog_.drafter.proposal_pitch == 0) + prog_.drafter.proposal_pitch = prog_.drafter.kind == RAD_DRAFT_BLOCK ? prog_.drafter.depth : 1; return RAD_OK; } @@ -1906,6 +1999,33 @@ int Builder::lora_alias(const char* native, const char* from, const char* to, in return RAD_OK; } +/* A block drafter's shorter block (rad_builder.h). Validated at declare: the core stages the block + * from it, and a block the plugin did not declare its ops at would fail the step. */ +int Builder::drafter_short_block(int64_t block) { + if (finished_) { + err(RAD_E_STATE, "drafter_short_block after declare finished"); + return RAD_E_STATE; + } + if (prog_.drafter.kind != RAD_DRAFT_BLOCK) { + err(RAD_E_STATE, "drafter_short_block: %s. Only a BLOCK drafter proposes a block; declare " + "it with rad_declare_drafter first.", + prog_.drafter.kind == RAD_DRAFT_NONE ? "no drafter is declared" + : "the declared drafter is a SERIAL head"); + return RAD_E_STATE; + } + const int64_t full = prog_.drafter.block > 0 ? prog_.drafter.block : prog_.drafter.depth + 1; + const int64_t lead = full - prog_.drafter.depth; /* rows ahead of the proposing ones */ + if (block >= full || block - lead < 1) { + err(RAD_E_INVAL, "drafter_short_block '%s': %lld rows. The short block must be shorter " + "than the drafter's own (%lld) and still propose a token (more than %lld " + "rows).", prog_.drafter_name.c_str(), (long long)block, (long long)full, + (long long)lead); + return RAD_E_INVAL; + } + prog_.drafter_short_block = block; + return RAD_OK; +} + void Builder::note_v(const char* f, va_list ap) { char msg[1024]; vsnprintf(msg, sizeof msg, f ? f : "", ap); @@ -2108,7 +2228,8 @@ void Builder::finish_kv_groups() { KVGroupInfo& gi = prog_.kv_groups[g]; const RadKVGroupDecl& d = gi.decl; - if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW) && gi.block_size == 0) { + if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW || d.kind == RAD_KV_RING) && + gi.block_size == 0) { /* The plugin may never have asked; the manifest still needs the answer. */ kv_block_size((rad_kvgroup)g); } @@ -2121,6 +2242,7 @@ void Builder::finish_kv_groups() { switch (d.kind) { case RAD_KV_FULL: case RAD_KV_WINDOW: + case RAD_KV_RING: /* One block holds K and V for block_size tokens, the block manager's unit. */ gi.bytes_per_block = rad_dtype_bytes(d.dtype, 2 * gi.block_size * elem_n_head * d.head_dim) * n_bound; @@ -2167,6 +2289,10 @@ void Builder::finish_buffer_liveness() { /* A second lane, signalled by any concurrent buffer, gets a second scratch region * (Program::scratch_regions). */ prog_.scratch_regions = concurrent_bufs_.empty() ? 1 : 2; + if (lane1_w0_ >= 0 && lane1_w1_ < 0) + err(RAD_E_STATE, "rad_lane1_window_begin without rad_lane1_window_end"); + prog_.lane1_w0 = lane1_w1_ >= 0 ? lane1_w0_ : -1; + prog_.lane1_w1 = lane1_w1_; /* Each buffer's first and last declaring op, in one pass over the op lists. */ const size_t nb = prog_.buffers.size(); @@ -2184,11 +2310,19 @@ void Builder::finish_buffer_liveness() { * rule); a buffer on the second lane, whose declared range does not bound when its bytes * are in use; and one with no declared use, since an op may issue any handle in any * order (--debug-graph reports the cost). */ - if (b.decl.kind != RAD_BUF_TRANSIENT || concurrent_bufs_.count((rad_buf)i) || first[i] < 0) { + if (b.decl.kind != RAD_BUF_TRANSIENT || first[i] < 0 || + (concurrent_bufs_.count((rad_buf)i) && lane1_w1_ < 0)) { b.first_def = 0; b.last_use = last_op; continue; } + /* A concurrent buffer under a declared window (rad_lane1_window_begin): live across the + * window, when lane 1 may touch it, and over its own uses. */ + if (concurrent_bufs_.count((rad_buf)i)) { + b.first_def = std::min(first[i], lane1_w0_); + b.last_use = std::max(last[i], lane1_w1_); + continue; + } b.first_def = first[i]; b.last_use = last[i]; @@ -2199,6 +2333,25 @@ void Builder::finish_buffer_liveness() { * output likewise: the engine reads it after the last op. */ if ((rad_buf)i == prog_.logits_buf || (rad_buf)i == prog_.pooled_buf) b.last_use = last_op; } + + /* Region 1 holds what an op the second lane may issue asks for (Program::scratch_bytes_lane1): + * every transient buffer of such an op is concurrent (Ctx::lane1_ rule 3). Ctx::issue refuses a + * larger request on lane 1 by name, so an op that breaks the rule fails rather than overruns. */ + prog_.scratch_bytes_lane1 = 0; + if (prog_.scratch_regions > 1) + for (size_t o = 1; o < prog_.ops.size() && o < op_bufs_.size(); ++o) { + bool lane1 = true; + for (const std::vector* v : { &op_bufs_[o].reads, &op_bufs_[o].writes }) + for (rad_buf h : *v) + if (prog_.buffers[h].decl.kind == RAD_BUF_TRANSIENT && !concurrent_bufs_.count(h)) + lane1 = false; + if (!lane1) continue; + for (const Band& bd : prog_.ops[o].bands) + if (bd.dom[RAD_DOMAIN_DEVICE] && + bd.dom[RAD_DOMAIN_DEVICE].scratch_bytes > prog_.scratch_bytes_lane1) + prog_.scratch_bytes_lane1 = bd.dom[RAD_DOMAIN_DEVICE].scratch_bytes; + } + if (prog_.scratch_bytes_lane1 > prog_.scratch_bytes) prog_.scratch_bytes_lane1 = prog_.scratch_bytes; } int Builder::finish() { @@ -2331,6 +2484,16 @@ int rad_buf_concurrent(RadBuilder* b, rad_buf buf) { return B(b)->buf_concurrent(buf); } +int rad_lane1_window_begin(RadBuilder* b) { + if (!b) return RAD_E_INVAL; + return B(b)->lane1_window(false); +} + +int rad_lane1_window_end(RadBuilder* b) { + if (!b) return RAD_E_INVAL; + return B(b)->lane1_window(true); +} + int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) { if (!b) return RAD_E_INVAL; return B(b)->weight_shard_span(w, lo, hi); @@ -2390,6 +2553,11 @@ int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const ch int rad_chain_on(void) { return rad_dev_chain_enabled(); } +int rad_drafter_short_block(RadBuilder* b, int64_t block) { + if (!b) return RAD_E_INVAL; + return B(b)->drafter_short_block(block); +} + int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) { if (!b) return RAD_E_INVAL; return B(b)->declare_encoder(d); diff --git a/core/build/rad_graph.cpp b/core/build/rad_graph.cpp index 410544bc..5ed7e372 100644 --- a/core/build/rad_graph.cpp +++ b/core/build/rad_graph.cpp @@ -364,12 +364,6 @@ std::string dump_graph_str(const Program& p, const std::vector* err return s; } -void dump_graph(const Program& p, FILE* out, const std::vector* errors) { - std::string s = dump_graph_str(p, errors); - fwrite(s.data(), 1, s.size(), out ? out : stderr); - fflush(out ? out : stderr); -} - /* ================================================================== the graph, as JSON * * dump_graph_str's content and more, for the server's Model view. It walks the same Program with diff --git a/core/build/startup.cpp b/core/build/startup.cpp index 9b491993..65bbf5af 100644 --- a/core/build/startup.cpp +++ b/core/build/startup.cpp @@ -270,7 +270,12 @@ int rad_tools_text_prepare(const LoadedPlugins& lp, int field, const std::string std::string buf(in.size() * 2 + 64, '\0'); for (int tries = 0; tries < 2; ++tries) { const int64_t n = ap->arch_text_prepare(field, in.c_str(), &buf[0], (int64_t)buf.size()); - if (n < 0) return (int)n; + if (n < 0) { + /* The plugin's reason, when it left one in the (zeroed) buffer. */ + buf.resize(std::strlen(buf.c_str())); + *out = std::move(buf); + return (int)n; + } if (n < (int64_t)buf.size()) { buf.resize((size_t)n); *out = std::move(buf); diff --git a/core/build/startup.h b/core/build/startup.h index 540f6ab7..e3d7151e 100644 --- a/core/build/startup.h +++ b/core/build/startup.h @@ -93,7 +93,7 @@ const RadAudioFormat* rad_tools_audio_format(const LoadedPlugins& plugins, const * (rad_arch_text_prepare): RAD_OK with the result in `*out` (the text unchanged when the plugin * states no rewrite), or the plugin's negative status. */ int rad_tools_text_prepare(const LoadedPlugins& plugins, int field, const std::string& in, - std::string* out); + std::string* out); /* on a refusal, `out` is its reason or "" */ /* The architecture plugin's video positions (rad_arch_video_positions), or null when it exports * none. */ diff --git a/core/config.cpp b/core/config.cpp index 812fd72f..fa8ffc0b 100644 --- a/core/config.cpp +++ b/core/config.cpp @@ -56,6 +56,10 @@ static const Flag g_flags[] = { "lossy wire: rotated 6-bit at 2 ranks, tiered int8 at 3\n" "and 4, none at 8" }, { "--tp-wire-min-kb", "N", "smallest all-reduce, in KiB, the lossy wire is used for" }, + { "--tp-attn-split", "MODE", "heads (default) | rows -- how a prefill-sized step's\n" + "attention splits over the ranks: rows gives each rank all\n" + "heads of its rows, a faster prefill for the projections at\n" + "full width on every card; not bit-identical to heads" }, { "--p2p", "MODE", "how the collectives reach the other cards: auto (default)\n" "asks the driver, on requires peer access and stops without\n" "it, off exchanges through pinned host memory" }, @@ -75,6 +79,12 @@ static const Flag g_flags[] = { { "--kv-cache-dtype", "T", "bf16 | fp8 | fp8_v4 | k6_v4 -- fp8 halves what a token of\n" "context costs; fp8_v4 keeps V in 4 bits (0.78 of fp8), k6_v4\n" "also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" }, + { "--state-cache-dtype", "T", "f32 (default) | f16 -- the recurrent state cache (delta net):\n" + "f16 halves the state pool, its checkpoints and its traffic,\n" + "and is lossy; the qwen35 plugins serve it" }, + { "--attn-prefill-fp8", "MODE", "off (default) | qk | pv | both -- the prefill attention's\n" + "Q.K^T, P.V or both as e4m3 WMMA over an fp8, fp8_v4 or\n" + "k6_v4 cache: faster at long context, and lossy" }, { "--host-pool-mib", "N", "pinned host tier" }, { "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n" " pins its host memory at startup (default 4096)" }, @@ -155,6 +165,13 @@ static const Flag g_flags[] = { " own operating point, which the plugin states. A container\n" " with no draft head is unaffected -- auto resolves to 0." }, { "--draft-window", "MODE", g_draft_window_help.c_str() }, + { "--draft-short-from", "N", "a block drafter that also serves a shorter block runs it\n" + "from N decoding sequences on (0 never, the default): the\n" + "long block pays at one sequence, the short one at many" }, + { "--draft-coupling", "MODE", "off (default) | on -- a linear MTP drafter samples each proposal\n" + " from its own shortlist and the sampler couples the target's draw\n" + " to it: more accepted drafts on sampled requests, the same output\n" + " law, other tokens than off for a fixed seed" }, { "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" }, { "--host", "ADDR", "listen address" }, @@ -438,6 +455,12 @@ int config_parse(int argc, char** argv, Config* c) { else if (!std::strcmp(v, "wht6")) c->tp_wire_exact = 0; else { RAD_ERR("--tp-wire takes exact or wht6, not '%s'", v); return RAD_E_INVAL; } } + else if (S("--tp-attn-split")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!std::strcmp(v, "heads")) c->tp_attn_rows = 0; + else if (!std::strcmp(v, "rows")) c->tp_attn_rows = 1; + else { RAD_ERR("--tp-attn-split takes heads or rows, not '%s'", v); return RAD_E_INVAL; } + } else if (S("--p2p")) { if (!(v = need(i))) return RAD_E_INVAL; if (!std::strcmp(v, "auto")) c->p2p = RAD_P2P_AUTO; @@ -489,6 +512,25 @@ int config_parse(int argc, char** argv, Config* c) { } c->kv_cache_dtype = v; } + else if (S("--state-cache-dtype")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (std::strcmp(v, "f32") && std::strcmp(v, "f16")) { + RAD_ERR("--state-cache-dtype takes f32 or f16, not '%s'", v); + return RAD_E_INVAL; + } + c->state_cache_dtype = v; + } + else if (S("--attn-prefill-fp8")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!std::strcmp(v, "off")) c->attn_prefill_fp8 = 0; + else if (!std::strcmp(v, "qk")) c->attn_prefill_fp8 = RAD_ATTN_FP8_QK; + else if (!std::strcmp(v, "pv")) c->attn_prefill_fp8 = RAD_ATTN_FP8_PV; + else if (!std::strcmp(v, "both")) c->attn_prefill_fp8 = RAD_ATTN_FP8_QK | RAD_ATTN_FP8_PV; + else { + RAD_ERR("--attn-prefill-fp8 takes off, qk, pv or both, not '%s'", v); + return RAD_E_INVAL; + } + } else if (S("--host-pool-mib")) { if (!num(0, INT64_MAX, &c->host_pool_mib)) return RAD_E_INVAL; } else if (S("--embedding-placement") || S("--ngram-placement")) { const bool emb = S("--embedding-placement"); @@ -638,6 +680,16 @@ int config_parse(int argc, char** argv, Config* c) { return RAD_E_INVAL; } } + else if (S("--draft-short-from")) { if (!num(0, INT32_MAX, &c->draft_short_from)) return RAD_E_INVAL; } + else if (S("--draft-coupling")) { + if (!(v = need(i))) return RAD_E_INVAL; + if (!std::strcmp(v, "off")) c->draft_coupling = false; + else if (!std::strcmp(v, "on")) c->draft_coupling = true; + else { + RAD_ERR("--draft-coupling takes off or on, not '%s'", v); + return RAD_E_INVAL; + } + } else if (S("--draft-model")) { /* Refused, not ignored: separate draft models are not supported (spec §10), and the * drafter comes from the container (rad-convert --draft-model merges one in; an MTP @@ -971,6 +1023,16 @@ int config_parse(int argc, char** argv, Config* c) { return RAD_OK; } +const char* attn_prefill_fp8_name(int bits) { + switch (bits) { + case 0: return "off"; + case RAD_ATTN_FP8_QK: return "qk"; + case RAD_ATTN_FP8_PV: return "pv"; + case RAD_ATTN_FP8_QK | RAD_ATTN_FP8_PV: return "both"; + } + return "?"; +} + /* ------------------------------------------------------------------ the startup report's rows */ namespace { @@ -1010,6 +1072,7 @@ const ShowRow kShow[] = { return or_none(s, "every library found"); } }, { "--tp", [](const Config& c) { return num(c.tp); } }, { "--tp-wire", [](const Config& c) { return std::string(c.tp_wire_exact ? "exact" : "wht6"); } }, + { "--tp-attn-split", [](const Config& c) { return std::string(c.tp_attn_rows ? "rows" : "heads"); } }, { "--tp-wire-min-kb", [](const Config& c) { return num(c.tp_wire_min_kb); } }, { "--p2p", [](const Config& c) { return std::string(c.p2p == RAD_P2P_ON ? "on" : c.p2p == RAD_P2P_OFF ? "off" : "auto"); } }, @@ -1025,6 +1088,9 @@ const ShowRow kShow[] = { { "--rope-scaling", [](const Config& c) { return or_none(c.rope_scaling, "the checkpoint's own"); } }, { "--gpu-headroom-mib", [](const Config& c) { return num(c.gpu_headroom_mib); } }, { "--kv-cache-dtype", [](const Config& c) { return c.kv_cache_dtype; } }, + { "--state-cache-dtype", [](const Config& c) { return c.state_cache_dtype; } }, + { "--attn-prefill-fp8", [](const Config& c) { + return std::string(attn_prefill_fp8_name(c.attn_prefill_fp8)); } }, { "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } }, { "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } }, { "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } }, @@ -1061,6 +1127,9 @@ const ShowRow kShow[] = { { "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } }, { "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } }, { "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } }, + { "--draft-short-from", [](const Config& c) { + return c.draft_short_from > 0 ? num(c.draft_short_from) : std::string("0 (never)"); } }, + { "--draft-coupling", [](const Config& c) { return onoff(c.draft_coupling); } }, { "--draft-model", [](const Config&) { return std::string("not implemented (the container's own drafter)"); } }, { "--host", [](const Config& c) { return c.host; } }, { "--port", [](const Config& c) { return num(c.port); } }, diff --git a/core/cvec.cpp b/core/cvec.cpp index b2c2840e..20661b4b 100644 --- a/core/cvec.cpp +++ b/core/cvec.cpp @@ -1,18 +1,5 @@ -/* cvec.cpp -- loading and validating a GGUF control vector (core/cvec.h). - * - * The format is llama.cpp's `controlvector` package: one `direction.` tensor of unit f32 per - * layer, plus three metadata keys. The reader is core/text/gguf.cpp, which already mmaps a GGUF - * and computes tensor byte sizes, so nothing here parses bytes by hand. - * - * The published package (hf.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection) is what the checks - * below are written against, and its own JSON states the operation's parameters: - * - * {"mode": "project", "dir": "per-layer", "scale": 1.0, "layer_range": [4, 44], ...} - * - * so a file is only accepted for a model whose hidden size equals the directions' width and whose - * architecture the file names. Everything else is refused at startup, by name, rather than - * steered along a direction from another residual basis. - */ +/* cvec.cpp -- loading and validating a GGUF control vector (core/cvec.h). The reader is + * core/text/gguf.cpp, which maps the file and sizes its tensors. */ #include "cvec.h" #include "text/gguf.h" @@ -98,10 +85,10 @@ int control_vector_discover(const std::string& model_path, const std::string& ar } -/* The package's own JSON, if it is beside the vector: `{"mode": "project", "scale": 1.0, - * "layer_range": [4, 44]}` is what the published Flash-Next vector ships. It is the only place - * the operation's parameters are stated, so they are read from there rather than configured; a - * malformed or absent file only means the defaults below. */ +/* The package's own JSON beside the vector (`.json`), the only place the operation's + * parameters are stated: `{"mode": "project", "scale": 1.0, "layer_range": [4, 44]}` for the + * published Flash-Next vector. Absent, the defaults apply. A file that is not JSON or names a mode + * other than `project` is refused: the directions were tuned for that operation. */ namespace { struct PackageJson { @@ -109,8 +96,8 @@ struct PackageJson { float scale = 1.0f; }; -PackageJson read_package_json(const std::string& gguf_path) { - PackageJson out; +int read_package_json(const std::string& gguf_path, PackageJson* out, std::string* why) { + *out = PackageJson{}; std::string stem = gguf_path; const size_t dot = stem.find_last_of('.'); const size_t slash = stem.find_last_of("/\\"); @@ -118,28 +105,28 @@ PackageJson read_package_json(const std::string& gguf_path) { stem = stem.substr(0, dot); const std::string path = stem + ".json"; std::ifstream f(path); - if (!f) return out; + if (!f) return RAD_OK; try { const nlohmann::json j = nlohmann::json::parse(f); if (const auto m = j.find("mode"); m != j.end() && m->is_string() && m->get() != "project") { - RAD_WARN("control vector: %s says mode '%s'; only 'project' is implemented, so the " - "defaults apply", path.c_str(), m->get().c_str()); - return out; + *why = "control vector " + path + ": mode '" + m->get() + + "'; only 'project' is implemented"; + return RAD_E_UNSUPPORTED; } if (const auto r = j.find("layer_range"); r != j.end() && r->is_array() && r->size() == 2 && (*r)[0].is_number_integer() && (*r)[1].is_number_integer()) { - out.first = (*r)[0].get(); - out.last = (*r)[1].get(); + out->first = (*r)[0].get(); + out->last = (*r)[1].get(); } if (const auto s = j.find("scale"); s != j.end() && s->is_number()) - out.scale = (float) s->get(); + out->scale = (float) s->get(); } catch (const std::exception& e) { - RAD_WARN("control vector: %s is not readable JSON (%s); the defaults apply", path.c_str(), - e.what()); + *why = "control vector " + path + ": not readable JSON (" + e.what() + ")"; + return RAD_E_INVAL; } - return out; + return RAD_OK; } } /* namespace */ @@ -206,16 +193,14 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_ } if (n_dir == 0) return fail("control vector " + path + ": the file holds no directions"); - /* The package's parameters: its JSON, else the published selection where the file covers it, - * else every direction the file carries. A deployment therefore has nothing to configure, and - * a file published with a different selection states it itself. */ - const PackageJson pj = read_package_json(path); + /* The package's parameters: its JSON, else every direction the file carries at scale 1, as + * llama.cpp applies a control vector given no layer range. */ + PackageJson pj; + std::string pj_why; + if (const int prc = read_package_json(path, &pj, &pj_why); prc != RAD_OK) return fail(pj_why); int first = pj.first, last = pj.last; float scale = pj.scale; - if (last < 0) { - if (n_model_layers >= 45 && dir_last >= 44) { first = 4; last = 44; } - else { first = (int) dir_first; last = (int) dir_last; } - } + if (last < 0) { first = (int) dir_first; last = (int) dir_last; } if (first < 1 || last < first) return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" + std::to_string(last) + " is empty"); diff --git a/core/cvec.h b/core/cvec.h index 2378b9f4..31faebcb 100644 --- a/core/cvec.h +++ b/core/cvec.h @@ -1,36 +1,26 @@ /* cvec.h -- control vectors: one GGUF direction per layer, projected out of the residual stream. * - * ============================== what it is ============================== + * The format is llama.cpp's `controlvector` GGUF: `direction.` tensors of f32, n_embd wide. The + * operation is llama.cpp's `--cvec-mode project` * - * The package at huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection carries one unit - * direction per layer (`direction.1` .. `direction.47`, 2560 f32 each) and the configuration its - * authors selected: the llama.cpp `--cvec-mode project` operation + * h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l| * package scale * - * h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l| + * applied by an architecture plugin that declares RadArchProbe::control_vector_ok (qwen4exp_fp8 + * issues `hc_project` on every stream of its gated residual). The layer range and scale come from + * the package's JSON beside the file; without one, every direction the file carries steers at + * scale 1. * - * over layers 4..44, applied to every stream of the gated residual. Strata ports the same - * package (`data/experimental-speed-projection`) with the same operation, range and per-request - * switch; this is that port for radiance, which has its own graph and cannot use llama.cpp's - * patch (arch/qwen4exp_fp8 issues `hc_project` from the op vocabulary instead). + * The vector shipped in data/vectors/ is a refusal-direction projection for Qwen3.8-Flash-Next: + * with it on, the model declines far fewer requests. It is loaded only with --control-vector, and + * each request can name its own choice. * - * The vector is a refusal-direction projection: with it on the model declines far fewer requests. - * Removing refusals removes a safety behaviour, so the default is OFF and every request names its - * own choice, and the file is only read when the engine finds one for this container. - * - * ============================== compatibility, checked, not assumed ============================== - * - * Nothing here trusts the file's provenance. A vector is refused unless + * A file is refused unless * * - `general.architecture` is `controlvector`, - * - `controlvector.model_hint`, when present, names this model's architecture plugin - * (`qwen4exp`), since a direction from another architecture's residual basis is noise, - * - every tensor is `direction.`, F32, one dimension, and exactly the model's `n_embd`, + * - `controlvector.model_hint`, when present, is this model's architecture id, + * - every tensor is `direction.`, F32, one dimension, exactly the model's `n_embd`, and + * 1 <= l < the model's layer count, * - the layer range lies inside the model and every layer in it has a direction. - * - * The published Flash-Next vector passes all four against a Flash-Next container: 47 tensors of - * 2560 f32, hint `qwen4exp`, range 4..44 of 48 layers. A 27B, Gemma or Qwen3.6 container refuses - * it at startup with the reason, rather than serving a model whose hidden states are moved along - * an unrelated direction. */ #pragma once #include "rad_internal.h" @@ -62,12 +52,9 @@ struct ControlVector { } }; -/* Read and validate `path` against a model of `n_embd` and `n_model_layers`. - * - * The operation's parameters come with the package, never from a command line: `path`'s own - * `.json` (the JSON the vector is published with) supplies `layer_range` and `scale` when it - * says `"mode": "project"`. Without one, the range is the published Qwen3.8-Flash-Next selection - * (4..44) where the file has directions there, else every layer the file carries, at scale 1. */ +/* Read and validate `path` against a model of `n_embd` and `n_model_layers`. `path`'s own + * `.json` supplies `layer_range` and `scale`; one that is not JSON or names a mode other than + * `project` is refused. Without it, every layer the file carries steers at scale 1. */ int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd, int64_t n_model_layers, ControlVector* out, std::string* err); @@ -77,8 +64,7 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_ * already knows the generation-config convention knows this one. */ std::string control_vector_sidecar_path(const std::string& model_path); -/* Resolve `auto`: sets *found to the first candidate that exists and is non-empty, or to "" when - * none does. *tried receives the candidates, for the log line that says why the feature is +/* Sets *found to the first candidate that exists and is non-empty, or to "" when none does. *tried receives the candidates, for the log line that says why the feature is * unavailable on this deployment. Discovery is a filesystem test only; whether the file is * compatible is control_vector_load's answer. */ int control_vector_discover(const std::string& model_path, const std::string& arch, diff --git a/core/device/aql.cpp b/core/device/aql.cpp index 96da9b75..748d74bd 100644 --- a/core/device/aql.cpp +++ b/core/device/aql.cpp @@ -241,6 +241,9 @@ Global& G() { return *g; } +/* Set by aql_force_host_kargs before the backend starts. */ +std::atomic g_force_host_kargs{false}; + std::string agent_isa(hsa_agent_t a) { char name[64] = {0}; hsa_agent_get_info(a, HSA_AGENT_INFO_NAME, name); @@ -423,13 +426,10 @@ bool init_devices() { "difference where the slot allows it", i, bus); } - /* The fallback on a card that needs none, to measure what reading each dispatch's - * arguments across the link costs against the same card's VRAM rings. */ - const char* force_host_kargs = std::getenv("RADIANCE_DEBUG_AQL_HOST_KARGS"); - if (force_host_kargs && *force_host_kargs && *force_host_kargs != '0') { + if (g_force_host_kargs.load(std::memory_order_acquire) && !g.dev[(size_t)i].host_kargs) { g.dev[(size_t)i].host_kargs = true; - RAD_WARN("device: card %d (%s): RADIANCE_DEBUG_AQL_HOST_KARGS puts the kernel argument " - "rings in host memory", i, bus); + RAD_INFO("device: card %d (%s) keeps kernel arguments in pinned host memory, as a " + "test asked", i, bus); } } /* Without the handler a fault falls back to the runtime's own handling, which the @@ -829,7 +829,7 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) { /* The running kernel and its arguments. A queue's read index stays on a packet until it * completes, so the packet there is in flight. Every pointer-shaped argument word is located * like the address, which names the operand that got a stale or short buffer. Only card - * `card`'s queues; arguments are read back through the BAR. */ + * `card`'s queues; the host reads the arguments at the packet's kernarg_address. */ std::lock_guard sl(G().streams_mu); for (Stream* s : G().streams) { if (s->ord != card) continue; @@ -3049,9 +3049,70 @@ int vres_ord(const void* addr) { return -1; } +/* The DRM interface version of card `gpu_id`'s render node, false when it cannot be read. */ +bool drm_version(uint32_t gpu_id, int* major, int* minor, std::string* name) { + /* struct drm_version, a layout fixed since DRM's first release. */ + struct DrmVersion { + int major, minor, patch; + size_t name_len; + char* name; + size_t date_len; + char* date; + size_t desc_len; + char* desc; + }; + const int rm = render_minor(gpu_id); + if (rm < 0) return false; + char path[64]; + std::snprintf(path, sizeof path, "/dev/dri/renderD%d", rm); + const int fd = open(path, O_RDWR | O_CLOEXEC); + if (fd < 0) return false; + char nm[32] = {0}; + DrmVersion v{}; + v.name = nm; + v.name_len = sizeof nm - 1; + const bool ok = ioctl(fd, _IOWR('d', 0x00, DrmVersion), &v) == 0; + close(fd); + if (!ok) return false; + *major = v.major; + *minor = v.minor; + *name = std::string(nm, std::min(v.name_len, sizeof nm - 1)); + return true; +} + +/* Whether hsa_amd_vmem mappings on card `dev` return. From HIP 7.16 (ROCm 10.1) the runtime maps + * a vmem handle with DRM_AMDGPU_GEM_VA, asks the kernel to signal a VM timeline syncobj once the + * page tables are written, and waits on that point with no timeout. amdgpu reads the timeline + * fields of GEM_VA from interface 3.64 (Linux 6.16) on; an older kernel ignores them, never + * signals the point, and the first commit waits forever in drm_syncobj_array_wait_timeout. The + * ROCm 7.2 runtime maps through the KFD and has no such wait. A card that would hang this way + * gets no virtual memory management: its pools are carved whole, as on a driver without it. */ +bool vmem_maps_return(int dev) { + static std::once_flag once[kMaxDevices]; + static bool ok[kMaxDevices]; + std::call_once(once[dev], [dev] { + ok[dev] = true; + int hip = 0; + if (hipRuntimeGetVersion(&hip) != hipSuccess || hip < 71600000) return; + int major = 0, minor = 0; + std::string name; + if (!drm_version(G().dev[(size_t)dev].kfd_id, &major, &minor, &name) || name != "amdgpu") + return; + if (major > 3 || (major == 3 && minor >= 64)) return; + ok[dev] = false; + RAD_WARN("device %d: this kernel's amdgpu interface is %d.%d, and the HIP %d.%d runtime " + "waits after every virtual-memory map for a page-table timeline that amdgpu " + "signals only from 3.64 (Linux 6.16) on, so a map here would never return. The " + "card runs without virtual memory management; a 6.16 or later kernel restores it", + dev, major, minor, hip / 10000000, hip / 100000 % 100); + }); + return ok[dev]; +} + int64_t a_vmem_granularity(void) { int dev = 0; if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= (int)G().dev.size()) return 0; + if (!vmem_maps_return(dev)) return 0; size_t gran = 0; if (hsa_amd_memory_pool_get_info(G().dev[(size_t)dev].vram, HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_REC_GRANULE, &gran) != @@ -3550,6 +3611,12 @@ const DeviceBackend* aql_backend_if_present(void) { int64_t aql_pageable_bytes(void) { return aql::g_pageable_bytes.load(std::memory_order_relaxed); } +int aql_force_host_kargs(void) { + if (aql::G().ok) return RAD_E_STATE; + aql::g_force_host_kargs.store(true, std::memory_order_release); + return RAD_OK; +} + int aql_vmem_device_of(const void* addr, int* dev) { const int d = vres_ord(addr); if (d < 0) return RAD_E_NOTFOUND; diff --git a/core/device/device.h b/core/device/device.h index a14df707..0d9655ce 100644 --- a/core/device/device.h +++ b/core/device/device.h @@ -38,11 +38,9 @@ extern "C" int rad_event_create_as(RadEvent* out, unsigned flags); extern "C" void rad_dev_host_wrote(void); /* Chained launches: chainable rows run their chained forms (RadKernelChainFn), and the backend * lets a chained kernel (named r4dchain*) wait in its prologue instead of behind the barrier bit. - * Only on the AQL backend, whose queues keep the completion counter. On by default where the - * model's plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays: the - * Gemma 4 31B and 26B) and that drafter decodes speculatively (rad_dev_chain_infer, from the - * engine before any row resolves). RADIANCE_CHAIN=0 turns them off and =1 on wherever the backend - * chains; `auto` is the default. */ + * Only on the AQL backend, whose queues keep the completion counter, and only where the model's + * plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter + * decodes speculatively (rad_dev_chain_infer, from the engine before any row resolves). */ extern "C" int rad_dev_chain_enabled(void); extern "C" void rad_dev_chain_infer(int pays); @@ -472,6 +470,10 @@ const DeviceBackend* hip_backend_if_present(void); /* The HIP backend with streams, events, copies and fills replaced by AQL packets the engine writes * itself (aql.cpp). Aborts with the reason on a machine it cannot run on. */ const DeviceBackend* aql_backend_if_present(void); +/* For tests: every card keeps its kernel argument rings and recorded-pass argument blocks in pinned + * host memory, the placement a card whose PCI BAR is smaller than its VRAM gets, so that path runs + * on any card. Takes effect only before the backend starts; RAD_E_STATE after. */ +int aql_force_host_kargs(void); /* Bytes copied to or from pageable host memory so far; each such copy is a host wait. */ int64_t aql_pageable_bytes(void); /* Fat binaries registered so far, counted whichever backend runs: the registration hooks are this diff --git a/core/device/dispatch.cpp b/core/device/dispatch.cpp index f0599462..cf075dd6 100644 --- a/core/device/dispatch.cpp +++ b/core/device/dispatch.cpp @@ -557,7 +557,7 @@ int rad_event_sync(RadEvent e) { } void rad_dev_host_wrote(void) { dev()->host_wrote(); } -/* Chaining's default, from the engine (rad_dev_chain_infer), and the answer once taken. Only +/* Whether launches chain, from the engine (rad_dev_chain_infer), and the answer once taken. Only * where the backend chains: the AQL backend writes the record a chained form reads, while a HIP * launch carries only the kernel's own arguments. */ static std::atomic g_chain_pays{0}; @@ -569,11 +569,10 @@ void rad_dev_chain_infer(int pays) { int rad_dev_chain_enabled(void) { int on = g_chain.load(std::memory_order_relaxed); if (on < 0) { - const char* e = std::getenv("RADIANCE_CHAIN"); - const bool want = e && *e && std::strcmp(e, "auto") != 0 - ? *e != '0' - : g_chain_pays.load(std::memory_order_relaxed) != 0; - on = want && std::strcmp(rad::device_backend_name(), "aql") == 0 ? 1 : 0; + on = g_chain_pays.load(std::memory_order_relaxed) != 0 && + std::strcmp(rad::device_backend_name(), "aql") == 0 + ? 1 + : 0; g_chain.store(on, std::memory_order_relaxed); } return on; diff --git a/core/engine.cpp b/core/engine.cpp index 40720b76..b1540b61 100644 --- a/core/engine.cpp +++ b/core/engine.cpp @@ -156,6 +156,7 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool sc.max_spec = cfg_.n_spec; sc.rank = rank; sc.world_size = cfg_.tp; + sc.draft_coupling = cfg_.draft_coupling; RAD_TRY(smp.declare(b, sc)); /* Where the chain writes the sampled ids. The engine declares it because rad-kbench drives the @@ -354,7 +355,7 @@ int Engine::issue_ahead(const RadBatch** out) { for (int i = 0; i < serial_rows_ && serial_done_ > 0; ++i) sched_.expect_draft(serial_row_[(size_t)i].seq, serial_done_); for (int i = 0; i < block_rows_; ++i) - sched_.expect_draft(block_row_[(size_t)i].seq, drafter_.depth); + sched_.expect_draft(block_row_[(size_t)i].seq, block_steps_); const RadBatch* nb = sched_.step_next(); if (!nb) return RAD_OK; /* Its rows' tokens, positions and slots, advanced on the card behind this step's acceptance @@ -405,13 +406,9 @@ int Engine::step_loop() { int idle = 0; std::vector cancel; /* Not in KL mode: its scored rows are copied out of the logits buffer after collection, and a - * pass issued ahead would overwrite them. A block drafter pipelines only on the card - * (engine_draft.cpp); the host's driver stages from the committed sequence. */ - block_card_ = drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0 && !cfg_.kld() && - !embedding_ && [] { const char* v = std::getenv("RADIANCE_DRAFT_BLOCK_HOST"); - return !(v && *v && *v != '0'); }(); - pipelining_ = !cfg_.kld() && !embedding_ && (drafter_.kind != RAD_DRAFT_BLOCK || block_card_) && - (serial_drafting() || block_card_ || cfg_.n_spec <= 0); + * pass issued ahead would overwrite them. */ + pipelining_ = !cfg_.kld() && !embedding_ && + (serial_drafting() || block_drafting() || cfg_.n_spec <= 0); const bool t_on = (int)log_level() >= (int)Log::Debug; /* The next step's forward pass when already issued behind the previous step, before its * readback (Scheduler::step_next). */ @@ -456,22 +453,7 @@ int Engine::step_loop() { idle = 0; if (t_on) phase_mark(PH_PLAN); - /* Zero freshly assigned recurrent slots before the step that reads them. The manager - * records the grab but cannot write (StateClear in core/mem/kv.h); the list is empty except - * on a sequence's first step. Each rank clears by its own plan: the slot number is the - * scheduler's, but the state size depends on the heads this rank holds, which can differ - * per rank (rad_arch.h remainder_place). */ - for (const StateClear& c : ranks_[0]->kv.state_clears()) { - for (auto& rk : ranks_) { - const KVGroupPlan* gp = rk->kv.plan(c.group); - if (!gp || !gp->stateful()) continue; - const int64_t bytes = gp->layer_bytes_per_state(); - for (int64_t l = 0; l < gp->n_layers; ++l) - if (void* p = rk->kv.state_ptr(c.group, (int32_t)l, c.slot)) - rad_memset_async(p, 0, bytes, rk->ctx.stream()); - } - } - ranks_[0]->kv.clear_state_clears(); + clear_fresh_states(); /* Entries that want logits rows, in BatchBuilder's out_ids order: those with * produces_token, 1 + n_spec rows each. Row and sequence indices differ (a mid-prompt @@ -530,7 +512,7 @@ int Engine::step_loop() { } if (t_on) phase_mark(PH_BEGIN); for (auto& rk : ranks_) { - const int s = rk->sampler.build_step(so.reqs); + const int s = rk->sampler.build_step(so.reqs, b->step); if (s < 0) { RAD_ERR("sampler build_step: %s", rad_strerror(s)); return s; } /* A request the sampler could not serve is cancelled; the step goes on. */ for (uint64_t id : rk->sampler.take_failed()) cancel.push_back(id); @@ -705,7 +687,8 @@ int Engine::step_loop() { /* Queue the drafter's passes behind the step before waiting: the card computes acceptance * itself and every pass reads it there (sched/advance.h), so one wait covers the whole * step. */ - st = block_card_ ? issue_block_drafter(b->step, so) : issue_serial_drafter(b->step, so); + st = block_drafting() ? issue_block_drafter(b->step, so) + : issue_serial_drafter(b->step, so); if (st < 0) return fail_loop(st); st = mark_step_end(b, so); if (st < 0) return fail_loop(st); @@ -717,6 +700,9 @@ int Engine::step_loop() { st = embedding_ ? collect_pooled(b, so) : collect_step(b, so); if (t_on) phase_mark(PH_COLLECT); if (st < 0) return fail_loop(st); + /* The step's sampler chain, verify op included, has returned: one line at the first + * coupled verify that actually completed. */ + couple_verify_evidence(b->step); if (cfg_.kld()) { st = score_rows(b, so); if (st < 0) return fail_loop(st); @@ -769,13 +755,10 @@ int Engine::step_loop() { if (t_on) phase_mark(PH_COMMIT); if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); } - /* The drafter for the next step. The host's block driver runs here, since it stages from - * the committed sequence. A serial one, or a block one on the card, already ran; what - * remains is to check its acceptance against the host's and publish its proposals. Each - * driver returns immediately for a kind that is not its own. */ - st = drafter_.kind != RAD_DRAFT_BLOCK ? finish_serial_drafter(so) - : block_card_ ? finish_block_drafter(so) - : run_block_drafter(b->step); + /* The drafter for the next step already ran on the card; what remains is to check its + * acceptance against the host's and publish its proposals. Each driver returns + * immediately for a kind that is not its own. */ + st = block_drafting() ? finish_block_drafter(so) : finish_serial_drafter(so); if (st < 0) return fail_loop(st); /* The step ends here, after its draft rounds, so step timing includes them * (Scheduler::step_finished). */ @@ -1370,6 +1353,25 @@ void Engine::drain_completed() { for (uint64_t id : done_) for (auto& rk : ranks_) rk->sampler.end_request(id); } +/* Zero freshly assigned recurrent slots before the step that reads them. The manager records the + * grab but cannot write (StateClear in core/mem/kv.h); the list is empty except on a sequence's + * first step. Each rank clears by its own plan: the slot number is the scheduler's, but the state + * size depends on the heads this rank holds, which can differ per rank (rad_arch.h + * remainder_place). */ +void Engine::clear_fresh_states() { + for (const StateClear& c : ranks_[0]->kv.state_clears()) { + for (auto& rk : ranks_) { + const KVGroupPlan* gp = rk->kv.plan(c.group); + if (!gp || !gp->stateful()) continue; + const int64_t bytes = gp->layer_bytes_per_state(); + for (int64_t l = 0; l < gp->n_layers; ++l) + if (void* p = rk->kv.state_ptr(c.group, (int32_t)l, c.slot)) + rad_memset_async(p, 0, bytes, rk->ctx.stream()); + } + } + ranks_[0]->kv.clear_state_clears(); +} + int Engine::serve(std::unique_ptr watch) { startup_watch_ = std::move(watch); if (ranks_.empty() || !ranks_[0]->ctx.program()) { @@ -1491,15 +1493,16 @@ int Engine::serve(std::unique_ptr watch) { auto* b = static_cast*>(pc_iface_.get()); /* Called inside Scheduler::step() under its lock, which makes touching the cache and rank * 0's manager safe; nothing here may call back into the scheduler. */ - b->restore_fn = [this, b](const Request& req) { + b->restore_fn = [this, b](const Request& req, bool whole_only) -> RestoreResult { const uint64_t t0 = rad_mono_ns(); PrefixCache& pc = ranks_[0]->prefix; /* Room is made before anything is planned (PCBinding::restore_plan): a chain the free * list cannot hold would otherwise come back only as far as it reaches. One block * table serves every rank, so what rank 0's cache gives up is room on every rank. */ - const std::vector want = - b->restore_plan(req, cvec_salt_for(req.sp.use_control_vector)); - if (want.empty()) return; + RestoreResult res = RestoreResult::Whole; + const std::vector want = b->restore_plan( + req, cvec_salt_for(req.sp.use_control_vector), whole_only, &res); + if (want.empty()) return res; /* The whole chain in one restore. With 4-token blocks a long conversation is tens of * thousands of entries; batched, it is one launch per (group, layer) per staging batch * and one copy per run of arena slots instead of a round trip per entry. */ @@ -1510,7 +1513,9 @@ int Engine::serve(std::unique_ptr watch) { if (!ranks_[0]->tierx.plan_promote(h, &j)) break; jobs.push_back(std::move(j)); } - if (jobs.empty()) return; + /* A record still in flight ends the chain here, as a short reservation does below. */ + if (jobs.size() < want.size()) res = RestoreResult::Cut; + if (jobs.empty()) return res; std::vector ok(jobs.size(), 1); for (auto& r : ranks_) { std::vector mine; @@ -1525,7 +1530,7 @@ int Engine::serve(std::unique_ptr watch) { const std::vector& cg = pc.cached_groups(); for (size_t i = 0; i < jobs.size(); ++i) { TierJob& j = jobs[i]; - if (!ok[i]) continue; + if (!ok[i]) { res = RestoreResult::Cut; continue; } const int rb = pc.rebind(j.key, j.blocks); if (rb != RAD_OK) { /* No entry to land in: release the reserved blocks and forget the tier record, @@ -1537,6 +1542,7 @@ int Engine::serve(std::unique_ptr watch) { } } ranks_[0]->tiers.note_restore((int64_t)(rad_mono_ns() - t0)); + return res; }; /* An eviction that would lose an entry waits for its copy instead. Called by the prefix * cache binding under the scheduler's lock when dropping already-copied entries did not @@ -1690,6 +1696,8 @@ std::string Engine::engine_info() const { e["tensor_parallel"] = cfg_.tp; e["tp_wire"] = cfg_.tp > 1 ? (cfg_.tp_wire_exact ? "exact" : "wht6") : "n/a"; e["tp_wire_min_kb"] = cfg_.tp_wire_exact ? 0 : cfg_.tp_wire_min_kb; + e["attn_prefill_fp8"] = attn_prefill_fp8_name(cfg_.attn_prefill_fp8); + e["tp_attn_split"] = cfg_.tp_attn_rows ? "rows" : "heads"; e["max_num_batched_tokens"] = cfg_.max_tok; e["placement"] = cfg_.placement; /* Each lookup table's requested and resolved placement. */ @@ -2540,6 +2548,7 @@ int Engine::run_server() { in.chunk_bos = gd.chunk_bos; in.chunk_eos = gd.chunk_eos; in.chunk_pad = gd.pad_token; + in.cond_opts = gd.cond_opts; image_bridge.drv = img_gen_; image_bridge.proc = mm_proc.get(); d.images = &image_bridge; @@ -2570,8 +2579,9 @@ int Engine::run_server() { std::string* why) const override { const int s = rad_tools_text_prepare(*plugins, field, in, out); if (s < 0 && why) - *why = s == RAD_E_INVAL ? "the model cannot take this text" - : std::string(rad_strerror(s)); + *why = !out->empty() ? *out + : s == RAD_E_INVAL ? "the model cannot take this text" + : std::string(rad_strerror(s)); return s; } int submit(std::unique_ptr r, std::string* why) override { @@ -2597,6 +2607,14 @@ int Engine::run_server() { in.default_steps = ad.voc_chunk > 0 ? 0 : ad.default_steps; in.default_cfg = ad.default_cfg; in.max_lanes = ad.max_lanes; + in.branches = ad.branches == 1 ? 1 : 2; + in.input_special = ad.input_special != 0; + in.tmpl_ref = pg.agen_str.tmpl_ref; + in.ref_item = pg.agen_str.ref_item; + in.ref_rate = ad.ref_rate; + in.ref_hop = ad.ref_hop; + in.ref_max_samples = ad.ref_max_samples; + in.ref_max = ad.ref_max; audio_bridge.drv = aud_gen_; audio_bridge.plugins = &plugins_; d.audio = &audio_bridge; @@ -2737,8 +2755,8 @@ int Engine::run_server() { RAD_INFO("chat: the template takes reasoning_effort %s, and none or minimal turn " "thinking off%s%s", list.c_str(), mapped.empty() ? "" : "; mapped: ", mapped.c_str()); - /* What a request naming no effort gets, which a client cannot see: Qwen3.8's template - * renders xhigh into a system prompt (#113). */ + /* What a request naming no effort gets, which a client cannot see: a template may + * render a level into a system prompt (Qwen3.8's renders xhigh). */ const std::string& dflt = srv.template_default_effort(); if (cfg_.reasoning_effort.empty() && !dflt.empty()) RAD_INFO("chat: a request naming no reasoning_effort renders as '%s', the " diff --git a/core/engine.h b/core/engine.h index ca9c8e36..b9a5d88c 100644 --- a/core/engine.h +++ b/core/engine.h @@ -19,6 +19,7 @@ */ #pragma once #include "rad_core.h" +#include "rad_spechub.h" /* RadMtpCoupleDraw/State: the coupled MTP wire rows */ #include "cvec.h" #include #include @@ -185,7 +186,6 @@ public: std::shared_ptr* hold, std::string* note, std::string* err); /* The adapter files a generator request may name: --lora's and those under --lora-dir. */ std::vector gen_lora_names() const; - bool gen_lora_enabled() const { return lora_gen_; } private: /* A generator's adapter files by name (--lora, POST /v1/load_lora_adapter, --lora-dir), opened * once and kept mapped; compositions read them when a combination is put in a slot. */ @@ -339,6 +339,10 @@ private: * string because RadDrafterDecl::name points into the Program. */ RadDrafterDecl drafter_{}; std::string drafter_name_; + /* The block drafter's shorter block (rad_drafter_short_block), 0 when it has none or + * --draft-short-from is 0. */ + int64_t drafter_short_ = 0; + bool short_on_ = false; /* the short block runs now (block_shape) */ /* Serial driver (spec §10): `depth` dependent passes after the step commits, each embedding * the previous proposal. MTP, EAGLE and Medusa-serial have this shape. */ @@ -374,6 +378,9 @@ private: gen::AudioDriver* aud_gen_ = nullptr; gen::VideoDriver* vid_gen_ = nullptr; int gen_loop(); + /* Zeroes the state slots the KV manager granted since the last step, on every rank's stream, + * before the step or pass that first reads them. */ + void clear_fresh_states(); bool serial_drafting() const; int advance_all(int mode, int round, bool from_proposal, int rows = -1); int issue_serial_drafter(int step, StepOut& so); @@ -383,7 +390,7 @@ private: /* The arena level and the followers' pools, before any release that runs a forward pass. */ int prepare_release(const RadBatch* b); /* Whether a step may be issued ahead: requires that the drafter, if any, runs on the card (the - * prompt-lookup drafter and the host's block driver both read the committed sequence). */ + * prompt-lookup drafter reads the committed sequence). */ bool pipelining_ = false; int finish_serial_drafter(const StepOut& so); /* Handed from issue_serial_drafter to finish_serial_drafter: the drafting rows, the rounds @@ -396,6 +403,25 @@ private: void step_state_fini(); StepSlot* slots_host_ = nullptr; + /* --draft-coupling (engine_draft.cpp). The head declares `mtp_couple_draws` and + * `mtp_couple_state`; the engine stages one draw per drafting row before the serial passes and + * reads the states back once, then binds each to the verify row it will be coupled at. */ + bool mtp_couple_ = false; + rad_buf couple_draws_buf_ = 0, couple_state_buf_ = 0; + int64_t couple_rows_ = 0; /* the state plane's rows per round */ + RadMtpCoupleDraw* couple_draw_stage_ = nullptr; /* pinned [max_seqs] */ + RadMtpCoupleState* couple_readback_ = nullptr; /* pinned [rounds, couple_rows_] */ + std::vector couple_by_card_; /* the plan's draw per card slot */ + RadMtpCoupleState couple_bound_[RAD_MTP_COUPLE_MAX_ROUNDS] = {}; + bool couple_evidence_ = false; /* the completed-verify line was written (once a process) */ + bool couple_host_note_ = false; /* the host-domain counterpart was written (once) */ + bool couple_malformed_note_ = false; /* a status -1 round was reported (once) */ + int stage_couple_draws(int n); + /* One INFO line at the first coupled verify that completed: the step, the live requests whose + * rows carried a bound state, the kernel and its domain. Read from the sampler's build + * snapshot after collect_step's wait, so it reports a finished verify, not an enqueue. */ + void couple_verify_evidence(int step); + /* Step-time attribution, Debug only (see the barrier in step_loop): time per scheduler phase. * The nine phases sum to the whole step, including the readback, commit and drafter after the * join. */ @@ -407,19 +433,23 @@ private: void phase_mark(int p); /* Block driver (spec §10): a context pass mirroring the step just run, then one pass that - * fills every drafted position at once. DFlash2 has this shape. run_block_drafter stages both - * after the commit; on the card (`block_card_`, the default), issue_block_drafter queues them - * behind the step before its readback and finish_block_drafter publishes the proposals after - * the commit, so the step can be issued ahead. RADIANCE_DRAFT_BLOCK_HOST=1 keeps the host's. */ - int run_block_drafter(int step); + * fills every drafted position at once. DFlash2 has this shape. issue_block_drafter queues + * both behind the step before its readback and finish_block_drafter publishes the proposals + * after the commit, so the step can be issued ahead. */ + bool block_drafting() const; int block_pass(const RadBatch* db, const char* what, int step); - bool block_card_ = false; int issue_block_drafter(int step, StepOut& so); int finish_block_drafter(const StepOut& so); + /* The block and proposal count this step's query pass runs at: the drafter's own, or its short + * block once --draft-short-from sequences decode, back to its own only two below. */ + void block_shape(int* block, int* steps); /* Handed from issue_block_drafter to finish_block_drafter and issue_ahead: the drafting rows, * in the query pass's order, and how many there are (0 when no query pass ran). */ std::vector block_row_; int block_rows_ = 0; + /* The proposals a row of the query pass took (block_shape), for finish_block_drafter and + * issue_ahead's expect_draft. */ + int block_steps_ = 0; /* Encoder driver (spec §11, core/engine_mm.cpp): encodes every media item the scheduler waits * on, in passes of whole segments, and reads it back into the item. Runs between steps, never * inside one. */ diff --git a/core/engine_bringup.cpp b/core/engine_bringup.cpp index 34abb97b..0767cdfe 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -84,6 +84,25 @@ struct MissReport { } }; +/* The kernels --attn-prefill-fp8 reached: the resolved rows, in any band and domain, that + * constrain `prefill_fp8`. An exact kernel ignores the parameter and states no constraint on it. */ +static std::vector prefill_fp8_rows(const Program& p) { + std::vector names; + for (const OpInfo& op : p.ops) + for (const Band& band : op.bands) + for (const Resolved& r : band.dom) { + if (!r || !r.row->info) continue; + const RadKernelInfo* k = r.row->info; + bool takes = false; + for (int c = 0; c < k->n_constraints; ++c) + if (k->constraints[c].key && !std::strcmp(k->constraints[c].key, "prefill_fp8")) + takes = true; + if (takes && std::find(names.begin(), names.end(), k->name) == names.end()) + names.push_back(k->name); + } + return names; +} + static MissReport miss_report(const Program& p, bool host_backend) { MissReport r; std::vector host_ops; /* in first-seen order */ @@ -885,6 +904,10 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const { bc.kv_dtype = cfg_.kv_cache_dtype == "bf16" ? RAD_BF16 : RAD_F8E4M3; bc.kv_quant = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4 : cfg_.kv_cache_dtype == "k6_v4" ? RAD_KVQ_K6V4 : RAD_KVQ_NONE; + bc.attn_prefill_fp8 = cfg_.attn_prefill_fp8; + bc.tp_attn_rows = cfg_.tp_attn_rows; + bc.state_dtype = cfg_.state_cache_dtype == "f16" ? RAD_F16 : 0; + bc.draft_coupling = cfg_.draft_coupling ? 1 : 0; bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024; bc.scope = ""; bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0; @@ -1019,6 +1042,40 @@ int Engine::declare() { return RAD_E_UNSUPPORTED; } } + /* The row split is a graph only the plugin can declare, and it splits over ranks. A plugin + * that does not say it serves it (RadArchProbe::tp_attn_rows_ok), or a single rank, would + * serve the head split under a name that promised the other, so the flag is refused rather + * than ignored. */ + if (cfg_.tp_attn_rows) { + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb); + if (!pb.tp_attn_rows_ok) { + RAD_ERR("--tp-attn-split rows: the '%s' plugin does not split attention by rows for " + "this model (heads does)", plugins_.arch_plugin.c_str()); + return RAD_E_UNSUPPORTED; + } + if (cfg_.tp < 2) { + RAD_ERR("--tp-attn-split rows splits a prefill's attention over tensor-parallel ranks, " + "and --tp %d has none to split over (heads does)", cfg_.tp); + return RAD_E_INVAL; + } + RAD_WARN("attention: a prefill-sized step splits by rows over the %d ranks " + "(--tp-attn-split rows): every card holds the attention's projections at full " + "width, and the result is not bit-identical to the head split", cfg_.tp); + } + /* Likewise an f16 recurrent state: a plugin that does not say it declares one would keep f32 + * under a flag that promised half the state memory. */ + if (cfg_.state_cache_dtype == "f16") { + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb); + if (!pb.state_f16_ok) { + RAD_ERR("--state-cache-dtype f16: the '%s' plugin does not declare its recurrent state " + "at f16 for this model (f32 does)", plugins_.arch_plugin.c_str()); + return RAD_E_UNSUPPORTED; + } + RAD_INFO("recurrent state cache: f16 (--state-cache-dtype), half the state memory; lossy, " + "the generated text differs from f32"); + } /* Resolved here, not at argument parsing: the plugin states its drafter's depth, and it is * selected only once the container is open. Every consumer of `n_spec` (buffer sizing, kernel * bands, the scheduler's window) runs after this. rad_arch_probe is the core's only source of @@ -1036,24 +1093,23 @@ int Engine::declare() { cfg_.n_spec > 0 ? "the depth the drafter in this container states as its operating point" : "this container carries no draft head"); } - /* Chained launches pay on some speculative steps and cost plain decode (4x R9700: the 31B - * with DFlash2 +13%, the 26B-A4B with DFlash +1%, Qwen3.8-27B with DFlash2 even; the 31B with - * no drafter -6.5%), so they are on by default only where the model's plugin measured a gain - * with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes + /* Chained launches pay on some speculative steps and cost plain decode (on 4x R9700 the 31B + * with DFlash2 gained 13%, the 26B-A4B with DFlash 1%, Qwen3.8-27B with DFlash2 nothing, and + * the 31B without a drafter lost 6.5%), so they are on only where the model's plugin measured a + * gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes * speculatively. */ { RadArchProbe pb{}; (void)rad_tools_probe(plugins_, meta_, &pb); - rad_dev_chain_infer(cfg_.n_spec > 0 && pb.chain_pays); - const char* e = std::getenv("RADIANCE_CHAIN"); + const bool pays = cfg_.n_spec > 0 && pb.chain_pays; + rad_dev_chain_infer(pays); const bool on = rad_dev_chain_enabled() != 0; - const char* why = e && *e && std::strcmp(e, "auto") != 0 - ? (on || *e == '0' ? "RADIANCE_CHAIN says so" : "the backend does not chain") - : on ? "the model's plugin measured a gain with its speculative drafter" - : "no drafter whose plugin measured a gain with them decodes " - "speculatively, or the backend does not chain"; + const char* why = on ? "the model's plugin measured a gain with its speculative drafter" + : pays ? "the device backend does not chain" + : "no drafter whose plugin measured a gain with them decodes " + "speculatively"; RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why); - decide("RADIANCE_CHAIN", on ? "1" : "0", why); + decide("chained launches", on ? "on" : "off", why); } /* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio * encoder (`radiance.encoder` names one) and the deployment is not text-only. */ @@ -1072,7 +1128,10 @@ int Engine::declare() { * area, which would need 16x the activation memory on every card. */ if (cfg_.mm_max_patches < 0) { const char* enc = rad_meta_gets(&meta_, "radiance.encoder", ""); - const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0; + /* A checkpoint's vision_config states a tower as a flat patch_size, or (Unlimited-OCR's + * DeepEncoder) only the per-width tables under a `vision_config.image_size`. */ + const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0 || + rad_meta_geti(&meta_, "vision_config.image_size", 0) > 0; cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0; /* Whole output rows a pass: the plugin's merge, when it states one. */ RadArchProbe pb{}; @@ -1091,54 +1150,44 @@ int Engine::declare() { : "the model carries no vision tower"); } - /* Declare once per rank (rank and world_size in RadBuildCtx; the plugin declares dimensions - * already divided, spec §9), every rank concurrently on its own thread. Concurrency is - * required: kernel init() runs during declare, and a collective's init is a rendezvous - * (libr4d's all-reduce publishes its peer scratch pointer and waits for every other rank), so - * a serial loop times out. Registry::select() and init_instance() share a mutex for this. Each - * thread binds its device first, because the current device is thread-local and the init - * allocates on it. */ - /* Control vectors are resolved here, before any rank declares: the plugin reads the direction - * table from RadBuildCtx, so a table that failed validation must stop the server before a graph - * is built around it. - * - * The feature is loaded only when the deployment asks: `--control-vector off|on`. Without it - * nothing is looked for, the graph declares no projection op, and a request that asks for one - * is refused by name -- so a deployment that does not use the feature pays nothing. With the - * flag, the engine looks beside the container (or in the directory, or in - * $RADIANCE_HOME/vectors) and uses the file if it is compatible; its operation parameters come - * from the package's own JSON. A file that does not fit is reported and skipped -- a sidecar - * must never stop a server nobody pointed at it. The flag's value is the startup switch: `off` - * leaves requests off until one asks (or the dashboard flips the default), `on` starts them on. */ - const std::string arch = meta_.arch_id ? meta_.arch_id : ""; + /* Control vectors are resolved before any rank declares, because the plugin reads the + * direction table from RadBuildCtx. Only `--control-vector off|on` loads one; without it + * nothing is looked for and the graph declares no projection op. With it, a plugin that does + * not apply control vectors (RadArchProbe::control_vector_ok), no file found, or a file that + * does not fit this model is refused: the operator asked for the feature. The operation's + * parameters come from the package's own JSON. The flag's value is the request default. */ if (cfg_.control_vector == "disabled") { RAD_INFO("control vectors: not loaded (no --control-vector); a request that asks for one is " "refused"); - } else if (!arch.empty()) { + } else { + RadArchProbe pb{}; + (void)rad_tools_probe(plugins_, meta_, &pb); + if (!pb.control_vector_ok) { + RAD_ERR("--control-vector %s: the '%s' plugin does not apply control vectors for this " + "model", cfg_.control_vector.c_str(), plugins_.arch_plugin.c_str()); + return RAD_E_UNSUPPORTED; + } + const std::string arch = meta_.arch_id ? meta_.arch_id : ""; std::string proj_path, tried; (void) control_vector_discover(cfg_.model, arch, cfg_.radiance_home, &proj_path, &tried); if (proj_path.empty()) { - RAD_INFO("control vectors: none found (%s)", tried.c_str()); - } else if (arch != "qwen4exp") { - RAD_WARN("control vectors: %s is for this family only (qwen4exp, whose gated residual " - "carries the projection op); this container is '%s' -- ignoring it", - proj_path.c_str(), arch.c_str()); - } else { - std::string why; - const int rc = control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers, - &cvec_, &why); - if (rc != RAD_OK) { - RAD_WARN("%s -- serving without it", why.c_str()); - cvec_ = ControlVector{}; - } + RAD_ERR("--control-vector %s: no control vector found for this model (looked at %s)", + cfg_.control_vector.c_str(), tried.c_str()); + return RAD_E_NOTFOUND; + } + std::string why; + if (control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers, &cvec_, &why) != + RAD_OK) { + RAD_ERR("--control-vector %s: %s", cfg_.control_vector.c_str(), why.c_str()); + cvec_ = ControlVector{}; + return RAD_E_INVAL; } } if (cvec_.loaded()) { cvec_views_.assign(ranks_.size(), RadControlVector{}); cvec_salt_ = control_vector_salt(cvec_); - /* `--control-vector on` starts the request default on, which is also how `--kld-record`/ - * `--kld-ref` score the projection itself: those modes serve no request to carry the - * switch. The switch still decides per request. */ + /* The request default; --kld-record / --kld-ref score documents with it, as they serve no + * request that could carry the field. */ const bool default_on = cfg_.control_vector == "on"; cvec_default_.store(default_on); RAD_INFO("control vectors: %s: %lld directions of %lld, layers %d..%d, scale %.3f -- " @@ -1156,6 +1205,13 @@ int Engine::declare() { cvec_default_.store(false); } + /* Declare once per rank (rank and world_size in RadBuildCtx; the plugin declares dimensions + * already divided, spec §9), every rank concurrently on its own thread. Concurrency is + * required: kernel init() runs during declare, and a collective's init is a rendezvous + * (libr4d's all-reduce publishes its peer scratch pointer and waits for every other rank), so + * a serial loop times out. Registry::select() and init_instance() share a mutex for this. Each + * thread binds its device first, because the current device is thread-local and the init + * allocates on it. */ std::vector st(ranks_.size(), RAD_OK); std::vector th; th.reserve(ranks_.size()); @@ -1246,6 +1302,28 @@ int Engine::declare() { return RAD_E_UNSUPPORTED; } } + /* --attn-prefill-fp8 is a permission an exact kernel also satisfies, so whether it acts is + * read off the resolution: a kernel that implements a lossy leg constrains `prefill_fp8`. A + * flag nothing takes stops the start rather than serving the exact form under its name. */ + if (cfg_.attn_prefill_fp8 != 0) { + const std::vector rows = prefill_fp8_rows(ranks_[0]->program); + const char* mode = attn_prefill_fp8_name(cfg_.attn_prefill_fp8); + if (rows.empty() && !cfg_.debug_graph) { + RAD_ERR("not starting: --attn-prefill-fp8 %s, but no attention kernel resolved for " + "this model takes e4m3 products at its geometry, cache (--kv-cache-dtype %s) " + "and kernel libraries; --attn-prefill-fp8 off serves it exactly", mode, + cfg_.kv_cache_dtype.c_str()); + return RAD_E_UNSUPPORTED; + } + std::string names; + for (const std::string& r : rows) names += (names.empty() ? "" : ", ") + r; + RAD_WARN("attention: LOSSY prefill (--attn-prefill-fp8 %s). %s rounded to e4m3 for fp8 " + "WMMA in %s, so this process does not compute the same function the exact " + "attention does; bands those kernels do not serve stay exact", mode, + cfg_.attn_prefill_fp8 == RAD_ATTN_FP8_QK ? "Q.K^T's query is" + : cfg_.attn_prefill_fp8 == RAD_ATTN_FP8_PV ? "P.V's probabilities are" + : "Q.K^T's query and P.V's probabilities are", names.c_str()); + } /* Checkpoint weights that cannot be served as stored cannot be loaded; name them all with the * remedy. */ if (ckpt_src_) { @@ -1272,6 +1350,24 @@ int Engine::declare() { drafter_name_ = p0.drafter_name; drafter_.name = drafter_name_.c_str(); if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{}; + drafter_short_ = drafter_.kind == RAD_DRAFT_BLOCK && cfg_.draft_short_from > 0 + ? p0.drafter_short_block : 0; + if (cfg_.draft_short_from > 0 && drafter_.kind == RAD_DRAFT_NONE) + RAD_WARN("--draft-short-from %lld: this deployment runs no drafter, so there is no block " + "to shorten", (long long)cfg_.draft_short_from); + else if (cfg_.draft_short_from > 0 && !drafter_short_) + RAD_WARN("--draft-short-from %lld: '%s' %s", (long long)cfg_.draft_short_from, + drafter_name_.c_str(), + drafter_.kind == RAD_DRAFT_BLOCK ? "declares no shorter block, so it keeps its own" + : "is a serial head, which proposes no block"); + if (drafter_short_) + RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld " + "row(s), %lld token(s)", (long long)cfg_.draft_short_from, + drafter_name_.c_str(), + (long long)drafter_short_, + (long long)(drafter_short_ - ((drafter_.block > 0 ? drafter_.block + : drafter_.depth + 1) - + drafter_.depth))); if (drafter_.kind != RAD_DRAFT_NONE) { /* A zero proposal handle means the sampler's token buffer: the head's logits go through * the ordinary sampler chain. */ @@ -1399,6 +1495,21 @@ void Engine::probe_arena_levels() { } /* ================================================================== 5. plan */ + +/* R-SWA: a RAD_KV_RING group names its ring's W in the declaration (`window`). Tell the manager + * before it plans, so the group is planned for per-sequence windows: sized for the whole context + * plus one ring a sequence (the ring in the fixed costs), never capped at the declare-time + * window, never snapshotted. Every plan (each sizing probe and the real manager) goes through + * here, so they all plan the same bytes. */ +static int declare_ring_windows(KVManager& kv, const Program& prog) { + for (size_t g = 1; g < prog.kv_groups.size(); ++g) { + const RadKVGroupDecl& d = prog.kv_groups[g].decl; + if (d.kind != RAD_KV_RING) continue; + RAD_TRY(kv.declare_runtime_window((int32_t)g, d.window)); + } + return RAD_OK; +} + int Engine::plan() { /* The budget is resolved once, for every rank, before any rank allocates. vram_budget_resolve * folds the smallest capacity with the largest program so one split fits every card, and @@ -1485,7 +1596,8 @@ int Engine::plan() { * memory, and the real pool does not exist yet. */ KVManager probe; host_arenas += arena_host_bytes(r->program); - if (probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) { + if (declare_ring_windows(probe, r->program) == RAD_OK && + probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) { ck_slot += probe.checkpoint_bytes(); f.kv_ceiling = probe.ceiling(ctx); f.kv_fixed = probe.fixed_bytes(); @@ -1621,7 +1733,8 @@ int Engine::plan() { * its carve). */ for (size_t i = 0; i < ranks_.size(); ++i) { probes[i] = std::make_unique(); - if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) { + if (declare_ring_windows(*probes[i], ranks_[i]->program) != RAD_OK || + probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) { kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index); break; } @@ -2959,6 +3072,7 @@ int Engine::configure_kv() { for (size_t i = 0; i < ranks_.size(); ++i) { auto& r = ranks_[i]; LogRank lr(r->index); + RAD_TRY(declare_ring_windows(r->kv, r->program)); RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_)); const int64_t t = r->kv.paged_tokens(r->pools.kv().avail()); /* A rank plan() re-sized for the common token count must page at least that count (same @@ -3193,13 +3307,16 @@ int Engine::configure_kv() { /* Can the pool hold one max-length sequence? The context limit and KV pool come from unrelated * flags; otherwise such a request is accepted and then refused at admission with a message * about blocks. Only full paged groups apply: a window group costs the window, and a linear - * group is O(1) in context. */ + * group is O(1) in context. A runtime-window (RAD_KV_RING) group is not checked here either: + * it is sized for the whole context plus one ring a sequence and its tokens are a per-sequence + * reference rather than the pool's capacity, so the comparison would be about the wrong + * number. */ { const int64_t want = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train; const KVManager& kv = ranks_[0]->kv; for (int32_t g = 0; g < kv.n_groups(); ++g) { const KVGroupPlan* p = kv.plan(g); - if (!p || !p->paged() || p->window_blocks > 0) continue; + if (!p || !p->paged() || p->window_blocks > 0 || p->runtime_win) continue; const int64_t cap = p->n_blocks * p->block_size; if (cap >= want) continue; /* A hard limit, unlike the backing ratio (how much of every-sequence-at-max_ctx the @@ -3487,16 +3604,18 @@ int Engine::start() { (void)rad_dev_set(ranks_[0]->device); /* The most the cache can hold: the whole carve, including lent blocks (a request reclaims them - * in the same step). Tokens are the smallest over the full paged groups; a windowed group - * bounds history, not capacity. /stats and /metrics report the same numbers (kv_tokens_max, - * radiance:kv_cache_max_tokens). */ + * in the same step). Tokens are the smallest over the full paged groups; a fixed-window group + * bounds history, not capacity. A runtime-window (RAD_KV_RING) group does hold its sequences' + * references, so it counts like a full group. /stats and /metrics report the same numbers + * (kv_tokens_max, radiance:kv_cache_max_tokens). */ { const KVManager& kv = ranks_[0]->kv; int64_t bytes = 0, state = 0, tokens = 0; for (const KVGroupPlan& p : kv.plans()) { bytes += kv.pool_bytes_carved(p.index); if (p.stateful()) state += kv.pool_bytes_carved(p.index); - if (!p.paged() || p.kind == RAD_KV_WINDOW || p.block_size <= 0) continue; + if (!p.paged() || (p.kind == RAD_KV_WINDOW && !p.runtime_win) || p.block_size <= 0) + continue; const int64_t t = p.n_blocks * p.block_size; if (tokens == 0 || t < tokens) tokens = t; } diff --git a/core/engine_draft.cpp b/core/engine_draft.cpp index cc43a80f..edf78fbc 100644 --- a/core/engine_draft.cpp +++ b/core/engine_draft.cpp @@ -6,6 +6,9 @@ */ #include "engine_priv.h" +#include "sample/mtp_couple_evidence.h" +#include "sched/mtp_couple_bind.h" +#include "sched/mtp_couple_plan.h" #include "sched/scheduler.h" #include "device/device.h" @@ -13,6 +16,7 @@ #include #include #include +#include #include #include @@ -48,6 +52,55 @@ int Engine::step_state_init() { if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0]->device)); slots_host_ = static_cast(rad_dev_alloc(slot_bytes, RAD_MEM_HOST_PINNED)); if (!slots_host_) return RAD_E_NOMEM; + + /* --draft-coupling: the head's two planes, found by name in the declared program, and the + * pinned staging beside them. A program without them is refused rather than served + * uncoupled. */ + mtp_couple_ = cfg_.draft_coupling; + if (mtp_couple_) { + /* Coupling is defined on a linear serial chain. A block drafter proposes a whole block + * from one pass, so it has no per-round draw to couple and no per-round state. */ + if (drafter_.kind != RAD_DRAFT_SERIAL || drafter_.depth <= 0) { + RAD_ERR("--draft-coupling on requires the linear serial draft chain (RAD_DRAFT_SERIAL " + "with depth > 0); this model declares drafter '%s' kind %d depth %d, which has " + "no per-round draw to couple", + drafter_.name ? drafter_.name : "(none)", drafter_.kind, drafter_.depth); + return RAD_E_UNSUPPORTED; + } + const Program& prog = ranks_[0]->program; + for (size_t i = 0; i < prog.buffers.size(); ++i) { + const std::string& name = prog.buffers[i].name; + auto ends = [&](const char* suffix) { + const size_t n = std::strlen(suffix); + return name.size() >= n && name.compare(name.size() - n, n, suffix) == 0; + }; + if (ends("mtp_couple_draws")) couple_draws_buf_ = (rad_buf)i; + if (ends("mtp_couple_state")) couple_state_buf_ = (rad_buf)i; + } + if (!couple_draws_buf_ || !couple_state_buf_) { + RAD_ERR("--draft-coupling on, but the architecture declared no coupled MTP planes; " + "this model's drafter cannot couple"); + return RAD_E_STATE; + } + const RadBufDecl& sd = prog.buffers[couple_state_buf_].decl; + if (sd.rank != 3 || sd.shape[2] != (int64_t)RAD_MTP_COUPLE_STATE_WORDS) { + RAD_ERR("--draft-coupling: 'mtp_couple_state' is not the [rounds, rows, %d]-word " + "plane the coupling reads", (int)RAD_MTP_COUPLE_STATE_WORDS); + return RAD_E_STATE; + } + couple_rows_ = sd.shape[1]; + /* One entry per card slot, indexed by StepEntry::card as slots_host_ is. */ + couple_by_card_.assign((size_t)n_slot, RadMtpCoupleDraw{}); + couple_draw_stage_ = static_cast( + rad_dev_alloc(n_slot * (int64_t)sizeof(RadMtpCoupleDraw), RAD_MEM_HOST_PINNED)); + couple_readback_ = static_cast(rad_dev_alloc( + (int64_t)drafter_.depth * couple_rows_ * (int64_t)sizeof(RadMtpCoupleState), + RAD_MEM_HOST_PINNED)); + if (!couple_draw_stage_ || !couple_readback_) return RAD_E_NOMEM; + RAD_INFO("MTP coupled LIVE: %d linear round(s), x~Q from the final reranked top8, maximal " + "coupling at the verify; fixed-seed tokens are NOT preserved", drafter_.depth); + } + RAD_TRY(rad_event_create_as(&step_end_, RAD_EVENT_LOCAL | RAD_EVENT_HOST_WAIT)); return RAD_OK; } @@ -62,6 +115,10 @@ void Engine::step_state_fini() { } if (slots_host_) rad_dev_free(slots_host_, RAD_MEM_HOST_PINNED); slots_host_ = nullptr; + if (couple_draw_stage_) rad_dev_free(couple_draw_stage_, RAD_MEM_HOST_PINNED); + if (couple_readback_) rad_dev_free(couple_readback_, RAD_MEM_HOST_PINNED); + couple_draw_stage_ = nullptr; + couple_readback_ = nullptr; if (step_end_) rad_event_destroy(step_end_); step_end_ = nullptr; } @@ -142,6 +199,8 @@ int Engine::issue_serial_drafter(int step, StepOut& so) { if (rounds <= 0) return RAD_OK; serial_rounds_ = rounds; serial_rows_ = n; + /* Before any serial pass reads a draw; round 1 is the history pass below. */ + if (mtp_couple_ && n > 0) RAD_TRY(stage_couple_draws(n)); /* RADIANCE_DEBUG_STAGE: running means of a draft pass's host time: batch + advance, greedy * sampler chain, barrier release and issue. They cost the step nothing until their sum exceeds @@ -213,6 +272,15 @@ int Engine::issue_serial_drafter(int step, StepOut& so) { * history (Scheduler::serial_batch). */ RAD_TRY(advance_all(ADV_TAKE, serial_done_, true, n)); Rank& r0 = *ranks_[0]; + if (mtp_couple_) { + /* Rounds 1..done of the drafting rows, on the same stream as the slots below. */ + const void* state = r0.ctx.buf_ptr(couple_state_buf_); + if (!state || serial_done_ > (int)drafter_.depth) return RAD_E_STATE; + const int64_t pitch = couple_rows_ * (int64_t)sizeof(RadMtpCoupleState); + RAD_TRY(rad_memcpy_2d_async(couple_readback_, pitch, state, pitch, + (int64_t)n * (int64_t)sizeof(RadMtpCoupleState), serial_done_, + r0.ctx.stream())); + } RAD_TRY(rad_memcpy_async(slots_host_, r0.step_slots, (int64_t)cfg_.max_seqs * (int64_t)sizeof(StepSlot), r0.ctx.stream())); return RAD_OK; @@ -253,8 +321,91 @@ int Engine::finish_serial_drafter(const StepOut& so) { /* No draft for a request the sampler will not speculate on (a constraining grammar that * cannot snapshot its state); the sampler would refuse the next step otherwise. */ if (!r0.sampler.allows_speculation(serial_row_[(size_t)i].seq)) continue; - sched_.set_draft(serial_row_[(size_t)i].seq, - &draft_out_[(size_t)i * (size_t)rounds], done); + const uint64_t seq = serial_row_[(size_t)i].seq; + const int rc = sched_.set_draft(seq, &draft_out_[(size_t)i * (size_t)rounds], done); + if (!mtp_couple_) continue; + /* Bound only for a request still running: one this commit finished, or whose draft the + * scheduler refused, binds nothing, and set_mtp_couple(..., 0) clears an earlier step's + * states (RAD_E_NOTFOUND for a request the sampler already dropped). + * + * The position is the committed output length after this commit, the n_out the next + * build_step reads. It comes from the scheduler's commit snapshot, not the plan's Request + * pointer, which reap() may already have freed (sched/mtp_couple_bind.h). */ + MtpCoupleBindPoint bp; + bp.found = sched_.committed_seq(seq, &bp.n_out, &bp.live); + if (!bp.found) + RAD_WARN("MTP coupled: serial row for sequence %llu is not in the committed step; " + "clearing its coupling", (unsigned long long)seq); + int n_bound = 0, n_malformed = 0; + std::string why; + const int bs = mtp_couple_bind_rounds( + bp, couple_draw_stage_[(size_t)i], &couple_readback_[(size_t)i], (int)couple_rows_, + done, slots_host_[serial_row_[(size_t)i].card], meta_.n_vocab, couple_bound_, + &n_bound, &why, &n_malformed); + if (bs < 0) { RAD_ERR("%s", why.c_str()); return bs; } + if (n_malformed > 0 && !couple_malformed_note_) { + couple_malformed_note_ = true; + RAD_WARN("MTP coupled: sequence %llu: %d draft round(s) had a shortlist with no valid " + "Q (non-finite score, duplicate id or no live entry); those rounds keep the " + "greedy proposal and the ordinary verify (logged once)", + (unsigned long long)seq, n_malformed); + } + for (auto& rk : ranks_) { + const int st = rk->sampler.set_mtp_couple(seq, couple_bound_, + rc == RAD_OK ? n_bound : 0); + if (st < 0 && st != RAD_E_NOTFOUND) return st; + } + } + return RAD_OK; +} + +/* One line, once, at the first coupled verify that completed. It reads the snapshot build_step + * froze for the step whose wait just returned (sample/mtp_couple_evidence.h), which the + * drafter's build_greedy does not clear, and checks that run() issued the verify for that build. + * Sequences are re-checked as Running after the wait. Request numbers, the row count and the + * kernel name only; a host-domain row is labelled as such. */ +void Engine::couple_verify_evidence(int step) { + if (!mtp_couple_ || couple_evidence_) return; + Sampler& smp = ranks_[0]->sampler; + const rad_op op = smp.staged_couple_op(); + const MtpCoupleEvidence ev = mtp_couple_evidence( + smp.couple_build(), step, ranks_[0]->ctx.op_domain(op), + [this](uint64_t seq) { return sched_.running(seq); }); + if (ev.rows <= 0 || smp.staged_couple_issued_step() != step) return; + const char* kernel = ranks_[0]->ctx.ip_kernel_name(op); + if (ev.device) { + couple_evidence_ = true; + RAD_INFO("MTP coupled verify completed: step %d, %lld bound row(s) over request(s) [%s], " + "kernel %s, domain device", step, (long long)ev.rows, ev.seqs.c_str(), kernel); + } else if (!couple_host_note_) { + couple_host_note_ = true; + RAD_INFO("MTP coupled verify completed on the host domain: step %d, %lld bound row(s) over " + "request(s) [%s], kernel %s -- not device evidence", step, (long long)ev.rows, + ev.seqs.c_str(), kernel); + } +} + +/* --draft-coupling: the draw for every drafting row, before any serial pass reads it. + * + * The coordinate is the pre-commit output size, which strictly grows between two steps that draft + * one request, so (base, round) never repeats a draft stream. The card is the slot the advance + * writes; the propose op keeps the greedy proposal for a row whose draw names another card. The + * rule is sched/mtp_couple_plan.h. */ +int Engine::stage_couple_draws(int n) { + std::string why; + const int stg = mtp_couple_plan_stage(sched_.plan(), + (int)(cfg_.max_seqs > 0 ? cfg_.max_seqs : 1), + serial_row_.data(), n, &couple_by_card_, + couple_draw_stage_, &why); + if (stg < 0) { + RAD_ERR("MTP coupled: %s", why.c_str()); + return stg; + } + for (auto& rk : ranks_) { + void* dst = rk->ctx.buf_ptr(couple_draws_buf_); + if (!dst) return RAD_E_STATE; + RAD_TRY(rad_memcpy_async(dst, couple_draw_stage_, + n * (int64_t)sizeof(RadMtpCoupleDraw), rk->ctx.stream())); } return RAD_OK; } @@ -276,11 +427,8 @@ int Engine::finish_serial_drafter(const StepOut& so) { * * Proposals go out through set_draft() like every other. * - * Two drivers run these passes. run_block_drafter, after the step commits, stages both from the - * committed sequence and reads the proposals back: two host waits a step with the card idle - * between them, and no step issued ahead. The card's driver (issue_block_drafter, the default) - * queues both behind the step before its readback, from the card's acceptance, as the serial - * driver does; RADIANCE_DRAFT_BLOCK_HOST=1 selects the host's. + * Both passes are queued behind the step before its readback, from the card's acceptance, as the + * serial driver's are (sched/advance.h), so the next step can be issued ahead of the commit. */ /* One drafter pass through the barrier. Neither pass samples (no logits in the context pass; the @@ -306,75 +454,51 @@ int Engine::block_pass(const RadBatch* db, const char* what, int step) { return s; } -int Engine::run_block_drafter(int step) { - if (drafter_.kind != RAD_DRAFT_BLOCK || drafter_.depth <= 0) return RAD_OK; - - const int steps = drafter_.depth; - /* The row count is the drafter's (defaulted and checked by declare_drafter). */ - const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1; - std::vector rows((size_t)cfg_.max_seqs); - const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token, - rows.data(), (int)rows.size()); - - Rank& r0 = *ranks_[0]; - void* prop = r0.ctx.buf_ptr(drafter_.proposal); - if (!prop) { - RAD_ERR("drafter '%s': `%s` was declared as the proposal buffer but never planned", - drafter_.name, r0.program.buffers[drafter_.proposal].name.c_str()); - return RAD_E_STATE; - } - - /* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the - * drafter will need, and skipping would leave a permanent hole in its cache. */ - if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step)); - - /* Cleared so a query batch that could not be built does not republish the previous step's - * proposals. */ - draft_out_.clear(); - if (n > 0) { - if (const RadBatch* qb = sched_.block_query(step)) { - RAD_TRY(block_pass(qb, "query", step)); - const int64_t n_raw = (int64_t)n * steps; - int32_t* const raw = readback_.reserve(n_raw); - if (!raw) return RAD_E_NOMEM; - RAD_TRY(rad_memcpy_async(raw, prop, n_raw * 4, r0.ctx.stream())); - RAD_TRY(rad_stream_sync(r0.ctx.stream())); - draft_out_.assign(raw, raw + n_raw); - } - } - sched_.block_end(); - if (n <= 0 || draft_out_.empty()) return RAD_OK; - - for (int i = 0; i < n; ++i) { - /* A request the sampler will not speculate on gets no draft; see finish_serial_drafter. */ - if (!r0.sampler.allows_speculation(rows[(size_t)i].seq)) continue; - sched_.set_draft(rows[(size_t)i].seq, &draft_out_[(size_t)i * (size_t)steps], steps); - } - return RAD_OK; +bool Engine::block_drafting() const { + return drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0; } -/* The card's driver: both passes behind the step, without waiting. After the trunk's ranks join, - * the acceptance runs on every rank (ADV_ACCEPT), leaving each sequence's anchor and committed - * end in its StepSlot. The context pass mirrors the trunk step, whose positions the host knows. +/* Both passes behind the step, without waiting. After the trunk's ranks join, the acceptance runs + * on every rank (ADV_ACCEPT), leaving each sequence's anchor and committed end in its StepSlot. The context pass mirrors the trunk step, whose positions the host knows. * The query pass's rows are device rows that the card positions at the committed end (ADV_BLOCK), * and its proposals go into the slots behind the anchor (ADV_BTAKE): exactly the token row the * next verify reads (ADV_TRUNK), so the step issued ahead verifies them with no host round trip. * collect_step's wait covers both passes and the slots' readback. */ +void Engine::block_shape(int* block, int* steps) { + *steps = drafter_.depth; + /* The row count is the drafter's (defaulted and checked by declare_drafter). */ + *block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1; + /* Its short block under load (rad_drafter_short_block): the same anchor convention, so as many + * fewer proposals as rows. The load is the step just run's, which the next step, the one these + * proposals are for, mostly repeats (Scheduler::short_block_on). */ + if (drafter_short_ <= 0) return; + short_on_ = Scheduler::short_block_on(short_on_, sched_.decoded_seqs(), cfg_.draft_short_from); + if (short_on_) { + *steps -= *block - (int)drafter_short_; + *block = (int)drafter_short_; + } +} + int Engine::issue_block_drafter(int step, StepOut& so) { block_rows_ = 0; - if (!block_card_) return RAD_OK; + if (!block_drafting()) return RAD_OK; RAD_TRY(advance_all(ADV_ACCEPT, 0, false)); /* The sampled ids before either pass, as the serial driver reads them. */ RAD_TRY(collect_issue(so)); - const int steps = drafter_.depth; - const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1; + /* The short block too (block_shape): its query pass is a shorter batch the card positions + * the same way, its proposals the front of each row at the drafter's pitch (ADV_BTAKE), and + * the step issued ahead verifies that many (issue_ahead). */ + int block = 0, steps = 0; + block_shape(&block, &steps); + block_steps_ = steps; block_row_.resize((size_t)cfg_.max_seqs); const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token, block_row_.data(), (int)block_row_.size(), /*on_card=*/true); - /* Even when nothing drafts; see run_block_drafter. */ + /* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the + * drafter will need, and skipping would leave a permanent hole in its cache. */ if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step)); if (n <= 0) return RAD_OK; const RadBatch* qb = sched_.block_query(step); @@ -393,7 +517,7 @@ int Engine::issue_block_drafter(int step, StepOut& so) { * (a disagreement is a defect and the step is refused, as in finish_serial_drafter), move the * drafter's filled range, and publish each row's proposal from the slots. */ int Engine::finish_block_drafter(const StepOut& so) { - if (!block_card_) return RAD_OK; + if (!block_drafting()) return RAD_OK; if (block_rows_ > 0) { const StepPlan& plan = sched_.plan(); for (size_t i = 0; i < plan.e.size(); ++i) { @@ -414,7 +538,7 @@ int Engine::finish_block_drafter(const StepOut& so) { if (block_rows_ <= 0) return RAD_OK; Rank& r0 = *ranks_[0]; - const int steps = drafter_.depth; + const int steps = block_steps_; draft_out_.assign((size_t)block_rows_ * (size_t)steps, 0); for (int i = 0; i < block_rows_; ++i) { const StepSlot& S = slots_host_[block_row_[(size_t)i].card]; diff --git a/core/engine_gen.cpp b/core/engine_gen.cpp index 27b286da..e4e02569 100644 --- a/core/engine_gen.cpp +++ b/core/engine_gen.cpp @@ -53,6 +53,8 @@ int Engine::gen_loop() { continue; } idle = 0; + /* A hybrid model's recurrent state: the slots a newly admitted request was granted. */ + clear_fresh_states(); if (const int ps = prepare_release(b); ps < 0) return stop(ps); for (auto& rk : ranks_) rk->ctx.set_gen_lora_slot(gen_->lora_slot()); issue_what_.store(kIssueModel, std::memory_order_release); diff --git a/core/engine_kld.cpp b/core/engine_kld.cpp index d402fff3..c94e42ef 100644 --- a/core/engine_kld.cpp +++ b/core/engine_kld.cpp @@ -124,6 +124,8 @@ int Engine::run_kld() { r->ignore_eos = true; r->sp.temp = 0.0f; r->score = true; + /* A loaded control vector scores at the deployment's default (--control-vector on|off). */ + r->sp.use_control_vector = cvec_default_on(); /* --kld-lora-sources: the other documents run as the base, in the same steps. */ const bool via = cfg_.kld_lora_sources.empty() || kld_->source(d).rfind(cfg_.kld_lora_sources, 0) == 0; diff --git a/core/engine_lora.cpp b/core/engine_lora.cpp index 81ffec81..a8e0a08e 100644 --- a/core/engine_lora.cpp +++ b/core/engine_lora.cpp @@ -275,7 +275,11 @@ int Engine::lora_copy(int slot, const std::vector> char* da = (char*)P.buffers[lp.a].ptr; char* db = (char*)P.buffers[lp.b].ptr; char* ds = (char*)P.buffers[lp.scale].ptr; - if (!da || !db || !ds) { rc = RAD_E_STATE; *err = "a pool has no address"; break; } + if (!da || !db || !ds) { + rc = RAD_E_STATE; + *err = "the adapter pool of '" + lp.weight + "' has no buffer address"; + break; + } da += (int64_t)slot * ab; db += (int64_t)slot * bb; ds += (int64_t)slot * sb; /* A pool this adapter does not touch is zeroed, not left as it was: the bytes are what * the slot's last adapter or the arena held, and a scale of 0 times a NaN is a NaN. */ diff --git a/core/engine_mm.cpp b/core/engine_mm.cpp index 2495cc5c..47930584 100644 --- a/core/engine_mm.cpp +++ b/core/engine_mm.cpp @@ -20,6 +20,8 @@ #include #include #include +#include +#include namespace rad { @@ -47,6 +49,33 @@ int Engine::run_encodes() { Rank& r0 = *ranks_[0]; const Program& prog = r0.program; + + /* Diagnostic: RADIANCE_DEBUG_MM_BUFFERS names encoder buffers (comma separated, with an + * optional `:rows` cap) and each pass writes them, as raw bytes, to `/buf.`. + * The pass has finished and been read back, so the copy sees each buffer's last writer; the + * tower's per-stage intermediates are tapped inside the pass instead (rad_block_sam.h). */ + struct DumpBuf { std::string name; int64_t rows; }; + std::vector dump_bufs; + static const char* const dump_list = std::getenv("RADIANCE_DEBUG_MM_BUFFERS"); + if (dump_dir && *dump_dir && dump_list) { + for (const char* s = dump_list; *s; ) { + const char* e = s; + while (*e && *e != ',') ++e; + std::string want(s, (size_t)(e - s)); + s = *e ? e + 1 : e; + int64_t rows = 0; + if (const size_t colon = want.find(':'); colon != std::string::npos) { + rows = std::strtoll(want.c_str() + colon + 1, nullptr, 10); + want.resize(colon); + } + if (!want.empty()) dump_bufs.push_back({ want, rows }); + } + } + auto answers_to = [](const std::string& name, const std::string& want) { + if (name.size() < want.size() || + name.compare(name.size() - want.size(), want.size(), want) != 0) return false; + return name.size() == want.size() || name[name.size() - want.size() - 1] == '.'; + }; for (auto& ip : items) { if (ip->encoded) continue; const RadEncoderDecl& e = ip->kind == mm::Kind::Audio ? prog.audio_encoder : prog.encoder; @@ -74,6 +103,10 @@ int Engine::run_encodes() { size_t i = 0; int32_t seg = 0; + /* The pass's grid, when the encoder declares that a pass is one geometry + * (RadEncoderDecl::one_grid). */ + const bool one_grid = enc.one_grid != 0; + int32_t seg_grid = 0; while (i < mine.size()) { std::vector parts; int64_t np = 0; @@ -81,16 +114,31 @@ int Engine::run_encodes() { mm::Item& it = *mine[i]; const int32_t first = seg; for (; seg < it.n_seg; ++seg) { + const int32_t g = it.seg_h(seg); + /* The one-output-row view separator (core/mm marks it explicitly) belongs to + * the pass of the view before it, so it neither breaks at a "grid change" nor + * sets the pass's grid. A square segment that is a real view (a chunked line + * of one tile) keeps the ordinary geometry rule below. */ + const bool sep = it.seg_is_sep(seg); const int64_t seg_p = it.patch_at(seg + 1) - it.patch_at(seg); if (seg_p > max_p) { RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld", (long long)seg_p, (long long)max_p); return RAD_E_STATE; } + if (one_grid && !sep && np > 0 && seg_grid != 0 && g != seg_grid) break; if (np + seg_p > max_p) break; np += seg_p; + if (!sep) seg_grid = g; + } + if (seg == first) { + /* Nothing of this item packed into the pass: its first segment did not fit + * a pass that already has content (a segment larger than the whole pass was + * refused above). `seg` addresses a real segment only below `it.n_seg`; + * a degenerate zero-segment item leaves seg_grid alone. */ + if (seg_grid == 0 && seg < it.n_seg) seg_grid = it.seg_h(seg); + break; } - if (seg == first) break; parts.push_back({ &it, first, seg - first }); if (seg == it.n_seg) { ++i; seg = 0; } } @@ -132,6 +180,35 @@ int Engine::run_encodes() { } /* Sync every rank's stream: the next pass rewrites every rank's staging and arena. */ for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream())); + + if (dump_dir && *dump_dir && !dump_bufs.empty()) { + for (const DumpBuf& d : dump_bufs) { + for (size_t bi = 1; bi < prog.buffers.size(); ++bi) { + const BufferInfo& info = prog.buffers[bi]; + if (!answers_to(info.name, d.name) || info.bytes <= 0) continue; + const int64_t nrow = info.decl.rank >= 1 ? info.decl.shape[0] : 1; + const int64_t rowb = nrow > 0 ? info.bytes / nrow : info.bytes; + const int64_t rows = d.rows > 0 ? std::min(d.rows, nrow) : nrow; + void* ptr = r0.ctx.buf_ptr((rad_buf)bi); + std::vector raw((size_t)(rows * rowb)); + if (!ptr || rad_memcpy_async(raw.data(), ptr, raw.size(), + r0.ctx.stream()) < 0) + continue; + rad_stream_sync(r0.ctx.stream()); + char path[512]; + std::snprintf(path, sizeof path, "%s/mm_%016llx%016llx_buf.%s.raw", + dump_dir, (unsigned long long)parts.front().item->key_hi, + (unsigned long long)parts.front().item->key_lo, + info.name.c_str()); + if (FILE* f = std::fopen(path, "wb")) { + std::fwrite(raw.data(), 1, raw.size(), f); + std::fclose(f); + RAD_INFO("encoder: wrote %s (%lld rows of %lld bytes)", path, + (long long)rows, (long long)rowb); + } + } + } + } } } @@ -143,9 +220,9 @@ int Engine::run_encodes() { it.pixels.shrink_to_fit(); if (dump_dir && *dump_dir) dump(it, ".bf16", it.embd.data(), it.embd.size()); } - RAD_DEBUG("encoder: %zu item(s) encoded in %.1f ms", items.size(), - std::chrono::duration(std::chrono::steady_clock::now() - t0) - .count()); + const double ms = std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(); + RAD_DEBUG("encoder: %zu item(s) encoded in %.1f ms", items.size(), ms); return RAD_OK; } diff --git a/core/format/checkpoint.cpp b/core/format/checkpoint.cpp index 9b935a3a..5c596d8f 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -247,6 +247,9 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) { m.n_ff = gi("intermediate_size", gi("moe_intermediate_size", 0)); m.n_vocab = gi("vocab_size", 0); m.n_ctx_train = gi("max_position_embeddings", 0); + /* The DeepSeek spelling: Unlimited-OCR's decoder is a DeepSeek-V2 MoE and states its expert + * count as `n_routed_experts`; a routed config names the count under one of the three and + * never under more than one, so the chain is a rename, not a guess. */ m.n_expert = gi("num_experts", gi("num_local_experts", gi("n_routed_experts", 0))); m.n_expert_used = gi("num_experts_per_tok", 0); m.n_expert_shared = gi("n_shared_experts", gi("num_shared_experts", @@ -852,7 +855,10 @@ int Checkpoint::open_safetensors(const std::string& path) { RAD_TRY(meta_merge_generation_config(md, &meta_)); RAD_TRY(meta_merge_preprocessor_configs(md, &meta_)); if (!meta_dir_.empty() && !path_exists(dir_ + "/tokenizer.json")) tok_dir_ = meta_dir_; - if (!is_file && !is_index) RAD_TRY(add_companions()); + if (!is_file && !is_index) { + RAD_TRY(add_companions()); + RAD_TRY(add_torch_files()); + } /* FP8's block, where the checkpoint states one. */ if (const char* bs = meta_.get("quantization_config.weight_block_size")) { long long r = 0, c = 0; @@ -895,6 +901,55 @@ int Checkpoint::add_companions() { return RAD_OK; } +/* PyTorch checkpoints beside the safetensors (torch_zip.h): a model whose part ships only as a + * torch.save file, such as Fish Audio drama-3's codec.pth, read as data, never unpickled. Each is + * read under `.`, in name order. A file the weights-only reader refuses (a pickled training + * state, an optimiser) is not an error of the checkpoint, only of a plugin that maps its tensors, + * which then finds them absent; the warning says why. A torch copy of the model's own weights + * (`pytorch_model*.pth`, `consolidated*.pth`) is passed over, as the safetensors are read. */ +int Checkpoint::add_torch_files() { + std::vector files; + std::error_code ec; + for (const auto& de : std::filesystem::directory_iterator(dir_, ec)) { + if (!de.is_regular_file(ec)) continue; + const std::string f = de.path().filename().string(); + if (f.size() <= 4 || f.compare(f.size() - 4, 4, ".pth") != 0) continue; + if (f.rfind("pytorch_model", 0) == 0 || f.rfind("consolidated", 0) == 0) continue; + files.push_back(f); + } + std::sort(files.begin(), files.end()); + for (const std::string& f : files) { + auto tz = std::make_unique(); + std::string why; + const std::string path = dir_ + "/" + f; + if (tz->open(path, &why) < 0) { + RAD_WARN("%s: not read (%s); a plugin that maps its tensors will not find them", + path.c_str(), why.c_str()); + continue; + } + const std::string prefix = f.substr(0, f.size() - 4) + "."; + for (const TorchTensor& t : tz->tensors()) { + if (index_.count(prefix + t.name)) { + RAD_ERR("%s: '%s%s' is already in the checkpoint", path.c_str(), prefix.c_str(), + t.name.c_str()); + return RAD_E_FORMAT; + } + SrcTensor s; + s.name = prefix + t.name; + s.rad_dtype = t.dtype; + s.shape = t.shape; + s.data = t.data; + s.bytes = (int64_t)t.bytes; + index_.emplace(s.name, tensors_.size()); + tensors_.push_back(std::move(s)); + } + RAD_INFO("%s: %zu tensors under '%s', read from the pickle as data", path.c_str(), + tz->tensors().size(), prefix.c_str()); + torch_.push_back(std::move(tz)); + } + return RAD_OK; +} + /* Which published quantisation this is, from quantization_config alone; import_piece checks the * tensors weight by weight, refusing a file at the first weight that disagrees. */ void Checkpoint::detect_import() { @@ -2950,7 +3005,6 @@ int ckpt_import_form(CkptWeight* w, const ImportForm& f, std::string* why) { return refuse(RAD_E_FORMAT, "the import rule's form of '" + w->name + "' is malformed"); w->enc = e; w->form = f; - w->reform = true; w->imported = true; w->trivial = false; w->why = "it is re-expressed by an import rule"; diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index ae18eb7e..264ddd74 100644 --- a/core/format/checkpoint.h +++ b/core/format/checkpoint.h @@ -24,6 +24,7 @@ #include "../rad_internal.h" #include "../rad_core.h" #include "safetensors.h" +#include "torch_zip.h" #include "../text/gguf.h" #include @@ -212,6 +213,7 @@ private: int open_diffusers(); int open_sgm(); int add_companions(); + int add_torch_files(); int open_gguf(const std::string& path); void detect_import(); @@ -220,6 +222,7 @@ private: GgufFile gguf_; MetaOwn meta_; std::vector> shards_; + std::vector> torch_; std::vector tensors_; std::unordered_map index_; std::unordered_map index_shard_; /* name -> shards_ position */ @@ -287,10 +290,9 @@ struct CkptWeight { * values in the logical shape, which ckpt_rows_f32 serves. Not trivial, so a recipe rule * stores it. */ std::vector derived; - /* An `import` rule's form, applied by ckpt_plane_rows (also `imported`). `rounded` counts the - * shipped scales `form.scale` does not hold exactly and `max_rel` is their largest relative - * change, both found by ckpt_import_form. */ - bool reform = false; + /* An `import` rule's form, applied by ckpt_plane_rows (the weight is then `imported`). + * `rounded` counts the shipped scales `form.scale` does not hold exactly and `max_rel` is their + * largest relative change, both found by ckpt_import_form. */ ImportForm form{}; int64_t rounded = 0; double max_rel = 0; diff --git a/core/format/torch_zip.cpp b/core/format/torch_zip.cpp new file mode 100644 index 00000000..917cefe5 --- /dev/null +++ b/core/format/torch_zip.cpp @@ -0,0 +1,661 @@ +/* torch_zip.cpp -- the zip directory and the weights-only pickle machine (torch_zip.h). */ +#include "torch_zip.h" + +#include +#include +#include +#include +#include +#include +#include + +namespace rad { +namespace { + +/* ================================================================== the zip directory */ +struct Entry { + const uint8_t* data = nullptr; + uint64_t bytes = 0; +}; + +uint16_t u16(const uint8_t* p) { return (uint16_t)(p[0] | (p[1] << 8)); } +uint32_t u32(const uint8_t* p) { + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} +uint64_t u64(const uint8_t* p) { return (uint64_t)u32(p) | ((uint64_t)u32(p + 4) << 32); } + +/* Every stored entry, by name. torch.save writes ZIP64 records past 4 GiB and pads each local + * header's extra field so a storage starts 64-byte aligned, which is why the data offset is read + * from the local header rather than assumed from the central one. */ +int zip_entries(const uint8_t* b, uint64_t n, std::unordered_map* out, + std::string* why) { + auto no = [&](const std::string& w) { + *why = w; + return RAD_E_FORMAT; + }; + if (n < 22) return no("too short to be a zip archive"); + /* The end-of-central-directory record: the last signature within a comment's reach. */ + int64_t eocd = -1; + const uint64_t lo = n > 22 + 65535 ? n - 22 - 65535 : 0; + for (uint64_t at = n - 22 + 1; at-- > lo;) + if (u32(b + at) == 0x06054b50) { + eocd = (int64_t)at; + break; + } + if (eocd < 0) return no("no zip end-of-central-directory record"); + if (u16(b + eocd + 4) != 0 || u16(b + eocd + 6) != 0) return no("a multi-disk zip archive"); + uint64_t count = u16(b + eocd + 10), cd_size = u32(b + eocd + 12), cd_off = u32(b + eocd + 16); + if (count == 0xffff || cd_size == 0xffffffffu || cd_off == 0xffffffffu) { + if (eocd < 20 || u32(b + eocd - 20) != 0x07064b50) + return no("a ZIP64 archive without its end-record locator"); + const uint64_t z = u64(b + eocd - 20 + 8); + if (n < 56 || z > n - 56 || u32(b + z) != 0x06064b50) + return no("a ZIP64 end record outside the file"); + count = u64(b + z + 32); + cd_size = u64(b + z + 40); + cd_off = u64(b + z + 48); + } + if (cd_off > n || cd_size > n - cd_off) return no("the central directory lies outside the file"); + if (count > ((uint64_t)1 << 20)) return no("more than a million zip entries"); + uint64_t at = cd_off; + const uint64_t end = cd_off + cd_size; + for (uint64_t i = 0; i < count; ++i) { + if (end - at < 46 || at > end || u32(b + at) != 0x02014b50) + return no("a malformed central directory entry"); + const uint16_t flags = u16(b + at + 8), method = u16(b + at + 10); + uint64_t csize = u32(b + at + 20), usize = u32(b + at + 24); + const uint64_t nl = u16(b + at + 28), el = u16(b + at + 30), cl = u16(b + at + 32); + uint64_t loff = u32(b + at + 42); + if (46 + nl + el + cl > end - at) return no("a central directory entry runs past its end"); + const std::string name((const char*)b + at + 46, (size_t)nl); + /* The ZIP64 extra field: an 8-byte value for each 32-bit field at its maximum, in order. */ + const uint8_t* ex = b + at + 46 + nl; + for (uint64_t e = 0; e + 4 <= el;) { + const uint64_t id = u16(ex + e), sz = u16(ex + e + 2); + if (e + 4 + sz > el) return no("a malformed extra field in '" + name + "'"); + if (id == 1) { + uint64_t f = e + 4; + const uint64_t fe = e + 4 + sz; + auto take = [&](uint64_t* v) { + if (*v != 0xffffffffu) return true; + if (f + 8 > fe) return false; + *v = u64(ex + f); + f += 8; + return true; + }; + if (!take(&usize) || !take(&csize) || !take(&loff)) + return no("a short ZIP64 extra field in '" + name + "'"); + } + e += 4 + sz; + } + if (flags & 1) return no("'" + name + "' is encrypted"); + if (method != 0) + return no("'" + name + "' is compressed (method " + std::to_string(method) + + "); torch.save stores its entries, and a compressed storage cannot be mapped"); + if (csize != usize) return no("'" + name + "' is stored with two different sizes"); + if (n < 30 || loff > n - 30 || u32(b + loff) != 0x04034b50) + return no("'" + name + "' has no local header where the directory places it"); + const uint64_t data = loff + 30 + u16(b + loff + 26) + u16(b + loff + 28); + if (data > n || usize > n - data) return no("'" + name + "' runs past the end of the file"); + if (!out->emplace(name, Entry{ b + data, usize }).second) + return no("'" + name + "' is in the archive twice"); + at += 46 + nl + el + cl; + } + return RAD_OK; +} + +/* ================================================================== the pickle machine */ +/* A value of the weights-only subset. Containers hold indices into the machine's pool, so a value + * reached twice through the memo is one value. */ +struct V { + enum K : uint8_t { None, Bool, Int, Float, Str, Bytes, Tuple, List, Dict, Global, Storage, + Tensor } k = None; + int64_t i = 0; /* Int, Bool; Storage: numel */ + double f = 0; + std::string s; /* Str, Bytes, Global's "module.name", Storage's key */ + std::vector a; /* Tuple, List; Dict: keys and values interleaved */ + uint32_t dtype = 0; /* Storage */ + std::string cls; /* Storage: its class */ + size_t storage = 0; /* Tensor */ + int64_t offset = 0; /* Tensor, in elements */ + std::vector shape, stride; /* Tensor */ +}; + +/* The storages torch writes a state dict's tensors into, and the dtype each holds. Doubles and + * complex storages have no RAD dtype and are refused by name where they appear. */ +uint32_t storage_dtype(const std::string& g) { + static const struct { const char* name; uint32_t dt; } kS[] = { + { "torch.FloatStorage", RAD_F32 }, { "torch.HalfStorage", RAD_F16 }, + { "torch.BFloat16Storage", RAD_BF16 }, { "torch.LongStorage", RAD_I64 }, + { "torch.IntStorage", RAD_I32 }, { "torch.ShortStorage", RAD_I16 }, + { "torch.CharStorage", RAD_I8 }, { "torch.ByteStorage", RAD_U8 }, + { "torch.BoolStorage", RAD_BOOL }, + }; + for (const auto& s : kS) + if (g == s.name) return s.dt; + return RAD_DT_INVALID; +} + +/* torch's weights-only allow-list, the part a state dict uses. */ +bool allowed_global(const std::string& g) { + return g == "collections.OrderedDict" || g == "torch._utils._rebuild_tensor_v2" || + g == "torch._utils._rebuild_parameter" || storage_dtype(g) != RAD_DT_INVALID; +} + +class Machine { +public: + Machine(const uint8_t* p, uint64_t n) : p_(p), n_(n) {} + + /* The pickle's result, or a negative status with `why`. */ + int run(size_t* result, std::string* why); + const V& at(size_t i) const { return pool_[i]; } + size_t size() const { return pool_.size(); } + +private: + static constexpr size_t kMaxPool = (size_t)1 << 23; + static constexpr size_t kMaxStack = (size_t)1 << 20; + static constexpr uint64_t kMaxStr = (uint64_t)1 << 20; + + int no(const std::string& w) { + why_ = w + " at byte " + std::to_string(at_) + " of the pickle"; + return RAD_E_FORMAT; + } + bool need(uint64_t k) const { return n_ - at_ >= k; } + size_t add(V v) { + pool_.push_back(std::move(v)); + return pool_.size() - 1; + } + bool pop(size_t* v) { + if (stack_.size() <= (marks_.empty() ? 0 : marks_.back())) return false; + *v = stack_.back(); + stack_.pop_back(); + return true; + } + /* The items above the last mark, and the mark gone. */ + bool pop_mark(std::vector* items) { + if (marks_.empty()) return false; + const size_t m = marks_.back(); + marks_.pop_back(); + items->assign(stack_.begin() + (std::ptrdiff_t)m, stack_.end()); + stack_.resize(m); + return true; + } + int push(size_t v) { + if (stack_.size() >= kMaxStack || pool_.size() >= kMaxPool) + return no("the pickle builds more than its bounds allow"); + stack_.push_back(v); + return RAD_OK; + } + int str(uint64_t len, V::K k) { + if (len > kMaxStr || !need(len)) return no("a string past its bound or the pickle's end"); + V v; + v.k = k; + v.s.assign((const char*)p_ + at_, (size_t)len); + at_ += len; + return push(add(std::move(v))); + } + int integer(int64_t x) { + V v; + v.k = V::Int; + v.i = x; + return push(add(std::move(v))); + } + int global(const std::string& mod, const std::string& name) { + const std::string g = mod + "." + name; + if (!allowed_global(g)) + return no("the global '" + g + "', which a weights-only checkpoint does not name; " + "nothing in the file is run, so it is refused"); + V v; + v.k = V::Global; + v.s = g; + return push(add(std::move(v))); + } + int reduce(); + int persistent_id(); + + const uint8_t* p_; + uint64_t n_; + uint64_t at_ = 0; + std::vector pool_; + std::vector stack_, marks_; + std::unordered_map memo_; + std::string why_; +}; + +int Machine::persistent_id() { + size_t pid; + if (!pop(&pid)) return no("BINPERSID with nothing to read"); + const V& t = pool_[pid]; + /* ('storage', , key, location, numel) */ + if (t.k != V::Tuple || t.a.size() != 5 || pool_[t.a[0]].k != V::Str || + pool_[t.a[0]].s != "storage" || pool_[t.a[1]].k != V::Global || + pool_[t.a[2]].k != V::Str || pool_[t.a[4]].k != V::Int) + return no("a persistent id that is not a storage"); + V s; + s.k = V::Storage; + s.cls = pool_[t.a[1]].s; + s.dtype = storage_dtype(s.cls); + s.s = pool_[t.a[2]].s; + s.i = pool_[t.a[4]].i; + if (s.dtype == RAD_DT_INVALID) return no("the storage class '" + s.cls + "'"); + if (s.i < 0) return no("a storage of negative size"); + return push(add(std::move(s))); +} + +int Machine::reduce() { + size_t args, fn; + if (!pop(&args) || !pop(&fn)) return no("REDUCE without its callable and arguments"); + if (pool_[fn].k != V::Global) return no("REDUCE of something that is not a global"); + if (pool_[args].k != V::Tuple) return no("REDUCE with arguments that are not a tuple"); + const std::string g = pool_[fn].s; + const std::vector a = pool_[args].a; + if (g == "collections.OrderedDict") { + if (!a.empty()) return no("an OrderedDict built from arguments"); + V d; + d.k = V::Dict; + return push(add(std::move(d))); + } + if (g == "torch._utils._rebuild_tensor_v2") { + /* (storage, storage_offset, size, stride, requires_grad, backward_hooks[, metadata]) */ + if (a.size() < 4 || pool_[a[0]].k != V::Storage || pool_[a[1]].k != V::Int || + pool_[a[2]].k != V::Tuple || pool_[a[3]].k != V::Tuple) + return no("_rebuild_tensor_v2 with arguments that are not a tensor's"); + V t; + t.k = V::Tensor; + t.storage = a[0]; + t.offset = pool_[a[1]].i; + for (size_t d : pool_[a[2]].a) { + if (pool_[d].k != V::Int || pool_[d].i < 0) return no("a tensor size that is not one"); + t.shape.push_back(pool_[d].i); + } + for (size_t d : pool_[a[3]].a) { + if (pool_[d].k != V::Int) return no("a tensor stride that is not one"); + t.stride.push_back(pool_[d].i); + } + if (t.shape.size() != t.stride.size() || t.shape.size() > RAD_MAX_RANK) + return no("a tensor whose size and stride disagree, or of rank past " + + std::to_string(RAD_MAX_RANK)); + return push(add(std::move(t))); + } + if (g == "torch._utils._rebuild_parameter") { + /* (data, requires_grad, backward_hooks): the parameter is its tensor. */ + if (a.empty() || pool_[a[0]].k != V::Tensor) return no("_rebuild_parameter of a non-tensor"); + return push(a[0]); + } + return no("a call of '" + g + "'"); +} + +int Machine::run(size_t* result, std::string* why) { + auto fail = [&](int st) { + *why = why_; + return st; + }; + auto line = [&](std::string* out) { + const uint8_t* e = (const uint8_t*)std::memchr(p_ + at_, '\n', (size_t)(n_ - at_)); + if (!e || (uint64_t)(e - (p_ + at_)) > 4096) return false; + out->assign((const char*)p_ + at_, (size_t)(e - (p_ + at_))); + at_ = (uint64_t)(e - p_) + 1; + return true; + }; + int st = RAD_OK; + while (at_ < n_) { + const uint8_t op = p_[at_++]; + switch (op) { + case 0x80: /* PROTO */ + if (!need(1) || p_[at_] < 2 || p_[at_] > 5) return fail(no("a pickle protocol other than 2..5")); + ++at_; + break; + case 0x95: /* FRAME: a length hint */ + if (!need(8)) return fail(no("a truncated FRAME")); + at_ += 8; + break; + case 'c': { /* GLOBAL "module\nname\n" */ + std::string mod, name; + if (!line(&mod) || !line(&name)) return fail(no("a malformed GLOBAL")); + st = global(mod, name); + break; + } + case 0x93: { /* STACK_GLOBAL */ + size_t nm, md; + if (!pop(&nm) || !pop(&md) || pool_[nm].k != V::Str || pool_[md].k != V::Str) + return fail(no("STACK_GLOBAL without a module and a name")); + st = global(pool_[md].s, pool_[nm].s); + break; + } + case 'q': case 'r': case 0x94: { /* BINPUT, LONG_BINPUT, MEMOIZE */ + uint32_t k; + if (op == 'q') { + if (!need(1)) return fail(no("a truncated BINPUT")); + k = p_[at_++]; + } else if (op == 'r') { + if (!need(4)) return fail(no("a truncated LONG_BINPUT")); + k = u32(p_ + at_); + at_ += 4; + } else { + k = (uint32_t)memo_.size(); + } + if (stack_.empty()) return fail(no("a memo store with nothing to store")); + if (memo_.size() >= kMaxStack) return fail(no("a memo past its bound")); + memo_[k] = stack_.back(); + break; + } + case 'h': case 'j': { /* BINGET, LONG_BINGET */ + uint32_t k; + if (op == 'h') { + if (!need(1)) return fail(no("a truncated BINGET")); + k = p_[at_++]; + } else { + if (!need(4)) return fail(no("a truncated LONG_BINGET")); + k = u32(p_ + at_); + at_ += 4; + } + auto it = memo_.find(k); + if (it == memo_.end()) return fail(no("a memo read of an empty slot")); + st = push(it->second); + break; + } + case '(': /* MARK */ + if (marks_.size() >= kMaxStack) return fail(no("marks past their bound")); + marks_.push_back(stack_.size()); + break; + case ')': { /* EMPTY_TUPLE */ + V t; + t.k = V::Tuple; + st = push(add(std::move(t))); + break; + } + case 't': case 0x85: case 0x86: case 0x87: { /* TUPLE, TUPLE1..3 */ + V t; + t.k = V::Tuple; + if (op == 't') { + if (!pop_mark(&t.a)) return fail(no("TUPLE without a mark")); + } else { + const int k = op - 0x84; + t.a.resize((size_t)k); + for (int j = k - 1; j >= 0; --j) + if (!pop(&t.a[(size_t)j])) return fail(no("a short tuple")); + } + st = push(add(std::move(t))); + break; + } + case ']': case '}': { /* EMPTY_LIST, EMPTY_DICT */ + V c; + c.k = op == ']' ? V::List : V::Dict; + st = push(add(std::move(c))); + break; + } + case 'a': case 'e': { /* APPEND, APPENDS */ + std::vector items(1); + if (op == 'a') { + if (!pop(&items[0])) return fail(no("APPEND with nothing to append")); + } else if (!pop_mark(&items)) { + return fail(no("APPENDS without a mark")); + } + if (stack_.empty() || pool_[stack_.back()].k != V::List) + return fail(no("APPEND to something that is not a list")); + V& l = pool_[stack_.back()]; + l.a.insert(l.a.end(), items.begin(), items.end()); + break; + } + case 's': case 'u': { /* SETITEM, SETITEMS */ + std::vector kv(2); + if (op == 's') { + if (!pop(&kv[1]) || !pop(&kv[0])) return fail(no("SETITEM without a pair")); + } else if (!pop_mark(&kv) || kv.size() % 2) { + return fail(no("SETITEMS without whole pairs")); + } + if (stack_.empty() || pool_[stack_.back()].k != V::Dict) + return fail(no("a SETITEM on something that is not a dict")); + V& d = pool_[stack_.back()]; + d.a.insert(d.a.end(), kv.begin(), kv.end()); + break; + } + case 'b': { /* BUILD: an OrderedDict's state (a state dict's _metadata), ignored */ + size_t state; + if (!pop(&state)) return fail(no("BUILD without a state")); + if (stack_.empty() || pool_[stack_.back()].k != V::Dict) + return fail(no("BUILD of something other than a dict")); + break; + } + case 'X': case 0x8c: case 0x8d: case 'B': case 'C': case 0x8e: { + /* BINUNICODE, SHORT_BINUNICODE, BINUNICODE8, BINBYTES, SHORT_BINBYTES, BINBYTES8 */ + uint64_t len; + const int w = (op == 0x8c || op == 'C') ? 1 : (op == 0x8d || op == 0x8e) ? 8 : 4; + if (!need((uint64_t)w)) return fail(no("a truncated string length")); + len = w == 1 ? p_[at_] : w == 4 ? u32(p_ + at_) : u64(p_ + at_); + at_ += (uint64_t)w; + st = str(len, (op == 'B' || op == 'C' || op == 0x8e) ? V::Bytes : V::Str); + break; + } + case 'J': /* BININT */ + if (!need(4)) return fail(no("a truncated BININT")); + st = integer((int32_t)u32(p_ + at_)); + at_ += 4; + break; + case 'K': /* BININT1 */ + if (!need(1)) return fail(no("a truncated BININT1")); + st = integer(p_[at_++]); + break; + case 'M': /* BININT2 */ + if (!need(2)) return fail(no("a truncated BININT2")); + st = integer(u16(p_ + at_)); + at_ += 2; + break; + case 0x8a: { /* LONG1: little-endian two's complement of up to 8 bytes here */ + if (!need(1)) return fail(no("a truncated LONG1")); + const uint64_t k = p_[at_++]; + if (k > 8 || !need(k)) return fail(no("a LONG1 wider than 64 bits")); + uint64_t v = 0; + for (uint64_t j = 0; j < k; ++j) v |= (uint64_t)p_[at_ + j] << (8 * j); + if (k > 0 && k < 8 && (p_[at_ + k - 1] & 0x80)) v |= ~(uint64_t)0 << (8 * k); + at_ += k; + st = integer((int64_t)v); + break; + } + case 'G': { /* BINFLOAT, big-endian */ + if (!need(8)) return fail(no("a truncated BINFLOAT")); + uint64_t v = 0; + for (int j = 0; j < 8; ++j) v = (v << 8) | p_[at_ + j]; + at_ += 8; + V f; + f.k = V::Float; + std::memcpy(&f.f, &v, 8); + st = push(add(std::move(f))); + break; + } + case 0x88: case 0x89: { /* NEWTRUE, NEWFALSE */ + V v; + v.k = V::Bool; + v.i = op == 0x88; + st = push(add(std::move(v))); + break; + } + case 'N': + st = push(add(V{})); + break; + case 'Q': + st = persistent_id(); + break; + case 'R': + st = reduce(); + break; + case '.': { /* STOP */ + size_t r; + if (!pop(&r)) return fail(no("STOP with nothing to return")); + *result = r; + return RAD_OK; + } + default: { + char hex[8]; + std::snprintf(hex, sizeof hex, "0x%02x", op); + return fail(no(std::string("the opcode ") + hex + + ", which a weights-only checkpoint does not use")); + } + } + if (st < 0) return fail(st); + } + return fail(no("no STOP before the pickle's end")); +} + +/* A state dict's tensors, nested dicts flattened to dotted names. The memo lets a dict hold itself + * or be shared by several parents; a state dict's dicts form a tree, so a dict reached a second + * time is refused, which also bounds the walk by the pool. */ +constexpr int kMaxDictDepth = 64; + +bool walk(const Machine& m, size_t d, const std::string& prefix, int depth, + std::vector* seen, std::vector>* out, + std::string* why) { + if (depth > kMaxDictDepth) { + *why = "dicts nested deeper than " + std::to_string(kMaxDictDepth) + " under '" + prefix + + "'"; + return false; + } + if ((*seen)[d]) { + *why = "a dict reached twice (under '" + prefix + "'); a state dict's dicts form a tree"; + return false; + } + (*seen)[d] = 1; + const V& v = m.at(d); + for (size_t j = 0; j + 1 < v.a.size(); j += 2) { + const V& k = m.at(v.a[j]); + if (k.k != V::Str) continue; + const V& x = m.at(v.a[j + 1]); + if (x.k == V::Tensor) out->emplace_back(prefix + k.s, v.a[j + 1]); + else if (x.k == V::Dict && + !walk(m, v.a[j + 1], prefix + k.s + ".", depth + 1, seen, out, why)) + return false; + } + return true; +} + +} /* namespace */ + +/* ================================================================== the file */ +TorchZipFile::~TorchZipFile() { close(); } + +void TorchZipFile::close() { + if (map_) ::munmap(map_, (size_t)bytes_); + if (fd_ >= 0) ::close(fd_); + map_ = nullptr; + base_ = nullptr; + bytes_ = 0; + fd_ = -1; + tensors_.clear(); +} + +int TorchZipFile::open(const std::string& path, std::string* why) { + close(); + path_ = path; + fd_ = ::open(path.c_str(), O_RDONLY | O_CLOEXEC); + if (fd_ < 0) { + *why = std::strerror(errno); + return RAD_E_IO; + } + struct stat st{}; + if (::fstat(fd_, &st) != 0) { + *why = std::strerror(errno); + close(); + return RAD_E_IO; + } + bytes_ = (uint64_t)st.st_size; + void* m = bytes_ ? ::mmap(nullptr, (size_t)bytes_, PROT_READ, MAP_PRIVATE, fd_, 0) : MAP_FAILED; + if (m == MAP_FAILED) { + *why = bytes_ ? std::string("mmap: ") + std::strerror(errno) : std::string("empty file"); + close(); + return bytes_ ? RAD_E_IO : RAD_E_FORMAT; + } + map_ = (uint8_t*)m; + base_ = map_; + const int s = parse(why); + if (s < 0) close(); + return s; +} + +int TorchZipFile::open_bytes(const uint8_t* data, uint64_t bytes, std::string* why) { + close(); + path_ = "(memory)"; + base_ = data; + bytes_ = bytes; + return parse(why); +} + +int TorchZipFile::parse(std::string* why) { + std::unordered_map ent; + RAD_TRY(zip_entries(base_, bytes_, &ent, why)); + /* The archive's one directory: the one holding data.pkl. */ + std::string dir; + int n_pkl = 0; + for (const auto& [name, e] : ent) { + const size_t sl = name.find('/'); + if (sl != std::string::npos && name.compare(sl, std::string::npos, "/data.pkl") == 0) { + dir = name.substr(0, sl + 1); + ++n_pkl; + } + } + if (n_pkl != 1) { + *why = n_pkl ? "more than one data.pkl" : "no /data.pkl: not a torch.save checkpoint"; + return RAD_E_FORMAT; + } + if (auto it = ent.find(dir + "byteorder"); it != ent.end() && + std::string((const char*)it->second.data, (size_t)it->second.bytes) != "little") { + *why = "a big-endian checkpoint"; + return RAD_E_FORMAT; + } + const Entry& pk = ent[dir + "data.pkl"]; + Machine m(pk.data, pk.bytes); + size_t root = 0; + RAD_TRY(m.run(&root, why)); + if (m.at(root).k != V::Dict) { + *why = "the pickle's result is not a state dict"; + return RAD_E_FORMAT; + } + std::vector> found; + std::vector seen(m.size(), 0); + if (!walk(m, root, "", 0, &seen, &found, why)) return RAD_E_FORMAT; + for (const auto& [name, ti] : found) { + const V& t = m.at(ti); + const V& s = m.at(t.storage); + auto it = ent.find(dir + "data/" + s.s); + if (it == ent.end()) { + *why = "'" + name + "' reads storage '" + s.s + "', which the archive does not hold"; + return RAD_E_FORMAT; + } + const int64_t esz = (int64_t)rad_dtype_bits(s.dtype) / 8; + /* The element count in checked arithmetic: a product that wraps would pass the fit + * check below with a shape that names far more bytes than the storage holds. */ + int64_t numel = 1; + bool contig = true, wraps = false; + for (size_t d = t.shape.size(); d-- > 0;) { + if (t.shape[d] != 1 && t.stride[d] != numel) contig = false; + wraps |= __builtin_mul_overflow(numel, t.shape[d], &numel); + } + int64_t end_bytes = 0; + if (!wraps && t.offset >= 0) + wraps = __builtin_add_overflow(t.offset, numel, &end_bytes) || + __builtin_mul_overflow(end_bytes, esz, &end_bytes); + if (wraps) { + *why = "'" + name + "' has a size or offset past 64 bits"; + return RAD_E_FORMAT; + } + if (!contig) { + *why = "'" + name + "' is not contiguous in its storage"; + return RAD_E_FORMAT; + } + if (t.offset < 0 || numel > s.i - t.offset || (uint64_t)end_bytes > it->second.bytes) { + *why = "'" + name + "' does not fit its storage '" + s.s + "'"; + return RAD_E_FORMAT; + } + if (numel == 0) continue; + TorchTensor tt; + tt.name = name; + tt.dtype = s.dtype; + tt.storage = s.cls; + tt.shape = t.shape; + tt.data = it->second.data + t.offset * esz; + tt.bytes = (uint64_t)(numel * esz); + tensors_.push_back(std::move(tt)); + } + return RAD_OK; +} + +} /* namespace rad */ diff --git a/core/format/torch_zip.h b/core/format/torch_zip.h new file mode 100644 index 00000000..a0ef7d1a --- /dev/null +++ b/core/format/torch_zip.h @@ -0,0 +1,64 @@ +/* torch_zip.h -- a PyTorch checkpoint (torch.save's zip format) as tensors, read without running + * any of its pickle. + * + * A .pth from torch.save is a zip archive of stored entries: `/data.pkl`, a pickle of the + * state dict whose tensors name their bytes by a persistent id, `/data/` holding + * each storage's raw little-endian bytes, and `/byteorder`. Fish Audio's codec ships this + * way (drama-3's codec.pth), with no safetensors copy. + * + * Unpickling would run whatever the file names. This reads the pickle as data instead: a small + * machine over the opcodes a weights-only file uses, whose only callables are the ones torch's own + * `weights_only` loader allows a state dict (collections.OrderedDict, + * torch._utils._rebuild_tensor_v2 and _rebuild_parameter) and whose only classes are the typed + * storages. Any other global, any other opcode, a compressed or encrypted entry, or a storage that + * does not hold its tensor is refused by name. Every read is bounds-checked and the machine's + * stack, memo and object counts are capped. + * + * Storages are mmapped, not copied; a tensor must be contiguous in its storage. Nested dicts + * flatten to dotted names, and values that are not tensors (an epoch count) are skipped. + */ +#pragma once +#include "../rad_internal.h" + +#include +#include + +namespace rad { + +struct TorchTensor { + std::string name; + uint32_t dtype = RAD_DT_INVALID; + std::string storage; /* the torch storage class, for diagnostics */ + std::vector shape; /* row-major */ + const uint8_t* data = nullptr; + uint64_t bytes = 0; +}; + +class TorchZipFile { +public: + TorchZipFile() = default; + ~TorchZipFile(); + TorchZipFile(const TorchZipFile&) = delete; + TorchZipFile& operator=(const TorchZipFile&) = delete; + + /* RAD_OK, or a negative RAD_E_* with `why` saying what was refused. */ + int open(const std::string& path, std::string* why); + /* The same over bytes the caller keeps alive (a test's archive in memory). */ + int open_bytes(const uint8_t* data, uint64_t bytes, std::string* why); + void close(); + + const std::vector& tensors() const { return tensors_; } + const std::string& path() const { return path_; } + +private: + int parse(std::string* why); + + int fd_ = -1; + uint8_t* map_ = nullptr; + const uint8_t* base_ = nullptr; + uint64_t bytes_ = 0; + std::string path_; + std::vector tensors_; +}; + +} /* namespace rad */ diff --git a/core/gen/audio.h b/core/gen/audio.h index b879a537..f649c408 100644 --- a/core/gen/audio.h +++ b/core/gen/audio.h @@ -65,6 +65,12 @@ struct AudioRequest { * conditional prompt as the declaration says (neg_token), and `neg_tokens` is empty. */ std::vector tokens; std::vector neg_tokens; + /* References (RadAudioGenDecl::tmpl_ref): the clips' samples end to end, each padded to whole + * frames; their bounds in samples, [clips + 1]; and for each row of `tokens` the frame of the + * clips it is, -1 for a token. All empty without references. */ + std::vector ref_audio; + std::vector ref_cu; + std::vector ref_frame; int64_t max_frames = 0; /* the most frames to make, >= 1 */ int32_t steps = 0; /* 0: the model's default */ float cfg = 0.0f; /* 0: the model's default */ diff --git a/core/gen/audio_driver.cpp b/core/gen/audio_driver.cpp index c40df146..1778e9e0 100644 --- a/core/gen/audio_driver.cpp +++ b/core/gen/audio_driver.cpp @@ -64,12 +64,25 @@ namespace { constexpr int64_t kAlign = 256; -int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; } - struct Sizes { int64_t T = 0, S = 0, L = 0, NB = 0; + int64_t NG = 0; /* stateful KV groups */ + int64_t RS = 0, RN = 0; /* references: samples and clips a request */ }; +/* The paged full-attention group, and how many stateful groups sit beside it. */ +int32_t full_group(const Program& prog, int64_t* n_state) { + int32_t full = 0; + int64_t ns = 0; + for (size_t g = 1; g < prog.kv_groups.size(); ++g) { + const int kind = prog.kv_groups[g].decl.kind; + if (kind == RAD_KV_FULL && !full) full = (int32_t)g; + else if (kind == RAD_KV_LINEAR || kind == RAD_KV_CONV) ++ns; + } + if (n_state) *n_state = ns; + return full; +} + Sizes sizes_of(const Program& prog, int64_t block_size) { const RadAudioGenDecl& d = prog.audio_gen; Sizes z; @@ -77,6 +90,9 @@ Sizes sizes_of(const Program& prog, int64_t block_size) { z.S = prog.ctx.max_seqs; z.L = d.max_lanes; z.NB = block_size > 0 ? (AudioDriver::max_seq_rows(d) + block_size - 1) / block_size : 0; + full_group(prog, &z.NG); + z.RS = d.ref_max_samples; + z.RN = d.ref_max; return z; } @@ -110,12 +126,22 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) { z.S * I, /* R_ESLOT */ z.S * I, /* R_LROW */ z.S * I, /* R_PREFIX */ + z.S * I, /* R_CTX */ + z.S * I, /* R_ACC */ + z.NG * z.S * I, /* R_SBT */ + z.NG * z.S * AudioDriver::kMaxStateWidth * I, /* R_SIDX */ + z.S * I, /* R_PSLOT */ + z.S * I, /* R_PPOS */ + z.S * I, /* R_PUSED */ + z.RS * 4, /* R_RAUD */ + z.RN > 0 ? (z.RN + 1) * I : 0, /* R_RCU */ + z.RN > 0 ? z.T * I : 0, /* R_RFRM */ }; int64_t off = 0; for (int r = 0; r < n; ++r) { bytes[r][0] = off; bytes[r][1] = want[r]; - off = align_up(off + want[r]); + off = align_up(off + want[r], kAlign); } return off; } @@ -123,8 +149,10 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) { } /* namespace */ int64_t AudioDriver::device_bytes(const Program& prog) { - if (!prog.is_audio_generator() || prog.kv_groups.size() < 2) return 0; - const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size); + if (!prog.is_audio_generator()) return 0; + const int32_t fg = full_group(prog, nullptr); + if (!fg) return 0; + const Sizes z = sizes_of(prog, prog.kv_groups[(size_t)fg].block_size); int64_t b[R_N][2]; return carve(z, b, R_N); } @@ -136,15 +164,39 @@ int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector(1, kv->state_index_width((int32_t)g)); + if (sg.width > kMaxStateWidth) { + RAD_ERR("audio generator: KV group %zu asks for %lld state slots a sequence; the " + "driver stages at most %lld", g, (long long)sg.width, + (long long)kMaxStateWidth); + return RAD_E_UNSUPPORTED; + } + state_groups_.push_back(sg); + } else { + n_full = -1; + break; + } + } + kv_group_ = full_group(prog, nullptr); + if (n_full != 1 || !kv_group_ || prog.kv_groups[(size_t)kv_group_].block_size <= 0) { + RAD_ERR("audio generator: the program declares %zu KV group(s); the driver stages one " + "paged full-attention group, the language model's, and the state and " + "convolution groups of a hybrid one beside it", prog.kv_groups.size() - 1); return RAD_E_UNSUPPORTED; } - kv_group_ = 1; - block_size_ = prog.kv_groups[1].block_size; + block_size_ = prog.kv_groups[(size_t)kv_group_].block_size; + nb_ = decl_.branches == 1 ? 1 : 2; const Sizes z = sizes_of(prog, block_size_); max_tok_ = z.T; max_seqs_ = z.S; @@ -154,13 +206,13 @@ int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector= 0; --i) free_lanes_.push_back((int32_t)i); return RAD_OK; @@ -224,7 +276,9 @@ int AudioDriver::submit(std::unique_ptr r, std::string* why) { return RAD_E_INVAL; }; const int64_t T = (int64_t)r->tokens.size(), Tn = (int64_t)r->neg_tokens.size(); - if (!neg_own_ && T <= d.neg_keep_head + d.neg_keep_tail) + if (nb_ == 1 && r->cfg != 0.0f && r->cfg != 1.0f) + return no("this model runs without guidance; guidance_scale must be 1"); + if (nb_ == 2 && !neg_own_ && T <= d.neg_keep_head + d.neg_keep_tail) return no("the prompt is " + std::to_string(T) + " tokens, too short to hold its own " "markers"); if (T < 1 || std::max(T, Tn) > d.max_prompt) @@ -236,6 +290,25 @@ int AudioDriver::submit(std::unique_ptr r, std::string* why) { " seconds)"); if (r->steps < 0 || r->steps > 1000) return no("num_inference_steps must be 1..1000"); 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()) { + 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() && + (int64_t)r->ref_audio.size() <= d.ref_max_samples && + (int64_t)r->ref_frame.size() == T; + for (int64_t i = 0; ok && i < n_ref; ++i) + ok = r->ref_cu[(size_t)i + 1] > r->ref_cu[(size_t)i] && r->ref_cu[(size_t)i + 1] % hop == 0; + 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) + 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, " + + std::to_string(d.ref_max_samples) + " samples together" + : std::string("this model takes no reference audio")); + } if (!kv_->can_ever_fit(std::max(T, Tn) + r->max_frames + 1)) return no("a piece of " + std::to_string(r->max_frames) + " frames after a " + std::to_string(T) + "-token prompt does not fit the KV cache even when it is " @@ -309,16 +382,19 @@ int AudioDriver::admit_locked() { const float cfg = r.cfg > 0.0f ? r.cfg : (float)decl_.default_cfg; /* The unconditional prompt: the request's own (the conditional one at guidance 1, which * makes the guided logits the conditional ones), or derived from the conditional one. */ - std::vector neg = r.tokens; - if (neg_own_ && cfg != 1.0f && !r.neg_tokens.empty()) { - neg = r.neg_tokens; - } else if (!neg_own_) { - for (int64_t i = decl_.neg_keep_head; i < j.T - decl_.neg_keep_tail; ++i) - neg[(size_t)i] = decl_.neg_token; + std::vector neg; + if (nb_ > 1) { + neg = r.tokens; + if (neg_own_ && cfg != 1.0f && !r.neg_tokens.empty()) { + neg = r.neg_tokens; + } else if (!neg_own_) { + for (int64_t i = decl_.neg_keep_head; i < j.T - decl_.neg_keep_tail; ++i) + neg[(size_t)i] = decl_.neg_token; + } } - /* Both branches for the whole piece, so nothing in flight ever waits for KV. */ + /* Every branch for the whole piece, so nothing in flight ever waits for KV. */ bool ok = true; - for (int b = 0; b < 2 && ok; ++b) { + for (int b = 0; b < nb_ && ok; ++b) { const int64_t rows = (b ? (int64_t)neg.size() : j.T) + r.max_frames + 1; j.seq[b] = ((uint64_t)1 << 61) | next_seq_++; if (kv_->add_sequence(j.seq[b]) < 0 || kv_->ensure(j.seq[b], rows) < 0) ok = false; @@ -390,7 +466,7 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3 for (size_t r = 0; r < ranks_.size(); ++r) { RadBatch& B = out_[r]; RadAudioGenBatch& A = aout_[r]; - RadKVGroupBatch& K = kout_[r]; + RadKVGroupBatch& K = kout_[r * (1 + state_groups_.size())]; const int ri = (int)r; B = RadBatch{}; B.step = step; @@ -412,8 +488,23 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3 K.seqused = dptr(ri, R_USED); K.block_size = block_size_; K.max_blocks = max_blocks_; - B.n_kv_groups = 1; + /* A stateful group's block-table row is the sequence's slot, as the text scheduler + * stages it, so a kernel reading tables needs no second path. */ + for (size_t gi = 0; gi < state_groups_.size(); ++gi) { + RadKVGroupBatch& Ks = (&K)[1 + gi]; + Ks = RadKVGroupBatch{}; + Ks.group = (rad_kvgroup)state_groups_[gi].g; + Ks.block_table = dptr(ri, R_SBT) + gi * max_seqs_; + Ks.block_table_pitch = 1; + Ks.seqused = dptr(ri, R_USED); + Ks.state_index = dptr(ri, R_SIDX) + gi * max_seqs_ * kMaxStateWidth; + Ks.state_index_pitch = state_groups_[gi].width; + Ks.max_blocks = 1; + } + B.n_kv_groups = (int)(1 + state_groups_.size()); B.kv = &K; + B.ctx_lens = dptr(ri, R_CTX); + B.num_accepted = dptr(ri, R_ACC); } A = RadAudioGenBatch{}; A.lane = dptr(ri, R_LANE); @@ -434,10 +525,38 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3 A.slot = dptr(ri, R_ESLOT); A.last_row = dptr(ri, R_LROW); A.prefix = dptr(ri, R_PREFIX); + A.prev_slot = dptr(ri, R_PSLOT); + A.prev_pos = dptr(ri, R_PPOS); + A.prev_used = dptr(ri, R_PUSED); B.agen_b = &A; } } +void AudioDriver::stage_state(const std::vector& seqs, const std::vector& ctx) { + const int64_t n = (int64_t)seqs.size(); + int32_t* cl = hptr(R_CTX); + int32_t* acc = hptr(R_ACC); + for (int64_t e = 0; e < n; ++e) { + cl[e] = ctx[(size_t)e]; + /* One-based, as num_accepted always is: a pass commits every row it runs. */ + acc[e] = 1; + } + reg_[R_CTX].used = reg_[R_ACC].used = n * 4; + for (size_t gi = 0; gi < state_groups_.size(); ++gi) { + const StateGroup& sg = state_groups_[gi]; + int32_t* bt = hptr(R_SBT) + gi * max_seqs_; + int32_t* si = hptr(R_SIDX) + gi * max_seqs_ * kMaxStateWidth; + for (int64_t e = 0; e < n; ++e) { + bt[e] = kv_->state_slot(seqs[(size_t)e], sg.g); + kv_->state_index_row(seqs[(size_t)e], sg.g, si + e * sg.width, (int)sg.width); + } + } + if (!state_groups_.empty()) { + reg_[R_SBT].used = (int64_t)state_groups_.size() * max_seqs_ * 4; + reg_[R_SIDX].used = (int64_t)state_groups_.size() * max_seqs_ * kMaxStateWidth * 4; + } +} + /* The KV slot of position `p` in a sequence with this block table. */ static int32_t slot_of(const std::vector& bt, int64_t p, int64_t bs) { const int64_t bi = p / bs; @@ -517,12 +636,13 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; /* Each branch's rows: both whole, or the same chunk of both (their lengths are then equal). */ const int64_t p0 = j.prompt_done; - int64_t cb[2]; + int64_t cb[2] = { 0, 0 }; if (decl_.prompt_whole) { cb[0] = j.T; - cb[1] = j.Tn; + cb[1] = nb_ > 1 ? j.Tn : 0; } else { - cb[0] = cb[1] = std::min(j.T - j.prompt_done, max_tok_ / 2); + cb[0] = std::min(j.T - j.prompt_done, max_tok_ / nb_); + cb[1] = nb_ > 1 ? cb[0] : 0; } const int64_t cmax = std::max(cb[0], cb[1]); int32_t* tok = hptr(R_TOK); @@ -530,12 +650,12 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { int32_t* slot = hptr(R_SLOT); int32_t* cu = hptr(R_CU); int64_t pitch = 1; - for (int b = 0; b < 2; ++b) + for (int b = 0; b < nb_; ++b) pitch = std::max(pitch, (int64_t)kv_->block_table(j.seq[b], kv_group_).size()); int32_t* btab = hptr(R_BT); int32_t* used = hptr(R_USED); cu[0] = 0; - for (int b = 0; b < 2; ++b) { + for (int b = 0; b < nb_; ++b) { const std::vector& src = b ? j.neg : j.req->tokens; const std::vector& bt = kv_->block_table(j.seq[b], kv_group_); for (int64_t i = 0; i < cb[b]; ++i) { @@ -549,26 +669,47 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { btab[b * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1; used[b] = (int32_t)(p0 + cb[b]); } - const int64_t rows = cu[2]; + const int64_t rows = cu[nb_]; const bool last = p0 + cb[0] == j.T; - for (int b = 0; b < 2; ++b) { - hptr(R_ESLOT)[b] = 2 * j.lane + b; + std::vector seqs; + std::vector ctx; + for (int b = 0; b < nb_; ++b) { + hptr(R_ESLOT)[b] = nb_ * j.lane + b; hptr(R_LROW)[b] = cu[b + 1] - 1; hptr(R_PREFIX)[b] = (int32_t)p0; + seqs.push_back(j.seq[b]); + ctx.push_back((int32_t)p0); } - reg_[R_ESLOT].used = reg_[R_LROW].used = reg_[R_PREFIX].used = 2 * 4; + stage_state(seqs, ctx); + reg_[R_ESLOT].used = reg_[R_LROW].used = reg_[R_PREFIX].used = nb_ * 4; hptr(R_LANE)[0] = j.lane; hptr(R_LAST)[0] = last ? 1 : 0; hptr(R_SEED)[0] = (uint32_t)(j.req->seed & 0xffffffffu); hptr(R_SEED)[1] = (uint32_t)(j.req->seed >> 32); reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = rows * 4; - reg_[R_CU].used = 3 * 4; - reg_[R_BT].used = 2 * pitch * 4; - reg_[R_USED].used = 2 * 4; + reg_[R_CU].used = (nb_ + 1) * 4; + reg_[R_BT].used = nb_ * pitch * 4; + reg_[R_USED].used = nb_ * 4; reg_[R_LANE].used = reg_[R_LAST].used = 4; reg_[R_SEED].used = 8; + /* The references: their clips, bounds and each row's frame (a whole prompt, so the rows are + * the prompt's own). */ + const AudioRequest& q = *j.req; + const int64_t n_ref = q.ref_cu.empty() ? 0 : (int64_t)q.ref_cu.size() - 1; + h_rcu_.clear(); + h_rfrm_.clear(); + if (n_ref > 0) { + std::memcpy(hptr(R_RAUD), q.ref_audio.data(), q.ref_audio.size() * 4); + std::memcpy(hptr(R_RCU), q.ref_cu.data(), q.ref_cu.size() * 4); + std::memcpy(hptr(R_RFRM), q.ref_frame.data() + p0, (size_t)cb[0] * 4); + reg_[R_RAUD].used = (int64_t)q.ref_audio.size() * 4; + reg_[R_RCU].used = (int64_t)q.ref_cu.size() * 4; + reg_[R_RFRM].used = cb[0] * 4; + h_rcu_ = q.ref_cu; + h_rfrm_.assign(q.ref_frame.begin() + p0, q.ref_frame.begin() + p0 + cb[0]); + } if (upload() < 0) return nullptr; - base_batches(rows, 2, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch); + base_batches(rows, nb_, (int32_t)cmax, (int32_t)(p0 + cmax), step, true, pitch); h_lane_.assign(1, j.lane); h_last_.assign(1, last ? 1 : 0); for (size_t r = 0; r < ranks_.size(); ++r) { @@ -577,6 +718,16 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { A.n_lane = 1; A.lane_h = h_lane_.data(); A.last_h = h_last_.data(); + if (n_ref > 0) { + const int ri = (int)r; + A.n_ref = n_ref; + A.ref_samples = (int64_t)q.ref_audio.size(); + A.ref_audio = dptr(ri, R_RAUD); + A.ref_cu = dptr(ri, R_RCU); + A.ref_cu_h = h_rcu_.data(); + A.ref_frame = dptr(ri, R_RFRM); + A.ref_frame_h = h_rfrm_.data(); + } } pass_.kind = RAD_GEN_PASS_PROMPT; pass_.jobs.assign(1, j.id); @@ -586,7 +737,7 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) { const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) { for (int g = 0; g < R_N; ++g) reg_[g].used = 0; - const int64_t L = (int64_t)js.size(), S = 2 * L; + const int64_t L = (int64_t)js.size(), S = nb_ * L; int32_t* tok = hptr(R_TOK); int32_t* pos = hptr(R_POS); int32_t* slot = hptr(R_SLOT); @@ -599,17 +750,19 @@ const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) int64_t pitch = 1; int32_t max_ctx = 0; for (const Job* j : js) - for (int b = 0; b < 2; ++b) + for (int b = 0; b < nb_; ++b) pitch = std::max(pitch, (int64_t)kv_->block_table(j->seq[b], kv_group_).size()); h_lane_.assign((size_t)L, 0); h_frame_.assign((size_t)L, 0); pass_.jobs.clear(); + std::vector seqs; + std::vector ctx; for (int64_t i = 0; i < L; ++i) { const Job& j = *js[(size_t)i]; - for (int b = 0; b < 2; ++b) { + for (int b = 0; b < nb_; ++b) { /* The frame's row follows the branch's prompt and its earlier frames. */ const int64_t p = (b ? j.Tn : j.T) + j.frame; - const int64_t e = 2 * i + b; + const int64_t e = nb_ * i + b; const std::vector& bt = kv_->block_table(j.seq[b], kv_group_); tok[e] = 0; pos[e] = (int32_t)p; @@ -618,9 +771,16 @@ const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) for (int64_t k = 0; k < pitch; ++k) btab[e * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1; used[e] = (int32_t)(p + 1); - hptr(R_ESLOT)[e] = 2 * j.lane + b; + /* The row before, whose hidden state the frame is sampled from: the prompt's last + * row for the first frame. */ + hptr(R_PSLOT)[e] = slot_of(bt, p - 1, block_size_); + hptr(R_PPOS)[e] = (int32_t)(p - 1); + hptr(R_PUSED)[e] = (int32_t)p; + hptr(R_ESLOT)[e] = nb_ * j.lane + b; hptr(R_LROW)[e] = (int32_t)e; max_ctx = std::max(max_ctx, (int32_t)(p + 1)); + seqs.push_back(j.seq[b]); + ctx.push_back((int32_t)p); } hptr(R_CFG)[i] = j.cfg; lane[i] = h_lane_[(size_t)i] = j.lane; @@ -630,6 +790,7 @@ const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) pass_.jobs.push_back(j.id); } cu[S] = (int32_t)S; + stage_state(seqs, ctx); reg_[R_TOK].used = reg_[R_POS].used = reg_[R_SLOT].used = S * 4; reg_[R_CU].used = (S + 1) * 4; reg_[R_BT].used = S * pitch * 4; @@ -637,6 +798,7 @@ const RadBatch* AudioDriver::build_frame(const std::vector& js, int step) reg_[R_LANE].used = reg_[R_FRAME].used = reg_[R_CFG].used = L * 4; reg_[R_SEED].used = 2 * L * 4; reg_[R_ESLOT].used = reg_[R_LROW].used = S * 4; + reg_[R_PSLOT].used = reg_[R_PPOS].used = reg_[R_PUSED].used = S * 4; if (upload() < 0) return nullptr; base_batches(S, S, 1, max_ctx, step, true, pitch); for (size_t r = 0; r < ranks_.size(); ++r) { diff --git a/core/gen/audio_driver.h b/core/gen/audio_driver.h index bb986103..561efb53 100644 --- a/core/gen/audio_driver.h +++ b/core/gen/audio_driver.h @@ -5,9 +5,15 @@ * `done()` folds its result back once every rank has run it. Requests arrive from HTTP threads * through `submit()` and leave through their AudioTicket. * - * A request holds a lane and two KV sequences, its conditional and unconditional branches, from - * admission to its last window; both are reserved for the whole piece at admission (prompt plus - * every frame the request may make), so a request in flight never waits for KV. + * A request holds a lane and two KV sequences, its conditional and unconditional branches (one, + * for a model of one branch: RadAudioGenDecl::branches), from admission to its last window; they + * are reserved for the whole piece at admission (prompt plus every frame the request may make), so + * a request in flight never waits for KV. + * + * The language model's KV is one paged full-attention group, beside which a hybrid model keeps + * the linear-attention state and convolution groups of its recurrent layers (RAD_KV_LINEAR, + * RAD_KV_CONV): one slot a sequence each, staged as their `state_index` rows, zeroed by the engine + * before the pass that first reads them. * * Pass priority, one pass at a time: * @@ -54,6 +60,9 @@ public: /* The longest sequence a branch holds: the whole prompt and every frame. The KV group is * sized from it. */ static int64_t max_seq_rows(const RadAudioGenDecl& d) { return d.max_prompt + d.max_frames + 1; } + /* State slots a state_index row holds at most: the state, and the scratch a kernel serving + * speculation asks for (RadKVGroupBatch::state_index_pitch), which a generator never runs. */ + static constexpr int64_t kMaxStateWidth = 8; /* ---------------------------------------------------------- HTTP threads */ /* Queue a request, refused at once with `why` when it can never run. */ @@ -115,7 +124,11 @@ private: struct Region { int64_t off = 0, bytes = 0, used = 0; }; enum { R_TOK, R_POS, R_CU, R_SLOT, R_BT, R_USED, R_LANE, R_LAST, R_FRAME, R_SEED, R_T, R_TN, R_CFG, R_PAIR, R_WLANE, R_FLAGS, R_WIDX, R_WF0, R_WNF, R_LCU, R_LSRC, - R_ESLOT, R_LROW, R_PREFIX, R_N }; + R_ESLOT, R_LROW, R_PREFIX, R_CTX, R_ACC, R_SBT, R_SIDX, R_PSLOT, R_PPOS, R_PUSED, + R_RAUD, R_RCU, R_RFRM, R_N }; + /* A hybrid model's stateful groups (linear-attention state, convolution history), each staged + * as one block-table word a sequence (its slot) and its state_index row. */ + struct StateGroup { int32_t g = 0; int64_t width = 1; }; template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } template T* dptr(int rank, int r) const { @@ -124,6 +137,9 @@ private: int upload(); void base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int32_t max_ctx, int step, bool kv, int64_t bt_pitch); + /* The stateful groups' rows for the entries of a PROMPT or FRAME pass, entry e being `seq[e]`, + * with each entry's context before the pass (ctx_lens). */ + void stage_state(const std::vector& seqs, const std::vector& ctx); int admit_locked(); void release_locked(Job& j); @@ -152,6 +168,8 @@ private: int64_t max_tok_ = 0, max_seqs_ = 0; int64_t block_size_ = 0, max_blocks_ = 0; int32_t kv_group_ = 0; + std::vector state_groups_; + int nb_ = 2; /* sequences a request: RadAudioGenDecl::branches */ bool neg_own_ = false; /* the unconditional prompt is the request's own */ std::vector ranks_; IKVManager* kv_ = nullptr; @@ -167,12 +185,12 @@ private: std::vector out_; /* one per rank */ std::vector aout_; - std::vector kout_; + std::vector kout_; /* [rank][1 + state groups] */ Pass pass_; bool frame_turn_ = true; /* FRAME goes first when both are due */ /* Host arrays a pass's plugin reads on the host (the _h fields), for the life of the pass. */ std::vector h_lane_, h_last_, h_frame_, h_wlane_, h_flags_, h_widx_, - h_wf0_, h_wnf_, h_lcu_; + h_wf0_, h_wnf_, h_lcu_, h_rcu_, h_rfrm_; mutable std::mutex mu_; std::deque> jobs_; /* arrival order */ diff --git a/core/gen/driver.cpp b/core/gen/driver.cpp index 20b5d6e6..5206421c 100644 --- a/core/gen/driver.cpp +++ b/core/gen/driver.cpp @@ -13,8 +13,6 @@ namespace { constexpr int64_t kAlign = 256; -int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; } - /* Upper bound on a reference picture's latent tokens: its area plus slack for rounding its sides * to the size multiple. */ int64_t ref_tokens_max(const RadGeneratorDecl& d) { @@ -97,7 +95,7 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) { for (int r = 0; r < n; ++r) { bytes[r][0] = off; bytes[r][1] = want[r][1]; - off = align_up(off + want[r][1]); + off = align_up(off + want[r][1], kAlign); } return off; } @@ -121,6 +119,12 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector& kv_ = kv; ranks_ = ranks; table_ = DiscreteTable{}; + if (decl_.cond_opts & ~(uint32_t)RAD_GEN_COND_REBALANCE) { + RAD_ERR("image generator: '%s' declares conditioning options 0x%x, and this engine knows " + "only RAD_GEN_COND_REBALANCE (0x%x)", decl_.name ? decl_.name : "", + (unsigned)decl_.cond_opts, (unsigned)RAD_GEN_COND_REBALANCE); + return RAD_E_UNSUPPORTED; + } if (discrete()) { std::string why; if (discrete_table(decl_, &table_, &why) < 0) { @@ -258,6 +262,8 @@ int Driver::submit(std::unique_ptr r, std::string* why) { !(decl_.samplers & (1u << r->sampler)) || r->scheduler < 0 || r->scheduler >= RAD_GEN_SCHED_COUNT)) return no("the sampler or scheduler is not one this model serves"); + if ((uint32_t)r->cond_opts & ~decl_.cond_opts) + return no("a conditioning option (rebalance) this model does not serve"); r->ticket->t_submit_ns = (int64_t)rad_mono_ns(); std::lock_guard lk(mu_); if (closed_) { @@ -530,6 +536,7 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste G.size_px = nullptr; G.entry_h = nullptr; G.tokens_h = nullptr; + G.cond_opts = 0; } } diff --git a/core/gen/driver.h b/core/gen/driver.h index 701fed38..443fddcc 100644 --- a/core/gen/driver.h +++ b/core/gen/driver.h @@ -125,7 +125,6 @@ private: R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE, R_AUX, R_SIGP, R_TSTEP, R_SAMP, R_STEPI, R_SIZE, R_N }; - int layout_regions(); template T* hptr(int r) const { return reinterpret_cast(host_ + reg_[r].off); } template T* dptr(int rank, int r) const { return reinterpret_cast((char*)dev_[(size_t)rank] + reg_[r].off); diff --git a/core/gen/video_driver.cpp b/core/gen/video_driver.cpp index db250124..1a60c5dc 100644 --- a/core/gen/video_driver.cpp +++ b/core/gen/video_driver.cpp @@ -195,7 +195,6 @@ constexpr int64_t kAlign = 256; * accept up to 4096. */ constexpr int64_t kSegCap = 64; -int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; } /* Region offsets and sizes, in the enum's order (video_driver.h), and the total; shared by the * allocation and the VRAM budget. `ep` and `pd` are the conditioning encoder's pass bound and @@ -239,7 +238,7 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd, for (int r = 0; r < n; ++r) { bytes[r][0] = off; bytes[r][1] = want[r]; - off = align_up(off + want[r]); + off = align_up(off + want[r], kAlign); } return off; } diff --git a/core/gen_config.cpp b/core/gen_config.cpp index aeebd68d..ee5a9216 100644 --- a/core/gen_config.cpp +++ b/core/gen_config.cpp @@ -22,6 +22,13 @@ void take(const char* what, const char* src, double v, double lo, double hi, boo src, what, v, lo_open ? "(" : "[", lo, hi); } +/* An integer field (a token count), same contract. */ +void take_i(const char* what, const char* src, int64_t v, int64_t lo, int64_t hi, int* dst) { + if (v >= lo && v <= hi) { *dst = (int)v; return; } + RAD_WARN("%s states %s %lld, which is outside [%lld, %lld]; ignoring it", + src, what, (long long)v, (long long)lo, (long long)hi); +} + } /* namespace */ SamplingParams GenSampling::onto(SamplingParams base) const { @@ -29,16 +36,36 @@ SamplingParams GenSampling::onto(SamplingParams base) const { if (top_p >= 0.0f) base.top_p = top_p; if (min_p >= 0.0f) base.min_p = min_p; if (top_k >= 0) base.top_k = top_k; + if (ngram_ban_n >= 0) base.ngram_ban_n = ngram_ban_n; + if (ngram_window >= 0) base.ngram_window = ngram_window; + if (!ngram_whitelist.empty()) base.ngram_whitelist = ngram_whitelist; return base; } +/* The one-line statement of a served sampling configuration. The wording is pinned by + * gen_config_test.cpp (gen_config_reads_the_ngram_ban) -- change it there in the same change. + * It spells the values out for a log reader; `onto` fills the fields from defaults. The two + * share values, not logic, and the duplication of the ban clause is a string, not a rule. */ std::string GenSampling::describe(const SamplingParams& sp) { - char buf[200]; + char buf[320]; std::snprintf(buf, sizeof buf, "temperature %.2f, top_k %d%s, top_p %.2f, min_p %.2f", (double)sp.temp, sp.top_k, sp.top_k == 0 ? " (the 1024 most likely tokens, the sampler's candidate width)" : "", (double)sp.top_p, (double)sp.min_p); - return buf; + std::string s(buf); + if (sp.ngram_ban_n > 0) { + char ban[96]; + if (sp.ngram_window > 0) + std::snprintf(ban, sizeof ban, ", ngram ban n %d over the last %d tokens", + sp.ngram_ban_n, sp.ngram_window); + else + std::snprintf(ban, sizeof ban, ", ngram ban n %d over the whole sequence", + sp.ngram_ban_n); + s += ban; + if (!sp.ngram_whitelist.empty()) + s += ", whitelist " + std::to_string(sp.ngram_whitelist.size()) + " ids"; + } + return s; } std::vector gen_sampling_sources(const GenSampling& stated, const std::string& src, @@ -88,6 +115,47 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli if (v >= -1) out->top_k = (int)(v < 0 ? 0 : v); else RAD_WARN("%s states top_k %lld, which is not a count; ignoring it", src, (long long)v); } + + /* The windowed no-repeat-n-gram ban. Its checkpoint name in transformers is + * no_repeat_ngram_size / no_repeat_ngram_window_size (Unlimited-OCR ships 35 over the last + * 128); this sampler's own names are taken too. The reference's negative window means the + * whole sequence, which this sampler spells 0. */ + it = j.find("no_repeat_ngram_size"); + if (it == j.end() || !it->is_number_integer()) it = j.find("ngram_ban_n"); + if (it != j.end() && it->is_number_integer()) + take_i("no_repeat_ngram_size", src, it->get(), 0, 256, &out->ngram_ban_n); + + it = j.find("no_repeat_ngram_window_size"); + if (it == j.end() || !it->is_number_integer()) it = j.find("ngram_window"); + if (it != j.end() && it->is_number_integer()) { + const int64_t v = it->get(); + take_i("no_repeat_ngram_window_size", src, v < 0 ? 0 : v, 0, 131072, &out->ngram_window); + } + + /* The ban's whitelist, a JSON array of token ids (the reference's whitelist_token_ids). + * Values are warned about and dropped, like every other field here: an id is a vocabulary + * coordinate, so a negative one is not a value at all. */ + it = j.find("no_repeat_ngram_whitelist"); + if (it != j.end() && !it->is_array()) { + /* The legacy key is only a problem when nothing rescues it: a config that states a bad + * reference name beside a good sampler-spelled one reads the good one, silently. */ + const auto own = j.find("ngram_whitelist"); + if (own == j.end() || !own->is_array()) + RAD_WARN("%s states a no_repeat_ngram_whitelist that is not an array; ignoring it", + src); + it = own; + } + if (it != j.end() && it->is_array()) { + for (const auto& v : *it) { + const int64_t id = v.is_number_integer() ? v.get() : -1; + if (id < 0 || id > INT32_MAX) { + RAD_WARN("%s states a no_repeat_ngram_whitelist entry outside [0, %d]; ignoring it", + src, INT32_MAX); + continue; + } + out->ngram_whitelist.push_back((int)id); + } + } return out->any(); } @@ -105,7 +173,9 @@ bool gen_sampling_from_kv(const std::function& get, Ge /* Rebuilt as JSON and passed to gen_sampling_parse, so container metadata and the original * file share one set of range checks and one reading of `do_sample`. */ nlohmann::json j = nlohmann::json::object(); - static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k" }; + static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k", + "no_repeat_ngram_size", "no_repeat_ngram_window_size", + "no_repeat_ngram_whitelist" }; for (const char* k : kFields) { const char* v = get(k); if (!v || !*v) continue; @@ -114,6 +184,17 @@ bool gen_sampling_from_kv(const std::function& get, Ge j[k] = (std::strcmp(v, "0") != 0); continue; } + if (std::strcmp(k, "no_repeat_ngram_whitelist") == 0) { + /* Not a number: the container's metadata is string-valued, and the whitelist is a + * JSON array spelled as JSON text. */ + try { + j[k] = nlohmann::json::parse(v); + } catch (const std::exception& e) { + RAD_WARN("the container states generation.%s as \"%s\", which is not a JSON " + "array of ids (%s); ignoring it", k, v, e.what()); + } + continue; + } char* end = nullptr; const double d = std::strtod(v, &end); if (end == v) { @@ -122,6 +203,7 @@ bool gen_sampling_from_kv(const std::function& get, Ge continue; } if (std::strcmp(k, "top_k") == 0) j[k] = (int64_t)d; + else if (std::strncmp(k, "no_repeat_ngram", 15) == 0) j[k] = (int64_t)d; else j[k] = d; } if (j.empty()) return false; diff --git a/core/gen_config.h b/core/gen_config.h index fa24225b..28c4aaa7 100644 --- a/core/gen_config.h +++ b/core/gen_config.h @@ -20,17 +20,30 @@ namespace rad { /* One config's sampler fields. -1 means "not stated", since 0 is a legal value of each (greedy - * temperature, top_k off, min_p off). */ + * temperature, top_k off, min_p off, n-gram ban off). */ struct GenSampling { float temp = -1.0f, top_p = -1.0f, min_p = -1.0f; int top_k = -1; + /* The windowed no-repeat-n-gram ban (transformers' no_repeat_ngram_size / + * no_repeat_ngram_window_size; Unlimited-OCR ships 35 over the last 128). `ngram_window` is + * normalized to 0, this sampler's "the whole sequence", when the config states it negative. */ + int ngram_ban_n = -1, ngram_window = -1; + /* The ban's whitelist: token ids the ban must never ban (the reference processor's + * `whitelist_token_ids`, removed from the banned set before the -inf writes). Transformers + * has no field for it; a container states it as `generation.no_repeat_ngram_whitelist`, a + * JSON array of ids. Empty means not stated. */ + std::vector ngram_whitelist; - bool any() const { return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0; } + bool any() const { + return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0 || + ngram_ban_n >= 0 || ngram_window >= 0 || !ngram_whitelist.empty(); + } /* Overlay onto `base` field by field; unstated fields keep base's, so sources stack. */ SamplingParams onto(SamplingParams base) const; - /* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00", for the startup log line. */ + /* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00, ngram ban n 35 over the last 128 + * tokens", for the startup log line (the last part only when a ban is on). */ static std::string describe(const SamplingParams& sp); }; diff --git a/core/hf_model.cpp b/core/hf_model.cpp index 0fadf0a5..66f85efa 100644 --- a/core/hf_model.cpp +++ b/core/hf_model.cpp @@ -39,11 +39,6 @@ bool repo_part(const std::string& p) { return true; } -bool ends_with(const std::string& s, const char* suf) { - const size_t n = std::strlen(suf); - return s.size() >= n && s.compare(s.size() - n, n, suf) == 0; -} - /* /../libexec/radiance/hfget.sh, which is where the install puts it and where the build * copies it. */ std::string hfget_path() { @@ -85,7 +80,7 @@ bool hf_repo_id(const std::string& s) { const std::string owner = s.substr(0, slash), name = s.substr(slash + 1); if (!repo_part(owner) || !repo_part(name)) return false; for (const char* suf : { ".rad", ".safetensors", ".gguf", ".json" }) - if (ends_with(name, suf)) return false; + if (name.ends_with(suf)) return false; return true; } @@ -102,7 +97,7 @@ std::string hf_served_path(const std::string& dir, std::string* why) { std::error_code ec; for (const fs::directory_entry& e : fs::directory_iterator(dir, ec)) { std::error_code fe; - if (e.is_regular_file(fe) && ends_with(e.path().filename().string(), ".rad")) + if (e.is_regular_file(fe) && e.path().filename().string().ends_with(".rad")) rad.push_back(e.path().filename().string()); } if (ec) { diff --git a/core/lora/adapter.cpp b/core/lora/adapter.cpp index 66dbeada..70dfb3e3 100644 --- a/core/lora/adapter.cpp +++ b/core/lora/adapter.cpp @@ -36,11 +36,6 @@ int fail(std::string* err, int code, const std::string& m) { return code; } -bool ends_with(const std::string& s, const char* p) { - const size_t n = std::strlen(p); - return s.size() >= n && s.compare(s.size() - n, n, p) == 0; -} - std::string shape_str(const std::vector& s) { std::string r = "["; for (size_t i = 0; i < s.size(); ++i) r += (i ? ", " : "") + std::to_string(s[i]); @@ -290,7 +285,7 @@ int AdapterFile::open(const std::string& path, std::string* err) { for (const StTensor& t : st_.tensors()) { const Suffix* hit = nullptr; for (const Suffix& s : kSuffix) - if (ends_with(t.name, s.s) && (!hit || std::strlen(s.s) > std::strlen(hit->s))) hit = &s; + if (t.name.ends_with(s.s) && (!hit || std::strlen(s.s) > std::strlen(hit->s))) hit = &s; if (!hit) { skipped_.push_back({ t.name, "not an adapter tensor" }); continue; @@ -610,7 +605,7 @@ std::regex pattern(const std::string& from, bool kohya) { } std::string module_of(const std::string& src) { - return ends_with(src, ".weight") ? src.substr(0, src.size() - 7) : std::string(); + return src.ends_with(".weight") ? src.substr(0, src.size() - 7) : std::string(); } } /* namespace */ diff --git a/core/lora/lora.cpp b/core/lora/lora.cpp index 640f9a32..708784ad 100644 --- a/core/lora/lora.cpp +++ b/core/lora/lora.cpp @@ -41,15 +41,6 @@ int fail(std::string* err, int code, const std::string& m) { return code; } -bool starts_with(const std::string& s, const char* p) { - const size_t n = std::strlen(p); - return s.size() >= n && s.compare(0, n, p) == 0; -} -bool ends_with(const std::string& s, const char* p) { - const size_t n = std::strlen(p); - return s.size() >= n && s.compare(s.size() - n, n, p) == 0; -} - std::vector split_dots(const std::string& s) { std::vector v; size_t at = 0; @@ -64,7 +55,7 @@ std::vector split_dots(const std::string& s) { /* `.weight` -> module and its leaf; "" when the source is not a `.weight` tensor. */ std::string module_of(const std::string& src, std::string* leaf) { - if (!ends_with(src, ".weight")) return ""; + if (!src.ends_with(".weight")) return ""; std::string m = src.substr(0, src.size() - 7); if (m.empty()) return ""; const size_t d = m.rfind('.'); @@ -100,7 +91,7 @@ const char* excluded_weight(const Program& prog, const WeightInfo& w) { return "a drafter / MTP layer (layer group at or above meta.n_layers)"; static const char* const kScopes[] = { "draft.", "vision.", "audio.", "mtp." }; for (const char* s : kScopes) - if (starts_with(w.name, s)) return "a non-trunk builder scope"; + if (w.name.starts_with(s)) return "a non-trunk builder scope"; return nullptr; } @@ -743,9 +734,9 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank, std::string explain_module(const Program& prog, const TargetSet& targets, const std::string& module) { const std::string want[3] = { module, - starts_with(module, "model.") && !starts_with(module, "model.language_model.") + module.starts_with("model.") && !module.starts_with("model.language_model.") ? "model.language_model." + module.substr(6) : "", - starts_with(module, "model.language_model.") ? "model." + module.substr(21) : "" }; + module.starts_with("model.language_model.") ? "model." + module.substr(21) : "" }; std::string first; bool any = false; for (const RadNameMap& m : prog.name_map) { @@ -939,7 +930,7 @@ int load_adapter(const std::string& dir, const std::vector& sites, int max if (!std::regex_match(k, m, key_re)) { std::string why = "is not a linear LoRA A/B tensor"; if (k.find("lora_embedding_") != std::string::npos) why = "is an embedding LoRA tensor"; - else if (ends_with(k, ".bias")) why = "is a trained bias"; + else if (k.ends_with(".bias")) why = "is a trained bias"; else if (k.find("modules_to_save") != std::string::npos) why = "is a modules_to_save copy"; else if (k.find("lora_magnitude_vector") != std::string::npos) why = "is a DoRA magnitude"; return fail(err, RAD_E_UNSUPPORTED, st_path + ": tensor " + k + " " + why + @@ -1034,9 +1025,9 @@ int pack_modules(const std::vector& sites, int max_rank, for (auto& kv : mods) { const AdModule& am = kv.second; std::vector cand{ am.name }; - if (starts_with(am.name, "model.") && !starts_with(am.name, "model.language_model.")) + if (am.name.starts_with("model.") && !am.name.starts_with("model.language_model.")) cand.push_back("model.language_model." + am.name.substr(6)); - if (starts_with(am.name, "model.language_model.")) + if (am.name.starts_with("model.language_model.")) cand.push_back("model." + am.name.substr(21)); std::vector hit; for (const std::string& c : cand) if (where.count(c)) hit.push_back(c); diff --git a/core/mem/kv.cpp b/core/mem/kv.cpp index d6193736..821dea16 100644 --- a/core/mem/kv.cpp +++ b/core/mem/kv.cpp @@ -2,6 +2,7 @@ #include "mem/kv.h" #include +#include #include namespace rad { @@ -76,6 +77,7 @@ static const char* kv_kind_name(int k) { case RAD_KV_WINDOW: return "window"; case RAD_KV_LINEAR: return "linear"; case RAD_KV_CONV: return "conv"; + case RAD_KV_RING: return "ring"; default: return "?"; } } @@ -126,7 +128,10 @@ int KVManager::plan_groups(const std::vector& groups, const Config& KVGroupPlan p; p.index = (int32_t)i; p.name = g.name.empty() ? fmt("kv%zu", i) : g.name; - p.kind = g.decl.kind; + /* R-SWA: RAD_KV_RING is a window group whose floor is per sequence (declare_runtime_window + * / SeqWindow), so it plans as a RAD_KV_WINDOW group with `runtime_win` set below. No + * other plan-path code has to know the kind. */ + p.kind = g.decl.kind == RAD_KV_RING ? RAD_KV_WINDOW : g.decl.kind; p.n_layers = (int64_t)g.layers.size(); if (p.n_layers <= 0) { @@ -161,7 +166,9 @@ int KVManager::plan_groups(const std::vector& groups, const Config& } if (p.kind == RAD_KV_WINDOW) { if (g.decl.window <= 0) { - RAD_ERR("KV group '%s': RAD_KV_WINDOW with window 0", p.name.c_str()); + RAD_ERR("KV group '%s': %s with window 0", p.name.c_str(), + g.decl.kind == RAD_KV_RING ? "RAD_KV_RING (the ring's W)" + : "RAD_KV_WINDOW"); return RAD_E_INVAL; } /* +1 because a window that is not block-aligned straddles one extra block. */ @@ -233,6 +240,28 @@ int KVManager::plan_groups(const std::vector& groups, const Config& } bundling_ = compare_bundling(bundles); + /* R-SWA: a declared runtime window turns the group's plan over to per-sequence windows (see + * declare_runtime_window). Applied after every declaration above, so a fixed-window group's + * plan is exactly what it was. */ + for (auto& p : plans_) apply_runtime_window(p); + /* A RAD_KV_RING group carries a runtime window by its kind, whether or not the caller had a + * manager to declare it on first (the engine's sizing probes declare it, but plan_groups must + * not depend on that). `window` is the ring's W. */ + for (size_t i = 1; i < plans_.size(); ++i) { + KVGroupPlan& p = plans_[i]; + if (groups[i].decl.kind != RAD_KV_RING || p.runtime_win) continue; + p.runtime_win = true; + p.runtime_tokens = groups[i].decl.window; + p.win_snap = false; + } + for (const auto& [g, w] : runtime_decl_) { + if (g < 0 || g >= (int32_t)plans_.size() || !plans_[(size_t)g].runtime_win) { + RAD_ERR("declare_runtime_window(%d): the group is not a RAD_KV_WINDOW or RAD_KV_RING " + "group in this program (a runtime window needs a windowed group)", (int)g); + return RAD_E_INVAL; + } + } + /* ---- fixed costs first: they are not per-token ---- */ checkpoint_bytes_ = 0; window_ck_bytes_ = 0; @@ -243,7 +272,7 @@ int KVManager::plan_groups(const std::vector& groups, const Config& for (size_t i = 1; i < plans_.size(); ++i) { KVGroupPlan& p = plans_[i]; p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 && - !groups[i].drafter; + !p.runtime_win && !groups[i].drafter; if (p.win_snap && !p.zero && p.n_layers > 0) window_ck_bytes_ += p.window_blocks * p.bytes_per_block; } @@ -257,26 +286,107 @@ int KVManager::plan_groups(const std::vector& groups, const Config& if (p.stateful()) fixed += align_up(p.bytes_per_state * p.n_states, RAD_ALIGN_UNIT); /* And one unit per paged group, whose size need not be a multiple of the alignment. */ for (const auto& p : plans_) if (p.paged()) fixed += RAD_ALIGN_UNIT; + /* A runtime window's ring is per sequence and on top of the context the split sizes: one + * ring a sequence, carved as a fixed cost. Its reference is the context itself, which the + * split already covers (the group is not capped at window_blocks). */ + for (const auto& p : plans_) + if (p.runtime_win && !p.zero) + fixed += align_up(max_seqs_ * p.ring_blocks_max() * p.bytes_per_block, RAD_ALIGN_UNIT); fixed_ = fixed; ckpts_ = budget_ckpts; return RAD_OK; } -/* Windowed groups are capped at window_pool_cap, as in carve(). */ +/* Windowed groups are capped at window_pool_cap, as in carve(). A runtime-window group is not: + * its blocks are the reference (one context a sequence, as a FULL group) plus the ring its fixed + * costs already carry. */ int64_t KVManager::ceiling(int64_t ctx) const { if (ctx <= 0) return 0; int64_t need = fixed_; for (const auto& p : plans_) { if (!p.paged() || p.block_size <= 0) continue; int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size); - if (p.kind == RAD_KV_WINDOW && p.window_blocks > 0) + if (p.kind == RAD_KV_WINDOW && !p.runtime_win && p.window_blocks > 0) blocks = std::min(blocks, window_pool_cap(p)); need += blocks * p.bytes_per_block; } return need; } +/* Moves a WINDOW group's plan to per-sequence runtime windows (declare_runtime_window). Returns + * false for any other group, so plan_groups() can apply it to every plan unconditionally. */ +bool KVManager::apply_runtime_window(KVGroupPlan& p) const { + auto it = runtime_decl_.find(p.index); + if (it == runtime_decl_.end() || p.kind != RAD_KV_WINDOW || p.runtime_win) return false; + p.runtime_win = true; + p.runtime_tokens = it->second; + /* The window a sequence may inherit (a fixed-window cap) is no longer the bound, and the + * declare-time window is not the sequence's own, so nothing here is snapshot-able. */ + p.win_snap = false; + return true; +} + +int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) { + if (g <= 0 || window_tokens <= 0) { + RAD_ERR("declare_runtime_window: group %d with a window of %lld (a runtime window needs a " + "real group and a positive W)", (int)g, (long long)window_tokens); + return RAD_E_INVAL; + } + const KVGroupPlan* p = plan(g); + if (p && p->kind != RAD_KV_WINDOW) { + RAD_ERR("group '%s' is not RAD_KV_WINDOW or RAD_KV_RING, so it cannot carry a runtime " + "window", p->name.c_str()); + return RAD_E_INVAL; + } + if (p && p->runtime_win && p->runtime_tokens != window_tokens) { + /* A RAD_KV_RING group's W is its declaration's `window`, and one already planned for + * another W has its ring in the fixed costs. */ + RAD_ERR("declare_runtime_window(%d): group '%s' already carries a runtime window of %lld " + "tokens, and its ring is sized for that", (int)g, p->name.c_str(), + (long long)p->runtime_tokens); + return RAD_E_INVAL; + } + if (configured_) { + RAD_ERR("declare_runtime_window(%d) after the carve: the group's blocks and fixed costs " + "are already sized for a different window", (int)g); + return RAD_E_STATE; + } + runtime_decl_[g] = window_tokens; + /* A plan built before the declaration (the engine's probes, or plan_groups() then declare) + * is updated in place; the next plan_groups() picks the declaration up on its own. + * + * A plan set shorter than `g` returns RAD_E_INVAL below with this store kept: deliberate. + * The declaration is the caller's standing intent (it survives forget(), whose vectors are + * emptied together and are not this map), and the short plan set is the probe ordering the + * declaration exists for -- the next plan_groups() applies it to a plan that has the group. */ + if (!plans_.empty()) { + if (g >= (int32_t)plans_.size()) return RAD_E_INVAL; + KVGroupPlan& q = plans_[(size_t)g]; + /* Whether the plan counted this group's window snapshot section (plan_groups' rule). */ + const bool counted = q.win_snap && !q.zero && q.n_layers > 0; + if (!apply_runtime_window(q)) return RAD_OK; /* already applied */ + /* The cost this declaration adds, against the plan as published: the ring is one a + * sequence, and the group gives up its window snapshot section. */ + fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT); + if (counted) { + const int64_t was = q.window_blocks * q.bytes_per_block; + /* The plan counted this group's snapshot section, so both totals carry `was`. + * Saturating hides an accounting bug; surface it in debug builds. */ + assert(window_ck_bytes_ >= was && checkpoint_bytes_ >= was && + "runtime window: snapshot byte totals below the section being removed"); + window_ck_bytes_ = window_ck_bytes_ > was ? window_ck_bytes_ - was : 0; + checkpoint_bytes_ = checkpoint_bytes_ > was ? checkpoint_bytes_ - was : 0; + } + } + return RAD_OK; +} + +int64_t KVManager::runtime_window_tokens(int32_t g) const { + const KVGroupPlan* p = plan(g); + return p && p->runtime_win ? p->runtime_tokens : 0; +} + /* The vectors parallel to plans_ are filled at different points of the carve, so a partial carve * would leave plans_ passing bounds checks (reserve_block checks plans_, then reads free_usable_) * over empty block state. On failure forget() empties both, so every entry point refuses @@ -329,11 +439,11 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector* block if (tokens_cap_ > 0 && tokens > tokens_cap_) tokens = tokens_cap_; /* A windowed group cannot address past its pool cap; cap it and give the bytes back to - * the others. */ + * the others. A runtime-window group's cap is the context plus its ring (a fixed cost). */ int32_t capped = -1; for (int32_t i : open) { const auto& p = plans_[i]; - if (p.kind != RAD_KV_WINDOW) continue; + if (p.kind != RAD_KV_WINDOW || p.runtime_win) continue; if (tokens / p.block_size > window_pool_cap(p)) { capped = i; break; } } if (capped < 0) break; @@ -370,7 +480,8 @@ int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const { int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const { if (tokens == kUnboundedTokens) return 0; const int64_t b = tokens / p.block_size; - if (p.kind == RAD_KV_WINDOW && b > window_pool_cap(p)) return window_pool_cap(p); + if (p.kind == RAD_KV_WINDOW && !p.runtime_win && b > window_pool_cap(p)) + return window_pool_cap(p); return b; } @@ -509,20 +620,31 @@ int KVManager::carve_into(Pool& kv_pool) { configured_ = true; report_ = bundling_.report(); + /* A runtime-window group reads as "ring": its window is the sequence's own, not the plan's. */ + auto kind_of = [](const KVGroupPlan& p) { + return p.runtime_win ? "ring" : kv_kind_name(p.kind); + }; for (const auto& p : plans_) { if (p.paged()) report_ += fmt(" %-14s %-6s %3lld layers block %4lld tok page %8s " "%7lld blocks = %9s (%lld tokens)\n", - p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers, + p.name.c_str(), kind_of(p), (long long)p.n_layers, (long long)p.block_size, humanb(p.bytes_per_block).c_str(), (long long)p.n_blocks, humanb(p.pool_bytes).c_str(), (long long)(p.n_blocks * p.block_size)); else report_ += fmt(" %-14s %-6s %3lld layers state %8s %7lld slots = %9s\n", - p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers, + p.name.c_str(), kind_of(p), (long long)p.n_layers, humanb(p.bytes_per_state).c_str(), (long long)p.n_states, humanb(p.pool_bytes).c_str()); } + for (const auto& p : plans_) { + if (!p.runtime_win) continue; + report_ += fmt(" %-14s runtime window W=%lld: a sequence keeps its reference and a ring " + "of at most %lld block(s), rewritten in place\n", + p.name.c_str(), (long long)p.runtime_tokens, + (long long)p.ring_blocks_max()); + } /* The pool's address range, so a GPU fault address can be placed in the carve. */ report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld\n", pool_base_, humanb(pool_ ? pool_->bytes() : 0).c_str(), @@ -805,7 +927,17 @@ int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const { const KVGroupPlan* p = plan(g); if (!p || !p->paged() || n_tokens <= 0) return 0; int64_t n = ceil_div(n_tokens, p->block_size); - if (p->kind == RAD_KV_WINDOW) n = std::min(n, window_seq_cap(*p)); + if (p->kind == RAD_KV_WINDOW) { + if (p->runtime_win) { + /* The reference's blocks up to n, plus one ring. Without a sequence the floor is + * unknown, so the whole context is the bound on the reference. */ + const int64_t ring = p->ring_blocks_max(); + const int64_t ctx = max_ctx_ > 0 ? max_ctx_ : n_tokens; + n = std::min(n, ceil_div(ctx, p->block_size)) + ring; + } else { + n = std::min(n, window_seq_cap(*p)); + } + } return n; } @@ -836,6 +968,7 @@ int KVManager::add_sequence(uint64_t id) { s.id = id; s.blocks.resize(plans_.size()); s.first_block_pos.assign(plans_.size(), 0); + s.win.resize(plans_.size()); s.state.assign(plans_.size(), -1); s.dirty_from.assign(plans_.size(), 0); seqs_.emplace(id, std::move(s)); @@ -853,6 +986,9 @@ int KVManager::preempt(uint64_t id) { for (int32_t b : s->blocks[g]) drop_block((int32_t)g, b); s->blocks[g].clear(); s->first_block_pos[g] = 0; + /* The runtime window goes with the blocks: re-admission re-arms it at the prompt end + * (the scheduler's admission path calls set_window again before the KV grows). */ + s->win[g] = SeqWindow{}; s->dirty_from[g] = 0; /* The recurrent state goes too (see preempt in kv.h, spec §7.1). */ if (s->state[g] >= 0) { drop_state((int32_t)g, s->state[g]); s->state[g] = -1; } @@ -870,6 +1006,12 @@ int KVManager::rollback(uint64_t id, int64_t n_tokens) { if (n_tokens < 0) return RAD_E_INVAL; /* Nothing to free; RAD_OK so "every draft accepted" needs no special path in the caller. */ if (n_tokens >= s->n_tokens) return RAD_OK; + /* A runtime-windowed sequence unwinds nothing: the ring's slots are reused once it is full, + * so the slots a rejected verify wrote may already hold newer keys. The scheduler gates + * drafting on has_runtime_window, so this refuses rather than corrupts, and only a caller + * that drafts beside a runtime window can reach it. */ + for (const SeqWindow& w : s->win) + if (w.set) return RAD_E_UNSUPPORTED; for (size_t g = 0; g < plans_.size(); ++g) { const auto& p = plans_[g]; @@ -899,6 +1041,80 @@ int64_t KVManager::first_block_pos(uint64_t id, int32_t g) const { return s->first_block_pos[(size_t)g]; } +/* ------------------------------------------------------------------ the runtime window */ + +int KVManager::set_window(uint64_t id, int64_t visible_lo, int64_t window_tokens) { + if (!configured_) return RAD_E_STATE; + Seq* s = find(id); + if (!s) return RAD_E_NOTFOUND; + if (visible_lo < 0 || window_tokens <= 0) return RAD_E_INVAL; + /* The reference is written linearly, so the floor cannot be behind KV the sequence already + * holds: rebasing would have to move blocks the ring has not been shaped for. */ + if (visible_lo < s->n_tokens) { + RAD_ERR("sequence %llu: runtime window floor %lld is behind its %lld held tokens", + (unsigned long long)id, (long long)visible_lo, (long long)s->n_tokens); + return RAD_E_STATE; + } + bool any = false; + /* With a declared runtime window in the program, arm exactly the declared groups: a plain + * fixed-window group beside them is carved for its fixed window, and arming it silently + * converts it. With none declared this is the caller-sizes-the-pool path kv.h states, and + * every windowed group arms as before. */ + bool declared = false; + for (const KVGroupPlan& p : plans_) + if (p.kind == RAD_KV_WINDOW && p.runtime_win) declared = true; + for (size_t g = 0; g < plans_.size(); ++g) { + const KVGroupPlan& p = plans_[g]; + if (p.kind != RAD_KV_WINDOW) continue; + if (declared && !p.runtime_win) { + RAD_ERR("sequence %llu: set_window meets fixed-window group '%s' beside a declared " + "runtime window; its pool is carved for its fixed window and the mix is not " + "supported", (unsigned long long)id, p.name.c_str()); + return RAD_E_UNSUPPORTED; + } + SeqWindow w; + w.set = true; + w.window = window_tokens; + w.visible_lo = visible_lo; + /* Whole blocks: the ring starts at the first boundary at or after the floor, and the + * tokens in [visible_lo, ring_pos) stay in the reference's last block (SeqWindow). The + * ring itself must span all of W: the frozen tokens are the oldest of the tail, so a + * smaller ring would lose the last W - span positions. */ + w.ring_pos = ceil_div(visible_lo, p.block_size) * p.block_size; + w.ring_blocks = ceil_div(window_tokens, p.block_size); + if (w.ring_blocks < 1) w.ring_blocks = 1; /* the ring always has somewhere to write */ + /* What the sequence can hold: the reference's blocks, then the whole ring. */ + const int64_t need = w.ring_pos / p.block_size + w.ring_blocks; + if (p.n_blocks > 0 && need > p.n_blocks) return RAD_E_FULL; + s->win[g] = w; + any = true; + } + if (!any) return RAD_E_UNSUPPORTED; + return RAD_OK; +} + +bool KVManager::runtime_window(uint64_t id, int32_t g, SeqWindow* out) const { + const Seq* s = find(id); + if (!s || g < 0 || g >= (int32_t)s->win.size() || !s->win[(size_t)g].set) return false; + if (out) *out = s->win[(size_t)g]; + return true; +} + +bool KVManager::has_runtime_window(uint64_t id) const { + const Seq* s = find(id); + if (!s) return false; + for (const SeqWindow& w : s->win) if (w.set) return true; + return false; +} + +/* What ensure() must have in the table for `n_tokens`: the reference grows linearly until the + * floor, then the ring fills up to its whole span and never grows again. */ +int64_t KVManager::window_table_len(const KVGroupPlan& p, const SeqWindow& w, int64_t n_tokens) { + const int64_t ref = w.ring_pos / p.block_size; + if (n_tokens <= w.ring_pos) return ceil_div(n_tokens, p.block_size); + return ref + std::min(w.ring_blocks, ceil_div(n_tokens - w.ring_pos, p.block_size)); +} + int64_t KVManager::seq_tokens(uint64_t id) const { const Seq* s = find(id); return s ? s->n_tokens : 0; } int64_t KVManager::take_table_changes(uint64_t id, int32_t g) const { @@ -1023,11 +1239,15 @@ int64_t KVManager::step_blocks(const KVGroupPlan& p) const { /* Slides from the step's first query, not its last. The query at keep_from reads keys down to * keep_from - window + 1, which lies in block keep_from / block - (window_blocks - 1) or later * (window_blocks - 1 >= window / block). A target from the step's end is the same for a decode - * step but drops keys the earlier rows of a prefill chunk still need. */ + * step but drops keys the earlier rows of a prefill chunk still need. + * + * A sequence with a runtime window is left alone. Its visible set is anchored at 0, so nothing in + * the table is below a sliding floor to recycle; the ring's blocks are rewritten in place and + * the table never moves (SeqWindow). */ void KVManager::recycle_window(Seq* s, int64_t keep_from) { for (size_t g = 0; g < plans_.size(); ++g) { const auto& p = plans_[g]; - if (p.kind != RAD_KV_WINDOW) continue; + if (p.kind != RAD_KV_WINDOW || s->win[g].set) continue; int64_t first = s->first_block_pos[g] / p.block_size; int64_t target = std::max(first, keep_from / p.block_size - (p.window_blocks - 1)); @@ -1066,7 +1286,9 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) { const auto& p = plans_[g]; if (p.paged()) { int64_t first = s->first_block_pos[g] / p.block_size; - int64_t want = ceil_div(n_tokens, p.block_size) - first; + int64_t want = s->win[g].set + ? window_table_len(p, s->win[g], n_tokens) - first + : ceil_div(n_tokens, p.block_size) - first; need[g] = want - (int64_t)s->blocks[g].size(); if (need[g] < 0) need[g] = 0; /* Copy-on-write: the partial block is the only one a write reaches; if it is shared, @@ -1102,7 +1324,9 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) { } } } - int64_t want = ceil_div(n_tokens, p.block_size) - first; + int64_t want = s->win[g].set + ? window_table_len(p, s->win[g], n_tokens) - first + : ceil_div(n_tokens, p.block_size) - first; if ((int64_t)s->blocks[g].size() < want) s->dirty_from[g] = std::min(s->dirty_from[g], (int64_t)s->blocks[g].size()); @@ -1126,6 +1350,10 @@ int KVManager::adopt(uint64_t id, int32_t g, const std::vector& blocks, if (!s) return RAD_E_NOTFOUND; const KVGroupPlan* p = plan(g); if (!p || !p->paged()) return RAD_E_INVAL; + /* A runtime window's table is its own reference plus ring, laid out against a floor no cache + * entry knows (set_window), so blocks adopted from a prefix hit would sit at the wrong + * positions. Prefix publish is skipped for such a sequence; this is the backstop. */ + if (s->win[(size_t)g].set) return RAD_E_STATE; /* Whole blocks only (see adopt in kv.h). */ if (n_tokens % p->block_size != 0) return RAD_E_INVAL; if ((int64_t)blocks.size() != n_tokens / p->block_size) return RAD_E_INVAL; @@ -1146,6 +1374,14 @@ int KVManager::fork(uint64_t parent, uint64_t child) { Seq* pa = find(parent); if (!pa) return RAD_E_NOTFOUND; if (seqs_.count(child)) return RAD_E_DUPLICATE; + /* The window is runtime data: a child that shared the table without it would read the ring + * as if it were a reference. A forking model (speculative decoding) does not carry one. */ + for (const SeqWindow& w : pa->win) + if (w.set) { + RAD_ERR("sequence %llu: fork refused, it carries a runtime window", + (unsigned long long)parent); + return RAD_E_UNSUPPORTED; + } /* Pass 1: the child needs its own state slot in every stateful group before anything is * shared (see fork in kv.h, spec §7.3). */ @@ -1160,6 +1396,7 @@ int KVManager::fork(uint64_t parent, uint64_t child) { if (plans_[g].paged()) { ch->blocks[g] = pa->blocks[g]; ch->first_block_pos[g] = pa->first_block_pos[g]; + ch->win[g] = pa->win[g]; for (int32_t b : ch->blocks[g]) add_ref(g, b); } else { grab_state((int32_t)g, &ch->state[g]); @@ -1189,7 +1426,10 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens, if (p.paged()) { int64_t first = s->first_block_pos[g] / p.block_size; int64_t want = ceil_div(n_tokens, p.block_size) - first; - if (p.kind == RAD_KV_WINDOW) want = std::min(want, window_seq_cap(p)); + if (p.kind == RAD_KV_WINDOW) { + if (s->win[g].set) want = window_table_len(p, s->win[g], n_tokens) - first; + else want = std::min(want, window_seq_cap(p)); + } int64_t extra = want - (int64_t)s->blocks[g].size() + 1; /* +1 for a COW copy */ if (extra > available_blocks((int32_t)g)) return false; } else if (p.stateful() && s->state[g] < 0 && free_states_[g].empty()) return false; @@ -1369,6 +1609,9 @@ bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector* out) out->clear(); const Seq* s = find(id); if (!s || pos <= 0) return false; + /* A runtime window is excluded from window snapshots (set_window): the window length is + * runtime data and the table is a reference plus a ring, not [lo, pos). */ + for (const SeqWindow& w : s->win) if (w.set) return false; for (size_t g = 0; g < plans_.size(); ++g) { const KVGroupPlan& p = plans_[g]; if (!p.win_snap) continue; @@ -1390,6 +1633,8 @@ bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector* out) int KVManager::seed_window(uint64_t id, int64_t pos) { Seq* s = find(id); if (!s) return RAD_E_NOTFOUND; + /* A sequence with a runtime window is never resumed from a window snapshot (set_window). */ + for (const SeqWindow& w : s->win) if (w.set) return RAD_E_STATE; /* Check every group before taking anything, as ensure() does. */ for (size_t g = 0; g < plans_.size(); ++g) { const KVGroupPlan& p = plans_[g]; diff --git a/core/mem/kv.h b/core/mem/kv.h index 046edb8b..f2240e1d 100644 --- a/core/mem/kv.h +++ b/core/mem/kv.h @@ -11,6 +11,10 @@ * RAD_KV_LINEAR per-sequence, fixed size: the GDN recurrent state * RAD_KV_CONV per-sequence, fixed size: a rolling window of conv_width-1 + n_spec entries * + * A RAD_KV_RING group is a RAD_KV_WINDOW whose floor is per sequence and set at runtime (R-SWA, + * see SeqWindow); it is planned as a WINDOW group with `runtime_win` set, so no kind of its own + * reaches the plan. + * * The two stateful kinds are also allocated, mapped and freed here, so one allocator decides what * a sequence owns. With two, a freed sequence's state slot could still be handed to the next * request by the other. @@ -50,6 +54,45 @@ struct BundleComparison { }; BundleComparison compare_bundling(const std::vector& bundles); +/* ------------------------------------------------------------------ the runtime window */ +/* A sequence's per-sequence window on a RAD_KV_WINDOW group, set at runtime (R-SWA, the + * "reference + ring" attention of Unlimited-OCR: a full causal prefill over the prompt and image + * tokens, then a ring of W decode slots right after it, rewritten in place forever). + * + * A fixed sliding window (`KVGroupPlan::window_blocks`, gemma4's) keeps the last W tokens: the + * table starts where the window begins and blocks leave from its front. A runtime window instead + * retains the whole prefill as the reference and appends into a ring after it: + * + * visible = [0, visible_lo) U [visible_lo, visible_lo + W) + * + * `visible_lo` is the sequence's own prefill length (image tokens included), so the visible set is + * per sequence. The reference is never recycled and first_block_pos stays 0 (the table still + * starts at position 0); only the ring's slot mapping recycles, so RoPE positions keep increasing + * with the token's own position and a decode query sees the whole reference plus the ring. + * + * Blocks are whole, so the ring can start only on a block boundary: it starts at + * `ring_pos = ceil(visible_lo / block) * block` with `ceil(W / block)` blocks, and the tokens in + * [visible_lo, ring_pos) stay in the reference's last block (they are the oldest of the tail and + * are never rewritten). The visible tail is therefore W .. W + block - 1 tokens when W is a block + * multiple -- with block_size 128 = W the 128-256 token granularity of the plan, exact even when + * the floor is not aligned -- and up to one block more otherwise, always a superset of the + * reference implementation's last W. The ring's blocks hold the newest positions in place (no + * block is allocated past them, so the sequence's bytes are flat once the floor is set): + * + * block index = ring_pos / block + ((pos - ring_pos) / block) % ring_blocks + * + * A sequence with a runtime window is excluded from prefix-cache reuse, window snapshots, forking + * and speculative rollback: all three assume the declare-time window, and the runtime length is + * not in any cache key (see KVManager::set_window). */ +struct SeqWindow { + bool set = false; + int64_t window = 0; /* W as set */ + int64_t visible_lo = 0; /* the retained reference ends here */ + int64_t ring_pos = 0; /* block-aligned first ring token position */ + int64_t ring_blocks = 0; /* whole blocks the ring holds */ + int64_t ring_span(int64_t block) const { return ring_blocks * block; } +}; + /* ------------------------------------------------------------------ per-group plan */ struct KVGroupPlan { int32_t index = -1; /* position in Program::kv_groups */ @@ -62,6 +105,18 @@ struct KVGroupPlan { int64_t bytes_per_state = 0; /* LINEAR/CONV: per sequence, every layer */ int64_t conv_slots = 0; /* CONV: conv_width - 1 + n_spec */ int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */ + /* WINDOW: sequences may be given a runtime window (declare_runtime_window). Such a group is + * sized for the whole context plus one ring per sequence instead of being capped at + * window_blocks, its window is not snapshotted, and a sequence armed with one is bounded by + * its own reference + ring rather than by window_blocks. */ + bool runtime_win = false; + int64_t runtime_tokens = 0; /* the W set_window arms a sequence with */ + /* The most ring blocks one sequence needs: ceil(W / block), the reference's fraction d of + * the ring's first block being frozen in it (see SeqWindow). */ + int64_t ring_blocks_max() const { + return runtime_tokens > 0 && block_size > 0 + ? (runtime_tokens + block_size - 1) / block_size : 0; + } /* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Set only for a * trunk group of a model with no linear state. A drafter's window is recomputed by draft * refill, and a model with linear state re-prefills a hit on a windowed trunk, so neither @@ -206,9 +261,49 @@ public: /* Recycles a committed chunk's window blocks. ensure() keeps a chunk's blocks beside the * window and only the next ensure() recycles them, so a prefill waiting for its next chunk * would hold a whole chunk of blocks; several such prefills can exhaust the pool. The - * scheduler calls this when it advances n_computed, passing the new n_computed. */ + * scheduler calls this when it advances n_computed, passing the new n_computed. + * + * A sequence with a runtime window retains its reference and rewrites its ring in place, so + * nothing below the floor may be recycled and this is a no-op for it. */ void trim_window(uint64_t seq, int64_t keep_from); + /* ---------------- the runtime window (R-SWA; see SeqWindow) ---------------- */ + /* Mark a WINDOW group as carrying per-sequence runtime windows of `window_tokens`. Call before + * plan_groups()/configure(): it changes the plan (the group is sized for the whole context + * plus one ring a sequence, its window is not snapshotted, and the ring joins the fixed + * costs), so a group declared after the plan is refused. A fixed-window group is untouched. + * + * A group that is not marked still accepts set_window() -- the caller then sizes the pool + * itself, e.g. by declaring the group's window as the whole context -- and each sequence's + * capacity is checked at set_window()/ensure() against the blocks actually carved. Once any + * group is marked, set_window() arms only marked groups: a plain fixed-window group beside a + * declared runtime window is refused, not silently converted (its pool is carved for the + * fixed window). */ + int declare_runtime_window(int32_t group, int64_t window_tokens); + + /* Give a sequence a runtime window with `visible_lo` (its prefill length, image tokens + * included) as the retained reference's end and a ring of `window_tokens` after it. Every + * paged WINDOW group of the sequence gets the same floor. Call it before the sequence's KV + * grows past `visible_lo` -- at admission, where the scheduler knows the prompt length -- so + * the reference is written linearly and no checkpoint can be reserved for it (a snapshot + * would describe a window the sequence no longer has). + * + * RAD_E_UNSUPPORTED no windowed group, or the fixed/runtime-window mix above; + * RAD_E_INVAL a negative floor or a window of 0; + * RAD_E_STATE the sequence already holds tokens past the floor; + * RAD_E_FULL the reference plus the ring exceeds what this group carved. */ + int set_window(uint64_t seq, int64_t visible_lo, int64_t window_tokens); + + /* The sequence's window in `group`, or false when it has none (a fixed-window group keeps + * KVGroupPlan::window_blocks and first_block_pos). The step batch maps a ring position with + * SeqWindow's rule; every other position maps as (pos - first_block_pos) / block_size. */ + bool runtime_window(uint64_t seq, int32_t group, SeqWindow* out) const; + /* Whether any group has a runtime window set for the sequence. Prefix publish, checkpoint + * reservation and snapshots are skipped for it (see set_window). */ + bool has_runtime_window(uint64_t seq) const; + /* The W declare_runtime_window gave the group, 0 if it carries no runtime windows. */ + int64_t runtime_window_tokens(int32_t group) const; + /* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's * block size: a partial block is never shared, because the next token written into it would * corrupt the cache entry. Bumps each block's refcount. */ @@ -363,7 +458,11 @@ public: /* The absolute token position block_table(seq, group)[0] covers: zero for a FULL group, the * recycled prefix for a WINDOW group. The slot mapping is (pos - first_block_pos) / * block_size; without the offset a sliding-window sequence writes to the wrong slot once it - * passes its window. */ + * passes its window. + * + * A sequence with a runtime window (set_window) keeps 0 for the group's whole life: its table + * is [reference][ring] from position 0 and only the ring's slot index recycles (SeqWindow), + * so the mapping above holds for the reference and SeqWindow's rule for the ring. */ int64_t first_block_pos(uint64_t seq, int32_t group) const; /* The first table entry changed since the last call; entries below it are unchanged, and @@ -461,6 +560,9 @@ private: * for a windowed group. 0 for kUnboundedTokens, which is not a count. */ int64_t zero_blocks(const KVGroupPlan& p, int64_t tokens) const; void forget(); + /* Turns a WINDOW group into a runtime-window one (declare_runtime_window). Returns false for a + * group that is not windowed. */ + bool apply_runtime_window(KVGroupPlan& p) const; /* One traversal serving both checkpoint directions; see checkpoint_save. */ int checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save, @@ -471,6 +573,7 @@ private: int64_t n_tokens = 0; std::vector> blocks; /* per group */ std::vector first_block_pos; /* WINDOW: token pos of blocks[0] */ + std::vector win; /* per group: the runtime window, if any */ std::vector state; /* per group, -1 when not stateful */ /* Per group, the lowest table entry written since the batch builder last staged this * sequence. An append or truncation lowers it to where it touched; a shift lowers it to @@ -486,8 +589,12 @@ private: void drop_state(int32_t g, int32_t s); Seq* find(uint64_t seq); const Seq* find(uint64_t seq) const; - /* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. */ + /* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. A runtime window + * (SeqWindow) is not trimmed: its reference must stay and its ring rewrites slots in place. */ void recycle_window(Seq* s, int64_t keep_from); + /* The table length a runtime-windowed sequence needs to hold `n_tokens`: the reference's + * blocks, then the ring's up to its whole span. */ + static int64_t window_table_len(const KVGroupPlan& p, const SeqWindow& w, int64_t n_tokens); std::vector plans_; std::vector> free_blocks_; /* per group */ @@ -515,6 +622,9 @@ private: int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, padding */ int64_t ckpts_ = 0; /* --checkpoint-slots, kept for the warning on a model with none */ int64_t tokens_cap_ = 0; /* cap_paged_tokens(): the least any rank can carve; 0 is none */ + /* declare_runtime_window(): group -> W. Survives forget(), which plan_groups() calls at its + * start: it is a declaration about the program, not about a plan. */ + std::unordered_map runtime_decl_; /* ---- the loan (see the public block) ---- * diff --git a/core/mem/kvtier.cpp b/core/mem/kvtier.cpp index b39144e5..3d1face9 100644 --- a/core/mem/kvtier.cpp +++ b/core/mem/kvtier.cpp @@ -606,6 +606,51 @@ void IdleTiers::drop_session(uint64_t id) { sessions_.erase(it); } +void IdleTiers::find_sessions(const std::string& label, uint64_t id, + std::vector* out) const { + out->clear(); + std::lock_guard lk(mu_); + for (const auto& kv : sessions_) { + const bool hit = id != 0 ? kv.first == id : (!label.empty() && kv.second.label == label); + if (!hit) continue; + SessionChain c; + c.id = kv.first; + c.label = kv.second.label; + c.chain = kv.second.chain; + out->push_back(std::move(c)); + } +} + +int64_t IdleTiers::shared_prefix_blocks(const std::vector& chain, + const std::vector& except) const { + if (chain.empty()) return 0; + std::lock_guard lk(mu_); + auto ro = roots_.find(chain[0]); + if (ro == roots_.end()) return 0; + int64_t most = 0; + for (uint64_t sid : ro->second) { + if (std::find(except.begin(), except.end(), sid) != except.end()) continue; + auto it = sessions_.find(sid); + if (it == sessions_.end()) continue; + const std::vector& other = it->second.chain; + size_t n = 0; + while (n < chain.size() && n < other.size() && chain[n] == other[n]) ++n; + if ((int64_t)n > most) most = (int64_t)n; + } + return most; +} + +void IdleTiers::cut_session(uint64_t id, int64_t keep_blocks, int64_t keep_tokens) { + std::lock_guard lk(mu_); + if (keep_blocks <= 0) { drop_session(id); return; } + auto it = sessions_.find(id); + if (it == sessions_.end()) return; + Session& s = it->second; + if ((int64_t)s.chain.size() <= keep_blocks) return; + s.chain.resize((size_t)keep_blocks); + s.n_tokens = keep_tokens; +} + std::vector IdleTiers::sessions(Occupancy* occ) const { /* One slice's hold on the lock (YieldingMutex). */ struct Slice { diff --git a/core/mem/kvtier.h b/core/mem/kvtier.h index 20eccac2..cdb79a5a 100644 --- a/core/mem/kvtier.h +++ b/core/mem/kvtier.h @@ -246,6 +246,31 @@ public: * microseconds apart. */ std::vector sessions(Occupancy* occ = nullptr) const; + /* ---------------- a release names a session ---------------- + * + * The cache keys by block and knows no conversation; the rows here are what a client can + * name. PrefixCache::release_session asks for the rows, walks their chains itself and + * reports back what is left of each. */ + struct SessionChain { + uint64_t id = 0; + std::string label; + std::vector chain; + }; + /* Every row carrying `label`, or with `id` nonzero the one row of that id. A label is the + * client's and may stand on several leaves (a conversation branched and both ends were + * served); a release by label means all of them. */ + void find_sessions(const std::string& label, uint64_t id, + std::vector* out) const; + /* How many blocks at the start of `chain` another stored session walks too: the longest + * common prefix with any row at the same root whose id is not in `except`. Those blocks + * belong to the other conversation as much as to this one. */ + int64_t shared_prefix_blocks(const std::vector& chain, + const std::vector& except) const; + /* The release is done: the row keeps its first `keep_blocks` (covering `keep_tokens`), + * which is the kept prefix or, beyond it, the deepest block a live request held back; it + * goes when that is zero. A kept stub is a leaf again until a later turn extends it. */ + void cut_session(uint64_t id, int64_t keep_blocks, int64_t keep_tokens); + struct Stats { /* `to_host` counts copies to host memory (link traffic); `dropped` counts VRAM copies * then given up. An entry can be copied and never dropped. */ diff --git a/core/mem/prefix.cpp b/core/mem/prefix.cpp index a2a418d8..d90f6fe1 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -368,11 +368,16 @@ int PrefixCache::insert(uint64_t session, for (int64_t b = 0; b < n_full; ++b) { const BlockHash& h = hs[(size_t)b]; auto it = map_.find(h); - if (it != map_.end() && it->second.in_lru) continue; /* touched below */ + /* With snapshots (recurrent state or a sliding window) an existing entry keeps the bytes + * it was published with, wherever it is held: a snapshot deeper in the chain was computed + * from them, and a recompute in another step shape can round the KV differently. The + * recomputed blocks go with the request's sequence; a later hit restores the tier copy. */ + if (it != map_.end() && (it->second.in_lru || has_linear_)) continue; /* touched below */ if (it != map_.end()) { - /* An off-device entry this request recomputed (a restore that did not fit, or a chain - * cut short). Its blocks become the entry's device copy and the tier copy goes - * (IdleTiers::rebound). An entry with a promotion in flight is left alone. */ + /* Without snapshots, an off-device entry this request recomputed (a restore that did + * not fit, or a chain cut short): its blocks become the entry's device copy and the + * tier copy goes (IdleTiers::rebound). An entry with a promotion in flight is left + * alone. */ if (!tiers_ || !tiers_->resident_off_device(h)) continue; std::vector mine(groups_.size(), -1); size_t held = 0; @@ -462,8 +467,9 @@ void PrefixCache::take_over(uint64_t session, const std::vector& hs, std::vector PrefixCache::restorable_from(const std::vector& tokens, const std::vector& mm, - int64_t fit) const { + int64_t fit, bool* cut) const { std::vector out; + if (cut) *cut = false; if (!enabled_ || !tiers_ || tokens.empty()) return out; /* Only blocks a hit can use: one token must remain, so a prompt ending on a block boundary @@ -488,13 +494,16 @@ std::vector PrefixCache::restorable_from(const std::vector& if (out.empty() || (int64_t)out.size() <= fit) return out; /* Restored up to `fit`, the hit ends at the first entry left behind. */ - ++stats_.restore_cuts; + if (cut) *cut = true; int64_t keep = std::max(0, fit); if (has_linear_) { const auto best = deepest_ckpt(hs, at[(size_t)keep] * block_size_); const int64_t upto = best == ck_by_prefix_.end() ? 0 : best->second.pos / block_size_; keep = std::lower_bound(at.begin(), at.begin() + keep, upto) - at.begin(); } + RAD_DEBUG("prefix cache: restore of %zu entries cut to %lld: the pool holds %lld of them, and " + "the hit ends at token %lld", out.size(), (long long)keep, + (long long)std::max(0, fit), (long long)(at[(size_t)keep] * block_size_)); out.resize((size_t)keep); return out; } @@ -508,7 +517,8 @@ int64_t PrefixCache::restore_room() const { int64_t PrefixCache::trim_for(const std::vector& tokens, const std::vector& mm, int64_t n_blocks) { - if (!enabled_ || n_blocks <= 0) return 0; + /* Without a host tier a trim erases, and making room for a restore must lose nothing. */ + if (!enabled_ || n_blocks <= 0 || !tiers_ || !tiers_->host_on()) return 0; const std::vector hs = chain_all(tokens, mm, (int64_t)tokens.size() / block_size_); std::unordered_set spare(hs.begin(), hs.end()); for (const auto& h : held_) spare.insert(h.first); @@ -981,4 +991,83 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) { stats_.ckpt_expired += (int64_t)gone.size(); return n; } + +/* ------------------------------------------------------------------ release on request */ + +int PrefixCache::release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionRelease* out) { + if (!out) return RAD_E_INVAL; + *out = SessionRelease{}; + if (!enabled_ || !tiers_ || block_size_ <= 0) return RAD_E_UNSUPPORTED; + if (label.empty() && id == 0) return RAD_E_INVAL; + if (keep_tokens < 0) return RAD_E_INVAL; + + std::vector rows; + tiers_->find_sessions(label, id, &rows); + if (rows.empty()) return RAD_E_NOTFOUND; + std::vector ids; + for (const IdleTiers::SessionChain& r : rows) ids.push_back(r.id); + + /* A kept token keeps its whole block: the block holding it is what the next turn hits. */ + const int64_t keep_blocks = (keep_tokens + block_size_ - 1) / block_size_; + int64_t entry_bytes = 0; + for (int32_t g : groups_) { + const KVGroupPlan* p = kv_->plan(g); + if (p) entry_bytes += p->bytes_per_block; + } + + for (const IdleTiers::SessionChain& row : rows) { + const int64_t n = (int64_t)row.chain.size(); + const int64_t shared = tiers_->shared_prefix_blocks(row.chain, ids); + const int64_t floor = std::max(keep_blocks, shared); + ++out->sessions; + out->kept_tokens += std::min(keep_blocks, n) * block_size_; + out->kept_shared += std::max(0, std::min(shared, n) - keep_blocks); + + /* Tip inwards, as expire() and the host tier's pressure do: what is left is still a + * prefix a lookup reaches. `live_upto` is one past the deepest block a request kept: + * the row is cut there, not at the kept prefix, so a later release reaches it. */ + int64_t live_upto = 0; + for (int64_t b = n - 1; b >= floor; --b) { + const BlockHash& h = row.chain[(size_t)b]; + auto it = map_.find(h); + if (it != map_.end()) { + Entry& e = it->second; + /* A sequence reads it, or a waiting request restored it and holds it against + * drop_clean: releasing would free nothing and lose the entry under them. Its + * snapshot stays with it; that request most likely resumes from it. */ + if (e.in_lru && (shared_with_live(e) || held_.count(h) > 0)) { + ++out->kept_live; + if (live_upto == 0) live_upto = b + 1; + continue; + } + if (e.in_lru) { + lru_.erase(e.lru); + e.in_lru = false; + release_blocks(e); + out->device_bytes += entry_bytes; + } + /* The host copy goes with the entry (forget), so count it before. */ + if (tiers_->resident_off_device(h) || tiers_->droppable(h)) + out->host_bytes += tiers_->entry_bytes(); + tiers_->forget(h); + map_.erase(it); + ++out->entries; + } + auto ck = ck_by_prefix_.find(h); + if (ck != ck_by_prefix_.end() && ck->second.valid && !handed(h) && !reserved(h)) { + const uint64_t session = ck->second.session; + retire_ckpt(ck); + unindex_ckpt(session, h); + ++out->snapshots; + } + } + const int64_t cut = std::min(n, std::max(keep_blocks, live_upto)); + tiers_->cut_session(row.id, cut, cut * block_size_); + } + out->tokens = out->entries * block_size_; + stats_.released += out->entries; + stats_.ckpt_released += out->snapshots; + return RAD_OK; +} } /* namespace rad */ diff --git a/core/mem/prefix.h b/core/mem/prefix.h index c88c405a..b60eec9e 100644 --- a/core/mem/prefix.h +++ b/core/mem/prefix.h @@ -174,6 +174,23 @@ CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t ma int64_t ctx, int64_t interval, int64_t slot_bytes, int64_t share_bytes, int64_t room_bytes); +/* ------------------------------------------------------------------ a release */ +/* What PrefixCache::release_session took out and what it left. Blocks are left for three + * reasons, counted apart so a caller can tell a half-shared conversation from a busy one: the + * caller asked for them (`keep_tokens`), another stored session's chain runs through them (a + * system prompt two conversations open with belongs to both), or a live sequence holds them. */ +struct SessionRelease { + int64_t sessions = 0; /* rows the label or id named */ + int64_t entries = 0; /* blocks forgotten, from VRAM or the host tier */ + int64_t tokens = 0; /* entries x block size */ + int64_t device_bytes = 0; /* pool bytes given back */ + int64_t host_bytes = 0; /* host-tier slots given back */ + int64_t snapshots = 0; + int64_t kept_tokens = 0; /* the chain's start, as asked, whole blocks */ + int64_t kept_shared = 0; /* blocks beyond that on another stored session's chain */ + int64_t kept_live = 0; /* blocks a running or waiting request holds */ +}; + /* ------------------------------------------------------------------ the cache */ class PrefixCache { public: @@ -256,20 +273,19 @@ public: * on a miss or token mismatch. Separate from lookup because lookup is const and has no * device; a promotion allocates blocks and runs a scatter between steps. * - * `fit` is how many entries the pool can take. A longer chain is cut, and counted - * (Stats::restore_cuts): with recurrent state at the deepest snapshot the shorter prefix - * reaches, since the hit resumes there and blocks past it would come back for nothing; - * without, at `fit`. */ + * `fit` is how many entries the pool can take. A longer chain is cut, and `*cut` set: with + * recurrent state at the deepest snapshot the shorter prefix reaches, since the hit resumes + * there and blocks past it would come back for nothing; without, at `fit`. */ std::vector restorable_from(const std::vector& tokens, const std::vector& mm, - int64_t fit = INT64_MAX) const; + int64_t fit = INT64_MAX, bool* cut = nullptr) const; /* Entries a restore can place now: free blocks against the carve, the least over the cached * groups. Lent blocks count, since KVManager::reserve_blocks recalls the loan for them. */ int64_t restore_room() const; /* Room for a restore of this prompt's chain: trim(), sparing the chain itself (its blocks * would only have to come back too) and every chain a waiting request holds (hold()), whose - * next attempt would restore it again. Nothing is lost; the reserve's trim after the next - * publish puts the pool's free quarter back. */ + * next attempt would restore it again. Only entries whose host copy has landed leave VRAM, + * so nothing is lost; with no host tier it takes nothing. */ int64_t trim_for(const std::vector& tokens, const std::vector& mm, int64_t n_blocks); @@ -315,6 +331,21 @@ public: * than what follows it: conversations expire from the tip inwards and a shared system prompt * outlives its readers. Returns how many entries went. */ int64_t expire(uint64_t now_ns, uint64_t ttl_ns); + + /* ---------------- release on request ---------------- + * + * Forget one stored conversation now instead of at the TTL: a client that deleted it, or + * replaced everything past a prefix (a compaction) and knows the rest is dead. `label` names + * every row carrying it, `id` (nonzero) one row by its engine id (IdleTiers::SessionInfo). + * The chain goes from the tip inwards like expire(): VRAM blocks to the pool, the host copy + * with them, the session's snapshots on the released blocks to the store. `keep_tokens` + * leaves the chain's first blocks standing (rounded up to whole blocks), so the prefix the + * client kept still hits. A block another stored session's chain shares stays, as does one a + * live sequence holds or a waiting request has restored; snapshots handed out or reserved + * this step stay too. RAD_E_NOTFOUND when nothing matches, RAD_E_UNSUPPORTED without the + * session table (no tiers attached). */ + int release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionRelease* out); /* ---------------- linear checkpoints ---------------- */ /* The next position strictly after `pos` at which the scheduler must split a chunk so that a * checkpoint lands on a boundary (spec §7.1, §7.3). */ @@ -357,8 +388,8 @@ public: int64_t drops = 0; /* Entries and snapshots removed by --prefix-cache-ttl, from any tier. */ int64_t expired = 0, ckpt_expired = 0; - /* Restores from the host tier cut short because the pool could not hold the chain. */ - int64_t restore_cuts = 0; + /* Entries and snapshots a client released (release_session). */ + int64_t released = 0, ckpt_released = 0; }; const Stats& stats() const { return stats_; } diff --git a/core/mem/vram_budget.h b/core/mem/vram_budget.h index 19b9aca5..67c2214c 100644 --- a/core/mem/vram_budget.h +++ b/core/mem/vram_budget.h @@ -82,9 +82,8 @@ struct VramFacts { bool lends = false; /* A loaded control vector's direction table: device bytes the engine already holds, which are * not part of the program or the pools and must not shrink what the plan may claim. It comes - * out of the headroom, as every deployment keeps that unclaimed. Without this, a deployment - * that merely *offers* a vector would plan its expert cache against a smaller card than one - * that does not, which is exactly the difference "off == stock" cannot allow. */ + * out of the headroom, as every deployment keeps that unclaimed, so a deployment that only + * offers a vector plans its expert cache against the same card as one that does not. */ int64_t held_out = 0; /* Integrated graphics: host memory the card must leave to the host, since device memory is * host memory there. 0 on a discrete card. */ diff --git a/core/mm/item.cpp b/core/mm/item.cpp index 62fea564..c1a14267 100644 --- a/core/mm/item.cpp +++ b/core/mm/item.cpp @@ -33,11 +33,18 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const { while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s; const int64_t within = first + k - patch_at(s); const int64_t bw = seg_w(s) / merge; - const int64_t in_col = within % merge; - const int64_t in_row = (within / merge) % merge; - const int64_t blk = within / (merge * merge); - const int64_t row = (blk / bw) * merge + in_row; - const int64_t col = (blk % bw) * merge + in_col; + int64_t row, col; + if (patch_raster) { + /* Raster order is its own inverse: patch i is row i / w, column i % w. */ + row = within / seg_w(s); + col = within % seg_w(s); + } else { + const int64_t in_col = within % merge; + const int64_t in_row = (within / merge) % merge; + const int64_t blk = within / (merge * merge); + row = (blk / bw) * merge + in_row; + col = (blk % bw) * merge + in_col; + } planes[k] = (int32_t)row; planes[count + k] = (int32_t)col; planes[2 * count + k] = seg_h(s); diff --git a/core/mm/media.h b/core/mm/media.h index 27ef41c6..4920bc47 100644 --- a/core/mm/media.h +++ b/core/mm/media.h @@ -46,7 +46,12 @@ int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRG /* Encodes `px`, [h, w, ch] 8-bit with ch 3 (RGB) or 4 (RGBA), as an image file; `format` is png, * jpeg or webp. `quality` 0..100 applies to jpeg and lossy webp (0 or above 100 picks the * format's default); png is lossless and webp is lossless at 100. jpeg refuses alpha. Returns - * RAD_E_UNSUPPORTED, with the reason, for a format this build cannot encode. */ + * RAD_E_UNSUPPORTED, with the reason, for a format this build cannot encode. + * + * Lossless webp is written by libwebp; FFmpeg's native VP8L decoder refuses some valid + * libwebp streams ("Invalid data", reproducible with ffmpeg 8.0.1 on a low-colour picture), + * so an FFmpeg-based consumer may not read every lossless file this writes. libwebp and + * browsers do. */ int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format, int32_t quality, std::vector* out, std::string* why); diff --git a/core/mm/processor.cpp b/core/mm/processor.cpp index 5703fd43..e8f49117 100644 --- a/core/mm/processor.cpp +++ b/core/mm/processor.cpp @@ -6,10 +6,19 @@ #include "rad_plugin.h" #include +#include #include #include +#include #include +#include #include +#include + +#if defined(__x86_64__) || defined(__i386__) || defined(_M_X64) +#include +#define RAD_MM_HAVE_AVX2 1 +#endif namespace rad { namespace mm { @@ -41,6 +50,49 @@ static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) { } int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) { + /* Unlimited-OCR: one processor class, two modes, both stated in preprocessor_config.json and + * processor_config.json (`processor.*`). Every key has the reference's default, so a container + * converted before the tower landed still states a processor. */ + if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "unlimited_ocr")) { + family = Family::UnlimitedOcr; + patch = (int32_t)rad_meta_geti(&m, "processor.patch_size", + rad_meta_geti(&m, "vision_config.patch_size", 16)); + downsample = (int32_t)rad_meta_geti(&m, "processor.downsample_ratio", 4); + merge = downsample; + temporal = 1; + base_size = (int32_t)rad_meta_geti(&m, "preprocessor.size.height", 1024); + tile = (int32_t)rad_meta_geti(&m, "preprocessor.tile_size", 640); + /* The base mode's whole view: what the reference states for its input, and what the + * preprocessor's `size` is. Multi-page inference may ask for the tile instead. */ + image_size = (int32_t)rad_meta_geti(&m, "preprocessor.size.width", base_size); + crop_mode = meta_bool(m, "preprocessor.crop_to_patches", true); + if (const char* t = rad_meta_gets(&m, "processor.image_token", nullptr); t && *t) + image_token = t; + min_tiles = (int32_t)rad_meta_geti(&m, "preprocessor.min_patches", 2); + max_tiles = (int32_t)rad_meta_geti(&m, "preprocessor.max_patches", 32); + tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1); + if (!read_triple(m, "preprocessor.image_mean", mean)) mean[0] = mean[1] = mean[2] = 0.5f; + if (!read_triple(m, "preprocessor.image_std", stdv)) stdv[0] = stdv[1] = stdv[2] = 0.5f; + /* 3 is PIL's bicubic, the only filter this processor stages. */ + const int64_t resample = rad_meta_geti(&m, "preprocessor.resample", 3); + if (resample != 3) { + if (why) *why = "the container resamples pictures with filter " + + std::to_string(resample) + "; this processor stages PIL's bicubic (3)"; + return RAD_E_UNSUPPORTED; + } + /* No video; the bands only have to be consistent for check(). */ + const int64_t f2 = (int64_t)factor() * factor(); + image_min_pixels = video_min_pixels = f2; + image_max_pixels = video_max_pixels = (int64_t)base_size * base_size; + min_frames = 1; + std::string bad; + if (check(&bad) < 0) { + if (why) *why = "the container's Unlimited-OCR processor configuration is " + "inconsistent: " + bad; + return RAD_E_INVAL; + } + return RAD_OK; + } /* LFM2-VL states its processor twice, in config.json and in processor_config.json's * image_processor; the latter is what the reference processor reads, so it goes first. */ if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "lfm2_vl")) { @@ -260,6 +312,20 @@ int VisionConfig::check(std::string* why) const { if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0) return no("max_pixels_tolerance and max_num_patches must be positive"); } + if (family == Family::UnlimitedOcr) { + if (patch <= 0 || downsample <= 0 || merge != downsample) + return no("the tower's geometry (patch_size " + std::to_string(patch) + + ", downsample_ratio " + std::to_string(downsample) + + ") does not cut a whole merged patch"); + if (base_size <= 0 || base_size % factor() || image_size <= 0 || image_size % factor()) + return no("the global view's side (" + std::to_string(base_size) + " and " + + std::to_string(image_size) + " pixels) is not a whole number of merged " + "patches"); + if (min_tiles < 1 || max_tiles < min_tiles || tile <= 0 || tile % factor()) + return no("the tiling (min_patches " + std::to_string(min_tiles) + ", max_patches " + + std::to_string(max_tiles) + ", tile_size " + std::to_string(tile) + + ") is not a range of whole merged patches"); + } if (family == Family::Glm5Next && (min_image_tokens < 1 || max_image_tokens < min_image_tokens)) return no("the image token band [" + std::to_string(min_image_tokens) + ", " + std::to_string(max_image_tokens) + "] is empty"); @@ -533,69 +599,314 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector* bounds, } /* namespace */ +/* ================================================================== AVX2 resample helpers + * + * The two passes below are fixed-point int32 per tap. Integer addition is exact and associative at + * these magnitudes (the coefficients of one output sum to 1 << prec and 255 << prec is about + * 1.07e9, so no wrapper), so evaluating eight output pixels at once in any tap order is the same + * function as the scalar loop; the rounding is only the final shift and clip. The horizontal pass + * has variable tap counts and arbitrary stride-3 starts, so its lanes gather one 32-bit word per + * tap (the RGB bytes of a pixel) and mask off inactive taps; the vertical pass reads whole rows, + * where eight pixels are 24 contiguous bytes. + * + * Dispatch is local rather than through libavx: this file is core host code, and the AVX2 bodies + * are target-attributed so the baseline object they live in still cannot execute AVX2 before the + * check. mm_force_scalar() selects the scalar path for the bit-exactness test. */ + +static std::atomic g_force_scalar{ false }; + +void mm_force_scalar(bool on) { g_force_scalar.store(on, std::memory_order_relaxed); } + +static bool mm_use_avx2() { +#ifdef RAD_MM_HAVE_AVX2 + static const bool cpu = [] { + __builtin_cpu_init(); + return __builtin_cpu_supports("avx2"); + }(); + return cpu && !g_force_scalar.load(std::memory_order_relaxed); +#else + return false; +#endif +} + +#if defined(RAD_MM_HAVE_AVX2) +#define RAD_MM_AVX2 __attribute__((target("avx2"))) +#define RAD_MM_INLINE_AVX2 __attribute__((target("avx2"), always_inline)) inline +#define RAD_MM_EXTRACT16(v) _mm256_extracti128_si256((v), 1) + +/* Eight RGB pixels from 24 contiguous bytes (bytes 0..23 of p). */ +RAD_MM_INLINE_AVX2 void load_rgb8(const uint8_t* p, __m256i* r, __m256i* g, __m256i* b) { + const __m128i a = _mm_loadu_si128((const __m128i*)p); + const __m128i c = _mm_loadl_epi64((const __m128i*)(p + 16)); + const __m128i mr0 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); + const __m128i mg0 = _mm_setr_epi8(1, 4, 7, 10, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); + const __m128i mb0 = _mm_setr_epi8(2, 5, 8, 11, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); + const __m128i mr1 = _mm_setr_epi8(2, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); + const __m128i mg1 = _mm_setr_epi8(0, 3, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); + const __m128i mb1 = _mm_setr_epi8(1, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1); + const __m128i rb = _mm_or_si128(_mm_shuffle_epi8(a, mr0), _mm_slli_si128(_mm_shuffle_epi8(c, mr1), 6)); + const __m128i gb = _mm_or_si128(_mm_shuffle_epi8(a, mg0), _mm_slli_si128(_mm_shuffle_epi8(c, mg1), 5)); + const __m128i bb = _mm_or_si128(_mm_shuffle_epi8(a, mb0), _mm_slli_si128(_mm_shuffle_epi8(c, mb1), 5)); + *r = _mm256_cvtepu8_epi32(rb); + *g = _mm256_cvtepu8_epi32(gb); + *b = _mm256_cvtepu8_epi32(bb); +} + +/* Eight rounded, clipped int32 sums written as eight RGB triplets (exactly 24 bytes). */ +RAD_MM_INLINE_AVX2 void store_rgb8(uint8_t* o, __m256i s0, __m256i s1, __m256i s2, int prec) { + const __m256i sh = _mm256_set1_epi32(prec); + const __m256i v0 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s0, sh), _mm256_setzero_si256()), + _mm256_set1_epi32(255)); + const __m256i v1 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s1, sh), _mm256_setzero_si256()), + _mm256_set1_epi32(255)); + const __m256i v2 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s2, sh), _mm256_setzero_si256()), + _mm256_set1_epi32(255)); + const __m128i r16 = _mm_packus_epi32(_mm256_castsi256_si128(v0), RAD_MM_EXTRACT16(v0)); + const __m128i g16 = _mm_packus_epi32(_mm256_castsi256_si128(v1), RAD_MM_EXTRACT16(v1)); + const __m128i b16 = _mm_packus_epi32(_mm256_castsi256_si128(v2), RAD_MM_EXTRACT16(v2)); + const __m128i r8 = _mm_packus_epi16(r16, r16); + const __m128i g8 = _mm_packus_epi16(g16, g16); + const __m128i b8 = _mm_packus_epi16(b16, b16); + /* Layout [r0..r3 g0..g3 b0..b3] then shuffle to 12 RGB bytes; twice for eight pixels. + * Mask the low four bytes before shifting, or each shift would overwrite the previous + * channel's bytes. */ + const __m128i low4 = _mm_set_epi64x(0, 0xffffffffll); + const __m128i m = _mm_setr_epi8(0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11, -1, -1, -1, -1); + const __m128i lo = _mm_shuffle_epi8( + _mm_or_si128(_mm_or_si128(_mm_and_si128(r8, low4), + _mm_slli_si128(_mm_and_si128(g8, low4), 4)), + _mm_slli_si128(_mm_and_si128(b8, low4), 8)), + m); + const __m128i hi = _mm_shuffle_epi8( + _mm_or_si128(_mm_or_si128(_mm_and_si128(_mm_srli_si128(r8, 4), low4), + _mm_slli_si128(_mm_and_si128(_mm_srli_si128(g8, 4), low4), 4)), + _mm_slli_si128(_mm_and_si128(_mm_srli_si128(b8, 4), low4), 8)), + m); + _mm_storel_epi64((__m128i*)o, lo); + _mm_storeu_si32(o + 8, _mm_srli_si128(lo, 8)); + _mm_storel_epi64((__m128i*)(o + 12), hi); + _mm_storeu_si32(o + 20, _mm_srli_si128(hi, 8)); +} + +/* One horizontal row, eight output pixels a step. plans is [group][tap] of eight (offset, coeff, + * mask) int32s. The gather reads four bytes at the last input pixel's B channel, so the caller + * keeps the buffer's final row on the scalar path. */ +RAD_MM_AVX2 void hpass_row(const uint8_t* row, uint8_t* o, int32_t ngroups, int32_t ksh, + int prec, const int32_t* plans) { + const __m256i zero = _mm256_setzero_si256(); + const __m256i round = _mm256_set1_epi32(1 << (prec - 1)); + const __m256i mask8 = _mm256_set1_epi32(0xff); + for (int32_t g = 0; g < ngroups; ++g) { + __m256i s0 = round, s1 = round, s2 = round; + const int32_t* pl = plans + (size_t)g * (size_t)ksh * 24; + for (int32_t t = 0; t < ksh; ++t, pl += 24) { + const __m256i off = _mm256_loadu_si256((const __m256i*)pl); + const __m256i coef = _mm256_loadu_si256((const __m256i*)(pl + 8)); + const __m256i msk = _mm256_loadu_si256((const __m256i*)(pl + 16)); + const __m256i word = _mm256_mask_i32gather_epi32(zero, (const int*)row, off, msk, 1); + const __m256i r = _mm256_and_si256(word, mask8); + const __m256i gg = _mm256_and_si256(_mm256_srli_epi32(word, 8), mask8); + const __m256i bb = _mm256_and_si256(_mm256_srli_epi32(word, 16), mask8); + s0 = _mm256_add_epi32(s0, _mm256_mullo_epi32(r, coef)); + s1 = _mm256_add_epi32(s1, _mm256_mullo_epi32(gg, coef)); + s2 = _mm256_add_epi32(s2, _mm256_mullo_epi32(bb, coef)); + } + store_rgb8(o + (size_t)g * 24, s0, s1, s2, prec); + } +} + +/* One vertical row: every tap is a whole source row, eight output pixels at a time. */ +RAD_MM_AVX2 void vpass_row(const Frame& src, int32_t ymin, int32_t ymax, const int32_t* k, + uint8_t* o, int prec) { + const __m256i round = _mm256_set1_epi32(1 << (prec - 1)); + int32_t xx = 0; + for (; xx + 8 <= src.w; xx += 8) { + __m256i s0 = round, s1 = round, s2 = round; + for (int32_t y = 0; y < ymax; ++y) { + const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3; + __m256i r, g, b; + load_rgb8(p, &r, &g, &b); + const __m256i kk = _mm256_set1_epi32(k[y]); + s0 = _mm256_add_epi32(s0, _mm256_mullo_epi32(r, kk)); + s1 = _mm256_add_epi32(s1, _mm256_mullo_epi32(g, kk)); + s2 = _mm256_add_epi32(s2, _mm256_mullo_epi32(b, kk)); + } + store_rgb8(o + (size_t)xx * 3, s0, s1, s2, prec); + } + for (; xx < src.w; ++xx) { + int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0; + for (int32_t y = 0; y < ymax; ++y) { + const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3; + s0 += p[0] * k[y]; + s1 += p[1] * k[y]; + s2 += p[2] * k[y]; + } + o[xx * 3 + 0] = clip8(s0, prec); + o[xx * 3 + 1] = clip8(s1, prec); + o[xx * 3 + 2] = clip8(s2, prec); + } +} + +/* One patch row: for each channel, P strided source bytes through that channel's LUT. lut32 is + * the same LUT as 32-bit words, so one gather gets all three channels' table entries. */ +RAD_MM_AVX2 void patch_row(const uint8_t* row, uint16_t* dst, int32_t P, size_t chstride, + const uint32_t* lut32, const uint16_t* lut) { + for (int32_t x = 0; x + 8 <= P; x += 8) { + __m256i r, g, b; + load_rgb8(row + (size_t)x * 3, &r, &g, &b); + const __m256i idx[3] = { r, g, b }; + for (int ch = 0; ch < 3; ++ch) { + const __m256i ii = _mm256_add_epi32(idx[ch], _mm256_set1_epi32(ch * 256)); + const __m256i v = _mm256_i32gather_epi32((const int*)lut32, ii, 4); + const __m128i h = _mm_packus_epi32(_mm256_castsi256_si128(v), RAD_MM_EXTRACT16(v)); + _mm_storeu_si128((__m128i*)(dst + (size_t)ch * chstride + x), h); + } + } + for (int ch = 0; ch < 3; ++ch) + for (int32_t x = (P / 8) * 8; x < P; ++x) + dst[(size_t)ch * chstride + x] = lut[ch * 256 + row[(size_t)x * 3 + ch]]; +} +#endif /* RAD_MM_HAVE_AVX2 */ + +/* One pass over an axis. `horizontal` reads rows [y0, y0 + rows) of `src` and writes w columns; + * `vertical` reads rows from `shift` on and writes h rows. Both accumulate in fixed point and + * round each output to eight bits, as Pillow does -- the intermediate's rounding is part of the + * function, and the scalar tap order must not change. + * + * Both passes are row-independent: every output row reads only its own input rows and writes only + * its own output row, in the same per-tap order, so splitting the rows across threads is bit-exact + * (the goldens pin it). */ +static void run_rows(int32_t rows, const std::function& row) { + unsigned hw = std::thread::hardware_concurrency(); + const int32_t nt = (int32_t)std::min(rows, (int32_t)std::min(hw ? hw : 1, 8)); + if (nt <= 1) { + for (int32_t y = 0; y < rows; ++y) row(y); + return; + } + std::vector ts; + ts.reserve((size_t)nt); + for (int32_t t = 0; t < nt; ++t) + ts.emplace_back([&row, t, nt, rows] { for (int32_t y = t; y < rows; y += nt) row(y); }); + for (std::thread& th : ts) th.join(); +} + +static void pass_horizontal(const Frame& src, int32_t y0, int32_t rows, int32_t w, + const std::vector& bh, const std::vector& kh, + int32_t ksh, int prec, Frame* out) { + out->w = w; + out->h = rows; + out->rgb.assign((size_t)w * (size_t)rows * 3, 0); + const bool simd = mm_use_avx2(); + const int32_t ngroups = simd ? w / 8 : 0; + std::vector plans; + if (ngroups) { + plans.resize((size_t)ngroups * (size_t)ksh * 24); + for (int32_t g = 0; g < ngroups; ++g) + for (int32_t t = 0; t < ksh; ++t) { + int32_t* p = plans.data() + ((size_t)g * (size_t)ksh + (size_t)t) * 24; + for (int32_t j = 0; j < 8; ++j) { + const int32_t xx = g * 8 + j; + const int32_t xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1]; + const bool on = t < xmax; + p[j] = on ? (xmin + t) * 3 : 0; + p[8 + j] = on ? kh[(size_t)xx * (size_t)ksh + (size_t)t] : 0; + p[16 + j] = on ? -1 : 0; + } + } + } + auto scalar_row = [&](const uint8_t* row, uint8_t* o, int32_t x0) { + for (int32_t xx = x0; xx < w; ++xx) { + const int32_t xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1]; + const int32_t* k = kh.data() + (size_t)xx * (size_t)ksh; + int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0; + for (int32_t x = 0; x < xmax; ++x) { + const uint8_t* p = row + (size_t)(x + xmin) * 3; + s0 += p[0] * k[x]; + s1 += p[1] * k[x]; + s2 += p[2] * k[x]; + } + o[xx * 3 + 0] = clip8(s0, prec); + o[xx * 3 + 1] = clip8(s1, prec); + o[xx * 3 + 2] = clip8(s2, prec); + } + }; + run_rows(rows, [&](int32_t yy) { + const uint8_t* row = src.rgb.data() + (size_t)(yy + y0) * (size_t)src.w * 3; + uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)w * 3; + /* The gather reads one byte past the row, which stays in the buffer on every row but its + * last; that one stays scalar. */ + if (!ngroups || yy + y0 == src.h - 1) { scalar_row(row, o, 0); return; } +#ifdef RAD_MM_HAVE_AVX2 + hpass_row(row, o, ngroups, ksh, prec, plans.data()); + scalar_row(row, o, ngroups * 8); +#endif + }); +} + +static void pass_vertical(const Frame& src, int32_t shift, int32_t h, + const std::vector& bv, const std::vector& kv, + int32_t ksv, int prec, Frame* out) { + out->w = src.w; + out->h = h; + out->rgb.assign((size_t)src.w * (size_t)h * 3, 0); + const bool simd = mm_use_avx2(); + run_rows(h, [&](int32_t yy) { + const int32_t ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1]; + const int32_t* k = kv.data() + (size_t)yy * (size_t)ksv; + uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)src.w * 3; +#ifdef RAD_MM_HAVE_AVX2 + if (simd) { vpass_row(src, ymin, ymax, k, o, prec); return; } +#endif + (void)simd; + for (int32_t xx = 0; xx < src.w; ++xx) { + int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0; + for (int32_t y = 0; y < ymax; ++y) { + const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3; + s0 += p[0] * k[y]; + s1 += p[1] * k[y]; + s2 += p[2] * k[y]; + } + o[xx * 3 + 0] = clip8(s0, prec); + o[xx * 3 + 1] = clip8(s1, prec); + o[xx * 3 + 2] = clip8(s2, prec); + } + }); +} + static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch) { if (in.w == w && in.h == h) { *out = in; return; } std::vector bh, kh, bv, kv; int ph = kPrec, pv = kPrec; const int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph); const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv); + const bool need_h = w != in.w, need_v = h != in.h; - /* The source rows the vertical pass reads, which is all the horizontal pass has to produce. */ - const int y_first = bv[0]; - const int y_last = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1]; - const bool need_h = w != in.w; - const bool need_v = h != in.h; + /* Pillow's pass order (libImaging/Resample.c): vertical first when the height shrinks and by + * more than twice what the width does, so the horizontal pass runs over fewer rows. The + * intermediate is eight bits, so the order changes the picture: both are the reference's. + * torchvision's on a uint8 tensor (ATen's CPU kernel) is horizontal first at every size. */ + const bool horizontal_first = + torch || !((int64_t)in.h - h > 0 && (int64_t)in.h - h > 2 * ((int64_t)in.w - w)); Frame tmp; - const Frame* src = ∈ + if (need_h && need_v) { + if (horizontal_first) { + /* Only the source rows the vertical pass reads are resampled horizontally. */ + const int32_t y0 = bv[0]; + const int32_t rows = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1] - y0; + pass_horizontal(in, y0, rows, w, bh, kh, ksh, ph, &tmp); + pass_vertical(tmp, y0, h, bv, kv, ksv, pv, out); + } else { + pass_vertical(in, 0, h, bv, kv, ksv, pv, &tmp); + pass_horizontal(tmp, 0, h, w, bh, kh, ksh, ph, out); + } + return; + } if (need_h) { - const int rows = need_v ? y_last - y_first : in.h; - const int y0 = need_v ? y_first : 0; - tmp.w = w; - tmp.h = rows; - tmp.rgb.assign((size_t)w * rows * 3, 0); - for (int yy = 0; yy < rows; ++yy) { - const uint8_t* row = in.rgb.data() + (size_t)(yy + y0) * in.w * 3; - uint8_t* o = tmp.rgb.data() + (size_t)yy * w * 3; - for (int xx = 0; xx < w; ++xx) { - const int xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1]; - const int32_t* k = kh.data() + (size_t)xx * ksh; - int32_t s0 = 1 << (ph - 1), s1 = s0, s2 = s0; - for (int x = 0; x < xmax; ++x) { - const uint8_t* p = row + (size_t)(x + xmin) * 3; - s0 += p[0] * k[x]; - s1 += p[1] * k[x]; - s2 += p[2] * k[x]; - } - o[xx * 3 + 0] = clip8(s0, ph); - o[xx * 3 + 1] = clip8(s1, ph); - o[xx * 3 + 2] = clip8(s2, ph); - } - } - src = &tmp; - } - if (!need_v) { *out = std::move(tmp); return; } - const int shift = need_h ? y_first : 0; - out->w = src->w; - out->h = h; - out->rgb.assign((size_t)src->w * h * 3, 0); - for (int yy = 0; yy < h; ++yy) { - const int ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1]; - const int32_t* k = kv.data() + (size_t)yy * ksv; - uint8_t* o = out->rgb.data() + (size_t)yy * src->w * 3; - for (int xx = 0; xx < src->w; ++xx) { - int32_t s0 = 1 << (pv - 1), s1 = s0, s2 = s0; - for (int y = 0; y < ymax; ++y) { - const uint8_t* p = src->rgb.data() + ((size_t)(y + ymin) * src->w + xx) * 3; - s0 += p[0] * k[y]; - s1 += p[1] * k[y]; - s2 += p[2] * k[y]; - } - o[xx * 3 + 0] = clip8(s0, pv); - o[xx * 3 + 1] = clip8(s1, pv); - o[xx * 3 + 2] = clip8(s2, pv); - } + pass_horizontal(in, 0, in.h, w, bh, kh, ksh, ph, out); + return; } + pass_vertical(in, 0, h, bv, kv, ksv, pv, out); } void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) { @@ -795,6 +1106,19 @@ int Processor::init(const VisionConfig& cfg, 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. */ + if (!token_id) return RAD_E_INVAL; + if (cfg_.tok_image < 0) cfg_.tok_image = token_id(cfg_.image_token); + if (cfg_.tok_image < 0) return RAD_E_NOTFOUND; + /* A tile's line and the global view are each one segment, so each must fit one pass. */ + const int64_t q = cfg.tile / cfg.patch; + const int64_t g = std::max(cfg.base_size, cfg.image_size) / cfg.patch; + if (q * (q + 4) > cfg.max_patches || g * (g + 4) > cfg.max_patches) return RAD_E_INVAL; + encode_text_ = std::move(encode_text); + return RAD_OK; + } /* The largest image one encoder pass takes, in pixels. Lowering the band's ceiling to it makes * smart_resize keep every image inside a pass. */ const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch; @@ -844,6 +1168,75 @@ void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32 } } +/* Unlimited-OCR's ratios of one tile count tie only when they are each other's transpose: two + * ratios of the same count are equally near an aspect only if one mirrors the other about it. So + * the reference's set order matters for exactly the (c, r) pairs below, the tall ones (c < r) + * its `sorted(set(...), key=area)` visits after their wide transpose -- the order CPython's set + * has for the 2..32-tile range the checkpoint states. It comes from the reference itself + * (tests/mkuocrgolden.py dumps it); outside that range the wide side is taken as last. */ +static constexpr int8_t kTallLast[][2] = { + {1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 9}, {1, 13}, {1, 14}, + {1, 16}, {1, 18}, {1, 20}, {1, 22}, {1, 27}, {1, 29}, {2, 3}, {2, 4}, + {2, 5}, {2, 6}, {2, 7}, {2, 8}, {2, 9}, {2, 14}, {2, 15}, {2, 16}, + {3, 5}, {3, 7}, {3, 9}, {4, 5}, {4, 6}, {4, 7}, {4, 8}, +}; +bool uocr_tall_last(int32_t c, int32_t r) { + for (const auto& p : kTallLast) + if (p[0] == c && p[1] == r) return true; + return false; +} + +/* One n defers at most its divisor pairs with c < n/c, at most the divisors below its square + * root. Over the 2..32-tile range the checkpoints state the table is built for, no n defers + * more than this; uocr_grid's deferred buffer is sized from it and the static_assert below + * keeps the bound checked against the table, not empirical. */ +static constexpr int32_t deferred_pairs_max(int32_t max_n) { + int32_t best = 0; + for (int32_t n = 2; n <= max_n; ++n) { + int32_t cnt = 0; + for (const auto& p : kTallLast) + if (p[0] < p[1] && (int32_t)p[0] * (int32_t)p[1] == n) ++cnt; + if (cnt > best) best = cnt; + } + return best; +} +static_assert(deferred_pairs_max(32) <= 8, + "uocr_grid's 8-slot deferred buffer must cover the stated 2..32 tile range"); + +void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile, + int32_t* cols, int32_t* rows) { + *cols = *rows = 1; + if (h <= 0 || w <= 0 || min_tiles < 1 || max_tiles < min_tiles) return; + const double aspect = (double)w / (double)h; + const double area = (double)w * (double)h; + const double half = 0.5 * (double)tile * (double)tile; + double best = INFINITY; + for (int32_t n = min_tiles; n <= max_tiles; ++n) { + int32_t deferred[8]; /* the transposed ratios the reference visits last */ + int32_t n_deferred = 0; + auto visit = [&](int32_t c, int32_t r) { + const double diff = std::fabs(aspect - (double)c / (double)r); + if (diff < best) { + best = diff; *cols = c; *rows = r; + } else if (diff == best && area > half * (double)n) { + *cols = c; *rows = r; + } + }; + for (int32_t c = 1; c <= n; ++c) { + if (n % c) continue; + if (c < n / c && uocr_tall_last(c, n / c)) { + /* Defensive: the static_assert proves 8 covers the stated 2..32 range. Beyond + * it the reference's tie order is not guaranteed, and a drop is a last resort + * against overflow, not a designed path. */ + if (n_deferred < 8) deferred[n_deferred++] = c; + continue; + } + visit(c, n / c); + } + for (int32_t k = 0; k < n_deferred; ++k) visit(deferred[k], n / deferred[k]); + } +} + /* LFM2-VL's image processor (transformers' Lfm2VlImageProcessor), segment by segment: the tiles * in row-major order, then the thumbnail. Within a segment, patches are in merge-block order (each * merge x merge block consecutive, dy then dx, as the projector's pixel unshuffle reads them, so @@ -921,6 +1314,240 @@ int Processor::image_lfm2(const Frame& f, std::shared_ptr* out, std::strin return RAD_OK; } +int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t* base_size, + int32_t* image_size, std::string* why) { + auto no = [why](const std::string& w) { + if (why) *why = w; + return RAD_E_INVAL; + }; + if (c.family != Family::UnlimitedOcr) return no("this model has one picture mode, not two"); + const int32_t F = c.factor(); + const bool cr = mode.kind == ImageMode::Base ? false + : mode.kind == ImageMode::Gundam ? true + : mode.several ? false + : c.crop_mode; + const int32_t bs = mode.base_size > 0 ? mode.base_size : c.base_size; + const int32_t is = mode.image_size > 0 ? mode.image_size : c.image_size; + if (cr) { + /* The crops are the tile the checkpoint was trained at; the reference's image_size is + * that same number, so a request may only restate it. */ + if (bs % F) + return no("base_size " + std::to_string(bs) + " is not a whole number of merged " + "patches (" + std::to_string(F) + ")"); + if (bs < 4 * F) + return no("base_size " + std::to_string(bs) + " is under two output rows"); + if (bs / c.patch != 64 && bs / c.patch != 40) + return no("the DeepEncoder serves base grids 64 and 40 (base_size 1024 or 640); " + "base_size " + std::to_string(bs) + " is neither"); + if (mode.image_size > 0 && mode.image_size != c.tile) + return no("crop mode cuts pictures into " + std::to_string(c.tile) + "-pixel tiles; " + "image_size " + std::to_string(mode.image_size) + " is not one"); + *crop = true; *base_size = bs; *image_size = c.tile; + return RAD_OK; + } + if (is % F) + return no("image_size " + std::to_string(is) + " is not a whole number of merged patches " + "(" + std::to_string(F) + ")"); + if (is < 4 * F) return no("image_size " + std::to_string(is) + " is under two output rows"); + if (is / c.patch != 64 && is / c.patch != 40) + return no("the DeepEncoder serves base grids 64 and 40 (image_size 1024 or 640); " + "image_size " + std::to_string(is) + " is neither"); + if (mode.base_size > 0 && mode.base_size != bs) + return no("the base mode pads a page to image_size, not base_size"); + *crop = false; *base_size = bs; *image_size = is; + return RAD_OK; +} + +int64_t uocr_tokens(const VisionConfig& c, const ImageMode& mode, int32_t cols, int32_t rows) { + bool crop = false; + int32_t bs = 0, is = 0; + if (uocr_mode(c, mode, &crop, &bs, &is, nullptr) < 0) return -1; + const int32_t P = c.patch, D = c.downsample; + /* The global view: `g` lines of `g` features, each followed by a newline, then the view + * separator (`[tok] * g + [tok]) * g + [tok]`). */ + const int32_t g = (crop ? bs : is) / P / D; + int64_t t = (int64_t)(g + 1) * g + 1; + /* The local views, when the picture is tiled: one line per feature row holding every tile's + * row, a newline after it (`[tok] * q * cols + [tok]) * q * rows`). */ + if (crop && (int64_t)cols * rows > 1) { + const int32_t q = c.tile / P / D; + t += (int64_t)(q * cols + 1) * q * rows; + } + return t; +} + +void pad_bicubic(const Frame& in, int32_t w, int32_t h, uint8_t fill, Frame* out) { + /* ImageOps.pad: contain() fits the picture inside w x h at its own aspect (PIL's bicubic, + * rounded as its round() does), then it is pasted centred on `fill`. */ + int32_t nw = w, nh = h; + if (in.w > 0 && in.h > 0) { + const double im_ratio = (double)in.w / (double)in.h; + const double dst_ratio = (double)w / (double)h; + if (im_ratio != dst_ratio) { + if (im_ratio > dst_ratio) { + nh = (int32_t)pyround((double)in.h / (double)in.w * (double)w); + if (nh == 0) nh = 1; + } else { + nw = (int32_t)pyround((double)in.w / (double)in.h * (double)h); + if (nw == 0) nw = 1; + } + } + } + const Frame* src = ∈ + Frame fitted; + if (nw != in.w || nh != in.h) { + resize_bicubic(in, nw, nh, &fitted); + src = &fitted; + } + out->w = w; + out->h = h; + out->rgb.assign((size_t)w * (size_t)h * 3, fill); + const int32_t x = nw != w ? (int32_t)pyround((double)(w - nw) * 0.5) : 0; + const int32_t y = nw != w ? 0 : (int32_t)pyround((double)(h - nh) * 0.5); + for (int32_t yy = 0; yy < src->h; ++yy) + std::memcpy(out->rgb.data() + ((size_t)(y + yy) * (size_t)w + (size_t)x) * 3, + src->rgb.data() + (size_t)yy * (size_t)src->w * 3, (size_t)src->w * 3); +} + +/* Unlimited-OCR's picture processor, the reference's infer() and infer_multi() exactly: the + * global view is the picture ImageOps.pad-ed to base_size (in the base mode, to image_size, + * squared first when that side is a tile or less), and in the gundam mode a picture larger than a + * tile is cut the way dynamic_preprocess cuts it. Each view is staged as its feature grid plus + * `downsample` patch columns nothing is read from, because the reference's layout puts a newline + * after every line of features: one output row per downsample x downsample patches, and the last + * column's rows are where those newlines go. The segments are, in the reference's order, the + * local grid's lines (one per tile row; a line wider than a pass is cut into chunks of whole + * tiles, its last chunk carrying the newline column), then the global view's grid, then the view + * separator's single row. */ +int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode, + std::shared_ptr* out, std::string* why) const { + const VisionConfig& c = cfg_; + const int32_t P = c.patch, M = c.merge; + bool crop = false; + int32_t base_size = 0, image_size = 0; + RAD_TRY(uocr_mode(c, mode, &crop, &base_size, &image_size, why)); + if (f.w <= 0 || f.h <= 0) { + if (why) *why = "the picture has no size"; + return RAD_E_INVAL; + } + const int32_t q = c.tile / P; /* a tile's patch rows */ + int32_t cols = 1, rows = 1; + const bool tiled = crop && (f.w > c.tile || f.h > c.tile); + if (tiled) uocr_grid(f.h, f.w, c.min_tiles, c.max_tiles, c.tile, &cols, &rows); + + /* The global view. The base mode squares a page of a tile or less before padding it, as the + * reference's multi-page path does. */ + Frame global; + if (crop) { + pad_bicubic(f, base_size, base_size, 127, &global); + } else if (image_size <= c.tile) { + /* The reference's multi-page path squares the page first, so a non-square page is + * aspect-distorted by this resize, and the pad below is a no-op by construction (the + * square already is the pad target). Square-first kept for reference parity. */ + Frame sq; + resize_bicubic(f, image_size, image_size, &sq); + pad_bicubic(sq, image_size, image_size, 127, &global); + } else { + pad_bicubic(f, image_size, image_size, 127, &global); + } + const int32_t g = (crop ? base_size : image_size) / P; + if ((int64_t)g * (g + 4) > c.max_patches) { + if (why) *why = "the global view's " + std::to_string((long long)g * (g + 4)) + + " patches are more than one encoder pass holds (" + + std::to_string(c.max_patches) + ")"; + return RAD_E_INVAL; + } + + /* ToTensor then Normalize, in f32: (u / 255 - mean) / std, rounded to bf16. */ + uint16_t lut[3][256]; + uint32_t lut32[3 * 256]; + for (int ch = 0; ch < 3; ++ch) + for (int v = 0; v < 256; ++v) { + const float p = (float)v / 255.0f; + lut[ch][v] = rad_f32_to_bf16((p - c.mean[ch]) / c.stdv[ch]); + lut32[ch * 256 + v] = lut[ch][v]; + } + const bool simd = mm_use_avx2(); + + auto it = std::make_shared(); + it->kind = Kind::Image; + it->patch_dim = c.patch_dim(); + it->rope_1d = true; + it->patch_raster = true; + int64_t seg_row = 0; + /* One segment of `gh` x `gw` patches from (x0, y0) of `src`, of which the first `real_w` + * patches a row carry pixels; the rest are the newline column. */ + auto append = [&](const Frame& src, int32_t x0, int32_t y0, int32_t gh, int32_t gw, + int32_t real_w, bool sep = false) { + it->segments.push_back({ gh, gw, it->n_patch, sep }); + it->seg_at.push_back((int32_t)seg_row); + it->expand.insert(it->expand.end(), (size_t)(gh / M) * (size_t)(gw / M), c.tok_image); + seg_row += (int64_t)(gh / M) * (gw / M); + it->n_patch += (int64_t)gh * gw; + const size_t at = it->pixels.size(); + it->pixels.resize(at + (size_t)gh * (size_t)gw * (size_t)it->patch_dim, 0); + uint16_t* dst = it->pixels.data() + at; + /* Each patch row writes its own disjoint run of dst, in the same order, so splitting the + * rows across threads is bit-exact. */ + run_rows(gh, [&](int32_t py) { + for (int32_t px = 0; px < real_w; ++px) { + uint16_t* pp = dst + ((size_t)py * (size_t)gw + (size_t)px) * (size_t)it->patch_dim; + const int32_t py0 = y0 + py * P, px0 = x0 + px * P; + for (int y = 0; y < P; ++y) { + const uint8_t* row = src.rgb.data() + + ((size_t)(py0 + y) * (size_t)src.w + (size_t)px0) * 3; +#ifdef RAD_MM_HAVE_AVX2 + if (simd) { + patch_row(row, pp + (size_t)y * P, P, (size_t)P * P, lut32, &lut[0][0]); + continue; + } +#endif + (void)simd; + for (int ch = 0; ch < 3; ++ch) { + const uint8_t* r = row + (size_t)ch; + uint16_t* q = pp + ((size_t)ch * P + (size_t)y) * P; + for (int x = 0; x < P; ++x) q[x] = lut[ch][r[(size_t)x * 3]]; + } + } + } + }); + }; + + if (tiled) { + Frame big; + resize_bicubic(f, cols * c.tile, rows * c.tile, &big); + /* A chunk of a line must fit one pass: q rows of q patches a tile, plus the newline + * column its last chunk holds. */ + int64_t per_row = c.max_patches / q; + const int64_t chunk = per_row > 4 ? (per_row - 4) / q : 0; + if (chunk < 1) { + if (why) *why = "one encoder pass holds no line of " + std::to_string(q) + + "-patch tiles (" + std::to_string(c.max_patches) + " patches)"; + return RAD_E_INVAL; + } + for (int32_t r = 0; r < rows; ++r) + for (int32_t c0 = 0; c0 < cols; c0 += (int32_t)chunk) { + const int32_t n = std::min((int32_t)chunk, cols - c0); + const bool last = c0 + n == cols; + append(big, c0 * c.tile, r * c.tile, q, q * n + (last ? 4 : 0), q * n); + } + } + append(global, 0, 0, g, g + 4, g); + /* The view separator: one output row, from a grid of exactly one merged cell and no pixels. */ + append(global, 0, 0, M, M, 0, /*sep=*/true); + + it->n_seg = (int32_t)it->segments.size(); + it->grid_t = 1; + it->grid_h = it->segments[0].h; + it->grid_w = it->segments[0].w; + it->rows_h = it->grid_h / M; + it->rows_w = it->grid_w / M; + it->seg_rows = it->rows_h * it->rows_w; + content_key(*it, &it->key_hi, &it->key_lo); + *out = std::move(it); + return RAD_OK; +} + /* GLM-5.3's image processor (transformers' Glm5NextImageProcessor, torchvision backend): the * picture, resized only when its size changes, in the top left of a canvas of zero bytes, which * the normalisation turns into each channel's -mean / std as it does the reference's padding. */ @@ -960,11 +1587,17 @@ int Processor::image_glm5next(const Frame& f, std::shared_ptr* out, std::s return RAD_OK; } -int Processor::image_from(const Frame& f, std::shared_ptr* out, std::string* why) const { +int Processor::image_from(const Frame& f, std::shared_ptr* out, std::string* why, + const ImageMode& mode) const { const VisionConfig& c = cfg_; + if (mode.kind != ImageMode::Default && c.family != Family::UnlimitedOcr) { + if (why) *why = "this model has one picture mode; images_config names one of two"; + return RAD_E_UNSUPPORTED; + } if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why); 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::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, &h, &w, why)); @@ -1140,7 +1773,12 @@ int Processor::video_from(const Video& v, std::shared_ptr* out, std::strin } int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens, - std::shared_ptr* out, std::string* why, int64_t max_pixels) const { + std::shared_ptr* out, std::string* why, int64_t max_pixels, + const ImageMode& mode) const { + if (mode.kind != ImageMode::Default && cfg_.family != Family::UnlimitedOcr) { + if (why) *why = "this model has one picture mode; images_config names one of two"; + return RAD_E_UNSUPPORTED; + } if (image_tokens != 0) { if (cfg_.family == Family::Glm5Next) { if (why) *why = "this model's image token budget is the server's (--image-tokens), " @@ -1169,7 +1807,7 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens, } if (cfg_.family == Family::Gemma4) return image_gemma4(f, image_tokens ? image_tokens : cfg_.image_soft_tokens, out, why); - return image_from(f, out, why); + return image_from(f, out, why, mode); } int Processor::encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, diff --git a/core/mm/processor.h b/core/mm/processor.h index 99ef0a71..14b70f9c 100644 --- a/core/mm/processor.h +++ b/core/mm/processor.h @@ -56,6 +56,18 @@ enum class Kind { Image, Video, Audio }; * own, followed by the whole picture at the budgeted size as a thumbnail. Patches * (y, x, channel) normalised by the mean and deviation, resized with torchvision's * fixed-point bicubic; images only, and the tokens rotate at their positions. + * UnlimitedOcr + * Unlimited-OCR's DeepSeek-OCR shape, in the checkpoint's two modes (ImageMode): the + * picture padded (ImageOps.pad) to base_size x base_size on a 127 grey as the global + * view, and, in the gundam mode, a picture larger than one tile cut into min_tiles.. + * max_tiles tile x tile crops at the tile in the ratio nearest its own (its + * dynamic_preprocess). The SAM neck downsamples by `downsample`, so patch * downsample + * is one output row. A view's rows are laid out as the reference's feature grid plus a + * column of newlines, which is why every segment carries `downsample` extra patch + * columns that nothing is read from: patches are raster order (Item::patch_raster), one + * patch (channel, y, x), each value (u / 255 - mean) / std in f32, rounded to bf16. + * Every placeholder is one id (the picture marker itself); the tokens rotate at their + * positions. * Glm5Next GLM-5.3's: a canvas whose sides are multiples of patch * merge and whose tokens fall * in [min_image_tokens, max_image_tokens] (the sides rounded up, a picture under the * floor grown, one over the budget fitted by the reference's search); the picture keeps @@ -64,7 +76,7 @@ enum class Kind { Image, Video, Audio }; * bottom, is zero bytes. Patches as QwenVL's. Images only, spelled * placeholders , the tokens at their positions (the language model has no * rotary). */ -enum class Family { QwenVL, Gemma4, Lfm2, Glm5Next }; +enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next }; struct VisionConfig { Family family = Family::QwenVL; @@ -91,6 +103,17 @@ struct VisionConfig { double max_pixels_tolerance = 0.0; int64_t max_segment_patches = 0; + /* UnlimitedOcr: the two modes' sizes, from the checkpoint's preprocessor config. The gundam + * mode pads the global view to `base_size` and cuts crops at `tile`; the base mode (a page of + * a multi-page document) pads the whole picture to `image_size`. `downsample` is the SAM + * neck's ratio: one output row is `patch * downsample` pixels a side. `crop_mode` is the + * deployment's mode when a request names none. */ + int32_t base_size = 0, image_size = 0, downsample = 0; + bool crop_mode = false; + /* The vocabulary's spelling of the picture marker (`processor.image_token`); every + * placeholder of a picture is that one id. */ + std::string image_token = ""; + /* Deployment bounds, not the checkpoint's. `max_patches` is the encoder's pass size: an image * is one segment and a segment is never split, so the image band's ceiling is lowered to fit * it. `max_source_pixels` bounds what the decoder may hold before any resize. */ @@ -112,6 +135,20 @@ struct VisionConfig { int from_meta(const RadModelMeta& m, std::string* why); }; +/* Which picture processor a request gets, for a checkpoint that has more than one: Unlimited-OCR + * states two modes and the reference names them gundam (one picture: the global view at base_size + * plus crops) and base (a page of a multi-page document: the global view only, at image_size). + * `Default` is the deployment's (`VisionConfig::crop_mode`), or base when `several` says the + * request carries more than one picture; a request may pick either mode and, with it, the sizes + * the checkpoint states differently. `base_size` and `image_size` of 0 keep the mode's own. A + * processor with one mode refuses a named mode and ignores `several`. */ +struct ImageMode { + enum Kind : int32_t { Default = 0, Gundam = 1, Base = 2 }; + int32_t kind = Default; + int32_t base_size = 0, image_size = 0; + bool several = false; +}; + /* The audio feature extractor family, from the container's audio_config.model_type. The * families differ in the spectrogram and in how a clip's frames are laid out for the encoder; * the Item they produce is shared. @@ -204,14 +241,20 @@ struct Item { * thumbnail): each is `h` x `w` patches starting at patch `patch0`. Empty means every segment * is grid_h x grid_w. The rest of the engine reads segments only through the accessors below, * so both forms look alike. */ - struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; }; + struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; bool sep = false; }; std::vector segments; /* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not * on the grid the Qwen-VL family's M-RoPE lays out (RopeLayout). */ bool rope_1d = false; + /* Patches are in raster order (row by row), not merge-block order: the coordinate planes + * invert the one or the other (Unlimited-OCR's tower reads a picture patch by patch). */ + bool patch_raster = false; int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; } int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; } + /* The one-output-row view separator (Unlimited-OCR stages it as a merge-grid cell of zeros). + * A square segment is not enough: a chunked line of one tile is q x q too. */ + bool seg_is_sep(int32_t s) const { return !segments.empty() && segments[(size_t)s].sep; } /* Segment s's first patch and first output row; s == n_seg is the end of the item. */ int64_t patch_at(int32_t s) const { if (segments.empty()) return (int64_t)s * grid_h * grid_w; @@ -319,13 +362,15 @@ public: /* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a * processor that sizes images by pixels refuses a non-zero one. `max_pixels`, when set, first - * scales a larger picture down to that area with PIL's bicubic. */ + * scales a larger picture down to that area with PIL's bicubic. `mode` picks one of the + * checkpoint's picture modes where it has more than one (Unlimited-OCR). */ int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr* out, - std::string* why, int64_t max_pixels = 0) const; + std::string* why, int64_t max_pixels = 0, const ImageMode& mode = ImageMode{}) const; int video(const uint8_t* bytes, size_t n, std::shared_ptr* out, std::string* why) const; /* From an already-decoded picture or frame list; for tests. */ - int image_from(const Frame& f, std::shared_ptr* out, std::string* why) const; + int image_from(const Frame& f, std::shared_ptr* out, std::string* why, + const ImageMode& mode = ImageMode{}) const; int video_from(const Video& v, std::shared_ptr* out, std::string* why) const; /* A picture in the video VAE's own form: decoded under the same `max_source_pixels` guard as @@ -381,6 +426,8 @@ private: int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr* out, std::string* why) const; int image_lfm2(const Frame& f, std::shared_ptr* out, std::string* why) const; + int image_unlimitedocr(const Frame& f, const ImageMode& mode, std::shared_ptr* out, + std::string* why) const; int image_glm5next(const Frame& f, std::shared_ptr* out, std::string* why) const; /* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */ int32_t tok_thumbnail_ = -1; @@ -444,6 +491,28 @@ void cap_area(const Frame& in, int64_t max_pixels, Frame* out); * aspect, the larger grid of two equally near when the picture fills over half of it. */ void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile, int32_t* cols, int32_t* rows); +/* Whether the reference's ratio set visits the tall side (c, r), c < r, of a transposed pair after + * the wide one: the only tie two ratios of one tile count can have. From the reference itself. */ +bool uocr_tall_last(int32_t c, int32_t r); +/* Unlimited-OCR's tile grid (its dynamic_preprocess): the min..max-tile grid nearest the picture's + * aspect, the one whose area the picture covers over half of when two are equally near, exactly + * as the reference's set ordering resolves it. The reference calls it only for a picture larger + * than one tile; this answers for any size. */ +void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile, + int32_t* cols, int32_t* rows); +/* The placeholders a picture takes: the global view's rows plus its separator, and, when tiled, + * one line of `cols` tiles per feature row with a newline after it. `cols` * `rows` is the tile + * grid. */ +int64_t uocr_tokens(const VisionConfig& c, const ImageMode& mode, int32_t cols, int32_t rows); +/* The mode `mode` resolves to for this deployment; RAD_E_INVAL names an unsupported size. */ +int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t* base_size, + int32_t* image_size, std::string* why); +/* Runs the resample and patch staging on their scalar path even where AVX2 is available, for a + * test that compares the two; process-wide. */ +void mm_force_scalar(bool on); +/* PIL's ImageOps.pad: `in` fitted inside w x h keeping its aspect (its bicubic), centred on `fill` + * in the channels' order (127 127 127 for the reference's 0.5 mean). */ +void pad_bicubic(const Frame& in, int32_t w, int32_t h, uint8_t fill, Frame* out); } /* namespace mm */ } /* namespace rad */ diff --git a/core/plugin/loader.cpp b/core/plugin/loader.cpp index 3fbaff00..7a10c70d 100644 --- a/core/plugin/loader.cpp +++ b/core/plugin/loader.cpp @@ -461,6 +461,9 @@ int Registry::commit_(Staged& s, int order) { const auto concurrent = dl_fn(s.handle, "rad_kernel_concurrent"); const auto collective = dl_fn(s.handle, "rad_kernel_collective"); const auto chainable = dl_fn(s.handle, "rad_kernel_chain"); + /* Per row when exported, else the library's own answer: a plugin that ships a device row and + * its host oracle in one library must not have the oracle's status leak onto the device row. */ + const auto kern_ref = dl_fn(s.handle, "rad_kernel_reference"); for (const auto& sr : staged_rows) { KernelRow row; row.info = sr.first; @@ -471,7 +474,7 @@ int Registry::commit_(Staged& s, int order) { const int coll = collective ? collective(sr.second) : 0; row.collective = coll != 0; row.releases_link = coll == 2; - row.reference = p.reference; + row.reference = kern_ref ? kern_ref(sr.second) != 0 : p.reference; row.chain = chainable && chainable(sr.second) != 0; rows_.push_back(row); } diff --git a/core/rad_core.h b/core/rad_core.h index 6951541f..8b6021e9 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -129,6 +129,8 @@ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped = * embedding takes Ram or Vram. */ enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 }; const char* table_placement_name(TablePlacement p); +/* --attn-prefill-fp8's spelling of RAD_ATTN_FP8_* bits: off, qk, pv or both. */ +const char* attn_prefill_fp8_name(int bits); /* --draft-window: how many drafts a step verifies per sequence (core/sched/draft.h). * Fixed every sequence drafts --num-speculative-tokens. * Adaptive that is the ceiling; head depth per step and each sequence's stop follow measured @@ -390,6 +392,8 @@ public: * for drafters that did not ask. */ bool drafter_shared_kv = false; int32_t drafter_pos_offset = 0; + /* A block drafter's shorter block (rad_drafter_short_block), 0 when it serves only its own. */ + int64_t drafter_short_block = 0; /* The declared media encoder (rad_declare_encoder). `modalities == 0` when none: every * text-only program, and every deployment with RadBuildCtx::max_enc_patches 0. @@ -414,7 +418,8 @@ public: * strings point at `agen_str`, as the image generator's do at `gen_str`. */ RadAudioGenDecl audio_gen{}; struct AudioGenStrings { - std::string name, tmpl, tmpl_plain, neg_tmpl; /* "" for an absent template */ + /* "" for an absent template; tmpl_ref and ref_item RadAudioGenDecl's references */ + std::string name, tmpl, tmpl_plain, neg_tmpl, tmpl_ref, ref_item; } 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. */ @@ -456,6 +461,14 @@ public: * region safely through in-order launch; a second lane is a second stream and needs its own. * Two when the architecture declared a buffer rad_buf_concurrent. */ int32_t scratch_regions = 1; + /* Region 1's size when there are two: the largest device scratch of an op the second lane may + * issue. By Ctx::lane1_'s rule 3 such an op touches only rad_buf_concurrent buffers, so an op + * with any other transient buffer never runs there; one naming no transient buffer counts. + * At most scratch_bytes; -1 (a program not built by the Builder) means scratch_bytes. */ + int64_t scratch_bytes_lane1 = -1; + /* The second lane's window (rad_lane1_window_begin): the first and last op handle lane 1 may run; + * -1 when the architecture declared none (concurrent buffers then live for the whole program). */ + int32_t lane1_w0 = -1, lane1_w1 = -1; /* Everything that resolved to nothing, reported whole rather than stopping at the first * failure (spec §3.1). Structured because the domains are reported differently: a device miss @@ -620,11 +633,22 @@ struct SamplingParams { /* The control vector (core/cvec.h): whether this request's steps project the vector found for * this deployment out of the residual stream. The server sets it from the request's - * `control_vector` field (`experimental_speed_projection` is Strata's spelling of the same - * switch), or from the deployment's runtime default when the request names none; it needs no - * reload and leaves the graph untouched. A deployment with no vector refuses `true` at - * admission rather than serving the stock model. */ + * `control_vector` field, or from the deployment's runtime default when the request names + * none. A deployment with no vector refuses `true` at admission. */ bool use_control_vector = false; + /* The windowed no-repeat-ngram ban (core/sample/sampler.h, `sample_ngram_ban`): a token that + * would complete an `ngram_ban_n`-gram already present in the last `ngram_window` tokens of + * the sequence is banned. `ngram_ban_n` 0 is off, the default; `ngram_window` <= 0 searches + * the whole staged history (the un-windowed processor). Unlimited-OCR's generation_config + * asks for 35 and 128 (the model card's document mode uses 1024). */ + int ngram_ban_n = 0; + int ngram_window = 0; + /* The ids exempt from that ban: the reference processor's whitelist + * (SlidingWindowNoRepeatNgramProcessor's `whitelist_token_ids`, whose set is removed from + * the banned set after it is built -- modeling_unlimitedocr.py:359,379). Global token ids, + * duplicates ignored. Empty (the default) is off: the ban is then bit-identical to the + * no-whitelist form. */ + std::vector ngram_whitelist; }; /* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers @@ -741,6 +765,9 @@ struct Config { * element plus a bf16 scale per 64) instead of 16 bits per element, 2.4x fewer bytes over * PCIe. The received sum then differs undetectably, hence a named flag, not a heuristic. */ int tp_wire_exact = 1; /* --tp-wire exact|wht6 */ + /* --tp-attn-split heads|rows: 1 runs a prefill-sized step's attention by rows over the ranks + * (RadBuildCtx::tp_attn_rows). Not bit-identical to the head split, so heads is the default. */ + int tp_attn_rows = 0; /* Smallest all-reduce message, in KiB, that the lossy wire compresses; smaller ones are sent * exact. Compression pays only when the transfer is bandwidth-bound: a decode step's handful * of residual rows costs more to rotate than it saves, while a prefill chunk is far larger. @@ -787,6 +814,11 @@ struct Config { * explicit and bf16 is the default. No "auto": it would always resolve to bf16 and only add * another name. */ std::string kv_cache_dtype = "bf16"; + std::string state_cache_dtype = "f32"; /* --state-cache-dtype: f32 | f16 */ + /* --attn-prefill-fp8 off|qk|pv|both: RAD_ATTN_FP8_* bits, the prefill attention's products + * accepted in e4m3 (RadBuildCtx::attn_prefill_fp8). Lossy, so off is the default. + * attn_prefill_fp8_name() spells it as the flag does. */ + int attn_prefill_fp8 = 0; int64_t host_pool_mib = 0; int64_t host_headroom_mib = 4096; /* --host-headroom-mib: RAM left free for the system at startup */ /* File tier for weights: what fits in neither the VRAM slab nor the pinned host pool is read @@ -881,6 +913,14 @@ struct Config { * VRAM and still decode one token a step. */ int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */ DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */ + /* A block drafter's short block (rad_drafter_short_block) from this many decoding sequences in + * the step just run; 0 never. Ignored without a drafter that declares one. */ + int64_t draft_short_from = 0; /* --draft-short-from */ + + /* --draft-coupling off|on: a linear serial drafter samples its proposals and the sampler + * applies the maximal coupling at the verify (RadBuildCtx::draft_coupling, abi/rad_spechub.h). + * Off by default; on changes which tokens a fixed seed yields, not their law. */ + bool draft_coupling = false; /* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ---------------- * diff --git a/core/runtime/arena.cpp b/core/runtime/arena.cpp index 19dab4c3..e7cecf04 100644 --- a/core/runtime/arena.cpp +++ b/core/runtime/arena.cpp @@ -5,15 +5,18 @@ namespace rad { -int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions) { +int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions, + int64_t scratch_bytes1) { release(); if (plan_bytes < 0 || scratch_bytes < 0 || regions < 1) return RAD_E_INVAL; + if (scratch_bytes1 < 0 || scratch_bytes1 > scratch_bytes) scratch_bytes1 = scratch_bytes; /* Scratch starts on a page boundary, so a workspace gets 4 KiB alignment for at most one * page of padding. */ const int64_t off = align_up(plan_bytes, RAD_ALIGN_UNIT); - const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT); - const int64_t tail = pitch * regions; + const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT); + const int64_t pitch1 = align_up(scratch_bytes1, RAD_ALIGN_UNIT); + const int64_t tail = pitch + pitch1 * (regions - 1); int64_t total = off + tail; /* Never zero bytes: a null base would turn a plan bug into an anonymous segfault. */ @@ -33,6 +36,8 @@ int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions scratch_off_ = off; scratch_bytes_ = scratch_bytes; scratch_pitch_ = pitch; + scratch_bytes1_ = regions > 1 ? scratch_bytes1 : 0; + scratch_pitch1_ = regions > 1 ? pitch1 : 0; scratch_regions_ = regions; return RAD_OK; } @@ -87,8 +92,10 @@ int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out) /* The staging region sits above every buffer, so it is a separate term. */ if (P.arena_stage_bytes > 0 && P.arena_stage_off >= 0) dev_bytes = std::max(dev_bytes, P.arena_stage_off + P.arena_stage_bytes); - int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) + - align_up(P.scratch_bytes, RAD_ALIGN_UNIT) * std::max(P.scratch_regions, 1); + const int64_t s1 = P.scratch_bytes_lane1 < 0 || P.scratch_bytes_lane1 > P.scratch_bytes + ? P.scratch_bytes : P.scratch_bytes_lane1; + int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) + align_up(P.scratch_bytes, RAD_ALIGN_UNIT) + + align_up(s1, RAD_ALIGN_UNIT) * (std::max(P.scratch_regions, 1) - 1); if (total == 0) total = RAD_ALIGN_UNIT; /* Arena::init's floor, for the same reason */ if (dev_out) *dev_out = dev_bytes; if (total_out) *total_out = total; diff --git a/core/runtime/arena.h b/core/runtime/arena.h index 8eb96a00..8aca7f04 100644 --- a/core/runtime/arena.h +++ b/core/runtime/arena.h @@ -25,18 +25,25 @@ public: Arena& operator=(const Arena&) = delete; /* `kind` is a RAD_MEM_* class: RAD_MEM_DEVICE for the device arena, RAD_MEM_HOST for the - * second arena a program with RAD_DOMAIN_HOST buffers gets. `regions` scratch regions of - * `scratch_bytes` each sit at the tail, one per lane. */ - int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1); + * second arena a program with RAD_DOMAIN_HOST buffers gets. `regions` scratch regions sit at the + * tail, one per lane: region 0 of `scratch_bytes`, the others of `scratch_bytes1` (-1: the same; + * Program::scratch_bytes_lane1). */ + int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1, + int64_t scratch_bytes1 = -1); void release(); char* base() const { return base_; } /* Region `r`, or region 0 when the arena holds fewer. */ void* scratch(int r = 0) const { if (!base_) return nullptr; - return base_ + scratch_off_ + (r > 0 && r < scratch_regions_ ? r * scratch_pitch_ : 0); + return base_ + scratch_off_ + + (r > 0 && r < scratch_regions_ ? scratch_pitch_ + (r - 1) * scratch_pitch1_ : 0); } + /* Region 0's size (the program's largest kernel), or region `r`'s. */ int64_t scratch_bytes() const { return scratch_bytes_; } + int64_t scratch_bytes(int r) const { + return r > 0 && r < scratch_regions_ ? scratch_bytes1_ : scratch_bytes_; + } int scratch_regions() const { return scratch_regions_; } int64_t bytes() const { return bytes_; } bool live() const { return base_ != nullptr; } @@ -48,6 +55,8 @@ private: int64_t scratch_off_ = 0; int64_t scratch_bytes_ = 0; int64_t scratch_pitch_ = 0; /* scratch_bytes_ padded to RAD_ALIGN_UNIT */ + int64_t scratch_bytes1_ = 0; /* each region past 0 */ + int64_t scratch_pitch1_ = 0; int scratch_regions_ = 1; }; diff --git a/core/runtime/ctx.cpp b/core/runtime/ctx.cpp index 4dffb3f5..5b21f691 100644 --- a/core/runtime/ctx.cpp +++ b/core/runtime/ctx.cpp @@ -153,13 +153,20 @@ int Ctx::bind_arena() { int64_t dev_bytes = 0, total = 0; arena_plan_bytes(P, &dev_bytes, &total); - RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1))); + RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1), + P.scratch_bytes_lane1)); /* The arena is in no pool and scales with max_tok, so core/mem/vram_budget.cpp charges it by * name rather than leaving it to --gpu-headroom-mib. This log line must agree with that * charge. */ - RAD_INFO("arena: %s device + %d x %s scratch = %s, charged to the VRAM budget before it was " - "split", humanb(dev_bytes).c_str(), arena_.scratch_regions(), - humanb(P.scratch_bytes).c_str(), humanb(total).c_str()); + if (arena_.scratch_regions() > 1) + RAD_INFO("arena: %s device + %s scratch + %s for the second lane = %s, charged to the VRAM " + "budget before it was split", humanb(dev_bytes).c_str(), + humanb(P.scratch_bytes).c_str(), humanb(arena_.scratch_bytes(1)).c_str(), + humanb(total).c_str()); + else + RAD_INFO("arena: %s device + %s scratch = %s, charged to the VRAM budget before it was " + "split", humanb(dev_bytes).c_str(), humanb(P.scratch_bytes).c_str(), + humanb(total).c_str()); if (host_hw > 0) { /* RAD_MEM_HOST_MAPPED, not RAD_MEM_HOST: nothing copies between the two arenas, so device @@ -333,6 +340,8 @@ int Ctx::bind_ops() { p.billed = (oi.op == "all_reduce"); p.collective = p.billed; p.lora_site = oi.lora_site; + p.order = oi.anchor > 0 && (size_t)oi.anchor < P.ops.size() ? P.ops[(size_t)oi.anchor].index + : oi.index; for (const Band& b : oi.bands) band_table_.push_back(b.hi); @@ -908,6 +917,7 @@ int Ctx::lane_join(int from, int to) { RAD_TRY(rad_event_record(lane_ev_[from], fs)); RAD_TRY(rad_event_wait(ts, lane_ev_[from])); scratch_open_[from] = false; /* `to` is now behind every scratch user `from` issued */ + if (from == 1 && to == 0) lane1_pending_ = false; return RAD_OK; } @@ -918,7 +928,7 @@ int Ctx::lane_join(int from, int to) { * field added to RadBatch changes its size: decide whether the key must read it, then update the * size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded * (below). */ -static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 336, +static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 360, "RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on"); static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72, "RadKVGroupBatch changed: check that Ctx::pass_key reads every new field"); @@ -949,6 +959,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const { /* Null on a step with no adapter row, which then issues no adapter op (Ctx::issue_lora): the * two are different passes. The slots themselves are read on the card. */ ptr(b->lora_slot); + /* Zero issues no projection op (RadBatch::control_vector). */ + mix((uint64_t)b->control_vector); for (int g = 0; g < b->n_kv_groups; ++g) { const RadKVGroupBatch& k = b->kv[g]; mix((uint64_t)k.group); ptr(k.slot_mapping); ptr(k.block_table); diff --git a/core/runtime/ctx.h b/core/runtime/ctx.h index ea8bf107..4f9c38da 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -94,6 +94,9 @@ struct OpPlan { bool billed = false; /* Runtime LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */ int32_t lora_site = -1; + /* Its position in the declared order, or its anchor's for a core-appended op: what the second + * lane's window (Program::lane1_w0..lane1_w1) is checked against. */ + int32_t order = 0; }; /* ------------------------------------------------------------------ routing handoff */ @@ -294,6 +297,8 @@ public: void dump_profile() const; /* spec §16, opt-in, with its caveat printed */ const char* step_error() const { return step_fail_.c_str(); } int64_t stream_waits() const { return n_stream_waits_; } + /* Lane 1 has work lane 0 has not joined (lane1_pending_). */ + bool lane1_pending() const { return lane1_pending_; } /* Host synchronisations on the step path. Always zero unless per-op timing is on (spec §16); * tests read it. Teardown's drain is not counted. */ int64_t host_syncs() const { return n_host_syncs_; } @@ -552,6 +557,9 @@ public: /* Backs rad_step_fail(): stops the step like an operand rejection, with the caller's * message. */ int step_fail(const char* what); + /* The device kernel `h` resolved to on this rank ("?" if it resolved none). For log + * attribution only. */ + const char* ip_kernel_name(rad_op h) const; private: [[noreturn]] void fatal_issue(rad_op h, int64_t n, const char* why) const; @@ -578,7 +586,6 @@ private: * byte-compares the two results, finding kernels that are not a function of their inputs, * which a host-vs-device comparison cannot detect. */ void oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd); - const char* ip_kernel_name(rad_op h) const; /* The reference library's host plan for (op, band): the band's own host plan when a reference * library won it, else one resolved from `registry_` on first use. Null when none exists. */ const IssuePlan* oracle_reference(rad_op h, int band); @@ -625,7 +632,8 @@ private: * 3. The buffer planner packs from one linear order, so two lanes can alias arena bytes * through buffers with disjoint declared lifetimes. The architecture passes every buffer * its second lane touches to `rad_buf_concurrent`, which makes it live for the whole - * program. + * program, or, where the architecture declares the second lane's window + * (rad_lane1_window_begin / _end), across the window and its own declared uses. * * 4. A slice must land in the same bucket-table band as the whole, or it picks a kernel with * a different summation order and silently changes output. `--debug-graph` prints a model's @@ -647,6 +655,9 @@ private: bool own_lane1_ = false; int lane_ = 0; RadEvent lane_ev_[2] = { nullptr, nullptr }; + /* An op was issued on lane 1 since lane 1 was last joined into lane 0; lane 0 joins it before + * an op outside the second lane's window (Ctx::issue_body). */ + bool lane1_pending_ = false; /* The last device op on each lane that touched host-domain memory. A host op runs at issue on * this thread and must be ordered behind every earlier device op that touched the host arena; * on each lane those complete no later than the last one. So a device op with a host-domain diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index 796ea0a6..9fdb9a2d 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -592,6 +592,25 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { ? "has no host kernel for this band, and the placement planner put " "it on the host anyway" : "has no device kernel for this band"); + /* The second lane's window (rad_lane1_window_begin): its concurrent buffers are live only across + * it, so lane 1 runs nothing outside it, and lane 0 joins lane 1 before it runs an op outside + * it, on either side: a transient of such an op may share bytes with a concurrent buffer. */ + if (program_ && program_->lane1_w1 >= 0) { + const bool outside = p.order < program_->lane1_w0 || p.order > program_->lane1_w1; + if (lane_ == 1 && outside) + return abort_step_msg(h, RAD_E_STATE, + fmt("issued on the second lane outside its declared window (ops " + "%d..%d, this one %d): the buffers it may touch there are " + "live only across the window", + (int)program_->lane1_w0, (int)program_->lane1_w1, (int)p.order)); + if (lane_ == 0 && lane1_pending_ && outside) { + const int js = lane_join(1, 0); + if (js < 0) + return abort_step_msg(h, js, "joining the second lane outside its window failed"); + } + } + if (lane_ == 1) lane1_pending_ = true; + /* The row's DIV on the ranged parameter held at the band's upper bound, maybe not here. */ if (ip.ranged_div > 1 && n % ip.ranged_div != 0) return abort_step_msg(h, RAD_E_SHAPE, @@ -884,7 +903,18 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { * correctness. That also covers lane 0 before lane 1 exists, since a lane built later has * nothing ordering it behind lane 0's earlier work. */ if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST && arena_.scratch_regions() > 1) { - /* Per-lane regions: nothing to order. */ + /* Per-lane regions: nothing to order. Region 1 holds what an op the second lane may issue + * asked for at declare (Program::scratch_bytes_lane1); a larger request there comes from an + * op with a transient buffer outside rad_buf_concurrent, which breaks Ctx::lane1_'s rule 3 + * in its buffers too, so it is refused by name rather than let overrun the region. */ + if (ip.args.scratch_bytes > arena_.scratch_bytes(lane_)) { + return abort_step_msg(h, RAD_E_SCRATCH, + fmt("kernel %s at n=%lld asks for %lld bytes of scratch on lane %d, whose region " + "holds %lld: an op on the second lane may touch only buffers named to " + "rad_buf_concurrent (Ctx::lane1_ rule 3)", + ip.row && ip.row->info ? ip.row->info->name : "?", (long long)n, + (long long)ip.args.scratch_bytes, lane_, (long long)arena_.scratch_bytes(lane_))); + } ip.args.scratch = scratch_take(lane_, ip.args.scratch_bytes); } else if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST) { ip.args.scratch = scratch_take(0, ip.args.scratch_bytes); @@ -1058,7 +1088,7 @@ void* Ctx::scratch_take(int region, int64_t bytes) { constexpr int64_t kAlign = 256; const int64_t need = (bytes + kAlign - 1) / kAlign * kAlign; int64_t off = scratch_cur_[region]; - if (off + need > arena_.scratch_bytes()) off = 0; + if (off + need > arena_.scratch_bytes(region)) off = 0; scratch_cur_[region] = off + need; return (char*)arena_.scratch(region) + off; } diff --git a/core/runtime/kvbind.cpp b/core/runtime/kvbind.cpp index 406e77ab..44f57716 100644 --- a/core/runtime/kvbind.cpp +++ b/core/runtime/kvbind.cpp @@ -32,6 +32,7 @@ void bind_kv_pools(const Program& p, const std::functionkind) { case RAD_KV_FULL: case RAD_KV_WINDOW: + case RAD_KV_RING: b.rank = 4; b.shape[0] = gp->n_blocks; b.shape[1] = d.n_head_kv; diff --git a/core/runtime/tierexec.cpp b/core/runtime/tierexec.cpp index 76f005b3..2c36c329 100644 --- a/core/runtime/tierexec.cpp +++ b/core/runtime/tierexec.cpp @@ -226,8 +226,18 @@ int TierExec::device_init() { bool ev = rad_event_create(&ev_compute_) == RAD_OK && rad_event_create(&ev_copy_) == RAD_OK && rad_event_create(&ev_restore_) == RAD_OK; for (int i = 0; i < kRing && ev; ++i) ev = rad_event_create(&ring_ev_[i]) == RAD_OK; - if (verify_rep_) vrep_ = (char*)rad_dev_alloc(copy_idx_ * rep_bytes_, RAD_MEM_HOST_PINNED); - if (!stage_ || !idx_dev_ || !idx_host_ || !ev || (verify_rep_ && !vrep_)) { + /* The verify scratch is a diagnostic's: without it the replicated groups go unchecked, and + * the tiers run as they would without RADIANCE_DEBUG_TIER_VERIFY. */ + if (verify_rep_) { + vrep_ = (char*)rad_dev_alloc(copy_idx_ * rep_bytes_, RAD_MEM_HOST_PINNED); + if (!vrep_) { + RAD_WARN("kv tiers: RADIANCE_DEBUG_TIER_VERIFY: no pinned host memory (%s) for this " + "rank's copy of the replicated groups, so they are not compared", + humanb(copy_idx_ * rep_bytes_).c_str()); + verify_rep_ = false; + } + } + if (!stage_ || !idx_dev_ || !idx_host_ || !ev) { release_device(); return RAD_E_NOMEM; } diff --git a/core/sample/host_ref.cpp b/core/sample/host_ref.cpp index 153fc873..b0153f49 100644 --- a/core/sample/host_ref.cpp +++ b/core/sample/host_ref.cpp @@ -12,6 +12,7 @@ #include #include #include +#include namespace rad { @@ -51,12 +52,6 @@ static uint64_t stream_key(uint32_t stream) { } } -/* rad_sample_uniform01's bits before the float conversion: one splitmix64 round over - * ((seed ^ key) * golden ratio + pos), cheap and stateless enough for a kernel. */ -uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream) { - return rad_sample_splitmix64((seed ^ stream_key(stream)) * 0x9E3779B97F4A7C15ull + pos); -} - float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream) { /* 24 bits: 32 bits divided by 2^32 can round to 1.0f, which walks off the end of an inverse * CDF. Calls rad_sample_uniform01 itself so host and device cannot drift apart. */ @@ -526,8 +521,48 @@ int32_t host_argmax(const float* logits, int64_t n_vocab) { return (int32_t)best; } -/* ================================================================== the chain */ +void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n, + int32_t window, const uint32_t* whitelist, int64_t wl_words) { + if (n <= 0 || !history || n_history < (int64_t)n) return; + const int64_t len = n_history; + const int64_t win = (window > 0 && window < len) ? window : len; + const int64_t start = len - win, end = len - n + 1; + if (end <= start) return; + const int64_t plen = (int64_t)n - 1, p0 = len - plen; + /* The set of tokens a continuation would complete an n-gram with, as the reference builds it: + * every n-gram in the window whose first n-1 tokens equal the current prefix contributes the + * token after them. */ + std::unordered_set banned; + for (int64_t idx = start; idx < end; ++idx) { + bool match = true; + for (int64_t j = 0; j < plen; ++j) { + if (history[idx + j] != history[p0 + j]) { match = false; break; } + } + if (match) banned.insert(history[idx + plen]); + } + + /* The reference's `banned.difference_update(self.whitelist)`, before any -inf: a token whose + * whitelist bit is set is never banned. A bit past the plane is not set, so a token outside + * it stays banned, as an id the reference's set does not contain. */ + if (whitelist && wl_words > 0) { + for (auto it = banned.begin(); it != banned.end();) { + const int64_t id = *it; + if (id >= 0 && (id >> 5) < wl_words && + (whitelist[(size_t)(id >> 5)] >> ((uint32_t)id & 31u)) & 1u) + it = banned.erase(it); + else + ++it; + } + } + + if (banned.empty()) return; + s.sorted = false; /* a -infinity candidate belongs after every finite one */ + for (Candidate& c : s.c) + if (banned.count(c.id) != 0) c.logit = -INFINITY; +} + +/* ================================================================== the chain */ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in, ChainOrder order) { /* Penalties first in both orders: they act on raw logits, the cuts on probabilities. */ @@ -547,6 +582,11 @@ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRe in.dry_breakers ? *in.dry_breakers : kNone); } + /* The n-gram ban, after the penalties and before the greedy split: the device chain issues it + * there, so a greedy request sees the same masked distribution. Off at ngram_ban_n 0. */ + host_ngram_ban(s, in.history, in.n_history, sp.ngram_ban_n, sp.ngram_window, + in.ngram_whitelist, in.ngram_whitelist_words); + /* Greedy skips the chain: penalties -> mask -> argmax. Temperature 0 collapses every other * logit to -inf, so a mask applied after it could leave nothing. */ if (sp.greedy()) { diff --git a/core/sample/host_ref.h b/core/sample/host_ref.h index 787309a5..9436fb57 100644 --- a/core/sample/host_ref.h +++ b/core/sample/host_ref.h @@ -71,7 +71,6 @@ enum : uint32_t { RAD_RNG_XTC = 1 /* XTC's "does this fire at all" coin */ }; -uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream); /* Uniform in [0,1) with 24 bits, the most a float resolves; more would let host and device * disagree in the last place. */ float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream); @@ -177,6 +176,19 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history, void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep, uint64_t seed, uint64_t pos); +/* The windowed no-repeat-ngram ban (`sample_ngram_ban`, Unlimited-OCR's + * SlidingWindowNoRepeatNgramProcessor): a candidate whose token would complete an `n`-gram the + * last `window` tokens of `history` already contain gets -infinity. `n` <= 0 is off, `window` <= 0 + * is the whole history. It runs after the penalties and DRY and before every cut, so the greedy + * path sees it too. + * + * `whitelist` is the reference's whitelist (a SET bit means exempt from the ban, the same plane + * form as host_mask's, word w bit b covering token 32w + b): ids removed from the banned set + * before anything is written, as `banned.difference_update(self.whitelist)` does. Null or zero + * words is off -- the reference's empty whitelist, the default serving form. */ +void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n, + int32_t window, const uint32_t* whitelist = nullptr, int64_t wl_words = 0); + /* The grammar mask. One bit per token, set means admissible; a cleared bit sets the logit to -inf * instead of removing the candidate, so nothing downstream is renumbered. `n_words` is * ceil(n_vocab/32). */ @@ -203,7 +215,8 @@ constexpr int64_t kSampleCandidates = 1024; constexpr int64_t kSampleMergeCandidates = 4096; enum class ChainOrder { - Radiance = 0, /* penalties, DRY, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */ + /* penalties, DRY, n-gram ban, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */ + Radiance = 0, LlamaCpp = 1 /* penalties, DRY, top-k, typical, top-p, min-p, XTC, temperature, pick */ }; @@ -215,6 +228,10 @@ struct HostRefInput { int64_t total_context = 0; /* DRY's clamp; 0 means use n_history */ const uint32_t* bitmask = nullptr; /* grammar mask, or null */ int64_t n_words = 0; + /* The n-gram ban's whitelist bitmask (a SET bit exempts a token, host_ngram_ban), null = + * no exemptions. */ + const uint32_t* ngram_whitelist = nullptr; + int64_t ngram_whitelist_words = 0; uint64_t pos = 0; /* output position: the RNG's second coordinate */ const DryBreakers* dry_breakers = nullptr; /* null runs DRY with no breakers */ /* The chain's candidate width (SamplerConfig::max_candidates): top-k narrows every row to diff --git a/core/sample/mtp_couple_evidence.h b/core/sample/mtp_couple_evidence.h new file mode 100644 index 00000000..7c9c9604 --- /dev/null +++ b/core/sample/mtp_couple_evidence.h @@ -0,0 +1,44 @@ +/* mtp_couple_evidence.h -- what the completed-verify log line may claim. + * + * The line reports a coupled verify only when the build that staged bound rows belongs to the step + * whose wait just returned, and counts only sequences still live after that wait. It reads + * Sampler::couple_build(), the snapshot build_step froze, because the drafter's build_greedy + * clears staged_any_couple() before the wait. The op's domain is printed so a host reference row + * is not read as a device verify. + * + * A pure function of the snapshot, a liveness predicate and the domain, so it is tested without + * an Engine (tests/sample_test.cpp). + */ +#pragma once + +#include "sampler.h" + +#include + +namespace rad { + +struct MtpCoupleEvidence { + int64_t rows = 0; /* bound rows of sequences still live after the wait */ + bool device = false; /* the op that ran is a device op */ + std::string seqs; /* those sequences, comma separated, in build order */ +}; + +/* `live(seq)` answers whether the sequence is still Running; the engine passes a predicate over + * Scheduler::running(), the tests a set. Empty (rows == 0) when the snapshot is not this step's, + * or nothing it staged is still live. */ +template +MtpCoupleEvidence mtp_couple_evidence(const Sampler::CoupleBuild& b, int64_t step, int domain, + Live&& live) { + MtpCoupleEvidence e; + if (b.step != step) return e; + e.device = domain == RAD_DOMAIN_DEVICE; + for (const auto& s : b.seqs) + if (live(s.first)) { + e.rows += s.second; + if (!e.seqs.empty()) e.seqs += ","; + e.seqs += std::to_string(s.first); + } + return e; +} + +} // namespace rad diff --git a/core/sample/sampler.cpp b/core/sample/sampler.cpp index 3f320b83..6ed16c0d 100644 --- a/core/sample/sampler.cpp +++ b/core/sample/sampler.cpp @@ -133,6 +133,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { } cfg_ = cfg; + couple_ = cfg.draft_coupling; if (cfg_.n_vocab_local <= 0) cfg_.n_vocab_local = cfg_.n_vocab / cfg_.world_size; /* The staged mask covers this rank's shard; the grammar's covers the whole vocabulary. @@ -178,7 +179,21 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { /* One byte per history token, nonzero where the token is a whole DRY sequence breaker (never * penalised). Resolved on the host, which has the vocabulary. */ buf_brk_ = decl("sampler.dry_breakers", RAD_U8, rows, cfg_.max_hist, RAD_BUF_PERSIST); + /* The n-gram ban's per-row {n-gram length, window}. Its own tiny plane because the params row + * is the fixed RadSampleParams wire format every sampler op shares. */ + buf_ngram_ = decl("sampler.ngram", RAD_I32, rows, 2, RAD_BUF_PERSIST); + /* The ban's whitelist bitmask, this rank's shard, shaped like the mask plane: a SET bit + * exempts that column. The ban op indexes it by the sampled row, not by mask_row. */ + buf_ngram_wl_ = decl("sampler.ngram_wl", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST); buf_mask_ = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST); + /* The coupled state plane, one row per sampled position, PERSIST because an upload fills it + * before the run phase issues anything. A round's state belongs to the verify row that + * follows it, so it rides the sampler's row array. */ + if (couple_) { + buf_couple_ = decl("sampler.mtp_couple", RAD_U32, rows, RAD_MTP_COUPLE_STATE_WORDS, + RAD_BUF_PERSIST); + if (!buf_couple_) return RAD_E_NOMEM; + } buf_cand_i_ = decl("sampler.cand_idx", RAD_I32, rows, ncand, RAD_BUF_TRANSIENT); buf_cand_v_ = decl("sampler.cand_val", RAD_F32, rows, ncand, RAD_BUF_TRANSIENT); if (vocab_parallel()) { @@ -197,7 +212,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows, lp_width() * cfg_.world_size, RAD_BUF_PERSIST); - if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ || + if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_ngram_ || + !buf_ngram_wl_ || !buf_mask_ || !buf_cand_i_ || !buf_cand_v_ || !buf_lp_ || (vocab_parallel() && (!buf_pairs_ || !buf_gather_ || !buf_lp_g_))) { RAD_ERR("sampler: a staging buffer failed to declare"); @@ -239,6 +255,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { op_penalties_ = op_vocab_off("sample_penalties"); op_dry_ = op_vocab_off("sample_dry"); + op_ngram_ban_ = op_vocab_off("sample_ngram_ban"); op_temp_ = op_vocab("sample_temp"); op_mask_ = op_vocab("sample_mask"); op_topk_ = op_vocab_off("sample_topk"); @@ -249,6 +266,19 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { op_typical_ = op_cand("sample_typical"); op_xtc_ = op_cand("sample_xtc"); op_pick_ = op_cand("sample_pick"); + /* The coupled verify, over the candidate plane the pick read. A row with no bound state keeps + * the pick's token; a step with no bound row does not issue it. */ + if (couple_) { + RadParam pc[3] = { + RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr }, + RadParam{ "n_cand", RAD_P_INT, (long long)ncand, 0, nullptr }, + RadParam{ "n_vocab", RAD_P_INT, (long long)cfg_.n_vocab, 0, nullptr }, + }; + op_couple_ = rad_decl_op(b, "mtp_couple_verify", pc, 3, nullptr, 0); + if (!op_couple_) return RAD_E_NOKERNEL; + /* No rad_op_reads: the other sampler ops declare no lists, and a list on this op alone + * would narrow the candidate planes' lifetime to it and refuse the first sample_topk. */ + } /* The temperature kernel again, over the candidate plane: `n_vocab` is only a row length to * it, so the candidate width works. */ { @@ -308,6 +338,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { int Sampler::stage_alloc() { const int64_t rows = rows_for(cfg_); + /* At most one entry per request; reserved here so a coupled step never allocates. */ + couple_build_.seqs.reserve((size_t)cfg_.max_seqs); /* Pinned: uploaded every step, and a pageable source turns the async copy into a staged one * with a host bounce (spec §8). */ @@ -320,7 +352,14 @@ int Sampler::stage_alloc() { greedy_ready_ = false; hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED); brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED); + ngram_stage_ = (int32_t*)rad_dev_alloc(rows * 2 * 4, RAD_MEM_HOST_PINNED); + ngram_wl_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED); mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED); + /* The coupled rows, pinned: uploaded every coupled step, and a pageable source would turn the + * async copy into a staged one with a host bounce (spec §8). */ + if (couple_) + couple_stage_ = (RadMtpCoupleState*)rad_dev_alloc( + rows * (int64_t)sizeof(RadMtpCoupleState), RAD_MEM_HOST_PINNED); /* Logprobs readback; only rank 0 reads it. */ if (cfg_.rank == 0) { @@ -337,10 +376,10 @@ int Sampler::stage_alloc() { } if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ || - !mask_stage_) { + !ngram_stage_ || !ngram_wl_stage_ || !mask_stage_ || (couple_ && !couple_stage_)) { RAD_ERR("sampler: could not pin %s of staging", humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 + - mask_words_ * 4)).c_str()); + mask_words_ * 8 + 8)).c_str()); stage_free(); return RAD_E_NOMEM; } @@ -353,7 +392,11 @@ void Sampler::stage_free() { if (late_stage_) rad_dev_free(late_stage_, RAD_MEM_HOST_PINNED); if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED); if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED); + if (ngram_stage_) rad_dev_free(ngram_stage_, RAD_MEM_HOST_PINNED); + if (ngram_wl_stage_) rad_dev_free(ngram_wl_stage_, RAD_MEM_HOST_PINNED); if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED); + if (couple_stage_) rad_dev_free(couple_stage_, RAD_MEM_HOST_PINNED); + couple_stage_ = nullptr; if (lp_host_) rad_dev_free(lp_host_, RAD_MEM_HOST_PINNED); if (lp_ci_host_) rad_dev_free(lp_ci_host_, RAD_MEM_HOST_PINNED); if (lp_cv_host_) rad_dev_free(lp_cv_host_, RAD_MEM_HOST_PINNED); @@ -366,6 +409,8 @@ void Sampler::stage_free() { cur_stage_ = nullptr; hist_stage_ = nullptr; brk_stage_ = nullptr; + ngram_stage_ = nullptr; + ngram_wl_stage_ = nullptr; mask_stage_ = nullptr; } @@ -373,9 +418,9 @@ Sampler::~Sampler() { stage_free(); } /* ================================================================== admission */ -/* Whether the two history stages run, shared by admission, request setup and step staging so - * they agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY - * also requires a positive multiplier; a negative one would reward repetition. */ +/* Whether the history stages run, shared by admission, request setup and step staging so they + * agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY also + * requires a positive multiplier; a negative one would reward repetition. */ static bool penalties_on(const SamplingParams& sp) { return sp.penalty_last_n != 0 && (sp.rep_penalty != 1.0f || sp.freq_penalty != 0.0f || sp.pres_penalty != 0.0f); @@ -385,6 +430,14 @@ static bool dry_on(const SamplingParams& sp) { return sp.dry_multiplier > 0.0f && sp.dry_base >= 1.0f && sp.dry_penalty_last_n != 0; } +/* The windowed no-repeat-ngram ban: n-gram length 0 is off (the request default). A window <= 0 + * is legal and means the whole staged history, the un-windowed processor; it is not a separate + * switch, because the reference's windowed form is what the model ships and a ban with no window + * is still a ban. */ +static bool ngram_ban_on(const SamplingParams& sp) { + return sp.ngram_ban_n > 0; +} + int Sampler::check_request(const SamplingParams& sp, std::string* why) const { auto refuse = [&](const char* what, int st) { if (why) *why = what; @@ -418,6 +471,12 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const { /* The DRY kernels read an allowed length below 1 as 2; refused rather than rewritten. */ if (dry_on(sp) && sp.dry_allowed_length < 1) return refuse("dry_allowed_length must be >= 1", RAD_E_INVAL); + /* The n-gram ban: an n-gram shorter than 2 is a single-token ban, which the reference defines + * (an empty prefix) and this chain implements, so 1 is accepted. A negative n or window has no + * meaning; window 0 is the whole staged history. */ + if (sp.ngram_ban_n < 0) return refuse("ngram_ban_n is negative", RAD_E_INVAL); + if (sp.ngram_window < 0) + return refuse("ngram_window is negative (0 searches the whole history)", RAD_E_INVAL); if (sp.n_probs > RAD_MAX_LOGPROBS) { if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) + " logprobs alternatives may be asked for"; @@ -457,6 +516,7 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const { if (!missing) missing = need(!sp.greedy() && sp.temp_last, op_temp_late_, "sample_temp (over the candidates, for temperature last)"); if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry"); + if (!missing) missing = need(ngram_ban_on(sp), op_ngram_ban_, "sample_ngram_ban"); if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_, "sample_mask"); if (!missing) missing = need(penalties_on(sp), op_penalties_, "sample_penalties"); @@ -573,7 +633,21 @@ bool Sampler::speculation_fixed(uint64_t req_id) const { /* ================================================================== the step path */ -int Sampler::build_step(const std::vector& reqs) { +/* Every state must name this request and its own round: one from another request or round would + * couple against a Q this step never drew. */ +int Sampler::set_mtp_couple(uint64_t req_id, const RadMtpCoupleState* states, int n) { + if (!couple_ || n < 0 || n > RAD_MTP_COUPLE_MAX_ROUNDS || (n && !states)) return RAD_E_STATE; + const auto it = seqs_.find(req_id); + if (it == seqs_.end()) return RAD_E_NOTFOUND; + for (int i = 0; i < n; ++i) + if (states[i].draw.seq != req_id || states[i].round != i + 1) return RAD_E_STATE; + SeqState& s = it->second; + for (int i = 0; i < n; ++i) s.couple[i] = states[i]; + s.couple_n = n; + return RAD_OK; +} + +int Sampler::build_step(const std::vector& reqs, int64_t step) { if (!declared_) return RAD_E_STATE; const auto t_build = std::chrono::steady_clock::now(); @@ -581,8 +655,15 @@ int Sampler::build_step(const std::vector& reqs) { n_seq_ = 0; any_brk_ = false; any_late_ = false; + any_ngram_ = false; + any_ngram_wl_ = false; + any_couple_ = false; cur_stage_ = params_stage_; lp_rows_.clear(); + /* The evidence snapshot this build owns; build_greedy never touches it. */ + couple_build_.step = step; + couple_build_.rows = 0; + couple_build_.seqs.clear(); /* DRY's host half for one row whose history `h[0, take)` is staged. Over the window the * kernel uses (the tail of the row, `dry_penalty_last_n` long when positive) it computes the @@ -635,6 +716,7 @@ int Sampler::build_step(const std::vector& reqs) { const int64_t n_total = n_prompt + n_out; const bool pen = penalties_on(sp); const bool dry = dry_on(sp); + const bool ngram = ngram_ban_on(sp); auto it = seqs_.find(r->id); SeqState* st = it == seqs_.end() ? nullptr : &it->second; @@ -669,6 +751,30 @@ int Sampler::build_step(const std::vector& reqs) { if (walk && k > 0 && !dead && gr->accept_token(r->draft[k - 1]) < 0) dead = true; if (budget && k > 0) think.push(sp.reasoning, r->draft[k - 1]); const int64_t row = n_seq_++; + /* Row k verifies draft k against the state its round left. A row with no bound state + * (the bonus row, a greedy row, an uncoupled step) gets a zeroed one, and the verify + * leaves the pick's token alone. */ + if (couple_) { + couple_stage_[row] = RadMtpCoupleState{}; + const auto sit = seqs_.find(r->id); + if (sit != seqs_.end() && !sp.greedy() && r->draft && k + 1 < n_pos && + k < sit->second.couple_n) { + const RadMtpCoupleState& c = sit->second.couple[k]; + /* Same request and seed, this row's round, position and proposed token + * (rad_mtp_couple_binds); anything else is a stale state from another step. */ + if (rad_mtp_couple_binds(c, r->id, sp.seed, (uint64_t)n_out, k, r->draft[k], + cfg_.n_vocab)) { + couple_stage_[row] = c; + any_couple_ = true; + ++couple_build_.rows; + auto& q = couple_build_.seqs; + size_t j = 0; + while (j < q.size() && q[j].first != r->id) ++j; + if (j == q.size()) q.emplace_back(r->id, 1); + else ++q[j].second; + } + } + } DeviceSampleParams& p = params_stage_[row]; std::memset(&p, 0, sizeof p); @@ -695,6 +801,26 @@ int Sampler::build_step(const std::vector& reqs) { p.dry_penalty_last_n = sp.dry_penalty_last_n; p.mask_row = -1; + /* The n-gram ban's pair, staged for every row so a row that turns it off cannot inherit + * its predecessor's values. */ + ngram_stage_[2 * row] = (int32_t)sp.ngram_ban_n; + ngram_stage_[2 * row + 1] = (int32_t)sp.ngram_window; + + /* The ban's whitelist, cut to this rank's shard like the grammar mask (shard_mask): + * global ids outside it exempt nothing here. Every row that runs the ban gets its + * words freshly written -- the plane is uploaded whole with the ban, so a row must + * never read another request's stale exemptions. */ + if (ngram) { + uint32_t* w = ngram_wl_stage_ + row * mask_words_; + std::memset(w, 0, (size_t)mask_words_ * 4); + for (int32_t id : sp.ngram_whitelist) { + const int64_t at = (int64_t)id - cfg_.vocab_off; + if (at < 0 || at >= cfg_.n_vocab_local) continue; + w[at >> 5] |= 1u << (uint32_t)(at & 31); + any_ngram_wl_ = true; + } + } + /* Greedy over a split vocabulary is a top-1 chain row, not an argmax: sample_argmax * writes a column of this rank's shard, not a token id. Top-k plus the merge produce * global ids, and the pick over one candidate is deterministic. A greedy row asking @@ -723,12 +849,14 @@ int Sampler::build_step(const std::vector& reqs) { any_late_ = true; } - /* History for the penalties and DRY, staged only for rows that run one of them: - * prompt, output so far and, at draft position k, the k drafts before it (they are - * emitted only if accepted, as one token at a time). Oldest first, truncated to + /* History for the penalties, DRY and the n-gram ban, staged only for rows that run one + * of them: prompt, output so far and, at draft position k, the k drafts before it (they + * are emitted only if accepted, as one token at a time). Oldest first, truncated to * max_hist; penalty_last_n still decides how much counts. Each row owns its row of the - * plane, so hist_off stays 0. */ - if (pen || dry) { + * plane, so hist_off stays 0. The n-gram ban's own window is `ngram_window`, applied to + * this span, so the reference's update order holds at a verify: position k sees the + * drafts before it, as the processor would after emitting them. */ + if (pen || dry || ngram) { const int64_t len = n_total + k; const int64_t take = std::min(len, cfg_.max_hist); int32_t* h = hist_stage_ + row * cfg_.max_hist; @@ -741,6 +869,9 @@ int Sampler::build_step(const std::vector& reqs) { p.hist_len = (int32_t)take; if (pen) p.flags |= RAD_SP_PENALTY; if (dry && stage_dry(p, h, take, brk, row)) p.flags |= RAD_SP_DRY; + /* A row whose history is shorter than its n-gram has nothing to ban (the reference + * skips it too), so the op is issued only when some row has a full n-gram. */ + if (ngram && take >= sp.ngram_ban_n) any_ngram_ = true; } if (gr && !dead && gr->constrains()) { @@ -881,7 +1012,17 @@ int Sampler::build_greedy(int64_t n) { n_seq_ = n; any_brk_ = false; any_late_ = false; + any_ngram_ = false; + any_ngram_wl_ = false; + any_couple_ = false; cur_stage_ = greedy_stage_; + /* A drafter's rows run the argmax only, so the n-gram plane is cleared: `run` reads it from + * the staging, and a stale pair from an earlier request's build must not issue the ban over + * history that was not staged this step. The exemption plane needs no clear: `run` uploads + * it only beside an issued ban, every row that runs the ban has its words rewritten in full + * by the build that staged the pair (build_step), and rows below a zeroed pair are skipped + * by the op before they read a word. */ + std::memset(ngram_stage_, 0, (size_t)cap * 2 * sizeof(int32_t)); if (greedy_ready_) return RAD_OK; for (int64_t i = 0; i < cap; ++i) { DeviceSampleParams& p = greedy_stage_[i]; @@ -904,7 +1045,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { const RadStream s = rad_stream(c); bool any_mask = false, any_greedy = false, any_chain = false; - bool any_penalty = false, any_dry = false, any_xtc = false; + bool any_penalty = false, any_dry = false, any_xtc = false, any_ngram = false; bool any_topp = false, any_minp = false, any_typ = false, any_temp = false; for (int64_t i = 0; i < n_seq_; ++i) { const DeviceSampleParams& p = cur_stage_[i]; @@ -912,6 +1053,11 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { any_penalty |= (p.flags & RAD_SP_PENALTY) != 0; any_dry |= (p.flags & RAD_SP_DRY) != 0; any_xtc |= (p.flags & RAD_SP_XTC) != 0; + /* The pair plane is read directly, not through cur_stage_: it is per-step staging the + * LAST builder filled (build_step writes a row's pair, build_greedy zeroes every pair), + * so it agrees with cur_stage_ by builder contract. A new builder must keep that + * contract: stage the pair with the params, zero it with the greedy ones. */ + any_ngram |= ngram_stage_[2 * i] > 0; if (p.flags & RAD_SP_GREEDY) any_greedy = true; else { any_chain = true; @@ -941,21 +1087,34 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { if (late) RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_, n_seq_ * (int64_t)sizeof(DeviceSampleParams), s)); - if (any_penalty || any_dry) + if (any_penalty || any_dry || any_ngram) RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_hist_), hist_stage_, n_seq_ * cfg_.max_hist * 4, s)); const bool pass_brk = any_dry && any_brk_; if (pass_brk) RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_brk_), brk_stage_, n_seq_ * cfg_.max_hist, s)); + /* The ban's whitelist rides with the ban, and only a row that runs the ban reads it. */ + const bool pass_wl = any_ngram && any_ngram_wl_; + if (any_ngram) + RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_ngram_), ngram_stage_, + n_seq_ * 2 * (int64_t)sizeof(int32_t), s)); + if (pass_wl) + RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_ngram_wl_), ngram_wl_stage_, + n_seq_ * mask_words_ * 4, s)); if (any_mask) RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_mask_), mask_stage_, n_seq_ * mask_words_ * 4, s)); + if (any_couple_) + RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_couple_), couple_stage_, + n_seq_ * (int64_t)sizeof(RadMtpCoupleState), s)); const RadOperand o_logits = opd_rows(logits, n_seq_); const RadOperand o_params = opd_rows(buf_params_, n_seq_); const RadOperand o_hist = opd_rows(buf_hist_, n_seq_); const RadOperand o_brk = opd_rows(buf_brk_, n_seq_); + const RadOperand o_ngram = opd_rows(buf_ngram_, n_seq_); + const RadOperand o_ngram_wl = opd_rows(buf_ngram_wl_, n_seq_); const RadOperand o_mask = opd_rows(buf_mask_, n_seq_); const RadOperand o_ci = opd_rows(buf_cand_i_, n_seq_); const RadOperand o_cv = opd_rows(buf_cand_v_, n_seq_); @@ -983,6 +1142,17 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { if (any_dry) RAD_TRY(issue(op_dry_, { o_logits, o_params, o_hist, pass_brk ? o_brk : opd_none() })); + /* The windowed no-repeat-ngram ban (Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor), + * after the penalties and before every cut: a banned logit is -infinity for the greedy argmax + * below as well as for the chain, which is the reference processor's effect on the + * distribution. Off (the default) the op is not issued at all, so a request without it + * samples exactly as before. */ + /* The whitelist operand is passed only when some staged row carries exemptions; absent + * means nothing is exempt, the reference's empty whitelist and the bit-identical default. */ + if (any_ngram) + RAD_TRY(issue(op_ngram_ban_, { o_logits, o_params, o_hist, o_ngram, + pass_wl ? o_ngram_wl : opd_none() })); + /* Greedy rows take the argmax after penalties and the mask. In a mixed batch both the argmax * and the chain run over the whole batch: the argmax writes every row, then the candidate * stages skip RAD_SP_GREEDY rows so the pick overwrites only chain rows. One extra logits @@ -1027,6 +1197,12 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { RAD_TRY(issue(op_temp_late_, { o_cv, opd_rows(buf_params_late_, n_seq_) })); RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok })); + /* After the pick, over the same plane: a coupled row replaces the pick's token and an unbound + * row keeps it. The issued step is recorded for the evidence line. */ + if (any_couple_) { + RAD_TRY(issue(op_couple_, { o_ci, o_cv, o_params, opd_rows(buf_couple_, n_seq_), o_tok })); + couple_issued_step_ = couple_build_.step; + } /* Copy the logprobs rows to the host behind the pick, on rank 0 only (collect_step asks * it): the summary and the candidate planes, which logprobs_for reads when the summary lacks diff --git a/core/sample/sampler.h b/core/sample/sampler.h index 87c1c65a..5eb8e254 100644 --- a/core/sample/sampler.h +++ b/core/sample/sampler.h @@ -9,6 +9,7 @@ * Chain order (reordering changes which tokens survive): * * penalties (repetition / frequency / presence, then DRY) + * the windowed no-repeat-ngram ban * temperature * the grammar mask * top-k @@ -47,6 +48,9 @@ * sample_penalties M(range) n_vocab vocab_off? logits, params, history -> logits (inout) * sample_dry M(range) n_vocab vocab_off? logits, params, history, breakers? * -> logits (inout) + * sample_ngram_ban M(range) n_vocab vocab_off? logits, params, history, ngram, + * whitelist? + * -> logits (inout) * sample_temp M(range) n_vocab logits, params -> logits (inout) * sample_mask M(range) n_vocab logits, params, bitmask -> logits (inout) * sample_topk M(range) n_vocab vocab_off? logits, params -> cand_idx, cand_val, @@ -64,13 +68,16 @@ * a verify. `params` is [M] DeviceSampleParams rows. `history` is [M, max_hist] int32 global * token ids, row m addressed by its hist_off/hist_len. `breakers` is [M, max_hist] uint8 beside * it, nonzero where that token is a whole DRY sequence breaker. `bitmask` is [M, mask_words] - * uint32, addressed by the row's mask_row. `vocab_off` is this rank's first vocabulary row, + * uint32, addressed by the row's mask_row. The ban's `whitelist` is a [M, mask_words] uint32 + * bitmask (a SET bit exempts that column from the ban) addressed by the row itself, absent when + * no staged row carries one. `vocab_off` is this rank's first vocabulary row, * declared only when the vocabulary is split; the three ops that map between token ids and this * rank's logit columns use it. Every op has a libref implementation, which is both its fallback * and its oracle (spec §17). */ #pragma once #include "rad_sample.h" +#include "rad_spechub.h" #include "../rad_core.h" #include "grammar.h" @@ -80,6 +87,7 @@ #include #include #include +#include #include namespace rad { @@ -109,6 +117,10 @@ struct SamplerConfig { * from this many of the most likely tokens, not the whole vocabulary. A request asking for a * larger top-k is refused at admission, not silently narrowed. */ int64_t max_candidates = kSampleCandidates; + + /* --draft-coupling: declare the coupled verify (`mtp_couple_verify`) behind the pick and the + * per-row state plane it reads. */ + bool draft_coupling = false; }; /* ================================================================== the driver */ @@ -160,13 +172,18 @@ public: /* Whether allows_speculation's answer can no longer change. It changes only when a grammar * whose backend cannot rewind starts to constrain (on a commit). */ bool speculation_fixed(uint64_t req_id) const; + /* --draft-coupling: bind the per-round states of the linear draft just published, `n` of + * them (0 clears). Each must name this request, the round it belongs to, and a `draw.mode` the + * row actually ran. RAD_E_NOTFOUND for a request already ended here. */ + int set_mtp_couple(uint64_t req_id, const RadMtpCoupleState* states, int n); /* ---------------------------------------------------------- step path */ /* Stage this step's parameter rows, penalty history and grammar bitmasks into pinned memory. * Scheduler thread, before the rank threads are released at the barrier. Allocates nothing; - * every buffer was sized at declare against max_seqs (spec §3.1). */ - int build_step(const std::vector& reqs); + * every buffer was sized at declare against max_seqs (spec §3.1). `step` is the engine's step + * the build stages for, carried into the coupling snapshot. */ + int build_step(const std::vector& reqs, int64_t step = -1); /* Stage `n` greedy rows for a drafter: no penalties, mask or history, and no RNG use, so * only the argmax runs. Draft output is a proposal checked by a greedy verifier @@ -200,6 +217,26 @@ public: * meaningful only where the row carries RAD_SP_MASK. */ const uint32_t* staged_mask(int64_t row) const { return mask_stage_ + row * mask_words_; } int64_t mask_words() const { return mask_words_; } + /* Staged row `row`'s bound coupled state, as `run` uploads it: all-zero where the row carries + * none (bonus row, greedy row, uncoupled step). Lets a build be checked without a device. */ + const RadMtpCoupleState& staged_couple(int64_t row) const { return couple_stage_[row]; } + /* Whether any row of the last build carries a bound state, i.e. whether `run` issues the + * verify op at all. Cleared by build_greedy: a gate for run(), not for evidence. */ + bool staged_any_couple() const { return any_couple_; } + /* The verify op the last build resolved, for naming its kernel in a log line. */ + rad_op staged_couple_op() const { return op_couple_; } + + /* What build_step staged for the coupled verify. build_greedy, which runs between that build + * and the step's wait, clears any_couple_ but leaves this snapshot. */ + struct CoupleBuild { + int64_t step = -1; /* the engine step this build staged */ + int64_t rows = 0; /* bound rows */ + /* The distinct sequences among them, with their bound rows. */ + std::vector> seqs; + }; + const CoupleBuild& couple_build() const { return couple_build_; } + /* The engine step whose build run() last issued the verify op for, or -1. */ + int64_t staged_couple_issued_step() const { return couple_issued_step_; } private: /* Whether the vocabulary is split, judged by this rank's logit width rather than the rank @@ -218,6 +255,11 @@ private: * newly committed tokens only. Read only when the request carries a thinking budget. */ ReasoningCount think; size_t think_seen = 0; + /* --draft-coupling: the linear draft's per-round states for the window the scheduler + * published, bound by set_mtp_couple and consumed by build_step. `couple_n` is how many of + * `couple` are live; 0 for a request whose drafts carry no coupled proposal. */ + RadMtpCoupleState couple[RAD_MTP_COUPLE_MAX_ROUNDS]{}; + int couple_n = 0; }; /* Mask staged row `row` to the reasoning block's close token, once the budget is spent @@ -232,6 +274,9 @@ private: /* Declared op handles; RAD_NULL_HANDLE means unresolved, which admission refuses by name. */ rad_op op_penalties_ = RAD_NULL_HANDLE; rad_op op_dry_ = RAD_NULL_HANDLE; + /* The windowed no-repeat-ngram ban (`sample_ngram_ban`), the stage Unlimited-OCR's + * generation_config asks for. It reads the same history plane as the two above. */ + rad_op op_ngram_ban_ = RAD_NULL_HANDLE; rad_op op_temp_ = RAD_NULL_HANDLE; rad_op op_temp_late_ = RAD_NULL_HANDLE; /* sample_temp over the candidates (temp_last) */ rad_op op_mask_ = RAD_NULL_HANDLE; @@ -244,6 +289,7 @@ private: rad_op op_argmax_ = RAD_NULL_HANDLE; rad_op op_allgather_ = RAD_NULL_HANDLE; rad_op op_merge_ = RAD_NULL_HANDLE; /* the candidate merge, under tensor parallel */ + rad_op op_couple_ = RAD_NULL_HANDLE; /* --draft-coupling only */ rad_op op_logprobs_ = RAD_NULL_HANDLE; /* summary of the raw distribution */ rad_op op_lp_gather_ = RAD_NULL_HANDLE; /* every rank's summary, under a split vocabulary */ @@ -252,6 +298,10 @@ private: rad_buf buf_params_late_ = RAD_NULL_HANDLE; /* the late temperature's rows */ rad_buf buf_hist_ = RAD_NULL_HANDLE; rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */ + rad_buf buf_ngram_ = RAD_NULL_HANDLE; /* the n-gram ban's {n, window} pair a row */ + /* The ban's whitelist bitmask, [rows, mask_words] like the grammar mask plane: a SET bit + * exempts that column from the ban. Uploaded with the ban, only when a staged row has one. */ + rad_buf buf_ngram_wl_ = RAD_NULL_HANDLE; rad_buf buf_mask_ = RAD_NULL_HANDLE; rad_buf buf_cand_i_ = RAD_NULL_HANDLE; rad_buf buf_cand_v_ = RAD_NULL_HANDLE; @@ -259,6 +309,12 @@ private: rad_buf buf_pairs_ = RAD_NULL_HANDLE; /* this rank's candidates as (global id, logit) */ rad_buf buf_lp_ = RAD_NULL_HANDLE; /* sample_logprobs' stats, [rows, lp_width()] */ rad_buf buf_lp_g_ = RAD_NULL_HANDLE; /* and every rank's side by side */ + rad_buf buf_couple_ = RAD_NULL_HANDLE; /* [rows, RAD_MTP_COUPLE_STATE_WORDS], flag only */ + RadMtpCoupleState* couple_stage_ = nullptr; /* pinned, one row per sampled position */ + bool couple_ = false; /* --draft-coupling */ + bool any_couple_ = false; /* does any row this step carry a bound state? */ + CoupleBuild couple_build_{}; /* what the last build_step staged, for the evidence line */ + int64_t couple_issued_step_ = -1; /* step whose verify op run() last issued */ /* Pinned staging, allocated once at declare. */ DeviceSampleParams* params_stage_ = nullptr; @@ -275,6 +331,8 @@ private: const DeviceSampleParams* cur_stage_ = nullptr; /* what the last build staged */ int32_t* hist_stage_ = nullptr; uint8_t* brk_stage_ = nullptr; + int32_t* ngram_stage_ = nullptr; /* [rows][2]: n-gram length, window */ + uint32_t* ngram_wl_stage_ = nullptr; /* [rows][mask_words] exemption bitmask */ uint32_t* mask_stage_ = nullptr; int64_t mask_words_ = 0; /* words for this rank's shard; what the mask op indexes */ @@ -282,6 +340,12 @@ private: /* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and * passed to sample_dry. */ bool any_brk_ = false; + /* Whether any row this step runs the n-gram ban. Its history is the plane the penalties use, + * so this only decides whether that plane is uploaded and the op issued. */ + bool any_ngram_ = false; + /* Whether any banned row this step whitelists a column of this rank's shard; only then is + * the exemption plane uploaded and passed to sample_ngram_ban. */ + bool any_ngram_wl_ = false; /* The whole-vocabulary mask the grammar fills, from which this rank's shard is cut. Used * only when the head is sharded; see declare(). */ diff --git a/core/sched/advance.h b/core/sched/advance.h index 6776a123..f0cfcc67 100644 --- a/core/sched/advance.h +++ b/core/sched/advance.h @@ -60,6 +60,16 @@ struct AdvGroup { int64_t used_off; /* [n_seq] seqused */ int64_t bt_off; /* [n_seq][pitch] block table */ int64_t first_off; /* [n_seq] the position each row's block table starts at */ + /* The runtime window (KVManager::set_window / SeqWindow), so the card computes the same + * `used` and slots the host builder staged: a ring sequence keeps its reference and rewrites + * a fixed ring of blocks, so its held span stops at its own table and a position past its + * ring_pos maps modulo ring_blocks. Without it (ring 0) the advance is the linear mapping, as + * before. ring_pos and the table length are per sequence (each prompt has its own floor and + * table), ring_blocks is the same for the group (one W). */ + int32_t ring; /* 1: the group carries runtime windows */ + int32_t ring_blocks; /* whole blocks the ring holds */ + int64_t rpos_off; /* [n_seq] the sequence's block-aligned first ring position, 0 if none */ + int64_t tlen_off; /* [n_seq] the sequence's block-table length in blocks, 0 if none */ }; /* One advance: a mode, the build it patches, and where its inputs are. Passed by value as the diff --git a/core/sched/advance_impl.h b/core/sched/advance_impl.h index bf331cce..774d352e 100644 --- a/core/sched/advance_impl.h +++ b/core/sched/advance_impl.h @@ -30,21 +30,43 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) { /* Every group's slots for the row's `n` positions (from the positions just written) and its * length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes - * tables for the furthest reachable position, so only a row whose output is unused hits this. */ + * tables for the furthest reachable position, so only a row whose output is unused hits this. + * + * A runtime window (e.ring, KVManager::set_window) must be computed exactly as the host builder + * staged it (BatchBuilder::build_groups), because this runs after the build and overwrites what it + * wrote: + * - `used` stops at the table: the ring reuses its blocks, so the sequence's held span is the + * table's, not the context's. Without this the decode walks bt[(used-1)/block] past the end, + * reads the -1 padding the builder fills and faults the card on a negative block; + * - a position at or past ring_pos lives in the ring, at block + * ring_pos/block + ((p - ring_pos)/block) % ring_blocks, not at (p - first)/block, which runs + * off the table once the ring wraps. */ RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n) { const AdvGroup* G = reinterpret_cast(a.slab + a.grp_off); const int32_t* pos = adv_i32(a, a.pos_off); for (int g = 0; g < a.n_groups; ++g) { const AdvGroup& e = G[g]; const int32_t first = adv_i32(a, e.first_off)[i]; - adv_i32(a, e.used_off)[i] = base + n - first; + /* Per sequence: each prompt has its own floor and its own table (advance.h). */ + const int32_t rpos = e.ring ? adv_i32(a, e.rpos_off)[i] : 0; + const int32_t tlen = e.ring ? adv_i32(a, e.tlen_off)[i] : 0; + const bool ring = e.ring && tlen > 0; + int64_t used = (int64_t)base + n - first; + if (ring) { + const int64_t span = (int64_t)tlen * e.block_size; + if (used > span) used = span; + } + adv_i32(a, e.used_off)[i] = (int32_t)used; if (!e.paged) continue; const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch; int32_t* slot = adv_i32(a, e.slot_off); for (int32_t j = 0; j < n; ++j) { const int32_t p = pos[k + j]; - const int32_t bi = (p - first) / e.block_size; - slot[k + j] = (p >= first && bi < e.pitch && bt[bi] >= 0) + int32_t bi = (p - first) / e.block_size; + if (ring && p >= rpos && e.ring_blocks > 0) + bi = rpos / e.block_size + + ((p - rpos) / e.block_size) % e.ring_blocks; + slot[k + j] = (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0) ? bt[bi] * e.block_size + p % e.block_size : -1; } } diff --git a/core/sched/batch.cpp b/core/sched/batch.cpp index 6cd9ac0a..92becbe9 100644 --- a/core/sched/batch.cpp +++ b/core/sched/batch.cpp @@ -6,6 +6,7 @@ #include "device/device.h" #include +#include #include #include @@ -112,6 +113,9 @@ void BatchBuilder::carve(Set& s, char* h) { pair(&s.h_dout, &s.d_dout, S); pair(&s.h_rows, &s.d_rows, 4 * S); pair(&s.h_first, &s.d_first, S * (int64_t)s.groups.size()); + /* The advance's per-sequence runtime-window data (advance.h); 0 when there is none. */ + pair(&s.h_rpos, &s.d_rpos, S); + pair(&s.h_tlen, &s.d_tlen, S); s.h_grp = ::rad::carve(h, oh, (int64_t)s.groups.size()); s.d_grp = ::rad::carve(d, od, (int64_t)s.groups.size()); for (size_t gi = 0; gi < s.groups.size(); ++gi) { @@ -686,17 +690,37 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& } int64_t t = 0; + /* The group's ring block count, read off the first armed sequence: declare_runtime_window + * fixes one W per group, so every armed sequence computes the same count. Collected here, + * with the table walk that already opens each window, so the group header below needs no + * second pass over the plan. */ + int32_t ring_blocks = 0; for (int64_t i = 0; i < n_seq; ++i) { const StepEntry& e = plan.e[(size_t)i]; int64_t first = 0; + SeqWindow win; + bool has_win = false; + int64_t bt_len = 0; /* the sequence's block table, in blocks */ + int64_t table_end = 0; /* the table's last position, for a runtime window's used */ if (L.paged) { /* The manager's block table, by sequence id; Request::blocks is not the source * of truth (see IKVManager). */ const std::vector& bt = kv.block_table(e.seq, (int32_t)gi); first = kv.first_block_pos(e.seq, (int32_t)gi); - for (int32_t j = 0; j < e.n_tokens; ++j) - g.h_slot[t + j] = kvgeom_.slot((int)gi, bt, first, (int64_t)e.ctx_len + j); + has_win = kv.runtime_window(e.seq, (int32_t)gi, &win); + if (has_win) { + assert(!ring_blocks || ring_blocks == (int32_t)win.ring_blocks); + ring_blocks = (int32_t)win.ring_blocks; + } + bt_len = (int64_t)bt.size(); + table_end = bt_len * L.block_size; + for (int32_t j = 0; j < e.n_tokens; ++j) { + const int64_t pos = (int64_t)e.ctx_len + j; + g.h_slot[t + j] = has_win + ? kvgeom_.slot_ring((int)gi, bt, first, pos, win) + : kvgeom_.slot((int)gi, bt, first, pos); + } /* Restage relative to what the card holds (BtMirror). The same sequence in the * same row keeps entries below the first changed one and below the end of both * old and new tables, so a decode step stages nothing or one appended block. A @@ -737,6 +761,11 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& s.h_convslot[(int64_t)gi * max_seqs_ + i] = st; } s.h_first[(int64_t)gi * max_seqs_ + i] = (int32_t)first; + /* The advance recomputes this row's used and slots after the build (advance_impl.h), + * so it needs the same per-sequence ring data this build staged: the row's floor and + * its table's length, 0 when the sequence has no runtime window. */ + s.h_rpos[i] = has_win ? (int32_t)win.ring_pos : 0; + s.h_tlen[i] = has_win ? (int32_t)bt_len : 0; t += e.n_tokens; /* Tokens the sequence holds in this table, not min(length, window). `seqused` counts @@ -745,8 +774,16 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& * unwritten slots at the end of the table, read as the newest context; a non-causal * window group would attend to them. Do not clamp to `window` either: the held span * may exceed it by under a block, and clamping would drop the newest tokens. Attending - * a few extra old positions is the cost of paging a window (vLLM does the same). */ + * a few extra old positions is the cost of paging a window (vLLM does the same). + * + * A runtime window (R-SWA) has reused its ring's slots once the sequence is past the + * ring's span, so the held span is the table's, not the context's: every slot of the + * reference and of the ring holds live KV, and the ring's blocks are what a non-causal + * decode reads. Before the ring is full the shorter of the two is the written count. */ int64_t used = (int64_t)e.ctx_len + e.n_tokens - first; + if (has_win) { + used = std::min(used, table_end); + } if (used < 0) used = 0; g.h_used[i] = (int32_t)used; if (L.paged) { @@ -773,6 +810,15 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set& a.used_off = (const char*)g.d_used - d0; a.bt_off = (const char*)g.d_bt - d0; a.first_off = (const char*)(s.d_first + (int64_t)gi * max_seqs_) - d0; + /* The runtime window (KVManager::set_window): the advance runs after this build and + * overwrites `used` and the slots, so it must reproduce the ring's mapping rather + * than the linear one (advance_impl.h). The floor and table length are per sequence + * (s.h_rpos / s.h_tlen), the ring's block count is the group's W, collected with the + * table walk above. */ + a.ring = ring_blocks ? 1 : 0; + a.ring_blocks = ring_blocks; + a.rpos_off = (const char*)s.d_rpos - d0; + a.tlen_off = (const char*)s.d_tlen - d0; } for (size_t r = 0; r < ranks_.size(); ++r) { @@ -872,6 +918,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, int32_t rope_mixed = 0; int64_t n_mm = 0; bool lora_rows = false; + int32_t cvec_rows = 0; s.h_cu[0] = 0; for (int64_t i = 0; i < n_seq; ++i) { const StepEntry& e = plan.e[(size_t)i]; @@ -905,6 +952,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, for (int32_t j = 0; j < e.n_tokens; ++j) s.h_lora[k + j] = ls; if (ls >= 0 && e.n_tokens > 0) lora_rows = true; } + /* The same rows derive.cpp's projection_on_rows sets (RadBatch::control_vector). */ + if (e.req && e.req->sp.use_control_vector && e.n_tokens > 0) cvec_rows = 1; /* Rotary position of each row at its own position (draft-head rows rotate at the index * they write, not the token they embed). Three planes of n_tok. */ if (mm_on_) { @@ -1113,6 +1162,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, /* Null on a step with no adapter row: the core then issues no adapter op, and the step * runs the same pass as an engine serving no adapters. */ B.lora_slot = lora_rows ? on_rank(base, b0, s.d_lora) : nullptr; + B.control_vector = cvec_rows; B.enc = 0; B.enc_n_patch = 0; B.enc_pixels = nullptr; @@ -1120,6 +1170,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv, B.enc_n_seg = 0; B.enc_cu = nullptr; B.enc_max_seg = 0; + B.enc_seg_h = nullptr; + B.enc_seg_w = nullptr; B.n_checkpoints = n_ck; B.checkpoint_tok = n_ck ? on_rank(base, b0, s.d_cktok) : nullptr; B.checkpoint_slot = n_ck ? on_rank(base, b0, s.d_ckslot) : nullptr; @@ -1188,6 +1240,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector& part const int64_t max_segs = enc.max_patches / (enc.merge > 0 ? enc.merge : 1) + 1; int64_t n_patch = 0, n_seg = 0, max_seg = 0; enc_cu_host_[0] = 0; + enc_seg_h_host_.clear(); + enc_seg_w_host_.clear(); for (const EncoderPart& p : parts) { const mm::Item& it = *p.item; if (p.seg0 < 0 || p.n_seg <= 0 || p.seg0 + p.n_seg > it.n_seg) { @@ -1210,6 +1264,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector& part for (int32_t q = p.seg0; q < p.seg0 + p.n_seg; ++q) { const int64_t seg_p = it.patch_at(q + 1) - it.patch_at(q); enc_cu_host_[n_seg + 1] = enc_cu_host_[n_seg] + (int32_t)seg_p; + enc_seg_h_host_.push_back(it.seg_h(q)); + enc_seg_w_host_.push_back(it.seg_w(q)); ++n_seg; if (seg_p > max_seg) max_seg = seg_p; } @@ -1256,6 +1312,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector& part B.enc_n_seg = n_seg; B.enc_cu = static_cast(enc_cu_dev_[r]); B.enc_max_seg = (int32_t)max_seg; + B.enc_seg_h = enc_seg_h_host_.data(); + B.enc_seg_w = enc_seg_w_host_.data(); } out_last_ = out_next_; out_next_ = (out_next_ + 1) % kOut; diff --git a/core/sched/batch.h b/core/sched/batch.h index c8142275..f2ec88f5 100644 --- a/core/sched/batch.h +++ b/core/sched/batch.h @@ -199,6 +199,11 @@ private: int32_t *h_rows = nullptr, *d_rows = nullptr; int32_t *h_first = nullptr, *d_first = nullptr; AdvGroup *h_grp = nullptr, *d_grp = nullptr; + /* [max_seqs] per-sequence runtime-window data for the advance: the block-aligned first + * ring position and the block table's length in blocks, 0 when the sequence has no + * runtime window (advance.h). Per sequence because each prompt has its own floor. */ + int32_t *h_rpos = nullptr, *d_rpos = nullptr; + int32_t *h_tlen = nullptr, *d_tlen = nullptr; char* h_derived = nullptr; /* derivation staging, byte-addressed */ /* [3][n_tok] rotary positions and [n_tok] encoder-row targets (RadBatch::rope_pos, @@ -328,6 +333,9 @@ private: int32_t* enc_coord_host_ = nullptr; int32_t* enc_cu_host_ = nullptr; std::vector enc_coord_tmp_; /* one item's coordinates; kept for its capacity */ + /* The pass's per-segment grid, host side (RadBatch::enc_seg_h/w). Filled by build_encoder and + * valid until the next build, like the staged coordinates. */ + std::vector enc_seg_h_host_, enc_seg_w_host_; int64_t last_n_tok_ = 0; struct MediaBytes { int64_t mm = 0, pix = 0, crd = 0, cu = 0; }; MediaBytes media_bytes(); /* the four per-rank device regions alloc_media reserves */ diff --git a/core/sched/geometry.cpp b/core/sched/geometry.cpp index e4a4b472..e5dca1ca 100644 --- a/core/sched/geometry.cpp +++ b/core/sched/geometry.cpp @@ -47,12 +47,16 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry * served by a different kernel may differ (§7.2). */ bool has_linear = false, has_window = false; for (const KVGroupInfo& kg : prog.kv_groups) { - if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) { + if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW || + kg.decl.kind == RAD_KV_RING) { if (kg.block_size > 0) { g.attn_block = lcm64(g.attn_block, kg.block_size); note(g.why, "attn_block", kg.block_size, kg.name.c_str()); /* A drafter's window is recomputed by draft refill; only the trunk's needs a - * snapshot for a prefix hit to resume. */ + * snapshot for a prefix hit to resume. A RAD_KV_RING group has no snapshot at all + * (KVManager::declare_runtime_window): its window is each sequence's own prompt + * length, which no slot could describe, so it is sized for the context plus a ring + * and is never checkpointed. */ if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter) has_window = true; } @@ -122,14 +126,15 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry * retention. * * Without linear state there are no checkpoints, except for a trunk window under a prefix - * cache, which snapshots the window behind a prompt's tail (window_ckpt) without splitting - * chunks. */ + * cache, which snapshots the window at interval boundaries and the prompt's tail + * (window_ckpt). */ if ((has_linear || (has_window && cfg.prefix_cache)) && cfg.checkpoint_interval > 0) g.checkpoint_interval = align_up(cfg.checkpoint_interval, g.quantum); else g.checkpoint_interval = 0; g.window_ckpt = !has_linear && g.checkpoint_interval > 0; - /* A window snapshot splits no chunk (plan_chunk), so there is no interval grid to span. */ + g.window_periodic = g.window_ckpt && cfg.checkpoint_policy != "tip-only"; + /* Window checkpoints do not support skipping snapshots inside a prefill span. */ g.span = (g.checkpoint_interval > 0 && !g.window_ckpt && cfg.prefill_span > 1) ? cfg.prefill_span : 1; g.shared_tok = prefill_shared_tok(cfg); @@ -149,9 +154,11 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry /* Log the effective chunk length. `plan_chunk` splits at the checkpoint interval first, so * when the interval is below --max-num-batched-tokens, raising the budget does not change the - * chunk; the log line makes that visible. A window snapshot splits nothing. */ + * chunk; the log line makes that visible. tip-only window snapshots do not + * split at the interval, so their chunk is bounded by the token budget. */ const int64_t span_tok = g.checkpoint_interval * g.span; - const int64_t eff = (g.checkpoint_interval > 0 && !g.window_ckpt && span_tok < cfg.max_tok) + const bool periodic = !g.window_ckpt || g.window_periodic; + const int64_t eff = (g.checkpoint_interval > 0 && periodic && span_tok < cfg.max_tok) ? span_tok : cfg.max_tok; RAD_INFO("chunk geometry: quantum %lld (attn block %lld, state chunk %lld), checkpoint " "interval %lld, max_tok %lld -> prefill chunks of at most %lld%s", diff --git a/core/sched/geometry.h b/core/sched/geometry.h index a0bb327c..437b0eb5 100644 --- a/core/sched/geometry.h +++ b/core/sched/geometry.h @@ -51,11 +51,14 @@ struct ChunkGeometry { /* Every contributor by name, for the startup line and the refusal. */ std::string why; - /* No linear state but a sliding window: the checkpoint snapshots only the window behind a - * prompt's tail (KVManager::has_window_snapshot). Chunks are not split at the interval, since - * a mid-prompt window snapshot gains nothing; the interval is only the shortest prompt worth - * a snapshot. */ + /* No linear state but a sliding window: checkpoints snapshot the window behind an + * interval boundary or the prompt's tail (KVManager::has_window_snapshot). Intermediate + * snapshots let an edited prompt resume below its divergence instead of from zero. + * tip-only skips interval snapshots and keeps the original tail-only chunking. */ bool window_ckpt = false; + /* Window checkpoints at interval boundaries too, not only at the tail: every policy but + * tip-only, which keeps the tail alone and so splits no chunk at the interval. */ + bool window_periodic = false; bool checkpoints() const { return checkpoint_interval > 0; } }; diff --git a/core/sched/mem_iface.h b/core/sched/mem_iface.h index 05934b33..af3e32df 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -44,6 +44,24 @@ struct IKVManager { /* After a committed step, a window group frees what no later query can read * (KVManager::trim_window). */ virtual void trim_window(uint64_t seq, int64_t keep_from) { (void)seq; (void)keep_from; } + /* R-SWA (KVManager::declare_runtime_window): the W this group arms a sequence with, 0 when it + * carries no runtime windows. The scheduler arms every sequence it admits with + * set_window(seq, prompt length, W); a manager with no runtime window refuses it and the + * scheduler never asks. */ + virtual int64_t runtime_window_tokens(int32_t group) const { (void)group; return 0; } + virtual int set_window(uint64_t seq, int64_t visible_lo, int64_t window_tokens) { + (void)seq; (void)visible_lo; (void)window_tokens; + return RAD_E_UNSUPPORTED; + } + /* The sequence's runtime window in `group`, if it has one (KVManager::runtime_window). A + * sequence with one is excluded from prefix publish, checkpoint snapshots and speculation: + * the window is runtime data and the ring rewrites its slots in place. */ + virtual bool runtime_window(uint64_t seq, int32_t group, SeqWindow* out) const { + (void)seq; (void)group; (void)out; + return false; + } + + virtual bool has_runtime_window(uint64_t seq) const { (void)seq; return false; } /* Window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The * defaults mean no hit on a windowed trunk is ever resumed. */ virtual bool has_window_snapshot() const { return false; } @@ -95,7 +113,11 @@ struct IKVManager { /* Absolute token position that block_table(seq, group)[0] covers: zero for a full group, * non-zero for a window group once blocks below the window are recycled. The step batch maps - * a slot as `(pos - first_block_pos) / block_size`. */ + * a slot as `(pos - first_block_pos) / block_size`. + * + * A sequence with a runtime window (runtime_window) keeps first_block_pos 0 even once the ring + * recycles: its table is [reference][ring] from position 0 and the ring's positions map + * modulo ring_blocks (SeqWindow), so only the slot index recycles, never the table. */ virtual int64_t first_block_pos(uint64_t seq, int32_t group) const = 0; /* Index of the first entry of block_table(seq, group) changed since the previous call; @@ -110,13 +132,22 @@ struct IKVManager { }; /* ------------------------------------------------------------------ the prefix cache */ +/* What IPrefixCache::restore did: brought back every entry the tiers hold for the prompt (or there + * were none), brought back part of them because the pool could not hold the chain, or, asked for + * the whole chain only, left it on the host. */ +enum class RestoreResult : uint8_t { Whole, Cut, Declined }; + struct IPrefixCache { virtual ~IPrefixCache() = default; /* Bring back whatever the idle tiers hold for this prompt, before the lookup. The engine * performs it (it allocates blocks and runs a device scatter). A failure only leaves a - * shorter prefix, which is always safe. */ - virtual void restore(const Request&) {} + * shorter prefix, which is always safe. With `whole_only`, a chain the pool cannot be made to + * hold whole is left on the host (RestoreResult::Declined). */ + virtual RestoreResult restore(const Request&, bool whole_only) { + (void)whole_only; + return RestoreResult::Whole; + } /* A step's admissions begin; the last step's lookup results have been consumed. */ virtual void begin_step() {} /* Keep this waiting request's chain in VRAM until release(). Called when admission is refused @@ -170,9 +201,17 @@ struct IPrefixCache { virtual CkptCounts ckpt_counts() const { return {}; } /* Entries expired by --prefix-cache-ttl; not counted as evictions. */ virtual int64_t expired() const { return 0; } - /* Restores the pool could not hold whole (PrefixCache::Stats::restore_cuts). */ - virtual int64_t restore_cuts() const { return 0; } virtual int64_t ckpt_expired() const { return 0; } + /* Entries and snapshots a client released on purpose (release_session). */ + virtual int64_t released() const { return 0; } + virtual int64_t ckpt_released() const { return 0; } + + /* Forget one stored conversation now, by the client's label or the engine's session id + * (PrefixCache::release_session). RAD_E_UNSUPPORTED from a cache without a session table. */ + virtual int release_session(const std::string& /*label*/, uint64_t /*id*/, + int64_t /*keep_tokens*/, SessionRelease* /*out*/) { + return RAD_E_UNSUPPORTED; + } /* Tokens of context held only by the cache right now. Blocks a running sequence also reads * are excluded. Separates a working cache from a leak in the pool figures. */ @@ -215,7 +254,7 @@ struct KVGeom { for (const KVGroupInfo& gi : groups) { G e; e.kind = gi.decl.kind; - e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW); + e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW || e.kind == RAD_KV_RING); e.block_size = gi.block_size > 0 ? gi.block_size : 1; e.window = gi.decl.window; k.g.push_back(e); @@ -231,6 +270,23 @@ struct KVGeom { if (bi < 0 || bi >= (int64_t)bt.size()) return -1; return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size)); } + + /* The same slot for a runtime window (SeqWindow): the reference maps linearly (first_pos is + * 0 there), and a position at or past the ring's start lives in block + * ring_pos/block + ((pos - ring_pos)/block) % ring_blocks, which is what rewrites the ring's + * slots in place. ring_pos is block-aligned, so `pos % block` stays the in-block offset. */ + int32_t slot_ring(int gi, const std::vector& bt, int64_t first_pos, int64_t pos, + const SeqWindow& w) const { + const G& e = g[(size_t)gi]; + int64_t bi; + if (w.set && pos >= w.ring_pos) { + bi = w.ring_pos / e.block_size + ((pos - w.ring_pos) / e.block_size) % w.ring_blocks; + } else { + bi = (pos - first_pos) / e.block_size; + } + if (bi < 0 || bi >= (int64_t)bt.size()) return -1; + return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size)); + } }; /* ------------------------------------------------------------------ binding the concrete classes */ @@ -246,6 +302,12 @@ struct KVBinding final : IKVManager { int ensure(uint64_t s, int64_t n) override { return m->ensure(s, n); } int ensure_from(uint64_t s, int64_t n, int64_t k) override { return m->ensure(s, n, k); } void trim_window(uint64_t s, int64_t k) override { m->trim_window(s, k); } + int64_t runtime_window_tokens(int32_t g) const override { return m->runtime_window_tokens(g); } + int set_window(uint64_t s, int64_t lo, int64_t w) override { return m->set_window(s, lo, w); } + bool runtime_window(uint64_t s, int32_t g, SeqWindow* o) const override { + return m->runtime_window(s, g, o); + } + bool has_runtime_window(uint64_t s) const override { return m->has_runtime_window(s); } bool has_window_snapshot() const override { return m->has_window_snapshot(); } int seed_window(uint64_t s, int64_t p) override { return m->seed_window(s, p); } int adopt(uint64_t s, int32_t g, const std::vector& b, int64_t n) override { @@ -344,16 +406,20 @@ struct PCBinding final : IPrefixCache { } /* Installed by the engine when the idle tiers are on; empty otherwise. */ - std::function restore_fn; - void restore(const Request& r) override { - if (restore_fn) restore_fn(r); + std::function restore_fn; + RestoreResult restore(const Request& r, bool whole_only) override { + return restore_fn ? restore_fn(r, whole_only) : RestoreResult::Whole; } /* The entries restore_fn brings back, in chain order: the whole chain if the pool can be made * to hold it, otherwise cut (PrefixCache::restorable_from). Room is made as evict() makes it, - * dropping entries with a landed host copy, then landing pending copies and dropping those, but - * never erasing one: a restore is worth no lost conversation. The pool's free quarter can go - * to it; the reserve's trim after the next publish frees it again. */ - std::vector restore_plan(const Request& r, uint64_t salt) { + * dropping entries with a landed host copy, then landing pending copies and dropping those, + * but never erasing one, so no other conversation is lost to a restore. The pool's free + * quarter can go to it; the reserve's trim after the next publish frees it again. `*res` + * says whether the chain was cut; with `whole_only`, a chain that would be cut comes back + * empty and Declined, and the room made stays for the next attempt. */ + std::vector restore_plan(const Request& r, uint64_t salt, bool whole_only = false, + RestoreResult* res = nullptr) { + if (res) *res = RestoreResult::Whole; media_keys(r, &mm_, salt); std::vector want = m->restorable_from(r.prompt, mm_); const int64_t need = (int64_t)want.size() - m->restore_room(); @@ -361,7 +427,16 @@ struct PCBinding final : IPrefixCache { const int64_t k = m->trim_for(r.prompt, mm_, need); if (k < need && flush_fn && flush_fn()) (void)m->trim_for(r.prompt, mm_, need - k); /* Landing copies may have moved records; take the chain again against the room made. */ - return m->restorable_from(r.prompt, mm_, m->restore_room()); + if (whole_only) { + want = m->restorable_from(r.prompt, mm_); + if ((int64_t)want.size() <= m->restore_room()) return want; + if (res) *res = RestoreResult::Declined; + return {}; + } + bool cut = false; + want = m->restorable_from(r.prompt, mm_, m->restore_room(), &cut); + if (cut && res) *res = RestoreResult::Cut; + return want; } void begin_step() override { m->begin_step(); } void hold(const Request& r) override { @@ -422,8 +497,13 @@ struct PCBinding final : IPrefixCache { return { st.ckpt_retired, st.ckpt_lru, st.ckpt_refused }; } int64_t expired() const override { return m->stats().expired; } - int64_t restore_cuts() const override { return m->stats().restore_cuts; } int64_t ckpt_expired() const override { return m->stats().ckpt_expired; } + int64_t released() const override { return m->stats().released; } + int64_t ckpt_released() const override { return m->stats().ckpt_released; } + int release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionRelease* out) override { + return m->release_session(label, id, keep_tokens, out); + } int64_t held_tokens() const override { return m->unshared_tokens(); } int64_t next_checkpoint_after(int64_t p) const override { return m->next_checkpoint_after(p); } diff --git a/core/sched/metrics.h b/core/sched/metrics.h index a4aa80cf..1ed81a9f 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -92,18 +92,20 @@ struct SchedMetrics { * and reservations that went without a snapshot. */ int64_t prefix_ckpt_retired = 0, prefix_ckpt_lru = 0, prefix_ckpt_refused = 0; int64_t prefix_expired = 0, prefix_ckpt_expired = 0; /* --prefix-cache-ttl */ + int64_t prefix_released = 0, prefix_ckpt_released = 0; /* DELETE /sessions */ /* Admissions whose attention hit was cut to nothing: no snapshot at or below it (recurrent * state or a window snapshot), a windowed trunk group no window snapshot covers, or blocks * that could not be adopted. `hit_cut_resumed_below` counts those that resumed at a - * snapshot more than one checkpoint interval below the hit: the retention ladder had - * nothing nearer, or the restore brought back only part of the chain. `hit_cut_tokens` is - * the checkpoint shortfall: prompt tokens the attention cache held and the admission - * computed again, because the hit resumed at a snapshot below it or was cut to nothing. */ + * snapshot more than one checkpoint interval below the hit: the previous reply was longer + * than an interval (decode writes no snapshot), the retention policy kept nothing nearer, or + * a restore was cut (prefix_restore_cuts). `hit_cut_tokens` is the checkpoint shortfall: + * prompt tokens the attention cache held and the admission computed again, because the hit + * resumed at a snapshot below it or was cut to nothing. */ int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0; int64_t hit_cut_resumed_below = 0; int64_t hit_cut_tokens = 0; /* Restores from the host tier the pool could not hold whole, even after giving up the VRAM - * copies of other conversations (PrefixCache::Stats::restore_cuts). */ + * copies of other conversations, counted once per admission (RestoreResult::Cut). */ int64_t prefix_restore_cuts = 0; /* Tokens of context held only by the cache, i.e. what eviction would free. Excludes blocks * shared with a running sequence. Same token axis as the paged groups, so comparable with diff --git a/core/sched/mtp_couple_bind.h b/core/sched/mtp_couple_bind.h new file mode 100644 index 00000000..b7500b59 --- /dev/null +++ b/core/sched/mtp_couple_bind.h @@ -0,0 +1,72 @@ +/* mtp_couple_bind.h -- the engine's post-commit binding step for a serial drafting row. + * + * Engine::finish_serial_drafter calls this after the commit, once the card's proposal states are + * read back. It decides: + * + * - the position the next build stages the row at: the request's committed output length after + * this commit. It is not rebuilt from the draw's pre-commit base plus the accepted count, which + * differ when a max_tokens or context cut emits fewer tokens than the card accepted; + * - whether the row binds at all: a sequence that is gone from the commit or no longer Running + * will not sample again. + * + * Both come from Scheduler::committed_seq(), filled by commit under the scheduler lock, never from + * the plan's StepEntry::req, which reap() may have freed by now. A header of its own so the rule + * can be tested against a real commit without an Engine (tests/sched_test.cpp). + */ +#pragma once + +#include "advance.h" +#include "rad_spechub.h" + +#include +#include + +namespace rad { + +/* Where the next build will sample this sequence, after the current step's commit. */ +struct MtpCoupleBindPoint { + bool found = false; /* the committed step carried the sequence */ + bool live = false; /* and its request was still Running (not finished/cancelled/failed) */ + uint64_t n_out = 0; /* its committed output length: what the next build reads as n_out */ +}; + +/* Bind `done` rounds of this row's draw to the positions the next build samples. `rb` is round 1 + * of this row in the engine's readback (stride `rb_stride` states), `tok[rd]` the card's token for + * round rd, `S` the card's slot. Fills `out[0, done)` and sets `*n_bound = done`; a sequence that + * is not live binds nothing (`*n_bound = 0`, RAD_OK) and leaves `out` untouched. RAD_E_STATE with + * `why` for a readback that is not this draw's, or is not a state the proposer could have written. + * A sampled round the proposer marked status -1 (a shortlist it could not turn into Q) kept the + * greedy proposal; it is bound as is, the sampler does not couple it, and `*n_malformed` counts it. + * `base` is never read here: it is the draft's coordinate, not the verify's. */ +inline int mtp_couple_bind_rounds(const MtpCoupleBindPoint& p, const RadMtpCoupleDraw& d, + const RadMtpCoupleState* rb, int rb_stride, int done, + const StepSlot& S, int64_t vocab, RadMtpCoupleState* out, + int* n_bound, std::string* why, int* n_malformed = nullptr) { + *n_bound = 0; + if (n_malformed) *n_malformed = 0; + if (!p.live) return RAD_OK; + const bool sampled = d.mode == 1; + for (int rd = 1; rd <= done; ++rd) { + const RadMtpCoupleState& st = rb[(size_t)(rd - 1) * (size_t)rb_stride]; + const bool malformed = sampled && st.status == -1; + if (std::memcmp(&st.draw, &d, sizeof d) || st.round != rd || st.x != S.tok[rd] || + (st.status != (sampled ? 1 : 0) && !malformed) || + (sampled && !malformed && !rad_mtp_couple_state_valid(st, vocab))) { + *why = "MTP coupled: sequence " + std::to_string(d.seq) + " round " + + std::to_string(rd) + " returned status " + std::to_string(st.status) + + " round " + std::to_string(st.round) + " x " + std::to_string(st.x) + + " for card token " + std::to_string(S.tok[rd]) + " (draw " + + (std::memcmp(&st.draw, &d, sizeof d) ? "stale" : "current") + + "); refusing the step"; + return RAD_E_STATE; + } + if (malformed && n_malformed) ++*n_malformed; + RadMtpCoupleState b = st; + b.pos = rad_mtp_couple_verify_pos(p.n_out, rd); + out[rd - 1] = b; + } + *n_bound = done; + return RAD_OK; +} + +} // namespace rad diff --git a/core/sched/mtp_couple_plan.h b/core/sched/mtp_couple_plan.h new file mode 100644 index 00000000..ea065f43 --- /dev/null +++ b/core/sched/mtp_couple_plan.h @@ -0,0 +1,53 @@ +/* mtp_couple_plan.h -- which draw the engine stages for each serial drafting row. + * + * Engine::stage_couple_draws (core/engine_draft.cpp) reads the draw of every sequence on its card + * from the step plan and, for each drafting row, the plan entry naming the row's sequence on the + * row's card. Pure host bookkeeping, so it is tested without a card. + * + * `by_card` has one entry per card slot, indexed by StepEntry::card in [0, max_seqs), the range of + * the StepSlots the advance reads. + */ +#pragma once + +#include "batch.h" +#include "scheduler.h" /* Scheduler::SerialRow */ + +#include "rad_spechub.h" + +#include +#include +#include + +namespace rad { + +/* Fills `by_card[0, n_card)` from the plan and writes one draw per drafting row to `stage[0, n)`. + * RAD_OK, or RAD_E_STATE with `why` set: the plane is too small for the card slots, or a drafting + * row's card carries no plan entry naming its sequence (a stale row -- the plugin would refuse the + * staged draw, so it is refused here where the row can be named). */ +inline int mtp_couple_plan_stage(const StepPlan& plan, int n_card, const Scheduler::SerialRow* rows, + int n, std::vector* by_card, + RadMtpCoupleDraw* stage, std::string* why) { + if (!by_card || !stage || !why) return RAD_E_INVAL; + if ((int)by_card->size() < n_card) { + *why = "the draw plane holds " + std::to_string(by_card->size()) + + " card slot(s), the step can use " + std::to_string(n_card); + return RAD_E_STATE; + } + for (int c = 0; c < n_card; ++c) (*by_card)[(size_t)c] = RadMtpCoupleDraw{}; + for (const StepEntry& e : plan.e) + if (e.req && e.card >= 0 && e.card < n_card) + (*by_card)[(size_t)e.card] = { e.req->sp.seed, (uint64_t)e.req->output.size(), e.seq, + e.card, e.req->sp.greedy() ? 0u : 1u }; + for (int i = 0; i < n; ++i) { + const Scheduler::SerialRow& row = rows[i]; + if (row.card < 0 || row.card >= n_card || (*by_card)[(size_t)row.card].seq != row.seq) { + *why = "drafting row " + std::to_string(i) + " (sequence " + std::to_string(row.seq) + + ", card " + std::to_string(row.card) + ") has no plan entry on its card"; + return RAD_E_STATE; + } + stage[i] = (*by_card)[(size_t)row.card]; + } + return RAD_OK; +} + +} // namespace rad diff --git a/core/sched/scheduler.cpp b/core/sched/scheduler.cpp index 7a5667db..2196413a 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -70,6 +70,20 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac has_linear_state_ = false; for (const auto& g : kvgeom_.g) if (!g.paged) has_linear_state_ = true; + /* R-SWA: which groups carry runtime per-sequence windows, and the W they arm a sequence + * with. Empty unless the engine declared one (KVManager::declare_runtime_window), so a model + * with a fixed window (gemma4) takes none of the runtime-window paths. */ + rswa_windows_.clear(); + for (size_t i = 1; i < kvgeom_.g.size(); ++i) { + const int64_t w = kv->runtime_window_tokens((int32_t)i); + if (w > 0) rswa_windows_.push_back({(int32_t)i, w}); + } + if (!rswa_windows_.empty()) + RAD_INFO("R-SWA: %zu KV group(s) with a runtime window; a sequence keeps its prompt as the " + "reference and decodes into a ring of %lld token(s) after it, and is excluded from " + "the prefix cache, checkpoints and speculation", + rswa_windows_.size(), (long long)rswa_windows_[0].tokens); + /* A hit can leave a drafter's own cache short only where a paged group is not prefix-cached * (scheduler.h, hit_holes_draft_). With the cache off cached_groups() is empty and this is * true, which costs nothing: no hits are taken, and every first block pass is at ctx_len 0. */ @@ -188,6 +202,7 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac free_cards_[(size_t)c] = (int32_t)(cfg.max_seqs - 1 - c); /* 0 is taken first */ reqs_.reserve((size_t)cfg.max_seqs); completed_.reserve((size_t)cfg.max_seqs); + committed_.reserve((size_t)cfg.max_seqs); by_id_.reserve((size_t)cfg.max_seqs * 2); hit_blocks_.resize(prog.kv_groups.size()); for (auto& v : hit_blocks_) v.reserve(64); @@ -282,6 +297,10 @@ int Scheduler::add_locked(std::unique_ptr r) { s.ckpt_src = -1; s.hit_attn = 0; s.hit_owed = false; + /* Slots are reused: a request that inherited `restore_waited` would never wait for a deferred + * release and its restore would be cut. */ + s.restore_waited = false; + s.restore_cut = false; s.req->state = ReqState::Waiting; /* The step path appends to `output`, so its capacity is settled here, on the arrival thread. @@ -307,6 +326,25 @@ Request* Scheduler::find(uint64_t id) { return it == by_id_.end() ? nullptr : reqs_[(size_t)it->second]->req.get(); } +bool Scheduler::running(uint64_t id) const { + std::lock_guard lk(mu_); + auto it = by_id_.find(id); + if (it == by_id_.end()) return false; + const SchedReq& s = *reqs_[(size_t)it->second]; + return s.req && s.req->state == ReqState::Running; +} + +bool Scheduler::committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const { + std::lock_guard lk(mu_); + for (const CommittedSeq& c : committed_) + if (c.seq == seq) { + if (n_out) *n_out = c.n_out; + if (live) *live = c.live; + return true; + } + return false; +} + int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) { std::lock_guard lk(mu_); auto it = by_id_.find(id); @@ -385,6 +423,40 @@ int64_t Scheduler::reset_prefix_cache() { return dropped; } +int Scheduler::release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionRelease* out) { + std::lock_guard lk(mu_); + if (!pc_ || !cfg_.prefix_cache) return RAD_E_UNSUPPORTED; + if (label.empty() && id == 0) return RAD_E_INVAL; + for (const auto& p : reqs_) { + if (!p || !p->req) continue; + const Request& r = *p->req; + if (r.state == ReqState::Finished || r.state == ReqState::Failed || + r.state == ReqState::Cancelled) + continue; + if ((id != 0 && r.id == id) || (!label.empty() && r.session_label == label)) + return RAD_E_STATE; + } + const int rc = pc_->release_session(label, id, keep_tokens, out); + if (rc == RAD_OK && out) { + if (label.empty()) + RAD_INFO("prefix cache: session %llu released: %lld entries (%lld tokens), %lld " + "snapshots; kept %lld tokens as asked, %lld blocks shared, %lld live", + (unsigned long long)id, (long long)out->entries, (long long)out->tokens, + (long long)out->snapshots, (long long)out->kept_tokens, + (long long)out->kept_shared, (long long)out->kept_live); + else + RAD_INFO("prefix cache: session '%s' released (%lld rows): %lld entries (%lld " + "tokens), %lld snapshots; kept %lld tokens as asked, %lld blocks shared, " + "%lld live", + label.c_str(), (long long)out->sessions, (long long)out->entries, + (long long)out->tokens, (long long)out->snapshots, + (long long)out->kept_tokens, (long long)out->kept_shared, + (long long)out->kept_live); + } + return rc; +} + void Scheduler::trim_prefix_cache() { if (!pc_ || !cfg_.prefix_cache) return; const std::vector& cg = pc_->cached_groups(); @@ -407,7 +479,12 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool * and failed requests are published too; their prompts were computed, and a client that hangs * up mid-answer is likely to ask for that prefix again. */ if (publish && cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) && - s.req->n_computed > 0) { + s.req->n_computed > 0 && !kv_->has_runtime_window(s.req->id)) { + /* R-SWA: a sequence with a runtime window is not published (KVManager::set_window). Its + * table is a reference plus a ring rather than a prefix from position 0, and the window + * length is runtime data that no cache key carries; a hit would adopt blocks for a window + * this sequence does not have. prefix.cpp already skips a windowed group -- this makes the + * policy explicit, rather than a consequence of the kind declared at build time. */ const std::vector& cg = pc_->cached_groups(); pub_blocks_.assign(cg.size(), {}); bool ok = !cg.empty(); @@ -466,6 +543,11 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool * refusal leaves the entry without one. */ void Scheduler::reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_t tok) { int32_t cs = -1; + /* R-SWA: a sequence with a runtime window is never checkpointed. The window is runtime data + * (the prompt's own length), so a slot would describe a window the sequence does not have, and + * the ring is not the [lo, pos) block list a restore seeds. The prefix cache can never reuse + * it either, so the copy would be dead weight. */ + if (kv_->has_runtime_window(r.id)) return; if (pc_->reserve_checkpoint(r, pos, &cs) < 0 || cs < 0) return; e.ckpt_tok = tok; e.ckpt_slot = cs; @@ -700,6 +782,12 @@ int Scheduler::draft_ngram(SchedReq& s, int depth) const { } /* ------------------------------------------------------------------ chunking */ +int64_t Scheduler::chunk_end(const Request& r, int64_t n_target) const { + if (rswa_windows_.empty() || !kv_->has_runtime_window(r.id)) return n_target; + const int64_t prompt = (int64_t)r.prompt.size(); + return std::min(n_target, r.n_computed < prompt ? prompt : r.n_computed + 1); +} + /* A prefill chunk splits at the linear-state checkpoint interval so a checkpoint is always * written (spec §7.3; see scheduler.h). * @@ -717,7 +805,18 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg if (geo_.checkpoints()) { const int64_t I = geo_.checkpoint_interval; int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */ - if (geo_.window_ckpt) next = INT64_MAX; /* a window snapshot: the tail only */ + if (geo_.window_ckpt && !geo_.window_periodic) { + /* An explicit tail-only policy should not pay for intermediate + * window copies or chunk splits just to retire those snapshots. */ + next = INT64_MAX; + } else if (geo_.window_ckpt) { + /* A tail-only window snapshot is unreachable after a prompt edit. + * Keep interval checkpoints too; the ordinary retention policy bounds + * their storage. Preserve the tail before the template's changed suffix, + * even when the prompt ends exactly on an interval boundary. */ + const int64_t tail = tail_checkpoint(n_target); + if (tail > n_computed) next = std::min(next, tail); + } /* A span (ChunkGeometry::span) starts only on an interval boundary past the first * interval, and its chunk is the span's intervals in a row, each the piece a span of 1 * makes a chunk of its own. Not from a prompt's start: the first interval may be served on @@ -731,7 +830,8 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg want = far - n_computed; else if (n_computed + want > next && n_computed + want < n_target) want = (n_computed + want) / I * I - n_computed; - if (!geo_.window_ckpt && (n_computed + want) % I == 0) { + if ((geo_.window_ckpt && n_computed + want == next) || + (!geo_.window_ckpt && (n_computed + want) % I == 0)) { if (checkpoint_pos) *checkpoint_pos = n_computed + want; } else if (n_computed + want == n_target) { /* Also one at the prompt's tail. The next turn resumes from the deepest snapshot @@ -918,6 +1018,20 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id)); + /* R-SWA: the visible set becomes [0, prompt) plus a ring of W once the prompt is placed. The + * floor is this sequence's own prompt length (image tokens included, they are prompt rows), + * and it is armed here rather than at the prefill's end so no checkpoint is reserved for the + * sequence: a snapshot would describe a window the sequence no longer has (set_window). */ + for (const RswaWindow& w : rswa_windows_) { + const int rc = kv_->set_window(r.id, (int64_t)r.prompt.size(), w.tokens); + if (rc < 0) { + RAD_WARN("request %llu: runtime window of %lld tokens over a %zu-token prompt: %s", + (unsigned long long)r.id, (long long)w.tokens, r.prompt.size(), + rad_strerror(rc)); + return rc; + } + } + /* A fresh attempt: nothing looked up or counted yet. A request that kept an earlier * attempt's hit (n_computed > 0) keeps what it found. */ if (r.n_computed == 0) { @@ -937,8 +1051,21 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { if (r.n_computed == 0 && cfg_.prefix_cache) { /* Restore before the lookup, which stops at the first block the tiers hold. This is * where a cold session gets its context back for the cost of a copy instead of a - * prefill. */ - pc_->restore(r); + * prefill. + * + * A sequence closed while a step issued ahead still read its blocks keeps them until the + * next commit, and the room a restore makes cannot include them yet: a request right + * behind another conversation's last turn would come back cut and prefill the rest. Such + * a restore waits one step, once, instead of being cut. */ + const bool whole_only = n_deferred_ > 0 && !s.restore_waited; + const RestoreResult rr = pc_->restore(r, whole_only); + if (rr == RestoreResult::Declined) { + s.restore_waited = true; + RAD_DEBUG("admit %llu: the restore waits a step for %d deferred release(s)", + (unsigned long long)r.id, n_deferred_); + return RAD_E_FULL; + } + s.restore_cut = rr == RestoreResult::Cut; HitCap cap; if (draft_refill_ > 0) { cap.tokens = std::max(0, (int64_t)r.prompt.size() - draft_refill_); @@ -974,8 +1101,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { "below it", (unsigned long long)r.id, (long long)h.n_attn_tokens); } else if (reuse < h.n_attn_tokens) { /* Within an interval of the hit is the ordinary case: a turn's tail past its last - * checkpoint. Further down, the snapshots in between are gone, or the attention - * blocks reach past what the tiers could restore of the chain. */ + * checkpoint. Further down, the previous reply was longer than an interval (decode + * writes no snapshot), the retention policy kept nothing nearer, or the attention + * blocks reach past the snapshot a cut restore stopped at. */ if (geo_.checkpoints() && h.n_attn_tokens - reuse > geo_.checkpoint_interval) s.hit_cut = SchedReq::HitCut::ResumedBelow; RAD_DEBUG("admit %llu: prefix hit of %lld tokens resumes at the snapshot at %lld", @@ -1056,9 +1184,10 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { * 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()); - want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at); + const int64_t end = chunk_end(r, target); + want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at); if (cap < budget && want > 0) - admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr, r.checkpoint_at); + admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at); } int rc = RAD_OK; if (want <= 0) rc = RAD_E_FULL; @@ -1093,6 +1222,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) { m_.attn_cached_tokens += s.hit_attn; m_.linear_cached_tokens += r.n_cached; if (s.hit_attn > r.n_cached) m_.hit_cut_tokens += s.hit_attn - r.n_cached; + if (s.restore_cut) ++m_.prefix_restore_cuts; switch (s.hit_cut) { case SchedReq::HitCut::NoSnapshot: ++m_.hit_cut_no_snapshot; break; case SchedReq::HitCut::Window: ++m_.hit_cut_window; break; @@ -1254,9 +1384,10 @@ const RadBatch* Scheduler::step() { 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); - want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at); + const int64_t end = chunk_end(r, target); + want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at); if (cap < budget && want > 0 && capped_at < 0) { - const int64_t full = plan_chunk(r.n_computed, target, budget, nullptr, + const int64_t full = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at); if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; } } @@ -1476,7 +1607,8 @@ const RadBatch* Scheduler::step() { if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk)); int64_t ckpt = -1; const int64_t grown = e.ckpt_slot < 0 && limit > had - ? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt, r.checkpoint_at) : had; + ? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at) + : had; if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) { e.n_tokens = (int32_t)grown; e.produces_token = (r.n_computed + grown >= s.seq_len()); @@ -1607,7 +1739,7 @@ bool Scheduler::prefill_continues() const { std::lock_guard lk(mu_); /* Only the step being released has a plan to read. Between a commit and the next step (an * encoder pass is prepared there) `plan_` is the committed step's, whose requests in_step() no - * longer holds: a cancel and reap may have released one (#127). */ + * longer holds: a cancel and reap may have released one. */ if (stage_rows_ <= 0 || !step_open_) return false; /* The next step is held to decode rows (--prefill-interleave): experts staged for a chunk now * would be dropped by that step. */ @@ -1804,6 +1936,10 @@ int Scheduler::commit(const StepResult& res) { } step_open_ = false; + /* What the serial bind reads after commit, copied here while the Requests are still held: + * reap() may release a finished one before finish_serial_drafter runs. */ + committed_.clear(); + const int32_t W = conv_window(); /* A mixed step leaves decode rows the same replay factors as a decode step (recurrent path @@ -1826,6 +1962,7 @@ int Scheduler::commit(const StepResult& res) { s.pending_free = false; --n_deferred_; } + committed_.push_back({e.seq, (uint64_t)r.output.size(), false}); continue; } @@ -1982,6 +2119,7 @@ int Scheduler::commit(const StepResult& res) { } else if (eos) { close_request(s, ReqState::Finished, "stop", carried); } + committed_.push_back({e.seq, (uint64_t)r.output.size(), r.state == ReqState::Running}); } m_.prefill_tokens += step_prefill_tok_; @@ -2125,7 +2263,10 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) { * so the host bounds it by all of them. A mid-prompt chunk verified nothing. */ const int64_t vstart = (int64_t)e.ctx_len + e.n_tokens - 1 - e.n_spec; const int64_t head_max = vstart + e.n_spec; - bool can_draft = may_draft && e.produces_token; + /* A runtime-window (R-SWA) sequence is never drafted for: its rollback refuses (the ring + * rewrites slots KVManager::rollback cannot unwind), so a rejected draft would only warn + * and waste the draft compute. This is the gate kv.cpp's rollback comment states. */ + bool can_draft = may_draft && e.produces_token && !kv_->has_runtime_window(r.id); /* Lookahead KV: round k writes the head's K and V at head + k - 1, past the committed end, * so blocks must exist up to the furthest head acceptance could leave. The next verify @@ -2305,8 +2446,12 @@ void Scheduler::serial_end(int rounds_done) { * also propose. Called while plan() still describes that step, because the context pass mirrors * it exactly, rejected suffix included: the drafter reads hidden states positionally from its * own buffer, so batch row i must be buffer row i. The rejected positions lie in [n_computed, - * n_computed + block), which the query pass overwrites before anything reads them, and the - * ensure() below covers them since n_computed + block reaches the trunk step's own end. + * n_computed + the trunk step's block), which a query pass overwrites before anything reads them. + * The ensure() below covers n_computed + `block`; with the block the trunk step verified that + * reaches its end. A short block (rad_drafter_short_block) after a long one does not: rejected + * rows past it fall on pages the commit's rollback freed, whose slot is -1, and every kv_store + * drops a negative slot. That rule is what keeps such a step from writing into another + * sequence's pages. * * On the card the step has not committed yet. The step began at n_computed (a row issued ahead * was staged at its furthest reach; it really continued from the committed end, as commit() @@ -2422,6 +2567,17 @@ int Scheduler::block_begin(int block, int depth, int window, int32_t mask, Block return n_draft_rows; } +int Scheduler::decoded_seqs() const { + std::lock_guard lk(mu_); + int n = 0; + for (const StepEntry& e : plan_.e) { + if (!e.produces_token || e.slot < 0 || (size_t)e.slot >= reqs_.size()) continue; + const SchedReq& s = *reqs_[(size_t)e.slot]; + if (s.req && s.req->state == ReqState::Running && s.running) ++n; + } + return n; +} + const Request* Scheduler::block_req(const BlockSeq& d) const { return live_req(d.slot, d.seq); } const Request* Scheduler::serial_req(const SerialSeq& m) const { return live_req(m.slot, m.seq); } @@ -2631,7 +2787,8 @@ SchedMetrics Scheduler::metrics_locked() const { m.prefix_ckpt_refused = cc.refused; m.prefix_expired = pc_->expired(); m.prefix_ckpt_expired = pc_->ckpt_expired(); - m.prefix_restore_cuts = pc_->restore_cuts(); + m.prefix_released = pc_->released(); + m.prefix_ckpt_released = pc_->ckpt_released(); m.prefix_held_tokens = pc_->held_tokens(); } m.attn_hit_rate = m.prompt_tokens ? (float)((double)m.attn_cached_tokens / (double)m.prompt_tokens) : 0.0f; diff --git a/core/sched/scheduler.h b/core/sched/scheduler.h index d89c323e..67607661 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -111,6 +111,12 @@ struct SchedReq { * snapshot more than an interval below it. */ enum class HitCut : uint8_t { None, NoSnapshot, Window, Adopt, ResumedBelow }; HitCut hit_cut = HitCut::None; + /* Admission waited a step for a sequence's deferred release before cutting its restore + * (Scheduler::admit_one); it waits once. */ + bool restore_waited = false; + /* That attempt's restore came back cut (SchedMetrics::prefix_restore_cuts, counted once the + * admission happens). */ + bool restore_cut = false; /* The whole sequence is prompt ++ output; n_computed indexes into it. */ int64_t seq_len() const { @@ -133,6 +139,15 @@ public: const int32_t* first_row = nullptr; /* [n_seq] */ }; + /* What commit left a sequence at: its committed length and whether it is still Running. + * Copied under the lock in commit because reap() may free the Request before the serial bind + * reads it. */ + struct CommittedSeq { + uint64_t seq = 0; + uint64_t n_out = 0; + bool live = false; + }; + /* `geo` is the already-resolved chunk geometry. The engine resolves it once because * PrefixCache::configure runs first and needs its checkpoint interval; pass nullptr to * resolve one here. */ @@ -161,6 +176,11 @@ public: * under exactly the load that cancels. */ int cancel(uint64_t id); Request* find(uint64_t id); + /* Whether the request is still admitted and Running, read under the lock. */ + bool running(uint64_t id) const; + /* What the step just committed left for `seq`, copied by commit under the lock. False when + * that step carried no such sequence. */ + bool committed_seq(uint64_t seq, uint64_t* n_out, bool* live) const; /* Requests that reached a terminal state since the last call, oldest first, swapped into * `out` under the lock (old contents discarded). Only the engine consumes it, to drop @@ -254,6 +274,13 @@ public: * cache. Takes the step lock because the step path inserts into the map (live sequences hold * their own block references). See IScheduler::reset_prefix_cache. */ int64_t reset_prefix_cache(); + /* Forget one stored conversation, by label or engine id, keeping its first `keep_tokens` + * (IPrefixCache::release_session). Refused with RAD_E_STATE while a request of that + * conversation is queued or running: its blocks would be skipped as live and its close + * would publish the chain again, so the release would be half done and undone at once. + * Takes the step lock like reset_prefix_cache. */ + int release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionRelease* out); /* ---------------------------------------------------------- the step path */ /* One decision, one batch. Null when there is nothing to run, which is not an error. */ @@ -322,25 +349,27 @@ public: * A block-diffusion drafter (RAD_DRAFT_BLOCK) proposes a whole block of `block` positions in * one pass, so there are no rounds; instead it runs two passes of different shapes. * - * block_begin right after commit(), while plan() still describes the step just run. - * Reserves the draft KV block the query pass writes, and returns which - * sequences may draft. + * block_begin right after the step is issued, before commit(), while plan() still + * describes it. Reserves the draft KV block the query pass writes, and + * returns which sequences may draft. * block_context the context pass, draft_pass -1. Its entries mirror the trunk step's * row for row (BlockSeq). * block_query the query pass, draft_pass +1. One entry per drafting sequence: the * anchor at its next position, then `block - 1` masks; `out_ids` names the * last `depth` rows. - * block_end moves the filled range over what actually ran. + * block_end after commit(): moves the filled range over what actually ran. * * The drafter writes its proposal to its declared proposal buffer, not through the sampler, * and the engine publishes it through set_draft(). * - * On the card (`on_card`), block_begin runs before commit() instead, right after the step is - * issued, so both passes queue behind it with no readback in between. The context pass is - * unchanged: it mirrors the trunk step, whose positions the host knows. The query pass's - * anchor depends on acceptance, so its rows are device rows (advance.h, ADV_BLOCK) staged at - * the furthest position acceptance could leave, and the reservation covers that far. - * block_end still runs after commit(). + * Both passes queue behind the step with no readback in between. The context pass mirrors the + * trunk step, whose positions the host knows. The query pass's anchor depends on acceptance, + * so its rows are device rows (advance.h, ADV_BLOCK) staged at the furthest position + * acceptance could leave, and the reservation covers that far. + * + * With `on_card` false, block_begin runs after commit() instead and stages the query pass + * from the committed sequence. The engine does not use it; it is the reference the + * scheduler's tests hold the card's staging to. */ struct BlockRow { uint64_t seq = 0; @@ -353,6 +382,17 @@ public: * in the order block_query() emits them. */ int block_begin(int block, int depth, int window, int32_t mask, BlockRow* out, int max, bool on_card = false); + /* How many running sequences the step just run decoded (produced a token for), the load a + * block drafter's block length is chosen by. Read before block_begin(). */ + int decoded_seqs() const; + /* Whether a block drafter runs its short block (--draft-short-from `from`), given whether it + * ran it last step and this step's decoded_seqs(): on from `from`, off again only at two + * below, so a load wavering at the threshold does not switch the pass shape every step. */ + static bool short_block_on(bool was_on, int64_t decoded, int64_t from) { + if (decoded >= from) return true; + if (decoded + 2 <= from) return false; + return was_on; + } const RadBatch* block_context(int step); const RadBatch* block_query(int step); void block_end(); @@ -397,6 +437,12 @@ public: * --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; + /* 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 + * multi-token chunk past the floor would overwrite keys its own earlier rows still read, while + * one token a step attends as its decode step did. Otherwise `n_target`. */ + int64_t chunk_end(const Request& r, int64_t n_target) const; private: Program* prog_ = nullptr; @@ -429,6 +475,13 @@ private: * meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index? * Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */ bool hit_holes_trunk_ = false; + /* R-SWA: the groups whose KV manager carries per-sequence runtime windows, with the W a + * sequence is armed with (IKVManager::runtime_window_tokens). Empty for every model that does + * not declare one, in which case admission and commit are exactly as before. A sequence with + * one keeps its prompt as a reference and decodes into a ring after it; it is excluded from + * prefix publish, checkpoints and speculation (the window is runtime data). */ + struct RswaWindow { int32_t group = -1; int64_t tokens = 0; }; + std::vector rswa_windows_; /* Draft refill: the drafter's window where a hit can leave a hole in a windowed block * drafter's cache, else 0. The drafter would be declined until its window slid past the hole, * which on a chat's follow-up turn is most of the reply, so the hit ends one window before the @@ -616,6 +669,8 @@ private: * 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; bool step_open_ = false; + /* The step just committed: its sequences' committed length and liveness, in plan order. */ + std::vector committed_; /* The single-sequence decode floor (rad::DecodeFloor), fed by step_finished. */ DecodeFloor decode_floor_; diff --git a/core/server/adapters.h b/core/server/adapters.h index 02d19f8e..347bd82f 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -35,6 +35,7 @@ #include #include +#include #include #include @@ -107,6 +108,8 @@ inline SchedMetrics bridge_metrics(const rad::SchedMetrics& m) { o.hit_cut_tokens = m.hit_cut_tokens; o.prefix_expired = m.prefix_expired; o.prefix_ckpt_expired = m.prefix_ckpt_expired; + o.prefix_released = m.prefix_released; + o.prefix_ckpt_released = m.prefix_ckpt_released; o.prefill_tps = m.prefill_tps; o.decode_tps = m.decode_tps; @@ -202,6 +205,24 @@ public: int64_t reset_prefix_cache() override { return s_->reset_prefix_cache(); } + int release_session(const std::string& label, uint64_t id, int64_t keep_tokens, + SessionReleased* out) override { + SessionRelease r; + const int rc = s_->release_session(label, id, keep_tokens, &r); + if (out) { + out->sessions = r.sessions; + out->entries = r.entries; + out->tokens = r.tokens; + out->device_bytes = r.device_bytes; + out->host_bytes = r.host_bytes; + out->snapshots = r.snapshots; + out->kept_tokens = r.kept_tokens; + out->kept_shared = r.kept_shared; + out->kept_live = r.kept_live; + } + return rc; + } + /* The stored conversations. The tiers keep monotonic timestamps; idle and age are converted * to "seconds ago" here, so only the monotonic clock is authoritative. */ TierCounters tier_counters() const override { @@ -708,10 +729,21 @@ public: std::shared_ptr* out, std::string* why) override { if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; } if (k == MediaKind::Audio) return p_->audio(bytes.data(), bytes.size(), out, why); - return k == MediaKind::Image - ? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why, - opts.max_pixels) - : p_->video(bytes.data(), bytes.size(), out, why); + if (k == MediaKind::Video) return p_->video(bytes.data(), bytes.size(), out, why); + mm::ImageMode mode; + mode.kind = (int32_t)opts.image_mode; + mode.base_size = opts.image_base_size; + mode.image_size = opts.image_size; + mode.several = opts.several_pictures; + /* The host share of a picture (decode, resample, patch staging), apart from the tower + * pass engine_mm.cpp times. */ + const auto t0 = std::chrono::steady_clock::now(); + const int rc = p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why, + opts.max_pixels, mode); + RAD_DEBUG("mm: host processor %lld bytes -> %.1f ms (rc %d)", (long long)bytes.size(), + std::chrono::duration( + std::chrono::steady_clock::now() - t0).count(), rc); + return rc; } int encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side, diff --git a/core/server/audio_gen.cpp b/core/server/audio_gen.cpp index ebe50260..a3d30871 100644 --- a/core/server/audio_gen.cpp +++ b/core/server/audio_gen.cpp @@ -11,11 +11,18 @@ * `guidance_scale` (the model's guidance: the denoiser's for a music model, the frame model's for * a speech one) and, for a model with a denoiser, `num_inference_steps`. * + * References, for a model that clones a voice (RadAudioGenDecl::tmpl_ref): `references` is an + * array of {"audio", "text"}, a clip of the voice (a data: URL or the base64 of an audio file, + * decoded to mono at the model's rate and padded to whole frames) and what it says; at most the + * model's count of them and seconds together. The prompt is then the references' template, each + * reference rendered from the model's item, its transcript and a row a frame of its clip. + * * Prompt: the plugin's template with its slots filled, each text first rewritten by the plugin * into the form the model was trained on (rad_arch_text_prepare). The template is tokenised with * its special tokens and the texts without, so a caller cannot write the model's control tokens - * into a lyric. A model that declares the unconditional branch's own template gets that one - * rendered from the same texts. + * into a lyric; a model that declares `input_special` has its input tokenised with them too (its + * speaker tags), its prepare() refusing the control tokens. A model that declares the + * unconditional branch's own template gets that one rendered from the same texts. * * Response: the whole piece, once it is finished, as `response_format` wav (16-bit PCM, the * model's rate and channels) or pcm (the same samples raw, little-endian). Streamed as the @@ -29,6 +36,7 @@ #include "oai.h" #include "gen/audio.h" +#include "mm/media.h" #include "rad_internal.h" #include @@ -109,6 +117,9 @@ int Server::speech_request(const json& body, const std::string& text, return fail(err_bad("instructions", "this model needs instructions, as a non-empty " "string: for a song its genre, mood, vocals and " "instruments")); + if (!inst.empty() && info.tmpl.empty()) + return fail(err_unsupported("instructions", "this model takes no instructions; its " + "direction is written in the input")); if (body.contains("speed") && !body["speed"].is_null() && !(body["speed"].is_number() && body["speed"].get() == 1.0)) return fail(err_unsupported("speed", "this model keeps its own tempo; the instructions " @@ -156,6 +167,8 @@ int Server::speech_request(const json& body, const std::string& text, if (!body["guidance_scale"].is_number() || !(body["guidance_scale"].get() >= 1.0) || body["guidance_scale"].get() > 30.0) return fail(err_bad("guidance_scale", "expected a number in [1, 30]")); + if (info.branches == 1 && body["guidance_scale"].get() != 1.0) + return fail(err_unsupported("guidance_scale", "this model runs without guidance")); r->cfg = (float)body["guidance_scale"].get(); } bool seed_given = false; @@ -170,33 +183,141 @@ int Server::speech_request(const json& body, const std::string& text, r->seed = (((uint64_t)rd() << 32) ^ rd()) & (((uint64_t)1 << 53) - 1); } + /* ---- the references: a clip of a voice and what it says, each */ + struct Ref { std::string text; int64_t frames = 0; }; + std::vector refs; + if (body.contains("references") && !body["references"].is_null()) { + const json& rs = body["references"]; + if (!rs.is_array()) + return fail(err_bad("references", "expected an array of {\"audio\", \"text\"}")); + if (!rs.empty() && info.tmpl_ref.empty()) + return fail(err_unsupported("references", "this model takes no reference audio; its " + "voice is described in the input")); + if ((int64_t)rs.size() > info.ref_max) + return fail(err_bad("references", "at most " + std::to_string(info.ref_max) + + " references a request")); + const int64_t hop = std::max(1, info.ref_hop); + r->ref_cu.assign(1, 0); + for (size_t i = 0; i < rs.size(); ++i) { + const std::string at = "references[" + std::to_string(i) + "]"; + const json& e = rs[i]; + if (!e.is_object()) + return fail(err_bad(at, "expected an object {\"audio\", \"text\"}")); + for (auto it = e.begin(); it != e.end(); ++it) + if (it.key() != "audio" && it.key() != "text") + return fail(err_bad(at + "." + it.key(), "a reference is its audio and its " + "text")); + if (!e.contains("audio") || !e["audio"].is_string()) + return fail(err_bad(at + ".audio", "the clip is required, as a data: URL or " + "base64 of an audio file")); + if (!e.contains("text") || !e["text"].is_string() || blank(e["text"].get())) + return fail(err_bad(at + ".text", "the clip's transcript is required, as a " + "non-empty string")); + /* The file: a data: URL, or its base64 alone (as fish-speech's server takes it). */ + const std::string& a = e["audio"].get_ref(); + std::vector bytes; + if (a.rfind("data:", 0) == 0) { + ApiError ue; + if (decode_media_url(a, at + ".audio", &bytes, &ue) < 0) return fail(ue); + } else if (!base64_decode(a, &bytes)) { + return fail(err_bad(at + ".audio", "invalid base64")); + } + /* Mono at the model's rate; one sample past what is left of the budget is decoded, + * so a clip too long is refused rather than cut. */ + const int64_t left = info.ref_max_samples - (int64_t)r->ref_audio.size(); + std::vector pcm; + std::string dwhy; + if (left < hop) + return fail(err_bad(at + ".audio", "the references are longer than this model " + "takes")); + if (mm::decode_audio(bytes.data(), bytes.size(), (int32_t)info.ref_rate, left + 1, + &pcm, &dwhy) < 0) + return fail(err_bad(at + ".audio", "the clip could not be used: " + dwhy)); + if (pcm.empty()) return fail(err_bad(at + ".audio", "the clip holds no audio")); + const int64_t padded = ((int64_t)pcm.size() + hop - 1) / hop * hop; + if (padded > left) + return fail(err_bad(at + ".audio", "the references hold more than " + + rad::fmt("%g", (double)info.ref_max_samples / + (double)info.ref_rate) + + " seconds together; this model takes no " + "more")); + pcm.resize((size_t)padded, 0.0f); + r->ref_audio.insert(r->ref_audio.end(), pcm.begin(), pcm.end()); + r->ref_cu.push_back((int32_t)r->ref_audio.size()); + Ref ref; + std::string why; + if (deps_.audio->prepare(RAD_TEXT_REFERENCE, e["text"].get(), &ref.text, + &why) < 0) + return fail(err_bad(at + ".text", why)); + ref.frames = padded / hop; + refs.push_back(std::move(ref)); + } + if (refs.empty()) r->ref_cu.clear(); + } + if (!refs.empty() && !inst.empty()) + return fail(err_unsupported("instructions", "a request with references takes no " + "instructions; the clips set the voice")); + /* ---- the prompt */ std::string i2, t2, why; if (!inst.empty() && deps_.audio->prepare(RAD_TEXT_INSTRUCTIONS, inst, &i2, &why) < 0) return fail(err_bad("instructions", why)); if (deps_.audio->prepare(RAD_TEXT_INPUT, text, &t2, &why) < 0) return fail(err_bad("input", why)); + auto encode = [&](const std::string& t, bool special, std::vector* ids_out) { + if (t.empty()) return; + const auto ids = deps_.tok->encode(t, false, /*parse_special=*/special); + ids_out->insert(ids_out->end(), ids.begin(), ids.end()); + }; + auto subst = [](std::string t, const std::string& key, const std::string& v) { + for (size_t p = t.find(key); p != std::string::npos; p = t.find(key, p + v.size())) + t.replace(p, key.size(), v); + return t; + }; + /* One reference (ref_item): its header, the transcript in it, tokenised as one segment with + * its special tokens (the speaker tags prepare() allows), a row a frame of its clip, and what + * follows the clip as another segment. */ + int64_t frame0 = 0; + auto render_ref = [&](size_t i, std::vector* ids_out) { + 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); + for (int64_t f = 0; f < refs[i].frames; ++f) { + ids_out->push_back(0); + r->ref_frame.push_back((int32_t)(frame0 + f)); + } + frame0 += refs[i].frames; + encode(subst(info.ref_item.substr(a + kAudio.size()), "{index}", idx), true, ids_out); + }; /* A template a segment at a time: its own text with special tokens, each slot without. */ auto render = [&](const std::string& t, std::vector* ids_out) { - static const std::string kInst = "{instructions}", kInput = "{input}"; + static const std::string kInst = "{instructions}", kInput = "{input}", + kRefs = "{references}"; size_t at = 0; while (at <= t.size()) { - const size_t a = t.find(kInst, at), b = t.find(kInput, at); - const size_t p = std::min(a, b); - const std::string lit = - t.substr(at, p == std::string::npos ? std::string::npos : p - at); - if (!lit.empty()) { - const auto ids = deps_.tok->encode(lit, false, /*parse_special=*/true); - ids_out->insert(ids_out->end(), ids.begin(), ids.end()); - } + 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)); + encode(t.substr(at, p == std::string::npos ? std::string::npos : p - at), true, + 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); + at = p + kRefs.size(); + continue; + } const bool is_inst = p == a; - const auto ids = deps_.tok->encode(is_inst ? i2 : t2, false, /*parse_special=*/false); - ids_out->insert(ids_out->end(), ids.begin(), ids.end()); + /* The input keeps its special tokens only for a model that asks (its speaker tags); + * the plugin's prepare() has refused the ones a caller may not write. */ + encode(is_inst ? i2 : t2, !is_inst && info.input_special, ids_out); at = p + (is_inst ? kInst : kInput).size(); } }; - render(inst.empty() ? info.tmpl_plain : info.tmpl, &r->tokens); + 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); const size_t n_prompt = std::max(r->tokens.size(), r->neg_tokens.size()); if ((int64_t)n_prompt > info.max_prompt) @@ -225,7 +346,7 @@ HttpResponse Server::handle_speech(const HttpRequest& req) { static const char* kKnown[] = { "model", "input", "instructions", "voice", "response_format", "speed", "stream", "stream_format", "seed", "max_new_tokens", "duration", "num_inference_steps", - "guidance_scale", "user", + "guidance_scale", "user", "references", }; for (auto it = body.begin(); it != body.end(); ++it) { bool known = false; @@ -339,9 +460,13 @@ HttpResponse Server::handle_speech(const HttpRequest& req) { std::string pcm; for (const gen::AudioChunk& c : chunks) append_pcm16(c.samples, &pcm); const double secs = (double)pcm.size() / 2.0 / (double)(info.channels * info.sample_rate); - RAD_INFO("audio: %.1f s from %lld frames in %lld windows, %.1f s%s", secs, - (long long)ticket->frames, (long long)ticket->windows, - (double)(ticket->t_done_ns - ticket->t_submit_ns) * 1e-9, + auto sec = [](int64_t a, int64_t b) { return a > 0 && b >= a ? (double)(b - a) * 1e-9 : 0.0; }; + RAD_INFO("audio: %.1f s from %lld frames in %lld windows, %.1f s: queue and prompt %.1f s, " + "first audio %.1f s, frames %.1f s%s", secs, (long long)ticket->frames, + (long long)ticket->windows, sec(ticket->t_submit_ns, ticket->t_done_ns), + sec(ticket->t_submit_ns, ticket->t_prompt_ns), + sec(ticket->t_submit_ns, ticket->t_first_audio_ns), + sec(ticket->t_prompt_ns, ticket->t_frames_ns), ticket->model_ended ? "" : " (the request's length)"); HttpResponse res; res.status = 200; diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index 53b976ba..ae2ff213 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -55,6 +55,18 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) { } if (req.method == "POST") { + /* The default applies to every client's requests that name no choice, so a server + * started without --api-key takes the change from a loopback client only, as it does a + * runtime adapter load. */ + if (opt_.api_key.empty() && !req.peer_is_loopback()) { + ApiError e; + e.status = 403; + e.type = "permission_error"; + e.message = "without --api-key, the control-vector default is changed only from a " + "loopback client; start the server with --api-key to change it from " + "elsewhere"; + return error_response(e, req.peer); + } json body; try { body = json::parse(req.body.empty() ? "{}" : req.body); @@ -138,6 +150,8 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { o["snapshot_store"] = { { "bytes_each", c.ck_bytes }, { "slots", c.ck_slots } }; /* Entries and snapshots removed by --prefix-cache-ttl, from whichever tier held them. */ o["expired"] = { { "entries", sm.prefix_expired }, { "snapshots", sm.prefix_ckpt_expired } }; + /* And the ones a client gave up on purpose (DELETE /sessions). */ + o["released"] = { { "entries", sm.prefix_released }, { "snapshots", sm.prefix_ckpt_released } }; /* Step-thread time spent on tier moves; every request waits through it. */ o["stall"] = { { "restores", c.restores }, { "restore_ms", (double)c.restore_ns / 1e6 }, { "flushes", c.flushes }, { "flush_ms", (double)c.flush_ns / 1e6 } }; @@ -167,6 +181,83 @@ HttpResponse Server::handle_sessions(const HttpRequest&) { return HttpResponse::json_body(200, json_dump(o)); } +/* ------------------------------------------------------------------ DELETE /sessions + * + * A client that deletes a conversation, or replaces everything past a prefix of it, knows the + * rest is dead before the TTL does. Named by the label it sent (`session_id`, or Anthropic's + * `metadata.user_id`), or by the engine id `/sessions` shows. `keep_tokens` keeps the chain's + * start. Shared blocks and blocks a live request reads stay; a request of the same conversation + * in flight is a 409, since its close would publish the chain again. */ +HttpResponse Server::handle_session_release(const HttpRequest& req) { + if (!deps_.sched) + return error_response(err_not_implemented("the server has no engine attached"), req.peer); + + const std::string label = req.param("label"); + uint64_t id = 0; + const std::string id_s = req.param("id"); + if (!id_s.empty()) { + if (id_s.find_first_not_of("0123456789") != std::string::npos || id_s.size() > 19) + return error_response(err_bad("id", "expected the session's engine id, a decimal " + "integer as /sessions reports it"), req.peer); + id = std::stoull(id_s); + if (id == 0) return error_response(err_bad("id", "0 names no session"), req.peer); + } + if (label.empty() && id == 0) + return error_response(err_bad("label", "name the session: DELETE /sessions/