Archived
radiance 1.12.0
New models: - Fish Audio drama-3: speech with speaker tags and inline direction, voices cloned from reference clips (the `references` field of /v1/audio/speech and the streaming session), two cards - Gemma 4 E2B/E4B (KV-shared layers, per-layer embeddings, clipped vision linears), with NVIDIA-Nemotron-3.5-Bolt-E4B in bf16 with DFlash and vision on one card, and E4B recipes Speed: - MXFP4 GEMMs for one to 64 rows and a tiled prefill GEMM at TN=4 from 1024 rows: the 27B MXFP4 with DFlash2 decodes about 1% faster at c1, 5% at c4 and 14% at c16 - The fp8 and int8 LM heads read their weight once for 65 to 128 rows - A prefill step of one sequence runs in two pieces on a second lane at two ranks (qwen35_fp8, gemma3): a 45K-token prompt on the 27B fp8 in 15.1 s instead of 16.2 s - Gemma 3's fused all-reduce junctions also under a lossy wire - --draft-short-from N: a block drafter runs its shorter block from N decoding sequences on (off by default; with 8 on the 27B MXFP4: c8 +12%, c16 +18%, c64 +32%, c1 unchanged) - --tp-attn-split rows: GLM-5.3-Flash's MLA attention split by rows over the ranks, 18 to 21% faster prefill; lossy, `heads` stays the default - --draft-coupling on: Qwen3.8-Flash-Next's MTP drafter samples its proposals from its reranked top-8 and the target's draw is coupled to it; pays at high temperatures (c1 at T 1.0: 155 -> 178 tok/s), costs at low ones; off by default Features: - Edited prompts on windowed models (Gemma 4) reuse their prefix: periodic window snapshots, and snapshot-backed prefix KV kept across recomputes (an edited tail on Gemma 4 31B: 96 s -> 2.6 s) - DELETE /sessions/<label> and DELETE /sessions?id=<id> forget one stored conversation - --state-cache-dtype f16: the delta-net state cache at half the memory (qwen35 plugins; lossy) Fixes: - A browser's CORS preflight allows DELETE Changes: Plugin ABI 27: out-of-tree plugins must be rebuilt. The environment switches the PRs added are flags now (--tp-attn-split, --draft-coupling, --state-cache-dtype).
This commit is contained in:
10 parents
4bca30369b
b1f4fccc52
d90e19dc15
3aded1bbf8
d912c694f3
824e238996
58142a6638
9322ea0b92
e9d03362f0
4d68a01a08
commit
5a9ce4912b
137 files changed
+12959
-1126
No files matched your search
+4
-1
@@ -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()
|
||||
|
||||
@@ -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.
|
||||
|
||||
@@ -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
|
||||
|
||||
+16
-3
@@ -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
|
||||
|
||||
+102
-17
@@ -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
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 <math.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
/* 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 */
|
||||
@@ -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));
|
||||
|
||||
@@ -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 <algorithm>
|
||||
#include <cmath>
|
||||
#include <vector>
|
||||
|
||||
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
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
+47
-14
@@ -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 `<base>.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 `<base>.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
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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 <cstdlib>
|
||||
#include <cstring>
|
||||
|
||||
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
|
||||
@@ -0,0 +1,10 @@
|
||||
# Built in radiance's tree, or standalone against an installed radiance
|
||||
# (`cmake -S arch/fishomni -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`); 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)
|
||||
File diff suppressed because it is too large.
Load diff
+23
-22
@@ -21,7 +21,6 @@
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_block_dflash2.h>
|
||||
#include <arch/rad_prefill_pipe.h>
|
||||
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
@@ -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
|
||||
|
||||
@@ -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<Layer> 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
|
||||
|
||||
@@ -87,9 +87,7 @@
|
||||
#include <arch/rad_block_mtp_fp8.h>
|
||||
#include <arch/rad_block_dflash2.h>
|
||||
#include <arch/rad_block_vit.h>
|
||||
#include <arch/rad_prefill_pipe.h>
|
||||
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
@@ -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 <class F>
|
||||
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);
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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. */
|
||||
|
||||
@@ -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); } },
|
||||
|
||||
+38
-20
@@ -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<StallWatch> 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<gen::AudioRequest> 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;
|
||||
|
||||
@@ -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 <map>
|
||||
#include <set>
|
||||
@@ -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<RadMtpCoupleDraw> 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<Scheduler::BlockRow> 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. */
|
||||
|
||||
@@ -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. */
|
||||
|
||||
+175
-5
@@ -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 <chrono>
|
||||
#include <cstdint>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
@@ -48,6 +52,55 @@ int Engine::step_state_init() {
|
||||
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0]->device));
|
||||
slots_host_ = static_cast<StepSlot*>(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<RadMtpCoupleDraw*>(
|
||||
rad_dev_alloc(n_slot * (int64_t)sizeof(RadMtpCoupleDraw), RAD_MEM_HOST_PINNED));
|
||||
couple_readback_ = static_cast<RadMtpCoupleState*>(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];
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -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 `<stem>.`, 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<std::string> 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<TorchZipFile>();
|
||||
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() {
|
||||
|
||||
@@ -24,6 +24,7 @@
|
||||
#include "../rad_internal.h"
|
||||
#include "../rad_core.h"
|
||||
#include "safetensors.h"
|
||||
#include "torch_zip.h"
|
||||
#include "../text/gguf.h"
|
||||
|
||||
#include <deque>
|
||||
@@ -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<std::unique_ptr<SafeTensorsFile>> shards_;
|
||||
std::vector<std::unique_ptr<TorchZipFile>> torch_;
|
||||
std::vector<SrcTensor> tensors_;
|
||||
std::unordered_map<std::string, size_t> index_;
|
||||
std::unordered_map<std::string, size_t> index_shard_; /* name -> shards_ position */
|
||||
|
||||
@@ -0,0 +1,661 @@
|
||||
/* torch_zip.cpp -- the zip directory and the weights-only pickle machine (torch_zip.h). */
|
||||
#include "torch_zip.h"
|
||||
|
||||
#include <cerrno>
|
||||
#include <cstring>
|
||||
#include <fcntl.h>
|
||||
#include <sys/mman.h>
|
||||
#include <sys/stat.h>
|
||||
#include <unistd.h>
|
||||
#include <unordered_map>
|
||||
|
||||
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<std::string, Entry>* 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<size_t> 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<int64_t> 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<size_t>* 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<V> pool_;
|
||||
std::vector<size_t> stack_, marks_;
|
||||
std::unordered_map<uint32_t, size_t> 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', <storage class>, 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<size_t> 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<size_t> 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<size_t> 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<char>* seen, std::vector<std::pair<std::string, size_t>>* 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<std::string, Entry> 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 <archive>/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<std::pair<std::string, size_t>> found;
|
||||
std::vector<char> 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 */
|
||||
@@ -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: `<archive>/data.pkl`, a pickle of the
|
||||
* state dict whose tensors name their bytes by a persistent id, `<archive>/data/<key>` holding
|
||||
* each storage's raw little-endian bytes, and `<archive>/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 <string>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
|
||||
struct TorchTensor {
|
||||
std::string name;
|
||||
uint32_t dtype = RAD_DT_INVALID;
|
||||
std::string storage; /* the torch storage class, for diagnostics */
|
||||
std::vector<int64_t> 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<TorchTensor>& 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<TorchTensor> tensors_;
|
||||
};
|
||||
|
||||
} /* namespace rad */
|
||||
@@ -65,6 +65,12 @@ struct AudioRequest {
|
||||
* conditional prompt as the declaration says (neg_token), and `neg_tokens` is empty. */
|
||||
std::vector<int32_t> tokens;
|
||||
std::vector<int32_t> 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<float> ref_audio;
|
||||
std::vector<int32_t> ref_cu;
|
||||
std::vector<int32_t> 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 */
|
||||
|
||||
+206
-42
@@ -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<Ran
|
||||
name_ = prog.agen_str.name;
|
||||
kv_ = kv;
|
||||
ranks_ = ranks;
|
||||
/* The language model's KV, both branches of every lane: one paged full-attention group. */
|
||||
if (prog.kv_groups.size() != 2 || prog.kv_groups[1].decl.kind != RAD_KV_FULL ||
|
||||
prog.kv_groups[1].block_size <= 0) {
|
||||
RAD_ERR("audio generator: the program declares %zu KV group(s); the driver stages exactly "
|
||||
"one full-attention group, the language model's", prog.kv_groups.size() - 1);
|
||||
/* The language model's KV, every branch of every lane: one paged full-attention group, and
|
||||
* a hybrid model's linear-attention state and convolution groups beside it. */
|
||||
state_groups_.clear();
|
||||
int n_full = 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) {
|
||||
++n_full;
|
||||
} else if (kind == RAD_KV_LINEAR || kind == RAD_KV_CONV) {
|
||||
StateGroup sg;
|
||||
sg.g = (int32_t)g;
|
||||
sg.width = std::max<int64_t>(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<Ran
|
||||
* chunk's vocode its frames and their context, and a whole prompt both its branches. */
|
||||
const int64_t step_rows = chunked() ? decl_.voc_context + decl_.voc_chunk
|
||||
: 2 * (decl_.win_lead + win_latents(decl_.win_frames));
|
||||
const int64_t prompt_rows = decl_.prompt_whole ? 2 * decl_.max_prompt : 2;
|
||||
if (max_seqs_ < 2 * decl_.max_lanes || max_tok_ < 2 * decl_.max_lanes ||
|
||||
const int64_t prompt_rows = decl_.prompt_whole ? nb_ * decl_.max_prompt : nb_;
|
||||
if (max_seqs_ < nb_ * decl_.max_lanes || max_tok_ < nb_ * decl_.max_lanes ||
|
||||
max_tok_ < step_rows || max_tok_ < prompt_rows) {
|
||||
RAD_ERR("audio generator: a pass carries %lld rows of %lld sequences; '%s' needs %lld "
|
||||
"sequences for its %lld lanes, %lld rows for a %s and %lld for a whole prompt",
|
||||
(long long)max_tok_, (long long)max_seqs_, name_.c_str(),
|
||||
(long long)(2 * decl_.max_lanes), (long long)decl_.max_lanes,
|
||||
(long long)(nb_ * decl_.max_lanes), (long long)decl_.max_lanes,
|
||||
(long long)step_rows, chunked() ? "chunk's vocode" : "window's step",
|
||||
(long long)prompt_rows);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
@@ -191,7 +245,7 @@ int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector<Ran
|
||||
if (!ranks_.empty()) RAD_TRY(rad_dev_set(ranks_[0].device));
|
||||
out_.assign(ranks_.size(), RadBatch{});
|
||||
aout_.assign(ranks_.size(), RadAudioGenBatch{});
|
||||
kout_.assign(ranks_.size(), RadKVGroupBatch{});
|
||||
kout_.assign(ranks_.size() * (1 + state_groups_.size()), RadKVGroupBatch{});
|
||||
free_lanes_.clear();
|
||||
for (int64_t i = decl_.max_lanes - 1; i >= 0; --i) free_lanes_.push_back((int32_t)i);
|
||||
return RAD_OK;
|
||||
@@ -222,7 +276,9 @@ int AudioDriver::submit(std::unique_ptr<AudioRequest> 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<AudioRequest> 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<int32_t> 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<int32_t> 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<int32_t>(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<int32_t>(ri, R_SBT) + gi * max_seqs_;
|
||||
Ks.block_table_pitch = 1;
|
||||
Ks.seqused = dptr<int32_t>(ri, R_USED);
|
||||
Ks.state_index = dptr<int32_t>(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<int32_t>(ri, R_CTX);
|
||||
B.num_accepted = dptr<int32_t>(ri, R_ACC);
|
||||
}
|
||||
A = RadAudioGenBatch{};
|
||||
A.lane = dptr<int32_t>(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<int32_t>(ri, R_ESLOT);
|
||||
A.last_row = dptr<int32_t>(ri, R_LROW);
|
||||
A.prefix = dptr<int32_t>(ri, R_PREFIX);
|
||||
A.prev_slot = dptr<int32_t>(ri, R_PSLOT);
|
||||
A.prev_pos = dptr<int32_t>(ri, R_PPOS);
|
||||
A.prev_used = dptr<int32_t>(ri, R_PUSED);
|
||||
B.agen_b = &A;
|
||||
}
|
||||
}
|
||||
|
||||
void AudioDriver::stage_state(const std::vector<uint64_t>& seqs, const std::vector<int32_t>& ctx) {
|
||||
const int64_t n = (int64_t)seqs.size();
|
||||
int32_t* cl = hptr<int32_t>(R_CTX);
|
||||
int32_t* acc = hptr<int32_t>(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<int32_t>(R_SBT) + gi * max_seqs_;
|
||||
int32_t* si = hptr<int32_t>(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<int32_t>& 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<int64_t>(j.T - j.prompt_done, max_tok_ / 2);
|
||||
cb[0] = std::min<int64_t>(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<int32_t>(R_TOK);
|
||||
@@ -528,12 +650,12 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
|
||||
int32_t* slot = hptr<int32_t>(R_SLOT);
|
||||
int32_t* cu = hptr<int32_t>(R_CU);
|
||||
int64_t pitch = 1;
|
||||
for (int b = 0; b < 2; ++b)
|
||||
for (int b = 0; b < nb_; ++b)
|
||||
pitch = std::max<int64_t>(pitch, (int64_t)kv_->block_table(j.seq[b], kv_group_).size());
|
||||
int32_t* btab = hptr<int32_t>(R_BT);
|
||||
int32_t* used = hptr<int32_t>(R_USED);
|
||||
cu[0] = 0;
|
||||
for (int b = 0; b < 2; ++b) {
|
||||
for (int b = 0; b < nb_; ++b) {
|
||||
const std::vector<int32_t>& src = b ? j.neg : j.req->tokens;
|
||||
const std::vector<int32_t>& 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<int32_t>(R_ESLOT)[b] = 2 * j.lane + b;
|
||||
std::vector<uint64_t> seqs;
|
||||
std::vector<int32_t> ctx;
|
||||
for (int b = 0; b < nb_; ++b) {
|
||||
hptr<int32_t>(R_ESLOT)[b] = nb_ * j.lane + b;
|
||||
hptr<int32_t>(R_LROW)[b] = cu[b + 1] - 1;
|
||||
hptr<int32_t>(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<int32_t>(R_LANE)[0] = j.lane;
|
||||
hptr<int32_t>(R_LAST)[0] = last ? 1 : 0;
|
||||
hptr<uint32_t>(R_SEED)[0] = (uint32_t)(j.req->seed & 0xffffffffu);
|
||||
hptr<uint32_t>(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<float>(R_RAUD), q.ref_audio.data(), q.ref_audio.size() * 4);
|
||||
std::memcpy(hptr<int32_t>(R_RCU), q.ref_cu.data(), q.ref_cu.size() * 4);
|
||||
std::memcpy(hptr<int32_t>(R_RFRM), q.ref_frame.data() + p0, (size_t)cb[0] * 4);
|
||||
reg_[R_RAUD].used = (int64_t)q.ref_audio.size() * 4;
|
||||
reg_[R_RCU].used = (int64_t)q.ref_cu.size() * 4;
|
||||
reg_[R_RFRM].used = cb[0] * 4;
|
||||
h_rcu_ = q.ref_cu;
|
||||
h_rfrm_.assign(q.ref_frame.begin() + p0, q.ref_frame.begin() + p0 + cb[0]);
|
||||
}
|
||||
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<float>(ri, R_RAUD);
|
||||
A.ref_cu = dptr<int32_t>(ri, R_RCU);
|
||||
A.ref_cu_h = h_rcu_.data();
|
||||
A.ref_frame = dptr<int32_t>(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<Job*>& 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<int32_t>(R_TOK);
|
||||
int32_t* pos = hptr<int32_t>(R_POS);
|
||||
int32_t* slot = hptr<int32_t>(R_SLOT);
|
||||
@@ -597,17 +750,19 @@ const RadBatch* AudioDriver::build_frame(const std::vector<Job*>& 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<int64_t>(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<uint64_t> seqs;
|
||||
std::vector<int32_t> 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<int32_t>& 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<Job*>& 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<int32_t>(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<int32_t>(R_PSLOT)[e] = slot_of(bt, p - 1, block_size_);
|
||||
hptr<int32_t>(R_PPOS)[e] = (int32_t)(p - 1);
|
||||
hptr<int32_t>(R_PUSED)[e] = (int32_t)p;
|
||||
hptr<int32_t>(R_ESLOT)[e] = nb_ * j.lane + b;
|
||||
hptr<int32_t>(R_LROW)[e] = (int32_t)e;
|
||||
max_ctx = std::max<int32_t>(max_ctx, (int32_t)(p + 1));
|
||||
seqs.push_back(j.seq[b]);
|
||||
ctx.push_back((int32_t)p);
|
||||
}
|
||||
hptr<float>(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<Job*>& 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<Job*>& 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) {
|
||||
|
||||
+24
-6
@@ -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 <class T> T* hptr(int r) const { return reinterpret_cast<T*>(host_ + reg_[r].off); }
|
||||
template <class T> 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<uint64_t>& seqs, const std::vector<int32_t>& 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<StateGroup> state_groups_;
|
||||
int nb_ = 2; /* sequences a request: RadAudioGenDecl::branches */
|
||||
bool neg_own_ = false; /* the unconditional prompt is the request's own */
|
||||
std::vector<RankIO> ranks_;
|
||||
IKVManager* kv_ = nullptr;
|
||||
@@ -167,12 +185,12 @@ private:
|
||||
|
||||
std::vector<RadBatch> out_; /* one per rank */
|
||||
std::vector<RadAudioGenBatch> aout_;
|
||||
std::vector<RadKVGroupBatch> kout_;
|
||||
std::vector<RadKVGroupBatch> 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<int32_t> 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<std::unique_ptr<Job>> jobs_; /* arrival order */
|
||||
|
||||
@@ -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<SessionChain>* 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<BlockHash>& chain,
|
||||
const std::vector<uint64_t>& 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<BlockHash>& 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::SessionInfo> IdleTiers::sessions(Occupancy* occ) const {
|
||||
/* One slice's hold on the lock (YieldingMutex). */
|
||||
struct Slice {
|
||||
|
||||
@@ -246,6 +246,31 @@ public:
|
||||
* microseconds apart. */
|
||||
std::vector<SessionInfo> 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<BlockHash> 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<SessionChain>* 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<BlockHash>& chain,
|
||||
const std::vector<uint64_t>& 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. */
|
||||
|
||||
+88
-7
@@ -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<int32_t> 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<IdleTiers::SessionChain> rows;
|
||||
tiers_->find_sessions(label, id, &rows);
|
||||
if (rows.empty()) return RAD_E_NOTFOUND;
|
||||
std::vector<uint64_t> 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<int64_t>(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 */
|
||||
@@ -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_; }
|
||||
|
||||
|
||||
@@ -442,6 +442,9 @@ int Registry::commit_(Staged& s, int order) {
|
||||
const auto concurrent = dl_fn<RadKernelConcurrentFn>(s.handle, "rad_kernel_concurrent");
|
||||
const auto collective = dl_fn<RadKernelCollectiveFn>(s.handle, "rad_kernel_collective");
|
||||
const auto chainable = dl_fn<RadKernelChainFn>(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<RadKernelReferenceFn>(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);
|
||||
}
|
||||
|
||||
+16
-1
@@ -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) ----------------
|
||||
*
|
||||
|
||||
+7
-2
@@ -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;
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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 <string>
|
||||
|
||||
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 <class Live>
|
||||
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
|
||||
+86
-2
@@ -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<Request*>& 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<Request*>& 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<Request*>& 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<Request*>& 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
|
||||
|
||||
+45
-2
@@ -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 <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
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<Request*>& 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<Request*>& 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<std::pair<uint64_t, int64_t>> 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;
|
||||
|
||||
@@ -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 "
|
||||
|
||||
@@ -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; }
|
||||
};
|
||||
|
||||
@@ -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); }
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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 <cstring>
|
||||
#include <string>
|
||||
|
||||
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
|
||||
@@ -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 <cstdint>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
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<RadMtpCoupleDraw>* 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
|
||||
@@ -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<std::mutex> 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<std::mutex> 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<std::mutex> 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<std::mutex> 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<int32_t>& 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<std::mutex> 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;
|
||||
|
||||
@@ -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<CommittedSeq> committed_;
|
||||
/* The single-sequence decode floor (rad::DecodeFloor), fed by step_finished. */
|
||||
DecodeFloor decode_floor_;
|
||||
|
||||
|
||||
@@ -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 {
|
||||
|
||||
+136
-15
@@ -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 <nlohmann/json.hpp>
|
||||
@@ -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<double>() == 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<double>() >= 1.0) ||
|
||||
body["guidance_scale"].get<double>() > 30.0)
|
||||
return fail(err_bad("guidance_scale", "expected a number in [1, 30]"));
|
||||
if (info.branches == 1 && body["guidance_scale"].get<double>() != 1.0)
|
||||
return fail(err_unsupported("guidance_scale", "this model runs without guidance"));
|
||||
r->cfg = (float)body["guidance_scale"].get<double>();
|
||||
}
|
||||
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<Ref> 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<int64_t>(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<std::string>()))
|
||||
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<const std::string&>();
|
||||
std::vector<uint8_t> 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<float> 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<std::string>(), &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<int32_t>* 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<int32_t>* 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<int32_t>* 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;
|
||||
|
||||
@@ -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/<label>, "
|
||||
"?label=<label> or ?id=<engine id>"), req.peer);
|
||||
int64_t keep_tokens = 0;
|
||||
const std::string keep_s = req.param("keep_tokens");
|
||||
if (!keep_s.empty()) {
|
||||
if (keep_s.find_first_not_of("0123456789") != std::string::npos || keep_s.size() > 12)
|
||||
return error_response(err_bad("keep_tokens", "expected a non-negative integer: the "
|
||||
"prefix to keep, in tokens"), req.peer);
|
||||
keep_tokens = std::stoll(keep_s);
|
||||
}
|
||||
|
||||
SessionReleased r;
|
||||
const int rc = deps_.sched->release_session(label, id, keep_tokens, &r);
|
||||
if (rc == RAD_E_UNSUPPORTED)
|
||||
return error_response(err_not_implemented(
|
||||
"this engine has no prefix cache (started with --no-prefix-cache, or the model "
|
||||
"declares no cacheable KV group)"), req.peer);
|
||||
const std::string who = label.empty() ? "id " + std::to_string(id) : "'" + label + "'";
|
||||
if (rc == RAD_E_NOTFOUND) {
|
||||
ApiError e;
|
||||
e.status = 404;
|
||||
e.type = "not_found_error";
|
||||
e.param = label.empty() ? "id" : "label";
|
||||
e.message = "no stored session " + who + "; GET /sessions lists them";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
if (rc == RAD_E_STATE) {
|
||||
ApiError e;
|
||||
e.status = 409;
|
||||
e.type = "conflict_error";
|
||||
e.code = "session_in_use";
|
||||
e.message = "a request of session " + who + " is queued or running; cancel it or wait "
|
||||
"for it to finish, then release again";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
if (rc == RAD_E_INVAL)
|
||||
return error_response(err_bad("keep_tokens", rad_strerror(rc)), req.peer);
|
||||
if (rc < 0) return error_response(err_internal(rad_strerror(rc)), req.peer);
|
||||
|
||||
json o;
|
||||
if (!label.empty()) o["label"] = label;
|
||||
if (id != 0) o["id"] = id;
|
||||
o["keep_tokens"] = keep_tokens;
|
||||
o["sessions"] = r.sessions;
|
||||
o["entries"] = r.entries;
|
||||
o["tokens"] = r.tokens;
|
||||
o["device_bytes"] = r.device_bytes;
|
||||
o["host_bytes"] = r.host_bytes;
|
||||
o["snapshots"] = r.snapshots;
|
||||
o["kept"] = { { "tokens", r.kept_tokens }, { "shared", r.kept_shared },
|
||||
{ "live", r.kept_live } };
|
||||
metrics_.observe_http(200);
|
||||
return HttpResponse::json_body(200, json_dump(o));
|
||||
}
|
||||
|
||||
HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
json o;
|
||||
o["model"] = opt_.model_id;
|
||||
@@ -234,6 +313,8 @@ HttpResponse Server::handle_stats(const HttpRequest&) {
|
||||
o["ckpt_evictions"] = { { "retention", m.prefix_ckpt_retired },
|
||||
{ "store_full", m.prefix_ckpt_lru } };
|
||||
o["ckpt_refused"] = m.prefix_ckpt_refused;
|
||||
o["released"] = { { "entries", m.prefix_released },
|
||||
{ "snapshots", m.prefix_ckpt_released } };
|
||||
o["hit_cuts"] = { { "no_snapshot", m.hit_cut_no_snapshot },
|
||||
{ "windowed_group", m.hit_cut_window },
|
||||
{ "adopt_failed", m.hit_cut_adopt },
|
||||
|
||||
@@ -506,7 +506,7 @@ int HttpTransport::serve(const Router& router, const TransportOptions& o) {
|
||||
* anthropic-version and anthropic-beta headers of Anthropic's clients, which nothing reads. */
|
||||
static const char* const kCorsHeaders =
|
||||
"Content-Type, Authorization, X-Api-Key, anthropic-version, anthropic-beta";
|
||||
static const char* const kCorsMethods = "GET, POST, OPTIONS";
|
||||
static const char* const kCorsMethods = "GET, POST, DELETE, OPTIONS";
|
||||
|
||||
/* Whether a request carries the API key: `Authorization: Bearer` (OpenAI; the scheme is
|
||||
* case-insensitive, RFC 9110) or `X-Api-Key` (Anthropic, also accepted by llama-server). */
|
||||
|
||||
@@ -78,6 +78,7 @@ struct SchedMetrics {
|
||||
int64_t prefix_restore_cuts = 0;
|
||||
/* Removed by --prefix-cache-ttl, cumulative. Not evictions: nothing wanted the memory. */
|
||||
int64_t prefix_expired = 0, prefix_ckpt_expired = 0;
|
||||
int64_t prefix_released = 0, prefix_ckpt_released = 0;
|
||||
/* Decoupled prefix caching (spec §7.3). `prefix_hit_rate` is the attention hit rate, as in
|
||||
* vLLM. The linear side hits at a different granularity (whole checkpoints, not blocks), so
|
||||
* it is reported separately, with token counts and checkpoints written. */
|
||||
@@ -168,6 +169,17 @@ struct SessionOccupancy {
|
||||
int64_t host_cap_bytes = 0;
|
||||
};
|
||||
|
||||
/* What a release took out of the store and what it left (PrefixCache::release_session). The
|
||||
* kept counts are apart on purpose: `shared` blocks belong to another stored conversation too,
|
||||
* `live` ones to a request still reading them. */
|
||||
struct SessionReleased {
|
||||
int64_t sessions = 0;
|
||||
int64_t entries = 0, tokens = 0;
|
||||
int64_t device_bytes = 0, host_bytes = 0;
|
||||
int64_t snapshots = 0;
|
||||
int64_t kept_tokens = 0, kept_shared = 0, kept_live = 0;
|
||||
};
|
||||
|
||||
/* One in-flight request, for the live request table: shows which request is stuck, e.g. one
|
||||
* waiting on a prompt that will never fit, which no aggregate metric reveals. */
|
||||
struct RequestStat {
|
||||
@@ -225,6 +237,15 @@ public:
|
||||
* allocated), but it takes the scheduler's lock because a step may be inserting into the map. */
|
||||
virtual int64_t reset_prefix_cache() { return RAD_E_UNSUPPORTED; }
|
||||
|
||||
/* Forgets one stored conversation (DELETE /sessions): every row carrying `label`, or with
|
||||
* `id` nonzero the row of that engine id; `keep_tokens` leaves the chain's start standing.
|
||||
* RAD_E_NOTFOUND when nothing matches (404), RAD_E_STATE while a request of that
|
||||
* conversation is queued or running (409), RAD_E_UNSUPPORTED without a prefix cache (501). */
|
||||
virtual int release_session(const std::string& /*label*/, uint64_t /*id*/,
|
||||
int64_t /*keep_tokens*/, SessionReleased* /*out*/) {
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* The live request table, oldest first; returns the count. Default: none kept. */
|
||||
virtual int requests(std::vector<RequestStat>* /*out*/) const { return 0; }
|
||||
|
||||
@@ -662,6 +683,15 @@ struct AudioGenInfo {
|
||||
int64_t sample_rate = 0, channels = 0;
|
||||
int64_t default_steps = 0, max_lanes = 1; /* default_steps 0: no denoiser */
|
||||
double default_cfg = 1.0;
|
||||
/* RadAudioGenDecl::branches (1: no guidance) and ::input_special (the {input} slot is
|
||||
* tokenised with special tokens). */
|
||||
int32_t branches = 2;
|
||||
bool input_special = false;
|
||||
/* RadAudioGenDecl's references: the prompt with them and one reference ("" when the model
|
||||
* takes none), the clips' rate and frame, and the most of them and their samples. */
|
||||
std::string tmpl_ref, ref_item;
|
||||
int64_t ref_rate = 0, ref_hop = 0, ref_max_samples = 0;
|
||||
int32_t ref_max = 0;
|
||||
};
|
||||
|
||||
class IAudioGen {
|
||||
|
||||
@@ -189,6 +189,8 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
c_prefix_ckpt_evict_.advance_to(m.prefix_ckpt_evictions);
|
||||
c_prefix_expired_.advance_to(m.prefix_expired);
|
||||
c_prefix_ckpt_expired_.advance_to(m.prefix_ckpt_expired);
|
||||
c_prefix_released_.advance_to(m.prefix_released);
|
||||
c_prefix_ckpt_released_.advance_to(m.prefix_ckpt_released);
|
||||
c_ckpt_retired_.advance_to(m.prefix_ckpt_retired);
|
||||
c_ckpt_lru_.advance_to(m.prefix_ckpt_lru);
|
||||
c_ckpt_refused_.advance_to(m.prefix_ckpt_refused);
|
||||
@@ -438,6 +440,13 @@ std::string Metrics::render() const {
|
||||
c_ckpt_retired_.get());
|
||||
labelled("radiance:prefix_cache_ckpt_evictions_by_reason_total", "reason", "store_full",
|
||||
c_ckpt_lru_.get());
|
||||
w.help("radiance:prefix_cache_released_total",
|
||||
"Prefix-cache entries and linear-state snapshots a client released on purpose "
|
||||
"(DELETE /sessions).", "counter");
|
||||
labelled("radiance:prefix_cache_released_total", "what", "entries",
|
||||
c_prefix_released_.get());
|
||||
labelled("radiance:prefix_cache_released_total", "what", "snapshots",
|
||||
c_prefix_ckpt_released_.get());
|
||||
w.counter("radiance:prefix_cache_ckpt_refused_total",
|
||||
"Checkpoints not written because every snapshot slot was in use by a restore "
|
||||
"in the same step.", L, c_ckpt_refused_.get());
|
||||
|
||||
@@ -151,6 +151,7 @@ private:
|
||||
Counter c_attn_cached_, c_linear_cached_, c_checkpoints_;
|
||||
Counter c_prefix_evict_, c_prefix_ckpt_evict_;
|
||||
Counter c_prefix_expired_, c_prefix_ckpt_expired_;
|
||||
Counter c_prefix_released_, c_prefix_ckpt_released_;
|
||||
Counter c_ckpt_retired_, c_ckpt_lru_, c_ckpt_refused_;
|
||||
Counter c_cut_no_snapshot_, c_cut_window_, c_cut_adopt_, c_cut_resumed_below_, c_cut_tokens_;
|
||||
Counter c_restore_cuts_;
|
||||
|
||||
@@ -210,6 +210,12 @@ void Server::register_routes() {
|
||||
[this](const HttpRequest& q) { return handle_control_vector(q); });
|
||||
router_.post("/admin/control-vector",
|
||||
[this](const HttpRequest& q) { return handle_control_vector(q); });
|
||||
/* Forget one stored conversation: by its client label in the path (or `?label=`, for a
|
||||
* label the path cannot carry), or by engine id with `?id=`. */
|
||||
router_.add ("DELETE", "/sessions/:label",
|
||||
[this](const HttpRequest& q) { return handle_session_release(q); });
|
||||
router_.add ("DELETE", "/sessions",
|
||||
[this](const HttpRequest& q) { return handle_session_release(q); });
|
||||
}
|
||||
|
||||
/* Workers beyond the admission ceiling. A generation holds its connection's worker for its whole
|
||||
|
||||
@@ -330,6 +330,7 @@ private:
|
||||
* like every other route but the health probes and the page; without a key, POST answers
|
||||
* loopback clients only. */
|
||||
HttpResponse handle_control_vector(const HttpRequest& req);
|
||||
HttpResponse handle_session_release(const HttpRequest& req);
|
||||
|
||||
HttpResponse error_response(const ApiError& e, const std::string& peer,
|
||||
ApiShape shape = ApiShape::OpenAI);
|
||||
|
||||
@@ -214,7 +214,7 @@ bool Server::speech_stream_loop(SpeechSession& s, WsConn& ws) {
|
||||
static const char* kFields[] = {
|
||||
"type", "model", "instructions", "voice", "response_format", "speed", "seed",
|
||||
"max_new_tokens", "duration", "num_inference_steps", "guidance_scale", "user",
|
||||
"stream_audio", "split_granularity", "text_input_mode",
|
||||
"references", "stream_audio", "split_granularity", "text_input_mode",
|
||||
};
|
||||
json fields = json::object();
|
||||
for (auto it = j.begin(); it != j.end(); ++it) {
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
# drama3-fp8.recipe -- Fish Audio drama-3 as its release ships it: block-scaled fp8 routed experts,
|
||||
# everything else of the language model and the codebook tower bf16.
|
||||
#
|
||||
# rad-convert <fishaudio/drama-3 directory> \
|
||||
# --recipe data/recipes/drama3-fp8.recipe -o drama3-fp8.rad
|
||||
#
|
||||
# The directory holds the model and codec.pth, its codec, which is read as checkpoint tensors
|
||||
# under `codec.` (core/format/torch_zip.h). The model is kept as stored. The codec ships f32:
|
||||
# its weight-normalised convolutions are folded here, and its linears, convolutions and
|
||||
# codebooks cast to bf16, the precision fish-speech decodes and encodes at, while its norms,
|
||||
# layer scales, ConvNeXt gains and snake parameters stay f32 -- read once a pass or less. The
|
||||
# encoder's residual quantiser (codec.enc.vq*) stays f32 too: each step is an argmax over
|
||||
# cosines, which f32 weights decide as the reference's f32 encoder does.
|
||||
|
||||
codec.*.n1.weight cast dtype=f32
|
||||
codec.*.n2.weight cast dtype=f32
|
||||
codec.*.ls1.weight cast dtype=f32
|
||||
codec.*.ls2.weight cast dtype=f32
|
||||
codec.norm.weight cast dtype=f32
|
||||
codec.up*.ln.* cast dtype=f32
|
||||
codec.up*.gamma cast dtype=f32
|
||||
codec.*.alpha cast dtype=f32
|
||||
codec.enc.*norm.weight cast dtype=f32
|
||||
codec.enc.down*.ln.* cast dtype=f32
|
||||
codec.enc.down*.gamma cast dtype=f32
|
||||
codec.enc.vq* cast dtype=f32
|
||||
codec.* cast dtype=bf16
|
||||
@@ -0,0 +1,16 @@
|
||||
# Fish Audio drama-3 (fishaudio/drama-3) as released, its routed experts block-scaled fp8: speech on
|
||||
# /v1/audio/speech, whole or streamed, and text spoken as it is written over the
|
||||
# /v1/audio/speech/stream WebSocket. Speakers are named in the input (<|speaker:0|> to
|
||||
# <|speaker:15|>) and so is the direction ([laughs], [whispering], a bracketed style). Two cards.
|
||||
# Under the Fish Audio Community License, research, non-commercial use and small commercial use are
|
||||
# free; a service that lets others generate speech (an API, a TTS site) needs a licence from Fish
|
||||
# Audio, and so does imitating a real person's voice without their consent.
|
||||
name: radiance-drama3
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-drama3
|
||||
command: >
|
||||
--model /models/drama3-fp8.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 2
|
||||
+231
-39
@@ -17,7 +17,7 @@ plugin claims.
|
||||
| `arch/glm5next` | `glm5next` | *(empty)* | GLM-5.3-Flash from AMD's Quark MXFP4 export: four mHC residual streams over 34 KDA and 11 sparse latent-attention (MLA) layers with a DSA indexer, 288 MXFP4 experts at top-8 under sigmoid routing, block-FP8 attention and dense layers at f32 scales, each weight served as stored; its MTP layer is a serial drafter. Pictures through its vision tower (`arch/common/rad_block_glm_vision.h`); bf16 KV |
|
||||
| `arch/lfm2_bf16` | `lfm2` | *(empty)* | LiquidAI's LFM2 and LFM2-VL, bf16, one rank |
|
||||
| `arch/embgemma2` | `embeddinggemma2` | *(empty)* | EmbeddingGemma 2: a bidirectional encoder with Gemma 4's vision tower and audio conformer, pooled to one vector |
|
||||
| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`), or RedHatAI's DFlash2 speculator (`arch/common/rad_block_dflash2.h`) |
|
||||
| `arch/gemma4_bf16` | `gemma4` | `compressed-tensors` | Gemma 4 31B dense, and the E2B/E4B form at one rank, with its vision tower: sliding-window and proportional-RoPE global (`attention_k_eq_v`) attention, GELU ffn, softcapped logits; int4 codes with an f16 scale per 128 from Google's CT-INT4 (QAT) release or from bf16, served w4a8, or int8 codes on the same grid from bf16 (w8a8, the Q8 container). Optional draft model (`rad-convert --draft-model`): Google's assistant, with no cache of its own (`rad_drafter_shared_kv`), or z-lab's DFlash drafter, the block `arch/gemma4` serves (`arch/common/rad_gemma4_dflash.h`), or RedHatAI's DFlash2 speculator (`arch/common/rad_block_dflash2.h`) |
|
||||
| `arch/gemma3` | `gemma3` | *(empty)* | Gemma 3 dense text (TranslateGemma 27B) from the bf16 checkpoint: sliding-window and global attention at one head geometry, GemmaRMSNorm, GELU ffn; linears bf16, or int8, MXFP4 or asymmetric int4 over an activation scaled per (row, 128), as the recipe stores them. Optional DFlash2 drafter (`rad-convert --draft-model`) |
|
||||
| `arch/gemma4` | `gemma4` | *(empty)* | Gemma 4 text from Google's bf16 checkpoint (the 26B-A4B MoE and the dense sizes without per-layer embeddings) with z-lab's DFlash drafter; routed experts bf16 or block fp8 |
|
||||
| `arch/qwenimage21` | `qwenimage21` | *(empty)* | Qwen-Image 2.1 and 2.1-Turbo, an image generator, from the diffusers pipeline directory; DiT and text encoder bf16 or block fp8 |
|
||||
@@ -29,6 +29,7 @@ plugin claims.
|
||||
| `arch/qwen3asr_bf16` | `qwen3asr` | *(empty)* | Qwen3-ASR: a Whisper-style audio encoder over a dense Qwen3 decoder, speech to text |
|
||||
| `arch/minimaxmusic3` | `minimaxmusic3` | *(empty)* | MiniMax-Music3, songs from a description and lyrics: a Qwen3-8B frame model, a depth decoder, a flow-matching DiT and a DAC vocoder, from the diffusers pipeline directory, bf16 |
|
||||
| `arch/breeze` | `breeze` | *(empty)* | Breeze-TTS-2, speech from text and a description of the voice: a T5Gemma 2 text encoder, a Qwen3 backbone with a 16-codebook depth decoder and the Qwen3-TTS 12 Hz codec, from the release directory, bf16, one card |
|
||||
| `arch/fishomni` | `fishomni` | `bsgemm-moe` | Fish Audio drama-3, speech from text with speaker tags and inline direction, its voices cloned from reference clips: the Qwen3.5-35B-A3B backbone with its routed experts block fp8 at f32 scales and everything else bf16, a 13-layer codebook tower over the backbone's full-attention cache, and Fish S2's modified DAC, encoder and decoder (`codec.pth`, read as data); from the release directory, two cards |
|
||||
| `arch/minimaxh3` | `minimaxh3` | *(empty)* | MiniMax-H3, a video with its stereo soundtrack from text: Qwen3-VL-32B's language model as the text encoder, a 33B single-stream diffusion transformer, a tiled ViT video decoder and a BigVGAN audio decoder, from the diffusers pipeline directory; linears block fp8 (`data/recipes/minimax-h3-fp8.recipe`) |
|
||||
| `arch/ltx2` | `ltx2` | *(empty)* | LTX-2.5 (base and distilled), a video with its stereo soundtrack from text or from text and a first frame: Gemma 4's language model and two text connectors, the duration head, a dual-stream audio-video DiT with four-way guidance, the causal video VAE (tiled past the default canvas) or the diffusion decoder, the audio VAE with a BigVGAN vocoder and bandwidth extension, the x2 latent upsampler; bf16 or block fp8, one card |
|
||||
|
||||
@@ -228,7 +229,9 @@ Three groups, which is why hybrid KV groups are first-class:
|
||||
across the 48 linear layers, and it is what the prefix-cache checkpoint of `spec.md` §7.3
|
||||
snapshots. Its reads and writes dominate the two GDN kernels. libr4d also compiles an f16 form
|
||||
(elements are O(0.1); the f16 round trip is about 5e-4 relative) that would halve that traffic,
|
||||
but the plugins declare f32 because f16 changes the generated text. How a speculative step keeps a
|
||||
but the plugins declare f32 because f16 changes the generated text; `--state-cache-dtype f16`
|
||||
declares f16 for a deployment that accepts the loss (GUIDE §4.4: on Qwen3.8-27B MXFP4, mean KL
|
||||
+0.9..+2.2 %, decode +10 % at sixteen streams without speculation). How a speculative step keeps a
|
||||
state it can roll back is `docs/OPS.md`'s `state_form`.
|
||||
|
||||
## FP8
|
||||
@@ -447,12 +450,12 @@ the blocks share, places them and issues the step's order.
|
||||
|---|---|---|
|
||||
| `rad_block_glm_mhc.h` | `ManifoldConn` | the four-stream residual's read and write |
|
||||
| `rad_block_glm_kda.h` | `GlmKda`, `KdaState` | the 34 linear layers and their recurrence |
|
||||
| `rad_block_glm_mla.h` | `GlmMla`, `MlaLatent` | the 11 sparse MLA layers and their absorbed core |
|
||||
| `rad_block_glm_mla.h` | `GlmMla`, `MlaLatent` | the 11 sparse MLA layers, in the head form or the row form |
|
||||
| `rad_block_glm_indexer.h` | `GlmIndexer`, `DsaCache` | the DSA indexer, its key cache and selection |
|
||||
| `rad_block_glm_router.h` | `GlmRouter` | the correction-bias router, through `MoeFP8` |
|
||||
| `rad_block_glm_mtp.h` | `GlmMtp` | the draft head around the plugin's layer 45 |
|
||||
| `rad_block_glm_vision.h` | `GlmVision`, `MediaRows` | the tower, and its rows over the embeddings |
|
||||
| `rad_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the split threshold, the column split of a replicated f32 projection |
|
||||
| `rad_glm_tp.h` | `GlmTp`, `SplitF32Proj` | the shards, the one row rule, the split thresholds, the column split of a replicated f32 projection |
|
||||
|
||||
```
|
||||
45 layers, hidden 4096, vocab 154880 (embedding and lm_head separate, bf16)
|
||||
@@ -548,45 +551,64 @@ at eight ranks each card holds 22.06 GiB of them, 19.67 GiB the routed experts.
|
||||
layer's latent, index and tail for every row and runs its MoE on the proposal rows only.
|
||||
|
||||
**Tensor parallelism.** At 1, 2, 4 or 8 ranks; declare refuses any other. `tests/glm5next_test.cpp`
|
||||
declares and steps the whole plugin at 1, 4 and 8, against pinned graph and step hashes at 1 and
|
||||
8, the connection, router and index-gate splits at 1, 2, 4 and 8, the indexer's row split at 2
|
||||
and 8, the row rule at every world, each issue's operand count against the loaded kernel
|
||||
libraries' schemas, and every declared weight against the served container's names and encodings.
|
||||
declares and steps the whole plugin at 1 and 8 against pinned graph and step hashes (the head form,
|
||||
the row form), the connection, router and index-gate splits at 1, 2, 4 and 8,
|
||||
the indexer's row split at 2 and 8, the MLA row split at 1, 2, 4 and 8, the row rule at every
|
||||
world, each issue's operand count against the loaded kernel libraries' schemas, and every declared
|
||||
weight against the served container's names and encodings.
|
||||
|
||||
One row rule (`GlmTp::run_rows`): from a pass of `GlmTp::kSplitRows` = 256 rows, a replicated
|
||||
piece of work splits by rows over the ranks instead, each rank taking one run of ceil(T / world)
|
||||
rows rounded up to whole 16-byte words of the row it gathers, because an `all_gather` moves whole
|
||||
words: multiples of four rows for the indexer's one i32 length a row. The last run may be short;
|
||||
a rank whose run lies wholly past a small step takes the first run and computes dead rows, so
|
||||
every plane it gathers is written (`GlmTp::run_of`). The indexer also splits a smaller step, from
|
||||
16 rows once rows x live blocks reach 2^18 (`GlmTp::kSplitWork`). Below the thresholds, as in
|
||||
decode, the collective costs more than it saves and every rank runs the replicated form.
|
||||
One row rule (`GlmTp::run_rows`): from a pass of `GlmTp::kSplitRows` = 256 rows, a replicated or
|
||||
head-split piece of work splits by rows over the ranks instead, each rank taking one run of
|
||||
ceil(T / world) rows rounded up to whole 16-byte words of the row it gathers, because an
|
||||
`all_gather` moves whole words: whole rows for the MLA's 4096-wide bf16 output, multiples of four
|
||||
rows for the indexer's one i32 length a row. The last run may be short; a rank whose run lies
|
||||
wholly past a small step takes the first run and computes dead rows, so every plane it gathers is
|
||||
written (`GlmTp::run_of`). The indexer alone also splits a smaller step, from 16 rows once rows x
|
||||
live blocks reach 2^18 (`GlmTp::kSplitWork`). Below the thresholds, as in decode, the collective
|
||||
costs more than it saves and every rank runs the replicated or head-split form.
|
||||
|
||||
- The routed and the shared experts split their 2048 width into equal contiguous slices, 256 a
|
||||
rank at eight; each rank computes its slice of every expert, and the block's all-reduce sums
|
||||
them. The dense feed-forward splits its 12288 the same way.
|
||||
- MLA splits by whole heads: the rows of q_b and kv_b (8 heads a rank at eight) and the columns
|
||||
of o. q_a, kv_a and the latent are replicated.
|
||||
of o. q_a, kv_a and the latent are replicated. Under `--tp-attn-split rows`
|
||||
(RadBuildCtx::tp_attn_rows, docs/GUIDE.md §4.7), from the threshold, it splits by rows instead
|
||||
(`GlmMla::Form::rows`): each rank takes its run under the row rule, the last run shorter,
|
||||
through q_b, absorption, attention with all 64 heads (`mla_attn_rows_bf16`, docs/OPS.md),
|
||||
expansion and o, and an `all_gather` of whole runs takes the all-reduce's place. The latent
|
||||
cache and the DSA selection are whole on every rank, so nothing is exchanged before the
|
||||
attention. Each rank sends its run to seven peers, half the bytes of the two-shot all-reduce,
|
||||
and the gather shares that all-reduce's exchange instance. The price is q_b, kv_b and o at full
|
||||
width on every rank, 120 MiB a layer and 1.29 GiB a card over the 11 trunk layers (the MTP layer
|
||||
keeps its heads), about 0.1 GiB of activations besides. The head form is the default because
|
||||
the row form is not bit-identical to it, and this model turns that into a measurable
|
||||
divergence: against the head form over a 66,657-position corpus of English, German and code at
|
||||
eight ranks the row form scores a mean KL of 0.038 (median 0.010, p99 0.357, top-1 agreement
|
||||
91.9 %). The projections are not the cause (q_b and o give the head form's bytes, and o summed
|
||||
as eight rank partials leaves the KL where it is); the attention's rounding is: the rows kernel
|
||||
parts from the paired tile in about 0.1 % of every row's outputs by one bf16 step, and the
|
||||
16-head tile, which parts in the same share of every second row only, halves the KL. On eight
|
||||
R9700 at Gen5 links the row form prefills a 20k-token prompt at 5,016 tok/s against 4,246 in
|
||||
the head form (+18 %) and a 64k-token one at 4,975 against 4,117 (+21 %); decode is unchanged.
|
||||
- KDA splits its 64 heads, with them the q/k/v rows, the convolution taps and the state; the two
|
||||
rank-128 projections into the gates are replicated.
|
||||
- The indexer's key side is replicated: every rank keeps the whole index cache and its tail. Its
|
||||
query side splits by rows from the threshold: each rank scores its run under the row rule,
|
||||
R = 4 * ceil(T / (4 * ranks)) query rows (`DsaCache::part_rows`), against the whole cache
|
||||
(`dsa_score` with `row_part`, the last run's rows past the step scoring `-inf`) and selects for
|
||||
the rows of its run that exist, under the bounds the scorer rebased to the run's first row
|
||||
(`cu_part`, docs/OPS.md); two `all_gather`s lay the runs' page tables and lengths end to end,
|
||||
513 and 1 i32 a row, 8 MiB a layer at a 4096-row chunk. The run's queries are all a rank needs,
|
||||
so the query projection, its quantiser and the head gates run on the run's rows too, and the
|
||||
gates need no gather; the bf16 projection stays on the step's rows where a run would be 64 rows
|
||||
or fewer, the skinny band whose split count a tuned configuration may set. Each row's selection
|
||||
is the same kernels' answer to the same operands, so the joined table is bit-identical to one
|
||||
rank's and MLA reads it unchanged. The scoring grows with the context (every row scores every
|
||||
complete block of its sequence), so this is where long prompts gain: the score plane shrinks to
|
||||
one run (256 MiB to 32 MiB at 64k of context and a 4096-row chunk). A smaller step splits too
|
||||
from 16 rows once rows x live blocks reach 2^18 (`GlmTp::kSplitWork`): eight sequences
|
||||
verifying five drafts from about 22k of context, where the scoring of 48 rows outweighs the two
|
||||
gathers; a single sequence's decode never does, and below both thresholds the indexer runs
|
||||
whole.
|
||||
R = 4 * ceil(T / (4 * ranks)) query rows (`DsaCache::part_rows`), against the whole cache (`dsa_score` with `row_part`,
|
||||
the last run's rows past the step scoring `-inf`) and selects for the rows of its run that exist,
|
||||
under the bounds the scorer rebased to the run's first row (`cu_part`, docs/OPS.md); two
|
||||
`all_gather`s lay the runs' page tables and lengths end to end, 513 and 1 i32 a row, 8 MiB a layer
|
||||
at a 4096-row chunk. The run's queries are all a rank needs, so the query projection, its
|
||||
quantiser and the head gates run on the run's rows too, and the gates need no gather; the bf16
|
||||
projection stays on the step's rows where a run would be 64 rows or fewer, the skinny band whose
|
||||
split count a tuned configuration may set. Each row's selection is the same kernels' answer to
|
||||
the same operands, so the joined table is bit-identical to one rank's and MLA reads it unchanged.
|
||||
The scoring grows with the context (every row scores every complete block of its sequence), so
|
||||
this is where long prompts gain: the score plane shrinks to one run (256 MiB to 32 MiB at 64k of
|
||||
context and a 4096-row chunk). A smaller step splits too from 16 rows once rows x live blocks
|
||||
reach 2^18 (`GlmTp::kSplitWork`): eight sequences verifying five drafts from about 22k of
|
||||
context, where the scoring of 48 rows outweighs the two gathers; a single sequence's decode never
|
||||
does, and below both thresholds the indexer runs whole.
|
||||
- The vocabulary is row-sharded, 19360 rows a rank at eight; the embedding's all-reduce is exact.
|
||||
- The f32 projections (the router's 288 x 4096, the index head gates' 32 x 4096, each
|
||||
connection's mHC projection of 24 x 16384) are replicated. From a pass of 256 rows
|
||||
@@ -983,6 +1005,27 @@ chained form right behind the GEMM before the reduction, otherwise it rides the
|
||||
reads change no value; on 4x R9700 the 31B with DFlash2 decoded 15% faster with them, and without
|
||||
a drafter about 2%.
|
||||
|
||||
**The E2B/E4B form.** `arch/gemma4_bf16` serves Gemma 4's small dense form (tested on
|
||||
NVIDIA-Nemotron-3.5-Bolt-E4B, `deploy/compose/nemotron-3.5-bolt-e4b-bf16.yaml`) at one rank:
|
||||
- KV-shared layers: from layer `n_layer - num_kv_shared_layers` on, a layer projects q only and
|
||||
attends over the cache of the last earlier layer of its class that keeps one (E4B: sliding layers
|
||||
read 22, full layers 23). Shared layers are not bound to a KV group, so their pages hold nothing.
|
||||
- Per-layer embeddings (`hidden_size_per_layer_input`): a token table scaled by sqrt(width), plus
|
||||
the normed projection of the scaled embedding, mixed at 2^-0.5. Each layer runs a branch after
|
||||
its feed-forward: gate, gelu times its slice, projection, norm, add. On a w4a8 or w8a8 trunk
|
||||
the junction closes that branch instead of the feed-forward. Image positions read the pad
|
||||
token's row of the table, as the reference does. The branch is not split across ranks, so a
|
||||
deployment at more than one rank is refused.
|
||||
- The global class may keep its own v (`attention_k_eq_v` 0) and leave
|
||||
`num_global_key_value_heads` null; it then takes `num_key_value_heads`.
|
||||
- The vision tower's clipped linears (`use_clipped_linears`) clamp each projection's input and
|
||||
output to the bounds the checkpoint stores (`rad_block_gemma4_vision.h`).
|
||||
|
||||
NVIDIA's DFlash drafter states `dflash_config.causal: false`, with every layer sliding; that flag
|
||||
sets the sliding layers' causality. The recipes are `gemma4-e4b-bf16-df`, `-w8a8-df`, `-w4a8` and
|
||||
`-w4a8-df`. The bf16 container's KL to HF bf16 is 0.0015 with bf16 KV and 0.014 with fp8 KV, so
|
||||
the compose file serves bf16 KV.
|
||||
|
||||
**FP8 experts.** The experts are ~90% of the weight bytes, so each projection is served as the
|
||||
container holds it, per layer: bf16 by `moe_gemm`, block fp8 by `moe_gemm_q`. gate_up
|
||||
`[1408, 2816]` is whole 64-row tiles and 128-blocks. down `[2816, 704]` is not (the fp8 grouped
|
||||
@@ -1088,15 +1131,23 @@ above), which matters little for translation prompts, whose shared prefix is a l
|
||||
A linear reading the same activation as the one before it (k and v after q, up after gate) reuses
|
||||
its codes. On every trunk the q and k norms and both rotaries are one `qkv_norm_rope` at `v_norm` 0.
|
||||
On an MXFP4 trunk each junction (the branch's post-norm, the residual add, the next norm and the
|
||||
next linear's E4M3 quantiser) is one `ar_rmsnorm_post_quant_fp8` at two ranks on the exact wire,
|
||||
the branch's all-reduce in the same launch, or a post-norm and `rmsnorm_quant_fp8` otherwise; a
|
||||
w4a8 / w8a8 trunk takes `gemma4_bf16`'s fused junctions; an i8a8 or asymmetric-int4 trunk runs the
|
||||
chain. Where a row is missing the plugin declares the chain, and the startup notes say which form
|
||||
each took. Under calibration no junction is fused (below).
|
||||
next linear's E4M3 quantiser) is one `ar_rmsnorm_post_quant_fp8` at two ranks, the branch's
|
||||
all-reduce in the same launch, or a post-norm and `rmsnorm_quant_fp8` otherwise; a w4a8 / w8a8
|
||||
trunk takes `gemma4_bf16`'s fused junctions; an i8a8 or asymmetric-int4 trunk runs the chain.
|
||||
Where a row is missing the plugin declares the chain, and the startup notes say which form each
|
||||
took. Under calibration no junction is fused (below).
|
||||
|
||||
The two fused all-reduce junctions (`ar_rmsnorm_post_quant_fp8`, and `ar_rmsnorm_quant_i8` on a
|
||||
w4a8 / w8a8 trunk's int8 junction) send the exact wire only, and are byte-identical to
|
||||
`all_reduce` followed by the chain. Under `--tp-wire wht6` they are declared all the same and taken
|
||||
per step where the 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, so a lossy-wire
|
||||
deployment's decode takes one launch a junction instead of three (all-reduce, post-norm,
|
||||
junction). A fused step is the unfused exact step bit for bit.
|
||||
|
||||
**Pipelined prefill.** At two ranks an MXFP4 trunk with the fused fp8 junctions prefills a prompt
|
||||
of 1024 tokens or more in two pieces, the junctions and all-reduces of one beside the other's
|
||||
compute (GUIDE §4.5, `RADIANCE_PREFILL_PIPELINE`). The window KV group's `seqused` counts from its
|
||||
compute (GUIDE §4.5). The window KV group's `seqused` counts from its
|
||||
rebased first block, so the first piece's bound is computed on the card (`sub_i32`: the group's
|
||||
`seqused` less the second piece's rows), not taken from its position. The gain needs 1024-row
|
||||
pieces: serve at `--max-num-batched-tokens 2048`.
|
||||
@@ -1608,6 +1659,147 @@ codes. Whisper large-v3 transcribes radiance's speech word for word.
|
||||
|
||||
---
|
||||
|
||||
# `fishomni`: Fish Audio drama-3, speech
|
||||
|
||||
`arch/fishomni` declares an audio generator in its chunked form with one branch a request
|
||||
(`rad_declare_audio_generator`, `branches` 1, `voc_chunk`): PROMPT runs the backbone over the
|
||||
whole prompt and the codebook tower over every prompt row, FRAME draws one frame of every speech in
|
||||
flight and runs the backbone over its embedding, VOCODE plays a lane's newest frames, sixteen at
|
||||
most. It is served on `/v1/audio/speech` and `/v1/audio/speech/stream` ([GUIDE §5.15](GUIDE.md)),
|
||||
on two cards. The checkpoint is the release directory; its codec, `codec.pth`, is read with it as
|
||||
checkpoint tensors under `codec.` (a `torch.save` archive, read as data and never unpickled:
|
||||
`core/format/torch_zip.h`).
|
||||
|
||||
```
|
||||
backbone Qwen3.5-35B-A3B's language model, unchanged: 40 layers of 2048, three gated delta-net
|
||||
layers to one gated attention layer (16 q / 2 kv heads of 256, NeoX rotary on 64 dims
|
||||
at theta 1e7), 256 experts of 512 at top-8 and a gated shared expert of 512, (1 + w)
|
||||
norms but the delta net's output norm. Only the routed experts are fp8 (E4M3 at an f32
|
||||
scale a 128 x 128 block, `quant_method: bsgemm-moe`); the rest is bf16. A prompt row is
|
||||
a token; a frame's row is bf16(bf16(E_lm[248099 + c0] + E_cb[4096 + c1]) / sqrt 2):
|
||||
code 0 through its semantic token, code 1 through section 1 of the codebook table
|
||||
head the main token over 4097 candidates only, the end of speech (248046) and the 4096
|
||||
semantic tokens in id order: the lm_head's rows for them, replicated (the full head is
|
||||
never declared)
|
||||
tower 13 layers bound as layers 40..52 of the backbone's full-attention KV group, causal over
|
||||
the whole sequence at the backbone's positions: 4 shared layers that inject code 0, then
|
||||
one a codebook, layer k injecting code k - 1 and its head drawing code k (4096 outputs).
|
||||
A layer is m = eh_proj([enorm(e); hnorm(h)]), a pre-norm block (q, gate, k, v from
|
||||
wqkv's rows [Q 4096 | G 4096 | K 512 | V 512], (1 + w) q/k norms, GPT-J rotary on 64
|
||||
dims at 1e7, attention * sigmoid(gate), SwiGLU 6144), a final (1 + w) norm. The first
|
||||
shared layer also adds the input frame's codes 2..9, embedded and summed in f32
|
||||
sampling temperature 1.0, top-p 0.9 over the whole candidate set, then the top-k: the main
|
||||
token uncapped (256) and each head 30, as SGLang-Omni draws; a semantic first draw
|
||||
among the lane's last 16 picks is redrawn at 1.0 / 0.95 / 30 (`ras_pick`)
|
||||
codec Fish S2's modified DAC decoder: ten raw codebook rows of 8 (one of 4096, nine of 1024,
|
||||
codes 1..9 clamped to 1023), each through its own weight-normed 1x1 projection to 1024
|
||||
and summed; 8 layers of 1024 (16 heads of 64, GPT-J rotary on all 64 at theta 1e4,
|
||||
causal over 128 frames, plain RMS norms at 1e-5, layer scales); twice a transposed
|
||||
conv k2 s2 and a ConvNeXt block; a causal conv k7 to 1536; four blocks of snake, a
|
||||
weight-normed causal transposed conv (8, 8, 4, 2) and three residual units (dilations
|
||||
1, 3, 9); snake and a conv k7 to one channel, tanh: 2048 samples a frame, 44.1 kHz mono
|
||||
encoder the codec's, for a reference clip (mono 44.1 kHz, padded to whole frames): a causal
|
||||
weight-normed conv k7 to 64; four blocks of three residual units (snake, conv k7 at
|
||||
dilations 1, 3, 9, snake, conv k1) and a snake and a causal conv of kernel two strides
|
||||
(2, 4, 8, 8), doubling the channels; after the last a 4-layer transformer (window 512
|
||||
rows); snake, conv k3; twice a causal conv k2 s2 (plain weights) and a ConvNeXt block;
|
||||
the 8-layer pre-quantiser transformer (window 128 frames); the semantic codebook's
|
||||
nearest code by cosine, then nine residual steps (`vq_encode`): ten codes a frame
|
||||
```
|
||||
|
||||
The passes, which shift the tower by a row against the reference's loop:
|
||||
|
||||
- **PROMPT** runs the backbone over the prompt and leaves its last row's final-norm hidden state in
|
||||
the lane, then runs the tower over every row, teacher-forced: each row's label is the row after
|
||||
it, which in a text prompt is text, so every layer's code embedding is zero (the
|
||||
concatenation's embedding half is filled with zeros once). With references the codec's encoder
|
||||
first turns the request's clips into frames, written into a code plane at the prompt rows that
|
||||
name them (`RadAudioGenBatch::ref_frame`); a frame's row is embedded as a made frame's is, a row
|
||||
before a frame is labelled with it, a frame's row carries its own codes 2..9, and the window of
|
||||
main picks starts with the prompt's last 16 rows. The last row's tower pass belongs to the first
|
||||
frame; FRAME 0 writes its cache rows again.
|
||||
- **FRAME j** draws the main token from the hidden state of the row before the frame's (the
|
||||
prompt's last for frame 0), runs the tower at THAT row's position, cache slot and context
|
||||
(`RadAudioGenBatch::prev_slot`, `prev_pos`, `prev_used`) drawing codes 1..9, stores the frame,
|
||||
and runs the backbone over its embedding at the frame's own row.
|
||||
|
||||
Traps (each still speaks, wrongly):
|
||||
|
||||
- **The experts' scale planes are f32**, not the bf16 of Qwen3.6-35B-A3B-FP8: the expert format is
|
||||
read per layer (`MoeFP8::probe`), served as fp8a8f32.
|
||||
- **The tower's wqkv is blocked, `[Q | G | K | V]`**, not the backbone's per-head `[q_h | gate_h]`
|
||||
pairs; its rotary is GPT-J's adjacent pairs, not the backbone's halves; its q/k norms run with
|
||||
`(1 + w)` although its config says `attention_qk_norm: false` (the exporter never wrote it).
|
||||
- **`eh_proj` reads `[enorm(e); hnorm(h)]`**, the embedding half first.
|
||||
- **Two masks.** A layer's code embedding is the label frame's, zero when the label is text; the
|
||||
input frame's codes 2..9 go into the first shared layer only, zero when the input row is text.
|
||||
The layers that inject code 0 read it by candidate, with the table's row 0 again in front: the
|
||||
end of speech's code 0 is clamped to 0, as fish-speech clamps it.
|
||||
- **The tower attends over the whole sequence**, prompt rows included, from 13 caches of its own;
|
||||
it is not an 11-position depth decoder (`max_seq_len` 11 is left over from S2).
|
||||
- **The candidates' softmax is over the 4097 only**, top-p over all of them and the top-k cut after
|
||||
it; a full-vocabulary softmax keeps a different nucleus.
|
||||
- **The codec's residual codebooks have 1024 entries** and the heads 4096 outputs: codes are clamped
|
||||
at 1023 at decode (`rvq_embed`'s `clamp`). Its weight norm is per output channel for the convs
|
||||
and per INPUT channel for the transposed convs (`[in, out, k]`), folded at convert.
|
||||
- **The encoder's transformer window is 512 rows**, not the 128 frames of the quantiser's: the
|
||||
window comes from `getattr` on a `functools.partial` config, which has no such attribute, so
|
||||
fish-speech's default of 512 holds. Both its transformers and the codec's convolutions are
|
||||
causal, so a clip right-padded to whole frames encodes its frames as the clip alone would.
|
||||
- **The reference prompt is tokenised a literal at a time**: the instruction's closing `:` and the
|
||||
first header's `\n\n` are one token when the two are joined. A transcript's speaker tag must
|
||||
follow `Text: ` directly, so white space before it moves behind it.
|
||||
- **The input is written as fish-speech's server writes it**: each speaker's turn
|
||||
`<|speaker:N|> ` and its text stripped, turns joined by a newline, untagged text speaker 0's.
|
||||
The same two turns joined by a space are spoken through far less often: for one two-line script,
|
||||
at fish-speech's sampling, one seed in six spoke both lines, against seven in ten with the
|
||||
newline.
|
||||
|
||||
Against fish-speech's own PyTorch code (the CPU path: experts fp8, dequantised per forward, so
|
||||
W8A16 where radiance runs W8A8), teacher-forced with radiance's codes over a 34-row prompt and 80
|
||||
frames: the prompt's token ids are identical; the backbone's hidden state is 5.3% from the
|
||||
reference's (relative L2, median over the frames; cosine at least 0.993), the experts' fp8
|
||||
activations most of it; the main token's candidate logits 3.6% (KL 0.013 nats a frame, the same
|
||||
argmax in 92.5% of frames); the nine heads' logits 1.35% (KL 0.007, the same argmax 93% of the time)
|
||||
over the 79 frames that are spoken. Through the codec, radiance's chunked bf16 decode is 35.4 dB SNR
|
||||
from the reference's whole-utterance bf16 decode of the same codes. Qwen3-ASR transcribes
|
||||
radiance's speech word for word.
|
||||
|
||||
The encoder against fish-speech's codec encoding the same clip (11.6 s, 250 frames) on the CPU:
|
||||
radiance's bf16 encoder gives the f32 reference's semantic code in 99.2% of the frames, and its
|
||||
residual codes in 97.6% (the first) down to 81.2% (the ninth); fish-speech's own bf16 encode gives
|
||||
95.6% and 94.0% down to 71.2% against the same f32. The reference prompt's token ids are
|
||||
fish-speech's. Cloning, scored by median F0 and Qwen3-ASR over eight seeds a case, the reference
|
||||
clips drama-3's own takes of invented sentences: without a reference a sentence's eight takes are
|
||||
eight voices (116 to 251 Hz); with a reference of a 188 Hz voice they come out at 175 to 210 Hz,
|
||||
of a 200 Hz voice at 197 to 250 Hz, of a 108 Hz voice at 96 to 122 Hz; two references tagged as
|
||||
speakers 0 and 1 voice a two-line exchange's turns at 193 to 210 Hz and 109 to 140 Hz. Every take
|
||||
but one is transcribed word for word (the miss is "I'm" for "I am"). A 12 s clip adds 0.12 s
|
||||
before a stream's first audio.
|
||||
|
||||
The sampling is not fish-speech's server's (temperature 0.7, top-p 0.7, top-k 30 for every draw).
|
||||
At those the model falls silent after a tag or a speaker's line and does not come back, the failure
|
||||
vLLM-Omni's recipe and SGLang-Omni's notes describe; SGLang-Omni's comment puts it on the main
|
||||
token's top-k cap, and the counts bear it out. Ten seeds each of four short scripts (an aside in
|
||||
`<whisper>`, two two-speaker exchanges, a plain sentence), complete by Qwen3-ASR, and stuck (run to
|
||||
the 400-frame limit in silence):
|
||||
|
||||
| temperature, top-p, top-k (main / heads) | complete | stuck |
|
||||
|---|---|---|
|
||||
| 0.7, 0.7, 30 / 30 (fish-speech's server) | 28 / 40 | 8 / 40 |
|
||||
| 1.0, 0.9, 30 / 30 (Fish Audio's model card) | 35 / 40 | 2 / 40 |
|
||||
| 1.0, 0.9, 256 / 30 (SGLang-Omni) | 36 / 40 | 0 / 40 |
|
||||
|
||||
The four misses at the last setting are a take that ended before the line after the whisper (twice),
|
||||
a second speaker's single word, and one word the recogniser misheard; the whispered line itself is
|
||||
spoken in all ten. A take still pauses a second or so around an aside.
|
||||
|
||||
On two R9700s a sentence is made at 0.30 of the time it plays (3.67 s of speech in 1.08 s, 13.5 ms
|
||||
a frame with the codec), a paragraph at 0.29 (11.6 s in 3.34 s); a stream's first audio comes
|
||||
0.23 s after the request; four paragraphs at once make 50.4 s of speech in 5.15 s.
|
||||
|
||||
---
|
||||
|
||||
# `minimaxh3`: MiniMax-H3, video with sound
|
||||
|
||||
`arch/minimaxh3` declares a video generator (`rad_declare_video_generator`), which makes the
|
||||
|
||||
+199
-73
@@ -285,6 +285,7 @@ and runs.
|
||||
| `qwen3asr_bf16` | Qwen3-ASR, speech to text from the checkpoint as it ships (§5.14) |
|
||||
| `minimaxmusic3` | MiniMax-Music3, songs from a description and lyrics (§5.15) |
|
||||
| `breeze` | Breeze-TTS-2, speech from text and an optional description of the voice (§5.15) |
|
||||
| `fishomni` | Fish Audio drama-3, speech from text with speaker tags and inline direction (§5.15) |
|
||||
| `minimaxh3` | MiniMax-H3 and FastH3, video with its stereo soundtrack from text (§5.16) |
|
||||
| `ltx2` | LTX-2.5, video with its stereo soundtrack from text or a first frame (§5.16) |
|
||||
|
||||
@@ -461,6 +462,12 @@ rad-convert /srv/models/MiniMaxAI/MiniMax-Music3 -o minimax-music3-bf16.rad \
|
||||
# bf16 (6 GB, one card)
|
||||
rad-convert /srv/models/BreezeBlue/Breeze-TTS-2 -o breeze-tts2-bf16.rad \
|
||||
--recipe data/recipes/breeze-tts2-bf16.recipe
|
||||
|
||||
# Fish Audio drama-3, speech (§5.15): the release directory, its codec in codec.pth read with it
|
||||
# (a torch.save checkpoint read as data, never unpickled); the experts stay block fp8 as shipped,
|
||||
# the codec is cast to bf16 (39 GB, two cards)
|
||||
rad-convert /srv/models/fishaudio/drama-3 -o drama3-fp8.rad \
|
||||
--recipe data/recipes/drama3-fp8.recipe
|
||||
```
|
||||
|
||||
A checkpoint directory's `model.safetensors.index.json` decides which shard each tensor is read
|
||||
@@ -922,6 +929,36 @@ the pool that holds context; compare M with the sessions you expect to keep live
|
||||
wht6`, a decode step above the row count startup names is all-reduced lossily like a prefill chunk;
|
||||
at 8 sequences and depth 3, Flash-Next's decode steps are above it.
|
||||
|
||||
**The delta-net state at f16** (`--state-cache-dtype f16`). The `qwen35` plugins (`qwen35_fp8`,
|
||||
and `qwen35moe_fp8` and `qwen35_w8a8`, built from it) declare the recurrent state cache f32. With
|
||||
`--state-cache-dtype f16` they declare it f16; startup and the declare log say so (`GDN state cache
|
||||
f16`), and a plugin that does not serve it is refused at startup by name. **It is lossy**: the
|
||||
state is rounded wherever it is stored, so the generated text changes. It halves the state pool and
|
||||
its host checkpoints, and the state's traffic, which grows with the number of decoding sequences.
|
||||
Measured on `qwen35_fp8` only, Qwen3.8-27B MXFP4 at `--tp 2` on two R9700s (PCIe Gen5 x8, 265 W),
|
||||
against the bf16 model:
|
||||
|
||||
| state | mean KL, 2048 chunk | mean KL, 64 chunk | top-1, 64 chunk |
|
||||
|---|---|---|---|
|
||||
| f32, `k6_v4` KV | 0.040238 | 0.039607 | 94.07% |
|
||||
| f16, `k6_v4` KV | 0.040005 | 0.040468 (+2.2%) | 94.00% |
|
||||
| f32, `fp8` KV | 0.039171 | 0.039327 | |
|
||||
| f16, `fp8` KV | 0.039600 (+1.1%) | 0.039690 (+0.9%) | |
|
||||
|
||||
A 64-token chunk stores the state, and rounds it, every 64 tokens. Decode, greedy, three rounds
|
||||
(medians, tok/s):
|
||||
|
||||
| streams | f32, no speculation | f16 | f32, speculation 7 | f16 |
|
||||
|---|---|---|---|---|
|
||||
| 1 | 67.1 | 67.5 (+0.6%) | 222.2 | 215.1 (-3.2%) |
|
||||
| 4 | 246.8 | 253.3 (+2.6%) | 636.9 | 621.0 (-2.5%) |
|
||||
| 16 | 708.0 | 779.5 (+10.1%) | 1223.8 | 1276.7 (+4.3%) |
|
||||
|
||||
Without speculation the rounds agree to a tenth and the gain grows with the streams. With
|
||||
speculation f16 also changes which drafts the greedy text accepts, so one and four streams moved
|
||||
down; whether that is the text or the step was not separated. Use it for many concurrent sequences
|
||||
where the KL above is acceptable, and measure your own load.
|
||||
|
||||
### 4.5 Prefill chunk size
|
||||
|
||||
A long prompt is prefilled in chunks of at most `--max-num-batched-tokens`. On a mixture-of-experts
|
||||
@@ -1049,61 +1086,37 @@ avoids the extra copies, at the cost of full re-prefill if an edit precedes the
|
||||
Recurrent-state models still checkpoint at intervals under `tip-only`; their
|
||||
existing scheduling is unchanged.
|
||||
|
||||
**One prefill sequence in two pieces** (`RADIANCE_PREFILL_PIPELINE`). On `qwen35_fp8` (and
|
||||
`qwen35_w8a8`, built from it, where its norms do not write rotated int8 codes) and on `gemma3`'s MXFP4 trunk, a step of at least 1024 tokens that
|
||||
carries one prefill sequence and nothing else runs in two pieces of about half, the first rounded up
|
||||
to 64 rows so both sit in the whole step's kernel band. Every block runs a piece at a time; the work
|
||||
between two blocks (the block's all-reduce, the next norm, and after a feed-forward the add) runs a
|
||||
piece at a time on the second lane, beside the other piece's compute. The all-reduce there is the
|
||||
narrow `overlap` launch ([OPS.md](OPS.md#collectives)): the fused all-reduce and norm holds its
|
||||
blocks while it waits on the link and slowed the GEMM beside it by a third, and a wide launch slows
|
||||
it 1.45-2.1x; either ate the whole gain at two ranks. A piece computes what a narrower chunk
|
||||
computes, so a pipelined step is the serial step bit for bit: Qwen3.8-27B's KL recordings (`k6_v4`,
|
||||
`--tp-wire wht6`) and TranslateGemma's compare equal with it on and off. One setting makes a piece
|
||||
differ from the whole step: a lossy `--tp-wire` whose `--tp-wire-min-kb` a piece's message falls
|
||||
under while the whole step's does not (that piece goes out exact).
|
||||
**One prefill sequence in two pieces.** At two ranks, on `qwen35_fp8` (and `qwen35_w8a8`, built
|
||||
from it, where its norms do not write rotated int8 codes) and on `gemma3`'s MXFP4 trunk with the
|
||||
fused fp8 junctions, a step of at least 1024 tokens that carries one prefill sequence and nothing
|
||||
else runs in two pieces of about half, the first rounded up to 64 rows so both sit in the whole
|
||||
step's kernel band. Every block runs a piece at a time; the work between two blocks (the block's
|
||||
all-reduce, the next norm, and after a feed-forward the add) runs a piece at a time on the second
|
||||
lane, beside the other piece's compute. The all-reduce there is the narrow `overlap` launch
|
||||
([OPS.md](OPS.md#collectives)): the fused all-reduce and norm holds its blocks while it waits on
|
||||
the link and slows the GEMM beside it by a third, and a wide launch slows it 1.45-2.1x. A piece
|
||||
computes what a narrower chunk computes, so a pipelined step is the serial step bit for bit, with
|
||||
one exception: a lossy `--tp-wire` whose `--tp-wire-min-kb` a piece's message falls under while the
|
||||
whole step's does not (that piece goes out exact). Decode steps are unchanged. There is no switch:
|
||||
the startup log says once that prefill steps are pipelined, and the first wide step that runs
|
||||
serially says why (`radiance: qwen35: a 2048-row prefill step runs serially: more than one
|
||||
sequence`).
|
||||
|
||||
| `RADIANCE_PREFILL_PIPELINE` | |
|
||||
|---|---|
|
||||
| `auto`, or unset | pipelined at two ranks |
|
||||
| `on` (`1`, `true`) | also at three, four and eight ranks; startup notes that it is not measured there |
|
||||
| `off` (`0`, `false`) | never |
|
||||
PIPE_TABLE
|
||||
|
||||
Another value is noted at startup and taken as `auto`. On two R9700s (PCIe Gen5 x8, 265 W):
|
||||
|
||||
| model, chunk | prompt | serial | pipelined |
|
||||
|---|---|---|---|
|
||||
| Qwen3.8-27B MXFP4, 2048 | 41k tokens | 9.00 s | 8.41 s |
|
||||
| TranslateGemma 27B MXFP4, 2048 | 6k | 1.27 s | 1.21 s |
|
||||
| | 12k | 2.48 s | 2.42 s |
|
||||
|
||||
The Qwen figure includes the tiled GEMM's TN=4 crossover at 1024 rows, which the 1024-row pieces
|
||||
need. At a 1024-token chunk TranslateGemma's pieces are 512 rows and gain nothing, so serve it at
|
||||
2048 (against 1024: -9% at 6k, -7% at 12k). Decode steps are unchanged.
|
||||
|
||||
- **Above two ranks it is not measured.** `on` lets it run at three, four and eight ranks. At four
|
||||
libr4d's `overlap` all-reduce rows take a narrow launch that leaves the CUs to compute
|
||||
([TP4.md](TP4.md)); at three and eight they launch wide unless `R4D_AR_LANE_3_8=1` (§4.7), and a
|
||||
wide all-reduce beside the other piece's GEMM is what ate the whole gain at two ranks, so try the
|
||||
pipeline there with the variable set too. Compare a long prompt's prefill with `on` and `off` at
|
||||
the chunk you serve before keeping it. On the exact wire only the two-shot band above 524288
|
||||
elements has a lane row: a smaller piece (512 rows of a model 1024 wide) keeps the wide launch,
|
||||
the one-shot at three and four ranks, the one-shot or the wide two-shot at eight. The
|
||||
tiered-int8 lane rows at three and four ranks have no such floor. Eight ranks have no
|
||||
lossy wire, so `on` there pipelines on the exact wire only. Qwen3.8-27B (4 KV heads) and
|
||||
TranslateGemma (16) do not serve at three ranks.
|
||||
- **Measured on MXFP4 containers.** `qwen35_w8a8` prefills serially where libr4d serves its
|
||||
rotated int8 norms (the boundary norms would need the int8 codes on the second lane; startup says
|
||||
so). Without them it builds the same code, not checked bit for bit on its int8 trunk.
|
||||
- **Two ranks only.** Other rank counts prefill serially: the pipeline has been timed against the
|
||||
serial step at two ranks only.
|
||||
- **Which steps.** A prefill step with more than one sequence, decode rows beside it, or media rows
|
||||
(an image's tokens) runs serially; the first wide step that does says why, once, on rank 0
|
||||
(`radiance: qwen35: a 2048-row prefill step runs serially: more than one sequence`). `gemma3`
|
||||
needs the fused fp8 junctions, a library that serves `sub_i32`, and no calibration tap
|
||||
(`RADIANCE_CALIB_DIR`); without them a startup note says the pipeline is off.
|
||||
(an image's tokens) runs serially. `qwen35_w8a8` prefills serially where libr4d serves its
|
||||
rotated int8 norms (the boundary norms issue E4M3 codes only; startup says so). `gemma3` needs
|
||||
the fused fp8 junctions, a library that serves `sub_i32`, and no calibration tap
|
||||
(`RADIANCE_CALIB_DIR`); without them a startup note says the pipeline is off. The pieces need
|
||||
1024 rows, so the gain needs a chunk of 2048 (the default `--max-num-batched-tokens`).
|
||||
- **Memory.** The buffers the second lane touches leave the arena's sharing pool across the
|
||||
architecture's second-lane window ([PLUGIN.md](PLUGIN.md) §11). On Qwen3.8-27B with its DFlash2
|
||||
drafter at 64 sequences and speculation 7 the activation arena is 526.32 MiB a card, as without
|
||||
a second lane; the second lane's third hardware queue (33 MiB, §4.3) remains.
|
||||
architecture's second-lane window ([PLUGIN.md](PLUGIN.md) §11), so the drafter's and the heads'
|
||||
buffers still share their bytes; the second lane's scratch region holds only what its ops ask
|
||||
for ([IMPLEMENTATION.md](IMPLEMENTATION.md)). The second lane's hardware queue (33 MiB, §4.3)
|
||||
remains.
|
||||
|
||||
**Sharing a step** (`--busy-prefill-chunk`, default `auto`). When other work is pending, a prefill
|
||||
chunk leaves room for one row plus the draft window per decode row behind it, and a share of the
|
||||
@@ -1187,6 +1200,38 @@ behind the packet processor's barrier bit, which saves most of the launch gap be
|
||||
kernels. The bytes are the same. Plain decode measured slower with them, so they stay off there
|
||||
and on every other model; the startup report's `chained launches` row says which and why.
|
||||
|
||||
**A shorter block under load: `--draft-short-from N`.** A block drafter's block is paid for by
|
||||
every drafting sequence, whatever each one verifies. At one sequence a long block pays; at many, its
|
||||
drafter rows and its weaker first positions cost more than the extra drafts bring. A drafter that also
|
||||
serves a shorter block declares it (PLUGIN.md §11); DFlash2 declares a block of 4 (3 drafts) wherever its
|
||||
own is longer, on `qwen35_fp8` and `gemma3`. With `--draft-short-from N` the engine runs that short block
|
||||
once N sequences decoded in the step just run, and the drafter's own block again only once the count
|
||||
falls two below N, so a load wavering at N does not change the pass shape every step. `0`, the default,
|
||||
never switches. Startup names what it will run:
|
||||
|
||||
```
|
||||
speculation: from 16 decoding sequences on, 'dflash2' runs its short block of 4 row(s), 3 token(s)
|
||||
```
|
||||
|
||||
or warns that the drafter declares no shorter block, is a serial head, or that none runs. The block driver runs the
|
||||
short block on the card as it runs the drafter's own: the query pass is the shorter batch, each row's
|
||||
proposals are the front of the drafter's proposal row, and the step issued ahead verifies that many.
|
||||
Qwen3.8-27B MXFP4 + DFlash2 on two R9700s, `--num-speculative-tokens 7` at the fixed window, `k6_v4`,
|
||||
sampled (temperature 1.0), medians of six rounds at 8 streams and three at 16-64, tok/s:
|
||||
|
||||
| streams | unset | `--draft-short-from 8` |
|
||||
|---|---|---|
|
||||
| 8 | 652.8 | 696.8 |
|
||||
| 16 | 751.9 | 945.6 |
|
||||
| 32 | 985.7 | 1070.8 |
|
||||
| 64 | 1055.0 | 1334.6 |
|
||||
|
||||
Below N the engine runs the drafter's own block, the same shapes as with the flag unset (greedy, six
|
||||
rounds: 1 stream 183.4 and 183.1, 4 streams 529.1 and 537.2). Set it to 8 for a server that decodes
|
||||
eight or more sequences at once. The drafts are verified as any others; as with
|
||||
`--num-speculative-tokens`, a different block is a different verify shape, so greedy text can differ at
|
||||
a near-tie.
|
||||
|
||||
### 4.7 Multiple cards
|
||||
|
||||
```sh
|
||||
@@ -1200,6 +1245,14 @@ the exact sum and nothing downstream can detect it, so it is an explicit flag. `
|
||||
the size below which messages stay exact; 128 KiB keeps single-sequence decode exact and compresses
|
||||
prefill.
|
||||
|
||||
`--tp-attn-split rows` runs a prefill-sized step's attention by rows: each rank takes its run of the
|
||||
step's rows with every head, and an `all_gather` of the runs replaces the all-reduce. Where the
|
||||
attention dominates a prefill that is faster, but every card then holds the attention's projections
|
||||
at full width, and the result is not bit-identical to the default `heads` split. Only a plugin that
|
||||
declares the row split takes it (GLM-5.3: +18 to 21 % prefill at eight ranks for 1.29 GiB a card, a
|
||||
mean KL of 0.038 against `heads`, docs/ARCHITECTURES.md); elsewhere, and at `--tp 1`, the flag stops
|
||||
the start by name.
|
||||
|
||||
At three and four ranks `wht6` selects tiered int8 over a two-shot all-reduce, both hops quantised
|
||||
(at three ranks the shards are whole 32-element groups, one uneven where the message does not
|
||||
divide), with the same floor. Eight ranks have no lossy wire; `--tp 8 --tp-wire wht6` stops at
|
||||
@@ -1295,17 +1348,6 @@ engine does not use it: on this board those weights lost their lead within a tim
|
||||
served no faster. `r4d_selftest --perfar8 --ar8-weights W0,..,W7` times other weights on another
|
||||
board (`off` for even shards).
|
||||
|
||||
**An all-reduce beside compute at three and eight ranks** (`R4D_AR_LANE_3_8`). An all-reduce a
|
||||
plugin issues on its second lane (`overlap` 1: a pipelined prefill, §4.5; qwen4exp's
|
||||
`--prefill-span`; gemma4's prefill trunk overlap; the image and video plugins' second-lane
|
||||
collectives) takes a narrow launch at two and four ranks, measured there: a wide all-reduce's
|
||||
blocks spin on peer flags on the CUs the GEMM beside it needs, and at two ranks slowed it
|
||||
1.45-2.1x. At three and eight ranks `ar_twoshot_3rank_exact_lane`, `ar_twoshot_3rank_ti8_lane` and
|
||||
`ar_twoshot_8rank_exact_lane` take those collectives, but by default they launch exactly as the
|
||||
wide rows do, so nothing changes against a build without them. With `R4D_AR_LANE_3_8=1` they take
|
||||
the four-rank launch, 4 blocks of 1024 threads. The bits are the same either way; only the time
|
||||
moves:
|
||||
|
||||
### 4.8 Host tier for finished conversations
|
||||
|
||||
By default a finished conversation's KV blocks stay in VRAM, held by the prefix cache, until evicted
|
||||
@@ -1335,6 +1377,29 @@ whichever tier holds it (VRAM blocks to the pool, host slot to the arena, snapsh
|
||||
hit or a new turn counts as a use, and a system prompt shared by several conversations stays while
|
||||
any of them is used.
|
||||
|
||||
A client that knows a conversation is dead need not wait for the TTL: `DELETE /sessions/<label>`
|
||||
forgets it now, with `<label>` the `session_id` (or Anthropic `metadata.user_id`) its requests
|
||||
carried, or `DELETE /sessions?id=<id>` by the engine id `GET /sessions` lists (`?label=` works for
|
||||
a label the path cannot carry). `?keep_tokens=N` keeps the first N tokens of the chain, rounded up
|
||||
to whole blocks, for a client that replaced everything past a prefix (a compaction) and wants the
|
||||
prefix to keep hitting; on a hybrid model the hit resumes at the last linear-state snapshot inside
|
||||
the kept prefix (one every `--checkpoint-interval` tokens), so a prefix shorter than the interval
|
||||
keeps nothing that hits. The chain goes from the tip inwards like expiry, host copy and the
|
||||
session's snapshots with it; a block another stored conversation also walks (the shared system
|
||||
prompt) stays, as does one a running request reads. A request of the same conversation in flight
|
||||
is refused with 409: finish or cancel it first. Like every route but the probes and the page, it
|
||||
takes `--api-key` when the server has one. The answer says what went and what stayed:
|
||||
|
||||
```json
|
||||
{"label":"chat-7","keep_tokens":0,"sessions":1,"entries":2048,"tokens":32768,
|
||||
"device_bytes":417792000,"host_bytes":835584000,"snapshots":6,
|
||||
"kept":{"tokens":0,"shared":64,"live":0}}
|
||||
```
|
||||
|
||||
An unknown label or id is 404; an engine without a prefix cache answers 501. `/sessions` and
|
||||
`/stats` count what was released under `released`, `/metrics` as
|
||||
`prefix_cache_released_total{what}`.
|
||||
|
||||
```sh
|
||||
radiance --model m.rad --prefix-cache-mib 8192 --prefix-cache-ttl 3600
|
||||
```
|
||||
@@ -1731,6 +1796,7 @@ by 0.002-0.003 nats.
|
||||
|---|---|---|
|
||||
| `--gpu-headroom-mib N` | 96 | VRAM left unclaimed on every card |
|
||||
| `--kv-cache-dtype T` | bf16 | `bf16`, `fp8`, or on Qwen3.8-27B and Qwen3.8-Flash-Next `fp8_v4` or `k6_v4` (§4.4) |
|
||||
| `--state-cache-dtype T` | f32 | `f32` or `f16`: the recurrent (delta-net) state cache; f16 halves the state memory and is lossy, `qwen35` plugins only (§4.4) |
|
||||
| `--attn-prefill-fp8 MODE` | off | `off`, `qk`, `pv` or `both`: the prefill attention's Q·Kᵀ, P·V or both in E4M3 over an `fp8`, `fp8_v4` or `k6_v4` cache; lossy, Qwen3.8-27B (§4.4) |
|
||||
| `--host-pool-mib N` | 0 | pinned host tier (weights) |
|
||||
| `--host-headroom-mib N` | 4096 | host RAM left free for the system when startup pins host memory — kept for the unpooled allocations, staging and page cache (§4.3) |
|
||||
@@ -1775,6 +1841,7 @@ by 0.002-0.003 nats.
|
||||
| `--tp N` | 1 | tensor-parallel ranks |
|
||||
| `--tp-wire MODE` | exact | `exact` or `wht6`, the lossy wire (§4.7) |
|
||||
| `--tp-wire-min-kb N` | 128 | smallest all-reduce, in KiB, the lossy wire is used for |
|
||||
| `--tp-attn-split MODE` | heads | `heads` or `rows`: how a prefill-sized step's attention splits over the ranks, on a plugin that serves the row split (§4.7) |
|
||||
| `--p2p MODE` | auto | `auto` asks the driver, `on` requires peer access, `off` exchanges through host memory (§4.7) |
|
||||
|
||||
**Speculation**
|
||||
@@ -1783,6 +1850,8 @@ by 0.002-0.003 nats.
|
||||
|---|---|---|
|
||||
| `--num-speculative-tokens N` | auto | speculative window; 0 disables. The ceiling under `--draft-window adaptive` |
|
||||
| `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, serial draft heads only (§4.6) |
|
||||
| `--draft-short-from N` | 0 | a block drafter that declares a shorter block runs it from N decoding sequences on, its own block again two below; 0 never (§4.6) |
|
||||
| `--draft-coupling MODE` | off | `on`: a linear MTP drafter with a 2-bit candidate head (Qwen3.8-Flash-Next) samples each proposal from its reranked top-8 and the sampler maximally couples the target's draw to it. The output distribution is unchanged and a fixed seed yields other tokens than `off`. The head's law is taken at temperature 1, so it pays at high request temperatures and costs at low ones: on Flash-Next TP2 at 2x R9700, tokens per decode step +18% at temperature 1.0 and c1, +11% at 0.7 and c4, -4% at 0.3. Greedy rows are unchanged; any other drafter is refused at startup |
|
||||
| `--draft-model PATH` | | not implemented: merge the drafter at convert time |
|
||||
|
||||
**Server**
|
||||
@@ -1879,7 +1948,7 @@ flags are refused on it, and so are the pixel bands.
|
||||
| `POST /v1/systemone` | LiquidAI d1's decisions over a state: named yes/no, choice and score questions answered as probabilities, nothing generated; needs a container converted as d1, else 501 (§5.13) |
|
||||
| `POST /v1/audio/transcriptions` | OpenAI's speech to text, for a model whose plugin transcribes (Qwen3-ASR), else 501 (§5.14) |
|
||||
| `GET /v1/realtime` (WebSocket) | OpenAI's realtime transcription session: audio streamed in, the words back as they are spoken (§5.14) |
|
||||
| `POST /v1/audio/speech` | OpenAI's speech API, whole or streamed: speech from a speech model (Breeze-TTS-2), `instructions` describing the voice; songs from a music model (MiniMax-Music3), `input` the lyrics and `instructions` the song; else 501 (§5.15) |
|
||||
| `POST /v1/audio/speech` | OpenAI's speech API, whole or streamed: speech from a speech model (Breeze-TTS-2, `instructions` describing the voice; drama-3, speakers and direction in the input); songs from a music model (MiniMax-Music3), `input` the lyrics and `instructions` the song; else 501 (§5.15) |
|
||||
| `GET /v1/audio/speech/stream` (WebSocket) | vLLM-Omni's realtime speech session: text streamed in, each sentence's audio streamed out as soon as the sentence is complete; needs an audio generation model (§5.15) |
|
||||
| `POST /v1/videos`, `GET /v1/videos[/:id[/content]]`, `DELETE /v1/videos/:id` | OpenAI's video jobs: a video with its soundtrack from a prompt, made in the background and downloaded as MP4; needs a video model (MiniMax-H3), else 501 (§5.16) |
|
||||
| `POST /v1/messages`, `POST /v1/messages/count_tokens` | Anthropic's Messages API, for Claude Code and the Anthropic SDKs (§5.9, §5.11) |
|
||||
@@ -1898,6 +1967,7 @@ flags are refused on it, and so are the pixel bands.
|
||||
| `POST /tokenize`, `POST /detokenize` | vLLM's shape (`prompt` or `messages` in, `prompt` out) and llama-server's (`content` in and out, `with_pieces`) |
|
||||
| `GET /get_tokenizer_info` | the tokeniser's configuration |
|
||||
| `POST /reset_prefix_cache` | drop every cached prefix |
|
||||
| `DELETE /sessions/<label>`, `DELETE /sessions?id=<id>` | forget one stored conversation (§4.8) |
|
||||
| `GET /` or `/dashboard` | the web dashboard |
|
||||
| `GET /stats`, `/graph`, `/sessions` | the JSON the dashboard is drawn from |
|
||||
|
||||
@@ -2249,7 +2319,7 @@ passes but not launches (the UNet runs once per image and branch), so two take t
|
||||
| `stream`, `stream_options.include_usage` | |
|
||||
| `timings_per_token`, `return_progress` | llama-server's: `timings` on every chunk, and `prompt_progress` chunks while the prompt is read |
|
||||
| `samplers` | llama-server's sampler order, names or letters. A stage it leaves out is off. The chain here is penalties, DRY, top-k, top-p, min-p, typical, XTC, with temperature first (the default) or last (llama-server's default), so a list in either order is honoured and any other is refused by name |
|
||||
| `session_id` | OpenRouter's conversation id: labels the conversation on `/sessions` and the dashboard |
|
||||
| `session_id` | OpenRouter's conversation id: labels the conversation on `/sessions` and the dashboard, and names it for `DELETE /sessions/<label>` (§4.8) |
|
||||
| `control_vector` | `true` applies the control vector this deployment found to this request's steps, `false` leaves them on the stock model; absent or null takes the deployment's default (`--control-vector on\|off`, or as changed in the dashboard's Model view). A deployment with no vector refuses `true` by name. On a compatible container (Qwen3.8-Flash-Next), a refusal-direction vector makes the model decline far fewer requests -- that is a safety behaviour removed, and you own what it writes (§4.10, "Control vectors") |
|
||||
| `logprobs`, `top_logprobs`, `n_probs` | each generated token's logprob and up to 20 alternatives (§5.12). Chat: `logprobs: true` with `top_logprobs` alternatives (0 when absent); completions: `logprobs: N`; any endpoint: llama-server's `n_probs: N`, which wins. Not with `echo` (the prompt's logprobs are not computed) |
|
||||
| `tools`, `tool_choice`, `parallel_tool_calls` | chat only. `tool_choice` is `auto`, `none`, `required` or `{"type":"function","function":{"name":...}}`; the last two hold the whole reply to calls (after the reasoning block), the named form to that one function, and cannot be combined with `response_format` or `grammar` |
|
||||
@@ -2453,7 +2523,7 @@ each field is read, taken without effect, or refused by name.
|
||||
| `output_config` | `effort` (`low`, `medium`, `high`, `xhigh`, `max`) is the chat request's `reasoning_effort`, which the template reads in its own level names: a level it does not take is refused with the ones it does, and `--reasoning-effort-map` renames them (§4.9). `format` (`{"type": "json_schema", "schema": ...}`, or the older top-level `output_format`) is a `response_format` (§5.5). `task_budget` is taken |
|
||||
| `context_management` | validated; the conversation is served as sent, and the answer says so: `"context_management": {"applied_edits": []}`, on `message_delta` in a stream |
|
||||
| `thread` | `create` is served as any request; `continue` is refused, since no conversation is stored |
|
||||
| `metadata` | `user_id` is the conversation's label on `/sessions` |
|
||||
| `metadata` | `user_id` is the conversation's label on `/sessions` and its name for `DELETE /sessions/<label>` (§4.8) |
|
||||
| `service_tier`, `inference_geo`, `speed`, `cache_control`, `diagnostics`, `safeguards`, `fallbacks`, `context_hint` | taken; none can change the answer here. `cache_control` on a block is dropped too |
|
||||
| `mcp_servers`, `container` | refused |
|
||||
| anything else | refused: `"<field>: Extra inputs are not permitted ..."`, Anthropic's own words, which Claude Code matches to retry without a beta field it can drop |
|
||||
@@ -2685,10 +2755,11 @@ socket.
|
||||
|
||||
### 5.15 Speech and music: `/v1/audio/speech`
|
||||
|
||||
An audio generation model answers OpenAI's `POST /v1/audio/speech`: a speech model (Breeze-TTS-2)
|
||||
speaks `input`, in a voice `instructions` may describe; a music model (MiniMax-Music3) sings `input`
|
||||
as lyrics, as `instructions` describe the song (SGLang-Omni's reading of the route). Both are
|
||||
converted from their release directories (§3.2).
|
||||
An audio generation model answers OpenAI's `POST /v1/audio/speech`: a speech model speaks `input`,
|
||||
in a voice `instructions` may describe (Breeze-TTS-2) or with its speakers and direction written in
|
||||
the input itself (drama-3); a music model (MiniMax-Music3) sings `input` as lyrics, as
|
||||
`instructions` describe the song (SGLang-Omni's reading of the route). Each is converted from its
|
||||
release directory (§3.2).
|
||||
|
||||
#### Speech: Breeze-TTS-2
|
||||
|
||||
@@ -2717,6 +2788,60 @@ as it is spoken. On one R9700 a sentence is made at 0.6 of the time it plays (5.
|
||||
speed they play (43 s of speech in 12.1 s). Breeze-TTS-2 is licensed for research and
|
||||
non-commercial use only, and BreezeBlue counts hosting it as an API as commercial.
|
||||
|
||||
#### Speech: drama-3
|
||||
|
||||
```sh
|
||||
radiance --model drama3-fp8.rad --tp 2 # two cards
|
||||
|
||||
curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{
|
||||
"input": "The lighthouse keeper counted seven ships before the fog rolled in."}' -o ships.wav
|
||||
curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d '{
|
||||
"input": "<|speaker:0|> Did you lock the back door?\n<|speaker:1|> [sighs] I thought you did."}' \
|
||||
-o door.wav # 44.1 kHz mono, 16-bit
|
||||
curl -s http://localhost:8000/v1/audio/speech -H 'Content-Type: application/json' -d @- \
|
||||
-o cloned.wav <<EOF # the voice of voice.wav
|
||||
{"input": "The lighthouse keeper counted seven ships before the fog rolled in.",
|
||||
"references": [{"audio": "$(base64 -w0 voice.wav)", "text": "What voice.wav says."}]}
|
||||
EOF
|
||||
```
|
||||
|
||||
- **`input`** is the script. Speakers are named in it, `<|speaker:0|>` to `<|speaker:15|>`, and
|
||||
text before any tag is speaker 0's; each speaker's turn is written as Fish Audio's server writes
|
||||
it (the tag, a space, the turn's text stripped, each turn on a line of its own), so the turns may
|
||||
be given on one line. The direction is written in the text too: point tags such as `[laughs]`,
|
||||
`[sighs]` or `[pause]`, a bracketed style before a line (`[with bright eager excitement] We
|
||||
won!`), `<whisper>...</whisper>`. The tokens only the prompt is built from (`<|im_start|>`,
|
||||
`<|im_end|>`, `<|voice|>`, `<|text|>`, `<|interleave|>`, `<|semantic:...|>`) are refused, and so
|
||||
is any other spelling of a speaker.
|
||||
- **`instructions` are refused**, the direction being the input's; `guidance_scale` must be 1 (the
|
||||
model runs one branch). Without references each speaker's voice is the model's choice, the same
|
||||
within a take.
|
||||
- **`references`** clone voices from recordings: an array of `{"audio": ..., "text": ...}`, the
|
||||
clip a `data:` URL or the base64 of an audio file (anything ffmpeg reads, decoded to mono
|
||||
44.1 kHz), its text what the clip says; at most 8 clips and 30 s of audio together. A
|
||||
reference's voice is the speaker its transcript is tagged with, speaker 0 when untagged, so a
|
||||
dialogue gives each speaker a clip: `"<|speaker:1|> ..."` as the second reference's text voices
|
||||
the input's `<|speaker:1|>` turns. The clips are encoded by the codec's own encoder in the
|
||||
request's first pass, in bf16 as fish-speech's server encodes them (a 12 s clip adds about
|
||||
0.12 s before the first audio), and the prompt is fish-speech's with references:
|
||||
`[Reference 1]`, its transcript and its frames, for each.
|
||||
- **The length** is `duration` in seconds or `max_new_tokens` in frames (21.5 a second), up to 95 s;
|
||||
the model ends the speech at the end of the script. The prompt holds at most 3072 tokens, a
|
||||
reference adding 21.5 a second of its clip.
|
||||
- **Sampling** is SGLang-Omni's: temperature 1.0 and top-p 0.9 (Fish Audio's model card), the
|
||||
first code uncapped and each later code at top-k 30, with fish-speech's repetition-aware redraw
|
||||
of the first code. fish-speech's server samples at 0.7, 0.7 and 30, where the model often falls
|
||||
silent after a tag or a speaker's line and runs to its length (docs/ARCHITECTURES.md has the
|
||||
counts). A take can still end before its last line; another `seed` usually speaks it all.
|
||||
- **`seed`**, **`response_format`**, **`speed`** and **`voice`** are read as for music below.
|
||||
|
||||
Speech is played sixteen frames (0.74 s) at a time as it is made. On two R9700s a sentence is made
|
||||
at 0.30 of the time it plays (3.67 s of speech in 1.08 s) and a stream's first audio comes 0.23 s
|
||||
after the request; four paragraphs at once make 50.4 s of speech in 5.15 s. drama-3 is under the
|
||||
Fish Audio Community License: research, non-commercial and small commercial use are free; a
|
||||
service that lets others generate speech needs a licence from Fish Audio, and so does imitating a
|
||||
real person's voice without their consent.
|
||||
|
||||
#### Music: MiniMax-Music3
|
||||
|
||||
```sh
|
||||
@@ -2778,7 +2903,8 @@ is complete, so the first audio waits for the first sentence rather than the who
|
||||
|
||||
- **`session.config`** takes the fields of `POST /v1/audio/speech` but `input` (`instructions`,
|
||||
`voice`, `seed`, `guidance_scale`, `max_new_tokens` or `duration` for each sentence, `speed`,
|
||||
`num_inference_steps` where the model has a denoiser), checked as that route checks them, and
|
||||
`num_inference_steps` where the model has a denoiser, `references` where it clones a voice),
|
||||
checked as that route checks them, and
|
||||
four of its own: `response_format` `pcm` (the default) or `wav`; `stream_audio`, false (the
|
||||
default) for one binary message a sentence or true for the audio as the model makes it;
|
||||
`split_granularity`, `sentence` (the default), `clause` (also at commas and semicolons) or `none`
|
||||
@@ -3109,6 +3235,7 @@ scheduler clamps reuse to the last linear checkpoint. That verdict is the tab's
|
||||
```sh
|
||||
curl -s localhost:8000/stats | jq # counters, memory, throughput
|
||||
curl -s localhost:8000/sessions | jq # what is stored and where
|
||||
curl -s -X DELETE localhost:8000/sessions/chat-7 | jq # forget one stored conversation (§4.8)
|
||||
curl -s localhost:8000/graph | jq # the resolved kernel graph
|
||||
curl -s localhost:8000/server_info | jq # model, cards, KV, draft depth, wire
|
||||
curl -s localhost:8000/diagnostics | jq # the startup report, hardware read again now (§7.1)
|
||||
@@ -3157,6 +3284,7 @@ there is none.
|
||||
| `prefix_hit_cuts_total{reason}`, `prefix_hit_cut_tokens_total` | admissions whose hit reused nothing (`no_snapshot`, `windowed_group`, `adopt_failed`) or resumed at a snapshot more than one checkpoint interval below it (`resumed_below`: the previous reply was longer than an interval, since decode writes no snapshot, the retention policy kept nothing nearer, or a restore was cut), and the checkpoint shortfall: cached prompt tokens computed again because the hit resumed at a snapshot below it. `/stats` and `/sessions` carry the same counts; `RADIANCE_LOG=debug` logs each eviction and each cut hit |
|
||||
| `prefix_restore_cuts_total` | restores from the host tier the pool could not hold whole, even after giving up other conversations' VRAM copies (§4.8); `RADIANCE_LOG=debug` logs where each was cut |
|
||||
| `prefix_cache_expired_total`, `prefix_cache_ckpt_expired_total` | what `--prefix-cache-ttl` removed (§4.8) |
|
||||
| `prefix_cache_released_total{what}` | entries and snapshots clients forgot through `DELETE /sessions` (§4.8) |
|
||||
| `num_requests_preempted` | |
|
||||
| `http_queue_depth`, `http_responses_total`, `http_admission_rejected_total` | |
|
||||
| `client_disconnect_total`, `stream_overflow_total` | |
|
||||
@@ -3256,7 +3384,7 @@ is the part of a log to paste into an issue. Its sections:
|
||||
warning is also printed as a `W` line of its own.
|
||||
|
||||
```
|
||||
I STARTUP REPORT -- radiance 1.11.0
|
||||
I STARTUP REPORT -- radiance 1.12.0
|
||||
I CONFIGURATION -- every option, the value in force, and where it came from
|
||||
I --model /models/flashnext.rad [command line]
|
||||
I --tp 2 [command line]
|
||||
@@ -3355,8 +3483,6 @@ reductions running on fewer blocks: Qwen3.8-27B's 41k-token prefill 9.5 s uncapp
|
||||
| `RADIANCE_CALIB_TOKENS` | with `RADIANCE_CALIB_DIR`, the tokens the calibration tap accumulates before it writes and switches itself off (default 65536) |
|
||||
| `RADIANCE_G3_CALIB_LAYERS` | `lo:hi`: `arch/gemma3`'s calibration tap over layers lo to hi - 1 only, to take a large model's Grams in passes (docs/ARCHITECTURES.md) |
|
||||
| `RADIANCE_PROFILE_EVERY` | with `--profile-ops`, dump the per-op table every N steps (default 32) |
|
||||
| `R4D_AR_LANE_3_8` | `1`: at three and eight ranks an all-reduce beside compute (`overlap` 1) takes the narrow four-rank launch instead of the wide one. Same bits; faster where the all-reduce is the shorter of the two, slower where it is the longer; not measured on such machines. Unset or `0`: the wide launch, as without the lane rows (§4.7) |
|
||||
| `RADIANCE_PREFILL_PIPELINE` | a prefill step of one sequence and 1024 tokens or more in two pieces, the work between blocks of one piece on the second lane beside the other's compute (§4.5): unset or `auto` at two ranks, `on` also at three, four and eight ranks (not measured there), `off` never. The bits are the serial step's |
|
||||
| `RADIANCE_LOG_STEPS` | log one line per step: its phase, sequences, and each one's token count and context (§4.5) |
|
||||
|
||||
Engine development has its own instruments: `RADIANCE_DEBUG_*` (residual probes, routing and issue
|
||||
|
||||
@@ -99,8 +99,8 @@ transient buffer counts. `Arena::init` takes both sizes, `arena_plan_bytes` char
|
||||
budget, and startup prints them (`arena: ... device + ... scratch + ... for the second lane = ...`).
|
||||
A lane-1 request larger than region 1 comes from an op that breaks rule 3 in its buffers too, so
|
||||
`Ctx::issue` fails the step naming the kernel (`RAD_E_SCRATCH`) rather than let it overrun the
|
||||
region. On Qwen3.8-27B with its DFlash2 drafter region 1 is 0 B, where it used to be a copy of region
|
||||
0: 50 MiB a card at speculation 7, 17 MiB without speculation.
|
||||
region. On Qwen3.8-27B with its DFlash2 drafter region 1 is 0 B against region 0's 50 MiB a card
|
||||
at speculation 7 (17 MiB without speculation).
|
||||
|
||||
**`rad_memset_async` refuses `RAD_MEM_HOST` on a card; the host backend cannot reproduce that.**
|
||||
`RAD_MEM_HOST` is pageable memory the GPU has never been shown, so the device backend returns
|
||||
|
||||
+73
-12
@@ -1263,14 +1263,16 @@ libref function says which (`libref/ref_audio.cpp`).
|
||||
|
||||
| op | params | operands |
|
||||
|---|---|---|
|
||||
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
|
||||
| `conv1d` | `M`(range) `cin` `cout` `k` `dil` `act`/opt `dtype` `causal`/opt `stride`/opt `cu_div`/opt | `x`, `w`w, `cu_seqlens`, `res`? → `y`; `b`w? |
|
||||
| `conv_t1d` | `M`(range) `cin` `cout` `stride` `dtype` `pad`/opt `k`/opt | `x`, `w`w, `b`w, `cu_seqlens` → `y` |
|
||||
| `snake` | `M`(range) `n` `dtype` `log`/opt | `x`, `alpha`w → `y`; `beta`w? |
|
||||
| `snake_aa` | `M`(range) `n` `ratio` `k` `log`/opt `dtype` | `x`, `alpha`w, `beta`w, `f_up`w, `f_down`w, `cu_seqlens` → `y` |
|
||||
| `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? |
|
||||
| `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt | `codes`, `t0`w, `t1`w → `y` |
|
||||
| `cfg_topk_sample` | `M`(range) `n_vocab` `k` `rep` `cond_k`/opt `cfg`:f64 `temp`:f64/opt `stream` `dtype` `sup_lo`/opt `sup_hi`/opt `penalty`:f64/opt `top_p`:f64/opt | `logits`, `seed`, `frame` → `ids`; `cfg`?, `lane`?, `hist`:inout? |
|
||||
| `rvq_embed` | `M`(range) `n_embd` `n_codes` `vocab` `off0` `scale`:f64 `dtype` `round`/opt `clamp`/opt | `codes`, `t0`w, `t1`w → `y` |
|
||||
| `vq_encode` | `M`(range) `n` `dim` `bins` `dtype` | `x`:inout, `in_w`w, `in_b`w, `cb`w, `out_w`w, `out_b`w → `codes` |
|
||||
| `frame_mix_store` | `M`(range) `n_embd` `L` `stride` `rep`/opt `dtype` | `hid`, `logits`w, `scale`w, `lane`, `frame`, `status`, `dst`:inout |
|
||||
| `end_status` | `M`(range) `end` `rep` | `ids`, `lane`, `status`:inout |
|
||||
| `ras_pick` | `M`(range) `win` `lo` `hi` `rep`/opt `clear`/opt | `first`, `alt`, `lane`, `hist`:inout → `ids` |
|
||||
| `frame_store` | `M`(range) `n_codes` `stride` `rep`/opt `skip`/opt | `codes`, `lane`, `frame`, `status`, `dst`:inout |
|
||||
| `resample_nearest` | `M`(range) `n` `dtype` | `x` → `y` |
|
||||
| `fourier_embed` | `M`(range) `n` `round`/opt `dtype` | `t`, `w`w → `y` |
|
||||
@@ -1295,14 +1297,34 @@ conditional first, then the unconditional) are consecutive rows, `rep` of them a
|
||||
`cond_k` > 0 only the entries where `c` reaches its `cond_k`-th largest value are. The `k`
|
||||
largest `g` (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and drawn by
|
||||
inverse CDF in descending `g`, `u = rad_philox_uniform_s(seed, 2^32 + frame, stream)`
|
||||
(`abi/rad_philox.h`); the pick goes to every one of the lane's `rep` slots. `logits`
|
||||
`[rep n, n_vocab]` f32 or bf16, `seed` `[n, 2]` u32 low word first, `frame` `[n]`.
|
||||
(`abi/rad_philox.h`); the pick goes to every one of the lane's `rep` slots. With `top_p` < 1
|
||||
(Fish Audio's draw) the kept list is cut first: over the softmax of every candidate's `g / temp`
|
||||
(its normaliser summed in index order), a kept rank whose inclusive cumulative probability in
|
||||
descending `g` exceeds `top_p` is dropped, rank 0 never, so the nucleus is taken over the whole
|
||||
distribution and the `k` cut applies after it. `logits` `[rep n, n_vocab]` f32 or bf16, `seed`
|
||||
`[n, 2]` u32 low word first, `frame` `[n]`.
|
||||
- `ras_pick`: Fish Audio's repetition-aware sampling, a choice between two draws of each lane:
|
||||
`ids[rep i] = alt[rep i]` when `first[rep i]` is in `[lo, hi)` and the lane's window holds it,
|
||||
else `first[rep i]`. The window `hist` `[lanes, win]` i32 is the lane's last `win` picks, oldest
|
||||
first, -1 empty (`clear` 1 empties it first, for a piece's first pick); the pick then enters it
|
||||
and the oldest leaves. A pick outside `[lo, hi)` (an end of speech) is never redrawn.
|
||||
- `end_status`: `status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]`.
|
||||
- `rvq_embed`: `codes` is code-major `[n_codes, rows]`, read at the operand's own strides (a block
|
||||
of a wider plane is a view);
|
||||
`y = bf16(bf16(t0[c_0 + off0] + bf16(sum_k t1[c_k + (k - 1) vocab])) * scale)`, or with `round` 1
|
||||
one f32 sum of every codebook's row in codebook order, times `scale`, rounded once to `y`'s dtype.
|
||||
A first code outside `t0` leaves its row unwritten; a later code outside `t1` adds nothing.
|
||||
With `clamp` n > 0 a code above `n - 1` reads row `n - 1` (before `off0` and the codebook's
|
||||
offset; a negative code still reads nothing): a codec whose codebooks are smaller than the heads
|
||||
that write its codes, as Fish Audio's 1024-entry residual codebooks under 4096-way heads.
|
||||
- `vq_encode`: one step of a residual vector quantiser with factorised, L2-normalised codes (DAC's,
|
||||
as Fish Audio's codec encodes a reference): per row of `x` `[rows, n]`, `e = in_w x + in_b`
|
||||
(`in_w` `[dim, n]`, a 1x1 convolution's weight); the code is the row of `cb` `[bins, dim]` of
|
||||
greatest cosine with `e`, `(e / max(|e|, 1e-12)) . (cb_c / max(|cb_c|, 1e-12))`, the lower index
|
||||
on a tie (0 when no score is above -inf), written to `codes[i]` at the operand's own stride; then
|
||||
`x -= out_w cb[code] + out_b` (`out_w` `[n, dim]`, the raw codebook row), rounded once into `x`.
|
||||
f32 arithmetic. A chain of these over a codec's codebooks, each quantising what the last left, is
|
||||
its residual quantiser.
|
||||
- `frame_store`: `dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]` for every `k`,
|
||||
when `frame >= skip` and `status[lane] >= 0`: a frame's codes into its lane's history, each
|
||||
codebook a row over the lane's frames, so a run of a lane's frames is a block of `n_codes`
|
||||
@@ -1345,7 +1367,14 @@ input reads zero outside it.
|
||||
- `conv1d`: PyTorch's `[cout, cin, k]` weight, `k` odd, dilation `dil` and padding
|
||||
`dil (k - 1) / 2` a side, or with `causal` 1 (any `k`) `dil (k - 1)` on the left; `res` is added
|
||||
after the bias, then `act` `none`, `tanh` or `clamp`, `min(max(y, -1), 1)` (BigVGAN's output
|
||||
clamp; a NaN stays NaN). f32 accumulation, one rounding.
|
||||
clamp; a NaN stays NaN). f32 accumulation, one rounding. `stride` s > 1 (causal only, the reach
|
||||
`dil (k - 1) + 1` at least s) pads `dil (k - 1) + 1 - s` on the left and keeps every s-th row:
|
||||
output row `o` of a sequence reads input rows `o s - pad + t dil`, and sequence `e`'s rows
|
||||
`[cu[e], cu[e+1])` become `[cu[e] / s, cu[e+1] / s)`, so every bound is a multiple of s; `res`
|
||||
and `y` have the output's rows (a causal codec encoder's downsampling, as Fish Audio's).
|
||||
`cu_div` reads the bounds in units that many input rows apart, as the other encoder ops do:
|
||||
sequence `e` is input rows `[cu[e] / cu_div, cu[e+1] / cu_div)`, each bound a multiple of
|
||||
`cu_div` times the stride, so one bounds array in samples serves every rate of an encoder.
|
||||
- `conv_t1d`: PyTorch's `[cin, cout, k]` transposed weight, any `k` of at least a stride (two
|
||||
strides by default), padding `pad` (`(k - stride) / 2` by default, which needs `k - stride` even;
|
||||
0 is the causal form, whose full output's last `k - stride` rows are dropped; it may exceed a
|
||||
@@ -2160,11 +2189,7 @@ start above 524288 elements (8192 at eight ranks), a band edge of the ranged `nu
|
||||
all-reduce kernel serves `y` absent, in place. `overlap` 1 says the caller issues the collective on
|
||||
its second lane, beside compute; libr4d then picks rows with a narrow launch (8 blocks of 256
|
||||
threads at two ranks, 4 of 1024 for the four-rank two-shots, exact and tiered-int8) that compute the
|
||||
same bits and leave the CUs to the kernels running beside them. At three and eight ranks the lane
|
||||
rows (exact at both, tiered-int8 at three) launch as the wide rows unless `R4D_AR_LANE_3_8=1` gives
|
||||
them the four-rank launch, unmeasured there (GUIDE §4.7); the eight-rank one starts above 524288
|
||||
elements, so an `overlap` 1 message of 8193..524288 elements keeps the wide two-shot there. libref
|
||||
ignores it.
|
||||
same bits and leave the CUs to the kernels running beside them. libref ignores it.
|
||||
|
||||
libr4d serves these at 2, 3, 4 and 8 ranks:
|
||||
|
||||
@@ -2534,6 +2559,29 @@ resolutions of one op. The one exception is `sample_chain` (below).
|
||||
| `sample_argmax` | `M`(range) `n_vocab` | `logits`, `params` → `token` |
|
||||
| `sample_merge_topk` | `M`(range) `n_cand` | `gathered`, `params` → `cand_idx`, `cand_val` |
|
||||
| `sample_logprobs` | `M`(range) `n_vocab` `k` `vocab_off`/opt | `logits`, `params` → `stats` |
|
||||
| `mtp_couple_propose` | `M`(range) `n_vocab` `round` `max_rounds` | `idx`:inout, `val`, `seq_ids`, `draw` → `state`:inout |
|
||||
| `mtp_couple_verify` | `M`(range) `n_cand` `n_vocab` | `cand_idx`, `cand_val`, `params`, `state` → `token`:inout |
|
||||
|
||||
`mtp_couple_propose` and `mtp_couple_verify` are the linear-MTP coupling (`--draft-coupling on`),
|
||||
and nothing else in the engine knows about coupling. Turning coupling on requires the
|
||||
linear serial draft chain: a block drafter (`RAD_DRAFT_BLOCK`) or no drafter at all is refused at
|
||||
bringup, because neither has a per-round draw to couple. The `spechub` plugin ships both rows and
|
||||
their host oracle in one library and marks them per row, so the device rows count as production
|
||||
kernels while the oracle stays reference; on a machine with no card only the oracle is left, and
|
||||
the gate refuses the coupling there. A `RADIANCE_KERNELS` list is exclusive:
|
||||
if it is set, it must name `spechub` or the coupled ops are not loaded at all.
|
||||
|
||||
`mtp_couple_propose` runs on a draft round's
|
||||
final reranked top-8 and samples the proposal `x ~ Q`, where `Q` is the FP64 softmax of those
|
||||
scores at temperature 1; it writes `x` into column 0 of `idx` and one state row per round. A row
|
||||
whose `seq_ids` does not name the card its draw was staged for, or whose shortlist is malformed,
|
||||
leaves column 0 alone with `status = -1`. `mtp_couple_verify` runs after `sample_pick`, over the same
|
||||
final candidate plane, and applies the maximal coupling: the draft is accepted when it equals the
|
||||
token the target itself drew at that position, and otherwise the token is a draw from the FP64
|
||||
residual `(P - Q)+`. Both use 53-bit uniforms at `params.pos`; a row whose state is not bound to
|
||||
that seed and position keeps the ordinary token. `P` is FP64-normalised where `sample_pick` is
|
||||
FP32/24-bit, so a coupled row realizes the ideal filtered target law and is **not** seed-identical
|
||||
to the ordinary pick.
|
||||
|
||||
`sample_temp` divides a row's logits by its `temp` and leaves a row whose `temp` is 0 or less, or
|
||||
exactly 1, as it is. The sampler relies on that: a step none of whose chain rows has another
|
||||
@@ -2887,7 +2935,7 @@ contributes nothing, and a row with no visible key outputs zero. The softmax is
|
||||
rounded once. `scale` is positive and finite and comes from the original query/key head width,
|
||||
not the latent width (GLM: `1/sqrt(256)` against a latent of 512).
|
||||
|
||||
libr4d has two `mla_attn` rows, both at `latent_dim` 512, `block_size` 4 and up to 64 heads. The
|
||||
libr4d has three `mla_attn` rows, all at `latent_dim` 512, `block_size` 4 and up to 64 heads. The
|
||||
matrix row, `mla_attn_matrix_bf16`, ranks above the wave row and takes heads in multiples of 8: the
|
||||
heads are the WMMA tile's rows, so all of them share each latent load, and the probabilities enter
|
||||
it as bf16 high and low parts with f32 accumulation. At a multiple of 16 a tile holds 16 heads of
|
||||
@@ -2899,6 +2947,19 @@ by table position, with a second pass where the two differ. Other head counts ta
|
||||
workgroups and merge the f32 partials before narrowing, into the fixed scratch their hooks
|
||||
reserve; without scratch they compute unsplit.
|
||||
|
||||
At exactly 64 heads the rows row, `mla_attn_rows_bf16`, ranks above both. A workgroup takes one
|
||||
query row and all its heads, four waves to each group of sixteen, and loads each 16-token key chunk
|
||||
once for all of them, where the matrix row loads it once a tile of sixteen. The scores are
|
||||
`K Q^T`, tokens as the tile's rows and heads as its columns, so a head's running maximum and
|
||||
denominator stay in its lane; the four waves of a group each take a quarter of the latent's dot
|
||||
products and add the four partials in one order, and the probabilities reach the value product
|
||||
through a lane swap instead of LDS. The next chunk's keys are fetched while the current one is
|
||||
multiplied. A row's output does not depend on the other rows of the batch, so a run of rows gives
|
||||
the bytes the whole batch would. Under 32 rows (a decode step at one rank) too few workgroups fill the card, and its launcher
|
||||
runs the matrix row's kernel instead. It also takes multiples of 32 heads (two groups a
|
||||
workgroup), which no constraint routes to it. GLM-5.3 splits a prefill's MLA by rows under tensor
|
||||
parallelism, so each rank holds all 64 heads of its rows (ARCHITECTURES.md, `glm5next`).
|
||||
|
||||
`mla_project` moves a query into the latent and a latent result out of it, through the bf16
|
||||
weight `b` `[heads*2*head_dim, latent_dim]` that stores each head's key rows, then its value rows.
|
||||
`mode=absorb` multiplies `a` `[M, heads, head_dim]` by the head's key block as stored,
|
||||
|
||||
+15
-6
@@ -57,6 +57,7 @@ Five more exports are optional, each looked up by exactly this name:
|
||||
| `int rad_kernel_concurrent(int i)` | nonzero: kernel `i` touches nothing but its operands and scratch, so independent launches may overlap |
|
||||
| `int rad_kernel_collective(int i)` | nonzero: kernel `i` exchanges data with the other ranks' cards, so the engine keeps its own bulk link traffic away while it runs. 2: each launch ends that hold itself once the other ranks' bytes have landed, through the `link_gate` parameter (`rad_abi.h`). Without this export only the `all_reduce` op is a collective |
|
||||
| `int rad_plugin_reference(void)` | nonzero: a **reference implementation**, ranked below every unnamed library, refused for serving unless `--debug-accept-reference-kernels`, and what `rad-kbench` checks the others against. libref declares itself this way |
|
||||
| `int rad_kernel_reference(int i)` | per row: nonzero marks kernel `i` as a reference implementation and 0 as a production one, overriding `rad_plugin_reference` for that library. For a plugin that ships a device row and its host oracle side by side (`plugin/spechub`) |
|
||||
|
||||
---
|
||||
|
||||
@@ -371,8 +372,8 @@ says so with `RAD_ARCH_SERVES_IMPORTS(0)` (`qwen35_w8a8` does), and imports keep
|
||||
outside the window (a drafter's, the heads') share its bytes again. What the plugin promises:
|
||||
it issues nothing on lane 1 outside the window. What the runtime does (`Ctx::issue`): an op
|
||||
issued on lane 1 outside the window fails the step, naming the window's op range and the op's
|
||||
position; the first op issued on lane 0 past the window joins lane 1 first when lane 1 has work
|
||||
pending, so the plugin need not join before the window ends; an op the core appends behind a
|
||||
position; an op issued on lane 0 outside the window, before or past it, joins lane 1 first when
|
||||
lane 1 has work pending, so the plugin need not join before the window ends; an op the core appends behind a
|
||||
declared one (runtime LoRA) counts at that op's position. The builder refuses a second `begin`,
|
||||
an `end` without a `begin`, twice or around no op, a `begin` never closed, and either call after
|
||||
declare. `qwen35_fp8` (with the plugins built from it) and `gemma3` declare one from the
|
||||
@@ -382,10 +383,18 @@ says so with `RAD_ARCH_SERVES_IMPORTS(0)` (`qwen35_w8a8` does), and imports keep
|
||||
([IMPLEMENTATION.md](IMPLEMENTATION.md)) the KV pool from 86 208 to 93 856 tokens.
|
||||
`tests/arch_test.cpp`'s builder applies the window to liveness as the core does, so the pinned
|
||||
graphs and steps are the ones the core plans; the runtime (`Ctx::issue`) is what refuses a lane-1
|
||||
op outside the window. The join is at the window's end only: an op declared before the window must
|
||||
not be issued again while lane 1 has work pending. Both calls are additive exports:
|
||||
`RAD_ABI_VERSION` (26) does not move, and a plugin that does not call them is unaffected. A plugin that calls them needs an engine that exports them; an older engine fails
|
||||
to load it (`dlopen` with `RTLD_NOW`: an undefined symbol).
|
||||
op outside the window. Both calls are ABI 27 exports; a plugin that does not call them is
|
||||
unaffected.
|
||||
- **A block drafter may serve a shorter block.** `rad_drafter_short_block(b, block)`, called once
|
||||
after `rad_declare_drafter`, says 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
|
||||
at either; the short block proposes `block - (RadDrafterDecl::block - depth)` tokens. The builder
|
||||
refuses it without a block drafter, at or above the drafter's own block, and where it would
|
||||
propose nothing. The engine runs it under `--draft-short-from` (GUIDE §4.6) and reads row `s` of
|
||||
the proposals at `s * proposal_pitch`; a block drafter's `proposal_pitch` defaults to its
|
||||
depth (a row holds the whole block's proposals and a short block fills its front) and is refused
|
||||
below it. The pass's block is `n_tok / n_seq`; a block the plugin has no ops for should fail the
|
||||
step (`rad_block_dflash2.h` does). Appended in ABI 27.
|
||||
- **Media preprocessing is the core's** (`core/mm`): resizing, patching, placeholder-token
|
||||
expansion and positions, in five processor families (Qwen-VL, Gemma 4, LFM2-VL, Unlimited-OCR,
|
||||
GLM-5.3) chosen by the container's `vision_config.model_type` (Unlimited-OCR's by its
|
||||
|
||||
-15
@@ -137,21 +137,6 @@ fold in fp32 in ascending rank order, so the switch between them changes no bits
|
||||
at three ranks is the tiered-int8 wire over the same uneven two-shot for messages from
|
||||
`--tp-wire-min-kb` up, and the exact one-shot below.
|
||||
|
||||
An all-reduce a plugin issues on its second lane beside compute (`overlap` 1, [OPS.md](OPS.md)
|
||||
Collectives) takes `ar_twoshot_3rank_exact_lane` or `ar_twoshot_3rank_ti8_lane`, the exact and
|
||||
tiered-int8 two-shots' entry points one priority above the wide rows: qwen4exp's pipelined prefill
|
||||
under `--prefill-span` ([GUIDE.md](GUIDE.md) §4.5), gemma4's prefill trunk overlap and the image and
|
||||
video plugins' second-lane collectives among them. By default they launch exactly as the wide rows
|
||||
(`tArTs38Lane` holds `tAr`'s defaults), so a three-rank deployment runs as it did before them.
|
||||
`R4D_AR_LANE_3_8=1` gives them the four-rank lane rows' launch, 4 blocks of 1024 threads; the
|
||||
arithmetic is the wide rows' either way, bit for bit. At two ranks a wide all-reduce beside a GEMM
|
||||
slowed it 1.45-2.1x on R9700s, which the narrow launch avoids; at three it may pay the same way,
|
||||
or cost where the all-reduce outlasts the compute beside it. Not measured: no three-card machine
|
||||
was available, and the launch is untuned there. GUIDE §4.7 has how to compare the two.
|
||||
`RADIANCE_PREFILL_PIPELINE=on` also allows `qwen35_fp8`'s and `gemma3`'s pipelined prefill at three
|
||||
ranks, but neither model this tree serves with them splits its KV heads three ways (Qwen3.8-27B has
|
||||
4, TranslateGemma 16), so it has nothing to run there yet.
|
||||
|
||||
Startup logs the geometry:
|
||||
|
||||
```
|
||||
|
||||
+3
-7
@@ -75,13 +75,9 @@ promotion truth; quick concurrency ladders within windows.
|
||||
5. Draft-pass graph capture — only if low-concurrency latency ever matters.
|
||||
6. **The dense pipelined prefill at TP4** (`qwen35_fp8`, `qwen35_w8a8`, `gemma3`; GUIDE §4.5): a
|
||||
prefill step of one sequence in two pieces, every block boundary's all-reduce on the second lane
|
||||
at `overlap` 1, so on this table's `*_4rank_*_lane` rows (row 1). Off by default above two
|
||||
ranks; `RADIANCE_PREFILL_PIPELINE=on` allows it and startup notes that it is unmeasured. Measured
|
||||
only at TP2 (2×R9700, PCIe Gen5 x8, 265 W): Qwen3.8-27B MXFP4 41k prefill 9.00 → 8.41 s,
|
||||
TranslateGemma 27B 6k 1.27 → 1.21 s at a 2048 chunk; bit for bit the serial step by construction,
|
||||
checked by KL recordings at TP2 (arch_test checks the pieces and lanes a four- and an eight-rank
|
||||
step declares, not their output). One boot-flag arm, `on` against `off`, at 18K-64K
|
||||
prompts and the chunk served, settles whether it ships on by default here.
|
||||
at `overlap` 1, which at four ranks would take this table's `*_4rank_*_lane` rows (row 1). It
|
||||
runs at two ranks only; enabling it here (`g.world == 2` in both plugins' declare) needs a
|
||||
timing against the serial step at 18K-64K prompts and the chunk served.
|
||||
|
||||
## Interaction diagram
|
||||
|
||||
|
||||
+13
-9
@@ -528,6 +528,18 @@ AVX_BF16_TARGET static inline void pv_rows(float* acc, int64_t D, const uint32_t
|
||||
for (int v = 0; v < 4; ++v) _mm512_storeu_ps(acc + i * D + c0 + 16 * v, o[i][v]);
|
||||
}
|
||||
|
||||
/* P row (64 floats) to bf16 pairs. Kept out of attn_dense_bf16's OpenMP loop: clang's OpenMP
|
||||
* outlining drops the enclosing function's target attribute, and a bf16 intrinsic in the
|
||||
* outlined body then crashes the backend. The outlined function calls this, as it already calls
|
||||
* qk_rows and pv_rows. */
|
||||
AVX_BF16_TARGET static inline void p_to_bf16_pairs(const float* sr, uint32_t* pr) {
|
||||
_mm512_storeu_si512((void*)pr, (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 16),
|
||||
_mm512_loadu_ps(sr)));
|
||||
_mm512_storeu_si512((void*)(pr + 16),
|
||||
(__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 48),
|
||||
_mm512_loadu_ps(sr + 32)));
|
||||
}
|
||||
|
||||
AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor* k,
|
||||
const RadTensor* v, const RadTensor* cu,
|
||||
const RadTensor* o, int64_t D, int64_t gqa,
|
||||
@@ -687,15 +699,7 @@ AVX_BF16_TARGET static bool attn_dense_bf16(const RadTensor* q, const RadTensor*
|
||||
}
|
||||
}
|
||||
/* P to bf16, round to nearest even: a row's 64 values become its 32 key pairs. */
|
||||
for (int64_t r = 0; r < R; ++r) {
|
||||
const float* sr = S + r * KT;
|
||||
uint32_t* pr = ppack + r * 32;
|
||||
_mm512_storeu_si512((void*)pr, (__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 16),
|
||||
_mm512_loadu_ps(sr)));
|
||||
_mm512_storeu_si512((void*)(pr + 16),
|
||||
(__m512i)_mm512_cvtne2ps_pbh(_mm512_loadu_ps(sr + 48),
|
||||
_mm512_loadu_ps(sr + 32)));
|
||||
}
|
||||
for (int64_t r = 0; r < R; ++r) p_to_bf16_pairs(S + r * KT, ppack + r * 32);
|
||||
for (int64_t c0 = 0; c0 < D; c0 += 64) {
|
||||
int64_t r = 0;
|
||||
for (; r + 6 <= R; r += 6) pv_rows<6>(acc + r * D, D, ppack + r * 32, vpack, K2, c0);
|
||||
|
||||
+159
-16
@@ -227,7 +227,10 @@ inline float sin_sq1(float v) {
|
||||
* k input rows' channel runs back to back, zeros outside its own sequence (padded on both sides,
|
||||
* or with `causal` on the left only). A band's patches are one gemm_nt_into call into f32 rows (the
|
||||
* bias added there); `res` and the tanh or the clamp to [-1, 1] are applied to the f32 rows, which
|
||||
* are rounded once into y. A 1-wide kernel over a dense x reads x itself as the patches. */
|
||||
* are rounded once into y. A 1-wide kernel over a dense x reads x itself as the patches. With a
|
||||
* `stride` (causal only) output row o's patch starts at input row o stride - pad, the pad the
|
||||
* reach less the stride, and a sequence of L rows makes L / stride. `cu_div`: the bounds in units
|
||||
* that many input rows apart, as libref reads them. */
|
||||
AVX_KERNEL(conv1d) {
|
||||
if (!rad_args_have(a, 3) || a->n_t < 5) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *W = &a->t[1], *cu = &a->t[2];
|
||||
@@ -235,20 +238,26 @@ AVX_KERNEL(conv1d) {
|
||||
if (!Y->data) return RAD_E_INVAL;
|
||||
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0);
|
||||
const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0);
|
||||
const int64_t st = p_int(a, "stride", 1), cd = p_int(a, "cu_div", 1);
|
||||
const char* act = p_str(a, "act", "none");
|
||||
const bool tanh_out = act && !std::strcmp(act, "tanh");
|
||||
const bool clamp_out = act && !std::strcmp(act, "clamp");
|
||||
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 ||
|
||||
causal < 0 || causal > 1)
|
||||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) ||
|
||||
cd < 1)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
if (n_seq <= 0) return RAD_E_SHAPE;
|
||||
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
|
||||
if (r0 < 0 || r1 <= r0 || rows_of(Y, cout) < r1 || rows_of(X, cin) < r1) return RAD_E_SHAPE;
|
||||
for (int64_t e = 0; e <= n_seq; ++e)
|
||||
if (cu_at(cu, e) % (cd * st)) return RAD_E_SHAPE;
|
||||
/* r0, r1: the output rows, the input's over the stride. */
|
||||
const int64_t r0 = cu_at(cu, 0) / (cd * st), r1 = cu_at(cu, n_seq) / (cd * st);
|
||||
if (r0 < 0 || r1 <= r0 || rows_of(Y, cout) < r1 || rows_of(X, cin) < r1 * st)
|
||||
return RAD_E_SHAPE;
|
||||
if (numel(W) < cout * cin * k || (B && numel(B) < cout)) return RAD_E_SHAPE;
|
||||
if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE;
|
||||
const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2, KK = k * cin;
|
||||
const int64_t pad = causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2, KK = k * cin;
|
||||
static thread_local std::vector<uint8_t> wbuf, pbuf;
|
||||
static thread_local std::vector<float> ybuf;
|
||||
|
||||
@@ -264,8 +273,8 @@ AVX_KERNEL(conv1d) {
|
||||
const uint32_t adt = b16 ? (uint32_t)RAD_BF16 : (uint32_t)RAD_F32;
|
||||
const size_t ael = b16 ? 2 : 4;
|
||||
/* A 1-wide kernel's patch row is x's own row. */
|
||||
const bool direct = k == 1 && X->rank == 2 && X->shape[1] == cin && X->stride[1] == 1 &&
|
||||
(X->dtype == RAD_BF16 || X->dtype == RAD_F32);
|
||||
const bool direct = k == 1 && st == 1 && X->rank == 2 && X->shape[1] == cin &&
|
||||
X->stride[1] == 1 && (X->dtype == RAD_BF16 || X->dtype == RAD_F32);
|
||||
const int64_t band = band_rows(KK, cout, r1 - r0);
|
||||
if (!direct) pbuf.resize((size_t)(band * KK) * ael + 64);
|
||||
ybuf.resize((size_t)(band * cout) + 16);
|
||||
@@ -282,10 +291,10 @@ AVX_KERNEL(conv1d) {
|
||||
pt = mat_view(pp, adt, nb, KK);
|
||||
AVX_PARALLEL_FOR_IF(nb * KK >= AVX_PAR_MIN)
|
||||
for (int64_t p = 0; p < nb; ++p) {
|
||||
const int64_t r = b0 + p, e = seq_of(cu, n_seq, r);
|
||||
const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1);
|
||||
const int64_t r = b0 + p, e = seq_of(cu, n_seq, r * st * cd);
|
||||
const int64_t s0 = cu_at(cu, e) / cd, s1 = cu_at(cu, e + 1) / cd;
|
||||
for (int64_t t = 0; t < k; ++t) {
|
||||
const int64_t ir = r + t * dil - pad;
|
||||
const int64_t ir = r * st + t * dil - pad;
|
||||
patch_slot(X, ir, cin, ir >= s0 && ir < s1, b16,
|
||||
pp + (size_t)(p * KK + t * cin) * ael);
|
||||
}
|
||||
@@ -590,8 +599,10 @@ AVX_KERNEL(cfg_topk_sample) {
|
||||
const int64_t sup_lo = p_int(a, "sup_lo", 0), sup_hi = p_int(a, "sup_hi", 0);
|
||||
const float cfg = p_f32(a, "cfg", 1.0f), temp = p_f32(a, "temp", 1.0f);
|
||||
const float pen = p_f32(a, "penalty", 1.0f);
|
||||
const double top_p = (double)p_f32(a, "top_p", 1.0f);
|
||||
if (V <= 0 || K <= 0 || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) ||
|
||||
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane))
|
||||
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane) ||
|
||||
!(top_p >= 0))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t n = numel(ids) / rep;
|
||||
if (n <= 0 || rows_of(lg, V) < rep * n || numel(fr) < n || numel(seed) < 2 * n ||
|
||||
@@ -650,11 +661,29 @@ AVX_KERNEL(cfg_topk_sample) {
|
||||
} else {
|
||||
for (int64_t j = 0; j < V; ++j) if (open(j)) idx[nc++] = j;
|
||||
}
|
||||
const int64_t kk = std::min(K, nc);
|
||||
/* top_p's normaliser over every candidate in index order (idx still is), as libref. */
|
||||
double z = 0;
|
||||
if (top_p < 1.0) {
|
||||
float gm = g[idx[0]];
|
||||
for (int64_t t = 1; t < nc; ++t) gm = std::max(gm, g[idx[t]]);
|
||||
const float m0 = gm / temp;
|
||||
for (int64_t t = 0; t < nc; ++t) z += std::exp((double)(g[idx[t]] / temp - m0));
|
||||
}
|
||||
int64_t kk = std::min(K, nc);
|
||||
std::partial_sort(idx, idx + kk, idx + nc, [g](int64_t p, int64_t q) {
|
||||
return g[p] > g[q] || (g[p] == g[q] && p < q);
|
||||
});
|
||||
const float m = g[idx[0]] / temp;
|
||||
if (top_p < 1.0) {
|
||||
double cum = 0;
|
||||
int64_t keep = 1;
|
||||
for (int64_t t = 0; t < kk; ++t) {
|
||||
cum += std::exp((double)(g[idx[t]] / temp - m)) / z;
|
||||
if (t > 0 && cum > top_p) break;
|
||||
keep = t + 1;
|
||||
}
|
||||
kk = keep;
|
||||
}
|
||||
double tot = 0;
|
||||
for (int64_t t = 0; t < kk; ++t) {
|
||||
e[t] = std::exp((double)(g[idx[t]] / temp - m));
|
||||
@@ -693,17 +722,18 @@ AVX_KERNEL(rvq_embed) {
|
||||
const int64_t D = p_int(a, "n_embd", 0), K = p_int(a, "n_codes", 0);
|
||||
const int64_t voc = p_int(a, "vocab", 0), off0 = p_int(a, "off0", 0);
|
||||
const float scale = p_f32(a, "scale", 1.0f);
|
||||
const int64_t round1 = p_int(a, "round", 0);
|
||||
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return RAD_E_SHAPE;
|
||||
const int64_t round1 = p_int(a, "round", 0), clamp = p_int(a, "clamp", 0);
|
||||
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1 || clamp < 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(Y, D);
|
||||
if (rows <= 0 || numel(codes) < K * rows) return RAD_E_SHAPE;
|
||||
const int64_t n0 = rows_of(t0, D), n1 = rows_of(t1, D);
|
||||
auto cl = [clamp](int64_t c) { return clamp > 0 && c > clamp - 1 ? clamp - 1 : c; };
|
||||
/* Code (k, r): a codebook's row at the plane's own pitch, a frame's code at its own stride. */
|
||||
const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rows;
|
||||
const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1;
|
||||
AVX_PARALLEL_FOR_IF(rows * D * K >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t c0 = ld_int_dt(codes->dtype, codes->data, r * rp) + off0;
|
||||
const int64_t c0 = cl(ld_int_dt(codes->dtype, codes->data, r * rp)) + off0;
|
||||
if (c0 < 0 || c0 >= n0) continue;
|
||||
float* acc = scratch_f32((size_t)D + 16);
|
||||
float* buf = scratch_f32_b((size_t)D + 16);
|
||||
@@ -716,7 +746,7 @@ AVX_KERNEL(rvq_embed) {
|
||||
}
|
||||
for (int64_t k = 1; k < K; ++k) {
|
||||
const int64_t cb =
|
||||
ld_int_dt(codes->dtype, codes->data, k * kp + r * rp) + (k - 1) * voc;
|
||||
cl(ld_int_dt(codes->dtype, codes->data, k * kp + r * rp)) + (k - 1) * voc;
|
||||
if (cb < 0 || cb >= n1) continue;
|
||||
const float* tr = in_row(t1, rowoff(t1, cb, D), D, buf);
|
||||
for (int64_t d = 0; d < D; ++d) acc[d] += tr[d];
|
||||
@@ -736,6 +766,70 @@ AVX_KERNEL(rvq_embed) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vq_encode */
|
||||
/* libref's step a row at a time: e as dim dot products over x's row, the codebook normalised once
|
||||
* a launch (F.normalize's division) and scored against e normalised, ties to the lower index, the
|
||||
* chosen raw row's out-projection subtracted and the row rounded once into x. */
|
||||
AVX_KERNEL(vq_encode) {
|
||||
if (!rad_args_have(a, 7)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *iw = &a->t[1], *ib = &a->t[2], *cb = &a->t[3];
|
||||
const RadTensor *ow = &a->t[4], *ob = &a->t[5], *codes = &a->t[6];
|
||||
const int64_t n = p_int(a, "n", 0), dim = p_int(a, "dim", 0), bins = p_int(a, "bins", 0);
|
||||
if (n <= 0 || dim <= 0 || bins <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(X, n);
|
||||
if (rows <= 0 || numel(codes) < rows || numel(iw) < dim * n || numel(ib) < dim ||
|
||||
numel(cb) < bins * dim || numel(ow) < n * dim || numel(ob) < n)
|
||||
return RAD_E_SHAPE;
|
||||
/* The weights dense in f32, held by this thread for the launch's parallel region. */
|
||||
auto dense = [](const RadTensor* t, int64_t m) {
|
||||
std::vector<float> v((size_t)m);
|
||||
for (int64_t i = 0; i < m; ++i) v[(size_t)i] = ldt(t, i);
|
||||
return v;
|
||||
};
|
||||
const std::vector<float> wi = dense(iw, dim * n), bi = dense(ib, dim);
|
||||
const std::vector<float> raw = dense(cb, bins * dim), wo = dense(ow, n * dim), bo = dense(ob, n);
|
||||
std::vector<float> cn((size_t)(bins * dim));
|
||||
for (int64_t c = 0; c < bins; ++c) {
|
||||
const float* cr = raw.data() + c * dim;
|
||||
float ss = 0.0f;
|
||||
for (int64_t j = 0; j < dim; ++j) ss += cr[j] * cr[j];
|
||||
const float nrm = std::max(std::sqrt(ss), 1e-12f);
|
||||
for (int64_t j = 0; j < dim; ++j) cn[(size_t)(c * dim + j)] = cr[j] / nrm;
|
||||
}
|
||||
const float *Wi = wi.data(), *Bi = bi.data(), *Raw = raw.data(), *Cn = cn.data();
|
||||
const float *Wo = wo.data(), *Bo = bo.data();
|
||||
AVX_PARALLEL_FOR_IF(rows * (2 * n + bins) * dim >= AVX_PAR_MIN)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(X, r, n);
|
||||
const float* xv = in_row(X, xb, n, scratch_f32((size_t)n + 16));
|
||||
float* e = scratch_f32_c((size_t)dim + 16);
|
||||
float ss = 0.0f;
|
||||
for (int64_t j = 0; j < dim; ++j) {
|
||||
e[j] = dotf(Wi + j * n, xv, n) + Bi[j];
|
||||
ss += e[j] * e[j];
|
||||
}
|
||||
const float nrm = std::max(std::sqrt(ss), 1e-12f);
|
||||
for (int64_t j = 0; j < dim; ++j) e[j] /= nrm;
|
||||
int64_t best = 0;
|
||||
float bs = -INFINITY;
|
||||
for (int64_t c = 0; c < bins; ++c) {
|
||||
float s = 0.0f;
|
||||
for (int64_t j = 0; j < dim; ++j) s += e[j] * Cn[c * dim + j];
|
||||
if (s > bs) { bs = s; best = c; }
|
||||
}
|
||||
st_int_dt(codes->dtype, codes->data, offlin(codes, r), best);
|
||||
float* y = scratch_f32_b((size_t)n + 16);
|
||||
const float* row = Raw + best * dim;
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
float q = 0.0f;
|
||||
for (int64_t j = 0; j < dim; ++j) q += Wo[d * dim + j] * row[j];
|
||||
y[d] = xv[d] - (q + Bo[d]);
|
||||
}
|
||||
out_row(X, xb, n, y);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ frame_mix_store */
|
||||
/* m = bf16(bf16(sum_l w_l h_l) * bf16(scale)), w = bf16(softmax(bf16(logits))) in libref's double
|
||||
* arithmetic, the planes summed in order with each product rounded before its add (`keep`). Entries
|
||||
@@ -789,6 +883,42 @@ AVX_KERNEL(frame_mix_store) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ ras_pick */
|
||||
/* libref's rule: the first draw unless it lies in [lo, hi) and the lane's window of its last `win`
|
||||
* picks holds it, then the alternative; the pick enters the window. Lanes are checked before
|
||||
* anything is written and run in order, as two entries may share a lane's window. */
|
||||
AVX_KERNEL(ras_pick) {
|
||||
if (!rad_args_have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *first = &a->t[0], *alt = &a->t[1], *lane = &a->t[2], *hist = &a->t[3];
|
||||
const RadTensor* ids = &a->t[4];
|
||||
const int64_t W = p_int(a, "win", 0), lo = p_int(a, "lo", 0), hi = p_int(a, "hi", 0);
|
||||
const int64_t rep = p_int(a, "rep", 1), clear = p_int(a, "clear", 0);
|
||||
const int64_t n = numel(lane);
|
||||
if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 ||
|
||||
numel(first) < rep * n || numel(alt) < rep * n || numel(ids) < rep * n)
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t L = at(lane, i);
|
||||
if (L < 0 || (L + 1) * W > numel(hist)) return RAD_E_SHAPE;
|
||||
}
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t hb = at(lane, i) * W;
|
||||
if (clear)
|
||||
for (int64_t w = 0; w < W; ++w) st_int_dt(hist->dtype, hist->data, offlin(hist, hb + w), -1);
|
||||
const int64_t f = at(first, rep * i);
|
||||
int64_t pick = f;
|
||||
if (f >= lo && f < hi)
|
||||
for (int64_t w = 0; w < W; ++w)
|
||||
if (at(hist, hb + w) == f) { pick = at(alt, rep * i); break; }
|
||||
for (int64_t r = 0; r < rep; ++r)
|
||||
st_int_dt(ids->dtype, ids->data, offlin(ids, rep * i + r), pick);
|
||||
for (int64_t w = 0; w + 1 < W; ++w)
|
||||
st_int_dt(hist->dtype, hist->data, offlin(hist, hb + w), at(hist, hb + w + 1));
|
||||
st_int_dt(hist->dtype, hist->data, offlin(hist, hb + W - 1), pick);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ end_status */
|
||||
/* status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]. */
|
||||
AVX_KERNEL(end_status) {
|
||||
@@ -1125,6 +1255,19 @@ AVX_KERNEL(int_affine) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ sub_i32 */
|
||||
/* y[i] = x[i] - s[0], int32. */
|
||||
AVX_KERNEL(sub_i32) {
|
||||
if (!rad_args_have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *X = &a->t[0], *S = &a->t[1], *Y = &a->t[2];
|
||||
const int64_t n = numel(Y);
|
||||
if (n <= 0 || numel(X) < n || numel(S) < 1) return RAD_E_SHAPE;
|
||||
const int64_t s0 = at(S, 0);
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
st_int_dt(Y->dtype, Y->data, offlin(Y, i), (int64_t)(int32_t)(at(X, i) - s0));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ cu_repeat */
|
||||
/* y[j] = j * len[0] * mult over y's elements: the bounds of equal sequences. */
|
||||
AVX_KERNEL(cu_repeat) {
|
||||
|
||||
@@ -997,6 +997,13 @@ std::vector<Case> build_cases() {
|
||||
for (int dil : { 1, 3 })
|
||||
add("conv1d", { HI("M", 24), HI("cin", 20), HI("cout", 13), HI("k", 7),
|
||||
HI("dil", dil), HI("causal", 1), HS("dtype", dt) });
|
||||
/* Strided, causal: Fish Audio's codec encoder downsamples with kernels of two strides
|
||||
* (2, 4, 8) and its quantiser with a kernel of one (k 2, stride 2). */
|
||||
for (int s : { 2, 4, 8 })
|
||||
add("conv1d", { HI("M", 64), HI("cin", 20), HI("cout", 13), HI("k", 2 * s),
|
||||
HI("dil", 1), HI("causal", 1), HI("stride", s), HS("dtype", dt) });
|
||||
add("conv1d", { HI("M", 64), HI("cin", 24), HI("cout", 16), HI("k", 2), HI("dil", 1),
|
||||
HI("causal", 1), HI("stride", 2), HS("dtype", dt) });
|
||||
for (int s : { 2, 4, 8 })
|
||||
add("conv_t1d", { HI("M", 12), HI("cin", 20), HI("cout", 13), HI("stride", s),
|
||||
HS("dtype", dt) });
|
||||
@@ -1041,6 +1048,12 @@ std::vector<Case> build_cases() {
|
||||
add("cfg_topk_sample", { HI("M", 6), HI("n_vocab", 645), HI("k", 645), HI("rep", 2),
|
||||
HF("cfg", 1.7), HF("temp", 0.8), HI("stream", 0),
|
||||
HS("dtype", "f32") });
|
||||
/* Fish Audio's draw: the nucleus over the whole candidate set's softmax, then the top-k cut;
|
||||
* at a small top_p the head alone, and above 1 none. */
|
||||
for (double tp : { 0.7, 0.05, 0.95 })
|
||||
add("cfg_topk_sample", { HI("M", 4), HI("n_vocab", 645), HI("k", 30), HI("rep", 1),
|
||||
HF("cfg", 1.0), HF("temp", 0.7), HI("stream", 2),
|
||||
HF("top_p", tp), HS("dtype", "f32") });
|
||||
/* A speech model's backbone pick: reserved ids suppressed (the vocabulary's last class stays a
|
||||
* candidate), a temperature, the penalty idle without a history. */
|
||||
for (int rep : { 1, 2 })
|
||||
@@ -1052,6 +1065,9 @@ std::vector<Case> build_cases() {
|
||||
for (double sc : { 1.0, 0.7 })
|
||||
add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 8), HI("vocab", 64),
|
||||
HI("off0", 5), HF("scale", sc), HS("dtype", dt) });
|
||||
/* Codes past a codebook smaller than its heads read its last row (Fish Audio's codec). */
|
||||
add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 4), HI("vocab", 64),
|
||||
HI("off0", 0), HF("scale", 1.0), HI("clamp", 40), HS("dtype", dt) });
|
||||
/* One rounding of the whole sum: sixteen codebooks, as a speech model's frame embedding. */
|
||||
for (double sc : { 1.0, 0.7 })
|
||||
add("rvq_embed", { HI("M", 7), HI("n_embd", 645), HI("n_codes", 16), HI("vocab", 64),
|
||||
@@ -1081,6 +1097,19 @@ std::vector<Case> build_cases() {
|
||||
}
|
||||
add("end_status", { HI("M", 2), HI("end", 5), HI("rep", 2) });
|
||||
add("end_status", { HI("M", 4), HI("end", 3), HI("rep", 1) });
|
||||
add("ras_pick", { HI("M", 4), HI("win", 16), HI("lo", 1), HI("hi", 9), HI("rep", 1) });
|
||||
add("ras_pick", { HI("M", 2), HI("win", 4), HI("lo", 0), HI("hi", 12), HI("rep", 2),
|
||||
HI("clear", 1) });
|
||||
/* A codec encoder's residual quantiser step: DAC's eight-wide codes over a semantic codebook
|
||||
* and a residual one, both dtypes; a dimension that is no vector's width. */
|
||||
for (const char* dt : { "f32", "bf16" }) {
|
||||
add("vq_encode", { HI("M", 7), HI("n", 64), HI("dim", 8), HI("bins", 4096),
|
||||
HS("dtype", dt) });
|
||||
add("vq_encode", { HI("M", 5), HI("n", 128), HI("dim", 8), HI("bins", 1024),
|
||||
HS("dtype", dt) });
|
||||
}
|
||||
add("vq_encode", { HI("M", 3), HI("n", 40), HI("dim", 5), HI("bins", 33),
|
||||
HS("dtype", "f32") });
|
||||
add("frame_store", { HI("M", 2), HI("n_codes", 16), HI("stride", 9), HI("rep", 2),
|
||||
HI("skip", 0) });
|
||||
add("frame_store", { HI("M", 4), HI("n_codes", 3), HI("stride", 5), HI("rep", 1),
|
||||
@@ -1093,6 +1122,8 @@ std::vector<Case> build_cases() {
|
||||
add("cu_repeat", { HI("M", 9), HI("mult", 1) });
|
||||
add("int_affine", { HI("M", 4), HS("src", "0 -1 2 1"), HS("mul", "2 0 8 4"),
|
||||
HS("add", "-1 7 -7 -3") });
|
||||
add("sub_i32", { HI("M", 1) });
|
||||
add("sub_i32", { HI("M", 37) });
|
||||
|
||||
/* ================================================================== speed-only, at model size
|
||||
*
|
||||
|
||||
@@ -4060,6 +4060,22 @@ void audio_cases(std::vector<Hand>& hs) {
|
||||
.pi("causal", 1).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (const int64_t s : { 2, 4 }) {
|
||||
/* A codec encoder's downsampling: kernel 2 stride, causal, the bounds in samples
|
||||
* (cu_div 8 input rows), two clips of 4 and 2 strides from input row 2 s. */
|
||||
const int64_t cin = 12, cout = 9, M = 8 * s;
|
||||
Hand h(("stride " + std::to_string(s) + ", bounds in units of 8 rows" + sfx).c_str(),
|
||||
"conv1d", norm_tol);
|
||||
h.dense(dt, { M, cin }, hfill(330 + s))
|
||||
.dense(dt, { cout, cin, 2 * s }, hfill(334, 0.3f))
|
||||
.idx({ (int32_t)(16 * s), (int32_t)(48 * s), (int32_t)(64 * s) })
|
||||
.none()
|
||||
.dense(dt, { M / s, cout }, hfill(335), true)
|
||||
.dense(dt, { cout }, hfill(336, 0.5f))
|
||||
.pi("M", M).pi("cin", cin).pi("cout", cout).pi("k", 2 * s).pi("dil", 1)
|
||||
.pi("causal", 1).pi("stride", s).pi("cu_div", 8).ps("dtype", dn);
|
||||
hs.push_back(std::move(h));
|
||||
}
|
||||
for (const int64_t s : { 5, 3 }) {
|
||||
/* A codec's odd strides at kernel 2 stride, causal, over sequences of 3, 1 and 5 rows
|
||||
* from row 1. */
|
||||
|
||||
@@ -260,8 +260,10 @@ AVX_QB_TARGET static void qb_codes(const QbTab& q, const uint8_t* src, int64_t n
|
||||
* first code), as code - zero in bf16 into dst[0, npad), the words past n zero. zr[j] is the zero
|
||||
* of the j-th 32 codes. A code minus its zero lies in [-31, 31], exact in bf16: `t` holds bf16(i -
|
||||
* 32) for i < 64, which one vpermt2w indexes by code - zero + 32. u5 codes are 40 bits for each
|
||||
* eight, deposited into bytes by pdep (BMI2, which the caller checked). */
|
||||
AVX_QB_TARGET __attribute__((target("bmi2"))) static void qb_codes_zp(
|
||||
* eight, deposited into bytes by pdep (BMI2, which the caller checked). BMI2 is named in the one
|
||||
* target attribute with the level's features: clang keeps only one of two stacked target
|
||||
* attributes and then refuses to inline _pdep_u64. */
|
||||
__attribute__((target("avx512f,avx512bw,avx512vl,avx512bf16,bmi2"))) static void qb_codes_zp(
|
||||
const uint8_t* row, int bits, int64_t n, int64_t npad, uint16_t* dst, const int32_t* zr,
|
||||
const __m512i* t) {
|
||||
for (int64_t i = 0; i < npad; i += 32) {
|
||||
|
||||
+2
-1
@@ -136,7 +136,8 @@ int avx_par_force(int threads);
|
||||
X(rvq_embed) X(frame_mix_store) X(end_status) X(frame_store) \
|
||||
X(resample_nearest) X(fourier_embed) X(win_input) X(win_prep) \
|
||||
X(win_finish) X(chan_split) X(interleave2) X(iota) \
|
||||
X(cu_repeat) X(snake_aa) X(int_affine) \
|
||||
X(cu_repeat) X(snake_aa) X(int_affine) X(sub_i32) \
|
||||
X(ras_pick) X(vq_encode) \
|
||||
/* ---- sampling, and the drafter's token walk */ \
|
||||
X(sample_penalties) X(sample_dry) X(sample_temp) X(sample_topk) \
|
||||
X(sample_topp) X(sample_minp) X(sample_typical) X(sample_xtc) \
|
||||
|
||||
+28
-3
@@ -717,7 +717,8 @@ static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") };
|
||||
/* ---- audio generation (avx_audio.cpp), as libref declares it ------------------------------ */
|
||||
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
|
||||
P_INTO("causal") };
|
||||
P_INTO("causal"), P_INTO("stride"),
|
||||
P_INTO("cu_div") };
|
||||
static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"),
|
||||
OUT("y"), WGT_O("b") };
|
||||
static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"),
|
||||
@@ -733,19 +734,28 @@ static const RadOperandSpec oSnakeAa[] = { OPD("x"), WGT("alpha"), WGT("beta"),
|
||||
static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"),
|
||||
P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"),
|
||||
P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"),
|
||||
P_INTO("sup_hi"), P_F64O("penalty") };
|
||||
P_INTO("sup_hi"), P_F64O("penalty"),
|
||||
P_F64O("top_p") };
|
||||
static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("frame"), OUT("ids"),
|
||||
OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") };
|
||||
static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"),
|
||||
P_INT("vocab"), P_INT("off0"), P_F64("scale"),
|
||||
P_STR("dtype"), P_INTO("round") };
|
||||
P_STR("dtype"), P_INTO("round"), P_INTO("clamp") };
|
||||
static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") };
|
||||
static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oVqEncode[] = { INOUT("x"), WGT("in_w"), WGT("in_b"), WGT("cb"),
|
||||
WGT("out_w"), WGT("out_b"), OUT("codes") };
|
||||
static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"),
|
||||
P_INTO("rep"), P_STR("dtype") };
|
||||
static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"),
|
||||
OPD("frame"), OPD("status"), INOUT("dst") };
|
||||
static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") };
|
||||
static const RadOperandSpec oEndStatus[] = { OPD("ids"), OPD("lane"), INOUT("status") };
|
||||
static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"),
|
||||
P_INTO("rep"), P_INTO("clear") };
|
||||
static const RadOperandSpec oRasPick[] = { OPD("first"), OPD("alt"), OPD("lane"), INOUT("hist"),
|
||||
OUT("ids") };
|
||||
static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"),
|
||||
P_INTO("rep"), P_INTO("skip") };
|
||||
static const RadOperandSpec oFrameStore[] = { OPD("codes"), OPD("lane"), OPD("frame"),
|
||||
@@ -776,6 +786,8 @@ static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
|
||||
static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") };
|
||||
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
|
||||
static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") };
|
||||
static const RadParamSpec pSubI32[] = { P_INT("M") };
|
||||
static const RadOperandSpec oSubI32[] = { OPD("x"), OPD("s"), OUT("y") };
|
||||
|
||||
/* ---- vocabulary edges --------------------------------------------------------------------- */
|
||||
static const RadParamSpec pEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_vocab"),
|
||||
@@ -1230,10 +1242,16 @@ static const RadOpSchema kSchemas[] = {
|
||||
"libref's." },
|
||||
{ "rvq_embed", ARR(pRvqEmbed), ARR(oRvqEmbed),
|
||||
"a frame's embedding from code-major residual codes, libref's roundings (`round` 1: one)." },
|
||||
{ "vq_encode", ARR(pVqEncode), ARR(oVqEncode),
|
||||
"one residual vector quantiser step: the code of greatest cosine with in_w x + in_b, then "
|
||||
"x -= out_w cb[code] + out_b; libref's arithmetic in another summation order." },
|
||||
{ "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix),
|
||||
"a frame's softmax-weighted mix of hidden planes, stored into its lane, bit for bit libref's." },
|
||||
{ "end_status", ARR(pEndStatus), ARR(oEndStatus),
|
||||
"status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]." },
|
||||
{ "ras_pick", ARR(pRasPick), ARR(oRasPick),
|
||||
"repetition-aware sampling: the alternative draw where the first is in [lo, hi) and in the "
|
||||
"lane's window of its last picks, else the first; the pick enters the window." },
|
||||
{ "frame_store", ARR(pFrameStore), ARR(oFrameStore),
|
||||
"a frame's codes into its lane's history, code-major rows over the lane's frames." },
|
||||
{ "resample_nearest", ARR(pMnD), ARR(oUnary),
|
||||
@@ -1252,6 +1270,7 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "cu_repeat", ARR(pCuRepeat), ARR(oCuRepeat), "y[j] = j * len[0] * mult." },
|
||||
{ "int_affine", ARR(pIntAffine), ARR(oIntAffine),
|
||||
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists." },
|
||||
{ "sub_i32", ARR(pSubI32), ARR(oSubI32), "y[i] = x[i] - s[0], int32." },
|
||||
{ "embed_lookup", ARR(pEmbedM), ARR(oEmbed),
|
||||
"embedding gather, vocab-parallel with an offset; `mult` multiplies every row (rounded once)." },
|
||||
{ "embed_lookup_q", ARR(pEmbed), ARR(oEmbedQ),
|
||||
@@ -1775,10 +1794,14 @@ SIMPLE("avx_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick
|
||||
L(cfg_topk_sample)),
|
||||
SIMPLE("avx_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes",
|
||||
DT_FLOAT, L(rvq_embed)),
|
||||
SIMPLE("avx_vq_encode", "vq_encode", "elem",
|
||||
"a residual quantiser's step: the nearest code by cosine", DT_FLOAT, L(vq_encode)),
|
||||
SIMPLE("avx_frame_mix_store", "frame_mix_store", "elem",
|
||||
"a frame's conditioning row into its lane", DT_FLOAT, L(frame_mix_store)),
|
||||
SIMPLE("avx_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY,
|
||||
L(end_status)),
|
||||
SIMPLE("avx_ras_pick", "ras_pick", "elem", "a repetition-aware choice between two draws a lane",
|
||||
DT_ANY, L(ras_pick)),
|
||||
SIMPLE("avx_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY,
|
||||
L(frame_store)),
|
||||
SIMPLE("avx_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour",
|
||||
@@ -1799,6 +1822,8 @@ SIMPLE("avx_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, L(iot
|
||||
SIMPLE("avx_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, L(cu_repeat)),
|
||||
SIMPLE("avx_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY,
|
||||
L(int_affine)),
|
||||
SIMPLE("avx_sub_i32", "sub_i32", "elem", "a device int32 vector less a device scalar", DT_ANY,
|
||||
L(sub_i32)),
|
||||
|
||||
SIMPLE("avx_embed_lookup", "embed_lookup", "vocab", "embedding gather", DT_FLOAT, L(embed_lookup)),
|
||||
/* Its layout hook only validates: the table is read as stored and other encodings are refused
|
||||
|
||||
+40
-3
@@ -71,7 +71,6 @@ The table lists a selection; `r4d_rows.cpp` and `r4d.h` hold the full set.
|
||||
| `gdn_gated_norm_had_quant_i8` | the GDN gated norm with the rotation and quantiser fused onto it |
|
||||
| `qk_norm_rope_gate` | q/k RMS norm, rope and the attention gate in one kernel |
|
||||
| `ar_oneshot_{3,4,8}rank_exact`, `ar_twoshot_{3,4,8}rank_exact`, `ar_twoshot_{3,4}rank_ti8`, `ar_gather_3rank` | the wider-world collectives (TP3/TP4/TP8), exact and int8-wire |
|
||||
| `ar_twoshot_{3,4,8}rank_exact_lane`, `ar_twoshot_{3,4}rank_ti8_lane` | the same two-shots at `overlap` 1, beside compute: the wide rows' entry points, the same bits; at four ranks a narrow launch (4 blocks of 1024 threads), at three and eight the wide launch unless `R4D_AR_LANE_3_8=1` gives them the narrow one (unmeasured on such cards) |
|
||||
| `p2p_copy2d`, `p2p_copy2d_kernel`, `p2p_fence` | strided peer device-to-device copy, through the copy engines or a kernel |
|
||||
|
||||
## Constraints as data
|
||||
@@ -189,14 +188,52 @@ this kernel: the 128-wide slab always, and a split only while every split keeps
|
||||
48-block grid or, at K ≥ 8192, regardless, up to ks·M = 1024 split rows. At 80 / 96 / 128 rows:
|
||||
17408 × 5120 161 / 187 / 215 → 161 / 175 / 197 µs, 5120 × 3072 71 / 79 / 67 → 55 / 60 / 69, 21504 ×
|
||||
5376 192 / 207 / 228 → 187 / 200 / 217. A different split sums a row in a different order, so at
|
||||
65..128 rows the re-tuned rule moves output bits within the selftest's bound: the one change in
|
||||
this family that is not bit for bit. Up to 64 rows the rule is as it was.
|
||||
65..128 rows the re-tuned rule moves output bits within the selftest's bound. Up to 64 rows the
|
||||
decode kernel's bits are as they were.
|
||||
|
||||
**Bits against the rows these replace.** `gemv` and `gemv_wide` sum a row in their own order (the
|
||||
K split over eight waves and 128-wide chunks), not the decode kernel's split-K order, so at 1..64
|
||||
rows their outputs differ from the decode row's in the last bf16 place on a few elements in ten
|
||||
thousand (within the selftest's bound). A greedy text can therefore differ from one produced
|
||||
with the decode row at those rows. Within the family a row's bits do not depend on M, as above.
|
||||
|
||||
**Tunables.** `gemv` and `gemv_wide` have none, so a `RADIANCE_TUNE` pin on `gemm_nt_q` passes
|
||||
them by. `decode_shortk` shares the decode row's axes (`ks`, `bk`, `nt`; 0 the rule), so a pin of
|
||||
those reaches both. A pin applies to every row serving the op, and an axis a serving row lacks
|
||||
stops startup by name.
|
||||
|
||||
## The OCP-MXFP4 tiled GEMM (prefill)
|
||||
|
||||
**`gemm_mxfp4a8_tiled`** (`gemm_nt_q` at `mxfp4a8`, the rows past the decode band). TN = 4 (256 ×
|
||||
128 blocks) from 1024 rows (it was 2048), unless its blocks would number under 128: at the
|
||||
crossover Qwen3.8-27B's gate_up -2 %, down -3 %, TranslateGemma 27B's gate_up -9 %, its down +1 %,
|
||||
and at 1536 rows all four better; TranslateGemma's 1024-row chunks run there. The weight words a
|
||||
thread stages are loaded into registers a slab ahead, right after the staging barrier, so their
|
||||
DRAM round trip runs under the slab's WMMAs (+1 VGPR at TN = 4, no spills). At 1024 rows Qwen
|
||||
gate_up 804 → 768 µs, down 443 → 417, ssm_in 396 → 384, ssm_out 249 → 231, q|gate 306 → 318;
|
||||
TranslateGemma gate_up 1063 → 1029, down 651 → 617; at 2048 rows 0..-4 %; a 41k-token Qwen3.8-27B
|
||||
prefill on two cards 8.57 → 8.28 s. A thin last row of blocks (1..160 rows, M under 1024) runs a
|
||||
second kernel whose blocks of that row skip the WMMAs of fragments past M, where the plain kernel
|
||||
computes them on clamped copies (half the only block's math at 129 rows); every other M runs the
|
||||
plain kernel, whose code is instruction for instruction the single kernel's from before the split
|
||||
(a guard inside the one kernel cost full blocks 1..15 %). Same-session A/B over 12 shapes: M
|
||||
129..160 -8..-20 %, 320..384 -2..-16 % (Qwen gate_up at 320 rows 402 → 339 µs, TranslateGemma's 513
|
||||
→ 441). Each of the three keeps the fold, the WMMAs and their order per output byte. Times are one
|
||||
rank's weight at TP2 on an R9700, the row alone, clocks warmed; over 20 shapes, M 129..2048: median
|
||||
-7.4 % over 140 cells, none slower beyond run-to-run noise.
|
||||
|
||||
`tn` (0 the rule, 2, 4) pins the TN choice through `RADIANCE_TUNE`.
|
||||
|
||||
## The fp8 and int8 heads past 64 rows
|
||||
|
||||
**`logits_gemm_fp8`, `logits_gemm_i8`** took passes of 64 rows and read the head again for each.
|
||||
With `MH` = 2 a workgroup's eight waves split into two M halves of four 16-row tiles over 64 weight
|
||||
rows that share one staged tile, so a pass takes 128 rows and reads the head once. Qwen3.8's
|
||||
per-rank head (124160 × 5120) at 128 rows 3059 → 1984 µs, TranslateGemma's (131072 × 5376) 3242 →
|
||||
2036; 65..128 rows -33..-39 %, 160..256 -26..-37 %, 64 and fewer unchanged; about 1 ms a step at 16
|
||||
streams with speculation. Same scale blocks, WMMAs and K order per output: the same bytes (the
|
||||
numeric cases at 65..150 rows for the fp8 head, 100 for the int8 head).
|
||||
|
||||
## Notes on the kernels
|
||||
|
||||
Three properties of the architecture are assumed throughout and not restated per kernel:
|
||||
|
||||
@@ -689,6 +689,10 @@ void r4d_hc_read_pin_prefill(int form);
|
||||
// wherever the cache rows are aligned to them), 1 the element-wise load the rule falls back to.
|
||||
// Bit-identical; r4d_selftest compares them and --perfmla times both.
|
||||
void r4d_mla_matrix_pin_form(int form);
|
||||
// Test hook: pins the MLA rows row's form. 0 is the launcher's rule (64 heads a workgroup, vector
|
||||
// key loads where aligned; the matrix row's kernel under 32 rows), 1 the element-wise key load
|
||||
// (bit-identical to 3), 2 32 heads a workgroup, 3 the rows kernel of the rule at any row count.
|
||||
void r4d_mla_rows_pin_form(int form);
|
||||
// Test hook: records the function each launch dispatches into `fns[0..cap)`, in order, until the
|
||||
// next call, and returns how many launches the previous recording saw (which may exceed its cap).
|
||||
// Null `fns` stops recording. r4d_selftest uses it to show that a pinned form dispatches a kernel
|
||||
|
||||
+255
-54
@@ -56,7 +56,7 @@ __device__ __forceinline__ uint64_t seed_of(const uint32_t* seed, int e) {
|
||||
|
||||
// ---------------------------------------------------------------------------- conv1d
|
||||
// An implicit GEMM, r4d_gen.hip's conv_igemm_kernel cut to one dimension: y[row][cout] = sum
|
||||
// over (tap, cin) of x[row + tap * dil - pad][cin] * w[cout][tap][cin], the weight stored
|
||||
// over (tap, cin) of x[row * stride + tap * dil - pad][cin] * w[cout][tap][cin], the weight stored
|
||||
// tap-major (r4d_layout.cpp relayouts PyTorch's [cout][cin][k] at load), so a 64-wide K tile is
|
||||
// eight 16-byte reads of input rows. A chunk outside its row's sequence reads zeros, which is the
|
||||
// per-sequence padding. Eight waves, BP rows x BC output channels a block, the next K tile's
|
||||
@@ -77,7 +77,8 @@ __global__ __launch_bounds__(256) void conv1d_igemm_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
|
||||
const uint16_t* __restrict__ bias, const uint16_t* __restrict__ res,
|
||||
const int* __restrict__ cu, uint16_t* __restrict__ y, int n_seq, int r_beg, int r_end,
|
||||
int cin, int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) {
|
||||
int cin, int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld,
|
||||
int res_ld, int act) {
|
||||
constexpr int BP = 2 * TP * 16, BC = 4 * TC * 16;
|
||||
constexpr int CPR = C1_BK / 8;
|
||||
constexpr int AL = BP * CPR / 256, WL = BC * CPR / 256;
|
||||
@@ -99,9 +100,9 @@ __global__ __launch_bounds__(256) void conv1d_igemm_kernel(
|
||||
const int m = p0 + r;
|
||||
a_ok[i] = m < r_end;
|
||||
a_row[i] = a_ok[i] ? m : r_beg;
|
||||
const int sq = seq_of(cu, n_seq, a_row[i]);
|
||||
a_s0[i] = cu[sq];
|
||||
a_s1[i] = cu[sq + 1];
|
||||
const int sq = seq_of(cu, n_seq, a_row[i] * stride * cdiv);
|
||||
a_s0[i] = cu[sq] / cdiv;
|
||||
a_s1[i] = cu[sq + 1] / cdiv;
|
||||
a_t[i] = e / cin;
|
||||
a_ci[i] = e % cin;
|
||||
adst[i] = sA + r * C1_PITCH + e;
|
||||
@@ -122,7 +123,7 @@ __global__ __launch_bounds__(256) void conv1d_igemm_kernel(
|
||||
const r4d_u32x4 zero = {0u, 0u, 0u, 0u};
|
||||
auto loadA = [&](int i) -> r4d_u32x4 {
|
||||
if (!a_ok[i] || a_t[i] >= k) return zero;
|
||||
const int ir = a_row[i] + a_t[i] * dil - pad;
|
||||
const int ir = a_row[i] * stride + a_t[i] * dil - pad;
|
||||
if (ir < a_s0[i] || ir >= a_s1[i]) return zero;
|
||||
return *(const r4d_u32x4*)(x + (size_t)ir * x_ld + a_ci[i]);
|
||||
};
|
||||
@@ -214,17 +215,18 @@ __global__ __launch_bounds__(kT) void conv1d_direct_kernel(
|
||||
const uint16_t* __restrict__ x, const uint16_t* __restrict__ w,
|
||||
const uint16_t* __restrict__ bias, const uint16_t* __restrict__ res,
|
||||
const int* __restrict__ cu, uint16_t* __restrict__ y, int n_seq, int r_beg, int r_end,
|
||||
int cin, int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) {
|
||||
int cin, int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld,
|
||||
int res_ld, int act) {
|
||||
const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x;
|
||||
const int64_t total = (int64_t)(r_end - r_beg) * cout;
|
||||
if (t >= total) return;
|
||||
const int co = (int)(t % cout);
|
||||
const int row = r_beg + (int)(t / cout);
|
||||
const int sq = seq_of(cu, n_seq, row);
|
||||
const int s0 = cu[sq], s1 = cu[sq + 1];
|
||||
const int sq = seq_of(cu, n_seq, row * stride * cdiv);
|
||||
const int s0 = cu[sq] / cdiv, s1 = cu[sq + 1] / cdiv;
|
||||
float acc = 0.0f;
|
||||
for (int kk = 0; kk < k; ++kk) {
|
||||
const int ir = row + kk * dil - pad;
|
||||
const int ir = row * stride + kk * dil - pad;
|
||||
if (ir < s0 || ir >= s1) continue;
|
||||
const uint16_t* xp = x + (size_t)ir * x_ld;
|
||||
const uint16_t* wp = w + ((size_t)co * k + kk) * cin;
|
||||
@@ -384,14 +386,14 @@ __global__ __launch_bounds__(256) void conv_t1d_kernel(
|
||||
// the output channels, its K the (tap, channel) pairs, channel innermost. A thread stages one K
|
||||
// column a slab and steps it sixteen at a time, so no K index is divided after the first.
|
||||
|
||||
// conv1d's A: output row m's tap t reads input row m + t dil - pad of m's own sequence, zero
|
||||
// outside it and past the last tap. As r4d_f32::RowsLoader, every load is issued at an address
|
||||
// clamped into x's first `r_end` rows and the zero selected after it.
|
||||
// conv1d's A: output row m's tap t reads input row m stride + t dil - pad of m's own sequence,
|
||||
// zero outside it and past the last tap. As r4d_f32::RowsLoader, every load is issued at an
|
||||
// address clamped into x's first `r_end` stride rows and the zero selected after it.
|
||||
template <int CNT>
|
||||
struct Conv1dRows {
|
||||
const float* x;
|
||||
const int* cu;
|
||||
int n_seq, r_end, cin, k, dil, pad, x_ld;
|
||||
int n_seq, r_end, cin, k, dil, pad, x_ld, stride, cdiv;
|
||||
int row[CNT], s0[CNT], s1[CNT];
|
||||
int t = 0, ci = 0;
|
||||
__device__ void init(int first_row, int kk) {
|
||||
@@ -399,9 +401,9 @@ struct Conv1dRows {
|
||||
for (int j = 0; j < CNT; ++j) {
|
||||
const int m = first_row + 16 * j;
|
||||
row[j] = m < r_end ? m : -1;
|
||||
const int sq = seq_of(cu, n_seq, m < r_end ? m : r_end - 1);
|
||||
s0[j] = cu[sq];
|
||||
s1[j] = cu[sq + 1];
|
||||
const int sq = seq_of(cu, n_seq, (m < r_end ? m : r_end - 1) * stride * cdiv);
|
||||
s0[j] = cu[sq] / cdiv;
|
||||
s1[j] = cu[sq + 1] / cdiv;
|
||||
}
|
||||
t = kk / cin;
|
||||
ci = kk % cin;
|
||||
@@ -409,9 +411,10 @@ struct Conv1dRows {
|
||||
__device__ void fetch(float (&v)[CNT]) const {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < CNT; ++j) {
|
||||
const int ir = row[j] + t * dil - pad;
|
||||
const int ir = row[j] * stride + t * dil - pad;
|
||||
const bool live = row[j] >= 0 && t < k && ir >= s0[j] && ir < s1[j];
|
||||
const int irc = ir < 0 ? 0 : (ir >= r_end ? r_end - 1 : ir);
|
||||
const int x_rows = r_end * stride;
|
||||
const int irc = ir < 0 ? 0 : (ir >= x_rows ? x_rows - 1 : ir);
|
||||
const float xv = x[(uint32_t)irc * (uint32_t)x_ld + (uint32_t)ci];
|
||||
v[j] = live ? xv : 0.0f;
|
||||
}
|
||||
@@ -428,12 +431,13 @@ template <int TN>
|
||||
__global__ __launch_bounds__(r4d_f32::kThr) void conv1d_f32_kernel(
|
||||
const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ bias,
|
||||
const float* res, const int* __restrict__ cu, float* y, int n_seq, int rows, int cin,
|
||||
int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) {
|
||||
int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld, int res_ld,
|
||||
int act) {
|
||||
constexpr int TM = 8, BM = 16 * TM, BN = 16 * TN;
|
||||
const int tid = threadIdx.x, tx = tid & 15, ty = tid >> 4;
|
||||
const int m0 = blockIdx.y * BM, n0 = blockIdx.x * BN;
|
||||
const int K = k * cin;
|
||||
Conv1dRows<TM> la{ x, cu, n_seq, rows, cin, k, dil, pad, x_ld };
|
||||
Conv1dRows<TM> la{ x, cu, n_seq, rows, cin, k, dil, pad, x_ld, stride, cdiv };
|
||||
r4d_f32::RowsLoader<TN> lw{ w, K, cout, K };
|
||||
la.init(m0 + ty, tx);
|
||||
lw.init(n0 + ty, tx);
|
||||
@@ -458,16 +462,17 @@ __global__ __launch_bounds__(r4d_f32::kThr) void conv1d_f32_kernel(
|
||||
__global__ __launch_bounds__(kT) void conv1d_f32_direct_kernel(
|
||||
const float* __restrict__ x, const float* __restrict__ w, const float* __restrict__ bias,
|
||||
const float* res, const int* __restrict__ cu, float* y, int n_seq, int rows, int cin,
|
||||
int cout, int k, int dil, int pad, int x_ld, int y_ld, int res_ld, int act) {
|
||||
int cout, int k, int dil, int pad, int stride, int cdiv, int x_ld, int y_ld, int res_ld,
|
||||
int act) {
|
||||
const int64_t t = (int64_t)blockIdx.x * kT + threadIdx.x;
|
||||
if (t >= (int64_t)rows * cout) return;
|
||||
const int co = (int)(t % cout);
|
||||
const int row = (int)(t / cout);
|
||||
const int sq = seq_of(cu, n_seq, row);
|
||||
const int s0 = cu[sq], s1 = cu[sq + 1];
|
||||
const int sq = seq_of(cu, n_seq, row * stride * cdiv);
|
||||
const int s0 = cu[sq] / cdiv, s1 = cu[sq + 1] / cdiv;
|
||||
float acc = 0.0f;
|
||||
for (int kk = 0; kk < k; ++kk) {
|
||||
const int ir = row + kk * dil - pad;
|
||||
const int ir = row * stride + kk * dil - pad;
|
||||
if (ir < s0 || ir >= s1) continue;
|
||||
const float* xp = x + (size_t)ir * x_ld;
|
||||
const float* wp = w + ((size_t)co * k + kk) * cin;
|
||||
@@ -622,6 +627,11 @@ __device__ uint32_t kth_key(F val, int j0, int j1, int kth, int* sh) {
|
||||
// [sup_lo, sup_hi) are optional. The kept values are divided by the temperature, as libref divides:
|
||||
// a multiply by its inverse rounds differently and can move a pick across a CDF boundary. A lane
|
||||
// with no candidate left writes -1.
|
||||
//
|
||||
// `top_p` < 1 cuts the kept list where the whole candidate set's cumulative probability passes it
|
||||
// (Fish Audio's draw). The normaliser is each thread's slice summed in index order, the slices
|
||||
// then summed by thread 0 in thread order: index order as libref sums, associated differently,
|
||||
// which in double moves a cut only for a cumulative within ~1e-16 of top_p.
|
||||
constexpr int kMaxK = 256;
|
||||
|
||||
__global__ __launch_bounds__(kT) void cfg_topk_kernel(
|
||||
@@ -629,9 +639,10 @@ __global__ __launch_bounds__(kT) void cfg_topk_kernel(
|
||||
const int* __restrict__ frame, int* __restrict__ ids, int V, int K, int rep, int cond_k,
|
||||
float cfg, float temp, uint64_t stream, const float* __restrict__ cfgs,
|
||||
const int* __restrict__ lane, int* __restrict__ hist, int n_hist, int sup_lo, int sup_hi,
|
||||
float pen) {
|
||||
float pen, float top_p) {
|
||||
__shared__ int sh[8];
|
||||
__shared__ int s_pre[kT];
|
||||
__shared__ double s_z[kT];
|
||||
__shared__ float s_g[kMaxK];
|
||||
__shared__ int s_i[kMaxK];
|
||||
__shared__ float s_e[kMaxK];
|
||||
@@ -721,8 +732,29 @@ __global__ __launch_bounds__(kT) void cfg_topk_kernel(
|
||||
s_pre[rank] = mi;
|
||||
}
|
||||
__syncthreads();
|
||||
if (top_p < 1.f) {
|
||||
const float m = s_e[0] / temp;
|
||||
double z = 0;
|
||||
for (int j = j0; j < j1; ++j)
|
||||
if (cand(j)) z += exp((double)(gval(j) / temp - m));
|
||||
s_z[tid] = z;
|
||||
}
|
||||
__syncthreads();
|
||||
if (tid == 0) {
|
||||
const float m = s_e[0] / temp;
|
||||
int kp = kk;
|
||||
if (top_p < 1.f) {
|
||||
double z = 0;
|
||||
for (int t = 0; t < kT; ++t) z += s_z[t];
|
||||
double cum = 0;
|
||||
kp = 1;
|
||||
for (int t = 0; t < kk; ++t) {
|
||||
cum += exp((double)(s_e[t] / temp - m)) / z;
|
||||
if (t > 0 && cum > (double)top_p) break;
|
||||
kp = t + 1;
|
||||
}
|
||||
}
|
||||
const int kk = kp;
|
||||
double tot = 0;
|
||||
for (int t = 0; t < kk; ++t) tot += exp((double)(s_e[t] / temp - m));
|
||||
const double u = (double)rad_philox_uniform_s(seed_of(seed, ln),
|
||||
@@ -761,15 +793,16 @@ __device__ __forceinline__ float ldtab(const void* t, int f32, size_t i) {
|
||||
__global__ __launch_bounds__(kT) void rvq_embed_kernel(
|
||||
const int* __restrict__ codes, int64_t kp, int64_t rp, const void* __restrict__ t0,
|
||||
int t0_f32, const void* __restrict__ t1, int t1_f32, void* __restrict__ y, int y_f32, int D,
|
||||
int K, int voc, int off0, int r0, int r1, float scale, int y_ld, int round1) {
|
||||
int K, int voc, int off0, int r0, int r1, float scale, int y_ld, int round1, int clamp) {
|
||||
const int r = blockIdx.x;
|
||||
const int c0 = codes[(size_t)r * rp] + off0;
|
||||
auto cl = [clamp](int c) { return clamp > 0 && c > clamp - 1 ? clamp - 1 : c; };
|
||||
const int c0 = cl(codes[(size_t)r * rp]) + off0;
|
||||
if (c0 < 0 || c0 >= r0) return;
|
||||
for (int d = threadIdx.x; d < D; d += kT) {
|
||||
const float e0 = ldtab(t0, t0_f32, (size_t)c0 * D + d);
|
||||
float acc = round1 ? e0 : 0.0f;
|
||||
for (int k = 1; k < K; ++k) {
|
||||
const int ck = codes[(size_t)k * kp + (size_t)r * rp] + (k - 1) * voc;
|
||||
const int ck = cl(codes[(size_t)k * kp + (size_t)r * rp]) + (k - 1) * voc;
|
||||
if (ck >= 0 && ck < r1) acc += ldtab(t1, t1_f32, (size_t)ck * D + d);
|
||||
}
|
||||
const float v = (round1 ? acc : bfr(e0 + bfr(acc))) * scale;
|
||||
@@ -778,6 +811,86 @@ __global__ __launch_bounds__(kT) void rvq_embed_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// One residual quantiser step (DAC's VectorQuantize), a workgroup a row of x. e = in_w x + in_b,
|
||||
// each of its `dim` sums split over the workgroup and reduced through LDS; each thread then scores
|
||||
// a strided run of the codebook against e normalised, every row normalised as it is read
|
||||
// (F.normalize's division), and the workgroup's argmax keeps the lower index on a tie; last the
|
||||
// chosen raw row's out-projection leaves x's row, rounded once. libref's arithmetic in another
|
||||
// summation order.
|
||||
constexpr int kVqMaxDim = 32;
|
||||
|
||||
__global__ __launch_bounds__(kT) void vq_encode_kernel(
|
||||
void* __restrict__ x, int x_f32, int x_ld, const void* __restrict__ iw, int iw_f32,
|
||||
const void* __restrict__ ib, int ib_f32, const void* __restrict__ cb, int cb_f32,
|
||||
const void* __restrict__ ow, int ow_f32, const void* __restrict__ ob, int ob_f32,
|
||||
int* __restrict__ codes, int64_t code_st, int n, int dim, int bins) {
|
||||
__shared__ float part[kT / 32][kVqMaxDim];
|
||||
__shared__ float e[kVqMaxDim], eh[kVqMaxDim];
|
||||
__shared__ float wbest[kT / 32];
|
||||
__shared__ int wcode[kT / 32];
|
||||
const int tid = threadIdx.x, wv = tid >> 5, ln = tid & 31;
|
||||
const size_t xb = (size_t)blockIdx.x * x_ld;
|
||||
auto ldx = [&](int d) {
|
||||
return x_f32 ? ((const float*)x)[xb + d] : bf2f(((const uint16_t*)x)[xb + d]);
|
||||
};
|
||||
for (int j = 0; j < dim; ++j) {
|
||||
float acc = 0.0f;
|
||||
for (int d = tid; d < n; d += kT) acc += ldtab(iw, iw_f32, (size_t)j * n + d) * ldx(d);
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) acc += __shfl_xor(acc, o, 32);
|
||||
if (ln == 0) part[wv][j] = acc;
|
||||
}
|
||||
__syncthreads();
|
||||
if (tid < dim) {
|
||||
float acc = 0.0f;
|
||||
for (int w = 0; w < kT / 32; ++w) acc += part[w][tid];
|
||||
e[tid] = acc + ldtab(ib, ib_f32, (size_t)tid);
|
||||
}
|
||||
__syncthreads();
|
||||
if (tid < dim) {
|
||||
float ss = 0.0f;
|
||||
for (int j = 0; j < dim; ++j) ss += e[j] * e[j];
|
||||
eh[tid] = e[tid] / fmaxf(sqrtf(ss), 1e-12f);
|
||||
}
|
||||
__syncthreads();
|
||||
// Each thread's best over its rows, ascending, so its first maximum is kept; INT_MAX none.
|
||||
float bs = -INFINITY;
|
||||
int bc = 0x7fffffff;
|
||||
for (int c = tid; c < bins; c += kT) {
|
||||
float ss = 0.0f;
|
||||
for (int j = 0; j < dim; ++j) {
|
||||
const float v = ldtab(cb, cb_f32, (size_t)c * dim + j);
|
||||
ss += v * v;
|
||||
}
|
||||
const float nrm = fmaxf(sqrtf(ss), 1e-12f);
|
||||
float dot = 0.0f;
|
||||
for (int j = 0; j < dim; ++j) dot += eh[j] * (ldtab(cb, cb_f32, (size_t)c * dim + j) / nrm);
|
||||
if (dot > bs) { bs = dot; bc = c; }
|
||||
}
|
||||
#pragma unroll
|
||||
for (int o = 16; o > 0; o >>= 1) {
|
||||
const float os = __shfl_xor(bs, o, 32);
|
||||
const int oc = __shfl_xor(bc, o, 32);
|
||||
if (os > bs || (os == bs && oc < bc)) { bs = os; bc = oc; }
|
||||
}
|
||||
if (ln == 0) { wbest[wv] = bs; wcode[wv] = bc; }
|
||||
__syncthreads();
|
||||
float fs = wbest[0];
|
||||
int fc = wcode[0];
|
||||
for (int w = 1; w < kT / 32; ++w)
|
||||
if (wbest[w] > fs || (wbest[w] == fs && wcode[w] < fc)) { fs = wbest[w]; fc = wcode[w]; }
|
||||
const int code = fc == 0x7fffffff ? 0 : fc; // no score above -inf: code 0, as libref
|
||||
if (tid == 0) codes[(size_t)blockIdx.x * code_st] = code;
|
||||
for (int d = tid; d < n; d += kT) {
|
||||
float q = 0.0f;
|
||||
for (int j = 0; j < dim; ++j)
|
||||
q += ldtab(ow, ow_f32, (size_t)d * dim + j) * ldtab(cb, cb_f32, (size_t)code * dim + j);
|
||||
const float v = ldx(d) - (q + ldtab(ob, ob_f32, (size_t)d));
|
||||
if (x_f32) ((float*)x)[xb + d] = v;
|
||||
else ((uint16_t*)x)[xb + d] = f32_to_bf16(v);
|
||||
}
|
||||
}
|
||||
|
||||
// dst[(lane n_codes + k) stride + frame - skip] = codes[k, rep i]; a thread a (lane, code). A lane
|
||||
// outside `status`, or a frame past `stride` or a lane past `dst`, stores nothing (libref refuses
|
||||
// the call).
|
||||
@@ -820,6 +933,32 @@ __global__ __launch_bounds__(kT) void frame_mix_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// Fish Audio's repetition-aware choice between two draws, a thread a lane (libref's
|
||||
// ref_ras_pick): the alternative where the first draw is in [lo, hi) and in the lane's window of
|
||||
// its last `W` picks, the pick then entering the window. A lane whose window lies outside `hist`
|
||||
// takes the first draw and keeps no window.
|
||||
__global__ __launch_bounds__(kT) void ras_pick_kernel(
|
||||
const int* __restrict__ first, const int* __restrict__ alt, const int* __restrict__ lane,
|
||||
int* __restrict__ hist, int* __restrict__ ids, int n, int W, int lo, int hi, int rep,
|
||||
int clear, long long n_hist) {
|
||||
const int i = blockIdx.x * kT + threadIdx.x;
|
||||
if (i >= n) return;
|
||||
const int f = first[rep * i];
|
||||
const long long L = lane[i];
|
||||
int pick = f;
|
||||
if (L >= 0 && (L + 1) * W <= n_hist) {
|
||||
int* h = hist + L * W;
|
||||
if (clear)
|
||||
for (int w = 0; w < W; ++w) h[w] = -1;
|
||||
if (f >= lo && f < hi)
|
||||
for (int w = 0; w < W; ++w)
|
||||
if (h[w] == f) { pick = alt[rep * i]; break; }
|
||||
for (int w = 0; w + 1 < W; ++w) h[w] = h[w + 1];
|
||||
h[W - 1] = pick;
|
||||
}
|
||||
for (int r = 0; r < rep; ++r) ids[rep * i + r] = pick;
|
||||
}
|
||||
|
||||
__global__ __launch_bounds__(kT) void end_status_kernel(
|
||||
const int* __restrict__ ids, const int* __restrict__ lane, int* __restrict__ status, int n,
|
||||
int rep, int end) {
|
||||
@@ -1079,24 +1218,26 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0);
|
||||
const long long k = r4d_geti_or(a, "k", 0), dil = r4d_geti_or(a, "dil", 1);
|
||||
const long long causal = r4d_geti_or(a, "causal", 0);
|
||||
const long long causal = r4d_geti_or(a, "causal", 0), st = r4d_geti_or(a, "stride", 1);
|
||||
const long long cd = r4d_geti_or(a, "cu_div", 1);
|
||||
const int act = conv1d_act(r4d_gets(a, "act"));
|
||||
if (act < 0) return R4D_NO(RAD_E_INVAL);
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 ||
|
||||
causal > 1)
|
||||
causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
long long rx = 0, ry = 0, rr = 0;
|
||||
const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry);
|
||||
const long long rl = res ? r4d_rows_pitch(res, cout, &rr) : 0;
|
||||
if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
const long long n_seq = r4d_numel(cu) - 1;
|
||||
if (n_seq <= 0 || ry <= 0 || rx < ry || (res && rr < ry) || r4d_numel(w) < cout * cin * k ||
|
||||
(b && r4d_numel(b) < cout))
|
||||
if (n_seq <= 0 || ry <= 0 || rx < ry * st || (res && rr < ry) ||
|
||||
r4d_numel(w) < cout * cin * k || (b && r4d_numel(b) < cout))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const uint16_t* bp = b ? (const uint16_t*)b->data : nullptr;
|
||||
/* Both kernels read input row row + tap * dil - pad: half the reach a side, or all of it on
|
||||
* the left for the causal form. */
|
||||
const int pad = (int)(causal ? dil * (k - 1) : dil * (k - 1) / 2);
|
||||
/* Both kernels read input row row * stride + tap * dil - pad: half the reach a side, or for
|
||||
* the causal form all of it on the left less the stride (the sequences' bounds whole
|
||||
* strides, as the op requires). */
|
||||
const int pad = (int)(causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2);
|
||||
const bool tiled = (cin % 8) == 0 && cout >= 16 && (xl % 8) == 0 &&
|
||||
((uintptr_t)x->data & 15) == 0 && ((uintptr_t)w->data & 15) == 0;
|
||||
const uint16_t* rp = res ? (const uint16_t*)res->data : nullptr;
|
||||
@@ -1109,8 +1250,8 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
|
||||
dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data,
|
||||
(const uint16_t*)w->data, bp, rp,
|
||||
(const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry,
|
||||
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl,
|
||||
(int)rl, act);
|
||||
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)cd,
|
||||
(int)xl, (int)yl, (int)rl, act);
|
||||
} else {
|
||||
constexpr int TP = 4, TC = 1, BP = 128, BC = 64;
|
||||
hipLaunchKernelGGL((conv1d_igemm_kernel<TP, TC>),
|
||||
@@ -1118,15 +1259,15 @@ extern "C" int r4d_rad_conv1d(const RadArgs* a, RadStream s) {
|
||||
dim3(256), 0, (hipStream_t)s, (const uint16_t*)x->data,
|
||||
(const uint16_t*)w->data, bp, rp,
|
||||
(const int*)cu->data, (uint16_t*)y->data, (int)n_seq, 0, (int)ry,
|
||||
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl,
|
||||
(int)rl, act);
|
||||
(int)cin, (int)cout, (int)k, (int)dil, pad, (int)st, (int)cd,
|
||||
(int)xl, (int)yl, (int)rl, act);
|
||||
}
|
||||
} else {
|
||||
hipLaunchKernelGGL(conv1d_direct_kernel, dim3(blocks_for(ry * cout)), dim3(kT), 0,
|
||||
(hipStream_t)s, (const uint16_t*)x->data, (const uint16_t*)w->data,
|
||||
bp, rp, (const int*)cu->data, (uint16_t*)y->data,
|
||||
(int)n_seq, 0, (int)ry, (int)cin, (int)cout, (int)k, (int)dil, pad,
|
||||
(int)xl, (int)yl, (int)rl, act);
|
||||
(int)st, (int)cd, (int)xl, (int)yl, (int)rl, act);
|
||||
}
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
@@ -1190,11 +1331,12 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) {
|
||||
if (!r4d_contig(w) || (b && !r4d_contig(b)) || !r4d_contig(cu)) return R4D_NO(RAD_E_STRIDE);
|
||||
const long long cin = r4d_geti_or(a, "cin", 0), cout = r4d_geti_or(a, "cout", 0);
|
||||
const long long k = r4d_geti_or(a, "k", 0), dil = r4d_geti_or(a, "dil", 1);
|
||||
const long long causal = r4d_geti_or(a, "causal", 0);
|
||||
const long long causal = r4d_geti_or(a, "causal", 0), st = r4d_geti_or(a, "stride", 1);
|
||||
const long long cd = r4d_geti_or(a, "cu_div", 1);
|
||||
const int act = conv1d_act(r4d_gets(a, "act"));
|
||||
if (act < 0) return R4D_NO(RAD_E_INVAL);
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 || causal < 0 ||
|
||||
causal > 1)
|
||||
causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) || cd < 1)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
long long rx = 0, ry = 0, rr = 0;
|
||||
const long long xl = r4d_rows_pitch(x, cin, &rx), yl = r4d_rows_pitch(y, cout, &ry);
|
||||
@@ -1202,18 +1344,19 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) {
|
||||
if (xl < 0 || yl < 0 || rl < 0) return R4D_NO(RAD_E_STRIDE);
|
||||
const long long n_seq = r4d_numel(cu) - 1;
|
||||
/* The tile's loaders index x and w with 32-bit element offsets. */
|
||||
if (n_seq <= 0 || ry <= 0 || rx < ry || (res && rr < ry) || r4d_numel(w) < cout * cin * k ||
|
||||
(b && r4d_numel(b) < cout) || ry > 0x7fffffffll || (ry + 127) / 128 > 65535 ||
|
||||
ry * xl >= (1ll << 32) || cout * cin * k >= (1ll << 32))
|
||||
if (n_seq <= 0 || ry <= 0 || rx < ry * st || (res && rr < ry) ||
|
||||
r4d_numel(w) < cout * cin * k || (b && r4d_numel(b) < cout) || ry > 0x7fffffffll ||
|
||||
(ry + 127) / 128 > 65535 || ry * st * xl >= (1ll << 32) || cout * cin * k >= (1ll << 32))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
const int pad = (int)(causal ? dil * (k - 1) : dil * (k - 1) / 2);
|
||||
const int pad = (int)(causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2);
|
||||
const float* bp = b ? (const float*)b->data : nullptr;
|
||||
const float* rp = res ? (const float*)res->data : nullptr;
|
||||
if (cout < 16) {
|
||||
hipLaunchKernelGGL(conv1d_f32_direct_kernel, dim3(blocks_for(ry * cout)), dim3(kT), 0,
|
||||
(hipStream_t)s, (const float*)x->data, (const float*)w->data, bp, rp,
|
||||
(const int*)cu->data, (float*)y->data, (int)n_seq, (int)ry, (int)cin,
|
||||
(int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, (int)rl, act);
|
||||
(int)cout, (int)k, (int)dil, pad, (int)st, (int)cd, (int)xl, (int)yl,
|
||||
(int)rl, act);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
const int tn = cout > 64 ? 8 : cout > 32 ? 4 : 2;
|
||||
@@ -1222,7 +1365,8 @@ extern "C" int r4d_rad_conv1d_f32(const RadArgs* a, RadStream s) {
|
||||
hipLaunchKernelGGL((conv1d_f32_kernel<TN>), grid, dim3(r4d_f32::kThr), 0, (hipStream_t)s, \
|
||||
(const float*)x->data, (const float*)w->data, bp, rp, \
|
||||
(const int*)cu->data, (float*)y->data, (int)n_seq, (int)ry, (int)cin, \
|
||||
(int)cout, (int)k, (int)dil, pad, (int)xl, (int)yl, (int)rl, act)
|
||||
(int)cout, (int)k, (int)dil, pad, (int)st, (int)cd, (int)xl, (int)yl, \
|
||||
(int)rl, act)
|
||||
if (tn == 8) C1F(8);
|
||||
else if (tn == 4) C1F(4);
|
||||
else C1F(2);
|
||||
@@ -1310,9 +1454,11 @@ extern "C" int r4d_rad_cfg_topk_sample(const RadArgs* a, RadStream s) {
|
||||
const long long sup_lo = r4d_geti_or(a, "sup_lo", 0), sup_hi = r4d_geti_or(a, "sup_hi", 0);
|
||||
const double cfg = r4d_getf(a, "cfg", 1.0), temp = r4d_getf(a, "temp", 1.0);
|
||||
const double pen = r4d_getf(a, "penalty", 1.0);
|
||||
/* As f32, as libref and libavx read it, so all three cut at the same value. */
|
||||
const float top_p = (float)r4d_getf(a, "top_p", 1.0);
|
||||
if (V <= 0 || K <= 0 || K > kMaxK || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V ||
|
||||
!(temp > 0) || V > (1 << 16) * kT || sup_lo < 0 || sup_hi < sup_lo || sup_hi > V ||
|
||||
!(pen > 0) || (!hist != !lane))
|
||||
!(pen > 0) || (!hist != !lane) || !(top_p >= 0.f))
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
long long rl = 0;
|
||||
const long long ll = r4d_rows_pitch(lg, V, &rl);
|
||||
@@ -1328,7 +1474,30 @@ extern "C" int r4d_rad_cfg_topk_sample(const RadArgs* a, RadStream s) {
|
||||
cfgs ? (const float*)cfgs->data : nullptr,
|
||||
lane ? (const int*)lane->data : nullptr, hist ? (int*)hist->data : nullptr,
|
||||
hist ? (int)(r4d_numel(hist) / V) : 0, (int)sup_lo, (int)sup_hi,
|
||||
(float)pen);
|
||||
(float)pen, top_p);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_ras_pick(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *first = r4d_opt(a, 0), *alt = r4d_opt(a, 1), *lane = r4d_opt(a, 2);
|
||||
const RadTensor *hist = r4d_opt(a, 3), *ids = r4d_opt(a, 4);
|
||||
if (!first || !alt || !lane || !hist || !ids) return R4D_NO(RAD_E_INVAL);
|
||||
if (!is_i32(first) || !is_i32(alt) || !is_i32(lane) || !is_i32(hist) || !is_i32(ids))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
if (!r4d_contig(first) || !r4d_contig(alt) || !r4d_contig(lane) || !r4d_contig(hist) ||
|
||||
!r4d_contig(ids))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
const long long W = r4d_geti_or(a, "win", 0), lo = r4d_geti_or(a, "lo", 0);
|
||||
const long long hi = r4d_geti_or(a, "hi", 0), rep = r4d_geti_or(a, "rep", 1);
|
||||
const long long clear = r4d_geti_or(a, "clear", 0);
|
||||
const long long n = r4d_numel(lane);
|
||||
if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 ||
|
||||
r4d_numel(first) < rep * n || r4d_numel(alt) < rep * n || r4d_numel(ids) < rep * n)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
hipLaunchKernelGGL(ras_pick_kernel, dim3(blocks_for(n)), dim3(kT), 0, (hipStream_t)s,
|
||||
(const int*)first->data, (const int*)alt->data, (const int*)lane->data,
|
||||
(int*)hist->data, (int*)ids->data, (int)n, (int)W, (int)lo, (int)hi,
|
||||
(int)rep, (int)clear, (long long)r4d_numel(hist));
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
@@ -1341,9 +1510,10 @@ extern "C" int r4d_rad_rvq_embed(const RadArgs* a, RadStream s) {
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long D = r4d_geti_or(a, "n_embd", 0), K = r4d_geti_or(a, "n_codes", 0);
|
||||
const long long voc = r4d_geti_or(a, "vocab", 0), off0 = r4d_geti_or(a, "off0", 0);
|
||||
const long long round1 = r4d_geti_or(a, "round", 0);
|
||||
const long long round1 = r4d_geti_or(a, "round", 0), clamp = r4d_geti_or(a, "clamp", 0);
|
||||
const double scale = r4d_getf(a, "scale", 1.0);
|
||||
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return R4D_NO(RAD_E_SHAPE);
|
||||
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1 || clamp < 0)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
long long ry = 0;
|
||||
const long long yl = r4d_rows_pitch(y, D, &ry);
|
||||
if (yl < 0 || !r4d_contig(t0) || !r4d_contig(t1)) return R4D_NO(RAD_E_STRIDE);
|
||||
@@ -1356,7 +1526,38 @@ extern "C" int r4d_rad_rvq_embed(const RadArgs* a, RadStream s) {
|
||||
t0->dtype == RAD_F32 ? 1 : 0, t1->data, t1->dtype == RAD_F32 ? 1 : 0,
|
||||
y->data, y->dtype == RAD_F32 ? 1 : 0, (int)D, (int)K, (int)voc, (int)off0,
|
||||
(int)(r4d_numel(t0) / D), (int)(r4d_numel(t1) / D), (float)scale, (int)yl,
|
||||
(int)round1);
|
||||
(int)round1, (int)clamp);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
extern "C" int r4d_rad_vq_encode(const RadArgs* a, RadStream s) {
|
||||
const RadTensor *x = r4d_opt(a, 0), *iw = r4d_opt(a, 1), *ib = r4d_opt(a, 2);
|
||||
const RadTensor *cb = r4d_opt(a, 3), *ow = r4d_opt(a, 4), *ob = r4d_opt(a, 5);
|
||||
const RadTensor* codes = r4d_opt(a, 6);
|
||||
if (!x || !iw || !ib || !cb || !ow || !ob || !codes) return R4D_NO(RAD_E_INVAL);
|
||||
auto bf_or_f32 = [](const RadTensor* t) { return t->dtype == RAD_BF16 || t->dtype == RAD_F32; };
|
||||
if (!is_i32(codes) || !bf_or_f32(x) || !bf_or_f32(iw) || !bf_or_f32(ib) || !bf_or_f32(cb) ||
|
||||
!bf_or_f32(ow) || !bf_or_f32(ob))
|
||||
return R4D_NO(RAD_E_DTYPE);
|
||||
const long long n = r4d_geti_or(a, "n", 0), dim = r4d_geti_or(a, "dim", 0);
|
||||
const long long bins = r4d_geti_or(a, "bins", 0);
|
||||
if (n <= 0 || dim <= 0 || dim > kVqMaxDim || bins <= 0) return R4D_NO(RAD_E_SHAPE);
|
||||
long long rx = 0;
|
||||
const long long xl = r4d_rows_pitch(x, n, &rx);
|
||||
if (xl < 0 || !r4d_contig(iw) || !r4d_contig(ib) || !r4d_contig(cb) || !r4d_contig(ow) ||
|
||||
!r4d_contig(ob))
|
||||
return R4D_NO(RAD_E_STRIDE);
|
||||
if (rx <= 0 || r4d_numel(codes) < rx || r4d_numel(iw) < dim * n || r4d_numel(ib) < dim ||
|
||||
r4d_numel(cb) < bins * dim || r4d_numel(ow) < n * dim || r4d_numel(ob) < n ||
|
||||
rx > 0x7fffffffll)
|
||||
return R4D_NO(RAD_E_SHAPE);
|
||||
/* A code at the operand's own stride: a row of a code-major plane, or a column of one. */
|
||||
const long long cs = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1;
|
||||
auto f32 = [](const RadTensor* t) { return t->dtype == RAD_F32 ? 1 : 0; };
|
||||
hipLaunchKernelGGL(vq_encode_kernel, dim3((unsigned)rx), dim3(kT), 0, (hipStream_t)s, x->data,
|
||||
f32(x), (int)xl, iw->data, f32(iw), ib->data, f32(ib), cb->data, f32(cb),
|
||||
ow->data, f32(ow), ob->data, f32(ob), (int*)codes->data, (int64_t)cs,
|
||||
(int)n, (int)dim, (int)bins);
|
||||
return st_of(hipGetLastError());
|
||||
}
|
||||
|
||||
|
||||
@@ -481,13 +481,15 @@ constexpr uint32_t lm_waves(uint32_t mt, uint32_t fkb) {
|
||||
}
|
||||
|
||||
// The body; lm_wmma_kernel and its chained form (RadKernelChainFn) wrap it.
|
||||
template <uint32_t MT, uint32_t FKB, bool I8>
|
||||
template <uint32_t MT, uint32_t FKB, bool I8, uint32_t MH = 1>
|
||||
__device__ __forceinline__ void lm_wmma_body(
|
||||
const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, uint32_t a_ld,
|
||||
float* __restrict__ C, uint32_t c_ld,
|
||||
uint32_t rows, uint32_t cols, uint32_t w_ld, uint32_t m_real) {
|
||||
constexpr uint32_t kFK = FKB * kBlock; /* K a staging round */
|
||||
constexpr uint32_t kRows = kDenseWaves * 16u; /* weight rows a workgroup covers */
|
||||
/* Weight rows a workgroup covers: 16 a wave, the waves split into MH halves along M that share
|
||||
* the staged tile (MH = 2: 64 rows, each half four 16-row activation tiles). */
|
||||
constexpr uint32_t kRows = kDenseWaves * 16u / MH;
|
||||
constexpr uint32_t kPitch = lds_pitch<kFK>(); /* BYTES a staged weight row */
|
||||
constexpr uint32_t kWUnits = kRows * (kFK / 16u); /* 16-byte staging units, weight */
|
||||
constexpr bool kPre = MT <= 3u; /* activation a K step ahead, below */
|
||||
@@ -497,12 +499,14 @@ __device__ __forceinline__ void lm_wmma_body(
|
||||
const uint32_t tid = (uint32_t)threadIdx.x;
|
||||
const uint32_t lane = tid & (kWave - 1u);
|
||||
const uint32_t wv = tid / kWave;
|
||||
const uint32_t wn = wv % (kDenseWaves / MH); /* this wave's 16 weight rows */
|
||||
const uint32_t mo = (wv / (kDenseWaves / MH)) * 16u * MT; /* its M half's first row */
|
||||
const uint32_t c = lane & 15u; /* this lane's weight row inside its 16-row tile */
|
||||
const uint32_t h = lane >> 4; /* which half of the K step */
|
||||
|
||||
for (uint32_t base = (uint32_t)blockIdx.x * kRows; base < rows; base += gridDim.x * kRows) {
|
||||
/* Clamped, not skipped: a tail workgroup recomputes the last row; the store drops it. */
|
||||
const uint32_t n = base + wv * 16u + c;
|
||||
const uint32_t n = base + wn * 16u + c;
|
||||
const uint32_t nc = (n < rows) ? n : (rows - 1u);
|
||||
const uint16_t* scl = (const uint16_t*)(W + (size_t)nc * w_ld + cols);
|
||||
|
||||
@@ -519,7 +523,7 @@ __device__ __forceinline__ void lm_wmma_body(
|
||||
auto aload = [&](uint32_t kf) {
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < MT; ++t) {
|
||||
const uint32_t m = t * 16u + c, mr = (m < m_real) ? m : (m_real - 1u);
|
||||
const uint32_t m = mo + t * 16u + c, mr = (m < m_real) ? m : (m_real - 1u);
|
||||
an[t] = *(const lm_s8v*)(A + (size_t)mr * a_ld + kt + kf + h * 8u);
|
||||
}
|
||||
};
|
||||
@@ -563,7 +567,7 @@ __device__ __forceinline__ void lm_wmma_body(
|
||||
for (uint32_t t = 0; t < MT; ++t) ac[t] = an[t];
|
||||
aload(kf + 16u < kFK ? kf + 16u : kf);
|
||||
}
|
||||
const i2v raw = frag<kFK>(s_w, wv * 16u, kf, lane);
|
||||
const i2v raw = frag<kFK>(s_w, wn * 16u, kf, lane);
|
||||
const lm_s8v bf =
|
||||
e4m3x8_to_bf16<I8>((uint32_t)raw[0], (uint32_t)raw[1]);
|
||||
/* The activation load is unconditional: a padding row re-reads the last real row and a select
|
||||
@@ -571,7 +575,7 @@ __device__ __forceinline__ void lm_wmma_body(
|
||||
* per K step). */
|
||||
#pragma unroll
|
||||
for (uint32_t t = 0; t < MT; ++t) {
|
||||
const uint32_t m = t * 16u + c;
|
||||
const uint32_t m = mo + t * 16u + c;
|
||||
[[maybe_unused]] const uint32_t mr = (m < m_real) ? m : (m_real - 1u);
|
||||
lm_s8v af;
|
||||
if constexpr (kPre) af = ac[t];
|
||||
@@ -594,7 +598,7 @@ __device__ __forceinline__ void lm_wmma_body(
|
||||
for (uint32_t t = 0; t < MT; ++t)
|
||||
#pragma unroll
|
||||
for (uint32_t j = 0; j < 8; ++j) {
|
||||
const uint32_t m = t * 16u + h * 8u + j;
|
||||
const uint32_t m = mo + t * 16u + h * 8u + j;
|
||||
if (m < m_real) C[(size_t)m * c_ld + n] = acc[t][j];
|
||||
}
|
||||
}
|
||||
@@ -603,16 +607,16 @@ __device__ __forceinline__ void lm_wmma_body(
|
||||
#define R4D_LMW_PARAMS const uint8_t* __restrict__ W, const uint16_t* __restrict__ A, \
|
||||
uint32_t a_ld, float* __restrict__ C, uint32_t c_ld, uint32_t rows, uint32_t cols, \
|
||||
uint32_t w_ld, uint32_t m_real
|
||||
template <uint32_t MT, uint32_t FKB, bool I8 = false>
|
||||
template <uint32_t MT, uint32_t FKB, bool I8 = false, uint32_t MH = 1>
|
||||
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void lm_wmma_kernel(
|
||||
R4D_LMW_PARAMS) {
|
||||
lm_wmma_body<MT, FKB, I8>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
|
||||
lm_wmma_body<MT, FKB, I8, MH>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
|
||||
}
|
||||
template <uint32_t MT, uint32_t FKB, bool I8 = false>
|
||||
template <uint32_t MT, uint32_t FKB, bool I8 = false, uint32_t MH = 1>
|
||||
__global__ __launch_bounds__(kDenseThreads) R4D_WAVES(lm_waves(MT, FKB)) void r4dchain_lm_wmma(
|
||||
R4D_LMW_PARAMS) {
|
||||
r4d_chain_wait();
|
||||
lm_wmma_body<MT, FKB, I8>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
|
||||
lm_wmma_body<MT, FKB, I8, MH>(W, A, a_ld, C, c_ld, rows, cols, w_ld, m_real);
|
||||
r4d_chain_done();
|
||||
}
|
||||
#undef R4D_LMW_PARAMS
|
||||
@@ -688,8 +692,8 @@ extern "C" int r4d_gemm_fp8a16_nt_mt(long a, long wq, long ws, long c,
|
||||
// wq [N][lm_row_bytes(K)] E4M3 codes, nkb bf16 scales, pad; `w_ld` BYTES a row (0 = that)
|
||||
// c [M][N] f32, `c_ld` elements a row (0 = N)
|
||||
//
|
||||
// The WMMA path takes M > 2 in chunks of 64 rows, each re-reading the weight; the matvec takes
|
||||
// M <= 2.
|
||||
// The WMMA path takes M > 2 in passes of up to 128 rows, each reading the weight once (past 64
|
||||
// rows in two M halves over one staged tile); the matvec takes M <= 2.
|
||||
//
|
||||
// This row must serve every M: all bands of one op read the same stored bytes, so a band falling
|
||||
// to another kernel (e.g. the bf16 projection) would misread the E4M3 codes.
|
||||
@@ -730,9 +734,31 @@ static int logits_gemm_8(long a, long wq, long c, int M, int K, int N, int a_ld,
|
||||
/* WMMA from M = 3, the matvec at or below. The tile's rate is nearly flat in M; the matvec is
|
||||
* marginally ahead at M = 2 and clearly at M = 1. Both read the same stored bytes. */
|
||||
if (M > 2) {
|
||||
/* Sixty-four rows per pass: four WMMA accumulator tiles (32 registers). */
|
||||
for (int m0 = 0; m0 < M; m0 += 64) {
|
||||
const int Mc = (M - m0) < 64 ? (M - m0) : 64;
|
||||
/* Passes of up to 128 rows. Up to 64, one tile of four WMMA accumulator tiles (32
|
||||
* registers) a wave; past 64, the same four a wave in two M halves over one staged weight
|
||||
* tile (MH = 2), so the head is read once a pass. */
|
||||
for (int m0 = 0; m0 < M; m0 += 128) {
|
||||
const int Mc = (M - m0) < 128 ? (M - m0) : 128;
|
||||
if (Mc > 64) {
|
||||
uint32_t fkb = lm_fkb_rule(4u);
|
||||
while (fkb > 1u && (cols % (fkb * kBlock)) != 0u) fkb >>= 1;
|
||||
const uint32_t per = kDenseWaves * 16u / 2u;
|
||||
const uint32_t blocks = std::min<uint32_t>(4096u, (rows + per - 1u) / per);
|
||||
const uint16_t* ac = (const uint16_t*)a + (size_t)m0 * a_ld;
|
||||
float* cc = (float*)c + (size_t)m0 * c_ld;
|
||||
if (fkb == 2u)
|
||||
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<4, 2, I8, 2> : lm_wmma_kernel<4, 2, I8, 2>),
|
||||
dim3(blocks), dim3(kDenseThreads), 0,
|
||||
(hipStream_t)stream, (const uint8_t*)wq, ac, (uint32_t)a_ld, cc,
|
||||
(uint32_t)c_ld, rows, cols, (uint32_t)w_ld, (uint32_t)Mc);
|
||||
else
|
||||
hipLaunchKernelGGL((chain ? r4dchain_lm_wmma<4, 1, I8, 2> : lm_wmma_kernel<4, 1, I8, 2>),
|
||||
dim3(blocks), dim3(kDenseThreads), 0,
|
||||
(hipStream_t)stream, (const uint8_t*)wq, ac, (uint32_t)a_ld, cc,
|
||||
(uint32_t)c_ld, rows, cols, (uint32_t)w_ld, (uint32_t)Mc);
|
||||
if (hipGetLastError() != hipSuccess) return -6;
|
||||
continue;
|
||||
}
|
||||
const uint32_t mt = (uint32_t)((Mc + 15) / 16);
|
||||
/* FKB = 4 would need kRows * (512 + 8) = 66560 bytes of LDS, over the 64 KiB limit. */
|
||||
uint32_t fkb = lm_fkb_rule(mt);
|
||||
|
||||
@@ -17,23 +17,19 @@
|
||||
// split the K slabs; each writes an fp32 partial [DKS][M][N], and the last to arrive (an
|
||||
// agent-scope counter per column block) sums them, with no second launch.
|
||||
//
|
||||
// Split, slab and load hint follow a rule tuned per cell on the 27B's per-rank shapes at
|
||||
// M = 8..128 (tunables `ks`, `bk`, `nt`; 0 selects the rule):
|
||||
// - split: the smallest power of two whose grid reaches 48 blocks at M <= 16, 56 at M <= 96 and
|
||||
// 40 above; for K >= 8192 keep doubling while a split has >= 24 128-wide slabs; never past
|
||||
// Split, slab and load hint follow a rule tuned on the 27B's and TranslateGemma's per-rank shapes
|
||||
// (tunables `ks`, `bk`, `nt`; 0 selects the rule):
|
||||
// - split up to 64 rows: the smallest power of two whose grid reaches 48 blocks at M <= 16 and
|
||||
// 56 above; for K >= 8192 keep doubling while a split has >= 24 128-wide slabs; never past
|
||||
// ks*M = 512, where partial traffic outweighs the gain.
|
||||
// - slab: 128, or 64 where LDS per block would cost a wide or deeply split grid its resident
|
||||
// blocks (see mxd_plan). A K not a multiple of 128 takes 64 (and a 2-way split widens to 4).
|
||||
// The rule was tuned when the weight was staged through LDS too, (16*DTM + 128) * (DBK+8)
|
||||
// bytes a block; the multi-fragment kernel now takes 2 * 16*DTM * (DBK+8).
|
||||
// - past 64 rows, re-tuned for the register kernel (r4d_selftest --perfmxd, warmed, every split
|
||||
// 1..8 at both slabs on the 27B's and TranslateGemma's per-rank shapes at 96 and 128 rows): the
|
||||
// 128-wide slab always (it never lost to 64), and a split only while every split keeps 16 slabs,
|
||||
// towards a 48-block grid or, at K >= 8192, regardless, up to ks*M = 1024 split rows. Against the
|
||||
// old rule at 96 / 128 rows: 5120 x 8704 116 / 160 -> 116 / 149 us (a split of 4), 6144 x 5120
|
||||
// 97 / 105 -> 87 / 109, 5120 x 3072 79 / 67 -> 60 / 69 (none), 17408 x 5120 187 / 215 -> 175 / 197
|
||||
// (the wide slab). A different split changes a split row's summation order, so bits move here.
|
||||
// - split past 64 rows: double only while every split keeps 16 128-wide slabs, towards a
|
||||
// 48-block grid or, at K >= 8192, regardless; never past ks*M = 1024.
|
||||
// - slab: 128, or 64 where LDS per block would cost a wide grid its resident blocks (see
|
||||
// mxd_plan); past 64 rows always 128. A K not a multiple of 128 takes 64 (and a 2-way split
|
||||
// widens to 4).
|
||||
// - non-temporal weight loads for weights of 4 MiB or more.
|
||||
// The split count sets a row's summation order, so a change to the rule moves the bits of the rows
|
||||
// it splits differently.
|
||||
//
|
||||
// No state is keyed on the stream, since a recorded pass may replay on another stream. The split
|
||||
// partial is the op's scratch (sized by the scratch hook, read+write, so overlapping ops get
|
||||
@@ -89,8 +85,8 @@ static __device__ __forceinline__ T mxd_ld(const T* p) {
|
||||
// The (row, 128) scale grid: thread t < ROWS owns row t, loads the next boundary's two scales a
|
||||
// boundary early and writes s_prev / s_next to LDS for the boundary's slab (the one-fragment kernel
|
||||
// at that slab, published by its staging barrier; the multi-fragment kernel a slab early into the
|
||||
// other half of its double buffer, published by the slab's closing barrier). A zero next block keeps the carried scale; after a zero block the carried scale is
|
||||
// looked up from the grid.
|
||||
// other half of its double buffer, published by the slab's closing barrier). A zero next block
|
||||
// keeps the carried scale; after a zero block the carried scale is looked up from the grid.
|
||||
static __device__ __forceinline__ float mxd_ratio(float ns, float np, const float* __restrict__ row,
|
||||
int kb) {
|
||||
return ns > 0.f ? (np > 0.f ? np : r4d_mxfp4_carried(row, kb - 2)) / ns : 1.f;
|
||||
@@ -206,15 +202,12 @@ constexpr int mxd_waves(int dbk, int dtm, bool ablk) {
|
||||
: 6;
|
||||
}
|
||||
|
||||
// The multi-fragment form (M > 16). A fragment-order weight word is the WMMA fragment's own register
|
||||
// (one dword a lane a k-step), so a wave loads its tile's words for a slab straight to registers and
|
||||
// folds them there, with no barrier between a wave and its weight; only the activation, shared by the
|
||||
// eight tiles, goes through LDS, double-buffered so a slab takes one barrier. The next slab's
|
||||
// activation and weight are loaded while this slab computes. The arithmetic -- the fold, the k-step
|
||||
// and slab order, the scale carry and the epilogue -- is the one the kernel staging the weight through
|
||||
// LDS had, so the bits are its own (checked byte for byte when it was replaced). r4d_selftest
|
||||
// --perfmxd, clocks warmed, LDS-staged -> registers: 17408 x 5120 at 64 rows 149 -> 129 us, at 96
|
||||
// 205 -> 159, at 128 245 -> 214; 5120 x 8704 at 128 169 -> 139; 6144 x 5120 at 128 121 -> 92.
|
||||
// The multi-fragment form (M > 16). A fragment-order weight word is the WMMA fragment's own
|
||||
// register (one dword a lane a k-step), so a wave loads its tile's words for a slab straight to
|
||||
// registers and folds them there, with no barrier between a wave and its weight. Only the
|
||||
// activation, shared by the eight tiles, goes through LDS, double-buffered so a slab takes one
|
||||
// barrier. The next slab's activation and weight are loaded while this slab computes. The fold,
|
||||
// k-step and slab order, scale carry and epilogue are the one-fragment form's (below).
|
||||
template <int DBK, int DKS, int DTM, bool NT, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_MXD_DWN * 32) R4D_WAVES(mxd_waves(DBK, DTM, ABLK))
|
||||
void r4d_gemm_mxfp4a8_decode_kernel(
|
||||
@@ -345,9 +338,10 @@ void r4d_gemm_mxfp4a8_decode_kernel(
|
||||
}
|
||||
|
||||
// The one-fragment form (M <= 16), every single-sequence verify step. Same tile, fold and split as
|
||||
// above, with the weight staged through LDS, plus: the next slab's A, codes and exponents are loaded
|
||||
// into registers while this slab computes, keeping loads in flight across barriers; a thread takes four adjacent slots (one 16 B
|
||||
// load); and each row's reference exponent is read once. Bit-identical to the kernel above.
|
||||
// above, with the weight staged through LDS, plus: the next slab's A, codes and exponents are
|
||||
// loaded into registers while this slab computes, keeping loads in flight across barriers; a thread
|
||||
// takes four adjacent slots (one 16 B load); and each row's reference exponent is read once.
|
||||
// Bit-identical to the kernel above.
|
||||
template <int DBK, int DKS, bool NT, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_MXD_DWN * 32) R4D_WAVES(DBK == 64 ? 16 : 12)
|
||||
void r4d_gemm_mxfp4a8_decode1_kernel(
|
||||
@@ -527,22 +521,22 @@ MxdPlan mxd_plan(int M, int K, int N, int KS, int BK, int NT) {
|
||||
MxdPlan p;
|
||||
int ks = 1;
|
||||
if (tm > 4) {
|
||||
// Past 64 rows (the register kernel; see the header): split only while every split keeps 16
|
||||
// 128-wide slabs, towards a 48-block grid, or at a deep K regardless.
|
||||
// Past 64 rows (see the header): split only while every split keeps 16 128-wide slabs, towards
|
||||
// a 48-block grid, or at a deep K regardless.
|
||||
const int slabs = K / 128;
|
||||
while (ks < R4D_MXD_MAX_KS && (nblk * ks < 48 || K >= 8192) && slabs / (2 * ks) >= 16 &&
|
||||
2 * ks * M <= 1024)
|
||||
ks <<= 1;
|
||||
} else {
|
||||
const int fill = M <= 16 ? 48 : (M <= 96 ? 56 : 40);
|
||||
const int fill = M <= 16 ? 48 : 56;
|
||||
while (ks < R4D_MXD_MAX_KS && nblk * ks < fill && 2 * ks * M <= 512) ks <<= 1;
|
||||
if (K >= 8192) // a deep K: a split of 24 or more slabs still waits on them
|
||||
while (ks < R4D_MXD_MAX_KS && (K / 128) / ks >= 24 && 2 * ks * M <= 512) ks <<= 1;
|
||||
}
|
||||
p.ks = KS > 0 ? KS : ks;
|
||||
// 64-wide slabs where LDS per block would cost resident blocks: DTM 4 unsplit on 110+ column
|
||||
// blocks, by the split the launch runs (a pin or a tuned point included), as before the register
|
||||
// kernel; past 64 rows the 128-wide slab always.
|
||||
// blocks, by the split the launch runs (a pin or a tuned point included); past 64 rows the
|
||||
// 128-wide slab always.
|
||||
const bool slab64 = tm == 4 && p.ks == 1 && nblk >= 110;
|
||||
p.bk = BK > 0 ? BK : (slab64 ? 64 : 128);
|
||||
p.nt = NT == 1 || (NT == 0 && (long)N * K / 2 >= (4l << 20));
|
||||
|
||||
@@ -13,15 +13,15 @@
|
||||
// Two forms, chosen from K alone so that a row's output bits do not depend on how many rows the
|
||||
// step carries (a verify step's first row is bit-identical to a plain decode of it):
|
||||
//
|
||||
// - K a multiple of 128: the WMMA form. One 16-column tile a block (two from 25 rows where N >= 4096,
|
||||
// K >= 3072 and the tile count is even), eight waves on
|
||||
// its K in chunks of one 128 block, and up to four 16-row tiles (M <= 64), each weight word
|
||||
// multiplied with every row tile's fragment once it is loaded. A lane loads its own B-fragment word of each k-step straight
|
||||
// from the fragment-order weight (the order is the fragment's), the rows sit in the A fragments
|
||||
// (rows >= M zero), and v_wmma_f32_16x16x16_fp8_fp8 multiplies. The per-(row, 128) activation scale is
|
||||
// applied to each chunk's partial. At M = 1 the WMMA does sixteen times the work it needs, which
|
||||
// costs nothing next to the weight stream; from M = 2 up it is what keeps the kernel on the
|
||||
// stream (the dot form pays a dot per row).
|
||||
// - K a multiple of 128: the WMMA form. One 16-column tile a block (two from 25 rows where
|
||||
// N >= 4096, K >= 3072 and the tile count is even), eight waves on its K in chunks of one 128
|
||||
// block, and up to four 16-row tiles (M <= 64), each weight word multiplied with every row
|
||||
// tile's fragment once it is loaded. A lane loads its own B-fragment word of each k-step
|
||||
// straight from the fragment-order weight (the order is the fragment's), the rows sit in the A
|
||||
// fragments (rows >= M zero), and v_wmma_f32_16x16x16_fp8_fp8 multiplies. The per-(row, 128)
|
||||
// activation scale is applied to each chunk's partial. At M = 1 the WMMA does sixteen times the
|
||||
// work it needs, which costs nothing next to the weight stream; from M = 2 up it is what keeps
|
||||
// the kernel on the stream (the dot form pays a dot per row).
|
||||
// - Otherwise (K = 64 mod 128): the dot form. A lane loads 16 bytes -- four columns' eight codes of
|
||||
// one k-step -- so a wave reads four k-steps, 512 contiguous bytes, from each of its TN tiles, and
|
||||
// multiplies with v_dot4_f32_fp8_fp8; the activation a lane reads (eight k of each row) serves its
|
||||
@@ -160,16 +160,11 @@ void r4d_gemm_mxfp4a8_gemv_kernel(
|
||||
// weight streams once whatever M is, and a row's sum is its tile's chain alone -- the same at every RT
|
||||
// and TN.
|
||||
//
|
||||
// TN: the activation is read per block, so one column tile a block reads all of it N/16 times (356 MB
|
||||
// from L2 at M = 64 on a 27B's 17408-row gate_up, against its 47 MB weight). Two tiles a block load
|
||||
// each activation fragment once for both. r4d_selftest --perfmxd, clocks warmed, TN 1 -> 2: 17408 x 5120
|
||||
// at 32 rows 125 -> 85 us, at 64 157 -> 122; 5120 x 8704 75 -> 56, 95 -> 75; 21504 x 5376 154 -> 111,
|
||||
// 183 -> 150; at 16 to 24 rows within a few percent either way. Four tiles spill past 32 rows.
|
||||
// Narrow or shallow weights lose with two (fewer blocks than the part has units, a short K a wave):
|
||||
// at 32..64 rows 1024 x 2048 +7..30 %, 2048 x 2048 +6..28 %, 2048 x 4096 +4..37 %, 6144 x 1536 at 32
|
||||
// rows +14..30 % (two repetitions each), so the launcher takes two from N 4096 and K 3072 only, where
|
||||
// every measured shape gained or held (4096 x 2048 even, 14336 x 4096 64 rows 120 -> 90 us,
|
||||
// 4096 x 7168 67 -> 55).
|
||||
// TN: the activation is read per block, so with one column tile a block it is read N/16 times
|
||||
// (356 MB from L2 at M = 64 on a 17408 x 5120 weight, against its 47 MB). Two tiles a block load
|
||||
// each activation fragment once for both. On narrow or shallow weights two tiles lose (fewer
|
||||
// blocks than the part has units, a short K a wave), so the launcher takes two only from N 4096
|
||||
// and K 3072, past 24 rows. Four tiles spill past 32 rows.
|
||||
template <bool ABLK, int RT, int TN = 1>
|
||||
__global__ __launch_bounds__(R4D_MXG_KW * 32)
|
||||
void r4d_gemm_mxfp4a8_gemvw_kernel(
|
||||
|
||||
@@ -24,13 +24,24 @@
|
||||
// 2^(Wref[n]-127) is applied in the epilogue (see r4d_gemm_mxfp4a8_nt_m64.hip).
|
||||
//
|
||||
// Tile: 8 waves as 4 (M) x 2 (N), each owning TM=4 x TN fragments, so a block covers BMF = 256
|
||||
// rows and BNF = 2*TN*16 columns. TN=4 halves the column-block count and only wins on long prompts
|
||||
// (crossover near M=2048 on a 17408x5120 weight), so tn=0 picks TN=4 from M >= 2048. The K slab is
|
||||
// 128 at TN=2 (64 if K % 128 != 0) and 64 at TN=4, which holds twice the accumulators.
|
||||
// rows and BNF = 2*TN*16 columns. TN=4 halves the column-block count and wins from M = 1024 on
|
||||
// (on gfx1201 at a 27B's per-rank weights, mixed below), so tn=0 picks TN=4 from M >= 1024. The K
|
||||
// slab is 128 at TN=2 (64 if K % 128 != 0) and 64 at TN=4, which holds twice the accumulators.
|
||||
// TN does not change an output's bits: each fragment runs the same WMMAs in the same K order.
|
||||
//
|
||||
// Barriers fence LDS only: __syncthreads() also drains the global load counter, and nothing in
|
||||
// global memory is shared between the waves, so the next slab's A loads stay in flight.
|
||||
//
|
||||
// The weight words and exponents a thread stages are loaded a slab ahead, into registers, right
|
||||
// after the staging barrier, so their DRAM round trip runs under the slab's WMMAs instead of in
|
||||
// front of the next unpack (+1 VGPR at TN=4). Loading the A fragments a slab ahead too (+38 VGPRs)
|
||||
// is slower.
|
||||
//
|
||||
// A thin last row of blocks (1..160 rows, under 1024 rows in all) runs a second kernel whose
|
||||
// blocks of that row skip the WMMAs of their padding fragments past M. Every other M runs the
|
||||
// plain kernel, whose body declares its own LDS: a guard inside the one kernel, or the body
|
||||
// taking the LDS by pointer, slows the full blocks.
|
||||
//
|
||||
// Staging is clamped, never predicated: a predicated load gets its own exec-mask region and the
|
||||
// compiler cannot carry a counted s_wait_loadcnt across the merge. Clamped loads (tile past M ->
|
||||
// last real tile, row past N -> last aligned group) issue back to back; the epilogue drops them.
|
||||
@@ -63,7 +74,7 @@
|
||||
#define R4D_MXT_NTHR (R4D_MXT_WM * R4D_MXT_WN * 32)
|
||||
#define R4D_MXT_BMF (R4D_MXT_WM * R4D_MXT_TM * 16)
|
||||
#define R4D_MXT_KUNIT 64 // the narrowest K slab, so K must be a multiple of it
|
||||
#define R4D_MXT_TN4_MIN_M 2048 // tn=0's crossover, see above
|
||||
#define R4D_MXT_TN4_MIN_M 1024 // tn=0's crossover, see above
|
||||
|
||||
typedef int mxt_v2i __attribute__((ext_vector_type(2)));
|
||||
typedef unsigned mxt_u2 __attribute__((ext_vector_type(2)));
|
||||
@@ -85,12 +96,16 @@ __global__ __launch_bounds__(256) void r4d_mxfp4a8_tile_a_kernel(
|
||||
*(mxt_u2*)(AT + o * 8) = v;
|
||||
}
|
||||
|
||||
template <int TN, int LBK, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
// The kernel's body. OWN: it declares its LDS arrays itself (the plain kernel); otherwise it takes
|
||||
// the caller's (the two-body kernel, one set for both bodies). PART: a block the M edge cuts,
|
||||
// which skips the WMMAs of its padding fragments past M.
|
||||
template <int TN, int LBK, bool ABLK, bool PART, bool OWN>
|
||||
__device__ __forceinline__ void r4d_gemm_mxfp4a8_tiled_body(
|
||||
const unsigned char* __restrict__ AT, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int as_rs, int ldws, int ldc) {
|
||||
int M, int K, int N, int as_rs, int ldws, int ldc, unsigned char* __restrict__ sW_in,
|
||||
unsigned int* __restrict__ sMag_in, float* __restrict__ sR_in) {
|
||||
constexpr int TM = R4D_MXT_TM, WN = R4D_MXT_WN, NTHR = R4D_MXT_NTHR, BMF = R4D_MXT_BMF;
|
||||
constexpr int NS = LBK / 16, STR = LBK + R4D_MXT_PAD, BNF = WN * TN * 16;
|
||||
constexpr int NTILES_T = BNF / 16, TOT_SLOTS = NTILES_T * NS * 32;
|
||||
@@ -98,15 +113,23 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
constexpr int WSLOTS = (TOT_SLOTS >= NTHR * 4) ? 4 : (TOT_SLOTS >= NTHR * 2 ? 2 : 1);
|
||||
constexpr int NW = TOT_SLOTS / (NTHR * WSLOTS);
|
||||
static_assert(NW * NTHR * WSLOTS == TOT_SLOTS, "the W tile must split evenly over the block");
|
||||
__shared__ unsigned char sW[BNF * STR];
|
||||
__shared__ unsigned int sMag[32];
|
||||
__shared__ float sR[ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
|
||||
__shared__ unsigned char sW_own[OWN ? BNF * STR : 1];
|
||||
__shared__ unsigned int sMag_own[OWN ? 32 : 1];
|
||||
__shared__ float sR_own[OWN && ABLK ? BMF : 1]; // ABLK: a boundary's ratio a row, then each row's final scale
|
||||
unsigned char* __restrict__ sW = OWN ? sW_own : sW_in;
|
||||
unsigned int* __restrict__ sMag = OWN ? sMag_own : sMag_in;
|
||||
float* __restrict__ sR = OWN ? sR_own : sR_in;
|
||||
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5;
|
||||
const int wm = wave / WN, wn = wave % WN;
|
||||
const int col = lane & 15, kb8 = (lane >> 4) * 8;
|
||||
const int m0 = blockIdx.y * BMF, n0 = blockIdx.x * BNF;
|
||||
const int ksteps = K / 16, Mt = (M + 15) >> 4;
|
||||
// PART: this wave's M fragments that hold a row below M, 0..TM and wave-uniform; the rest are
|
||||
// padding whose WMMAs are skipped (their rows are dropped at the store). Their A loads stay,
|
||||
// clamped, in the slab's one clause.
|
||||
const int live = PART ? __builtin_amdgcn_readfirstlane(min(TM, max(0, Mt - ((m0 >> 4) + wm * TM))))
|
||||
: TM;
|
||||
|
||||
if (tid < 32) sMag[tid] = (&kMxfp4Mag[0][0])[tid];
|
||||
|
||||
@@ -155,6 +178,31 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
const unsigned int* __restrict__ Wp = (const unsigned int*)W;
|
||||
lds_barrier(); // sMag
|
||||
|
||||
// The slab's weight words and exponents, loaded a slab ahead (the first one here).
|
||||
unsigned int wqn[NW][WSLOTS], wswn[NW];
|
||||
auto wload = [&](int k0) {
|
||||
const int kstep0 = k0 / 16;
|
||||
#pragma unroll
|
||||
for (int it = 0; it < NW; ++it) {
|
||||
const unsigned int* src =
|
||||
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
|
||||
const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP;
|
||||
if constexpr (WSLOTS == 4) {
|
||||
const mxt_u4 v = *(const mxt_u4*)src;
|
||||
wqn[it][0] = v[0]; wqn[it][1] = v[1]; wqn[it][2] = v[2]; wqn[it][3] = v[3];
|
||||
wswn[it] = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]);
|
||||
} else if constexpr (WSLOTS == 2) {
|
||||
const mxt_u2 v = *(const mxt_u2*)src;
|
||||
wqn[it][0] = v[0]; wqn[it][1] = v[1];
|
||||
wswn[it] = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]);
|
||||
} else {
|
||||
wqn[it][0] = *src;
|
||||
wswn[it] = Ws[(size_t)blk * ldws + wrc[it]];
|
||||
}
|
||||
}
|
||||
};
|
||||
wload(0);
|
||||
|
||||
for (int k0 = 0; k0 < K; k0 += LBK) {
|
||||
// ABLK: at a 128 boundary each row's ratio goes to LDS, published by the staging barrier below
|
||||
// (sR's previous readers finished before the last slab's closing barrier). A zero block keeps
|
||||
@@ -172,36 +220,20 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
for (int st = 0; st < NS; ++st)
|
||||
af[i][st] = *(const mxt_v2i*)(abase[i] +
|
||||
(aoff + (unsigned int)(k0 * 16) + (unsigned int)(st * 256)));
|
||||
// W slab -> LDS, folded to e4m3.
|
||||
const int kstep0 = k0 / 16;
|
||||
// W slab -> LDS, folded to e4m3, from the words loaded a slab ago.
|
||||
#pragma unroll
|
||||
for (int it = 0; it < NW; ++it) {
|
||||
const unsigned int* src =
|
||||
&Wp[((size_t)(wrc[it] >> 4) * ksteps + kstep0 + wkst[it]) * 32 + wlanec[it]];
|
||||
const int blk = (k0 + wkst[it] * 16) / R4D_MXFP4_GROUP;
|
||||
unsigned int wq[WSLOTS], wsw;
|
||||
if constexpr (WSLOTS == 4) {
|
||||
const mxt_u4 v = *(const mxt_u4*)src;
|
||||
wq[0] = v[0]; wq[1] = v[1]; wq[2] = v[2]; wq[3] = v[3];
|
||||
wsw = *(const unsigned int*)(Ws + (size_t)blk * ldws + wrc[it]);
|
||||
} else if constexpr (WSLOTS == 2) {
|
||||
const mxt_u2 v = *(const mxt_u2*)src;
|
||||
wq[0] = v[0]; wq[1] = v[1];
|
||||
wsw = *(const unsigned short*)(Ws + (size_t)blk * ldws + wrc[it]);
|
||||
} else {
|
||||
wq[0] = *src;
|
||||
wsw = Ws[(size_t)blk * ldws + wrc[it]];
|
||||
}
|
||||
#pragma unroll
|
||||
for (int q = 0; q < WSLOTS; ++q) {
|
||||
const int d = r4d_mxfp4_fold_d((int)((wref[it] >> (8 * q)) & 0xFF),
|
||||
(int)((wsw >> (8 * q)) & 0xFF));
|
||||
(int)((wswn[it] >> (8 * q)) & 0xFF));
|
||||
unsigned int lo, hi;
|
||||
r4d_mxfp4_unpack8_t(wq[q], sMag[d * 2], sMag[d * 2 + 1], &lo, &hi);
|
||||
r4d_mxfp4_unpack8_t(wqn[it][q], sMag[d * 2], sMag[d * 2 + 1], &lo, &hi);
|
||||
*(mxt_u2*)(&sW[(wrow[it] + q) * STR + wkloc[it]]) = mxt_u2{lo, hi};
|
||||
}
|
||||
}
|
||||
lds_barrier();
|
||||
if (k0 + LBK < K) wload(k0 + LBK); // the next slab's weight flies across this slab's WMMAs
|
||||
|
||||
if constexpr (ABLK) {
|
||||
// Re-express each row's partial sum in the new block's scale: one ratio a lane a row.
|
||||
@@ -235,11 +267,13 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
// loads above the first WMMA.
|
||||
__builtin_amdgcn_sched_barrier(0);
|
||||
#pragma unroll
|
||||
for (int i = 0; i < TM; ++i)
|
||||
for (int i = 0; i < TM; ++i) {
|
||||
if (PART && i >= live) break; // wave-uniform: padding fragments past M
|
||||
#pragma unroll
|
||||
for (int j = 0; j < TN; ++j)
|
||||
acc[i][j] = __builtin_amdgcn_wmma_f32_16x16x16_fp8_fp8_w32_gfx12(wf[j], af[i][step],
|
||||
acc[i][j]);
|
||||
}
|
||||
}
|
||||
lds_barrier();
|
||||
}
|
||||
@@ -287,6 +321,37 @@ __global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
}
|
||||
}
|
||||
|
||||
// The plain kernel: every block the unguarded body, over the body's own LDS.
|
||||
template <int TN, int LBK, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_kernel(
|
||||
const unsigned char* __restrict__ AT, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int as_rs, int ldws, int ldc) {
|
||||
r4d_gemm_mxfp4a8_tiled_body<TN, LBK, ABLK, false, true>(AT, As, W, Ws, Wref, C, M, K, N, as_rs, ldws,
|
||||
ldc, nullptr, nullptr, nullptr);
|
||||
}
|
||||
|
||||
// The two-body kernel, for a thin last row of blocks: a block of that row takes the guarded body,
|
||||
// every other block the unguarded one, uniform over the block, over one set of LDS arrays.
|
||||
template <int TN, int LBK, bool ABLK>
|
||||
__global__ __launch_bounds__(R4D_MXT_NTHR) void r4d_gemm_mxfp4a8_tiled_part_kernel(
|
||||
const unsigned char* __restrict__ AT, const float* __restrict__ As,
|
||||
const unsigned char* __restrict__ W, const unsigned char* __restrict__ Ws,
|
||||
const unsigned char* __restrict__ Wref, __hip_bfloat16* __restrict__ C,
|
||||
int M, int K, int N, int as_rs, int ldws, int ldc) {
|
||||
constexpr int BNF = R4D_MXT_WN * TN * 16, STR = LBK + R4D_MXT_PAD;
|
||||
__shared__ unsigned char sW[BNF * STR];
|
||||
__shared__ unsigned int sMag[32];
|
||||
__shared__ float sR[ABLK ? R4D_MXT_BMF : 1];
|
||||
if ((int)(blockIdx.y + 1) * R4D_MXT_BMF > M)
|
||||
r4d_gemm_mxfp4a8_tiled_body<TN, LBK, ABLK, true, false>(AT, As, W, Ws, Wref, C, M, K, N, as_rs,
|
||||
ldws, ldc, sW, sMag, sR);
|
||||
else
|
||||
r4d_gemm_mxfp4a8_tiled_body<TN, LBK, ABLK, false, false>(AT, As, W, Ws, Wref, C, M, K, N, as_rs,
|
||||
ldws, ldc, sW, sMag, sR);
|
||||
}
|
||||
|
||||
extern "C" int r4d_gemm_mxfp4a8_tiled_group(void) { return R4D_MXFP4_GROUP; }
|
||||
|
||||
extern "C" long r4d_mxfp4a8_tile_a_bytes(int M, int K) {
|
||||
@@ -332,9 +397,18 @@ extern "C" void r4d_gemm_mxfp4a8_tiled(long at, long ascale, long wq, long ws, l
|
||||
auto Rp = (const unsigned char*)wref;
|
||||
auto Cp = (__hip_bfloat16*)c;
|
||||
hipStream_t st = (hipStream_t)stream;
|
||||
#define MXT_LAUNCH(TNv, LBKv, ABv) \
|
||||
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, Sp, \
|
||||
Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc)
|
||||
// The two-body kernel only for a thin last row of blocks (1..160 rows) under 1024 rows; see the
|
||||
// header.
|
||||
const int rem = M % R4D_MXT_BMF;
|
||||
const bool part = rem > 0 && rem <= 160 && M < 1024;
|
||||
#define MXT_LAUNCH(TNv, LBKv, ABv) do { \
|
||||
if (part) \
|
||||
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_part_kernel<TNv, LBKv, ABv>), grid, block, 0, st, \
|
||||
Ap, Sp, Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc); \
|
||||
else \
|
||||
hipLaunchKernelGGL((r4d_gemm_mxfp4a8_tiled_kernel<TNv, LBKv, ABv>), grid, block, 0, st, Ap, \
|
||||
Sp, Wp, Zp, Rp, Cp, M, K, N, as_rs, ldws, ldc); \
|
||||
} while (0)
|
||||
if (TN == 4) { if (ablk) MXT_LAUNCH(4, 64, true); else MXT_LAUNCH(4, 64, false); }
|
||||
else if (wide_slab) { if (ablk) MXT_LAUNCH(2, 128, true); else MXT_LAUNCH(2, 128, false); }
|
||||
else { if (ablk) MXT_LAUNCH(2, 64, true); else MXT_LAUNCH(2, 64, false); }
|
||||
|
||||
@@ -537,6 +537,178 @@ __global__ __launch_bounds__(128) void attend_matrix(const uint16_t* q, const ui
|
||||
atomicAdd(&g_mla_stats[2], (unsigned long long)(raster + 15) / 16);
|
||||
}
|
||||
}
|
||||
/* ROWS gives a workgroup one query row and HG groups of sixteen heads, four waves a group, so a
|
||||
* key chunk is loaded once for 16*HG heads instead of the head-tiled row's sixteen. GLM's prefill
|
||||
* splits attention by rows, one rank holding all 64 heads of its rows; that is what this serves.
|
||||
*
|
||||
* Scores are S^T = K Q^T: tokens are the matrix rows and heads the columns, so a head is a lane
|
||||
* and its running maximum and denominator stay in registers. Each wave of a group takes a quarter
|
||||
* of the latent dimension; the four partial dot products meet in LDS and every wave of the group
|
||||
* adds them in the same order, so all four hold identical scores and statistics. The
|
||||
* probabilities become the second product's B operand with one permlanex16 swap, and each wave
|
||||
* accumulates O^T for its quarter of the latent columns, the keys read transposed from the tile.
|
||||
* The next chunk's keys are fetched into registers while the current one is multiplied, so a
|
||||
* chunk costs two barriers. */
|
||||
constexpr int kRowsPitch = 520;
|
||||
template <int HG, bool WIDE>
|
||||
__global__ __launch_bounds__(HG * 128) void attend_rows(const uint16_t* q, const uint16_t* kv,
|
||||
const int* bt, const int* len,
|
||||
uint16_t* out, float* scratch, Meta m) {
|
||||
constexpr int NT = HG * 128, LOADS = 16 * 64 / NT;
|
||||
static_assert(LOADS * NT == 16 * 64 && LOADS <= 32, "a chunk's 16-byte pieces over the group");
|
||||
__shared__ __align__(16) uint16_t keys[2][16 * kRowsPitch];
|
||||
__shared__ __align__(32) float partial[HG * 4][32 * 8];
|
||||
__shared__ int visible[2][16];
|
||||
const int tid = threadIdx.x, lane = tid & 31, wave = tid >> 5, quarter = wave & 3,
|
||||
group = wave >> 2, r = blockIdx.x, split = blockIdx.z;
|
||||
const int head = blockIdx.y * 16 * HG + group * 16 + (lane & 15);
|
||||
const int live = min(max(len[(long)r * m.lp], 0), m.blocks * m.bs);
|
||||
const int begin = (int)((long)live * split / m.splits),
|
||||
end = (int)((long)live * (split + 1) / m.splits);
|
||||
v8bf query[8];
|
||||
{
|
||||
const uint16_t* qp =
|
||||
q + (long)r * m.qr + (long)head * m.qh + quarter * 128 + 4 * (lane >> 4);
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 8; ++s) {
|
||||
union {
|
||||
uint16_t h[8];
|
||||
v8bf f;
|
||||
} u;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 4; ++e) {
|
||||
u.h[e] = qp[s * 16 + e];
|
||||
u.h[4 + e] = qp[s * 16 + 8 + e];
|
||||
}
|
||||
query[s] = u.f;
|
||||
}
|
||||
}
|
||||
uint4 staged[LOADS];
|
||||
unsigned staged_ok = 0;
|
||||
auto fetch = [&](int start) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < LOADS; ++j) {
|
||||
const int flat = tid + j * NT, token = start + (flat >> 6), piece = flat & 63;
|
||||
const int page = token < end ? bt[(long)r * m.bp + (token / m.bs) * m.bc] : -1;
|
||||
const bool ok = page >= 0 && page < m.pages;
|
||||
const long at = ok ? (long)page * m.kp + (token % m.bs) * m.kt + piece * 8 : 0;
|
||||
if constexpr (WIDE) {
|
||||
staged[j] = *(const uint4*)(kv + at);
|
||||
if (!ok) staged[j] = make_uint4(0, 0, 0, 0);
|
||||
} else {
|
||||
uint32_t w[4];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i)
|
||||
w[i] = ok ? (uint32_t)kv[at + 2 * i] | (uint32_t)kv[at + 2 * i + 1] << 16 : 0u;
|
||||
staged[j] = make_uint4(w[0], w[1], w[2], w[3]);
|
||||
}
|
||||
staged_ok = ok ? staged_ok | 1u << j : staged_ok & ~(1u << j);
|
||||
}
|
||||
};
|
||||
auto stash = [&](int b) {
|
||||
#pragma unroll
|
||||
for (int j = 0; j < LOADS; ++j) {
|
||||
const int flat = tid + j * NT, token = flat >> 6, piece = flat & 63;
|
||||
*(uint4*)(keys[b] + token * kRowsPitch + piece * 8) = staged[j];
|
||||
if (!piece) visible[b][token] = (int)(staged_ok >> j & 1u);
|
||||
}
|
||||
};
|
||||
v8f value[8];
|
||||
#pragma unroll
|
||||
for (int mt = 0; mt < 8; ++mt) value[mt] = (v8f){ 0 };
|
||||
float run_max = -INFINITY, run_den = 0;
|
||||
fetch(begin);
|
||||
stash(0);
|
||||
__syncthreads();
|
||||
int buf = 0;
|
||||
for (int start = begin; start < end; start += 16) {
|
||||
const bool more = start + 16 < end;
|
||||
if (more) fetch(start + 16);
|
||||
const uint16_t* tile = keys[buf];
|
||||
v8f dot = { 0 };
|
||||
#pragma unroll
|
||||
for (int s = 0; s < 8; ++s)
|
||||
dot = mma(frag(tile, kRowsPitch, 0, quarter * 128 + s * 16, lane), query[s], dot);
|
||||
*(v8f*)&partial[wave][lane * 8] = dot;
|
||||
__syncthreads();
|
||||
v8f score = *(const v8f*)&partial[group * 4][lane * 8];
|
||||
#pragma unroll
|
||||
for (int k = 1; k < 4; ++k) score += *(const v8f*)&partial[group * 4 + k][lane * 8];
|
||||
float chunk_max = -INFINITY;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
score[e] = visible[buf][8 * (lane >> 4) + e] ? score[e] * m.scale : -INFINITY;
|
||||
chunk_max = fmaxf(chunk_max, score[e]);
|
||||
}
|
||||
chunk_max = fmaxf(chunk_max, swap16(chunk_max));
|
||||
const float next_max = fmaxf(run_max, chunk_max);
|
||||
const float alpha = isfinite(next_max) ? expf(run_max - next_max) : 1;
|
||||
float p[8], sum = 0;
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
p[e] = isfinite(score[e]) ? expf(score[e] - next_max) : 0;
|
||||
sum += p[e];
|
||||
}
|
||||
/* Both halves add tokens 0-7 before 8-15, so the sixteen lanes of a head agree. */
|
||||
const float other = swap16(sum);
|
||||
run_den = run_den * alpha + (lane < 16 ? sum + other : other + sum);
|
||||
run_max = next_max;
|
||||
/* A B fragment's lane holds its head's tokens 0-3 and 8-11 (lanes 0-15) or 4-7 and 12-15
|
||||
* (16-31); a score lane holds 0-7 or 8-15. Each half sends the other the four it needs. */
|
||||
uint32_t hi[4], lo[4];
|
||||
#pragma unroll
|
||||
for (int i = 0; i < 4; ++i) {
|
||||
const uint16_t h0 = f32_to_bf16(p[2 * i]), h1 = f32_to_bf16(p[2 * i + 1]);
|
||||
hi[i] = (uint32_t)h0 | (uint32_t)h1 << 16;
|
||||
lo[i] = (uint32_t)f32_to_bf16(p[2 * i] - bf16_to_f32(h0)) |
|
||||
(uint32_t)f32_to_bf16(p[2 * i + 1] - bf16_to_f32(h1)) << 16;
|
||||
}
|
||||
const bool low = lane < 16;
|
||||
const uint32_t hx0 = r4d_xor_lane_u32<16>(low ? hi[2] : hi[0]),
|
||||
hx1 = r4d_xor_lane_u32<16>(low ? hi[3] : hi[1]),
|
||||
lx0 = r4d_xor_lane_u32<16>(low ? lo[2] : lo[0]),
|
||||
lx1 = r4d_xor_lane_u32<16>(low ? lo[3] : lo[1]);
|
||||
union {
|
||||
uint32_t w[4];
|
||||
v8bf f;
|
||||
} ph, pl;
|
||||
ph.w[0] = low ? hi[0] : hx0;
|
||||
ph.w[1] = low ? hi[1] : hx1;
|
||||
ph.w[2] = low ? hx0 : hi[2];
|
||||
ph.w[3] = low ? hx1 : hi[3];
|
||||
pl.w[0] = low ? lo[0] : lx0;
|
||||
pl.w[1] = low ? lo[1] : lx1;
|
||||
pl.w[2] = low ? lx0 : lo[2];
|
||||
pl.w[3] = low ? lx1 : lo[3];
|
||||
#pragma unroll
|
||||
for (int mt = 0; mt < 8; ++mt) {
|
||||
const auto v = fragT(tile, kRowsPitch, quarter * 128 + mt * 16, 0, lane);
|
||||
value[mt] *= alpha;
|
||||
value[mt] = mma(v, ph.f, value[mt]);
|
||||
value[mt] = mma(v, pl.f, value[mt]);
|
||||
}
|
||||
if (more) stash(buf ^ 1);
|
||||
__syncthreads();
|
||||
buf ^= 1;
|
||||
}
|
||||
#pragma unroll
|
||||
for (int mt = 0; mt < 8; ++mt)
|
||||
#pragma unroll
|
||||
for (int e = 0; e < 8; ++e) {
|
||||
const int col = quarter * 128 + mt * 16 + 8 * (lane >> 4) + e;
|
||||
if (m.splits == 1)
|
||||
out[(long)r * m.orr + (long)head * m.oh + col] =
|
||||
f32_to_bf16(run_den > 0 ? value[mt][e] / run_den : 0);
|
||||
else
|
||||
scratch[(((long)r * m.heads + head) * m.splits + split) * PART + col] =
|
||||
value[mt][e];
|
||||
}
|
||||
if (m.splits > 1 && !quarter && lane < 16) {
|
||||
float* dst = scratch + (((long)r * m.heads + head) * m.splits + split) * PART;
|
||||
dst[D] = run_max;
|
||||
dst[D + 1] = run_den;
|
||||
}
|
||||
}
|
||||
/* Read once: the launch path asks on every matrix launch. */
|
||||
bool stats_on() {
|
||||
static const bool on = [] {
|
||||
@@ -647,6 +819,70 @@ int body(const RadArgs* a, RadStream stream) {
|
||||
if (rc == RAD_OK && stats) report_stats(stream);
|
||||
return rc;
|
||||
}
|
||||
/* r4d_mla_rows_pin_form: 0 is the launcher's rule (64 heads a workgroup, vector key loads where
|
||||
* the cache is aligned, the matrix row's kernel under kRowsMin rows), 1 the element-wise key load,
|
||||
* 2 thirty-two heads a workgroup, 3 the rule's rows kernel at any row count, 4 the matrix row's
|
||||
* kernel at every row count. The pin is a test hook (r4d_selftest, r4d_emu); nothing else sets
|
||||
* it. */
|
||||
int g_mla_rows_form = 0;
|
||||
/* Under it, a decode step's rows at one rank, a workgroup a row leaves the card mostly idle, and
|
||||
* the matrix row's four tiles a row and its splits are faster (r4d_selftest --case
|
||||
* mla_attn_rows_bf16, M 7: 0.5x). */
|
||||
constexpr long kRowsMin = 32;
|
||||
int rows_body(const RadArgs* a, RadStream stream) {
|
||||
if (!a || a->n_t < 5) return RAD_E_INVAL;
|
||||
const auto &q = a->t[0], &kv = a->t[1], &bt = a->t[2], &len = a->t[3], &o = a->t[4];
|
||||
if (q.dtype != RAD_BF16 || kv.dtype != RAD_BF16 || o.dtype != RAD_BF16 || bt.dtype != RAD_I32 ||
|
||||
len.dtype != RAD_I32)
|
||||
return RAD_E_DTYPE;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
if (!a->t[i].data) return RAD_E_INVAL;
|
||||
const long heads = r4d_geti_or(a, "heads", 0), bs = r4d_geti_or(a, "block_size", 0);
|
||||
const float scale = (float)r4d_getf(a, "scale", 0);
|
||||
if (r4d_geti_or(a, "latent_dim", 0) != D || heads < 1 || heads > 64 || bs < 1 || bs > 256 ||
|
||||
!std::isfinite(scale) || scale <= 0 || q.rank != 3 || q.shape[0] < 1 ||
|
||||
q.shape[0] > 65535 || q.shape[1] != heads || q.shape[2] != D || q.stride[2] != 1 ||
|
||||
q.stride[1] < D || q.stride[0] < heads * q.stride[1] || kv.rank != 4 || kv.shape[0] < 1 ||
|
||||
kv.shape[0] > INT_MAX || kv.shape[1] != 1 || kv.shape[2] != bs || kv.shape[3] != D ||
|
||||
kv.stride[3] != 1 || kv.stride[2] < D || kv.stride[0] < bs * kv.stride[2] || bt.rank != 2 ||
|
||||
bt.shape[0] != q.shape[0] || bt.shape[1] < 1 || bt.shape[1] > INT_MAX / bs ||
|
||||
bt.stride[1] < 1 || bt.stride[0] < bt.shape[1] * bt.stride[1] || len.rank != 1 ||
|
||||
len.shape[0] != q.shape[0] || len.stride[0] < 1 || o.rank != 3 ||
|
||||
o.shape[0] != q.shape[0] || o.shape[1] != heads || o.shape[2] != D || o.stride[2] != 1 ||
|
||||
o.stride[1] < D || o.stride[0] < heads * o.stride[1])
|
||||
return RAD_E_SHAPE;
|
||||
if (heads % 32) return RAD_E_UNSUPPORTED;
|
||||
const int form = g_mla_rows_form;
|
||||
if (form == 4 || (!form && q.shape[0] < kRowsMin)) return body<true>(a, stream);
|
||||
const int group_heads = heads % 64 || form == 2 ? 32 : 64;
|
||||
const long rows = q.shape[0], groups = heads / group_heads, jobs = rows * groups;
|
||||
/* Short batches split the history until 64 workgroups run, two to each of the R9700's 32
|
||||
* WGPs, as far as 16-token chunks and the scratch's 2048 partials allow. */
|
||||
int splits = (int)std::min(64l, (64 + jobs - 1) / jobs);
|
||||
splits = (int)std::max(1l, std::min((long)splits, (bt.shape[1] * bs + 15) / 16));
|
||||
splits = (int)std::max(1l, std::min((long)splits, 2048 / (rows * heads)));
|
||||
if (!a->scratch || a->scratch_bytes < matrix_scratch_bytes) splits = 1;
|
||||
const bool wide = form != 1 && !((uintptr_t)kv.data & 15) && !(kv.stride[0] % 8) &&
|
||||
!(kv.stride[2] % 8);
|
||||
Meta m{ q.stride[0], q.stride[1], kv.stride[0], kv.stride[2],
|
||||
bt.stride[0], bt.stride[1], len.stride[0], o.stride[0],
|
||||
o.stride[1], (int)q.shape[0], (int)heads, (int)bt.shape[1],
|
||||
(int)bs, (int)kv.shape[0], splits, scale };
|
||||
#define ROWS_EMIT(HG, W) \
|
||||
R4D_EMIT(stream, (attend_rows<HG, W>), dim3(m.rows, (unsigned)groups, m.splits), \
|
||||
dim3(HG * 128), 0, (const uint16_t*)q.data, (const uint16_t*)kv.data, \
|
||||
(const int*)bt.data, (const int*)len.data, (uint16_t*)o.data, (float*)a->scratch, m)
|
||||
int rc;
|
||||
if (group_heads == 64)
|
||||
rc = wide ? ROWS_EMIT(4, true) : ROWS_EMIT(4, false);
|
||||
else
|
||||
rc = wide ? ROWS_EMIT(2, true) : ROWS_EMIT(2, false);
|
||||
#undef ROWS_EMIT
|
||||
if (rc == RAD_OK && splits > 1)
|
||||
rc = R4D_EMIT(stream, merge, dim3(m.rows, (m.heads + 3) / 4), dim3(128), 0,
|
||||
(const float*)a->scratch, (uint16_t*)o.data, m);
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) {
|
||||
return body<false>(a, stream);
|
||||
@@ -654,12 +890,16 @@ extern "C" int r4d_rad_mla_attn(const RadArgs* a, RadStream stream) {
|
||||
extern "C" int r4d_rad_mla_attn_matrix(const RadArgs* a, RadStream stream) {
|
||||
return body<true>(a, stream);
|
||||
}
|
||||
extern "C" int r4d_rad_mla_attn_rows(const RadArgs* a, RadStream stream) {
|
||||
return rows_body(a, stream);
|
||||
}
|
||||
extern "C" int r4d_rad_mla_project(const RadArgs* a, RadStream stream) {
|
||||
return project_body(a, stream);
|
||||
}
|
||||
extern "C" int64_t r4d_rad_mla_attn_scratch(const RadArgs*) { return scratch_bytes; }
|
||||
extern "C" int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*) { return matrix_scratch_bytes; }
|
||||
extern "C" void r4d_mla_matrix_pin_form(int form) { g_mla_matrix_form = form; }
|
||||
extern "C" void r4d_mla_rows_pin_form(int form) { g_mla_rows_form = form; }
|
||||
/* Test hook: the current device's RADIANCE_MLA_CONFLICT_STATS counters since the last call (passes,
|
||||
* second passes, raster chunks), then zeroed. */
|
||||
extern "C" void r4d_mla_matrix_stats(unsigned long long* out) {
|
||||
|
||||
@@ -234,8 +234,10 @@ int r4d_rad_conv_t1d_f32 (const RadArgs*, RadStream);
|
||||
int r4d_rad_snake (const RadArgs*, RadStream);
|
||||
int r4d_rad_cfg_topk_sample (const RadArgs*, RadStream);
|
||||
int r4d_rad_rvq_embed (const RadArgs*, RadStream);
|
||||
int r4d_rad_vq_encode (const RadArgs*, RadStream);
|
||||
int r4d_rad_frame_mix_store (const RadArgs*, RadStream);
|
||||
int r4d_rad_end_status (const RadArgs*, RadStream);
|
||||
int r4d_rad_ras_pick (const RadArgs*, RadStream);
|
||||
int r4d_rad_frame_store (const RadArgs*, RadStream);
|
||||
int r4d_rad_resample_nearest (const RadArgs*, RadStream);
|
||||
int r4d_rad_fourier_embed (const RadArgs*, RadStream);
|
||||
@@ -729,6 +731,7 @@ int r4d_rad_mla_attn(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_mla_attn_scratch(const RadArgs*);
|
||||
int r4d_rad_mla_attn_matrix(const RadArgs*, RadStream);
|
||||
int64_t r4d_rad_mla_attn_matrix_scratch(const RadArgs*);
|
||||
int r4d_rad_mla_attn_rows(const RadArgs*, RadStream);
|
||||
int r4d_shape_mla_attn(const RadParam*, int, int, RadOpdDesc*);
|
||||
int r4d_rad_router_sigmoid_topk(const RadArgs*, RadStream);
|
||||
int r4d_shape_router_sigmoid_topk(const RadParam*, int, int, RadOpdDesc*);
|
||||
|
||||
+61
-92
@@ -2497,7 +2497,8 @@ static const RadOperandSpec oAttnPS[] = {
|
||||
/* ---- audio generation (r4d_audio.hip); the same specs as libref's (ref_registry.cpp). */
|
||||
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
|
||||
P_INTO("causal") };
|
||||
P_INTO("causal"), P_INTO("stride"),
|
||||
P_INTO("cu_div") };
|
||||
static const RadOperandSpec oConv1d[] = {
|
||||
{ "x", RAD_OPD_IN, 0 }, { "w", RAD_OPD_WEIGHT, 0 }, { "cu_seqlens", RAD_OPD_IN, 0 },
|
||||
{ "res", RAD_OPD_IN, 1 }, { "y", RAD_OPD_OUT, 0 }, { "b", RAD_OPD_WEIGHT, 1 },
|
||||
@@ -2516,7 +2517,8 @@ static const RadOperandSpec oSnake[] = {
|
||||
static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"),
|
||||
P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"),
|
||||
P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"),
|
||||
P_INTO("sup_hi"), P_F64O("penalty") };
|
||||
P_INTO("sup_hi"), P_F64O("penalty"),
|
||||
P_F64O("top_p") };
|
||||
static const RadOperandSpec oCfgTopk[] = {
|
||||
{ "logits", RAD_OPD_IN, 0 }, { "seed", RAD_OPD_IN, 0 }, { "frame", RAD_OPD_IN, 0 },
|
||||
{ "ids", RAD_OPD_OUT, 0 }, { "cfg", RAD_OPD_IN, 1 }, { "lane", RAD_OPD_IN, 1 },
|
||||
@@ -2524,11 +2526,18 @@ static const RadOperandSpec oCfgTopk[] = {
|
||||
};
|
||||
static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"),
|
||||
P_INT("vocab"), P_INT("off0"), P_F64("scale"),
|
||||
P_STR("dtype"), P_INTO("round") };
|
||||
P_STR("dtype"), P_INTO("round"), P_INTO("clamp") };
|
||||
static const RadOperandSpec oRvqEmbed[] = {
|
||||
{ "codes", RAD_OPD_IN, 0 }, { "t0", RAD_OPD_WEIGHT, 0 }, { "t1", RAD_OPD_WEIGHT, 0 },
|
||||
{ "y", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oVqEncode[] = {
|
||||
{ "x", RAD_OPD_INOUT, 0 }, { "in_w", RAD_OPD_WEIGHT, 0 }, { "in_b", RAD_OPD_WEIGHT, 0 },
|
||||
{ "cb", RAD_OPD_WEIGHT, 0 }, { "out_w", RAD_OPD_WEIGHT, 0 }, { "out_b", RAD_OPD_WEIGHT, 0 },
|
||||
{ "codes", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"),
|
||||
P_INTO("rep"), P_STR("dtype") };
|
||||
static const RadOperandSpec oFrameMix[] = {
|
||||
@@ -2540,6 +2549,12 @@ static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep"
|
||||
static const RadOperandSpec oEndStatus[] = {
|
||||
{ "ids", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 }, { "status", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"),
|
||||
P_INTO("rep"), P_INTO("clear") };
|
||||
static const RadOperandSpec oRasPick[] = {
|
||||
{ "first", RAD_OPD_IN, 0 }, { "alt", RAD_OPD_IN, 0 }, { "lane", RAD_OPD_IN, 0 },
|
||||
{ "hist", RAD_OPD_INOUT, 0 }, { "ids", RAD_OPD_OUT, 0 },
|
||||
};
|
||||
static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"),
|
||||
P_INTO("rep"), P_INTO("skip") };
|
||||
static const RadOperandSpec oFrameStore[] = {
|
||||
@@ -3507,10 +3522,16 @@ static const RadOpSchema kSchemas[] = {
|
||||
SCHEMA("rvq_embed", pRvqEmbed, oRvqEmbed,
|
||||
"a frame's embedding from code-major residual codes, the first codebook's table and the "
|
||||
"others' stacked one, times `scale`; `round` 1 rounds the f32 sum once."),
|
||||
SCHEMA("vq_encode", pVqEncode, oVqEncode,
|
||||
"one residual vector quantiser step: the code of greatest cosine with in_w x + in_b "
|
||||
"(the lower index on a tie), then x -= out_w cb[code] + out_b."),
|
||||
SCHEMA("frame_mix_store", pFrameMix, oFrameMix,
|
||||
"a frame's conditioning row (softmax-weighted planes times scale) into its lane."),
|
||||
SCHEMA("end_status", pEndStatus, oEndStatus,
|
||||
"status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]."),
|
||||
SCHEMA("ras_pick", pRasPick, oRasPick,
|
||||
"repetition-aware sampling: the alternative draw where the first is in [lo, hi) and in "
|
||||
"the lane's window of its last picks, else the first; the pick enters the window."),
|
||||
SCHEMA("frame_store", pFrameStore, oFrameStore,
|
||||
"a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] "
|
||||
"= codes[k, rep i] when frame >= skip and status[lane] >= 0."),
|
||||
@@ -4205,20 +4226,6 @@ static const RadConstraint cArTsExact8[] = {
|
||||
C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS),
|
||||
C_P2P,
|
||||
};
|
||||
/* The three- and eight-rank two-shots at `overlap` 1, as cArTsExact4Lane: a pipelined prefill's
|
||||
* all-reduce beside the other piece's compute. They launch as the wide rows unless R4D_AR_LANE_3_8=1
|
||||
* (tArTs38Lane); neither launch has been measured on three or eight cards. */
|
||||
static const RadConstraint cArTsExact3Lane[] = {
|
||||
C_EQ("world_size", 3), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"),
|
||||
C_GE("numel", R4D_AR_WIDE_ONESHOT_MAX_ELEMS + 1), C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS),
|
||||
C_EQ("overlap", 1), C_P2P,
|
||||
};
|
||||
static const RadConstraint cArTsExact8Lane[] = {
|
||||
C_EQ("world_size", 8), C_EQ("exact", 1), C_IN("dtype", "bf16 fp16 fp32"),
|
||||
C_DIV("numel", 64), C_GE("numel", R4D_AR_WIDE_ONESHOT_MAX_ELEMS + 1),
|
||||
C_LE("numel", R4D_AR_TWOSHOT_WIDE_MAX_ELEMS),
|
||||
C_EQ("overlap", 1), C_P2P,
|
||||
};
|
||||
static const RadConstraint cArWht6[] = {
|
||||
C_EQ("world_size", 2), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 64),
|
||||
C_P2P,
|
||||
@@ -4237,11 +4244,6 @@ static const RadConstraint cArTi8Ts3[] = {
|
||||
C_EQ("world_size", 3), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 32),
|
||||
C_P2P,
|
||||
};
|
||||
/* The same at `overlap` 1 (tArTs38Lane: the wide launch unless R4D_AR_LANE_3_8=1). */
|
||||
static const RadConstraint cArTi8Ts3Lane[] = {
|
||||
C_EQ("world_size", 3), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 32),
|
||||
C_EQ("overlap", 1), C_P2P,
|
||||
};
|
||||
static const RadConstraint cArTi8Ts4[] = {
|
||||
C_EQ("world_size", 4), C_EQ("exact", 0), C_IN("dtype", "bf16 fp16"), C_DIV("numel", 128),
|
||||
C_P2P,
|
||||
@@ -4398,6 +4400,16 @@ static const RadConstraint cMlaMatrix[] = { C_GE("M", 1),
|
||||
C_GE("blocks", 1),
|
||||
C_EQ("block_size", 4),
|
||||
C_IN("dtype", "bf16") };
|
||||
/* GLM's prefill splits MLA by rows, a rank holding every head of its rows: the rows row loads a
|
||||
* key chunk once for a workgroup of 64 heads and outranks the matrix row there. Measured on gfx1201
|
||||
* (r4d_selftest --perfmla 512 513 64 20 topk:16:16000), a rank's run of 512 rows takes 3.9 ms
|
||||
* against 12.3 ms on the matrix row, and the 4096 rows x 8 heads it replaces 14.0 ms on the paired
|
||||
* matrix row. Under 32 rows its launcher runs the matrix row's kernel (r4d_mla.hip); a bound on M
|
||||
* here would cut every mla_attn band at 32, the eight-head ones too. */
|
||||
static const RadConstraint cMlaRows[] = { C_GE("M", 1), C_LE("M", 65535),
|
||||
C_EQ("latent_dim", 512), C_EQ("heads", 64),
|
||||
C_GE("blocks", 1), C_EQ("block_size", 4),
|
||||
C_IN("dtype", "bf16") };
|
||||
/* `n` is bounded by LDS: nh (hc*n) and ne (n) are both bf16 and live through the second phase;
|
||||
* 28672 elements is that budget at hc 4. */
|
||||
static const RadConstraint cMtpEnter[] = {
|
||||
@@ -4846,10 +4858,8 @@ static const RadConstraint cGemmMxfp4A8GemvWide[] = {
|
||||
/* gemm_mxfp4a8_decode_shortk: the decode entry at 33..64 rows of a wide, short weight, above
|
||||
* gemv_wide by priority. There gemv_wide's blocks hold three or four row tiles over a short K each,
|
||||
* so the cross-wave reduction of a block weighs more than its WMMAs, and the decode kernel's split
|
||||
* wins (R9700, each row alone, ours' gemv_wide / decode / upstream's decode, us: 19456 x 2560 at 64
|
||||
* rows 131.8 / 93.3 / 104.5, 16384 x 2048 92.8 / 68.6 / 76.1, 9728 x 2560 74.1 / 52.5 / 67.4).
|
||||
* Narrower N stays with gemv_wide (5120 x 2176 at 40 rows 39.2 against the decode kernel's 52.8),
|
||||
* as does K past 2560 (17408 x 5120 at 40 rows 119.3 against 129.0). */
|
||||
* wins on gfx1201 (19456 x 2560 at 64 rows: 93.3 us against gemv_wide's 131.8). Narrower N and K
|
||||
* past 2560 stay with gemv_wide. */
|
||||
static const RadConstraint cGemmMxfp4A8DecodeShortK[] = {
|
||||
C_GE("M", 33), C_LE("M", 64), C_GE("N", 8192), C_LE("N", 36864), C_LE("K", 2560), C_DIV("K", 64),
|
||||
C_DIV("N", 16), C_IN("dtype", "mxfp4a8"),
|
||||
@@ -4956,11 +4966,11 @@ static const RadTunable tGemmPrefill[] = {
|
||||
};
|
||||
|
||||
/* The MXFP4 tiled GEMM's one axis: compiled arms of one template. 0 is the M crossover (TN=4 from
|
||||
* M >= 1024), which needs M. */
|
||||
* M >= 2048), which needs M. */
|
||||
static const int64_t kMxTn[] = { 0, 2, 4 };
|
||||
static const RadTunable tGemmMxfp4Tiled[] = {
|
||||
{ "tn", kMxTn, NELEM(kMxTn), 0,
|
||||
"16-column fragments per wave: 2 = 256x64 block, 4 = 256x128. 0 = TN 4 from M >= 1024" },
|
||||
"16-column fragments per wave: 2 = 256x64 block, 4 = 256x128. 0 = TN 4 from M >= 2048" },
|
||||
};
|
||||
|
||||
/* The MXFP4 decode GEMM's axes. 0 on each is the kernel's own rule (r4d_gemm_mxfp4a8_decode.hip);
|
||||
@@ -5044,25 +5054,6 @@ static const RadTunable tArTs4Lane[] = {
|
||||
{ "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" },
|
||||
{ "ts_min", kArTsMin, NELEM(kArTsMin), 32768, "unused here (tAr says why it is declared)" },
|
||||
};
|
||||
|
||||
/* The three- and eight-rank two-shots at `overlap` 1 (cArTsExact3Lane, cArTsExact8Lane, cArTi8Ts3Lane). The
|
||||
* four-rank lane's narrow launch was measured at four ranks; at three and eight it is not, and a narrow
|
||||
* grid can also lose there: where the all-reduce is the longer of the two (a large message, slow or shared
|
||||
* links, seven peers to feed at eight ranks) the step waits on a slower collective. So by default these
|
||||
* rows launch as the wide rows do (tAr's defaults: the same grid, the same bits, the same time) and the
|
||||
* narrow launch is a deployment's choice, read once at load: R4D_AR_LANE_3_8=1 gives them the four-rank
|
||||
* lane's four blocks of 1024. Any other value, or unset, is the default. */
|
||||
static int64_t ar_lane38_nblocks() {
|
||||
const char* e = std::getenv("R4D_AR_LANE_3_8");
|
||||
return e && e[0] == '1' && !e[1] ? 4 : 0;
|
||||
}
|
||||
static const RadTunable tArTs38Lane[] = {
|
||||
{ "nblocks", kArNblocks, NELEM(kArNblocks), ar_lane38_nblocks(), "blocks in the grid. 0 = scale with the message and clamp (the wide rows' launch, the default); 4 under R4D_AR_LANE_3_8=1" },
|
||||
{ "nthreads", kArNthreads, NELEM(kArNthreads), 1024, "threads per block" },
|
||||
{ "drain", kArDrain, NELEM(kArDrain), 3, "store-drain wait before the flag: 3 = s_wait_storecnt, 1 = vmcnt" },
|
||||
{ "acq", kArAcq, NELEM(kArAcq), 0, "acquire fence after the flag read" },
|
||||
{ "ts_min", kArTsMin, NELEM(kArTsMin), 32768, "unused here (tAr says why it is declared)" },
|
||||
};
|
||||
/* The same axes with narrow defaults, for a collective issued beside compute (`overlap` 1). The
|
||||
* wide launch (up to 24 blocks of 1024 threads spinning on peer flags) suits an all-reduce that has
|
||||
* the card to itself; beside a GEMM it slows the GEMM by 1.45-2.1x. Eight blocks of 256 threads
|
||||
@@ -5201,6 +5192,8 @@ static const RadConstraint cRmsMod[] = { C_IN("dtype", "bf16"), C_DIV("n", 8), C
|
||||
static const RadConstraint cRmsModQ[] = { C_IN("dtype", "bf16"), C_DIV("n", 128), C_LE("n", 8192),
|
||||
C_EQ("group", 128) };
|
||||
static const RadConstraint cGenF32[] = { C_IN("dtype", "f32") };
|
||||
/* vq_encode: e's sums staged in LDS, a codebook dimension of 32 at most. */
|
||||
static const RadConstraint cVqEncode[] = { C_IN("dtype", "bf16 f32"), C_LE("dim", 32) };
|
||||
static const RadConstraint cPatchUnfold[] = { C_IN("dtype", "f32"), C_LE("C", 64) };
|
||||
static const RadConstraint cGenAnyFloat[] = { C_IN("dtype", "bf16 f32") };
|
||||
static const RadConstraint cSnakeAa[] = { C_IN("dtype", "f32"), C_LE("k", 32) };
|
||||
@@ -5708,6 +5701,12 @@ static const RadKernelInfo kKernels[] = {
|
||||
nullptr, nullptr, r4d_rad_scale, nullptr, nullptr, nullptr,
|
||||
r4d_shape_scale },
|
||||
|
||||
{ "mla_attn_rows_bf16", "mla_attn", "attn", "row-tiled WMMA latent attention, one key load for 64 heads",
|
||||
"latent_dim=512, heads=64, block_size=4",
|
||||
"bf16 operands; FP32 probabilities via high/low BF16",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY + 2, ROW(cMlaRows), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_mla_attn_rows, r4d_rad_mla_attn_matrix_scratch, nullptr, nullptr,
|
||||
r4d_shape_mla_attn },
|
||||
{ "mla_attn_matrix_bf16", "mla_attn", "attn", "head-tiled WMMA latent attention with FP32 softmax",
|
||||
"latent_dim=512, heads a multiple of 8 (heads%16==8 pairs two requests a tile), block_size=4",
|
||||
"bf16 operands; FP32 probabilities via high/low BF16",
|
||||
@@ -5866,7 +5865,8 @@ static const RadKernelInfo kKernels[] = {
|
||||
"the lm_head projection over an fp8 head: C[M, n_vocab] f32 = x[M, n_embd] @ dequant(W)^T, "
|
||||
"one wave a vocabulary row, the row's own scales in its tail",
|
||||
"any M -- one pass to 32 rows, instantiated exactly to 8 and rounded up to a multiple of 4 above "
|
||||
"it, then chunked; n_embd a multiple of 128, which is the group the scales are taken over. The "
|
||||
"it, to 64 rows in four tiles a wave, to 128 in two M halves of four that share the staged head "
|
||||
"tile, then chunked by 128; n_embd a multiple of 128, which is the group the scales are taken over. The "
|
||||
"stored row is padded to 16 bytes so the uint4 load stays aligned at any such n_embd",
|
||||
"bf16 x, E4M3 head with a bf16 scale per 128x128 tile stored PER ROW, F32 LOGITS OUT, fp32 "
|
||||
"accumulate",
|
||||
@@ -7131,21 +7131,6 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_twoshot_3rank_exact, nullptr, nullptr, nullptr,
|
||||
r4d_shape_all_reduce },
|
||||
|
||||
/* The row above at `overlap` 1: the same entry point and the same arithmetic; the wide launch unless
|
||||
* R4D_AR_LANE_3_8=1 gives it the four-rank lane's narrow one (tArTs38Lane; not measured on three cards). */
|
||||
{ "ar_twoshot_3rank_exact_lane", "all_reduce", "ar",
|
||||
"all-reduce (sum), reduce-scatter + all-gather over P2P IPC scratch, beside compute; the wide "
|
||||
"launch unless R4D_AR_LANE_3_8=1 makes it narrow",
|
||||
"exactly 3 ranks, all peer-accessible, overlap 1; messages above "
|
||||
R4D_XSTR(R4D_AR_WIDE_ONESHOT_MAX_ELEMS) " elements; shards as even as the word count allows; "
|
||||
"in place; cudagraph-safe",
|
||||
"bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks "
|
||||
"and to the wide row",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_AR_TWOSHOT + 1,
|
||||
ROW(cArTsExact3Lane), ROW(tArTs38Lane), nullptr,
|
||||
r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_twoshot_3rank_exact, nullptr, nullptr, nullptr,
|
||||
r4d_shape_all_reduce },
|
||||
|
||||
{ "ar_twoshot_4rank_exact", "all_reduce", "ar",
|
||||
"all-reduce (sum), reduce-scatter + all-gather over P2P IPC scratch, per-block pipelined "
|
||||
"handshake",
|
||||
@@ -7185,21 +7170,6 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_twoshot_8rank_exact, nullptr, nullptr, nullptr,
|
||||
r4d_shape_all_reduce },
|
||||
|
||||
/* The row above at `overlap` 1: the same entry point and the same arithmetic; the wide launch unless
|
||||
* R4D_AR_LANE_3_8=1 gives it the four-rank lane's narrow one (tArTs38Lane; not measured on eight cards). */
|
||||
{ "ar_twoshot_8rank_exact_lane", "all_reduce", "ar",
|
||||
"all-reduce (sum), reduce-scatter + all-gather over P2P IPC scratch, beside compute; the wide "
|
||||
"launch unless R4D_AR_LANE_3_8=1 makes it narrow",
|
||||
"exactly 8 ranks, all peer-accessible, overlap 1; messages above "
|
||||
R4D_XSTR(R4D_AR_WIDE_ONESHOT_MAX_ELEMS) " elements; message must shard evenly over the ranks; "
|
||||
"in place; cudagraph-safe",
|
||||
"bf16 / fp16 / fp32 payload, fp32 accumulate in ascending rank order, bit-identical across ranks "
|
||||
"and to the wide row",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_AR_TWOSHOT + 1,
|
||||
ROW(cArTsExact8Lane), ROW(tArTs38Lane), nullptr,
|
||||
r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_twoshot_8rank_exact, nullptr, nullptr, nullptr,
|
||||
r4d_shape_all_reduce },
|
||||
|
||||
{ "ar_gather_2rank", "all_gather", "ar",
|
||||
"all-gather, one-shot push over P2P IPC scratch, per-block flag handshake",
|
||||
"exactly 2 ranks, peer-accessible; y is [2 * numel] with rank r's input at r * numel; "
|
||||
@@ -7327,20 +7297,6 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_twoshot_3rank_ti8, nullptr, nullptr, nullptr,
|
||||
r4d_shape_all_reduce },
|
||||
|
||||
/* The row above at `overlap` 1: the same entry point and the same arithmetic; the wide launch unless
|
||||
* R4D_AR_LANE_3_8=1 gives it the four-rank lane's narrow one (tArTs38Lane; not measured on three cards). */
|
||||
{ "ar_twoshot_3rank_ti8_lane", "all_reduce", "ar",
|
||||
"all-reduce (sum), reduce-scatter + all-gather on the tiered-int8 wire -- lossy, beside compute; "
|
||||
"the wide launch unless R4D_AR_LANE_3_8=1 makes it narrow",
|
||||
"exactly 3 ranks, all peer-accessible, overlap 1; groups of 32, split over the shards as evenly as "
|
||||
"they divide; under min_bytes the exact one-shot; cudagraph-safe",
|
||||
"bf16 / fp16 payload, int8 + fp16 scale + u32 record per group on the wire, fp32 accumulate in "
|
||||
"ascending rank order, bit-identical across ranks and to the wide row",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_AR_ONESHOT + 1,
|
||||
ROW(cArTi8Ts3Lane), ROW(tArTs38Lane), nullptr,
|
||||
r4d_rad_ar_init, r4d_rad_ar_fini, r4d_rad_ar_twoshot_3rank_ti8, nullptr, nullptr, nullptr,
|
||||
r4d_shape_all_reduce },
|
||||
|
||||
{ "ar_twoshot_4rank_ti8", "all_reduce", "ar",
|
||||
"all-reduce (sum), reduce-scatter + all-gather; both hops ride the tiered-int8 wire (double "
|
||||
"quant, the owner storing the decode of its own words) -- lossy",
|
||||
@@ -9092,6 +9048,13 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
ROW(cGenBf16), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_rvq_embed },
|
||||
|
||||
{ "vq_encode", "vq_encode", "elem",
|
||||
"a residual quantiser's step: the nearest code by cosine", "a workgroup a row, dim <= 32",
|
||||
"bf16 or f32 rows and weights, f32 arithmetic, the row rounded once",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
ROW(cVqEncode), NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_vq_encode },
|
||||
|
||||
{ "frame_mix_store_bf16", "frame_mix_store", "elem",
|
||||
"a frame's conditioning row into its lane", "a workgroup a lane, L <= 16",
|
||||
"bf16 planes and rows, f32 logits and scale",
|
||||
@@ -9105,6 +9068,12 @@ R4D_WIN_PAIR(512, 1) R4D_WIN_PAIR(512, 2) R4D_WIN_PAIR(512, 4) R4D_WIN_PAIR(512,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_end_status },
|
||||
|
||||
{ "ras_pick", "ras_pick", "elem",
|
||||
"a repetition-aware choice between two draws a lane", "a thread a lane", "i32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
nullptr, 0, NOTUNE,
|
||||
nullptr, nullptr, r4d_rad_ras_pick },
|
||||
|
||||
{ "frame_store", "frame_store", "elem",
|
||||
"a frame's codes into its lane's history", "a thread a (lane, code); dst contiguous", "i32",
|
||||
RAD_DOMAIN_DEVICE, R4D_PRIO_ONLY,
|
||||
|
||||
+321
-131
@@ -145,6 +145,7 @@ struct Plugin {
|
||||
void (*pin_qsel)(int) = nullptr;
|
||||
void (*pin_mla)(int) = nullptr;
|
||||
void (*mla_stats)(unsigned long long*) = nullptr;
|
||||
void (*pin_mla_rows)(int) = nullptr;
|
||||
int (*record)(const void**, int) = nullptr;
|
||||
void (*ar8_settings)(const R4DAr8Settings*) = nullptr;
|
||||
};
|
||||
@@ -213,6 +214,7 @@ static bool load(Plugin* pl, const char* path) {
|
||||
okall &= sym(pl->h, "r4d_qsa_select_pin_form", &pl->pin_qsel);
|
||||
okall &= sym(pl->h, "r4d_mla_matrix_pin_form", &pl->pin_mla);
|
||||
okall &= sym(pl->h, "r4d_mla_matrix_stats", &pl->mla_stats);
|
||||
okall &= sym(pl->h, "r4d_mla_rows_pin_form", &pl->pin_mla_rows);
|
||||
okall &= sym(pl->h, "r4d_record_dispatches", &pl->record);
|
||||
okall &= sym(pl->h, "r4d_ar8_test_settings", &pl->ar8_settings);
|
||||
ScopedAr8::apply = pl->ar8_settings;
|
||||
@@ -400,74 +402,6 @@ static void cross_check(const Plugin& pl) {
|
||||
ok("every row that needs two or more ranks requires device.p2p 1 or 0", no_p2p == 0,
|
||||
p2pdetail);
|
||||
|
||||
/* The three- and eight-rank `overlap` rows launch as their wide rows unless R4D_AR_LANE_3_8=1
|
||||
* (r4d_rows.cpp, tArTs38Lane): every axis default the wide row's, nblocks 4 under the variable.
|
||||
* The four-rank lane rows keep their measured narrow launch either way. */
|
||||
{
|
||||
const char* env = std::getenv("R4D_AR_LANE_3_8");
|
||||
const bool narrow = env && env[0] == '1' && !env[1];
|
||||
auto row = [&](const char* n) -> const RadKernelInfo* {
|
||||
for (int k = 0; k < nk; ++k)
|
||||
if (!std::strcmp(pl.kernel_at(k)->name, n)) return pl.kernel_at(k);
|
||||
return nullptr;
|
||||
};
|
||||
auto deflt = [](const RadKernelInfo* r, const char* key) -> long long {
|
||||
for (int v = 0; v < r->n_tunables; ++v)
|
||||
if (!std::strcmp(r->tunables[v].key, key)) return (long long)r->tunables[v].deflt;
|
||||
return -1;
|
||||
};
|
||||
static const char* const pairs[][2] = {
|
||||
{ "ar_twoshot_3rank_exact_lane", "ar_twoshot_3rank_exact" },
|
||||
{ "ar_twoshot_8rank_exact_lane", "ar_twoshot_8rank_exact" },
|
||||
{ "ar_twoshot_3rank_ti8_lane", "ar_twoshot_3rank_ti8" },
|
||||
};
|
||||
int bad = 0;
|
||||
std::string detail;
|
||||
for (const auto& pr : pairs) {
|
||||
const RadKernelInfo* l = row(pr[0]);
|
||||
const RadKernelInfo* w = row(pr[1]);
|
||||
if (!l || !w) { ++bad; detail += std::string(pr[0]) + " or its wide row absent; "; continue; }
|
||||
for (const char* key : { "nblocks", "nthreads", "drain", "acq" }) {
|
||||
const long long want = narrow && !std::strcmp(key, "nblocks") ? 4 : deflt(w, key);
|
||||
if (deflt(l, key) != want) {
|
||||
++bad;
|
||||
detail += std::string(pr[0]) + ":" + key + " " + std::to_string(deflt(l, key)) +
|
||||
" (want " + std::to_string(want) + "); ";
|
||||
}
|
||||
}
|
||||
}
|
||||
ok(narrow ? "the 3/8-rank overlap rows take the narrow launch (R4D_AR_LANE_3_8=1)"
|
||||
: "the 3/8-rank overlap rows launch as their wide rows (R4D_AR_LANE_3_8 unset)",
|
||||
bad == 0, detail);
|
||||
/* And they accept every pin their wide rows accept: a RADIANCE_TUNE all_reduce pin is applied
|
||||
* to every row serving the op, and a key or value a serving row lacks fails the selection. */
|
||||
int bad_axis = 0;
|
||||
std::string axis_detail;
|
||||
for (const auto& pr : pairs) {
|
||||
const RadKernelInfo* l = row(pr[0]);
|
||||
const RadKernelInfo* w = row(pr[1]);
|
||||
if (!l || !w) continue;
|
||||
for (int v = 0; v < w->n_tunables; ++v) {
|
||||
const RadTunable& wt = w->tunables[v];
|
||||
const RadTunable* lt = nullptr;
|
||||
for (int u = 0; u < l->n_tunables; ++u)
|
||||
if (!std::strcmp(l->tunables[u].key, wt.key)) lt = &l->tunables[u];
|
||||
if (!lt) { ++bad_axis; axis_detail += std::string(pr[0]) + " lacks " + wt.key + "; "; continue; }
|
||||
for (int i = 0; i < wt.n_values; ++i) {
|
||||
bool has = false;
|
||||
for (int j = 0; j < lt->n_values; ++j) has = has || lt->values[j] == wt.values[i];
|
||||
if (!has) {
|
||||
++bad_axis;
|
||||
axis_detail += std::string(pr[0]) + ":" + wt.key + " lacks " +
|
||||
std::to_string((long long)wt.values[i]) + "; ";
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
ok("the 3/8-rank overlap rows accept every tunable pin of their wide rows", bad_axis == 0,
|
||||
axis_detail);
|
||||
}
|
||||
|
||||
/* The libr4d orderings the integer priority has to preserve. */
|
||||
int p_ts = -1, p_os = -1, p_dec = -1, p_pre = -1, p_m16 = -1, p_m64 = -1, p_bt = -1;
|
||||
int p_g2dec = -1, p_g2pre = -1, p_g2win = -1;
|
||||
@@ -6256,18 +6190,28 @@ int64_t seq_of(const std::vector<int32_t>& cu, int64_t r) {
|
||||
return s;
|
||||
}
|
||||
|
||||
/* conv1d: the causal form beside the symmetric one, on the tiled and the direct kernels. */
|
||||
/* conv1d: the causal form beside the symmetric one, on the tiled and the direct kernels; strided
|
||||
* causal forms (a codec encoder's downsampling, kernels of two strides and of one) over sequences
|
||||
* of whole strides, the bounds also in units of 8 rows (cu_div, an encoder's samples). */
|
||||
void conv1d_cases(const Plugin& pl) {
|
||||
const RadKernelInfo* r = find(pl, "conv1d_bf16");
|
||||
if (!r) { ok("conv1d_bf16", false, "row absent"); return; }
|
||||
struct C { int64_t cin, cout, k, dil; int causal, extras; };
|
||||
for (const C& c : { C{ 16, 32, 3, 2, 0, 0 }, C{ 16, 32, 3, 2, 1, 1 }, C{ 16, 128, 4, 1, 1, 0 },
|
||||
C{ 6, 3, 7, 3, 1, 1 }, C{ 6, 3, 2, 1, 1, 0 } }) {
|
||||
const std::vector<int32_t> cu = { 0, 13, 30 };
|
||||
const int64_t M = 30;
|
||||
struct C { int64_t cin, cout, k, dil; int causal, extras; int64_t st, cd = 1; };
|
||||
for (const C& c : { C{ 16, 32, 3, 2, 0, 0, 1 }, C{ 16, 32, 3, 2, 1, 1, 1 },
|
||||
C{ 16, 128, 4, 1, 1, 0, 1 }, C{ 6, 3, 7, 3, 1, 1, 1 },
|
||||
C{ 6, 3, 2, 1, 1, 0, 1 }, C{ 16, 32, 4, 1, 1, 0, 2 },
|
||||
C{ 16, 128, 16, 1, 1, 1, 8 }, C{ 6, 3, 8, 1, 1, 1, 4 },
|
||||
C{ 16, 32, 2, 1, 1, 0, 2 }, C{ 16, 64, 4, 1, 1, 1, 2, 8 },
|
||||
C{ 6, 3, 8, 1, 1, 0, 4, 8 } }) {
|
||||
/* Bounds of whole strides: 13 and 30 rounded up to the stride; the op reads them times
|
||||
* cu_div. */
|
||||
const int64_t s1 = (13 + c.st - 1) / c.st * c.st, s2 = (30 + c.st - 1) / c.st * c.st;
|
||||
const std::vector<int32_t> cu = { 0, (int32_t)s1, (int32_t)s2 };
|
||||
const std::vector<int32_t> cu_op = { 0, (int32_t)(s1 * c.cd), (int32_t)(s2 * c.cd) };
|
||||
const int64_t M = s2, MO = M / c.st;
|
||||
std::vector<float> x = randv((size_t)(M * c.cin), 1.0f);
|
||||
std::vector<float> w = randv((size_t)(c.cout * c.cin * c.k), 0.3f);
|
||||
std::vector<float> b = randv((size_t)c.cout, 0.5f), res = randv((size_t)(M * c.cout), 0.5f);
|
||||
std::vector<float> b = randv((size_t)c.cout, 0.5f), res = randv((size_t)(MO * c.cout), 0.5f);
|
||||
void* dx = up_bf16(x);
|
||||
void* db = up_bf16(b);
|
||||
void* dres = up_bf16(res);
|
||||
@@ -6275,27 +6219,31 @@ void conv1d_cases(const Plugin& pl) {
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("cin", c.cin), PI("cout", c.cout),
|
||||
PI("k", c.k), PI("dil", c.dil), PS("act", c.extras ? "tanh" : "none"),
|
||||
PS("dtype", "bf16"), PI("causal", c.causal) };
|
||||
const std::string nm = fmt("conv1d_bf16 cin %lld cout %lld k %lld dil %lld causal %d%s",
|
||||
if (c.st > 1) ps.push_back(PI("stride", c.st));
|
||||
if (c.cd > 1) ps.push_back(PI("cu_div", c.cd));
|
||||
const std::string nm = fmt("conv1d_bf16 cin %lld cout %lld k %lld dil %lld causal %d "
|
||||
"stride %lld cu_div %lld%s",
|
||||
(long long)c.cin, (long long)c.cout, (long long)c.k,
|
||||
(long long)c.dil, c.causal, c.extras ? " +bias+res+tanh" : "");
|
||||
(long long)c.dil, c.causal, (long long)c.st, (long long)c.cd,
|
||||
c.extras ? " +bias+res+tanh" : "");
|
||||
void* dw = stored_weight(r, ps, w, c.cout, c.cin * c.k, nm.c_str());
|
||||
void* dcu = up_i32(cu);
|
||||
void* dy = dalloc((size_t)(M * c.cout) * 2);
|
||||
void* dcu = up_i32(cu_op);
|
||||
void* dy = dalloc((size_t)(MO * c.cout) * 2);
|
||||
if (!dw) continue;
|
||||
RadTensor tres = T(dres, RAD_BF16, { M, c.cout }), tb = T(db, RAD_BF16, { c.cout });
|
||||
RadTensor tres = T(dres, RAD_BF16, { MO, c.cout }), tb = T(db, RAD_BF16, { c.cout });
|
||||
if (!c.extras) { absent(tres); absent(tb); }
|
||||
const int rc = launch(r, { T(dx, RAD_BF16, { M, c.cin }), T(dw, RAD_BF16, { c.cout, c.cin, c.k }),
|
||||
T(dcu, RAD_I32, { 3 }), tres, T(dy, RAD_BF16, { M, c.cout }), tb },
|
||||
T(dcu, RAD_I32, { 3 }), tres, T(dy, RAD_BF16, { MO, c.cout }), tb },
|
||||
ps);
|
||||
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
|
||||
const int64_t pad = c.causal ? c.dil * (c.k - 1) : c.dil * (c.k - 1) / 2;
|
||||
std::vector<float> want((size_t)(M * c.cout));
|
||||
for (int64_t row = 0; row < M; ++row) {
|
||||
const int64_t e = seq_of(cu, row), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1];
|
||||
const int64_t pad = c.causal ? c.dil * (c.k - 1) + 1 - c.st : c.dil * (c.k - 1) / 2;
|
||||
std::vector<float> want((size_t)(MO * c.cout));
|
||||
for (int64_t row = 0; row < MO; ++row) {
|
||||
const int64_t e = seq_of(cu, row * c.st), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1];
|
||||
for (int64_t co = 0; co < c.cout; ++co) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t kk = 0; kk < c.k; ++kk) {
|
||||
const int64_t ir = row + kk * c.dil - pad;
|
||||
const int64_t ir = row * c.st + kk * c.dil - pad;
|
||||
if (ir < s0 || ir >= s1) continue;
|
||||
for (int64_t ci = 0; ci < c.cin; ++ci)
|
||||
acc += w[(size_t)((co * c.cin + ci) * c.k + kk)] * x[(size_t)(ir * c.cin + ci)];
|
||||
@@ -6428,10 +6376,14 @@ void snake_cases(const Plugin& pl) {
|
||||
}
|
||||
}
|
||||
|
||||
/* Picks whose nucleus ended inside the top k, so that a top_p case is known to test the cut. */
|
||||
int64_t g_topp_cuts = 0;
|
||||
|
||||
/* ref_cfg_topk_sample's rule on the host, for one lane, over f32 logits. */
|
||||
int ref_pick(const std::vector<float>& lg, int64_t V, int64_t lane_row, int rep, float cfg,
|
||||
int64_t K, int64_t cond_k, float temp, int64_t sup_lo, int64_t sup_hi, float pen,
|
||||
std::vector<int32_t>* hist, int64_t hb, uint64_t seed, int32_t frame, uint64_t stream) {
|
||||
std::vector<int32_t>* hist, int64_t hb, uint64_t seed, int32_t frame, uint64_t stream,
|
||||
float top_p = 1.0f) {
|
||||
std::vector<float> c((size_t)V), g((size_t)V);
|
||||
for (int64_t j = 0; j < V; ++j) c[(size_t)j] = lg[(size_t)(rep * lane_row * V + j)];
|
||||
if (rep == 2) {
|
||||
@@ -6464,11 +6416,28 @@ int ref_pick(const std::vector<float>& lg, int64_t V, int64_t lane_row, int rep,
|
||||
if (open(j)) idx.push_back(j);
|
||||
}
|
||||
if (idx.empty()) return -1;
|
||||
const int64_t kk = std::min<int64_t>(K, (int64_t)idx.size());
|
||||
double z = 0;
|
||||
if (top_p < 1.0f) {
|
||||
float gm = g[(size_t)idx[0]];
|
||||
for (const int64_t j : idx) gm = std::max(gm, g[(size_t)j]);
|
||||
for (const int64_t j : idx) z += std::exp((double)(g[(size_t)j] / temp - gm / temp));
|
||||
}
|
||||
int64_t kk = std::min<int64_t>(K, (int64_t)idx.size());
|
||||
std::partial_sort(idx.begin(), idx.begin() + kk, idx.end(), [&](int64_t p, int64_t q) {
|
||||
return g[(size_t)p] > g[(size_t)q] || (g[(size_t)p] == g[(size_t)q] && p < q);
|
||||
});
|
||||
const float m = g[(size_t)idx[0]] / temp;
|
||||
if (top_p < 1.0f) {
|
||||
double cum = 0;
|
||||
int64_t keep = 1;
|
||||
for (int64_t t = 0; t < kk; ++t) {
|
||||
cum += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m)) / z;
|
||||
if (t > 0 && cum > (double)top_p) break;
|
||||
keep = t + 1;
|
||||
}
|
||||
if (keep < kk) ++g_topp_cuts;
|
||||
kk = keep;
|
||||
}
|
||||
double tot = 0;
|
||||
std::vector<double> e((size_t)kk);
|
||||
for (int64_t t = 0; t < kk; ++t) {
|
||||
@@ -6493,16 +6462,26 @@ int ref_pick(const std::vector<float>& lg, int64_t V, int64_t lane_row, int rep,
|
||||
void cfg_topk_cases(const Plugin& pl) {
|
||||
const RadKernelInfo* r = find(pl, "cfg_topk_sample");
|
||||
if (!r) { ok("cfg_topk_sample", false, "row absent"); return; }
|
||||
struct C { int64_t V; int rep; bool hist, cfgs; int64_t sup_lo, sup_hi, cond_k; float temp; };
|
||||
struct C {
|
||||
int64_t V; int rep; bool hist, cfgs; int64_t sup_lo, sup_hi, cond_k; float temp;
|
||||
float top_p = 1.0f; int64_t K = 50;
|
||||
};
|
||||
/* The last two are Fish Audio's draws (arch/fishomni): its main pick over eos and 4096
|
||||
* semantic ids at temperature 0.7, nucleus 0.7, top 30, and its repetition-aware redraw at 1.0,
|
||||
* 0.95, 30. */
|
||||
for (const C& c : { C{ 2052, 2, true, true, 2048, 2051, 0, 0.9f },
|
||||
C{ 2051, 1, true, false, 2048, 2051, 0, 0.9f },
|
||||
C{ 2051, 2, false, true, 2048, 2051, 0, 0.9f },
|
||||
C{ 16385, 2, false, false, 0, 0, 50, 1.0f } }) {
|
||||
const int64_t n = 3, lanes = 4, K = 50;
|
||||
const std::string nm = fmt("cfg_topk_sample V %lld rep %d%s%s sup [%lld, %lld) cond_k %lld",
|
||||
C{ 16385, 2, false, false, 0, 0, 50, 1.0f },
|
||||
C{ 4097, 1, false, false, 0, 0, 0, 0.7f, 0.7f, 30 },
|
||||
C{ 4097, 1, false, false, 0, 0, 0, 1.0f, 0.95f, 30 } }) {
|
||||
const int64_t n = 3, lanes = 4, K = c.K;
|
||||
const std::string nm = fmt("cfg_topk_sample V %lld rep %d%s%s sup [%lld, %lld) cond_k %lld"
|
||||
" top_p %g k %lld",
|
||||
(long long)c.V, c.rep, c.hist ? " hist" : "",
|
||||
c.cfgs ? " per-lane cfg" : "", (long long)c.sup_lo,
|
||||
(long long)c.sup_hi, (long long)c.cond_k);
|
||||
(long long)c.sup_hi, (long long)c.cond_k, (double)c.top_p,
|
||||
(long long)K);
|
||||
std::vector<int32_t> lane = { 2, 0, 3 };
|
||||
std::vector<float> cfgv = { 1.0f, 3.0f, 4.0f };
|
||||
std::vector<uint32_t> seed = { 7u, 0u, 0x9e3779b9u, 1u, 0xdeadbeefu, 0x12345u };
|
||||
@@ -6525,6 +6504,9 @@ void cfg_topk_cases(const Plugin& pl) {
|
||||
for (size_t i = 0; i < lg.size(); ++i) {
|
||||
const float v = rnd() * 6.0f;
|
||||
lg[i] = (i % 97 == 0) ? 5.95f : v;
|
||||
/* About 19 peaks a row hold most of the mass, so the nucleus ends inside the top
|
||||
* 30 and the cut is what decides the pick. */
|
||||
if (c.top_p < 1.0f && i % 211 == 5) lg[i] = 12.0f + 4.0f * rnd();
|
||||
}
|
||||
void* dlg = up_f32(lg);
|
||||
std::vector<int32_t> frame((size_t)n, f);
|
||||
@@ -6537,7 +6519,7 @@ void cfg_topk_cases(const Plugin& pl) {
|
||||
PI("rep", c.rep), PI("cond_k", c.cond_k), PF("cfg", 1.5),
|
||||
PF("temp", c.temp), PI("stream", 3), PS("dtype", "f32"),
|
||||
PI("sup_lo", c.sup_lo), PI("sup_hi", c.sup_hi),
|
||||
PF("penalty", 1.1) };
|
||||
PF("penalty", 1.1), PF("top_p", c.top_p) };
|
||||
const int rc = launch(r, { T(dlg, RAD_F32, { c.rep * n, c.V }), T(dseed, RAD_U32, { n, 2 }),
|
||||
T(dfr, RAD_I32, { n }), T(dids, RAD_I32, { c.rep * n }), tcfg,
|
||||
tlane, thist },
|
||||
@@ -6550,7 +6532,8 @@ void cfg_topk_cases(const Plugin& pl) {
|
||||
const int want = ref_pick(lg, c.V, i, c.rep, c.cfgs ? cfgv[(size_t)i] : 1.5f, K,
|
||||
c.cond_k, c.temp, c.sup_lo, c.sup_hi, 1.1f,
|
||||
c.hist ? &hist : nullptr,
|
||||
c.hist ? lane[(size_t)i] * c.V : -1, sd, f, 3);
|
||||
c.hist ? lane[(size_t)i] * c.V : -1, sd, f, 3,
|
||||
c.top_p);
|
||||
for (int t = 0; t < c.rep; ++t)
|
||||
if (got[(size_t)(c.rep * i + t)] != want) ++wrong;
|
||||
}
|
||||
@@ -6558,12 +6541,64 @@ void cfg_topk_cases(const Plugin& pl) {
|
||||
}
|
||||
ok((nm + " picks").c_str(), wrong == 0, fmt("%lld of %lld picks differ", (long long)wrong,
|
||||
(long long)(4 * c.rep * n)));
|
||||
if (c.top_p < 1.0f) {
|
||||
ok((nm + " cuts").c_str(), g_topp_cuts > 0, "the nucleus never ended inside the top k");
|
||||
g_topp_cuts = 0;
|
||||
}
|
||||
if (c.hist)
|
||||
ok((nm + " history").c_str(), hist_wrong == 0,
|
||||
fmt("%lld history entries differ", (long long)hist_wrong));
|
||||
}
|
||||
}
|
||||
|
||||
/* ras_pick over four picks of three lanes, the first clearing their windows: the picks and the
|
||||
* windows against libref's rule on the host, exactly. Draws repeat often (a band of 6 ids) so the
|
||||
* redraw is exercised, and one is outside [lo, hi) (never redrawn). */
|
||||
void ras_pick_cases(const Plugin& pl) {
|
||||
const RadKernelInfo* r = find(pl, "ras_pick");
|
||||
if (!r) { ok("ras_pick", false, "row absent"); return; }
|
||||
const int64_t n = 3, lanes = 4, W = 4, lo = 1, hi = 6;
|
||||
std::vector<int32_t> lane = { 2, 0, 3 };
|
||||
std::vector<int32_t> hist((size_t)(lanes * W), 5);
|
||||
void* dlane = up_i32(lane);
|
||||
void* dhist = up_i32(hist);
|
||||
void* dids = dalloc((size_t)n * 4);
|
||||
int64_t wrong = 0;
|
||||
for (int step = 0; step < 4; ++step) {
|
||||
std::vector<int32_t> first((size_t)n), alt((size_t)n);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
first[(size_t)i] = (int32_t)((step * 2 + i * 3) % 7); /* 0 is outside [lo, hi) */
|
||||
alt[(size_t)i] = (int32_t)(10 + step * 3 + i);
|
||||
}
|
||||
void* df = up_i32(first);
|
||||
void* da = up_i32(alt);
|
||||
const int clear = step == 0 ? 1 : 0;
|
||||
std::vector<RadParam> ps = { PI("M", n), PI("win", W), PI("lo", lo), PI("hi", hi),
|
||||
PI("rep", 1), PI("clear", clear) };
|
||||
const int rc = launch(r, { T(df, RAD_I32, { n }), T(da, RAD_I32, { n }),
|
||||
T(dlane, RAD_I32, { n }), T(dhist, RAD_I32, { lanes, W }),
|
||||
T(dids, RAD_I32, { n }) },
|
||||
ps);
|
||||
if (rc != RAD_OK) { ok("ras_pick", false, "rc " + std::to_string(rc)); return; }
|
||||
const std::vector<int32_t> got = down_i32(dids, (size_t)n);
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
int32_t* h = hist.data() + lane[(size_t)i] * W;
|
||||
if (clear) for (int64_t w = 0; w < W; ++w) h[w] = -1;
|
||||
int32_t pick = first[(size_t)i];
|
||||
if (pick >= lo && pick < hi)
|
||||
for (int64_t w = 0; w < W; ++w)
|
||||
if (h[w] == pick) { pick = alt[(size_t)i]; break; }
|
||||
for (int64_t w = 0; w + 1 < W; ++w) h[w] = h[w + 1];
|
||||
h[W - 1] = pick;
|
||||
if (got[(size_t)i] != pick) ++wrong;
|
||||
}
|
||||
}
|
||||
ok("ras_pick picks", wrong == 0, fmt("%lld of %lld picks differ", (long long)wrong,
|
||||
(long long)(4 * n)));
|
||||
ok("ras_pick windows", differ(down_i32(dhist, hist.size()), hist) == 0,
|
||||
"the windows differ from libref's rule");
|
||||
}
|
||||
|
||||
/* rvq_embed: libref's two roundings, the single rounding over bf16 and f32 tables into a bf16 or
|
||||
* f32 row, codes read as a block of a wider frame-major history (strides other than the dense
|
||||
* plane's), and a first code outside its table leaving the row unwritten. Exact. */
|
||||
@@ -6571,9 +6606,12 @@ void rvq_embed_cases(const Plugin& pl) {
|
||||
const RadKernelInfo* r = find(pl, "rvq_embed_bf16");
|
||||
if (!r) { ok("rvq_embed_bf16", false, "row absent"); return; }
|
||||
const int64_t D = 96, K = 5, voc = 11, off0 = 3, rows = 6, lanes = 2, stride = 9;
|
||||
struct C { int round1; bool f32tab, f32y, block; };
|
||||
/* The last case clamps every code at 8 (`clamp`): codes 8..10 read row 7, and the later code
|
||||
* past t1 reads its codebook's row 7 instead of nothing. */
|
||||
struct C { int round1; bool f32tab, f32y, block; int clamp = 0; };
|
||||
for (const C& c : { C{ 0, false, false, false }, C{ 1, false, false, false },
|
||||
C{ 1, true, true, true }, C{ 1, false, true, true } }) {
|
||||
C{ 1, true, true, true }, C{ 1, false, true, true },
|
||||
C{ 0, false, false, false, 8 } }) {
|
||||
std::vector<float> t0 = randv((size_t)((voc + off0) * D), 1.0f);
|
||||
std::vector<float> t1 = randv((size_t)((K - 1) * voc * D), 1.0f);
|
||||
void* d0 = c.f32tab ? up_f32(t0) : up_bf16(t0);
|
||||
@@ -6607,10 +6645,12 @@ void rvq_embed_cases(const Plugin& pl) {
|
||||
const float scale = 0.5f;
|
||||
std::vector<RadParam> ps = { PI("M", rows), PI("n_embd", D), PI("n_codes", K),
|
||||
PI("vocab", voc), PI("off0", off0), PF("scale", scale),
|
||||
PS("dtype", c.f32y ? "f32" : "bf16"), PI("round", c.round1) };
|
||||
const std::string nm = fmt("rvq_embed_bf16 round %d %s tables -> %s%s", c.round1,
|
||||
PS("dtype", c.f32y ? "f32" : "bf16"), PI("round", c.round1),
|
||||
PI("clamp", c.clamp) };
|
||||
const std::string nm = fmt("rvq_embed_bf16 round %d %s tables -> %s%s clamp %d", c.round1,
|
||||
c.f32tab ? "f32" : "bf16", c.f32y ? "f32" : "bf16",
|
||||
c.block ? ", codes a history block" : "");
|
||||
c.block ? ", codes a history block" : "", c.clamp);
|
||||
auto cl = [&](int64_t v) { return c.clamp > 0 && v > c.clamp - 1 ? c.clamp - 1 : v; };
|
||||
const int rc = launch(r, { tc, T(d0, c.f32tab ? RAD_F32 : RAD_BF16, { voc + off0, D }),
|
||||
T(d1, c.f32tab ? RAD_F32 : RAD_BF16, { (K - 1) * voc, D }),
|
||||
T(dy, ydt, { rows, D }) },
|
||||
@@ -6618,13 +6658,13 @@ void rvq_embed_cases(const Plugin& pl) {
|
||||
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
|
||||
std::vector<float> want = sentinel;
|
||||
for (int64_t i = 0; i < rows; ++i) {
|
||||
const int64_t c0 = code[(size_t)i] + off0;
|
||||
const int64_t c0 = cl(code[(size_t)i]) + off0;
|
||||
if (c0 < 0 || c0 >= voc + off0) continue;
|
||||
for (int64_t d = 0; d < D; ++d) {
|
||||
const float e0 = t0[(size_t)(c0 * D + d)];
|
||||
float acc = c.round1 ? e0 : 0.0f;
|
||||
for (int64_t k = 1; k < K; ++k) {
|
||||
const int64_t ck = code[(size_t)(k * rows + i)] + (k - 1) * voc;
|
||||
const int64_t ck = cl(code[(size_t)(k * rows + i)]) + (k - 1) * voc;
|
||||
if (ck >= 0 && ck < (K - 1) * voc) acc += t1[(size_t)(ck * D + d)];
|
||||
}
|
||||
const float s = c.round1 ? acc : bfr(e0 + bfr(acc));
|
||||
@@ -6638,6 +6678,104 @@ void rvq_embed_cases(const Plugin& pl) {
|
||||
}
|
||||
}
|
||||
|
||||
/* vq_encode at Fish Audio's codec geometry (n 1024, codes of dimension 8, a semantic codebook of
|
||||
* 4096 and a residual one of 1024) and an odd one, bf16 and f32 rows, f32 and bf16 weights, the
|
||||
* codes a dense row and a strided column: each code against the host's cosine argmax in double (a
|
||||
* pick within 1e-5 of the best score is a near tie, not a miss), the row after against
|
||||
* x - out_w cb[code] - out_b for the code the kernel took. */
|
||||
void vq_encode_cases(const Plugin& pl) {
|
||||
const RadKernelInfo* r = find(pl, "vq_encode");
|
||||
if (!r) { ok("vq_encode", false, "row absent"); return; }
|
||||
struct C { int64_t n, dim, bins, M; bool f32x, f32w; int64_t cst; };
|
||||
for (const C& c : { C{ 1024, 8, 4096, 37, false, true, 1 }, C{ 1024, 8, 1024, 37, false, true, 1 },
|
||||
C{ 1024, 8, 1024, 20, true, true, 3 }, C{ 1024, 8, 4096, 9, false, false, 1 },
|
||||
C{ 200, 5, 300, 11, true, false, 2 } }) {
|
||||
const int64_t n = c.n, dim = c.dim, bins = c.bins, M = c.M;
|
||||
std::vector<float> x = randv((size_t)(M * n), 1.0f);
|
||||
std::vector<float> iw = randv((size_t)(dim * n), 1.0f / std::sqrt((float)n));
|
||||
std::vector<float> ib = randv((size_t)dim, 0.1f), cb = randv((size_t)(bins * dim), 1.0f);
|
||||
std::vector<float> ow = randv((size_t)(n * dim), 0.3f), ob = randv((size_t)n, 0.1f);
|
||||
/* A bf16 upload rounds the host copy to what the device holds. */
|
||||
const uint32_t wdt = c.f32w ? RAD_F32 : RAD_BF16, xdt = c.f32x ? RAD_F32 : RAD_BF16;
|
||||
auto upw = [&](std::vector<float>& w) { return c.f32w ? up_f32(w) : up_bf16(w); };
|
||||
void* dx = c.f32x ? up_f32(x) : up_bf16(x);
|
||||
const std::vector<int32_t> plane((size_t)(M * c.cst), -7);
|
||||
void* dc = up_i32(plane);
|
||||
RadTensor tc = T(dc, RAD_I32, { M });
|
||||
tc.stride[0] = c.cst;
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("n", n), PI("dim", dim), PI("bins", bins),
|
||||
PS("dtype", c.f32x ? "f32" : "bf16") };
|
||||
const std::string nm = fmt("vq_encode n %lld dim %lld bins %lld, %s rows, %s weights, "
|
||||
"code stride %lld", (long long)n, (long long)dim,
|
||||
(long long)bins, c.f32x ? "f32" : "bf16",
|
||||
c.f32w ? "f32" : "bf16", (long long)c.cst);
|
||||
const int rc = launch(r, { T(dx, xdt, { M, n }), T(upw(iw), wdt, { dim, n }),
|
||||
T(upw(ib), wdt, { dim }), T(upw(cb), wdt, { bins, dim }),
|
||||
T(upw(ow), wdt, { n, dim }), T(upw(ob), wdt, { n }), tc },
|
||||
ps);
|
||||
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
|
||||
const std::vector<int32_t> got = down_i32(dc, plane.size());
|
||||
const std::vector<float> gx = c.f32x ? down_f32(dx, x.size()) : down_bf16(dx, x.size());
|
||||
int64_t miss = 0, near = 0, gaps = 0;
|
||||
std::vector<float> want = x;
|
||||
for (int64_t i = 0; i < M; ++i) {
|
||||
std::vector<double> e((size_t)dim);
|
||||
double ss = 0;
|
||||
for (int64_t j = 0; j < dim; ++j) {
|
||||
double acc = ib[(size_t)j];
|
||||
for (int64_t d = 0; d < n; ++d)
|
||||
acc += (double)iw[(size_t)(j * n + d)] * x[(size_t)(i * n + d)];
|
||||
e[(size_t)j] = acc;
|
||||
ss += acc * acc;
|
||||
}
|
||||
const double en = std::max(std::sqrt(ss), 1e-12);
|
||||
auto score = [&](int64_t k) {
|
||||
const float* row = cb.data() + k * dim;
|
||||
double cs = 0, dot = 0;
|
||||
for (int64_t j = 0; j < dim; ++j) cs += (double)row[j] * row[j];
|
||||
const double cn = std::max(std::sqrt(cs), 1e-12);
|
||||
for (int64_t j = 0; j < dim; ++j) dot += e[(size_t)j] / en * (row[j] / cn);
|
||||
return dot;
|
||||
};
|
||||
int64_t best = 0;
|
||||
double bs = -1e300;
|
||||
for (int64_t k = 0; k < bins; ++k) {
|
||||
const double s = score(k);
|
||||
if (s > bs) { bs = s; best = k; }
|
||||
}
|
||||
for (int64_t g = 1; g < c.cst; ++g)
|
||||
if (got[(size_t)(i * c.cst + g)] != -7) ++gaps;
|
||||
const int64_t k = got[(size_t)(i * c.cst)];
|
||||
if (k < 0 || k >= bins) { ++miss; continue; }
|
||||
if (k != best) {
|
||||
if (bs - score(k) <= 1e-5) ++near;
|
||||
else ++miss;
|
||||
}
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
double q = ob[(size_t)d];
|
||||
for (int64_t j = 0; j < dim; ++j)
|
||||
q += (double)ow[(size_t)(d * dim + j)] * cb[(size_t)(k * dim + j)];
|
||||
want[(size_t)(i * n + d)] = (float)(x[(size_t)(i * n + d)] - q);
|
||||
}
|
||||
}
|
||||
ok((nm + " codes").c_str(), miss == 0 && gaps == 0,
|
||||
fmt("%lld of %lld codes wrong (%lld near ties taken), %lld gaps of the strided codes "
|
||||
"written", (long long)miss, (long long)M, (long long)near, (long long)gaps));
|
||||
if (c.f32x) {
|
||||
/* f32 rows: against the f32 rows themselves (check() rounds its reference to bf16). */
|
||||
double e = 0, r2 = 0;
|
||||
for (size_t i = 0; i < want.size(); ++i) {
|
||||
e += ((double)gx[i] - want[i]) * ((double)gx[i] - want[i]);
|
||||
r2 += (double)want[i] * want[i];
|
||||
}
|
||||
const double rl = std::sqrt(e / std::max(r2, 1e-30));
|
||||
ok(fmt("%s residual (rel_l2 %.3g, bound 1e-05)", nm.c_str(), rl).c_str(), rl <= 1e-5);
|
||||
} else {
|
||||
check(nm + " residual", gx, want, 1e-2);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/* frame_store: each lane's codes into its block of the history, frames before `skip` and lanes
|
||||
* whose status ended the piece left alone. Exact. */
|
||||
void frame_store_cases(const Plugin& pl) {
|
||||
@@ -9894,36 +10032,43 @@ void gate_add_none_case(const Plugin& pl) {
|
||||
|
||||
/* conv1d at f32 at a BigVGAN's geometries: conv_pre's 2048 -> 1024 over 7 taps, the AMP blocks'
|
||||
* dilated 3/7/11 taps with the residual the output itself, the direct kernel's 8 channels and the
|
||||
* final conv's one with its clamp. Two sequences, so a tap crossing a sequence's edge reads zero. */
|
||||
* final conv's one with its clamp; then a DAC encoder's strided causal downsampling (kernels of two
|
||||
* strides, 2 to 8, and the quantizer's of one). Two sequences, so a tap crossing a sequence's edge
|
||||
* reads zero; a strided case's sequences are whole strides. */
|
||||
void conv1d_f32_cases(const Plugin& pl) {
|
||||
const RadKernelInfo* r = find(pl, "conv1d_f32");
|
||||
if (!r) { ok("conv1d_f32", false, "row absent"); return; }
|
||||
struct C { int64_t cin, cout, k, dil, M0, M1; int act, bias, res; }; /* res 2: y itself */
|
||||
struct C { int64_t cin, cout, k, dil, M0, M1; int act, bias, res; int64_t st = 1; }; /* res 2: y itself */
|
||||
for (const C& c : { C{ 2048, 1024, 7, 1, 9, 15, 0, 1, 0 }, C{ 64, 128, 7, 1, 37, 60, 0, 1, 0 },
|
||||
C{ 32, 32, 11, 5, 70, 41, 0, 1, 2 }, C{ 16, 16, 3, 3, 50, 77, 0, 1, 1 },
|
||||
C{ 48, 40, 3, 1, 33, 30, 1, 1, 0 }, C{ 8, 8, 11, 5, 90, 64, 0, 1, 2 },
|
||||
C{ 8, 1, 7, 1, 100, 99, 2, 0, 0 }, C{ 64, 64, 11, 1, 200, 137, 2, 1, 2 } }) {
|
||||
C{ 8, 1, 7, 1, 100, 99, 2, 0, 0 }, C{ 64, 64, 11, 1, 200, 137, 2, 1, 2 },
|
||||
C{ 64, 128, 4, 1, 36, 60, 0, 1, 0, 2 }, C{ 128, 256, 8, 1, 64, 40, 0, 1, 1, 4 },
|
||||
C{ 256, 512, 16, 1, 96, 136, 0, 1, 0, 8 }, C{ 8, 8, 16, 1, 32, 48, 0, 1, 0, 8 },
|
||||
C{ 64, 64, 2, 1, 50, 30, 0, 1, 2, 2 } }) {
|
||||
const std::vector<int32_t> cu = { 0, (int32_t)c.M0, (int32_t)(c.M0 + c.M1) };
|
||||
const int64_t M = c.M0 + c.M1;
|
||||
const int64_t M = c.M0 + c.M1, MO = M / c.st;
|
||||
std::vector<float> x = randv((size_t)(M * c.cin), 1.0f);
|
||||
std::vector<float> w = randv((size_t)(c.cout * c.cin * c.k), 1.0f / std::sqrt((float)(c.cin * c.k)));
|
||||
std::vector<float> b = randv((size_t)c.cout, 0.5f), res = randv((size_t)(M * c.cout), 0.5f);
|
||||
std::vector<float> b = randv((size_t)c.cout, 0.5f), res = randv((size_t)(MO * c.cout), 0.5f);
|
||||
std::vector<RadParam> ps = { PI("M", M), PI("cin", c.cin), PI("cout", c.cout), PI("k", c.k),
|
||||
PI("dil", c.dil),
|
||||
PS("act", c.act == 1 ? "tanh" : c.act == 2 ? "clamp" : "none"),
|
||||
PS("dtype", "f32") };
|
||||
const std::string nm = fmt("conv1d_f32 cin %lld cout %lld k %lld dil %lld%s%s%s", (long long)c.cin,
|
||||
if (c.st > 1) { ps.push_back(PI("causal", 1)); ps.push_back(PI("stride", c.st)); }
|
||||
const std::string nm = fmt("conv1d_f32 cin %lld cout %lld k %lld dil %lld%s%s%s%s", (long long)c.cin,
|
||||
(long long)c.cout, (long long)c.k, (long long)c.dil,
|
||||
c.st > 1 ? fmt(" causal stride %lld", (long long)c.st).c_str() : "",
|
||||
c.bias ? " +bias" : "", c.res == 2 ? " +res in place" : c.res ? " +res" : "",
|
||||
c.act == 1 ? " tanh" : c.act == 2 ? " clamp" : "");
|
||||
void* dw = stored_weight_f32(r, ps, w, c.cout, c.cin * c.k, nm.c_str());
|
||||
if (!dw) continue;
|
||||
void* dx = up_f32(x);
|
||||
void* db = up_f32(b);
|
||||
void* dy = up_f32(c.res == 2 ? res : std::vector<float>((size_t)(M * c.cout), 0.0f));
|
||||
void* dy = up_f32(c.res == 2 ? res : std::vector<float>((size_t)(MO * c.cout), 0.0f));
|
||||
void* dr = up_f32(res);
|
||||
RadTensor ty = T(dy, RAD_F32, { M, c.cout });
|
||||
RadTensor tr = c.res == 2 ? ty : T(dr, RAD_F32, { M, c.cout });
|
||||
RadTensor ty = T(dy, RAD_F32, { MO, c.cout });
|
||||
RadTensor tr = c.res == 2 ? ty : T(dr, RAD_F32, { MO, c.cout });
|
||||
RadTensor tb = T(db, RAD_F32, { c.cout });
|
||||
if (!c.res) absent(tr);
|
||||
if (!c.bias) absent(tb);
|
||||
@@ -9932,14 +10077,14 @@ void conv1d_f32_cases(const Plugin& pl) {
|
||||
T(up_i32(cu), RAD_I32, { 3 }), tr, ty, tb },
|
||||
ps);
|
||||
if (rc != RAD_OK) { ok(nm.c_str(), false, "rc " + std::to_string(rc)); continue; }
|
||||
const int64_t pad = c.dil * (c.k - 1) / 2;
|
||||
std::vector<float> want((size_t)(M * c.cout));
|
||||
for (int64_t row = 0; row < M; ++row) {
|
||||
const int64_t e = seq_of(cu, row), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1];
|
||||
const int64_t pad = c.st > 1 ? c.dil * (c.k - 1) + 1 - c.st : c.dil * (c.k - 1) / 2;
|
||||
std::vector<float> want((size_t)(MO * c.cout));
|
||||
for (int64_t row = 0; row < MO; ++row) {
|
||||
const int64_t e = seq_of(cu, row * c.st), s0 = cu[(size_t)e], s1 = cu[(size_t)e + 1];
|
||||
for (int64_t co = 0; co < c.cout; ++co) {
|
||||
double acc = 0;
|
||||
for (int64_t kk = 0; kk < c.k; ++kk) {
|
||||
const int64_t ir = row + kk * c.dil - pad;
|
||||
const int64_t ir = row * c.st + kk * c.dil - pad;
|
||||
if (ir < s0 || ir >= s1) continue;
|
||||
for (int64_t ci = 0; ci < c.cin; ++ci)
|
||||
acc += (double)w[(size_t)((co * c.cin + ci) * c.k + kk)] * x[(size_t)(ir * c.cin + ci)];
|
||||
@@ -12903,6 +13048,8 @@ static void fp8_real(const Plugin& pl, const char* file, long long woff, long lo
|
||||
static void perf_row(const Plugin& pl, const char* name, std::vector<RadTensor> ts,
|
||||
std::vector<RadParam> ps, void* wbase, size_t wbytes, int copies,
|
||||
double bytes, int iters, int widx = 2, const char* point = nullptr) {
|
||||
/* R4D_PERF_ONLY=<row>: time that row alone (a sweep over one row skips the rest). */
|
||||
if (const char* only = std::getenv("R4D_PERF_ONLY"); only && *only && std::strcmp(only, name)) return;
|
||||
const RadKernelInfo* r = find(pl, name);
|
||||
if (!r) { std::printf(" %-22s row absent\n", name); return; }
|
||||
/* The label is the row, or the tuned point in a sweep. `ps` already carries that point; this
|
||||
@@ -14599,25 +14746,28 @@ static void mla_check(const Plugin& pl, int64_t rows, int64_t heads, int64_t blo
|
||||
const int rc = oracle->launch(&args, nullptr);
|
||||
ok("MLA host oracle", rc == RAD_OK);
|
||||
args.t = device.data();
|
||||
/* The head-tiled row serves tiles of 16 heads or of 8 heads from two requests (cMlaMatrix);
|
||||
* other head counts must be refused rather than computed. */
|
||||
if (std::strstr(name, "matrix") && heads % 8) {
|
||||
/* The head-tiled row serves tiles of 16 heads or of 8 heads from two requests (cMlaMatrix),
|
||||
* the rows row groups of 32 or 64 heads; other head counts must be refused rather than
|
||||
* computed. */
|
||||
const bool by_rows = std::strstr(name, "rows") != nullptr;
|
||||
auto* const pin = by_rows ? pl.pin_mla_rows : pl.pin_mla;
|
||||
if ((std::strstr(name, "matrix") && heads % 8) || (by_rows && heads % 32)) {
|
||||
args.scratch = nullptr;
|
||||
args.scratch_bytes = 0;
|
||||
const int grc = row->launch(&args, nullptr);
|
||||
st_stream_sync(nullptr);
|
||||
ok(fmt("MLA %s refuses heads=%lld (not a multiple of 8) with RAD_E_UNSUPPORTED, no launch",
|
||||
name, (long long)heads)
|
||||
ok(fmt("MLA %s refuses heads=%lld (not a multiple of %d) with RAD_E_UNSUPPORTED, no launch",
|
||||
name, (long long)heads, by_rows ? 32 : 8)
|
||||
.c_str(),
|
||||
grc == RAD_E_UNSUPPORTED);
|
||||
dlclose(ref);
|
||||
return;
|
||||
}
|
||||
if (form && pl.pin_mla) pl.pin_mla(form);
|
||||
if (form && pin) pin(form);
|
||||
const int64_t need = row->scratch ? row->scratch(&args) : 0;
|
||||
void* scratch = need > 0 ? dalloc((size_t)need + 256) : nullptr;
|
||||
if (need <= 0 || !scratch) {
|
||||
if (form && pl.pin_mla) pl.pin_mla(0);
|
||||
if (form && pin) pin(0);
|
||||
ok("MLA scratch allocation", false);
|
||||
dlclose(ref);
|
||||
return;
|
||||
@@ -14686,7 +14836,7 @@ static void mla_check(const Plugin& pl, int64_t rows, int64_t heads, int64_t blo
|
||||
versus, base, name, base / us, shape);
|
||||
}
|
||||
}
|
||||
if (form && pl.pin_mla) pl.pin_mla(0);
|
||||
if (form && pin) pin(0);
|
||||
dlclose(ref);
|
||||
}
|
||||
|
||||
@@ -14796,17 +14946,19 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads,
|
||||
PS("dtype", "bf16") };
|
||||
std::vector<uint16_t> base, rule;
|
||||
auto run = [&](const char* name, int form, const char* label) {
|
||||
const bool by_rows = std::strstr(name, "rows") != nullptr;
|
||||
auto* const pin = by_rows ? pl.pin_mla_rows : pl.pin_mla;
|
||||
const RadKernelInfo* r = find(pl, name);
|
||||
if (!r) {
|
||||
std::printf(" %-34s row absent\n", label);
|
||||
return;
|
||||
}
|
||||
if (form >= 0) {
|
||||
if (!pl.pin_mla) {
|
||||
if (!pin) {
|
||||
std::printf(" %-34s no pin hook\n", label);
|
||||
return;
|
||||
}
|
||||
pl.pin_mla(form);
|
||||
pin(form);
|
||||
}
|
||||
RadArgs a;
|
||||
std::memset(&a, 0, sizeof(a));
|
||||
@@ -14823,7 +14975,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads,
|
||||
const int rc = r->launch(&a, nullptr);
|
||||
if (rc != RAD_OK || st_stream_sync(nullptr) != hipSuccess) {
|
||||
std::printf(" %-34s rc=%d (shape not served)\n", label, rc);
|
||||
if (form >= 0) pl.pin_mla(0);
|
||||
if (form >= 0) pin(0);
|
||||
return;
|
||||
}
|
||||
std::vector<uint16_t> got(qh.size());
|
||||
@@ -14844,7 +14996,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads,
|
||||
st_ev_destroy(w1);
|
||||
}
|
||||
const double us = st_time_us([&](int) { r->launch(&a, nullptr); }, iters, nullptr);
|
||||
if (form >= 0) pl.pin_mla(0);
|
||||
if (form >= 0) pin(0);
|
||||
char diff[192] = "reference";
|
||||
if (base.empty())
|
||||
base = got;
|
||||
@@ -14870,7 +15022,7 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads,
|
||||
}
|
||||
if (form == 0) rule = got;
|
||||
std::printf(" %-34s %10.2f us %7.2f TFLOP/s %s\n", label, us, flops / (us * 1e6), diff);
|
||||
if (form >= 0 && pl.mla_stats) {
|
||||
if (form >= 0 && !by_rows && pl.mla_stats) {
|
||||
/* One more launch with the conflict counters on, outside the timing. */
|
||||
ScopedEnv counting("RADIANCE_MLA_CONFLICT_STATS", "1");
|
||||
unsigned long long v[3];
|
||||
@@ -14899,6 +15051,11 @@ static void mla_perf(const Plugin& pl, int64_t M, int64_t blocks, int64_t heads,
|
||||
run("mla_attn_matrix_bf16", 0, "matrix 16 heads, vector load");
|
||||
run("mla_attn_matrix_bf16", 1, "matrix 16 heads, element load");
|
||||
}
|
||||
if (heads == 64) {
|
||||
run("mla_attn_rows_bf16", 0, "rows 64 heads, vector load");
|
||||
run("mla_attn_rows_bf16", 1, "rows 64 heads, element load");
|
||||
run("mla_attn_rows_bf16", 2, "rows 32 heads, vector load");
|
||||
}
|
||||
}
|
||||
|
||||
static void kda_check(const Plugin& pl, const char* mode, bool cold, int accepted_count,
|
||||
@@ -18321,7 +18478,7 @@ static void fp8_perf(const Plugin& pl, int64_t N, int64_t K, int64_t M, int iter
|
||||
/* The lm head, a decode GEMM too. Its weight is [N][K + 2*nkb] E4M3 with each row's bf16
|
||||
* scales in its tail (r4d_fp8_layout.cpp), so it has its own buffer, and the weight is the
|
||||
* second operand. */
|
||||
if (M <= 64) {
|
||||
if (M <= 256) {
|
||||
const int64_t lstride = r4d_fp8::lm_row_bytes(K);
|
||||
const size_t lwb = (size_t)N * (size_t)lstride;
|
||||
int lcopies = (int)(((size_t)768 << 20) / lwb) + 1;
|
||||
@@ -26982,6 +27139,12 @@ static void device_phase(const Plugin& pl) {
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 640, 2, true);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 400, 640, 4, true);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 2100, 512, 2560, 0, true);
|
||||
/* The plain kernel at a whole row of blocks (not the part kernel, which takes a last row of
|
||||
* 1..160 under 1024 rows): TN=4 forced and by the rule from 1024 rows, and TN=2 at the
|
||||
* 64-wide slab (K not a multiple of 128). */
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 256, 400, 640, 4, true);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 1024, 4096, 640, 0, true);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 512, 272, 576, 2, true);
|
||||
/* K not a multiple of 128: the TN=2 kernel takes the 64-wide slab. */
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 576, 2);
|
||||
mxfp4a8_numeric(pl, "gemm_mxfp4a8_tiled", 300, 272, 576, 2, true);
|
||||
@@ -27394,7 +27557,9 @@ static void device_phase(const Plugin& pl) {
|
||||
if (sel("conv_t1d_bf16")) au::conv_t1d_cases(pl);
|
||||
if (sel("snake_bf16")) au::snake_cases(pl);
|
||||
if (sel("cfg_topk_sample")) au::cfg_topk_cases(pl);
|
||||
if (sel("ras_pick")) au::ras_pick_cases(pl);
|
||||
if (sel("rvq_embed_bf16")) au::rvq_embed_cases(pl);
|
||||
if (sel("vq_encode")) au::vq_encode_cases(pl);
|
||||
if (sel("frame_store")) au::frame_store_cases(pl);
|
||||
if (sel("iota")) au::iota_cases(pl);
|
||||
if (sel("sub_i32")) au::sub_i32_cases(pl);
|
||||
@@ -27721,6 +27886,26 @@ static void device_phase(const Plugin& pl) {
|
||||
for (int64_t heads : { 8, 16 }) mla_project_check(pl, rows, heads, mode, true);
|
||||
}
|
||||
}
|
||||
if (sel("mla_attn_rows_bf16")) {
|
||||
/* A rank's run of rows with all 64 heads (GLM's prefill split by rows), against the matrix
|
||||
* row on the same operands. Under 32 rows the rule runs the matrix kernel, so the rows
|
||||
* kernel is pinned there (form 3). */
|
||||
for (int requests : { 1, 2, 7, 33 })
|
||||
for (int64_t blocks : { 17, 513 })
|
||||
mla_check(pl, requests, 64, blocks, "mla_attn_rows_bf16", MlaFill::ragged,
|
||||
"mla_attn_matrix_bf16", requests < 32 ? 3 : 0);
|
||||
mla_check(pl, 7, 64, 513, "mla_attn_rows_bf16", MlaFill::full, "mla_attn_matrix_bf16", 3);
|
||||
mla_check(pl, 2, 64, 513, "mla_attn_rows_bf16", MlaFill::prefill, "mla_attn_matrix_bf16", 3);
|
||||
mla_check(pl, 33, 64, 513, "mla_attn_rows_bf16", MlaFill::prefill, "mla_attn_matrix_bf16");
|
||||
for (int64_t swaps : { 0, 4, 16, 64 })
|
||||
mla_check(pl, 33, 64, 65, "mla_attn_rows_bf16", MlaFill::topk, "mla_attn_matrix_bf16",
|
||||
0, swaps);
|
||||
mla_check(pl, 7, 64, 513, "mla_attn_rows_bf16", MlaFill::prefill, nullptr, 1);
|
||||
mla_check(pl, 33, 64, 65, "mla_attn_rows_bf16", MlaFill::topk, nullptr, 2, 16);
|
||||
mla_check(pl, 7, 64, 65, "mla_attn_rows_bf16", MlaFill::topk, "mla_attn_matrix_bf16", 0, 4);
|
||||
mla_check(pl, 7, 32, 65, "mla_attn_rows_bf16", MlaFill::ragged, nullptr, 3);
|
||||
mla_check(pl, 4, 40, 17, "mla_attn_rows_bf16");
|
||||
}
|
||||
if (sel("mla_attn_matrix_bf16")) {
|
||||
mla_check(pl, 7, 16, 17, "mla_attn_matrix_bf16");
|
||||
mla_check(pl, 33, 16, 17, "mla_attn_matrix_bf16");
|
||||
@@ -28009,6 +28194,11 @@ static void device_phase(const Plugin& pl) {
|
||||
for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)13, (int64_t)32, (int64_t)33,
|
||||
(int64_t)64 })
|
||||
fp8_logits_numeric(pl, 5120, 5120, M);
|
||||
/* Past 64 rows a pass is the two-half tile (MH = 2), whose second half may be partial; past
|
||||
* 128 a second pass follows. */
|
||||
for (const int64_t M : { (int64_t)65, (int64_t)80, (int64_t)128, (int64_t)150 })
|
||||
fp8_logits_numeric(pl, 5120, 5120, M);
|
||||
fp8_logits_numeric(pl, 2560, 2560, 100);
|
||||
/* And K = 2560, the padded row: its stored width 2600 is not a multiple of 16, so
|
||||
* r4d_fp8_lm.h rounds it to 2608 (5120's 5200 needs no pad). M = 1 takes the matvec, M = 8
|
||||
* the WMMA tile, which index the row differently. */
|
||||
@@ -28024,7 +28214,7 @@ static void device_phase(const Plugin& pl) {
|
||||
}
|
||||
/* The int8 head over the same stored row: both forms, and the padded K = 2560 row. */
|
||||
if (sel("logits_gemm_i8") || sel("logit_rerank_i8")) {
|
||||
for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)33, (int64_t)64 })
|
||||
for (const int64_t M : { (int64_t)1, (int64_t)8, (int64_t)33, (int64_t)64, (int64_t)100 })
|
||||
fp8_logits_numeric(pl, 5120, 5120, M, true);
|
||||
for (const int64_t M : { (int64_t)1, (int64_t)8 })
|
||||
fp8_logits_numeric(pl, 2560, 2560, M, true);
|
||||
|
||||
+165
-18
@@ -51,8 +51,13 @@ inline int64_t ldi(const RadTensor* t, int64_t i) {
|
||||
* them), outside of which the input reads zero (each sequence is padded on its own). w is
|
||||
* PyTorch's Conv1d weight [cout, cin, k], b [cout], `dil` the dilation and the padding
|
||||
* dil (k - 1) / 2 on each side (k odd), so a sequence keeps its length; with `causal` 1 all of it,
|
||||
* dil (k - 1), on the left (any k). `res`, when bound, is added after the bias; then `act` (none,
|
||||
* tanh, or clamp to [-1, 1], a vocoder's output clamp). f32 accumulation, one rounding. */
|
||||
* dil (k - 1), on the left (any k). A `stride` s > 1 (causal only, a reach of at least s) keeps
|
||||
* every s-th output row: the left pad is the reach less s, and a sequence of L rows (every bound a
|
||||
* whole number of strides) gives L / s, y's and res's rows the input's over s. `cu_div` reads the
|
||||
* bounds in units that many input rows apart: sequence e is input rows [cu[e] / cu_div,
|
||||
* cu[e+1] / cu_div), each bound a multiple of cu_div stride. `res`, when bound, is added after the
|
||||
* bias; then `act` (none, tanh, or clamp to [-1, 1], a vocoder's output clamp). f32
|
||||
* accumulation, one rounding. */
|
||||
int ref_conv1d(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *w = &a->t[1], *cu = &a->t[2];
|
||||
@@ -60,29 +65,38 @@ int ref_conv1d(const RadArgs* a, RadStream) {
|
||||
if (!y->data) return RAD_E_INVAL;
|
||||
const int64_t cin = p_int(a, "cin", 0), cout = p_int(a, "cout", 0), k = p_int(a, "k", 0);
|
||||
const int64_t dil = p_int(a, "dil", 1), causal = p_int(a, "causal", 0);
|
||||
const int64_t st = p_int(a, "stride", 1), cd = p_int(a, "cu_div", 1);
|
||||
const char* act = p_str(a, "act", "none");
|
||||
const bool tanh_out = act && !std::strcmp(act, "tanh");
|
||||
const bool clamp_out = act && !std::strcmp(act, "clamp");
|
||||
if (!tanh_out && !clamp_out && act && std::strcmp(act, "none")) return RAD_E_INVAL;
|
||||
if (cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || dil <= 0 ||
|
||||
causal < 0 || causal > 1)
|
||||
causal < 0 || causal > 1 || st < 1 || (st > 1 && (!causal || dil * (k - 1) + 1 < st)) ||
|
||||
cd < 1)
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t n_seq = numel(cu) - 1;
|
||||
if (n_seq <= 0) return RAD_E_SHAPE;
|
||||
const int64_t r0 = cu_at(cu, 0), r1 = cu_at(cu, n_seq);
|
||||
if (r0 < 0 || r1 <= r0 || rows_of(y, cout) < r1 || rows_of(x, cin) < r1) return RAD_E_SHAPE;
|
||||
/* A stride takes each sequence of L rows to L / stride, so every bound is a whole number of
|
||||
* strides (of cu_div units each). */
|
||||
for (int64_t e = 0; e <= n_seq; ++e)
|
||||
if (cu_at(cu, e) % (cd * st)) return RAD_E_SHAPE;
|
||||
const int64_t r0 = cu_at(cu, 0) / cd, r1 = cu_at(cu, n_seq) / cd;
|
||||
if (r0 < 0 || r1 <= r0 || rows_of(y, cout) < r1 / st || rows_of(x, cin) < r1)
|
||||
return RAD_E_SHAPE;
|
||||
if (numel(w) < cout * cin * k || (b && numel(b) < cout)) return RAD_E_SHAPE;
|
||||
if (res && rows_of(res, cout) < r1) return RAD_E_SHAPE;
|
||||
const int64_t pad = causal ? dil * (k - 1) : dil * (k - 1) / 2;
|
||||
REF_PAR_FOR((r1 - r0) * cout * cin * k)
|
||||
for (int64_t r = r0; r < r1; ++r) {
|
||||
const int64_t e = seq_of(cu, n_seq, r);
|
||||
const int64_t s0 = cu_at(cu, e), s1 = cu_at(cu, e + 1);
|
||||
if (res && rows_of(res, cout) < r1 / st) return RAD_E_SHAPE;
|
||||
/* Causal: the reach is dil (k - 1) + 1 input rows and the left pad that less the stride, so
|
||||
* output row o of a sequence reads input rows o stride - pad .. o stride + stride - 1. */
|
||||
const int64_t pad = causal ? dil * (k - 1) + 1 - st : dil * (k - 1) / 2;
|
||||
REF_PAR_FOR((r1 - r0) / st * cout * cin * k)
|
||||
for (int64_t r = r0 / st; r < r1 / st; ++r) {
|
||||
const int64_t e = seq_of(cu, n_seq, r * st * cd);
|
||||
const int64_t s0 = cu_at(cu, e) / cd, s1 = cu_at(cu, e + 1) / cd;
|
||||
const int64_t yb = rowoff(y, r, cout), ys = laststride(y);
|
||||
for (int64_t co = 0; co < cout; ++co) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t kk = 0; kk < k; ++kk) {
|
||||
const int64_t ir = r + kk * dil - pad;
|
||||
const int64_t ir = r * st + kk * dil - pad;
|
||||
if (ir < s0 || ir >= s1) continue;
|
||||
const int64_t xb = rowoff(x, ir, cin), xs = laststride(x);
|
||||
for (int64_t ci = 0; ci < cin; ++ci)
|
||||
@@ -256,6 +270,9 @@ int ref_snake_aa(const RadArgs* a, RadStream) {
|
||||
* `cond_k` > 0 only the entries where c reaches its cond_k-th largest value are. Of the candidates
|
||||
* the `k` largest g (ties to the lower index) are kept, divided by `temp`, softmaxed in f32 and
|
||||
* drawn by inverse CDF in descending g with u = rad_philox_uniform_s(seed, 2^32 + frame, stream).
|
||||
* With `top_p` < 1 the kept list is cut first where the cumulative probability of the whole
|
||||
* candidate set's softmax over temp (summed in index order) passes top_p, as Fish Audio's sampler
|
||||
* cuts it: a rank whose inclusive cumulative probability exceeds top_p is dropped, rank 0 never.
|
||||
* The pick is written to all of the lane's `rep` slots of `ids`. logits [rep n, n_vocab] f32 or
|
||||
* bf16; seed [n, 2]; frame [n]. */
|
||||
int ref_cfg_topk_sample(const RadArgs* a, RadStream) {
|
||||
@@ -267,8 +284,10 @@ int ref_cfg_topk_sample(const RadArgs* a, RadStream) {
|
||||
const int64_t sup_lo = p_int(a, "sup_lo", 0), sup_hi = p_int(a, "sup_hi", 0);
|
||||
const float cfg = p_f32(a, "cfg", 1.0f), temp = p_f32(a, "temp", 1.0f);
|
||||
const float pen = p_f32(a, "penalty", 1.0f);
|
||||
const double top_p = (double)p_f32(a, "top_p", 1.0f);
|
||||
if (V <= 0 || K <= 0 || K > V || rep < 1 || rep > 2 || ck < 0 || ck > V || !(temp > 0) ||
|
||||
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane))
|
||||
sup_lo < 0 || sup_hi < sup_lo || sup_hi > V || !(pen > 0) || (!hist != !lane) ||
|
||||
!(top_p >= 0))
|
||||
return RAD_E_SHAPE;
|
||||
const int64_t n = numel(ids) / rep;
|
||||
if (n <= 0 || rows_of(lg, V) < rep * n || numel(fr) < n || numel(seed) < 2 * n ||
|
||||
@@ -319,13 +338,32 @@ int ref_cfg_topk_sample(const RadArgs* a, RadStream) {
|
||||
if (open(j)) idx[(size_t)nc++] = j;
|
||||
}
|
||||
if (nc == 0) return RAD_E_SHAPE;
|
||||
const int64_t kk = std::min(K, nc);
|
||||
/* The whole candidate set's normaliser, in index order (idx still is), for top_p. */
|
||||
double z = 0;
|
||||
if (top_p < 1.0) {
|
||||
float gm = g[(size_t)idx[0]];
|
||||
for (int64_t t = 1; t < nc; ++t) gm = std::max(gm, g[(size_t)idx[(size_t)t]]);
|
||||
const float m0 = gm / temp;
|
||||
for (int64_t t = 0; t < nc; ++t)
|
||||
z += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m0));
|
||||
}
|
||||
int64_t kk = std::min(K, nc);
|
||||
std::partial_sort(idx.begin(), idx.begin() + kk, idx.begin() + nc,
|
||||
[&](int64_t p, int64_t q) {
|
||||
return g[(size_t)p] > g[(size_t)q] ||
|
||||
(g[(size_t)p] == g[(size_t)q] && p < q);
|
||||
});
|
||||
const float m = g[(size_t)idx[0]] / temp;
|
||||
if (top_p < 1.0) {
|
||||
double cum = 0;
|
||||
int64_t keep = 1;
|
||||
for (int64_t t = 0; t < kk; ++t) {
|
||||
cum += std::exp((double)(g[(size_t)idx[(size_t)t]] / temp - m)) / z;
|
||||
if (t > 0 && cum > top_p) break;
|
||||
keep = t + 1;
|
||||
}
|
||||
kk = keep;
|
||||
}
|
||||
double tot = 0;
|
||||
std::vector<double> e((size_t)kk);
|
||||
for (int64_t t = 0; t < kk; ++t) {
|
||||
@@ -361,24 +399,26 @@ int ref_rvq_embed(const RadArgs* a, RadStream) {
|
||||
const int64_t D = p_int(a, "n_embd", 0), K = p_int(a, "n_codes", 0);
|
||||
const int64_t voc = p_int(a, "vocab", 0), off0 = p_int(a, "off0", 0);
|
||||
const float scale = p_f32(a, "scale", 1.0f);
|
||||
const int64_t round1 = p_int(a, "round", 0);
|
||||
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1) return RAD_E_SHAPE;
|
||||
const int64_t round1 = p_int(a, "round", 0), clamp = p_int(a, "clamp", 0);
|
||||
if (D <= 0 || K < 1 || voc <= 0 || round1 < 0 || round1 > 1 || clamp < 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(y, D);
|
||||
if (rows <= 0 || numel(codes) < K * rows) return RAD_E_SHAPE;
|
||||
const int64_t r0 = rows_of(t0, D), r1 = rows_of(t1, D);
|
||||
/* `clamp`: a code above clamp - 1 reads row clamp - 1 (a negative one still reads nothing). */
|
||||
auto cl = [clamp](int64_t c) { return clamp > 0 && c > clamp - 1 ? clamp - 1 : c; };
|
||||
/* Code (k, r): a codebook's row at the plane's own pitch, a frame's code at its own stride. */
|
||||
const int64_t kp = codes->rank >= 2 ? codes->stride[codes->rank - 2] : rows;
|
||||
const int64_t rp = codes->rank >= 1 ? codes->stride[codes->rank - 1] : 1;
|
||||
REF_PAR_FOR(rows * D * K)
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t c0 = ld_int(codes->dtype, codes->data, r * rp) + off0;
|
||||
const int64_t c0 = cl(ld_int(codes->dtype, codes->data, r * rp)) + off0;
|
||||
if (c0 < 0 || c0 >= r0) continue;
|
||||
std::vector<float> acc((size_t)D, 0.0f);
|
||||
const int64_t b0 = rowoff(t0, c0, D), yb = rowoff(y, r, D);
|
||||
if (round1)
|
||||
for (int64_t d = 0; d < D; ++d) acc[(size_t)d] = ldt(t0, b0 + d * laststride(t0));
|
||||
for (int64_t k = 1; k < K; ++k) {
|
||||
const int64_t ck = ld_int(codes->dtype, codes->data, k * kp + r * rp) + (k - 1) * voc;
|
||||
const int64_t ck = cl(ld_int(codes->dtype, codes->data, k * kp + r * rp)) + (k - 1) * voc;
|
||||
if (ck < 0 || ck >= r1) continue;
|
||||
const int64_t tb = rowoff(t1, ck, D);
|
||||
for (int64_t d = 0; d < D; ++d) acc[(size_t)d] += ldt(t1, tb + d * laststride(t1));
|
||||
@@ -392,6 +432,62 @@ int ref_rvq_embed(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ vq_encode */
|
||||
/* One step of a residual vector quantiser with factorised, L2-normalised codes (DAC's
|
||||
* VectorQuantize, as Fish Audio's codec encodes): per row of x [rows, n], e = in_w x + in_b
|
||||
* (in_w [dim, n]); the code is the row of cb [bins, dim] of greatest cosine with e,
|
||||
* (e / max(|e|, 1e-12)) . (cb_c / max(|cb_c|, 1e-12)), the lower index on a tie; then
|
||||
* x -= out_w cb[code] + out_b (out_w [n, dim], the raw codebook row), rounded once into x. f32,
|
||||
* every sum in index order. A chain of these over a codec's codebooks is its residual quantiser,
|
||||
* each step quantising what the last left. */
|
||||
int ref_vq_encode(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 7)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *iw = &a->t[1], *ib = &a->t[2], *cb = &a->t[3];
|
||||
const RadTensor *ow = &a->t[4], *ob = &a->t[5], *codes = &a->t[6];
|
||||
const int64_t n = p_int(a, "n", 0), dim = p_int(a, "dim", 0), bins = p_int(a, "bins", 0);
|
||||
if (n <= 0 || dim <= 0 || bins <= 0) return RAD_E_SHAPE;
|
||||
const int64_t rows = rows_of(x, n);
|
||||
if (rows <= 0 || numel(codes) < rows || numel(iw) < dim * n || numel(ib) < dim ||
|
||||
numel(cb) < bins * dim || numel(ow) < n * dim || numel(ob) < n)
|
||||
return RAD_E_SHAPE;
|
||||
/* The codebook normalised once, as F.normalize divides. */
|
||||
std::vector<float> cn((size_t)(bins * dim));
|
||||
for (int64_t c = 0; c < bins; ++c) {
|
||||
float ss = 0.0f;
|
||||
for (int64_t j = 0; j < dim; ++j) ss += ldt(cb, c * dim + j) * ldt(cb, c * dim + j);
|
||||
const float nrm = std::max(std::sqrt(ss), 1e-12f);
|
||||
for (int64_t j = 0; j < dim; ++j) cn[(size_t)(c * dim + j)] = ldt(cb, c * dim + j) / nrm;
|
||||
}
|
||||
REF_PAR_FOR(rows * (dim * n + bins * dim + n * dim))
|
||||
for (int64_t r = 0; r < rows; ++r) {
|
||||
const int64_t xb = rowoff(x, r, n), xs = laststride(x);
|
||||
std::vector<float> e((size_t)dim);
|
||||
float ss = 0.0f;
|
||||
for (int64_t j = 0; j < dim; ++j) {
|
||||
float acc = 0.0f;
|
||||
for (int64_t d = 0; d < n; ++d) acc += ldt(iw, j * n + d) * ldt(x, xb + d * xs);
|
||||
e[(size_t)j] = acc + ldt(ib, j);
|
||||
ss += e[(size_t)j] * e[(size_t)j];
|
||||
}
|
||||
const float nrm = std::max(std::sqrt(ss), 1e-12f);
|
||||
for (int64_t j = 0; j < dim; ++j) e[(size_t)j] /= nrm;
|
||||
int64_t best = 0;
|
||||
float bs = -INFINITY;
|
||||
for (int64_t c = 0; c < bins; ++c) {
|
||||
float s = 0.0f;
|
||||
for (int64_t j = 0; j < dim; ++j) s += e[(size_t)j] * cn[(size_t)(c * dim + j)];
|
||||
if (s > bs) { bs = s; best = c; }
|
||||
}
|
||||
st_int(codes->dtype, codes->data, offlin(codes, r), best);
|
||||
for (int64_t d = 0; d < n; ++d) {
|
||||
float q = 0.0f;
|
||||
for (int64_t j = 0; j < dim; ++j) q += ldt(ow, d * dim + j) * ldt(cb, best * dim + j);
|
||||
stt(x, xb + d * xs, ldt(x, xb + d * xs) - (q + ldt(ob, d)));
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ frame_mix_store */
|
||||
/* A frame's conditioning row, stored into its lane: m = bf16(bf16(sum_l w_l h_l) * bf16(scale))
|
||||
* with w = bf16(softmax(bf16(logits))) over the `L` hidden planes of hid [L, rows, n_embd], row
|
||||
@@ -437,6 +533,44 @@ int ref_frame_mix_store(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ ras_pick */
|
||||
/* Fish Audio's repetition-aware sampling, the choice between two draws a lane: the first draw
|
||||
* ids[rep i] = first[rep i], unless it lies in [lo, hi) and the lane's window (its last `win`
|
||||
* picks, `hist` [lanes, win], oldest first, -1 empty) holds it, in which case the alternative
|
||||
* draw alt[rep i] is taken. The pick then enters the window, its oldest entry leaving. `clear` 1
|
||||
* empties the lane's window first (a piece's first pick). A pick outside [lo, hi) (Fish's end of
|
||||
* speech) is never redrawn. */
|
||||
int ref_ras_pick(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 5)) return RAD_E_INVAL;
|
||||
const RadTensor *first = &a->t[0], *alt = &a->t[1], *lane = &a->t[2], *hist = &a->t[3];
|
||||
const RadTensor* ids = &a->t[4];
|
||||
const int64_t W = p_int(a, "win", 0), lo = p_int(a, "lo", 0), hi = p_int(a, "hi", 0);
|
||||
const int64_t rep = p_int(a, "rep", 1), clear = p_int(a, "clear", 0);
|
||||
const int64_t n = numel(lane);
|
||||
if (W <= 0 || lo < 0 || hi < lo || rep < 1 || clear < 0 || clear > 1 || n <= 0 ||
|
||||
numel(first) < rep * n || numel(alt) < rep * n || numel(ids) < rep * n)
|
||||
return RAD_E_SHAPE;
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t L = ldi(lane, i);
|
||||
if (L < 0 || (L + 1) * W > numel(hist)) return RAD_E_SHAPE;
|
||||
}
|
||||
for (int64_t i = 0; i < n; ++i) {
|
||||
const int64_t hb = ldi(lane, i) * W;
|
||||
if (clear)
|
||||
for (int64_t w = 0; w < W; ++w) st_int(hist->dtype, hist->data, offlin(hist, hb + w), -1);
|
||||
const int64_t f = ldi(first, rep * i);
|
||||
int64_t pick = f;
|
||||
if (f >= lo && f < hi)
|
||||
for (int64_t w = 0; w < W; ++w)
|
||||
if (ldi(hist, hb + w) == f) { pick = ldi(alt, rep * i); break; }
|
||||
for (int64_t r = 0; r < rep; ++r) st_int(ids->dtype, ids->data, offlin(ids, rep * i + r), pick);
|
||||
for (int64_t w = 0; w + 1 < W; ++w)
|
||||
st_int(hist->dtype, hist->data, offlin(hist, hb + w), ldi(hist, hb + w + 1));
|
||||
st_int(hist->dtype, hist->data, offlin(hist, hb + W - 1), pick);
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ end_status */
|
||||
/* A frame's status per lane from its first pick: status[lane[i]] = -1 when ids[rep i] is `end`
|
||||
* (the model ended the piece), else the pick. */
|
||||
@@ -746,6 +880,19 @@ int ref_int_affine(const RadArgs* a, RadStream) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ sub_i32 */
|
||||
/* y[i] = x[i] - s[0], int32: a device length less a device offset. */
|
||||
int ref_sub_i32(const RadArgs* a, RadStream) {
|
||||
if (!have(a, 3)) return RAD_E_INVAL;
|
||||
const RadTensor *x = &a->t[0], *s = &a->t[1], *y = &a->t[2];
|
||||
const int64_t n = numel(y);
|
||||
if (n <= 0 || numel(x) < n || numel(s) < 1) return RAD_E_SHAPE;
|
||||
const int64_t s0 = ldi(s, 0);
|
||||
for (int64_t i = 0; i < n; ++i)
|
||||
st_int(y->dtype, y->data, offlin(y, i), (int64_t)(int32_t)(ldi(x, i) - s0));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ cu_repeat */
|
||||
/* Sequence bounds of equal sequences: y[j] = j * len[0] * mult over y's elements. A pass's
|
||||
* lengths live on the device (a window's frames, the latents a vocoder decodes per channel group),
|
||||
|
||||
@@ -209,8 +209,10 @@ int ref_snake(const RadArgs*, RadStream);
|
||||
int ref_snake_aa(const RadArgs*, RadStream);
|
||||
int ref_cfg_topk_sample(const RadArgs*, RadStream);
|
||||
int ref_rvq_embed(const RadArgs*, RadStream);
|
||||
int ref_vq_encode(const RadArgs*, RadStream);
|
||||
int ref_frame_mix_store(const RadArgs*, RadStream);
|
||||
int ref_end_status(const RadArgs*, RadStream);
|
||||
int ref_ras_pick(const RadArgs*, RadStream);
|
||||
int ref_frame_store(const RadArgs*, RadStream);
|
||||
int ref_resample_nearest(const RadArgs*, RadStream);
|
||||
int ref_fourier_embed(const RadArgs*, RadStream);
|
||||
@@ -222,6 +224,7 @@ int ref_interleave2(const RadArgs*, RadStream);
|
||||
int ref_iota(const RadArgs*, RadStream);
|
||||
int ref_cu_repeat(const RadArgs*, RadStream);
|
||||
int ref_int_affine(const RadArgs*, RadStream);
|
||||
int ref_sub_i32(const RadArgs*, RadStream);
|
||||
int ref_chan_affine(const RadArgs*, RadStream);
|
||||
int ref_conv2d_nhwc(const RadArgs*, RadStream);
|
||||
int ref_im2col_nhwc(const RadArgs*, RadStream);
|
||||
@@ -452,8 +455,10 @@ REF_SHAPE_FN(ref_snake);
|
||||
REF_SHAPE_FN(ref_snake_aa);
|
||||
REF_SHAPE_FN(ref_cfg_topk_sample);
|
||||
REF_SHAPE_FN(ref_rvq_embed);
|
||||
REF_SHAPE_FN(ref_vq_encode);
|
||||
REF_SHAPE_FN(ref_frame_mix_store);
|
||||
REF_SHAPE_FN(ref_end_status);
|
||||
REF_SHAPE_FN(ref_ras_pick);
|
||||
REF_SHAPE_FN(ref_frame_store);
|
||||
REF_SHAPE_FN(ref_resample_nearest);
|
||||
REF_SHAPE_FN(ref_fourier_embed);
|
||||
@@ -465,6 +470,7 @@ REF_SHAPE_FN(ref_interleave2);
|
||||
REF_SHAPE_FN(ref_iota);
|
||||
REF_SHAPE_FN(ref_cu_repeat);
|
||||
REF_SHAPE_FN(ref_int_affine);
|
||||
REF_SHAPE_FN(ref_sub_i32);
|
||||
REF_SHAPE_FN(ref_chan_affine);
|
||||
REF_SHAPE_FN(ref_conv2d_nhwc);
|
||||
REF_SHAPE_FN(ref_im2col_nhwc);
|
||||
|
||||
+31
-3
@@ -935,7 +935,8 @@ static const RadOperandSpec oBweUp[] = { OPD("x"), OPD("res"), OUT("y") };
|
||||
/* ---- audio generation (ref_audio.cpp) */
|
||||
static const RadParamSpec pConv1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("k"),
|
||||
P_INT("dil"), P_STRO("act"), P_STR("dtype"),
|
||||
P_INTO("causal") };
|
||||
P_INTO("causal"), P_INTO("stride"),
|
||||
P_INTO("cu_div") };
|
||||
static const RadOperandSpec oConv1d[] = { OPD("x"), WGT("w"), OPD("cu_seqlens"), OPD_O("res"),
|
||||
OUT("y"), WGT_O("b") };
|
||||
static const RadParamSpec pConvT1d[] = { P_INT("M"), P_INT("cin"), P_INT("cout"), P_INT("stride"),
|
||||
@@ -951,19 +952,28 @@ static const RadOperandSpec oSnakeAa[] = { OPD("x"), WGT("alpha"), WGT("beta"),
|
||||
static const RadParamSpec pCfgTopk[] = { P_INT("M"), P_INT("n_vocab"), P_INT("k"), P_INT("rep"),
|
||||
P_INTO("cond_k"), P_F64("cfg"), P_F64O("temp"),
|
||||
P_INT("stream"), P_STR("dtype"), P_INTO("sup_lo"),
|
||||
P_INTO("sup_hi"), P_F64O("penalty") };
|
||||
P_INTO("sup_hi"), P_F64O("penalty"),
|
||||
P_F64O("top_p") };
|
||||
static const RadOperandSpec oCfgTopk[] = { OPD("logits"), OPD("seed"), OPD("frame"), OUT("ids"),
|
||||
OPD_O("cfg"), OPD_O("lane"), INOUT_O("hist") };
|
||||
static const RadParamSpec pRvqEmbed[] = { P_INT("M"), P_INT("n_embd"), P_INT("n_codes"),
|
||||
P_INT("vocab"), P_INT("off0"), P_F64("scale"),
|
||||
P_STR("dtype"), P_INTO("round") };
|
||||
P_STR("dtype"), P_INTO("round"), P_INTO("clamp") };
|
||||
static const RadOperandSpec oRvqEmbed[] = { OPD("codes"), WGT("t0"), WGT("t1"), OUT("y") };
|
||||
static const RadParamSpec pVqEncode[] = { P_INT("M"), P_INT("n"), P_INT("dim"), P_INT("bins"),
|
||||
P_STR("dtype") };
|
||||
static const RadOperandSpec oVqEncode[] = { INOUT("x"), WGT("in_w"), WGT("in_b"), WGT("cb"),
|
||||
WGT("out_w"), WGT("out_b"), OUT("codes") };
|
||||
static const RadParamSpec pFrameMix[] = { P_INT("M"), P_INT("n_embd"), P_INT("L"), P_INT("stride"),
|
||||
P_INTO("rep"), P_STR("dtype") };
|
||||
static const RadOperandSpec oFrameMix[] = { OPD("hid"), WGT("logits"), WGT("scale"), OPD("lane"),
|
||||
OPD("frame"), OPD("status"), INOUT("dst") };
|
||||
static const RadParamSpec pEndStatus[] = { P_INT("M"), P_INT("end"), P_INT("rep") };
|
||||
static const RadOperandSpec oEndStatus[] = { OPD("ids"), OPD("lane"), INOUT("status") };
|
||||
static const RadParamSpec pRasPick[] = { P_INT("M"), P_INT("win"), P_INT("lo"), P_INT("hi"),
|
||||
P_INTO("rep"), P_INTO("clear") };
|
||||
static const RadOperandSpec oRasPick[] = { OPD("first"), OPD("alt"), OPD("lane"), INOUT("hist"),
|
||||
OUT("ids") };
|
||||
static const RadParamSpec pFrameStore[] = { P_INT("M"), P_INT("n_codes"), P_INT("stride"),
|
||||
P_INTO("rep"), P_INTO("skip") };
|
||||
static const RadOperandSpec oFrameStore[] = { OPD("codes"), OPD("lane"), OPD("frame"),
|
||||
@@ -993,6 +1003,8 @@ static const RadOperandSpec oIota[] = { OUT("y") };
|
||||
static const RadParamSpec pCuRepeat[] = { P_INT("M"), P_INT("mult") };
|
||||
static const RadParamSpec pIntAffine[] = { P_INT("M"), P_STR("src"), P_STR("mul"), P_STR("add") };
|
||||
static const RadOperandSpec oIntAffine[] = { OPD("x"), OUT("y") };
|
||||
static const RadParamSpec pSubI32[] = { P_INT("M") };
|
||||
static const RadOperandSpec oSubI32[] = { OPD("x"), OPD("s"), OUT("y") };
|
||||
static const RadOperandSpec oCuRepeat[] = { OPD("len"), OUT("y") };
|
||||
|
||||
/* ================================================================== the schema table */
|
||||
@@ -1845,11 +1857,19 @@ static const RadOpSchema kSchemas[] = {
|
||||
"a frame's embedding from code-major residual codes [n_codes, rows]: t0[c0 + off0] plus the sum "
|
||||
"of t1[c_k + (k - 1) vocab], times `scale`, rounded as bf16(bf16(t0 + bf16(sum)) * scale), or "
|
||||
"with `round` 1 one f32 sum in codebook order times scale, rounded once." },
|
||||
{ "vq_encode", ARR(pVqEncode), ARR(oVqEncode),
|
||||
"one residual vector quantiser step: e = in_w x + in_b, the code the row of cb of greatest "
|
||||
"cosine with e (the lower index on a tie), then x -= out_w cb[code] + out_b; f32, x rounded "
|
||||
"once." },
|
||||
{ "frame_mix_store", ARR(pFrameMix), ARR(oFrameMix),
|
||||
"a frame's conditioning row: the softmax(logits)-weighted sum of hid's L planes times scale, "
|
||||
"stored at dst[lane * stride + frame - 1] for frame >= 1 and status[lane] >= 0." },
|
||||
{ "end_status", ARR(pEndStatus), ARR(oEndStatus),
|
||||
"status[lane[i]] = ids[rep i] == end ? -1 : ids[rep i]." },
|
||||
{ "ras_pick", ARR(pRasPick), ARR(oRasPick),
|
||||
"repetition-aware sampling: ids[rep i] = alt[rep i] where first[rep i] is in [lo, hi) and in "
|
||||
"the lane's window of its last `win` picks (hist [lanes, win], -1 empty, cleared first with "
|
||||
"`clear` 1), else first[rep i]; the pick then enters the window." },
|
||||
{ "frame_store", ARR(pFrameStore), ARR(oFrameStore),
|
||||
"a frame's codes into its lane's history: dst[(lane n_codes + k) stride + frame - skip] = "
|
||||
"codes[k, rep i] when frame >= skip and status[lane] >= 0." },
|
||||
@@ -1883,6 +1903,8 @@ static const RadOpSchema kSchemas[] = {
|
||||
{ "int_affine", ARR(pIntAffine), ARR(oIntAffine),
|
||||
"y[j] = (src[j] < 0 ? 0 : x[src[j]]) * mul[j] + add[j] over three integer lists: shapes and "
|
||||
"bounds derived from a pass's device geometry." },
|
||||
{ "sub_i32", ARR(pSubI32), ARR(oSubI32),
|
||||
"y[i] = x[i] - s[0], int32: a device length less a device offset." },
|
||||
};
|
||||
|
||||
/* ================================================================== the kernel table */
|
||||
@@ -2430,10 +2452,14 @@ SIMPLE("ref_cfg_topk_sample", "cfg_topk_sample", "sample", "a guided top-k pick
|
||||
DT_FLOAT, ref_cfg_topk_sample),
|
||||
SIMPLE("ref_rvq_embed", "rvq_embed", "elem", "a frame's embedding from its residual codes",
|
||||
DT_FLOAT, ref_rvq_embed),
|
||||
SIMPLE("ref_vq_encode", "vq_encode", "elem",
|
||||
"a residual quantiser's step: the nearest code by cosine", DT_FLOAT, ref_vq_encode),
|
||||
SIMPLE("ref_frame_mix_store", "frame_mix_store", "elem", "a frame's conditioning row into its lane",
|
||||
DT_FLOAT, ref_frame_mix_store),
|
||||
SIMPLE("ref_end_status", "end_status", "elem", "a frame's status from its first pick", DT_ANY,
|
||||
ref_end_status),
|
||||
SIMPLE("ref_ras_pick", "ras_pick", "elem", "a repetition-aware choice between two draws a lane",
|
||||
DT_ANY, ref_ras_pick),
|
||||
SIMPLE("ref_frame_store", "frame_store", "elem", "a frame's codes into its lane's history", DT_ANY,
|
||||
ref_frame_store),
|
||||
SIMPLE("ref_resample_nearest", "resample_nearest", "elem", "rows resampled nearest-neighbour",
|
||||
@@ -2454,6 +2480,8 @@ SIMPLE("ref_iota", "iota", "elem", "an arithmetic index sequence", DT_ANY, ref_i
|
||||
SIMPLE("ref_cu_repeat", "cu_repeat", "elem", "bounds of equal sequences", DT_ANY, ref_cu_repeat),
|
||||
SIMPLE("ref_int_affine", "int_affine", "elem", "integers derived from device geometry", DT_ANY,
|
||||
ref_int_affine),
|
||||
SIMPLE("ref_sub_i32", "sub_i32", "elem", "a device int32 vector less a device scalar", DT_ANY,
|
||||
ref_sub_i32),
|
||||
};
|
||||
|
||||
/* ================================================================== plugin exports */
|
||||
|
||||
+49
-4
@@ -3227,16 +3227,20 @@ static int64_t two_seqs(int64_t M) { return M >= 4 ? 2 : 1; }
|
||||
int ref_conv1d_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), cin = gi(p, n_p, "cin", 0), cout = gi(p, n_p, "cout", 0);
|
||||
const int64_t k = gi(p, n_p, "k", 0), causal = gi(p, n_p, "causal", 0);
|
||||
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0))
|
||||
const int64_t st = gi(p, n_p, "stride", 1), dil = gi(p, n_p, "dil", 1);
|
||||
if (M <= 0 || cin <= 0 || cout <= 0 || k <= 0 || (!causal && (k & 1) == 0) || st < 1 ||
|
||||
(st > 1 && (!causal || dil * (k - 1) + 1 < st || M % st)) || gi(p, n_p, "cu_div", 1) != 1)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
const uint32_t D = act_dt(p, n_p);
|
||||
const int64_t S = two_seqs(M);
|
||||
/* A strided convolution is described over one sequence: two would each need a whole number
|
||||
* of strides. Bounds in coarser units (cu_div) are not drawn; ref_test checks them. */
|
||||
const int64_t S = st > 1 ? 1 : two_seqs(M);
|
||||
Opd o;
|
||||
o.t(D, { M, cin }); /* x */
|
||||
o.t(D, { cout, cin, k }); /* w */
|
||||
o.t_idx({ S + 1 }, 0, -1, (uint32_t)RAD_OPD_F_IDX_CU); /* cu_seqlens */
|
||||
o.t(D, { M, cout }); /* res */
|
||||
o.t(D, { M, cout }); /* y */
|
||||
o.t(D, { M / st, cout }); /* res */
|
||||
o.t(D, { M / st, cout }); /* y */
|
||||
o.t(D, { cout }); /* b */
|
||||
return o.finish("conv1d", operand, out);
|
||||
}
|
||||
@@ -3314,6 +3318,22 @@ int ref_rvq_embed_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out
|
||||
return o.finish("rvq_embed", operand, out);
|
||||
}
|
||||
|
||||
int ref_vq_encode_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), n = gi(p, n_p, "n", 0);
|
||||
const int64_t dim = gi(p, n_p, "dim", 0), bins = gi(p, n_p, "bins", 0);
|
||||
if (M <= 0 || n <= 0 || dim <= 0 || bins <= 0) return RAD_E_UNSUPPORTED;
|
||||
const uint32_t F = (uint32_t)RAD_F32;
|
||||
Opd o;
|
||||
o.t(act_dt(p, n_p), { M, n }); /* x, INOUT */
|
||||
o.t(F, { dim, n }); /* in_w */
|
||||
o.t(F, { dim }); /* in_b */
|
||||
o.t(F, { bins, dim }); /* cb */
|
||||
o.t(F, { n, dim }); /* out_w */
|
||||
o.t(F, { n }); /* out_b */
|
||||
o.t_idx({ M }, bins, -1, 0); /* codes, OUT */
|
||||
return o.finish("vq_encode", operand, out);
|
||||
}
|
||||
|
||||
int ref_frame_mix_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), D = gi(p, n_p, "n_embd", 0), L = gi(p, n_p, "L", 0);
|
||||
const int64_t st = gi(p, n_p, "stride", 0);
|
||||
@@ -3341,6 +3361,21 @@ int ref_end_status_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
|
||||
return o.finish("end_status", operand, out);
|
||||
}
|
||||
|
||||
int ref_ras_pick_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), rep = gi(p, n_p, "rep", 1), W = gi(p, n_p, "win", 0);
|
||||
const int64_t hi = gi(p, n_p, "hi", 0);
|
||||
if (M <= 0 || rep < 1 || W <= 0 || hi <= 0 || M > REF_LANES) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
/* Picks over a small band so the windows repeat them often enough to exercise the redraw. */
|
||||
const int64_t band = std::min<int64_t>(hi + 2, 12);
|
||||
o.t_idx({ rep * M }, band, -1, 0); /* first */
|
||||
o.t_idx({ rep * M }, band, -1, 0); /* alt */
|
||||
o.t_idx({ M }, REF_LANES, -1, (uint32_t)RAD_OPD_F_IDX_UNIQUE); /* lane */
|
||||
o.t_idx({ REF_LANES * W }, band, -1, 0); /* hist, INOUT */
|
||||
o.t_idx({ rep * M }, band, -1, 0); /* ids, OUT */
|
||||
return o.finish("ras_pick", operand, out);
|
||||
}
|
||||
|
||||
int ref_frame_store_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), K = gi(p, n_p, "n_codes", 0);
|
||||
const int64_t st = gi(p, n_p, "stride", 0), rep = gi(p, n_p, "rep", 1);
|
||||
@@ -3479,6 +3514,16 @@ int ref_int_affine_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
|
||||
return o.finish("int_affine", operand, out);
|
||||
}
|
||||
|
||||
int ref_sub_i32_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0);
|
||||
if (M <= 0) return RAD_E_UNSUPPORTED;
|
||||
Opd o;
|
||||
o.t_idx({ M }, 100000, -1, 0); /* x */
|
||||
o.t_idx({ 1 }, 1000, -1, 0); /* s */
|
||||
o.t_idx({ M }, 1, -1, 0); /* y */
|
||||
return o.finish("sub_i32", operand, out);
|
||||
}
|
||||
|
||||
/* ================================================================== LTX-2 (ref_ltx.cpp) */
|
||||
int ref_rope_split_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
|
||||
const int64_t M = gi(p, n_p, "M", 0), nh = gi(p, n_p, "n_head", 0);
|
||||
|
||||
@@ -0,0 +1,42 @@
|
||||
# spechub -- the linear-MTP coupling kernels.
|
||||
#
|
||||
# Two ops, `mtp_couple_propose` and `mtp_couple_verify`, each with a device row and a host reference
|
||||
# row. The arithmetic is abi/rad_spechub.h's, shared with the engine. The device launches include
|
||||
# libr4d/r4d_emit.h by its path in this tree, so the device form builds from this tree's sources
|
||||
# (in the tree's build or standalone against an install); a host-only build needs abi/ alone.
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(spechub LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
# The device rows are built where the installed radiance has a device build; HIP is enabled
|
||||
# after project(), from the package's record of that build.
|
||||
if(RAD_HIP_FOUND)
|
||||
enable_language(HIP)
|
||||
endif()
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
set(SPECHUB_COMMON
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/spechub.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/ref_spechub.cpp
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/exports.cpp)
|
||||
|
||||
if(NOT RAD_HIP_FOUND)
|
||||
message(STATUS "spechub: this radiance has no device build -- only the host reference is built")
|
||||
rad_add_plugin(spechub kernels SOURCES ${SPECHUB_COMMON})
|
||||
else()
|
||||
# The owning project must enable HIP itself; enable_language() is project scope. The top-level tree
|
||||
# does it with -DRAD_WITH_HIP=ON, and a standalone build must do the same after project().
|
||||
get_property(spechub_langs GLOBAL PROPERTY ENABLED_LANGUAGES)
|
||||
if(NOT "HIP" IN_LIST spechub_langs)
|
||||
message(FATAL_ERROR "spechub: HIP_SOURCES need `enable_language(HIP)` in this project (set "
|
||||
"-DRAD_WITH_HIP=ON, or enable it after project()).")
|
||||
endif()
|
||||
rad_add_plugin(spechub kernels SOURCES ${SPECHUB_COMMON}
|
||||
HIP_SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/spechub.hip)
|
||||
target_compile_definitions(spechub PRIVATE RAD_SPECHUB_WITH_DEVICE=1)
|
||||
endif()
|
||||
|
||||
# -ffp-contract=off for correctness: an FMA fused into the ordered FP64 mass sums would move the
|
||||
# token off the host reference.
|
||||
target_compile_options(spechub PRIVATE -ffp-contract=off)
|
||||
@@ -0,0 +1,97 @@
|
||||
/* plugin/spechub/exports.cpp -- the plugin's export block.
|
||||
*
|
||||
* The whole kernel-plugin set (schema count/at, kernel count/at, ABI version, info) and nothing else.
|
||||
* The rows themselves, their schemas and their argument readers are in spechub.cpp; the launches are
|
||||
* spechub.hip (device) and ref_spechub.cpp (host).
|
||||
*
|
||||
* Reference status is per row: the library carries device rows and their host oracle, so
|
||||
* `rad_kernel_reference` marks the device rows 0 and the host rows 1, and `rad_plugin_reference`
|
||||
* stays 0. Marking the whole library would make the reference gate refuse the device rows. On a
|
||||
* machine with no card only the reference rows exist, and the gate refuses the coupling there.
|
||||
*
|
||||
* The ops are declared only under --draft-coupling on; the plugin never reads the flag.
|
||||
*/
|
||||
#include "spechub.h"
|
||||
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
#include "../../libr4d/r4d_emit.h" /* only for the three globals it declares */
|
||||
|
||||
/* r4d_emit.h's dispatch recorder, defined here because plugins load RTLD_LOCAL and cannot
|
||||
* resolve libr4d's copy. Nothing in this plugin sets the log, so the recorder stays inert. */
|
||||
const void** r4d_dispatch_log = nullptr;
|
||||
int r4d_dispatch_cap = 0;
|
||||
int r4d_dispatch_n = 0;
|
||||
#endif
|
||||
|
||||
namespace {
|
||||
const RadPluginInfo kInfo = {
|
||||
RAD_PLUGIN_KERNEL, "spechub", "0.1.0",
|
||||
"Linear-MTP maximal coupling: a Q draw per round and the coupled target verify", "gfx1201",
|
||||
};
|
||||
} /* namespace */
|
||||
|
||||
extern "C" uint32_t rad_plugin_abi_version(void) { return RAD_ABI_VERSION; }
|
||||
extern "C" const RadPluginInfo* rad_plugin_info(void) { return &kInfo; }
|
||||
/* Mixed library: 0, and the per-row answer below does the classifying. */
|
||||
extern "C" int rad_plugin_reference(void) { return 0; }
|
||||
|
||||
/* Row layout is [device 0, device 1, ref 0, ref 1] with a card, [ref 0, ref 1] without. The
|
||||
* device rows are the production kernels; the host rows are the oracle rad-kbench checks them
|
||||
* against and the only thing a card-less machine can run. */
|
||||
extern "C" int rad_kernel_reference(int i) {
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
return (i == 0 || i == 1) ? 0 : 1;
|
||||
#else
|
||||
(void)i;
|
||||
return 1;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" int rad_kernel_schema_count(void) { return rad_spechub_schema_count(); }
|
||||
extern "C" const RadOpSchema* rad_kernel_schema_at(int i) { return rad_spechub_schema_at(i); }
|
||||
|
||||
/* Two device rows and the two host references beside them, in that order. A card-less machine loads
|
||||
* the same library and resolves only the reference rows. */
|
||||
extern "C" int rad_kernel_count(void) {
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
return 4;
|
||||
#else
|
||||
return 2;
|
||||
#endif
|
||||
}
|
||||
|
||||
extern "C" const RadKernelInfo* rad_kernel_at(int i) {
|
||||
const int op = i & 1;
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
if (i == 0 || i == 1) {
|
||||
static const RadKernelInfo r[2] = {
|
||||
rad_spechub_row(0, rad_mine_mtp_couple_propose_launch),
|
||||
rad_spechub_row(1, rad_mine_mtp_couple_verify_launch),
|
||||
};
|
||||
return &r[i];
|
||||
}
|
||||
#endif
|
||||
static const RadKernelInfo ref[2] = {
|
||||
[] {
|
||||
RadKernelInfo x = rad_spechub_row(0, rad_ref_mtp_couple_propose);
|
||||
x.name = "ref_mtp_couple_propose";
|
||||
x.domain = RAD_DOMAIN_HOST;
|
||||
x.priority = 0;
|
||||
return x;
|
||||
}(),
|
||||
[] {
|
||||
RadKernelInfo x = rad_spechub_row(1, rad_ref_mtp_couple_verify);
|
||||
x.name = "ref_mtp_couple_verify";
|
||||
x.domain = RAD_DOMAIN_HOST;
|
||||
x.priority = 0;
|
||||
return x;
|
||||
}(),
|
||||
};
|
||||
#ifdef RAD_SPECHUB_WITH_DEVICE
|
||||
if (i < 2 || i > 3) return nullptr;
|
||||
return &ref[op];
|
||||
#else
|
||||
if (i < 0 || i > 1) return nullptr;
|
||||
return &ref[i];
|
||||
#endif
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
/* plugin/spechub/ref_spechub.cpp -- the two coupling ops on the host.
|
||||
*
|
||||
* One row at a time through the abi/rad_spechub.h helpers. These are the rows the device kernels
|
||||
* are checked against, and the only implementation a machine with no card can run.
|
||||
*/
|
||||
#include "spechub.h"
|
||||
|
||||
int rad_ref_mtp_couple_propose(const RadArgs* a, RadStream) {
|
||||
RadMtpCoupleProposeCall c{};
|
||||
const int rc = rad_mtp_couple_propose_args(a, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
for (int64_t row = 0; row < c.M; ++row) rad_mtp_couple_propose_row(c, row);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int rad_ref_mtp_couple_verify(const RadArgs* a, RadStream) {
|
||||
RadMtpCoupleVerifyCall c{};
|
||||
const int rc = rad_mtp_couple_verify_args(a, &c);
|
||||
if (rc != RAD_OK) return rc;
|
||||
for (int64_t row = 0; row < c.M; ++row) rad_mtp_couple_verify_row(c, row);
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
/* plugin/spechub/spechub.cpp -- the two coupling ops' schemas, shapes and argument validation.
|
||||
*
|
||||
* Shape hooks and geometry only: the arithmetic is in abi/rad_spechub.h (inline, host and device) and
|
||||
* the launches are in spechub.hip and ref_spechub.cpp. This file is host C++ and compiles with no
|
||||
* card, which is what lets a card-less machine check the plugin's schema and shapes.
|
||||
*/
|
||||
#include "spechub.h"
|
||||
|
||||
#include <climits>
|
||||
#include <cstddef>
|
||||
|
||||
namespace {
|
||||
|
||||
#define PI(k) { k, RAD_P_INT, RAD_REQUIRED, 0 }
|
||||
const RadParamSpec kProposeParams[] = {
|
||||
PI("M"), PI("n_vocab"), PI("round"), PI("max_rounds"),
|
||||
};
|
||||
const RadParamSpec kVerifyParams[] = { PI("M"), PI("n_cand"), PI("n_vocab") };
|
||||
#undef PI
|
||||
|
||||
/* `idx` is INOUT: the round's proposal IS the head's column 0, and a sampled row overwrites it. */
|
||||
const RadOperandSpec kProposeOperands[] = {
|
||||
{ "idx", RAD_OPD_INOUT, 0 },
|
||||
{ "val", RAD_OPD_IN, 0 },
|
||||
{ "seq_ids", RAD_OPD_IN, 0 },
|
||||
{ "draw", RAD_OPD_IN, 0 },
|
||||
{ "state", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
|
||||
/* The verify runs after the ordinary pick over the SAME final candidate plane, so its operands are
|
||||
* the sampler's own: candidates, parameter rows, coupled state rows, and the token plane the pick
|
||||
* already wrote. */
|
||||
const RadOperandSpec kVerifyOperands[] = {
|
||||
{ "cand_idx", RAD_OPD_IN, 0 },
|
||||
{ "cand_val", RAD_OPD_IN, 0 },
|
||||
{ "params", RAD_OPD_IN, 0 },
|
||||
{ "state", RAD_OPD_IN, 0 },
|
||||
{ "token", RAD_OPD_INOUT, 0 },
|
||||
};
|
||||
|
||||
const RadOpSchema kSchemas[] = {
|
||||
{ "mtp_couple_propose", kProposeParams, 4, kProposeOperands, 5,
|
||||
"Linear MTP round `round`: x~Q, Q = FP64 T1 softmax of the final top8 scores; x into idx "
|
||||
"column 0 and the state into state[round-1][row]. mode0 rows keep column 0 (status 0); bad "
|
||||
"ids/scores or seq_ids != draw.card keep it too (status -1)." },
|
||||
{ "mtp_couple_verify", kVerifyParams, 3, kVerifyOperands, 5,
|
||||
"Maximal coupling of a bound mtp_couple state after sample_pick over all surviving target "
|
||||
"candidates, FP64 P and 53-bit ACCEPT/RESID uniforms at params.pos; residual (P-Q)+ with "
|
||||
"r(x)=0. Rows whose state is not status 1, not bound to params seed/pos, malformed, or whose "
|
||||
"(P,Q) admit no coupling keep the ordinary token." },
|
||||
};
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int rad_spechub_schema_count() { return 2; }
|
||||
const RadOpSchema* rad_spechub_schema_at(int i) {
|
||||
return i >= 0 && i < 2 ? &kSchemas[i] : nullptr;
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
/* The geometry both hooks and the arg readers agree on. `op` 0 proposes, 1 verifies. A RANGE `M`
|
||||
* reads as its high bound, which is what a shape hook must do: it sizes buffers before selection has
|
||||
* collapsed anything, so it describes the whole band. */
|
||||
int couple_geometry(const RadParam* p, int n, int op, bool range, int64_t* M, int64_t* vocab,
|
||||
int64_t* n_cand) {
|
||||
if (!p) return RAD_E_INVAL;
|
||||
*M = range ? rad_param_getdim(p, n, "M", 0) : rad_param_geti(p, n, "M", 0);
|
||||
*vocab = rad_param_geti(p, n, "n_vocab", 0);
|
||||
*n_cand = op ? rad_param_geti(p, n, "n_cand", 0) : 8;
|
||||
if (*M < 1 || *M > INT32_MAX || *vocab < 1 || *vocab > INT32_MAX) return RAD_E_UNSUPPORTED;
|
||||
if (*n_cand < 1 || *n_cand > INT32_MAX) return RAD_E_UNSUPPORTED;
|
||||
if (!op) {
|
||||
const int64_t round = rad_param_geti(p, n, "round", 0);
|
||||
const int64_t rounds = rad_param_geti(p, n, "max_rounds", 0);
|
||||
if (rounds < 1 || rounds > RAD_MTP_COUPLE_MAX_ROUNDS || round < 1 || round > rounds)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Does one operand's extent fit the shape its hook declares? A row-owning kernel reads a whole row,
|
||||
* so the last axis is structural and every leading one is a row count. */
|
||||
int span(const RadTensor& t, const RadOpdDesc& d, uint64_t* bytes) {
|
||||
if (!t.data || (uintptr_t)t.data % 4) return RAD_E_INVAL;
|
||||
if (t.dtype != d.dtype) return RAD_E_DTYPE;
|
||||
if (t.rank != d.rank) return RAD_E_SHAPE;
|
||||
uint64_t words = 1;
|
||||
for (int j = (int)d.rank - 1; j >= 0; --j) {
|
||||
if (t.shape[j] < 1 || t.shape[j] > INT32_MAX || (d.shape[j] > 0 && t.shape[j] != d.shape[j]))
|
||||
return RAD_E_SHAPE;
|
||||
if (t.stride[j] < 1 || (j == (int)d.rank - 1 && t.stride[j] != 1) ||
|
||||
(j < (int)d.rank - 1 && (uint64_t)t.stride[j] < words))
|
||||
return RAD_E_STRIDE;
|
||||
const uint64_t extent = (uint64_t)(t.shape[j] - 1);
|
||||
if (extent && (uint64_t)t.stride[j] > (INT64_MAX / 4 - words) / extent) return RAD_E_SHAPE;
|
||||
words += extent * (uint64_t)t.stride[j];
|
||||
}
|
||||
*bytes = words * 4;
|
||||
if ((uintptr_t)t.data > UINTPTR_MAX - *bytes) return RAD_E_INVAL;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
int rad_mtp_couple_propose_shape(const RadParam* p, int n, int i, RadOpdDesc* out) {
|
||||
if (!out || i < 0 || i >= 5) return RAD_E_INVAL;
|
||||
int64_t M, v, nc;
|
||||
int rc = couple_geometry(p, n, 0, true, &M, &v, &nc);
|
||||
if (rc != RAD_OK) return rc;
|
||||
RadOpdDesc d{};
|
||||
d.idx_const = -1;
|
||||
d.dtype = RAD_I32;
|
||||
d.rank = 2;
|
||||
d.shape[0] = M;
|
||||
d.shape[1] = 8;
|
||||
if (i == 0) { d.fill = RAD_FILL_INDEX; d.idx_max = (int32_t)v; }
|
||||
if (i == 1) d.dtype = RAD_F32;
|
||||
if (i == 2) { d.rank = 1; d.fill = RAD_FILL_INDEX; d.idx_max = (int32_t)M; }
|
||||
if (i == 3) { d.dtype = RAD_U32; d.shape[1] = RAD_MTP_COUPLE_DRAW_WORDS; }
|
||||
if (i == 4) {
|
||||
/* Rounds are the state plane's leading axis, and `max_rounds` is exactly the bound the caller
|
||||
* sized it at. */
|
||||
const int64_t rounds = rad_param_geti(p, n, "max_rounds", 1);
|
||||
d.dtype = RAD_U32;
|
||||
d.rank = 3;
|
||||
d.shape[0] = rounds;
|
||||
d.shape[1] = M;
|
||||
d.shape[2] = RAD_MTP_COUPLE_STATE_WORDS;
|
||||
}
|
||||
*out = d;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int rad_mtp_couple_verify_shape(const RadParam* p, int n, int i, RadOpdDesc* out) {
|
||||
if (!out || i < 0 || i >= 5) return RAD_E_INVAL;
|
||||
int64_t M, v, nc;
|
||||
int rc = couple_geometry(p, n, 1, true, &M, &v, &nc);
|
||||
if (rc != RAD_OK) return rc;
|
||||
RadOpdDesc d{};
|
||||
d.idx_const = -1;
|
||||
d.dtype = RAD_I32;
|
||||
d.rank = 2;
|
||||
d.shape[0] = M;
|
||||
d.shape[1] = nc;
|
||||
if (i == 1) d.dtype = RAD_F32;
|
||||
if (i == 2 || i == 3) {
|
||||
d.dtype = RAD_U32;
|
||||
d.shape[1] = i == 2 ? 24 : RAD_MTP_COUPLE_STATE_WORDS;
|
||||
}
|
||||
if (i == 4) d.rank = 1;
|
||||
*out = d;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* The resolved `M` is the arena band's ceiling; this issue may carry fewer live rows, and both
|
||||
* kernels take the row count from operand 0. Dim 0 is narrowed to the live rows before each
|
||||
* operand's extent is checked, the wire planes must be eight-byte aligned with an even row stride,
|
||||
* and separate storage is part of the contract: an aliased pair would let a write land on a read. */
|
||||
int rad_couple_validate(const RadArgs* a, int op, int64_t* M, int64_t* vocab, int64_t* n_cand) {
|
||||
if (!a || !a->t || a->n_t != 5) return RAD_E_INVAL;
|
||||
int rc = couple_geometry(a->p, a->n_p, op, false, M, vocab, n_cand);
|
||||
if (rc != RAD_OK) return rc;
|
||||
const int64_t live = a->t[0].rank ? a->t[0].shape[0] : 0;
|
||||
if (live < 1 || live > *M) return RAD_E_SHAPE;
|
||||
*M = live;
|
||||
const int64_t rounds = op ? 1 : rad_param_geti(a->p, a->n_p, "max_rounds", 1);
|
||||
uint64_t bytes[5] = {};
|
||||
for (int i = 0; i < 5; ++i) {
|
||||
RadOpdDesc d{};
|
||||
rc = op ? rad_mtp_couple_verify_shape(a->p, a->n_p, i, &d)
|
||||
: rad_mtp_couple_propose_shape(a->p, a->n_p, i, &d);
|
||||
if (rc != RAD_OK) return rc;
|
||||
d.shape[0] = *M;
|
||||
/* `seq_ids` covers the whole batch and the state plane is [rounds, rows]; both are checked
|
||||
* below rather than against the live row count. */
|
||||
if (!op && i == 2) d.shape[0] = 0;
|
||||
if (!op && i == 4) { d.shape[0] = rounds; d.shape[1] = 0; }
|
||||
/* The sampler exposes a flat token plane and its production [M, 1] one. */
|
||||
if (op && i == 4 && a->t[i].rank == 2) { d.rank = 2; d.shape[1] = 1; }
|
||||
if ((rc = span(a->t[i], d, &bytes[i])) != RAD_OK) return rc;
|
||||
if (!op && i == 2 && a->t[i].shape[0] < *M) return RAD_E_SHAPE;
|
||||
if (!op && i == 4 && a->t[i].shape[1] < *M) return RAD_E_SHAPE;
|
||||
const bool wire = op ? (i == 2 || i == 3) : (i == 3 || i == 4);
|
||||
if (wire && ((uintptr_t)a->t[i].data % 8 || a->t[i].stride[0] % 2 ||
|
||||
(a->t[i].rank == 3 && a->t[i].stride[1] % 2)))
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* An even ROW stride keeps every shortlist row 8-byte aligned; the innermost stride is 1. */
|
||||
if (!op && a->t[0].stride[0] % 2) return RAD_E_STRIDE;
|
||||
for (int i = 0; i < 5; ++i)
|
||||
for (int j = i + 1; j < 5; ++j) {
|
||||
const uintptr_t x = (uintptr_t)a->t[i].data, y = (uintptr_t)a->t[j].data;
|
||||
if (x < y + bytes[j] && y < x + bytes[i]) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int rad_mtp_couple_propose_args(const RadArgs* a, RadMtpCoupleProposeCall* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
int64_t M, v, nc;
|
||||
const int rc = rad_couple_validate(a, 0, &M, &v, &nc);
|
||||
if (rc != RAD_OK) return rc;
|
||||
RadMtpCoupleProposeCall c{};
|
||||
c.M = M;
|
||||
c.vocab = v;
|
||||
c.round = (int)rad_param_geti(a->p, a->n_p, "round", 0);
|
||||
c.idx = (int32_t*)a->t[0].data;
|
||||
c.val = (const float*)a->t[1].data;
|
||||
c.card = (const int32_t*)a->t[2].data;
|
||||
c.draw = (const uint32_t*)a->t[3].data;
|
||||
c.state = (uint32_t*)a->t[4].data;
|
||||
c.ld_idx = a->t[0].stride[0];
|
||||
c.ld_val = a->t[1].stride[0];
|
||||
c.ld_draw = a->t[3].stride[0];
|
||||
c.st_round = a->t[4].stride[0];
|
||||
c.st_row = a->t[4].stride[1];
|
||||
*out = c;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int rad_mtp_couple_verify_args(const RadArgs* a, RadMtpCoupleVerifyCall* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
int64_t M, v, nc;
|
||||
const int rc = rad_couple_validate(a, 1, &M, &v, &nc);
|
||||
if (rc != RAD_OK) return rc;
|
||||
RadMtpCoupleVerifyCall c{};
|
||||
c.M = M;
|
||||
c.vocab = v;
|
||||
c.n_cand = nc;
|
||||
c.idx = (const int32_t*)a->t[0].data;
|
||||
c.val = (const float*)a->t[1].data;
|
||||
c.params = (const uint32_t*)a->t[2].data;
|
||||
c.state = (const uint32_t*)a->t[3].data;
|
||||
c.token = (int32_t*)a->t[4].data;
|
||||
for (int i = 0; i < 5; ++i) c.ld[i] = a->t[i].stride[0];
|
||||
*out = c;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
RadKernelInfo rad_spechub_row(int i, RadLaunchFn launch) {
|
||||
RadKernelInfo r{};
|
||||
r.name = i ? "spechub_mtp_couple_verify" : "spechub_mtp_couple_propose";
|
||||
r.op = i ? "mtp_couple_verify" : "mtp_couple_propose";
|
||||
r.family = "draft";
|
||||
r.computes = i ? "maximal coupling over the surviving target candidates, FP64 P"
|
||||
: "x~Q over the final top8, FP64 T1 softmax";
|
||||
r.shape = i ? "M,n_cand,n_vocab" : "M,n_vocab,round,max_rounds<=8";
|
||||
r.dtypes = "f32,i32,u32";
|
||||
r.domain = RAD_DOMAIN_DEVICE;
|
||||
r.priority = 100;
|
||||
r.launch = launch;
|
||||
r.opd_shape = i ? rad_mtp_couple_verify_shape : rad_mtp_couple_propose_shape;
|
||||
return r;
|
||||
}
|
||||
Loaded 100 of 137 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user