diff --git a/CMakeLists.txt b/CMakeLists.txt index da4380b9..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.11.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 6f638028..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 @@ -44,12 +46,17 @@ 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, and its norm and SiLU producers writing the int8 linears' operands directly @@ -59,7 +66,8 @@ Written by Deadcode, with contributions from: exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose 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, and the eight-rank two-shot in ring order + 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 @@ -73,6 +81,8 @@ Written by Deadcode, with contributions from: - 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 a43dbf6b..ad8f3592 100644 --- a/README.md +++ b/README.md @@ -48,6 +48,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC | 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 +121,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 +211,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 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 f2691cb0..fdd8889b 100644 --- a/abi/rad_builder.h +++ b/abi/rad_builder.h @@ -208,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 */ @@ -446,17 +478,14 @@ 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, and lane 1 is joined into lane 0 before any op - * declared after the window runs. 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 the first op past the window - * issued on lane 0 joins lane 1 first when lane 1 has work pending. Optional, one window a program; - * call both at declare, in order. The runtime joins lane 1 into lane 0 at the window's end only, so an - * op declared before the window must not be issued again while lane 1 has work pending (a transient - * it uses may share bytes with a concurrent buffer the window keeps live). Additive export; - * RAD_ABI_VERSION does not move. */ + * 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); @@ -640,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 @@ -700,6 +730,17 @@ int rad_drafter_shared_kv(RadBuilder* b, int pos_offset); * 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 @@ -1011,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 @@ -1072,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); @@ -1360,6 +1432,17 @@ typedef struct RadArchProbe { /* 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); @@ -1538,11 +1621,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 3a21a315..aa684371 100644 --- a/abi/rad_runtime.h +++ b/abi/rad_runtime.h @@ -489,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 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_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_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_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_fp8.h b/arch/common/rad_fp8.h index 05e775a5..4cdbb459 100644 --- a/arch/common/rad_fp8.h +++ b/arch/common/rad_fp8.h @@ -762,6 +762,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(). */ @@ -815,8 +819,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. */ @@ -1054,9 +1060,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; @@ -1066,6 +1073,11 @@ 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); @@ -1105,6 +1117,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; + } if (a.q8_fed && rot8 != a.q8_rot) { fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its " "producer wrote %s\n", wn, rot8 ? " rotated" : " plain", @@ -1164,6 +1181,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 " @@ -1230,6 +1252,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); @@ -1300,6 +1327,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. */ @@ -1411,10 +1443,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. */ @@ -1446,10 +1478,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) { @@ -1458,7 +1491,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 @@ -1468,13 +1501,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) { @@ -1483,14 +1516,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) { @@ -1504,12 +1537,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_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_prefill_pipe.h b/arch/common/rad_prefill_pipe.h deleted file mode 100644 index f0b44ecf..00000000 --- a/arch/common/rad_prefill_pipe.h +++ /dev/null @@ -1,42 +0,0 @@ -#pragma once -// RADIANCE_PREFILL_PIPELINE: whether an architecture with a pipelined prefill (a prefill step of one -// sequence in two pieces, the collectives between blocks on the second lane, beside the other piece's -// compute) uses it. -// -// auto (or unset) at two ranks, where it was measured (Qwen3.8-27B 41k prefill -6.6 %, -// TranslateGemma-27B 6k -4.7 % at a 2048 chunk, bit for bit the serial step); -// on (1, true) also at three, four and eight ranks: libr4d has the narrow `overlap` two-shot -// all-reduce there (the wide rows' entry points at a launch that leaves the CUs to -// compute), but the step has not been measured on such hardware; -// off (0, false) never. -// -// Any other rank count has no narrow row, and a wide all-reduce beside the GEMMs ate the whole gain at -// two (it slows the GEMM 1.45-2.1x), so those stay serial. Past two ranks only the two-shot band is -// narrow: a piece small enough for the one-shot band (at most 524288 elements, e.g. 512 rows of a model -// 1024 wide) still gets the wide one-shot; and eight ranks have no lossy wire, so `on` there pipelines -// on the exact wire only. -#include "rad_arch.h" - -#include -#include - -namespace rad::arch { - -inline bool prefill_pipeline(RadBuilder* b, int world, const char* who) { - const char* e = std::getenv("RADIANCE_PREFILL_PIPELINE"); - auto is = [&](const char* v) { return e && !std::strcmp(e, v); }; - const bool on = is("on") || is("1") || is("true"), off = is("off") || is("0") || is("false"); - if (e && *e && !on && !off && !is("auto")) - rad_note(b, "%s: RADIANCE_PREFILL_PIPELINE=%s is not auto, on or off; taken as auto", who, e); - if (off || world < 2) return false; - if (world == 2) return true; - if (on && (world == 3 || world == 4 || world == 8)) { - rad_note(b, "%s: RADIANCE_PREFILL_PIPELINE=on allows the pipelined prefill at %d ranks, not " - "yet measured on such hardware (it still needs what the architecture checks)", - who, world); - return true; - } - return false; -} - -} // namespace rad::arch 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 1ff4c75c..af01a6d8 100644 --- a/arch/gemma3/gemma3.cpp +++ b/arch/gemma3/gemma3.cpp @@ -21,7 +21,6 @@ #include #include #include -#include #include #include @@ -769,7 +768,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) }; @@ -796,8 +795,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; @@ -818,7 +820,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), @@ -938,6 +940,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); @@ -1049,6 +1052,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, @@ -1192,17 +1196,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_NOWEIGHTS), {m.b_x}, {m.b_x}); - /* The pipelined prefill (step_pipelined) wherever a step can be wide enough, on an MXFP4 trunk - * with fused junctions (decided below), at the rank counts RADIANCE_PREFILL_PIPELINE allows - * (rad_prefill_pipe.h: two by default). Its second lane touches the stream, the branch - * output, the shared input pair and the bounds, so those leave the sharing pool (the drafter - * taps are copied on the first lane: pipe_taps) - * (Ctx::lane1_); the pair is one for every block so that this costs one pair, not one a + /* 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.max_tok >= kPipeMinRows && !calib_dir() && - rad::arch::prefill_pipeline(b, (int)g.world, "gemma3"); - } + 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; @@ -1509,8 +1509,7 @@ static const int32_t* pipe_ready(RadCtx* c, const RadBatch* batch, Model& m, boo 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); RADIANCE_PREFILL_PIPELINE=off " - "runs prefill serially"); + "(no pinned host memory, or the copy failed)"); *failed = true; return nullptr; } @@ -1617,7 +1616,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); @@ -1633,10 +1633,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/glm5next/glm5next.cpp b/arch/glm5next/glm5next.cpp index f9f8855d..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; @@ -429,6 +450,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c 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)); @@ -578,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/qwen35_fp8/qwen35_fp8.cpp b/arch/qwen35_fp8/qwen35_fp8.cpp index 8d88d74a..25570fed 100644 --- a/arch/qwen35_fp8/qwen35_fp8.cpp +++ b/arch/qwen35_fp8/qwen35_fp8.cpp @@ -87,9 +87,7 @@ #include #include #include -#include -#include #include #include @@ -284,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); @@ -434,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 " @@ -604,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; @@ -890,22 +890,23 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c RAD_NOWEIGHTS), {m.b_x}, {m.b_x}); #if !QWEN35_MOE - /* The pipelined prefill (step_pipelined), wherever a step can be wide enough, at the rank - * counts RADIANCE_PREFILL_PIPELINE allows (rad_prefill_pipe.h: two by default). Its second - * lane touches the residual stream, the normed input in both forms and the bounds, so those - * leave the sharing pool (the drafter taps are copied on the first lane: pipe_taps) - * (Ctx::lane1_); 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 + /* 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, and that int8 path is unmeasured, so such a - * trunk prefills serially, as before this pipeline. */ + * (NormQuantFP8::step_plain) issue the E4M3 pair only, so such a trunk prefills serially. */ if (m.a_h.q8_fed) { - if (g.world > 1 && g.max_tok >= kPipeMinRows && ctx->rank == 0) + 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.max_tok >= kPipeMinRows && rad::arch::prefill_pipeline(b, (int)g.world, "qwen35"); + m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows; } if (m.pipe_on) { RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_x)); @@ -1215,8 +1216,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * 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). Measured on Qwen3.8-27B at two - * R9700s: a 41k-token prompt 9.0 -> 8.4 s. + * 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 @@ -1228,12 +1228,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c * 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 (Qwen's KL recordings compare equal). + * 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 -- not the drafter taps, which it no longer touches (pipe_taps). */ + * the sharing pool at declare (the drafter taps it does not touch: pipe_taps). */ template static void pipe_on1(RadCtx* c, const F& issue) { @@ -1363,8 +1363,7 @@ static const int32_t* pipe_ready(RadCtx* c, const RadBatch* batch, Model& m, boo 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); RADIANCE_PREFILL_PIPELINE=off " - "runs prefill serially"); + "(no pinned host memory, or the copy failed)"); *failed = true; return nullptr; } @@ -1553,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/qwen4exp_fp8/qwen4exp_fp8.cpp b/arch/qwen4exp_fp8/qwen4exp_fp8.cpp index e092e4c9..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. */ diff --git a/core/build/rad_build.h b/core/build/rad_build.h index 3bacf446..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); diff --git a/core/build/rad_builder.cpp b/core/build/rad_builder.cpp index f08f0138..2fa9d950 100644 --- a/core/build/rad_builder.cpp +++ b/core/build/rad_builder.cpp @@ -1418,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; } @@ -1428,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 " @@ -1505,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; } @@ -1800,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 " @@ -1843,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; } @@ -1935,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); @@ -2462,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/startup.cpp b/core/build/startup.cpp index fe5178ad..b08ee817 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 d84b7ab7..78fe62d1 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 4635b1e4..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,9 @@ 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" }, @@ -158,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" }, @@ -441,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; @@ -492,6 +512,14 @@ 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; @@ -652,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 @@ -1034,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"); } }, @@ -1049,6 +1088,7 @@ 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); } }, @@ -1087,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/engine.cpp b/core/engine.cpp index f3532071..317f6ede 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 @@ -452,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 @@ -526,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); @@ -714,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); @@ -1364,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()) { @@ -1687,6 +1695,7 @@ std::string Engine::engine_info() const { 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. */ @@ -2568,8 +2577,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 { @@ -2595,6 +2605,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; diff --git a/core/engine.h b/core/engine.h index 725d6c5a..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 @@ -338,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. */ @@ -373,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); @@ -395,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. */ @@ -413,10 +440,16 @@ private: int block_pass(const RadBatch* db, const char* what, int step); 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 59689caa..89c38eb0 100644 --- a/core/engine_bringup.cpp +++ b/core/engine_bringup.cpp @@ -905,6 +905,9 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const { 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; @@ -1029,6 +1032,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 @@ -1303,6 +1340,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. */ diff --git a/core/engine_draft.cpp b/core/engine_draft.cpp index 8ecdbd66..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; } @@ -313,6 +464,21 @@ bool Engine::block_drafting() const { * 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_drafting()) return RAD_OK; @@ -321,8 +487,12 @@ int Engine::issue_block_drafter(int step, StepOut& so) { /* 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); @@ -368,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/format/checkpoint.cpp b/core/format/checkpoint.cpp index 7a5b340a..c41db4a8 100644 --- a/core/format/checkpoint.cpp +++ b/core/format/checkpoint.cpp @@ -855,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; @@ -898,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() { diff --git a/core/format/checkpoint.h b/core/format/checkpoint.h index 99806047..de5f8f72 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 @@ -187,6 +188,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(); @@ -195,6 +197,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 */ 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 d5c9beb5..1778e9e0 100644 --- a/core/gen/audio_driver.cpp +++ b/core/gen/audio_driver.cpp @@ -66,8 +66,23 @@ constexpr int64_t kAlign = 256; 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; @@ -75,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; } @@ -108,6 +126,16 @@ 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) { @@ -121,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); } @@ -134,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; @@ -152,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; @@ -222,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) @@ -234,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 " @@ -307,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; @@ -388,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; @@ -410,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); @@ -432,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; @@ -515,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); @@ -528,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) { @@ -547,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) { @@ -575,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); @@ -584,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); @@ -597,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; @@ -616,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; @@ -628,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; @@ -635,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/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 a899f0ad..d90f6fe1 100644 --- a/core/mem/prefix.cpp +++ b/core/mem/prefix.cpp @@ -368,14 +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); - /* A snapshot-backed prefix keeps its first bytes even in the host tier: a short - * recompute can round the KV differently, while older conversations' recurrent snapshots - * still depend on the original attention KV. Non-stateful caches may rebind below. */ - if (it != map_.end() && (it->second.in_lru || has_linear_)) 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; @@ -989,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 f433edc4..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: @@ -314,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). */ @@ -356,6 +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; + /* 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/plugin/loader.cpp b/core/plugin/loader.cpp index 0e39344d..1c864985 100644 --- a/core/plugin/loader.cpp +++ b/core/plugin/loader.cpp @@ -442,6 +442,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; @@ -452,7 +455,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 bbb3d411..8b6021e9 100644 --- a/core/rad_core.h +++ b/core/rad_core.h @@ -392,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. @@ -416,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. */ @@ -762,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. @@ -808,6 +814,7 @@ 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. */ @@ -906,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/ctx.h b/core/runtime/ctx.h index a943e72c..303cfaa3 100644 --- a/core/runtime/ctx.h +++ b/core/runtime/ctx.h @@ -291,6 +291,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_; } @@ -549,6 +551,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; @@ -575,7 +580,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); @@ -645,7 +649,8 @@ 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 (the window's join). */ + /* 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; diff --git a/core/runtime/issue.cpp b/core/runtime/issue.cpp index bd364ec4..a8e7f245 100644 --- a/core/runtime/issue.cpp +++ b/core/runtime/issue.cpp @@ -593,18 +593,20 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) { "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 1 is joined before lane 0 runs past it. */ + * 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) { - if (lane_ == 1 && (p.order < program_->lane1_w0 || p.order > program_->lane1_w1)) + 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_ && p.order > program_->lane1_w1) { + 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 at its window's end failed"); + return abort_step_msg(h, js, "joining the second lane outside its window failed"); } } if (lane_ == 1) lane1_pending_ = true; 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 329e2dd6..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. @@ -185,6 +186,14 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) { * 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()) { @@ -257,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. */ { @@ -316,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). */ @@ -331,6 +355,11 @@ int Sampler::stage_alloc() { 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) { @@ -347,7 +376,7 @@ int Sampler::stage_alloc() { } if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ || - !ngram_stage_ || !ngram_wl_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_ * 8 + 8)).c_str()); @@ -366,6 +395,8 @@ void Sampler::stage_free() { 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); @@ -602,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(); @@ -612,8 +657,13 @@ int Sampler::build_step(const std::vector& reqs) { 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 @@ -701,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); @@ -940,6 +1014,7 @@ int Sampler::build_greedy(int64_t n) { 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 @@ -1030,6 +1105,9 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) { 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_); @@ -1119,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 e29c0b2e..5eb8e254 100644 --- a/core/sample/sampler.h +++ b/core/sample/sampler.h @@ -77,6 +77,7 @@ */ #pragma once #include "rad_sample.h" +#include "rad_spechub.h" #include "../rad_core.h" #include "grammar.h" @@ -86,6 +87,7 @@ #include #include #include +#include #include namespace rad { @@ -115,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 */ @@ -166,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 @@ -206,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 @@ -224,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 @@ -253,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 */ @@ -272,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; diff --git a/core/sched/geometry.cpp b/core/sched/geometry.cpp index cee15da0..e5dca1ca 100644 --- a/core/sched/geometry.cpp +++ b/core/sched/geometry.cpp @@ -133,6 +133,7 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry else g.checkpoint_interval = 0; g.window_ckpt = !has_linear && g.checkpoint_interval > 0; + 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; @@ -156,7 +157,7 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry * 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 bool periodic = !g.window_ckpt || cfg.checkpoint_policy != "tip-only"; + 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 " diff --git a/core/sched/geometry.h b/core/sched/geometry.h index 15007824..437b0eb5 100644 --- a/core/sched/geometry.h +++ b/core/sched/geometry.h @@ -56,6 +56,9 @@ struct ChunkGeometry { * 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 768a7a5d..af3e32df 100644 --- a/core/sched/mem_iface.h +++ b/core/sched/mem_iface.h @@ -202,6 +202,16 @@ struct IPrefixCache { /* Entries expired by --prefix-cache-ttl; not counted as evictions. */ virtual int64_t expired() 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. */ @@ -488,6 +498,12 @@ struct PCBinding final : IPrefixCache { } int64_t expired() const override { return m->stats().expired; } 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 88ab4fe5..1ed81a9f 100644 --- a/core/sched/metrics.h +++ b/core/sched/metrics.h @@ -92,6 +92,7 @@ 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 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 31177649..2196413a 100644 --- a/core/sched/scheduler.cpp +++ b/core/sched/scheduler.cpp @@ -202,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); @@ -325,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); @@ -403,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(); @@ -751,7 +805,7 @@ int64_t Scheduler::plan_chunk(int64_t n_computed, int64_t n_target, int64_t budg if (geo_.checkpoints()) { const int64_t I = geo_.checkpoint_interval; int64_t next = ((n_computed / I) + 1) * I; /* strictly after n_computed */ - if (geo_.window_ckpt && cfg_.checkpoint_policy == "tip-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; @@ -1882,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 @@ -1904,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; } @@ -2060,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_; @@ -2386,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() @@ -2503,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); } @@ -2712,6 +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_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 7b5c1568..67607661 100644 --- a/core/sched/scheduler.h +++ b/core/sched/scheduler.h @@ -139,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. */ @@ -167,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 @@ -260,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. */ @@ -361,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(); @@ -637,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 198465d4..fc492cbb 100644 --- a/core/server/adapters.h +++ b/core/server/adapters.h @@ -108,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; @@ -203,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 { diff --git a/core/server/audio_gen.cpp b/core/server/audio_gen.cpp index aac14e6e..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; diff --git a/core/server/dashboard.cpp b/core/server/dashboard.cpp index bac5cdfc..ae2ff213 100644 --- a/core/server/dashboard.cpp +++ b/core/server/dashboard.cpp @@ -150,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 } }; @@ -179,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/