Archived
merge 1.12.0: gemma4 E2B/E4B and Nemotron Bolt E4B arrive; the ref2va audio, rows and ABI work carried across
conv1d keeps both stride forms: upstream's causal codec downsample with cu_div (Fish Audio) and the port's explicit-pad non-causal one (the H3 audio encoder's), in libref, libavx and libr4d alike; the ABI takes upstream's 27 on top of the port's RadVideoGenBatch growth.
This commit is contained in:
commit
7c3b5ab7d5
285 files changed
+30500
-2898
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.10.0 LANGUAGES C CXX)
|
||||
project(radiance VERSION 1.12.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
@@ -305,6 +305,9 @@ if(CMAKE_SYSTEM_PROCESSOR MATCHES "^(x86_64|AMD64|amd64)$")
|
||||
add_subdirectory(libavx)
|
||||
endif()
|
||||
add_subdirectory(arch)
|
||||
# spechub: the linear-MTP coupling kernels (--draft-coupling). Built by default; without the flag
|
||||
# no op resolves to its rows.
|
||||
add_subdirectory(plugin/spechub)
|
||||
add_subdirectory(tools)
|
||||
if(RAD_BUILD_TESTS)
|
||||
enable_testing()
|
||||
|
||||
@@ -15,10 +15,12 @@ Written by Deadcode, with contributions from:
|
||||
adaptive draft window, the MoE prefill forms, the sorted operand's decode kernel, two K blocks a
|
||||
pass for up to 80 routed rows, --prefill-span, the towers' lookup tables counted once, and for
|
||||
Gemma 4 its assistant head as a drafter that reads the trunk's cache, bf16 checkpoints, the fused
|
||||
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, and the
|
||||
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files
|
||||
w4a8 decode step, the vision tower and window snapshots that let a prefix hit resume, the
|
||||
Gemma 4 31B heretic-ara and Ornith-1.5-35B-A3B compose files, and Gemma 4's E2B/E4B form (KV-shared
|
||||
layers, per-layer embeddings, clipped vision linears) with NVIDIA-Nemotron-3.5-Bolt-E4B
|
||||
- mechkbfan: the token embedding in the pinned host pool
|
||||
- Code000: the n-gram gather on the card and the MTP head's history-pass skip
|
||||
- Code000: the n-gram gather on the card and the MTP head's history-pass skip, and the MTP draft
|
||||
coupling with its cooperative verify (--draft-coupling)
|
||||
- baKon: three-rank tensor parallelism, serving any world size from the shipped container, the
|
||||
request log, an uneven world's per-rank KV and weights split, --rope-scaling, the model entry's
|
||||
context length, root and capabilities, /props, the three-rank two-shot all-reduce and tiered-int8
|
||||
@@ -33,7 +35,10 @@ Written by Deadcode, with contributions from:
|
||||
- Perire: Gemma 4 26B-A4B with z-lab's DFlash drafter -- its plugin, its kernels in libr4d (the
|
||||
windowed paged attention, pair_argmax, the fused sandwich joins and expert_scale) and the host
|
||||
emulator that tests them, the prefill split into two slices with their all-reduces beside the
|
||||
compute, and the vocabulary-sharded draft head
|
||||
compute, and the vocabulary-sharded draft head; Gemma 4 31B on four cards (its all-reduces fused
|
||||
with the junctions, overlapped with the compute and sent compressed, chained launches with block
|
||||
drafters), the embedding scale rounded as Hugging Face rounds it, and block drafters' drafts
|
||||
accepted on the card
|
||||
- redxherring: --model taking a Hugging Face repo id
|
||||
- Smellyyyy: the idea behind --prefill-interleave
|
||||
- gearwave00001: /v1/messages as Claude Code sends it
|
||||
@@ -41,25 +46,43 @@ Written by Deadcode, with contributions from:
|
||||
- sfjes: Gemma 4 31B dense -- its plugin, its two attention classes and their kernels, and prefix
|
||||
reuse that leaves a windowed group alone -- and --host-headroom-mib
|
||||
- zivius: LiquidAI's LFM2 and LFM2-VL and d1's /v1/systemone, after the design of their Codeberg
|
||||
PR 50, and Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime
|
||||
PR 50, Qwen3-ASR with /v1/audio/transcriptions and /v1/realtime, and Fish Audio drama-3 -- its
|
||||
plugin, its codec encoder and decoder, voice cloning from reference clips, and the torch.save
|
||||
reader
|
||||
- mici81: Gemma 3 dense (TranslateGemma 27B) -- its plugin, the windowed h128 attention, the
|
||||
sandwich junction's all-reduce and its DFlash2 drafter -- the fp8_v4 and k6_v4 KV caches, GPTQ's
|
||||
factorisations through LAPACK and a column-split linear's Hessian from per-rank parts,
|
||||
R4D_AR_MAX_BLOCKS for two engines on one set of cards, and added tokens decoded as HuggingFace
|
||||
decodes them
|
||||
R4D_AR_MAX_BLOCKS for two engines on one set of cards, added tokens decoded as HuggingFace
|
||||
decodes them, the MXFP4 GEMM rows for one to 64 rows and the tiled prefill GEMM's TN=4 form, the
|
||||
fp8 and int8 heads read once up to 128 rows, the pipelined prefill of one sequence on a second
|
||||
lane, Gemma 3's junctions under a lossy wire, the block drafter's short block
|
||||
(--draft-short-from) and the f16 delta-net state cache
|
||||
- eddie168168: the rotated int8 trunk (i8a8h) and the qwen35_w8a8 plugin serving it, and the
|
||||
out-of-tree test at the tree's VOPD setting
|
||||
out-of-tree test at the tree's VOPD setting, and its norm and SiLU producers writing the int8
|
||||
linears' operands directly
|
||||
- davetha: JSON Schema patterns read unanchored, with their shorthand classes and escapes
|
||||
- Nunze: the eight-rank all-reduce's bands, weighted shards from the PCIe links and pieces, the
|
||||
sampler's candidate width at eight ranks, the image test stage's parallelism, budgets and
|
||||
exclusions, jinja's dotted integer index, GLM-5.3-Flash's kernels in libr4d and tool calls whose
|
||||
name the opener opens
|
||||
name the opener opens, GLM-5.3-Flash's vision tower and processor, its decode at a few rows and
|
||||
its DSA indexer split over the ranks, a host-tier restore that makes room as pressure does, KV
|
||||
groups every rank holds kept once a host slot, the eight-rank two-shot in ring order, the MLA
|
||||
row form (--tp-attn-split rows) and DELETE /sessions
|
||||
- John McDonough: GLM-5.3-Flash -- its plugin, its blocks (mHC streams, KDA, the DSA indexer and
|
||||
sparse latent attention, f32-scaled FP8 and MXFP4 experts under sigmoid routing) and their
|
||||
reference and AVX ops -- a Quark export's block-FP8 layers, the signed QSA ranking, the
|
||||
one-sequence KV floor over the live plan, and prefill staging paid by expert residency
|
||||
- Memoria: the dashboard's decode floor and recent window, the sparklines' percentile range, and
|
||||
the bringup time in /stats
|
||||
the bringup time in /stats, the acceptance tiles' live figures and statsdump's size-capped
|
||||
rotation
|
||||
- C_Tamas: control vectors, loaded when the deployment asks and applied as a per-layer residual
|
||||
projection
|
||||
- J-Nova: Unlimited-OCR, and Sage-A1.5 with its vision tower and its DFlash2 drafter
|
||||
- thekk1: the fp8 QK and PV legs of the h256 prefill attention (--attn-prefill-fp8)
|
||||
- lortht: Krea 2's rebalance of the text taps
|
||||
- Quackster: cards with a small PCI BAR, their kernel arguments kept in host memory
|
||||
- farcryjohn: periodic window snapshots that let an edited prompt reuse its prefix
|
||||
- gostar: snapshot-backed prefix KV kept across recomputes
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
|
||||
@@ -34,6 +34,8 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
|
||||
| Gemma 4 31B: int4 trunk, int8 activations and lm_head, DFlash drafter, vision | `gemma4-31b-dense-w4a8-df.rad` (22 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash) | `gemma4-31b-w4a8-df.yaml` |
|
||||
| Gemma 4 31B Q8: int8 trunk and lm_head (Q8_0's grid at group 128), int8 DFlash drafter, vision | `gemma4-31b-dense-q8-df.rad` (33 GiB) | [convert](#convert-a-checkpoint) | `gemma4-31b-q8-df.yaml` |
|
||||
| Gemma 4 31B on four cards: int4 trunk, int8 activations and lm_head, RedHatAI's DFlash2 drafter, vision | `gemma4-31b-dense-w4a8-df2-qkv.rad` (23 GiB) | [download](https://huggingface.co/Ashlyn4202025/gemma4-31b-w4a8-dflash2) | `gemma4-31b-w4a8-df2-tp4.yaml` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B bf16 (Gemma 4 E4B), NVIDIA's DFlash drafter, vision, one card | `nemotron-3.5-bolt-e4b-bf16.rad` (16 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-bf16) | `nemotron-3.5-bolt-e4b-bf16.yaml` |
|
||||
| NVIDIA-Nemotron-3.5-Bolt-E4B int8 (i8a8, Gemma 4 E4B), NVIDIA's DFlash drafter, vision, one card | `nemotron-3.5-bolt-e4b-i8g.rad` (12 GiB) | [download](https://huggingface.co/keptn/nemotron-3.5-bolt-e4b-i8g) | `nemotron-3.5-bolt-e4b-i8g.yaml` |
|
||||
| Qwen-Image 2.1 FP8: text to image and image edits | `qwen-image-2.1-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-fp8) | `qwen-image-2.1.yaml` |
|
||||
| Qwen-Image 2.1 Turbo FP8: the same in 8 steps | `qwen-image-2.1-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-qwen-image-2.1-turbo-fp8) | `qwen-image-2.1-turbo.yaml` |
|
||||
| Krea 2 Turbo FP8: text to image, one card | `krea-2-turbo-fp8.rad` (16 GiB) | [download](https://huggingface.co/StillDeadcode/krea-2-turbo-radiance-fp8) | `krea-2-turbo.yaml` |
|
||||
@@ -45,7 +47,9 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
|
||||
| MiniMax-H3 FP8: video with its stereo soundtrack from text | `minimax-h3-fp8.rad` (60 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-h3-fp8) | `minimax-h3.yaml` |
|
||||
| FastH3 8-Step V2 FP8: the same in eight steps | `fasth3-8-step-v2-fp8.rad` (62 GiB) | [download](https://huggingface.co/StillDeadcode/fasth3-8-step-v2-fp8) | `fasth3.yaml` |
|
||||
| MiniMax-Music3 bf16: songs from lyrics and a description | `minimax-music3-bf16.rad` (20 GiB) | [download](https://huggingface.co/StillDeadcode/minimax-music3-bf16) | `minimax-music3.yaml` |
|
||||
| Unlimited-OCR bf16: document parsing with the DeepEncoder tower | `unlimited-ocr-bf16.rad` (6.2 GiB) | [download](https://huggingface.co/Aijuus/unlimited-ocr-bf16) | `unlimited-ocr-bf16.yaml` |
|
||||
| Breeze-TTS-2 bf16: speech, whole, streamed or live, one card | `breeze-tts2-bf16.rad` (5.5 GiB) | [download](https://huggingface.co/StillDeadcode/radiance-breeze-tts2-bf16) | `breeze-tts2.yaml` |
|
||||
| Fish Audio drama-3: speech with speaker tags and inline direction, voices cloned from reference clips, whole, streamed or live; block-FP8 experts, two cards | `drama3-fp8.rad` (36 GiB) | [convert](#convert-a-checkpoint) | `drama3.yaml` |
|
||||
| Qwen3.8-27B ParoQuant int4, int5 or MXFP4 (learned rotations), DFlash2 drafter, vision | `qwen3.8-27b-paro-int4.rad` (19 GiB; int5 22 GiB) | [convert](#convert-a-checkpoint) | `qwen3.8-27b-paro.yaml` |
|
||||
| TranslateGemma 27B MXFP4 (GPTQ), translation; optional DFlash2 drafter | `translategemma-27b-mxfp4-gptq.rad` (17 GiB) | [convert](#convert-a-checkpoint) | `translategemma-27b.yaml` |
|
||||
| GLM-5.3-Flash: MXFP4 experts and block-FP8 attention (AMD Quark), MTP, vision, eight cards | `glm53-flash-mxfp4.rad` (172 GiB) | [convert](#convert-a-checkpoint) | `glm53-flash.yaml` |
|
||||
@@ -120,7 +124,12 @@ from lyrics and a description, 44.1 kHz stereo, made at about the speed it plays
|
||||
speech in a voice the request describes, made in 0.6 of its playing time on one card, its first
|
||||
streamed audio 0.21 s after the request. Breeze-TTS-2 also speaks text while it is being written,
|
||||
over the `/v1/audio/speech/stream` WebSocket; it is licensed for research and non-commercial use
|
||||
only.
|
||||
only. Fish Audio's drama-3 speaks a script whose speakers and direction are written in it
|
||||
(`<|speaker:1|>`, `[laughs]`), each speaker in the model's voice or one cloned from a reference
|
||||
clip and its transcript, at 0.3 of its playing time on two cards, its first streamed audio
|
||||
0.23 s after the request; under the Fish Audio Community License a service that lets others
|
||||
generate speech with it needs a licence from Fish Audio, and imitating a real person's voice needs
|
||||
their consent.
|
||||
|
||||
## Run with Docker
|
||||
|
||||
@@ -205,6 +214,7 @@ four-rank rows have no compose file. The other models' flags are in their compos
|
||||
| MiniMax-H3 and FastH3 | `--tp 2 --vision-tower-placement ram` |
|
||||
| MiniMax-Music3 | `--tp 2` |
|
||||
| Breeze-TTS-2 | `--tp 1` |
|
||||
| Fish Audio drama-3 | `--tp 2` |
|
||||
|
||||
Every model here runs at up to 32 sequences a step. The Flash-Next rows (except the bf16 reference)
|
||||
and the 27B in bf16 keep 8: on a hybrid model each sequence holds its own recurrent state, and 32 of
|
||||
@@ -308,27 +318,6 @@ ctest --test-dir build -L oot # rebuilds every bundled plugin out o
|
||||
`CMakePresets.json` names the same runs (`ctest --preset fast`, `host`, `gpu`, `full`, `asan`), and
|
||||
[`docs/GUIDE.md`](docs/GUIDE.md) §1.3 describes the tiers and the test binaries' options.
|
||||
|
||||
## Draft acceptance
|
||||
|
||||
Speculative decoding drafts up to `--num-speculative-tokens` tokens a step; the target model
|
||||
verifies them in one pass, and a draft survives only if it matches what the target would have
|
||||
produced. A position is verified only when every earlier position survived, so the same events
|
||||
admit two ratios, and they differ only in the denominator:
|
||||
|
||||
- **Conditional** -- accepted / *reached*: of the drafts actually verified at a position, how
|
||||
many passed. The dashboard's live "conditionally accepted" figure and the per-position bars are
|
||||
conditional. Always the higher number, and it moves with the workload.
|
||||
- **Marginal** -- accepted / *drafted*: of everything the drafter proposed, how much survived.
|
||||
The engine's `draft_accept` (/stats, and `radiance:draft_acceptance_ratio` on /metrics) is
|
||||
marginal, cumulative over the life of the process. Lower by construction, and slow to move.
|
||||
|
||||
They cannot agree, and neither is the other one broken. At depth 3 a step drafts three tokens
|
||||
but reaches position 3 only when 1 and 2 both passed, so marginal is roughly the product of the
|
||||
conditionals: bars reading 56/75/77% give (0.56 + 0.56x0.75 + 0.56x0.75x0.77) / 3 = 43%. A live
|
||||
63% beside a lifetime 43% is one lane, two questions. Quote the conditional when asking "how
|
||||
good is the drafter right now"; quote the marginal when asking "what fraction of draft work
|
||||
became text." Never compare the two across that boundary.
|
||||
|
||||
## Documentation
|
||||
|
||||
| | |
|
||||
|
||||
+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
|
||||
|
||||
+156
-17
@@ -80,6 +80,13 @@ enum {
|
||||
RAD_KVQ_K6V4 = 2
|
||||
};
|
||||
|
||||
/* The products of the prefill attention a deployment accepts in e4m3 (RadBuildCtx::
|
||||
* attn_prefill_fp8, `attn_paged`'s `prefill_fp8`): bits, so both is 3. */
|
||||
enum {
|
||||
RAD_ATTN_FP8_QK = 1, /* Q.K^T, the query rounded to e4m3 after the softmax scale */
|
||||
RAD_ATTN_FP8_PV = 2 /* P.V, the probabilities rounded to e4m3 */
|
||||
};
|
||||
|
||||
typedef struct RadBuildCtx {
|
||||
int rank; /* declare runs once per rank; the plugin declares dimensions */
|
||||
int world_size; /* already divided -- the core inserts no collectives (spec §9) */
|
||||
@@ -174,6 +181,17 @@ typedef struct RadBuildCtx {
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int kv_quant;
|
||||
|
||||
/* ---- appended in ABI 26 (fp8 prefill attention) */
|
||||
/* RAD_ATTN_FP8_* bits from --attn-prefill-fp8: the attention products the deployment accepts
|
||||
* in e4m3 rather than exactly. 0 (the zero-initialised default) is exact. A plugin passes a
|
||||
* nonzero value on as `attn_paged`'s `prefill_fp8` (docs/OPS.md) and omits the parameter at
|
||||
* 0, so an exact declare is unchanged. The engine refuses to start when no resolved kernel
|
||||
* takes it, so a plugin that ignores the field is refused rather than silently exact.
|
||||
*
|
||||
* Zero-defaulted and in the padding after kv_quant, so no other field moves and a plugin built
|
||||
* against the older struct is unchanged. */
|
||||
int attn_prefill_fp8;
|
||||
|
||||
/* ---- appended in ABI 26 (control vectors) */
|
||||
/* A control vector loaded from a GGUF `controlvector` file found for this model, or null.
|
||||
*
|
||||
@@ -190,6 +208,38 @@ typedef struct RadBuildCtx {
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
const struct RadControlVector* cvec;
|
||||
|
||||
/* ---- appended in ABI 27 (row-split prefill attention) */
|
||||
/* 1 from --tp-attn-split rows: from the plugin's split threshold, a prefill-sized step under
|
||||
* tensor parallelism runs attention by rows, each rank all heads of its run of the step's
|
||||
* rows and an all_gather of the runs, instead of by heads. It is faster where the attention
|
||||
* dominates, costs the full-width projections on every rank, and is not bit-identical to the
|
||||
* head split. 0 (the zero-initialised default) is the head split. The engine sets it only
|
||||
* above one rank and only for a plugin whose probe sets RadArchProbe::tp_attn_rows_ok, and
|
||||
* refuses the flag otherwise.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int tp_attn_rows;
|
||||
|
||||
/* ---- appended in ABI 27 (recurrent state at f16) */
|
||||
/* RAD_F16 from --state-cache-dtype f16: the recurrent state caches (RAD_KV_LINEAR groups) are
|
||||
* stored at f16 instead of the plugin's f32, which halves the state pool, its checkpoints and
|
||||
* its traffic and changes the generated text. 0 (the zero-initialised default) is the
|
||||
* plugin's own width. The engine sets it only for a plugin whose probe has
|
||||
* RadArchProbe::state_f16_ok and refuses the flag otherwise.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
uint32_t state_dtype;
|
||||
|
||||
/* ---- appended in ABI 27 (draft coupling) */
|
||||
/* Nonzero from --draft-coupling on: a linear serial drafter samples each round's proposal from
|
||||
* its own shortlist law and declares the planes and ops the coupled verify reads
|
||||
* (abi/rad_spechub.h, docs/OPS.md `mtp_couple_propose`). 0, the zero-initialised default,
|
||||
* declares the greedy drafter. A plugin that cannot couple returns RAD_E_UNSUPPORTED from
|
||||
* declare when it is set; the engine refuses a model whose program carries no coupled planes.
|
||||
*
|
||||
* Trailing and zero-defaulted, so a plugin built against the older struct is unchanged. */
|
||||
int draft_coupling;
|
||||
} RadBuildCtx;
|
||||
|
||||
/* ================================================================== control vectors */
|
||||
@@ -351,13 +401,20 @@ enum {
|
||||
RAD_KV_FULL = 0, /* paged, per-token, growing -- full attention */
|
||||
RAD_KV_WINDOW = 1, /* paged, per-token, bounded by the window */
|
||||
RAD_KV_LINEAR = 2, /* per-sequence, fixed size -- GDN recurrent state */
|
||||
RAD_KV_CONV = 3 /* per-sequence, a rolling window of width-1 + num_spec entries */
|
||||
RAD_KV_CONV = 3, /* per-sequence, a rolling window of width-1 + num_spec entries */
|
||||
/* Paged exactly like RAD_KV_WINDOW, but the window's floor is per sequence and set at
|
||||
* runtime (R-SWA, spec §7.2): `window` is the ring's W, and a sequence keeps everything from
|
||||
* position 0 up to its own prompt (prefill and image rows) plus a ring of W slots after it,
|
||||
* rewritten in place. So the group is sized for the whole context plus one ring a sequence,
|
||||
* never checkpointed, and never reused from the prefix cache. A model that serves a fixed
|
||||
* sliding window declares RAD_KV_WINDOW instead. */
|
||||
RAD_KV_RING = 4
|
||||
};
|
||||
|
||||
typedef struct RadKVGroupDecl {
|
||||
int kind; /* RAD_KV_* */
|
||||
uint32_t dtype;
|
||||
int64_t window; /* RAD_KV_WINDOW: the window; 0 otherwise */
|
||||
int64_t window; /* RAD_KV_WINDOW: the window; RAD_KV_RING: the ring's W; 0 otherwise */
|
||||
int64_t n_head_kv;
|
||||
int64_t head_dim;
|
||||
int64_t state_dim[2]; /* RAD_KV_LINEAR: the per-head state geometry, e.g. {128,128} */
|
||||
@@ -421,6 +478,17 @@ int rad_op_writes(RadBuilder* b, rad_op h, const rad_buf* bufs, int n);
|
||||
* A no-op for a PERSIST or DERIVED buffer, which is live everywhere already. */
|
||||
int rad_buf_concurrent(RadBuilder* b, rad_buf buf);
|
||||
|
||||
/* ---- appended in ABI 27 (the second lane's window) */
|
||||
/* The second lane's window: every op the architecture issues on lane 1 is declared between
|
||||
* rad_lane1_window_begin and rad_lane1_window_end. With a window a rad_buf_concurrent buffer is live
|
||||
* over the window and its own declared uses instead of the whole program, so buffers used only
|
||||
* outside the window (a drafter's, the heads') can share its bytes. The runtime holds the
|
||||
* architecture to it: an op issued on lane 1 outside the window fails the step by name, and an op
|
||||
* issued on lane 0 outside the window joins lane 1 first when lane 1 has work pending. Optional, one
|
||||
* window a program; call both at declare, in order. */
|
||||
int rad_lane1_window_begin(RadBuilder* b);
|
||||
int rad_lane1_window_end(RadBuilder* b);
|
||||
|
||||
/* An uneven shard: this rank's slice of a RAD_SHARD_ROW or RAD_SHARD_COL weight's split dimension
|
||||
* is [lo, hi) rather than an even 1/tp. Rows of each stacked row part for ROW, columns for COL, in
|
||||
* the container's unsharded units. The declared extent must already be `hi - lo` (per row part,
|
||||
@@ -601,7 +669,8 @@ typedef struct RadDrafterDecl {
|
||||
|
||||
/* Where a pass leaves its proposal. 0 = the sampler's token buffer. */
|
||||
rad_buf proposal;
|
||||
int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1 */
|
||||
int64_t proposal_pitch; /* elements a row in `proposal`; 0 means 1, and for a BLOCK
|
||||
* drafter `depth` (less is refused) */
|
||||
|
||||
/* BLOCK only. `mask_token` is the id every unfilled block position embeds; a block drafter
|
||||
* without one cannot run. `window` is the drafter's own sliding window over its own cache, 0
|
||||
@@ -654,14 +723,24 @@ int rad_declare_drafter(RadBuilder* b, const RadDrafterDecl* d);
|
||||
int rad_drafter_shared_kv(RadBuilder* b, int pos_offset);
|
||||
|
||||
/* Whether this engine's launches chain (RadKernelChainFn, abi/rad_abi.h): the core's decision, on
|
||||
* the AQL backend only, which keeps a completion counter per queue -- by default where the model's
|
||||
* plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter
|
||||
* decodes speculatively, or as RADIANCE_CHAIN says. A plugin that places work by whether a kernel
|
||||
* waits in its prologue behind the one before it -- a weight read issued on lane 0 right after its
|
||||
* GEMM -- asks this instead of reading the environment, so it follows that decision. Additive
|
||||
* export; RAD_ABI_VERSION does not move. */
|
||||
* the AQL backend only, which keeps a completion counter per queue, where the model's plugin
|
||||
* measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
|
||||
* speculatively. A plugin that places work by whether a kernel waits in its prologue behind the
|
||||
* one before it -- a weight read issued on lane 0 right after its GEMM -- asks this, so it follows
|
||||
* that decision. Additive export; RAD_ABI_VERSION does not move. */
|
||||
int rad_chain_on(void);
|
||||
|
||||
/* A block drafter that also serves a shorter block: the plugin declared its query pass at `block`
|
||||
* rows a sequence as well as at RadDrafterDecl::block, with the same anchor convention, so the
|
||||
* core may stage a step's block at either. The short block proposes
|
||||
* `block - (RadDrafterDecl::block - depth)` tokens. Called once, after rad_declare_drafter.
|
||||
*
|
||||
* The block is proposed whole, so its length is paid for by every drafting sequence whatever each
|
||||
* verifies: at one sequence a long block's extra drafts pay, at many its rows and its weaker first
|
||||
* positions cost more than they bring. The core picks per step (--draft-short-from). */
|
||||
/* ---- appended in ABI 27 (a block drafter's short block) */
|
||||
int rad_drafter_short_block(RadBuilder* b, int64_t block);
|
||||
|
||||
/* ================================================================== the encoder */
|
||||
/* A media encoder the plugin runs on an encoder pass (RadBatch::enc). The core drives the pass and
|
||||
* reads its result, so the plugin declares it. A plugin that declares none serves text only, and
|
||||
@@ -692,6 +771,12 @@ typedef struct RadEncoderDecl {
|
||||
* the pass and before any other pass runs, so the planner may share its bytes with buffers
|
||||
* no encoder pass touches. */
|
||||
rad_buf out;
|
||||
|
||||
/* ---- appended in ABI 26 (one grid a pass) */
|
||||
/* 1: every segment of a pass has one grid (Item segment height), for an encoder whose
|
||||
* position tables or kernels are per geometry; the core ends a pass where the grid changes.
|
||||
* 0 packs segments of any grid into a pass. */
|
||||
int32_t one_grid;
|
||||
} RadEncoderDecl;
|
||||
|
||||
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d);
|
||||
@@ -866,6 +951,11 @@ typedef struct RadGeneratorDecl {
|
||||
* `cond_rows` a whole number of windows. */
|
||||
int32_t chunk_tokens;
|
||||
int32_t chunk_bos, chunk_eos;
|
||||
|
||||
/* ---- appended in ABI 26 (Krea 2's rebalance) */
|
||||
/* The RAD_GEN_COND_* options (rad_runtime.h) the plugin's COND pass serves, as a mask; a
|
||||
* request asking for another is refused. 0: none. */
|
||||
uint32_t cond_opts;
|
||||
} RadGeneratorDecl;
|
||||
|
||||
/* RadGeneratorDecl::beta_schedule: betas linear in sqrt(beta) (Stable Diffusion's
|
||||
@@ -962,7 +1052,8 @@ typedef struct RadAudioGenDecl {
|
||||
/* The prompt, as text the core tokenises: `{instructions}` is replaced by the request's
|
||||
* instructions (a piece's description, a voice's) and `{input}` by its input text (lyrics, the
|
||||
* words to speak), each first rewritten by the plugin's rad_arch_text_prepare when it exports
|
||||
* one. Special tokens are spelled as text. */
|
||||
* one. Special tokens are spelled as text. NULL for a model that takes no instructions, which
|
||||
* then declares `tmpl_plain` and has a request's instructions refused. */
|
||||
const char* tmpl;
|
||||
/* The unconditional branch is the conditional prompt with every token but the first
|
||||
* `neg_keep_head` and the last `neg_keep_tail` replaced by `neg_token`, so the two branches
|
||||
@@ -1023,6 +1114,36 @@ typedef struct RadAudioGenDecl {
|
||||
* latent: `lat_num` = `lat_den` = 1, `samples_per_latent` samples a frame. */
|
||||
int64_t voc_chunk;
|
||||
int64_t voc_context;
|
||||
|
||||
/* ---- appended in ABI 27 (one-branch speech over a hybrid model, references) */
|
||||
/* Sequences a request runs: 0 or 2, the conditional and unconditional branches above; 1, the
|
||||
* conditional one alone, for a model without guidance (no unconditional prompt is rendered,
|
||||
* a request's guidance must be 1, and every per-entry array of a PROMPT or FRAME pass has one
|
||||
* entry a lane, its `slot` the lane itself). The KV, the prompt's rows and a frame's rows then
|
||||
* cost half. */
|
||||
int32_t branches;
|
||||
/* Nonzero: the `{input}` slot is tokenised with its special tokens, which the template's own
|
||||
* text always is, so a caller can write the model's speaker tags. The plugin's
|
||||
* rad_arch_text_prepare then refuses the control tokens a caller must not write. */
|
||||
int32_t input_special;
|
||||
/* References (voice cloning): with `tmpl_ref`, a request may carry up to `ref_max` of them,
|
||||
* each a transcript and a clip of the voice saying it, which the plugin encodes into frames
|
||||
* in the request's PROMPT pass (whole prompts only: `prompt_whole`). `tmpl_ref` is the prompt
|
||||
* of a request with references, `{references}` each of them rendered from `ref_item` in turn
|
||||
* and `{input}` as in `tmpl_plain`. `ref_item` is one reference: `{index}` its number from 1,
|
||||
* `{text}` its transcript (rewritten by rad_arch_text_prepare as RAD_TEXT_REFERENCE) and
|
||||
* `{audio}` its frames, one prompt row each (RadAudioGenBatch::ref_frame); the text before
|
||||
* `{audio}` is tokenised as one segment with its special tokens (the transcript's own, which
|
||||
* prepare() has limited to those a caller may write), and so is the text after it. A clip is
|
||||
* mono f32 in [-1, 1] at `ref_rate`, right-padded with zeros to a whole number of `ref_hop`
|
||||
* samples, each `ref_hop` samples one frame; a request's clips hold at most `ref_max_samples`
|
||||
* samples together. NULL `tmpl_ref`: references are refused. */
|
||||
const char* tmpl_ref;
|
||||
const char* ref_item;
|
||||
int64_t ref_rate;
|
||||
int64_t ref_hop;
|
||||
int64_t ref_max_samples;
|
||||
int32_t ref_max;
|
||||
} RadAudioGenDecl;
|
||||
|
||||
int rad_declare_audio_generator(RadBuilder* b, const RadAudioGenDecl* d);
|
||||
@@ -1477,12 +1598,28 @@ typedef struct RadArchProbe {
|
||||
* libr4d has their rows for its attention geometry. A layout whose bit is clear is refused at
|
||||
* startup with the plugin named. */
|
||||
int32_t kv_quant_ok;
|
||||
|
||||
/* ---- appended in ABI 26 (chained launches, control vectors) */
|
||||
/* Nonzero when this plugin measured its speculative step faster with chained launches
|
||||
* (RadKernelChainFn: a dependent kernel waits in its own prologue rather than behind the
|
||||
* queue's barrier bit). With a drafter decoding speculatively on the AQL backend, the core
|
||||
* then takes them by default; RADIANCE_CHAIN overrides either way. Zero keeps them off: plain
|
||||
* decode measured slower chained, and a plugin that never measured them asks for nothing. */
|
||||
* then takes them. Zero keeps them off: plain decode measured slower chained, and a plugin
|
||||
* that never measured them asks for nothing. */
|
||||
int32_t chain_pays;
|
||||
/* Nonzero when the plugin applies RadBuildCtx::cvec for this model. --control-vector is
|
||||
* refused at startup with the plugin named when this is 0. */
|
||||
int32_t control_vector_ok;
|
||||
|
||||
/* ---- appended in ABI 27 (row-split prefill attention) */
|
||||
/* Nonzero when the plugin serves RadBuildCtx::tp_attn_rows for this model. --tp-attn-split
|
||||
* rows is refused at startup with the plugin named when this is 0. */
|
||||
int32_t tp_attn_rows_ok;
|
||||
|
||||
/* ---- appended in ABI 27 (recurrent state at f16) */
|
||||
/* Nonzero when the plugin declares its recurrent state at f16 under RadBuildCtx::state_dtype
|
||||
* and its kernels read that width. --state-cache-dtype f16 is refused at startup with the
|
||||
* plugin named when this is 0. */
|
||||
int32_t state_f16_ok;
|
||||
} RadArchProbe;
|
||||
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
@@ -1661,11 +1798,13 @@ const RadAudioFormat* rad_arch_audio_format(const RadModelMeta* meta);
|
||||
* as given. Training data has conventions a client does not know -- section tags on lines of
|
||||
* their own and lower case, no markdown in a description -- and only the plugin knows them.
|
||||
*
|
||||
* `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8. Writes at most `cap` bytes, the NUL included,
|
||||
* and returns the length the whole result needs without its NUL (call again with more room when
|
||||
* it is >= cap), or a negative status for text the model cannot take. Called on HTTP threads, so
|
||||
* it keeps no state. */
|
||||
enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2 };
|
||||
* `field` is RAD_TEXT_*, `in` NUL-terminated UTF-8: the instructions, the input, or a
|
||||
* reference's transcript (RadAudioGenDecl::ref_item's `{text}`). Writes at most `cap` bytes, the
|
||||
* NUL included, and returns the length the whole result needs without its NUL (call again with
|
||||
* more room when it is >= cap), or a negative status for text the model cannot take, with the
|
||||
* reason in `out` (NUL-terminated within `cap`) when it has one to give the caller. Called on
|
||||
* HTTP threads, so it keeps no state. */
|
||||
enum { RAD_TEXT_INSTRUCTIONS = 1, RAD_TEXT_INPUT = 2, RAD_TEXT_REFERENCE = 3 };
|
||||
int64_t rad_arch_text_prepare(int field, const char* in, char* out, int64_t cap);
|
||||
|
||||
/* The layout of a video generator's passes (rad_declare_video_generator), which only the model
|
||||
|
||||
+43
-3
@@ -243,6 +243,19 @@ typedef struct RadBatch {
|
||||
/* A video generator's pass (rad_declare_video_generator; `gen` is one of its
|
||||
* RAD_GEN_PASS_*): its payload. Null on every other step. */
|
||||
const struct RadVideoGenBatch* vgen_b;
|
||||
|
||||
/* ---- appended in ABI 26 (control vectors) */
|
||||
/* Host-side: nonzero when some row of this pass takes the loaded control vector (its
|
||||
* `projection_on_rows` entry is 1). A projection skips a zero row anyway, so a block issues
|
||||
* no projection op when this is 0 and the pass is the one a deployment without a vector runs. */
|
||||
int32_t control_vector;
|
||||
|
||||
/* ---- appended in ABI 26 (per-segment encoder grids) */
|
||||
/* host: [enc_n_seg] each segment's grid in patches, the same values enc_coord planes 2 and 3
|
||||
* carry. A plugin that has to pick a geometry before it issues ops (a tower with one set of
|
||||
* position tables per grid) reads them here; they live as long as the pass. */
|
||||
const int32_t* enc_seg_h;
|
||||
const int32_t* enc_seg_w;
|
||||
} RadBatch;
|
||||
|
||||
/* What a generator pass carries beside the step batch's own fields, which keep their meanings:
|
||||
@@ -379,13 +392,15 @@ typedef struct RadGenBatch {
|
||||
* where a window's end-of-text marker sits. */
|
||||
const int32_t* tokens_h;
|
||||
/* ---- appended in ABI 26 (Krea 2's rebalance) */
|
||||
/* COND: the request's RAD_GEN_COND_* options, 0 for none. */
|
||||
/* COND: the request's RAD_GEN_COND_* options, 0 for none and on every other pass. Only
|
||||
* options the plugin declares (RadGeneratorDecl::cond_opts) are set. */
|
||||
int32_t cond_opts;
|
||||
} RadGenBatch;
|
||||
|
||||
/* A request's conditioning options on a COND pass (RadGenBatch::cond_opts). */
|
||||
enum {
|
||||
RAD_GEN_COND_REBALANCE = 1 /* Krea 2: the text taps at the plugin's fixed rebalance gains */
|
||||
RAD_GEN_COND_REBALANCE = 1 /* the conditioning at the plugin's fixed rebalance gains (the
|
||||
* request field `rebalance`; Krea 2: its text taps) */
|
||||
};
|
||||
|
||||
/* An entry's flags on a DENOISE pass. */
|
||||
@@ -474,6 +489,30 @@ typedef struct RadAudioGenBatch {
|
||||
/* VOCODE with RadAudioGenDecl::voc_chunk: the lane's first frame the pass reads, counted
|
||||
* from the first kept frame. 64 bits so that it starts past the struct's ABI 18 end. */
|
||||
int64_t voc_frame0;
|
||||
|
||||
/* ---- appended in ABI 27 (a frame head at the previous row, references) */
|
||||
/* FRAME, one value per entry ([n_seq]): the row before the frame's own row -- the one whose
|
||||
* hidden state the frame is sampled from -- as its KV slot, its position, and the context
|
||||
* through it (position + 1). A model whose frame head attends at that row (Fish Audio
|
||||
* drama-3's codebook tower, layers bound to the language model's full-attention group) issues
|
||||
* those layers there, before the language model runs at the frame's own row. */
|
||||
const int32_t* prev_slot;
|
||||
const int32_t* prev_pos;
|
||||
const int32_t* prev_used;
|
||||
|
||||
/* PROMPT of a request with references (RadAudioGenDecl::tmpl_ref; n_ref 0 without): its
|
||||
* clips' samples end to end (`ref_samples` f32 on the device), the clips' bounds in samples
|
||||
* ([n_ref + 1], each a whole number of RadAudioGenDecl::ref_hop), and for every row of the
|
||||
* pass the frame of the clips it is or -1 for a token row ([n_tok]), frames counted over the
|
||||
* clips in order, frame f the samples [f ref_hop, (f + 1) ref_hop). A frame's row stages
|
||||
* token 0; the plugin embeds the frame there instead. */
|
||||
int64_t n_ref;
|
||||
int64_t ref_samples;
|
||||
const float* ref_audio;
|
||||
const int32_t* ref_cu;
|
||||
const int32_t* ref_cu_h;
|
||||
const int32_t* ref_frame;
|
||||
const int32_t* ref_frame_h;
|
||||
} RadAudioGenBatch;
|
||||
|
||||
/* A window entry's flags on a WINDOW pass. FIRST is RAD_GEN_F_FIRST's bit and the others are clear
|
||||
@@ -738,7 +777,8 @@ int rad_issue(RadCtx* c, rad_op op, const RadOperand* opd, int n_opd, int64_t n)
|
||||
* the all-reduce numbers its scratch slots per launch and the ranks must agree; a kernel with a
|
||||
* device-wide arrival counter must key it on the stream (libr4d's split-K GEMM does), or it may
|
||||
* not run here; and every buffer the second lane touches must be named to rad_buf_concurrent,
|
||||
* because the planner packs transients from one linear order. */
|
||||
* because the planner packs transients from one linear order (live for the whole program, or across
|
||||
* the second lane's window where the architecture declares one, abi/rad_builder.h). */
|
||||
int rad_lane(RadCtx* c, int lane);
|
||||
int rad_lane_join(RadCtx* c, int from, int to);
|
||||
|
||||
|
||||
@@ -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 */
|
||||
+37
-24
@@ -596,25 +596,30 @@ inline rad_op rw(RadBuilder* b, rad_op h,
|
||||
* (core/runtime/ctx.h): it is no collective, keeps no counter and touches no arena byte.
|
||||
*
|
||||
* Only at decode and verify heights, up to kPrefetchRows rows: a DFlash2 verify's 8 a sequence, a
|
||||
* z-lab DFlash verify's 16, a plain decode's one. With the ceiling at 64, a prompt's prefill steps
|
||||
* (40 rows on the 31B's test prompt) took the reads too, and a freshly started 31B server's first
|
||||
* greedy reply then differed on 4 of 6 starts (4x R9700, the cards' memory scribbled before each
|
||||
* start); at 16, and with no reads at all, 0 of 6. Per-op output hashes later located that
|
||||
* divergence at the prefill all-reduce's first reuse of a double-buffered slot: a race in the
|
||||
* all-reduce, which its full fence on prefill-sized messages (libr4d) cures, not in anything the
|
||||
* reads touch. The reads stay off prompt steps all the same. */
|
||||
* z-lab DFlash verify's 16, a plain decode's one. Prompt steps never take the reads: beside the
|
||||
* prefill all-reduces they made a fresh server's first greedy reply differ, the slot-reuse race
|
||||
* that libr4d's full fence on prefill-sized four-rank messages (kArFenceFromElems) also cures. */
|
||||
constexpr int64_t kPrefetchRows = 16;
|
||||
/* The read goes on lane 0 itself, right after the GEMM, where its chained form (libr4d
|
||||
* r4dchain_prefetch) waits for that GEMM and then reads beside the collective after it without
|
||||
* holding the collective: no join between the lanes, so no record on the GEMM and no barrier bit
|
||||
* on it, and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1. On
|
||||
* 4x R9700 (31B DFlash2, three rounds, every reply identical): code 385-386 tok/s against 363-365,
|
||||
* prose 284-286 against 269-270, decode after a 6.4k prompt 580-583 against 538-541. Only where
|
||||
* launches chain (rad_chain_on, the core's decision), since a plain launch would read in series
|
||||
* there; elsewhere the read goes on lane 1, behind a join from lane 0. */
|
||||
/* Where launches chain (rad_chain_on, the core's decision) the read goes on lane 0 itself, right
|
||||
* after the GEMM: its chained form (libr4d r4dchain_prefetch) waits for that GEMM and then reads
|
||||
* beside the collective after it without holding the collective, so there is no join between the
|
||||
* lanes and the read starts as the GEMM's last block ends rather than ~10 us later on lane 1 (on
|
||||
* 4x R9700, the 31B with DFlash2 decoded 6-8% faster than with the read on lane 1). A plain launch
|
||||
* would read in series on lane 0, so elsewhere the read goes on lane 1, behind a join from lane
|
||||
* 0. */
|
||||
inline bool prefetch_lane0() { return rad_chain_on() != 0; }
|
||||
/* RADIANCE_PREFETCH_BESIDE=0 issues none of these reads. Beside another server on the same card
|
||||
* the lane-1 form costs more than it gains: the card has fewer hardware queue slots than the two
|
||||
* servers have queues, and the join puts a queue switch into every decode step. */
|
||||
inline bool prefetch_beside_on() {
|
||||
static const bool on = [] {
|
||||
const char* e = std::getenv("RADIANCE_PREFETCH_BESIDE");
|
||||
return !(e && e[0] == '0' && e[1] == 0);
|
||||
}();
|
||||
return on;
|
||||
}
|
||||
inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
if (!op || T > kPrefetchRows) return;
|
||||
if (!op || T > kPrefetchRows || !prefetch_beside_on()) return;
|
||||
if (prefetch_lane0()) {
|
||||
RAD_ISSUE(c, op, RAD_W(w));
|
||||
return;
|
||||
@@ -622,15 +627,9 @@ inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
if (rad_lane_join(c, 0, 1) == RAD_OK && rad_lane(c, 1) == RAD_OK) RAD_ISSUE(c, op, RAD_W(w));
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
/* RADIANCE_PREFETCH=0 declares no reads at all (docs/GUIDE.md); read at declare. */
|
||||
inline bool prefetch_enabled() {
|
||||
const char* e = std::getenv("RADIANCE_PREFETCH");
|
||||
return !(e && !std::strcmp(e, "0"));
|
||||
}
|
||||
/* The `prefetch` of `w`'s first `bytes`, where a library serves it and the reads are on; 0
|
||||
* otherwise. */
|
||||
/* The `prefetch` of `w`'s first `bytes` where a library serves it; 0 otherwise. */
|
||||
inline rad_op decl_prefetch(RadBuilder* b, rad_weight w, int64_t bytes) {
|
||||
if (!w || bytes <= 0 || !prefetch_enabled() || !rad_op_declared(b, "prefetch")) return 0;
|
||||
if (!w || bytes <= 0 || !rad_op_declared(b, "prefetch")) return 0;
|
||||
return RAD_OP(b, "prefetch", RAD_PARAMS(RAD_INT("bytes", bytes)), RAD_WEIGHTS(w));
|
||||
}
|
||||
|
||||
@@ -687,6 +686,9 @@ struct Geom {
|
||||
/* Messages below this many bytes use the exact all-reduce even with a lossy wire. Passed as
|
||||
* `all_reduce`'s `min_bytes`; 0 leaves the default to the kernel plugin. */
|
||||
int64_t wire_min_bytes = 0;
|
||||
/* RAD_ATTN_FP8_* bits: the attention products accepted in e4m3 (RadBuildCtx describes it).
|
||||
* decl_attn passes it on as `attn_paged`'s `prefill_fp8`. */
|
||||
int attn_prefill_fp8 = 0;
|
||||
float eps = 1e-6f;
|
||||
/* GemmaRMSNorm's `1 +`. Qwen3.5, Qwen3-Next and Gemma normalise with `x_hat * (1 + w)` and
|
||||
* store `w` near 0.1, so reading it as a plain gain shrinks every normed activation 5-10x. An
|
||||
@@ -957,6 +959,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
|
||||
g.world = c->world_size ? c->world_size : 1;
|
||||
g.wire_exact= c->tp_wire_lossy ? 0 : 1;
|
||||
g.wire_min_bytes = c->tp_wire_min_bytes;
|
||||
g.attn_prefill_fp8 = c->attn_prefill_fp8;
|
||||
g.eps = m->rms_eps;
|
||||
g.theta = m->rope_theta;
|
||||
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
|
||||
@@ -1163,6 +1166,16 @@ inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* An `attn_paged` op with the deployment's `prefill_fp8` appended (docs/OPS.md). At 0 the
|
||||
* parameters are passed unchanged, so op identities and tune keys do not change. */
|
||||
inline rad_op decl_attn(RadBuilder* b, const Geom& g, const char* name,
|
||||
const RadParam* params, int n, const rad_weight* weights, int nw) {
|
||||
if (g.attn_prefill_fp8 == 0) return rad_decl_op(b, name, params, n, weights, nw);
|
||||
std::vector<RadParam> p(params, params + n);
|
||||
p.push_back(RAD_INT("prefill_fp8", g.attn_prefill_fp8));
|
||||
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
|
||||
}
|
||||
|
||||
/* Reads a model's rotary scaling into `g.rope_scale` and `g.yarn`. Every architecture calls it
|
||||
* after geom_from, for the target ("") and for a drafter with its own config ("draft."). Only the
|
||||
* free-form keys are read; RadModelMeta::rope_scale is not, since a factor without its type would
|
||||
|
||||
@@ -139,7 +139,7 @@ inline int AttnBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
|
||||
/* attn_paged before kv_store: block_size is RAD_DERIVED, read off the resolved attention
|
||||
* kernel and back into kv_store with rad_kv_block_size() (rad_block_attn_gated.h says why). */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
|
||||
@@ -124,7 +124,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size` (rad_block_attn_gated.h
|
||||
* explains declare vs issue order). */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0), RAD_INT("n_head", g.n_head),
|
||||
|
||||
@@ -195,7 +195,7 @@ inline int AttnGatedBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, in
|
||||
*
|
||||
* The ranged parameter is q_len, not M: 1 at decode, up to n_spec+1 at a verify, thousands in
|
||||
* a prefill chunk, with a libr4d kernel per band. `scale` defaults to 1/sqrt(head_dim). */
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
op_attn = rw(b, decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
|
||||
@@ -157,6 +157,21 @@ struct AttnGatedFP8 {
|
||||
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
|
||||
/* Whether step() with `own_ar` false runs the dense path a piece at a time over a caller's
|
||||
* normed pieces (ArPieces::in_ready): one prefill sequence in two pieces, each the chunk a
|
||||
* span of 1 makes, on the unfused prologue with one rotary component per token (every token's
|
||||
* components agree, so plane 0 of an M-RoPE batch's positions is each token's position) and
|
||||
* the gate quantised by gate_quant_fp8. */
|
||||
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
return pieces && pieces->in_ready && pieces->cu && pieces->cuts(T) &&
|
||||
T <= 2 * pieces->rows && !op_add && !op_fill && op_gq && !op_sig && !qsa_sel &&
|
||||
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL &&
|
||||
!(T <= fused_rows) && batch->positions && !rope_mixed(batch) &&
|
||||
kvb && kvb->slot_mapping && kvb->block_table && kvb->seqused;
|
||||
}
|
||||
};
|
||||
|
||||
inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
@@ -293,7 +308,7 @@ inline int AttnGatedFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int
|
||||
|
||||
/* Declared before kv_store, which reads back the resolved `block_size`
|
||||
* (rad_block_attn_gated.h). */
|
||||
op_attn = RAD_OP(b, "attn_paged",
|
||||
op_attn = decl_attn(b, g, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
@@ -477,6 +492,51 @@ inline void AttnGatedFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
/* One prefill sequence in two pieces over the caller's normed input (takes_pieces): the
|
||||
* projections, prologue, cache store, attention, gate and out projection of the first piece,
|
||||
* then the second's, so the first piece's reduction runs beside all of the second piece's
|
||||
* work. Each piece is the chunk a span of 1 makes: its rows, its positions, its slots, and an
|
||||
* attention over its own query bounds (ArPieces::cu) that sees the cache up to its own end --
|
||||
* the first piece's position after its last row, the step's seqused for the second, which
|
||||
* reads the first piece's keys from the cache as a later chunk would. */
|
||||
if (!own_ar && takes_pieces(batch, pieces)) {
|
||||
const int64_t R = pieces->rows, hd = g.head_dim, qw = g.q_dim();
|
||||
const int64_t qgw = g.n_head * 2 * hd, kvw = g.n_head_kv * hd;
|
||||
const int64_t tpitch = kvb->block_table_pitch;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p == 0 ? 0 : R;
|
||||
const int64_t n = p == 0 ? R : T - R;
|
||||
const int32_t* pos = (batch->rope_pos ? batch->rope_pos : batch->positions) + r0;
|
||||
qg.step(c, w.h, w.qg, T, r0, n);
|
||||
kp.step(c, w.h, w.k, T, r0, n);
|
||||
vp.step(c, w.h, w.v, T, r0, n);
|
||||
RAD_ISSUE_N(c, op_q_norm, n * g.n_head,
|
||||
bcol_at(w.qg, r0, qgw, 0, hd, n), RAD_W(w_q_norm),
|
||||
brow_slice(w.q, r0, n, qw));
|
||||
RAD_ISSUE_N(c, op_k_norm, n * g.n_head_kv,
|
||||
brow_slice(w.k, r0, n, kvw), RAD_W(w_k_norm),
|
||||
brow_slice(w.k, r0, n, kvw));
|
||||
RAD_ISSUE_N(c, op_rope_q, n, brow_slice(w.q, r0, n, qw), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_rope_k, n, brow_slice(w.k, r0, n, kvw), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_kv_store, n,
|
||||
brow_slice(w.k, r0, n, kvw), brow_slice(w.v, r0, n, kvw),
|
||||
praw(slot + r0, RAD_I32, n), kv_cache(kv, layer));
|
||||
RAD_ISSUE_N(c, op_attn, n,
|
||||
brows(w.q, T), kv_cache(kv, layer), praw2(table, RAD_I32, 1, tpitch),
|
||||
praw(p == 0 ? batch->positions + R : used, RAD_I32, 1),
|
||||
RAD_NONE, RAD_NONE, praw(pieces->cu + p, RAD_I32, 2),
|
||||
brows(w.attn.x, T));
|
||||
RAD_ISSUE_N(c, op_gq, n * g.n_head,
|
||||
bcol_at(w.qg, r0, qgw, hd, hd, n), brow_slice(w.attn.x, r0, n, qw),
|
||||
brow_slice(w.attn.cq(), r0, n, qw),
|
||||
brow_slice(w.attn.cs(), r0, n, fp8_blocks(qw)),
|
||||
brow_slice(w.attn.x, r0, n, qw));
|
||||
o.step(c, w.attn, w.h.x, T, r0, n);
|
||||
if (p == 0) pieces->hand(r0, n);
|
||||
}
|
||||
return;
|
||||
}
|
||||
|
||||
if (!ext_in) nq_h.step(c, T);
|
||||
if (op_fill) {
|
||||
/* Attention-zero rank: zero output, then the reduce and the residual. */
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -139,6 +139,13 @@ struct GdnFP8 {
|
||||
* trailing add, which would read the delta before the reduction. */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool own_ar = true,
|
||||
ArPieces* pieces = nullptr) const;
|
||||
/* Whether step() with `own_ar` false runs the whole block a piece at a time over `pieces`
|
||||
* (its piece path), asked by a caller that must know before it commits to a schedule. */
|
||||
bool takes_pieces(const RadBatch* batch, const ArPieces* pieces) const {
|
||||
return pieces && pieces->cu && pieces->cuts(batch->n_tok) &&
|
||||
batch->n_tok <= 2 * pieces->rows && (ext_in || pieces->in_ready) && !op_add &&
|
||||
batch->n_seq == 1 && batch->phase == RAD_PHASE_PREFILL;
|
||||
}
|
||||
/* Whether a step of T rows issues the all-reduce itself, asked by a caller before taking it
|
||||
* over; and that all-reduce over rows [r0, r0 + rows) of the output. */
|
||||
bool issues_ar(int64_t T) const { return op_ar && !ar_taken(g, T, ar_out, ar_out_take); }
|
||||
@@ -389,10 +396,10 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
* piece the chunk a span of 1 makes (the projection over its rows; the convolution, solve and
|
||||
* scan over its bounds, with the state handed on through the cache; the gated norm, quantiser
|
||||
* and out projection), so the first piece's reduction runs beside all of the second piece's
|
||||
* work. The second piece reads the history the first left in the convolution slot: a spanned
|
||||
* step is past the prompt's first interval, so its context length is never zero. */
|
||||
if (!own_ar && pieces && pieces->cu && pieces->cuts(T) && T <= 2 * pieces->rows && ext_in &&
|
||||
!op_add && S == 1 && batch->phase == RAD_PHASE_PREFILL) {
|
||||
* work. The second piece reads the history the first left in the convolution slot, so each
|
||||
* piece passes its own context length, its first row's position: the step's would tell the
|
||||
* second piece of a prompt's first chunk that it has none. */
|
||||
if (!own_ar && takes_pieces(batch, pieces)) {
|
||||
const int64_t in_w = conv_dim + v_dim;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p * pieces->rows;
|
||||
@@ -405,7 +412,7 @@ inline void GdnFP8::step(RadCtx* c, const RadBatch* batch, bool own_ar,
|
||||
bcol(w.in.x, 0, conv_dim, T), RAD_W(w_conv), RAD_NONE, RAD_W(w_a_log),
|
||||
RAD_W(w_dt_bias), kv_cache(kv_conv, layer), praw(cu, RAD_I32, 2),
|
||||
bcol(w.ab, 0, H, T), bcol(w.ab, H, H, T),
|
||||
praw(cv_idx, RAD_I32, 1), praw(batch->ctx_lens, RAD_I32, 1),
|
||||
praw(cv_idx, RAD_I32, 1), praw(batch->positions + r0, RAD_I32, 1),
|
||||
brows(w.q, T), brows(w.k, T), brows(w.v, T),
|
||||
brows(w.gdec, T), brows(w.beta, T));
|
||||
RAD_ISSUE_N(c, op_kkt, n,
|
||||
|
||||
@@ -19,6 +19,15 @@
|
||||
* replace the image's placeholder embeddings (which the text model scales by sqrt(n_embd); the
|
||||
* image rows are not scaled).
|
||||
*
|
||||
* Clipped linears (vision_config.use_clipped_linears, Gemma 4 E2B/E4B): every projection clamps its
|
||||
* input and its output to bounds the checkpoint stores (`<proj>.input_min/max`, `output_min/max`;
|
||||
* transformers' Gemma4ClippableLinear). The tower keeps its fused q|k|v and gate|up GEMMs, so it
|
||||
* takes the input bounds of q_proj (and of gate_proj) for the fused input, q_proj's output bounds for
|
||||
* q's columns, k_proj's for k's and v's, and gate_proj's output bounds for gate|up. That is exact
|
||||
* where the fused parts share their bounds, as NVIDIA's E4B does in all 16 layers (k and v share the
|
||||
* input bounds of q and their output bounds, up shares gate's). The bound weights are one bf16
|
||||
* element each, read by `clamp`.
|
||||
*
|
||||
* One encoder pass carries RadBuildCtx::max_enc_patches patches over any number of segments (an
|
||||
* image, or one frame of a video). Every rank runs the whole tower (engine_mm.cpp), so its weights
|
||||
* are replicated (RAD_SHARD_NONE) and each rank writes the rows into its own copy of the embedding
|
||||
@@ -41,8 +50,12 @@ struct Gemma4Vision {
|
||||
rad_weight pre_ff = 0, gate_up = 0, down = 0, post_ff = 0;
|
||||
rad_op op_in = 0, op_qkv = 0, op_qk = 0, op_attn = 0, op_o = 0, op_pa = 0, op_add1 = 0;
|
||||
rad_op op_pf = 0, op_gu = 0, op_act = 0, op_down = 0, op_pff = 0, op_add2 = 0;
|
||||
/* clipped linears: the bounds (lo, hi) of the nine clamps, and the clamps */
|
||||
enum { C_QKV_IN, C_Q_OUT, C_KV_OUT, C_O_IN, C_O_OUT, C_GU_IN, C_GU_OUT, C_DN_IN, C_DN_OUT, C_N };
|
||||
rad_weight lo[C_N] = {}, hi[C_N] = {};
|
||||
rad_op op_c[C_N] = {};
|
||||
};
|
||||
bool on = false, standardize = false;
|
||||
bool on = false, standardize = false, clip = false;
|
||||
int64_t P = 0, R = 0, width = 0, heads = 0, hd = 0, ff = 0, patch_dim = 0, pool = 0;
|
||||
int64_t npos = 0, n_embd = 0;
|
||||
rad_weight w_in = 0, w_px = 0, w_py = 0, w_proj = 0, w_sbias = 0, w_sscale = 0;
|
||||
@@ -88,15 +101,14 @@ struct Gemma4Vision {
|
||||
(long long)pool, (long long)depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Clipped linears (their bounds are buffers the vision checkpoint states as infinite) and
|
||||
* any rotary or activation other than the 2-D one and gelu-tanh are refused by name. */
|
||||
if (rad_meta_geti(m, "vision_config.use_clipped_linears", 0) ||
|
||||
(std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
|
||||
/* Any rotary or activation other than the 2-D one and gelu-tanh is refused by name. */
|
||||
if ((std::strcmp(rt, "default") && std::strcmp(rt, "axial")) ||
|
||||
std::strcmp(act, "gelu_pytorch_tanh")) {
|
||||
fprintf(stderr, "radiance: %s: this vision tower uses clipped linears, a '%s' rotary or "
|
||||
"a '%s' activation, which it does not serve\n", who, rt, act);
|
||||
fprintf(stderr, "radiance: %s: this vision tower uses a '%s' rotary or a '%s' "
|
||||
"activation, which it does not serve\n", who, rt, act);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
clip = rad_meta_geti(m, "vision_config.use_clipped_linears", 0) != 0;
|
||||
n_embd = model_embd;
|
||||
patch_dim = 3 * patch * patch;
|
||||
const int64_t kk = pool * pool;
|
||||
@@ -154,6 +166,27 @@ struct Gemma4Vision {
|
||||
l.gate_up = decl_w(b, nm.f("v.blk.%lld.gate_up", li), RAD_BF16, {2 * ff, width}, A, N, g);
|
||||
l.down = decl_w(b, nm.f("v.blk.%lld.down", li), RAD_BF16, {width, ff}, A, N, g);
|
||||
l.post_ff = decl_w(b, nm.f("v.blk.%lld.post_ff", li), RAD_BF16, {width}, A, N, g);
|
||||
if (clip) {
|
||||
/* clamp k -> the checkpoint projection whose bound it takes, and which bound */
|
||||
static const char* const proj[Layer::C_N] = {
|
||||
"self_attn.q_proj", "self_attn.q_proj", "self_attn.k_proj", "self_attn.o_proj",
|
||||
"self_attn.o_proj", "mlp.gate_proj", "mlp.gate_proj", "mlp.down_proj",
|
||||
"mlp.down_proj" };
|
||||
static const bool in_side[Layer::C_N] = { true, false, false, true, false, true,
|
||||
false, true, false };
|
||||
for (int k = 0; k < Layer::C_N; ++k) {
|
||||
const char* side = in_side[k] ? "input" : "output";
|
||||
const char* lo_n = nm.f("v.blk.%lld.clip%d.lo", li, k);
|
||||
const char* hi_n = nm.f("v.blk.%lld.clip%d.hi", li, k);
|
||||
RAD_ARCH_TRY(map_copy(b, lo_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_min", V, li,
|
||||
proj[k], side)));
|
||||
RAD_ARCH_TRY(map_copy(b, hi_n, nm.ckpt("%s.encoder.layers.%lld.%s.%s_max", V, li,
|
||||
proj[k], side)));
|
||||
l.lo[k] = decl_w(b, lo_n, RAD_BF16, {1}, A, N, g);
|
||||
l.hi[k] = decl_w(b, hi_n, RAD_BF16, {1}, A, N, g);
|
||||
if (!l.lo[k] || !l.hi[k]) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
b_x = decl_b(b, nm.f("v.x"), RAD_BF16, {P, width});
|
||||
@@ -198,6 +231,11 @@ struct Gemma4Vision {
|
||||
RAD_INT("vocab_offset", 0), RAD_F64("mult", 1.0)),
|
||||
RAD_WEIGHTS(w));
|
||||
};
|
||||
auto clamp = [&](int64_t n, rad_weight lo, rad_weight hi) {
|
||||
return RAD_OP(b, "clamp", RAD_PARAMS(RAD_RANGE("M", 1, P), RAD_INT("n", n),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_WEIGHTS(lo, hi));
|
||||
};
|
||||
auto gain = [&](rad_weight w) {
|
||||
return RAD_OP(b, "mul_weight", RAD_PARAMS(RAD_RANGE("M", 1, R), RAD_INT("n", width),
|
||||
RAD_STR("dtype", "bf16"), RAD_INT("scalar", 0)),
|
||||
@@ -212,6 +250,19 @@ struct Gemma4Vision {
|
||||
char sec[48];
|
||||
std::snprintf(sec, sizeof sec, "%lld %lld", (long long)(hd / 4), (long long)(hd / 4));
|
||||
for (Layer& l : L) {
|
||||
/* the clamps, each in place on the one buffer its linear reads or writes (each of those
|
||||
* is read by that linear alone, or by what follows it) */
|
||||
if (clip) {
|
||||
using C = Layer;
|
||||
const struct { int k; int64_t n; rad_buf buf; } cl[C::C_N] = {
|
||||
{ C::C_QKV_IN, width, b_h }, { C::C_Q_OUT, width, b_qkv },
|
||||
{ C::C_KV_OUT, 2 * width, b_qkv }, { C::C_O_IN, width, b_att },
|
||||
{ C::C_O_OUT, width, b_o }, { C::C_GU_IN, width, b_h },
|
||||
{ C::C_GU_OUT, 2 * ff, b_gu }, { C::C_DN_IN, ff, b_ff },
|
||||
{ C::C_DN_OUT, width, b_o } };
|
||||
for (const auto& e : cl)
|
||||
l.op_c[e.k] = rw(b, clamp(e.n, l.lo[e.k], l.hi[e.k]), {e.buf}, {e.buf});
|
||||
}
|
||||
l.op_in = rw(b, rms(P, l.in_norm), {b_x}, {b_h});
|
||||
l.op_qkv = rw(b, gemm(P, 3 * width, width, l.qkv), {b_h}, {b_qkv});
|
||||
l.op_qk = rw(b, RAD_OP(b, "qk_norm_rope",
|
||||
@@ -272,10 +323,11 @@ struct Gemma4Vision {
|
||||
e.out = b_out;
|
||||
RAD_ARCH_TRY(rad_declare_encoder(b, &e));
|
||||
rad_note(b, "vision tower: %lld layers of %lld (%lld heads x %lld), ff %lld, patch %lld, "
|
||||
"pooled %lldx%lld%s; %lld patches a pass -> %lld rows of %lld",
|
||||
"pooled %lldx%lld%s%s; %lld patches a pass -> %lld rows of %lld",
|
||||
(long long)depth, (long long)width, (long long)heads, (long long)hd, (long long)ff,
|
||||
(long long)patch, (long long)pool, (long long)pool,
|
||||
standardize ? ", standardised" : "", (long long)P, (long long)R,
|
||||
standardize ? ", standardised" : "", clip ? ", clipped linears" : "",
|
||||
(long long)P, (long long)R,
|
||||
(long long)n_embd);
|
||||
on = true;
|
||||
return RAD_OK;
|
||||
@@ -299,20 +351,33 @@ struct Gemma4Vision {
|
||||
RAD_ISSUE_N(c, op_py, Pn, praw(crd, RAD_I32, Pn), RAD_W(w_py), brows(b_py, Pn));
|
||||
RAD_ISSUE_N(c, op_padd, Pn, brows(b_px, Pn), brows(b_py, Pn), brows(b_px, Pn));
|
||||
RAD_ISSUE_N(c, op_add, Pn, brows(b_x, Pn), brows(b_px, Pn), brows(b_x, Pn));
|
||||
/* a clamp of operand `x` in place, when the tower clips */
|
||||
auto cl = [&](const Layer& l, int k, RadOperand x) {
|
||||
if (clip) RAD_ISSUE_N(c, l.op_c[k], Pn, x, RAD_W(l.lo[k]), RAD_W(l.hi[k]), x);
|
||||
};
|
||||
for (const Layer& l : L) {
|
||||
RAD_ISSUE_N(c, l.op_in, Pn, brows(b_x, Pn), RAD_W(l.in_norm), brows(b_h, Pn));
|
||||
cl(l, Layer::C_QKV_IN, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.op_qkv, Pn, brows(b_h, Pn), RAD_W(l.qkv), brows(b_qkv, Pn));
|
||||
cl(l, Layer::C_Q_OUT, bcol(b_qkv, 0, width, Pn));
|
||||
cl(l, Layer::C_KV_OUT, bcol(b_qkv, width, 2 * width, Pn));
|
||||
RAD_ISSUE_N(c, l.op_qk, Pn, brows(b_qkv, Pn), rc, RAD_W(l.q_norm), RAD_W(l.k_norm));
|
||||
RAD_ISSUE_N(c, l.op_attn, Pn, bcol(b_qkv, 0, width, Pn), bcol(b_qkv, width, width, Pn),
|
||||
bcol(b_qkv, 2 * width, width, Pn), cu, brows(b_att, Pn));
|
||||
cl(l, Layer::C_O_IN, brows(b_att, Pn));
|
||||
RAD_ISSUE_N(c, l.op_o, Pn, brows(b_att, Pn), RAD_W(l.o), brows(b_o, Pn));
|
||||
cl(l, Layer::C_O_OUT, brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pa, Pn, brows(b_o, Pn), RAD_W(l.post_attn), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_add1, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pf, Pn, brows(b_x, Pn), RAD_W(l.pre_ff), brows(b_h, Pn));
|
||||
cl(l, Layer::C_GU_IN, brows(b_h, Pn));
|
||||
RAD_ISSUE_N(c, l.op_gu, Pn, brows(b_h, Pn), RAD_W(l.gate_up), brows(b_gu, Pn));
|
||||
cl(l, Layer::C_GU_OUT, brows(b_gu, Pn));
|
||||
RAD_ISSUE_N(c, l.op_act, Pn, bcol(b_gu, 0, ff, Pn), bcol(b_gu, ff, ff, Pn),
|
||||
brows(b_ff, Pn));
|
||||
cl(l, Layer::C_DN_IN, brows(b_ff, Pn));
|
||||
RAD_ISSUE_N(c, l.op_down, Pn, brows(b_ff, Pn), RAD_W(l.down), brows(b_o, Pn));
|
||||
cl(l, Layer::C_DN_OUT, brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_pff, Pn, brows(b_o, Pn), RAD_W(l.post_ff), brows(b_o, Pn));
|
||||
RAD_ISSUE_N(c, l.op_add2, Pn, brows(b_x, Pn), brows(b_o, Pn), brows(b_x, Pn));
|
||||
}
|
||||
|
||||
@@ -151,7 +151,8 @@ struct GlmKda {
|
||||
!w.input || !w.forget_low || !w.gate_low || !w.out || w.input == w.out ||
|
||||
w.forget_low == w.gate_low)
|
||||
return RAD_E_INVAL;
|
||||
// All seven projections are plain BF16 in the pinned checkpoint.
|
||||
// All seven projections are plain bf16 in the pinned checkpoint; under w_bf16,
|
||||
// LinearFP8::declare refuses a quantised one by name.
|
||||
Geom bg = g;
|
||||
bg.w_bf16 = true;
|
||||
const int64_t width = GlmTp::kda_width(g.world), heads = GlmTp::heads(g.world);
|
||||
@@ -193,9 +194,6 @@ struct GlmKda {
|
||||
RAD_ARCH_TRY(output.declare(b, nm, bg, nm.f("blk.%d.attn_output", layer), 4096, width,
|
||||
RAD_SHARD_COL, group, { nm.ckpt("%s.o_proj.weight", prefix) },
|
||||
act(w.core.out), w.out));
|
||||
if (!qkv.bf16 || !beta.bf16 || !forget_a.bf16 || !forget_b.bf16 || !gate_a.bf16 ||
|
||||
!gate_b.bf16 || !output.bf16)
|
||||
return RAD_E_UNSUPPORTED;
|
||||
if (reduce) op_ar = GlmTp::reduce(b, g, w.out);
|
||||
return reduce && g.world > 1 && !op_ar ? RAD_E_INVAL : RAD_OK;
|
||||
}
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/* rad_block_glm_vision.h -- GLM-5.3's vision tower (transformers' Glm5NextVisionModel), served by
|
||||
* glm5next.
|
||||
*
|
||||
* WHAT IT COMPUTES, per encoder pass (RadBatch::enc):
|
||||
* What it computes, per encoder pass (RadBatch::enc):
|
||||
*
|
||||
* x = patches @ Wp^T + bp the Conv3d patch embedding as a linear layer; a
|
||||
* patch row is (channel, frame, y, x), no position
|
||||
|
||||
+20
-27
@@ -365,36 +365,25 @@ inline void HyperConn::read(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) con
|
||||
c.rotate ? brow_slice(w.rs, r0, rows, fp8_blocks(g.n_embd)) : RAD_NONE);
|
||||
}
|
||||
|
||||
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
|
||||
* every block leaves its delta in the activation its norm produced, and the input is dead by
|
||||
* then. */
|
||||
/* ================================================================== the control-vector projection
|
||||
*
|
||||
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). Turned on
|
||||
* for a request, a steered layer's wide stream is projected off that layer's direction right after
|
||||
* the feed-forward's write:
|
||||
* A control vector is one unit direction per layer (a `controlvector` GGUF, core/cvec.h). For a
|
||||
* request that takes it, a steered layer's wide stream loses its component along that layer's
|
||||
* direction right after the feed-forward's write:
|
||||
*
|
||||
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
|
||||
* h[s] -= scale * (h[s] . v) * v for each of the hc streams s
|
||||
*
|
||||
* which is llama.cpp's `--cvec-mode project` and the operation the Qwen3.8-Flash-Next package
|
||||
* documents. The dot is per stream, not on the stream mean: the patch applies it to the
|
||||
* [n_embd, hc, tokens] view where `mul_mat(v, cur)` reduces over dim 0 alone.
|
||||
* This is llama.cpp's `--cvec-mode project`. The dot is per stream, not on the stream mean, as
|
||||
* llama.cpp's `mul_mat(v, cur)` over the [n_embd, hc, tokens] view reduces dim 0 alone.
|
||||
*
|
||||
* Two properties the architecture plugin does not have to think about, both here:
|
||||
* The switch is per request: `on` is a derived buffer of one int32 per row
|
||||
* (core/sched/derive.cpp, `projection_on_rows`), so a step that mixes a projected conversation
|
||||
* with a stock one projects only the rows that asked. The kernel neither reads nor writes a zero
|
||||
* row, and a pass with no row on issues nothing (RadBatch::control_vector). `scale` is the norm
|
||||
* the file stored for the layer times the package's own scale.
|
||||
*
|
||||
* - **the switch is per request.** `on` is a derived buffer of one int32 per token row
|
||||
* (core/sched/derive.cpp's `projection_on_rows`), so a step that mixes a projected
|
||||
* conversation with a stock one projects exactly the rows that asked for it. All zeros is the
|
||||
* stock model: the kernel skips a zero row without reading or writing it, so an unprojected
|
||||
* request's stream is the one the stock model computes. (The *deployment* is not bit-identical
|
||||
* to one with no vector: the direction table's VRAM can move an expert or a KV block, which is
|
||||
* the tie-level variance radiance documents elsewhere. Measured, docs/GUIDE.md 4.10.)
|
||||
* - **the parameters travel with the file.** `scale` is the norm the file stored for that layer
|
||||
* (times the package's own `scale`, read from its JSON), and the direction row is sliced from
|
||||
* the table at issue, so nothing is configured per deployment or scanned per layer.
|
||||
*
|
||||
* One instance per layer: `declare` emits an op only when the vector steers that layer, so a
|
||||
* deployment without a vector declares no op, no buffer and no branch in the step. */
|
||||
* One instance per layer; `declare` emits an op only where the vector steers, so a deployment
|
||||
* without a vector declares no op and no buffer. */
|
||||
struct HcProject {
|
||||
rad_op op = 0; /* 0: this layer is not steered (or there is no vector) */
|
||||
const float* dir = nullptr; /* this layer's row of the device direction table */
|
||||
@@ -456,9 +445,10 @@ struct HcProject {
|
||||
}
|
||||
|
||||
/* Rows [r0, r0 + rows) of the stream. The whole step is r0 = 0; the pipelined step issues one
|
||||
* call per piece, in the same place in the graph. */
|
||||
void step(RadCtx* c_, int64_t r0, int64_t rows) const {
|
||||
if (!op) return;
|
||||
* call per piece, in the same place in the graph. Nothing is issued on a pass where no row
|
||||
* takes the vector (RadBatch::control_vector): every row would be skipped. */
|
||||
void step(RadCtx* c_, const RadBatch* batch, int64_t r0, int64_t rows) const {
|
||||
if (!op || !batch || !batch->control_vector) return;
|
||||
RAD_ISSUE_N(c_, op, rows,
|
||||
brow_slice(h, r0, rows, hc * n),
|
||||
praw(dir, RAD_F32, n),
|
||||
@@ -466,6 +456,9 @@ struct HcProject {
|
||||
}
|
||||
};
|
||||
|
||||
/* The block's output `y` is read from `w.x.x`, the buffer the read wrote the block's input to:
|
||||
* every block leaves its delta in the activation its norm produced, and the input is dead by
|
||||
* then. */
|
||||
inline void HyperConn::write(RadCtx* c_, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (!op_write) return;
|
||||
if (takes_gather(T)) {
|
||||
|
||||
@@ -75,6 +75,20 @@ struct MlpFP8 {
|
||||
void step_rows(RadCtx* c, int64_t T) const { slice(c, T, 0, T); }
|
||||
/* One row slice of the whole block; `rows <= 0` means the rest of the step. */
|
||||
void slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
/* The slice in its parts, for a caller that runs the norm and the tail elsewhere (qwen35_fp8's
|
||||
* pipelined prefill puts both on the second lane): the projections from the normed input to
|
||||
* the delta in `w.h.x`, then the all-reduce and add this block issues itself. */
|
||||
void body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const;
|
||||
void tail(RadCtx* c, int64_t r0, int64_t rows) const;
|
||||
/* The block's all-reduce over rows [r0, r0 + rows) of the output, at `overlap` where declared
|
||||
* (a caller that runs it beside other work). */
|
||||
void issue_ar(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov ? op_ar_ov : op_ar, rows * g.n_embd,
|
||||
brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
}
|
||||
/* Set before declare: the `overlap` issue_ar's collective is declared at, 0 for none. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
};
|
||||
|
||||
inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire,
|
||||
@@ -129,6 +143,17 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
/* The same collective for a caller that runs it beside other work (issue_ar): at `overlap` 1
|
||||
* it gets the rows that hold fewer CUs while waiting on the link. */
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes),
|
||||
RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h.x}, {w.h.x});
|
||||
|
||||
/* Only when the next block's norm will not add (rad_fp8.h: NormQuantFP8). */
|
||||
if (add_out)
|
||||
@@ -149,6 +174,11 @@ inline int MlpFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, co
|
||||
inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
nq_h.step(c, T, r0, rows);
|
||||
body(c, T, r0, rows);
|
||||
tail(c, r0, rows);
|
||||
}
|
||||
|
||||
inline void MlpFP8::body(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (op_gated && rows <= gated_rows) {
|
||||
RAD_ISSUE_N(c, op_gated, rows, brow_slice(w.h.q, r0, rows, g.n_embd),
|
||||
brow_slice(w.h.s, r0, rows, g.n_embd / RAD_FP8_BLOCK), RAD_W(gate_up.w),
|
||||
@@ -160,6 +190,9 @@ inline void MlpFP8::slice(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const
|
||||
gq_ffn.step(c, w.gate_up, T, r0, rows);
|
||||
}
|
||||
down.step(c, w.ffn, w.h.x, T, r0, rows);
|
||||
}
|
||||
|
||||
inline void MlpFP8::tail(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
if (op_ar && !(ar_out && ar_fused_ok(g, rows)))
|
||||
RAD_ISSUE_N(c, op_ar, rows * g.n_embd, brow_slice(w.h.x, r0, rows, g.n_embd), RAD_NONE);
|
||||
if (op_add)
|
||||
|
||||
@@ -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));
|
||||
}
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+67
-16
@@ -296,6 +296,10 @@ struct ArPieces {
|
||||
* chunk a span of 1 makes, the state carried through the cache) and hand off the first
|
||||
* piece's reduction before the second piece's projection. Null for any other step. */
|
||||
const int32_t* cu = nullptr;
|
||||
/* The caller normed each piece's input itself (qwen35_fp8's pipelined prefill, on the second
|
||||
* lane behind the previous block's piece), so a block with its own norm takes the piece path
|
||||
* as one with an external input does and skips that norm. */
|
||||
bool in_ready = false;
|
||||
bool cuts(int64_t T) const { return done && rows > 0 && T > rows; }
|
||||
void hand(int64_t r0, int64_t n) { done(u, r0, n); ++handed; }
|
||||
};
|
||||
@@ -395,6 +399,9 @@ struct NormQuantFP8 {
|
||||
}
|
||||
/* Asked by the preceding block before issuing its own collective. */
|
||||
bool takes_ar(int64_t T) const { return pick(T) != op; }
|
||||
/* The plain op whatever the wire, for a caller that issued the preceding all-reduce itself
|
||||
* (qwen35_fp8's pipelined prefill, which runs it narrow beside compute). */
|
||||
void step_plain(RadCtx* c, int64_t T, int64_t r0 = 0, int64_t rows = 0) const;
|
||||
};
|
||||
|
||||
inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain, rad_buf x,
|
||||
@@ -472,6 +479,16 @@ inline int NormQuantFP8::declare(RadBuilder* b, const Geom& g, rad_weight gain,
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* step() below with the plain op, whatever the wire. */
|
||||
inline void NormQuantFP8::step_plain(RadCtx* c, int64_t T, int64_t r0, int64_t rows) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(src, r0, rows, n),
|
||||
res ? brow_slice(res, r0, rows, n) : RAD_NONE, RAD_W(w),
|
||||
brow_slice(a.q, r0, rows, n),
|
||||
brow_slice(a.s, r0, rows, n / RAD_FP8_BLOCK),
|
||||
brow_slice(a.x, r0, rows, n));
|
||||
}
|
||||
|
||||
/* `r0`/`rows` select a row slice, defaulting to the whole step (`brow_slice` at offset 0 equals
|
||||
* `brows`). Slicing lets a block run in passes (the routed feed-forward). Each slice must land in
|
||||
* the same bucket-table band as the whole (core/runtime/ctx.h), or a different kernel with a
|
||||
@@ -755,6 +772,10 @@ struct LinearFP8 {
|
||||
* this is set; otherwise the linear reads unwritten arena bytes. */
|
||||
bool reads_x = false;
|
||||
bool mapped = false; /* probe() made the name map; declare() does not make it again */
|
||||
/* The stored weight this linear's views take when it is not `<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(). */
|
||||
@@ -808,8 +829,10 @@ struct LinearFP8 {
|
||||
rad_weight decl_dense(RadBuilder* b, Names& nm, const char* base, const char* wn, const RadEncoding& enc,
|
||||
int64_t K,
|
||||
RadWeightGroup grp);
|
||||
/* Rows [r0, r0 + rows) of the input into the same rows of `y`, or from row `y0` of `y` when
|
||||
* that is set: a rank's run of a step's rows written to a buffer sized for the run. */
|
||||
void step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0 = 0,
|
||||
int64_t rows = 0) const;
|
||||
int64_t rows = 0, int64_t y0 = -1) const;
|
||||
/* A span per stacked row part (rad_weight_shard_span_parts), in weight rows; the scale plane
|
||||
* gets the same spans in its rows. Call after declare(). With a 1/128 plane every span and
|
||||
* total must be whole scale blocks. */
|
||||
@@ -1047,9 +1070,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
|
||||
/* Name map first: the weight's encoding, looked up through it, picks the branch below. */
|
||||
const char* wn = nm.f("%s.weight", base);
|
||||
if (!mapped) RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
if (!mapped && !stored) RAD_ARCH_TRY(map_linear(b, wn, src));
|
||||
const char* sw = stored ? stored : wn;
|
||||
RadEncoding enc{};
|
||||
const bool known = weight_enc(b, wn, &enc);
|
||||
const bool known = weight_enc(b, sw, &enc);
|
||||
const bool plain = known && rad_enc_is(&enc, "plain") && enc.n_planes == 1 &&
|
||||
enc.plane[0].dtype == RAD_BF16;
|
||||
|
||||
@@ -1059,11 +1083,17 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* constraints. */
|
||||
bf16 = g.w_bf16 || plain;
|
||||
if (bf16) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (known && !plain) {
|
||||
char en[256];
|
||||
rad_enc_format(&enc, en, sizeof en);
|
||||
fprintf(stderr, "radiance: '%s' is %s and this model's linears are plain bf16; a "
|
||||
"bf16 container is served bf16 throughout\n", wn, en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, but this linear runs as a plain bf16 GEMM "
|
||||
"(a bf16 model, or a block that keeps its linears bf16); the "
|
||||
"container must store it bf16\n", wn, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
/* A bf16 weight needs the input's bf16 plane, which a quantised model's producer may not
|
||||
@@ -1097,6 +1127,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
const bool rot8 = known && linear_is_w8h(enc);
|
||||
i8 = known && (linear_is_w8(enc) || rot8);
|
||||
if (i8) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Upstream's rot guard: fed codes must match the weight's rotation form. */
|
||||
if (a.q8_fed && rot8 != a.q8_rot) {
|
||||
fprintf(stderr, "radiance: '%s' is a%s int8 weight and its input is fed codes its "
|
||||
@@ -1161,6 +1196,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* codes, and (scale, zero) as `b_scale`. */
|
||||
paro5 = known && linear_is_paro_w5(enc);
|
||||
if (paro5) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int bits = enc.plane[0].dtype == RAD_U4 ? 4 : 5;
|
||||
if (!a.x) {
|
||||
fprintf(stderr, "radiance: '%s' is a rotated %d-bit weight, rotated from its input's "
|
||||
@@ -1227,6 +1267,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* whole 128s, the scale group. */
|
||||
w4 = known && linear_is_w4(enc);
|
||||
if (w4) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (!a.x) {
|
||||
fprintf(stderr, "radiance: '%s' is a 4-bit weight, read from its input's bf16 plane, "
|
||||
"and its input has none\n", wn);
|
||||
@@ -1297,6 +1342,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
paro = known && linear_is_paro_mxfp4(enc);
|
||||
mx = known && (linear_is_mxfp4(enc) || paro);
|
||||
if (mx) {
|
||||
if (stored) {
|
||||
fprintf(stderr, "radiance: '%s' views '%s', which only a block-fp8 linear "
|
||||
"may\n", wn, stored);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (paro) {
|
||||
/* The rotation is applied to the activation, so this linear needs the input's bf16
|
||||
* plane (probe() set reads_x) and quantises it itself. */
|
||||
@@ -1408,10 +1458,10 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
f32_scale = fp8_scale && fp8_scale->dtype == RAD_F32;
|
||||
/* One stored weight, two operands: the codes and scale plane of `<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. */
|
||||
@@ -1443,10 +1493,11 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
* asymmetric integer and mxfp4 grids) are passed as RAD_NONE when unused, since the runtime checks
|
||||
* the operand count against the schema (core/runtime/issue.cpp). */
|
||||
inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, int64_t r0,
|
||||
int64_t rows) const {
|
||||
int64_t rows, int64_t y0) const {
|
||||
if (rows <= 0) rows = T - r0;
|
||||
const int64_t yr = y0 < 0 ? r0 : y0;
|
||||
if (bf16) {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, r0, rows, N));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.x, r0, rows, K), RAD_W(w), brow_slice(y, yr, rows, N));
|
||||
return;
|
||||
}
|
||||
if (i8) {
|
||||
@@ -1455,7 +1506,7 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.q8, r0, rows, K),
|
||||
brow_slice(a.s8, r0, rows, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
/* The 4-bit weight's copies of the input start at their buffers' first row: they live only
|
||||
@@ -1465,13 +1516,13 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK));
|
||||
RAD_ISSUE_N(c, op2, rows, brow_slice(a8q, 0, rows, K),
|
||||
brow_slice(a8s, 0, rows, K / RAD_FP8_BLOCK), RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (w4) {
|
||||
RAD_ISSUE_N(c, op_a16, rows, brow_slice(a.x, r0, rows, K), brow_slice(a16, 0, rows, K));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a16, 0, rows, K), RAD_NONE, RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (paro5 && rot_split && rows > rot_split) {
|
||||
@@ -1480,14 +1531,14 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)));
|
||||
RAD_ISSUE_N(c, op2, rows, brow_slice(rot_q2, r0, rows, rot_parts * K),
|
||||
brow_slice(rot_s2, r0, rows, rot_parts * (K / RAD_FP8_BLOCK)),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (paro5) {
|
||||
RAD_ISSUE_N(c, op_rot, rows, brow_slice(a.x, r0, rows, K), RAD_W(rot_pairs),
|
||||
RAD_W(rot_angle), RAD_W(rot_scale), brow_slice(rot_q, r0, rows, rot_parts * K));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(rot_q, r0, rows, rot_parts * K), RAD_NONE,
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (mx) {
|
||||
@@ -1501,12 +1552,12 @@ inline void LinearFP8::step(RadCtx* c, const ActFP8& a, rad_buf y, int64_t T, in
|
||||
brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK));
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(aq, r0, rows, ak),
|
||||
brow_slice(as, r0, rows, ak / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_W(wref));
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_W(wref));
|
||||
return;
|
||||
}
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(a.q, r0, rows, K),
|
||||
brow_slice(a.s, r0, rows, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, rows, N), RAD_NONE, RAD_NONE);
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, yr, rows, N), RAD_NONE, RAD_NONE);
|
||||
}
|
||||
|
||||
/* ================================================== an fp8 weight with no op of its own
|
||||
|
||||
@@ -40,7 +40,8 @@
|
||||
* The sliding layers are causal and the full layer is not. The checkpoint's `layer_types` names
|
||||
* four sliding layers and one full one, and the PR's test pins `causal True` on the sliding
|
||||
* layers and `False` on the full one, so this block declares two attention ops and issues the one
|
||||
* each layer's type names.
|
||||
* each layer's type names. A config that states `dflash_config.causal` (NVIDIA's E4B drafter:
|
||||
* false, all five layers sliding) sets the sliding layers' causality.
|
||||
*
|
||||
* The logits are soft-capped, which is deliberately ignored: the draft is an argmax, and
|
||||
* cap * tanh(x / cap) is strictly increasing.
|
||||
@@ -115,18 +116,15 @@ inline double embed_scale(int64_t hidden) {
|
||||
/* prefetch where a library serves it: the 31B trunk reading the next GEMM's leading weight bytes
|
||||
* into the on-die cache beside the all-reduce in front of that GEMM, at decode heights (on lane 0
|
||||
* as a chained read, or on the second lane: rad_arch.h prefetch_lane0), and the DFlash2 drafter's
|
||||
* reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB. With
|
||||
* the reads on lane 0 (two rounds on 4x R9700): 20 MB 391 / 391 code tok/s, 289 / 288 prose;
|
||||
* 16 MB 386 / 384, 285 / 283; 24 MB 388 / 387; 12 MB 368 / 369. */
|
||||
* reads likewise. It writes nothing the model reads. Each read takes a weight's first 20 MB: on 4x
|
||||
* R9700 with the reads on lane 0, 16 and 24 MB decoded 1-2% slower and 12 MB about 6%. */
|
||||
constexpr int64_t kPrefetchBytes = (int64_t)20 << 20;
|
||||
|
||||
/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention. It
|
||||
* took the place of o_proj's read there: the 31B at tp 4 on 4x R9700, two rounds, every reply
|
||||
* identical, 380 / 281 / 203 tok/s against 367 / 271 / 196 with o_proj's 16 MB; 10, 11, 12, 14
|
||||
* and 20 MB of down_proj 379, 377, 373, 373 and 362; down_proj beside o_proj's read, or beside the
|
||||
* feed-forward reduction, slower than either alone. The reads beside a reduction are one queue,
|
||||
* and a longer one beside the attention pushes gate_up's read past the reduction it should hide
|
||||
* in. */
|
||||
/* down_proj's read, the trunk GEMM no other read covers: its first 9 MB, beside the attention, in
|
||||
* place of a read of o_proj there (about 3.5% faster on the 31B at tp 4 on 4x R9700; 10-20 MB of
|
||||
* down_proj were slower, as were two reads beside one reduction). The reads beside a reduction
|
||||
* are one queue, and a longer one beside the attention pushes gate_up's read past the reduction
|
||||
* it should hide in. */
|
||||
constexpr int64_t kPrefetchDownBytes = (int64_t)9 << 20;
|
||||
|
||||
/* Block fp8 as libr4d's fp8a8 GEMMs read it: fp8_e4m3 codes, a bf16 scale per 128x128 block, no
|
||||
@@ -166,8 +164,8 @@ inline long long dflash_block(const RadModelMeta* meta) {
|
||||
|
||||
/* DFlash proposes its whole block in one pass, so its depth is the block it was trained at less
|
||||
* the anchor, and nothing else: 15 for z-lab's Gemma 4 drafters (block_size 16). True when the
|
||||
* container carries one and `out` now names its depth. Chained launches measured a gain with it
|
||||
* (the 26B-A4B's speculative step, +1% on 4x R9700), so the probe asks for them
|
||||
* container carries one and `out` names its depth. Chained launches pay with it (the 26B-A4B's
|
||||
* speculative step is 1% faster on 4x R9700), so the probe asks for them
|
||||
* (RadArchProbe::chain_pays). */
|
||||
inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (dflash_kind(meta) != 1) return false;
|
||||
@@ -181,8 +179,8 @@ inline bool dflash_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
|
||||
/* The same for a DFlash2 drafter, for a plugin that serves rad_block_dflash2.h (the 31B's): its
|
||||
* anchor predicts nothing either, so the depth is the trained block less one, 7 for RedHatAI's
|
||||
* gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches measured a gain with it (the
|
||||
* 31B's speculative step, +13% on 4x R9700), so the probe asks for them. */
|
||||
* gemma-4-31B-it-speculator.dflash2 (block_size 8). Chained launches pay with it (the 31B's
|
||||
* speculative step is 13% faster on 4x R9700), so the probe asks for them. */
|
||||
inline bool dflash2_probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (dflash_kind(meta) != 2) return false;
|
||||
const long long bs = dflash_block(meta);
|
||||
@@ -238,6 +236,7 @@ struct Dflash1 {
|
||||
int64_t n_taps = 0; /* how many trunk layers `fc` concatenates */
|
||||
int64_t block = 0; /* query rows per sequence: the anchor plus block - 1 masks */
|
||||
int64_t window = 0; /* the sliding layers' window; 0 for none */
|
||||
int causal = 1; /* the sliding layers: causal (z-lab) or not (dflash_config.causal) */
|
||||
int full[MAX_LAYERS] = {}; /* 1: a full-attention (non-causal, unwindowed) layer */
|
||||
double escale = 1.0; /* the target's embedding scale, rounded as the target holds it */
|
||||
int64_t kv_rep = 1; /* how many times the cache holds each kv head (kv_rep_for) */
|
||||
@@ -519,7 +518,12 @@ inline int Dflash1::Lin::declare(RadBuilder* b, Names& nm, const char* base, int
|
||||
int64_t p[RAD_MAX_ROW_PARTS] = {0};
|
||||
int np = 0;
|
||||
for (int64_t q : row_parts) {
|
||||
if (np >= RAD_MAX_ROW_PARTS || q % 16) return RAD_E_INVAL;
|
||||
if (np >= RAD_MAX_ROW_PARTS || q % 16) {
|
||||
fprintf(stderr, "radiance: '%s' has a %lld-row part per rank; an int8 weight takes at "
|
||||
"most %d parts, each a multiple of 16 rows.\n", base, (long long)q,
|
||||
(int)RAD_MAX_ROW_PARTS);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
p[np++] = q;
|
||||
}
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, access, shard, grp, p, np);
|
||||
@@ -582,7 +586,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
dc.block = trained;
|
||||
if (dg.n_layer > MAX_LAYERS) return RAD_E_UNSUPPORTED;
|
||||
if (dg.n_layer > MAX_LAYERS) {
|
||||
fprintf(stderr, "radiance: gemma4: the DFlash drafter has %lld layers; this block carries "
|
||||
"at most %d\n", (long long)dg.n_layer, MAX_LAYERS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
{
|
||||
std::vector<int> full;
|
||||
const char* lt = rad_meta_gets(meta, "draft.layer_types", nullptr);
|
||||
@@ -610,6 +618,11 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
|
||||
"window\n");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* z-lab's configs state no causality and train the sliding layers causal; NVIDIA's
|
||||
* (Nemotron-3.5-Bolt-E4B's DFlash) states `dflash_config.causal: false`, every layer
|
||||
* sliding and non-causal over its window. */
|
||||
dc.causal = rad_meta_geti(meta, "draft.dflash_config.causal",
|
||||
rad_meta_geti(meta, "draft.is_causal", 1)) != 0 ? 1 : 0;
|
||||
}
|
||||
}
|
||||
if (!head_sharded(dg) && dg.world > 1) {
|
||||
@@ -664,11 +677,12 @@ inline int Dflash1::declare_drafter(RadBuilder* b, const RadModelMeta* meta,
|
||||
int nfull = 0;
|
||||
for (int64_t l = 0; l < dg.n_layer; ++l) nfull += dc.full[l];
|
||||
rad_note(b, "the DFlash drafter is declared: %lld layers at absolute %d..%d (%d full, %lld "
|
||||
"sliding over %lld causal), %lld heads / %lld kv x %lld, ffn %lld, reading the "
|
||||
"sliding over %lld, %s), %lld heads / %lld kv x %lld, ffn %lld, reading the "
|
||||
"trunk at %lld tap(s); linears %s. One forward over %lld rows proposes %lld "
|
||||
"tokens; the head is %s, argmax %s",
|
||||
(long long)dg.n_layer, t.base_layer, t.base_layer + (int)dg.n_layer - 1, nfull,
|
||||
(long long)(dg.n_layer - nfull), (long long)dc.window, (long long)dg.n_head,
|
||||
(long long)(dg.n_layer - nfull), (long long)dc.window,
|
||||
dc.causal ? "causal" : "non-causal", (long long)dg.n_head,
|
||||
(long long)dg.n_head_kv, (long long)dg.head_dim, (long long)dg.n_ff,
|
||||
(long long)t.n_taps,
|
||||
df->i8 ? "int8 (w8a8, an int8 activation per row)" : "on the E4M3 grid (fp8a8 / mxfp4a8)",
|
||||
@@ -849,7 +863,7 @@ inline int Dflash1::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
|
||||
};
|
||||
bool any_full = false, any_swa = false;
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) (cfg.full[l] ? any_full : any_swa) = true;
|
||||
if (any_swa) op_attn_swa = attn(1, cfg.window);
|
||||
if (any_swa) op_attn_swa = attn(cfg.causal, cfg.window);
|
||||
if (any_full) op_attn_full = attn(0, 0);
|
||||
|
||||
/* The copies into the cache's layout (rep_kv), a head-wide strided row copy each. Each pass's
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -0,0 +1,167 @@
|
||||
/* rad_resample.h -- fp32 bicubic resampling reproducing torch's
|
||||
* F.interpolate(x, size=(n, m), mode="bicubic", antialias=True) on the CPU float32 kernel,
|
||||
* operation for operation, for the Unlimited-OCR DeepEncoder's position tables.
|
||||
*
|
||||
* The reference resamples two fixed tables (deepencoder.py):
|
||||
* get_abs_pos_sam() permutes SAM's pos_embed [1,64,64,768] to (0,3,1,2), casts fp32 and
|
||||
* interpolates to 40x40; get_abs_pos() takes CLIP position_embedding rows 1: as a 16x16 grid,
|
||||
* interpolates to 10x10, and cats row 0 (cls) in front. Here the table is row-major [h, w, C]
|
||||
* with C innermost and each of the C channels is interpolated over the (h, w) grid
|
||||
* independently; the cls split/catenation is the caller's job.
|
||||
*
|
||||
* The float32 antialias path (upsample_bicubic2d_aa_kernel_impl ->
|
||||
* upsample_separable_Nd_kernel_impl -> _compute_index_ranges_weights with antialias=true,
|
||||
* aten/src/ATen/native/cpu/UpSampleKernel.cpp, torch v2.14.0) is mirrored operation for
|
||||
* operation, scalar_t = float:
|
||||
* per axis scale = (float)(in / out); support = scale >= 1 ? (interp_size/2) * scale =
|
||||
* 2 * scale : 2; invscale = scale >= 1 ? 1 / scale : 1;
|
||||
* the output-pixel centre center = scale * (i + 0.5f);
|
||||
* the taps run over xmin = max((int64)(center - support + 0.5), 0) ..
|
||||
* min((int64)(center + support + 0.5), in) - 1 -- truncating casts, so a negative
|
||||
* start truncates toward zero before the clamp to 0; border taps are simply absent,
|
||||
* the row normalization below absorbs the lost mass;
|
||||
* each tap weight is aa_filter((j + xmin - center + 0.5) * invscale), the Keys cubic
|
||||
* with a = -0.5 (torch's antialias filter is the Pillow-compatible -0.5 kernel; the
|
||||
* -0.75 OpenCV-compatible one belongs to the non-antialias path);
|
||||
* the axis weights are normalized by their float running sum total_w, exactly as
|
||||
* _compute_indices_min_size_weights_aa divides wt_ptr[j] /= total_w;
|
||||
* the resize is separable: the width pass over every input row first, then the height
|
||||
* pass (the order upsample_separable_Nd_kernel_impl walks the dims), each tap
|
||||
* accumulating acc = (float)(acc + w * v) in float.
|
||||
* Golden-checked by tests/resample_golden.py (geometries 64->40, 24->20, 8->5, 16->10,
|
||||
* 16x20->10x13, and both checkpoint tables).
|
||||
*/
|
||||
#pragma once
|
||||
#ifndef RAD_RESAMPLE_H
|
||||
#define RAD_RESAMPLE_H
|
||||
|
||||
#include <cmath>
|
||||
#include <cstdint>
|
||||
#include <cstring>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
namespace resample_detail {
|
||||
|
||||
/* aa_filter, the Keys cubic with a = -0.5 that torch's antialias path uses (the -0.75
|
||||
* OpenCV-compatible kernel belongs to the non-antialias path), in float. */
|
||||
inline float cubic_aa(float x) {
|
||||
const float ax = std::fabs(x);
|
||||
if (ax < 1.0f) return ((1.5f * ax - 2.5f) * ax) * ax + 1.0f;
|
||||
if (ax < 2.0f) return (((-0.5f * ax + 2.5f) * ax - 4.0f) * ax) + 2.0f;
|
||||
return 0.0f;
|
||||
}
|
||||
|
||||
struct Axis {
|
||||
int n = 0; /* tap slots per output pixel (max_interp_size) */
|
||||
std::vector<int32_t> size; /* [out] taps this output pixel reads */
|
||||
std::vector<int32_t> idx; /* [out*n] input index per tap (xmin + j) */
|
||||
std::vector<float> w; /* [out*n] weights, normalized by the tap sum */
|
||||
};
|
||||
|
||||
/* One axis of _compute_indices_min_size_weights_aa, float32 expression for expression. */
|
||||
inline Axis make_axis(int in, int out) {
|
||||
Axis a;
|
||||
const float scale = (float)((double)in / (double)out);
|
||||
const float support = scale >= 1.0f ? (float)(2.0 * (double)scale) : 2.0f;
|
||||
const float invscale = scale >= 1.0f ? (float)(1.0 / (double)scale) : 1.0f;
|
||||
a.n = (int)std::ceil((double)support) * 2 + 1; /* max_interp_size */
|
||||
a.size.resize((size_t)out, 0);
|
||||
a.idx.assign((size_t)out * (size_t)a.n, 0);
|
||||
a.w.assign((size_t)out * (size_t)a.n, 0.0f);
|
||||
for (int i = 0; i < out; ++i) {
|
||||
const float c = ((float)i + 0.5f) * scale;
|
||||
int xmin = (int)(c - support + 0.5f);
|
||||
if (xmin < 0) xmin = 0;
|
||||
int xsize = (int)(c + support + 0.5f);
|
||||
if (xsize > in) xsize = in;
|
||||
xsize -= xmin;
|
||||
if (xsize < 0) xsize = 0;
|
||||
/* ATen's own `xsize = min(xsize, n)`, kept for parity. It cannot bind here: with
|
||||
* xmin > 0 the window spans 2*support + 1 taps, at most a.n = 2*ceil(support) + 1
|
||||
* (the bound ATen sized the slots from), and with xmin == 0 it spans fewer. So the
|
||||
* clamp is a no-op safety net, never a silent tap truncation. */
|
||||
if (xsize > a.n) xsize = a.n;
|
||||
int* idx = &a.idx[(size_t)i * (size_t)a.n];
|
||||
float* w = &a.w[(size_t)i * (size_t)a.n];
|
||||
float total = 0.0f;
|
||||
for (int j = 0; j < xsize; ++j) {
|
||||
w[j] = cubic_aa(((float)(xmin + j) - c + 0.5f) * invscale);
|
||||
idx[j] = xmin + j;
|
||||
total = (float)(total + w[j]);
|
||||
}
|
||||
a.size[i] = xsize;
|
||||
if (total != 0.0f)
|
||||
for (int j = 0; j < xsize; ++j) w[j] = (float)(w[j] / total);
|
||||
}
|
||||
return a;
|
||||
}
|
||||
|
||||
/* One 1D resize pass. `rows` scans travel `src_row_stride` floats apart, taps step
|
||||
* `tap_stride` floats along the resized axis, and outputs land at
|
||||
* dst + r * dst_row_stride + i * out_stride + channel; tap order and float accumulation
|
||||
* follow ATen's separable 1D resize. */
|
||||
inline void resize_axis(const float* src, int64_t src_row_stride, int64_t tap_stride,
|
||||
float* dst, int64_t dst_row_stride, int64_t out_stride, int rows,
|
||||
const Axis& ax, int out_n, int channels) {
|
||||
for (int r = 0; r < rows; ++r) {
|
||||
const float* srow = src + (size_t)r * (size_t)src_row_stride;
|
||||
float* drow = dst + (size_t)r * (size_t)dst_row_stride;
|
||||
for (int i = 0; i < out_n; ++i) {
|
||||
const int n = ax.size[i];
|
||||
const int32_t* idx = &ax.idx[(size_t)i * (size_t)ax.n];
|
||||
const float* w = &ax.w[(size_t)i * (size_t)ax.n];
|
||||
for (int c = 0; c < channels; ++c) {
|
||||
if (n == 0) { drow[(size_t)i * (size_t)out_stride + (size_t)c] = 0.0f; continue; }
|
||||
float acc = (float)(srow[(size_t)idx[0] * (size_t)tap_stride + (size_t)c] * w[0]);
|
||||
for (int j = 1; j < n; ++j)
|
||||
acc = (float)(acc +
|
||||
srow[(size_t)idx[j] * (size_t)tap_stride + (size_t)c] * w[j]);
|
||||
drow[(size_t)i * (size_t)out_stride + (size_t)c] = acc;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace resample_detail
|
||||
|
||||
/* Resample an [in_h, in_w, channels] fp32 table (channels innermost) to
|
||||
* [out_h, out_w, channels] with torch's bicubic + antialias interpolation: the width pass
|
||||
* over every input row, then the height pass. Runs once at load. */
|
||||
inline void resample_bicubic_aa(const float* src, int in_h, int in_w, int out_h, int out_w,
|
||||
int channels, float* dst) {
|
||||
if (!src || !dst || in_h <= 0 || in_w <= 0 || out_h <= 0 || out_w <= 0 || channels <= 0)
|
||||
return;
|
||||
if (in_h == out_h && in_w == out_w) {
|
||||
std::memcpy(dst, src, (size_t)in_h * (size_t)in_w * (size_t)channels * sizeof(float));
|
||||
return;
|
||||
}
|
||||
const resample_detail::Axis ay = resample_detail::make_axis(in_h, out_h);
|
||||
const resample_detail::Axis ax = resample_detail::make_axis(in_w, out_w);
|
||||
const float* work = src;
|
||||
int work_w = in_w;
|
||||
std::vector<float> wide;
|
||||
if (in_w != out_w) { /* width pass first, the order upsample_separable_Nd walks the dims */
|
||||
wide.assign((size_t)in_h * (size_t)out_w * (size_t)channels, 0.0f);
|
||||
resample_detail::resize_axis(src, (int64_t)in_w * channels, channels, wide.data(),
|
||||
(int64_t)out_w * channels, channels, in_h, ax, out_w,
|
||||
channels);
|
||||
work = wide.data();
|
||||
work_w = out_w;
|
||||
}
|
||||
if (in_h == out_h) {
|
||||
if (work != dst)
|
||||
std::memcpy(dst, work, (size_t)out_h * (size_t)out_w * (size_t)channels * sizeof(float));
|
||||
return;
|
||||
}
|
||||
/* height pass over the widened rows: one scan per output-width column */
|
||||
resample_detail::resize_axis(work, channels, (int64_t)work_w * channels, dst, channels,
|
||||
(int64_t)out_w * channels, work_w, ay, out_h, channels);
|
||||
}
|
||||
|
||||
} // namespace arch
|
||||
} // namespace rad
|
||||
|
||||
#endif // RAD_RESAMPLE_H
|
||||
@@ -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
+448
-14
@@ -22,6 +22,7 @@
|
||||
#include <arch/rad_fp8.h>
|
||||
#include <arch/rad_block_dflash2.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cmath>
|
||||
@@ -94,7 +95,18 @@ struct G3Linear {
|
||||
bool i8g = false;
|
||||
bool mx = false;
|
||||
bool a4 = false; /* asymmetric int4 over the per-(row, 128) int8 activation */
|
||||
/* a4 at decode heights, as LinearFP8's w4 (rad_fp8.h): up to kA4Split rows the bf16 input is
|
||||
* cast to f16 (`a16`) for w4a16_asym's skinny kernel; w4a8i8_asym has only a prefill kernel,
|
||||
* which at one row does 16 times the matrix work. */
|
||||
static constexpr int64_t kA4Split = 64;
|
||||
int64_t a4_split = 0;
|
||||
rad_buf a16 = 0;
|
||||
rad_op op_a16 = 0, op_dec = 0;
|
||||
bool shared_in = false;
|
||||
/* Set before declare: an E4M3 (MXFP4) linear's input pair given by the caller (the pipelined
|
||||
* prefill's one pair for every block) instead of one of its own. It keeps its own quantiser
|
||||
* into it, so a step that does not write the pair by a fused junction still fills it. */
|
||||
rad_buf q8_into = 0, s8_into = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
|
||||
std::initializer_list<const char*> src,
|
||||
@@ -104,6 +116,9 @@ struct G3Linear {
|
||||
const G3Linear* in_from = nullptr);
|
||||
void step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const;
|
||||
void gemm(RadCtx* c, rad_buf y, int64_t T) const;
|
||||
/* The same over rows [r0, r0 + n) of an E4M3 (MXFP4) linear, for the pipelined prefill. */
|
||||
void step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const;
|
||||
void gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const;
|
||||
};
|
||||
|
||||
inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char* base,
|
||||
@@ -198,7 +213,8 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
if (in_from && (in_from->i8g || in_from->a4) && in_from->q8 && in_from->K == K) {
|
||||
/* not an a4 linear's pair: below its decode band it writes none */
|
||||
if (in_from && in_from->i8g && in_from->q8 && in_from->K == K) {
|
||||
q8 = in_from->q8;
|
||||
s8 = in_from->s8;
|
||||
shared_in = true;
|
||||
@@ -218,7 +234,21 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a8i8_asym")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ q8, s8 }, { y });
|
||||
return op ? RAD_OK : RAD_E_INVAL;
|
||||
if (!op) return RAD_E_INVAL;
|
||||
a4_split = std::min<int64_t>(kA4Split, g.max_tok);
|
||||
a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { a4_split, K });
|
||||
if (!a16) return RAD_E_INVAL;
|
||||
op_a16 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("n", K),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", "f16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { a16 });
|
||||
op_dec = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a16_asym")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ a16 }, { y });
|
||||
return (op_a16 && op_dec) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
if (i8g || mx) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
@@ -239,13 +269,13 @@ inline int G3Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
ws = decl_view(b, sn, wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
}
|
||||
if (in_from && in_from->mx == mx && (in_from->i8g || in_from->a4) == i8g && in_from->q8 && in_from->K == K) {
|
||||
if (in_from && in_from->mx == mx && in_from->i8g == i8g && !in_from->a4 && in_from->q8 && in_from->K == K) {
|
||||
q8 = in_from->q8;
|
||||
s8 = in_from->s8;
|
||||
shared_in = true;
|
||||
} else {
|
||||
q8 = decl_b(b, nm.f("%s.q8", base), mx ? RAD_F8E4M3 : RAD_I8, { g.max_tok, K });
|
||||
s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK });
|
||||
q8 = mx && q8_into ? q8_into : decl_b(b, nm.f("%s.q8", base), mx ? RAD_F8E4M3 : RAD_I8, { g.max_tok, K });
|
||||
s8 = mx && s8_into ? s8_into : decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK });
|
||||
if (!q8 || !s8) return RAD_E_INVAL;
|
||||
op_q = rw(b, RAD_OP(b, mx ? "quant_act_fp8" : "quant_act_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
@@ -281,6 +311,10 @@ inline void G3Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const {
|
||||
if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE);
|
||||
gemm(c, y, T);
|
||||
} else if (a4 && T <= a4_split) {
|
||||
RAD_ISSUE_N(c, op_a16, T, brows(a, T), brows(a16, T));
|
||||
RAD_ISSUE_N(c, op_dec, T, brows(a16, T), RAD_NONE, RAD_W(w), RAD_W(ws), brows(y, T),
|
||||
RAD_NONE, RAD_NONE);
|
||||
} else if (i8g || mx || a4) {
|
||||
/* quant_act_i8g / quant_act_fp8 take x, q, scale: no optional `asum`. */
|
||||
if (!shared_in)
|
||||
@@ -295,6 +329,24 @@ inline void G3Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const {
|
||||
brows(y, T), RAD_NONE, mx ? RAD_W(wref) : RAD_NONE);
|
||||
}
|
||||
|
||||
inline void G3Linear::gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op, n, brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, K / RAD_FP8_BLOCK),
|
||||
RAD_W(w), RAD_W(ws), brow_slice(y, r0, n, N), RAD_NONE, RAD_W(wref));
|
||||
}
|
||||
|
||||
inline void G3Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const {
|
||||
if (a4 && n <= a4_split) {
|
||||
RAD_ISSUE_N(c, op_a16, n, brow_slice(a, r0, n, K), brows(a16, n));
|
||||
RAD_ISSUE_N(c, op_dec, n, brows(a16, n), RAD_NONE, RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, n, brow_slice(a, r0, n, K), brow_slice(q8, r0, n, K),
|
||||
brow_slice(s8, r0, n, K / RAD_FP8_BLOCK));
|
||||
gemm_rows(c, y, r0, n);
|
||||
}
|
||||
|
||||
/* ---- the GPTQ calibration tap (rad_arch.h's calib_*): the Gram of one linear's bf16 input,
|
||||
* summed over the corpus in a PERSIST [K, K] f32 buffer. Declared only with RADIANCE_CALIB_DIR set,
|
||||
* for the layers RADIANCE_G3_CALIB_LAYERS names ("lo:hi", default every layer): a down projection's
|
||||
@@ -343,6 +395,12 @@ struct Gemma3Attn {
|
||||
/* Calibration: q|k|v's shared input and o_proj's (this rank's columns). */
|
||||
G3Tap tap_in{}, tap_o{};
|
||||
const bool* tap_live = nullptr;
|
||||
/* Set before declare by a pipelined deployment: the all-reduce a second time at `overlap` 1 (a
|
||||
* launch that leaves the CUs to the compute beside it), and q|k|v's input pair shared by every
|
||||
* block (the junctions write it a piece at a time on the second lane). */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
const G3Linear* pipe_in = nullptr;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
rad_kvgroup group, const Wire& wire, double scale);
|
||||
@@ -352,6 +410,17 @@ struct Gemma3Attn {
|
||||
void post(RadCtx* c, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
|
||||
}
|
||||
/* The pipelined prefill (step_pipelined): the block over one prefill sequence in two pieces,
|
||||
* its input pair already written; hands the first piece behind its out projection. */
|
||||
void step_pieces(RadCtx* c, const RadBatch* batch, ArPieces* pc, const int32_t* used0) const;
|
||||
/* The tail a piece at a time on the second lane: the overlap all-reduce and the post-norm. */
|
||||
void ar_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov, n * g.n_embd, brow_slice(w.h, r0, n, g.n_embd), RAD_NONE);
|
||||
}
|
||||
void post_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_post, n, brow_slice(w.h, r0, n, g.n_embd), RAD_W(w_post),
|
||||
brow_slice(w.h, r0, n, g.n_embd));
|
||||
}
|
||||
};
|
||||
|
||||
int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
@@ -359,6 +428,7 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
g = geom; cls = cgeo; layer = l; kv = group; w = wire; attn_scale = scale;
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const char* pre = kLayers;
|
||||
if (pipe_in) { ln_q.q8_into = pipe_in->q8; ln_q.s8_into = pipe_in->s8; }
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l)));
|
||||
@@ -460,6 +530,13 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes), RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
|
||||
op_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
@@ -474,6 +551,49 @@ int Gemma3Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Each piece is the chunk a span of 1 makes: its rows, positions and slots, and an attention over
|
||||
* its own query bounds (ArPieces::cu) seeing the cache up to its own end -- `used0`, the group's
|
||||
* seqused less the second piece's rows, for the first; the step's seqused for the second, which
|
||||
* reads the first piece's keys from the cache as a later chunk would (the sliding window included:
|
||||
* a window group's seqused counts from its rebased first block). */
|
||||
void Gemma3Attn::step_pieces(RadCtx* c, const RadBatch* batch, ArPieces* pc,
|
||||
const int32_t* used0) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
const int64_t T = batch->n_tok, R = pc->rows;
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const int64_t tpitch = kvb ? kvb->block_table_pitch : 0;
|
||||
for (int64_t p = 0; p < 2; ++p) {
|
||||
const int64_t r0 = p == 0 ? 0 : R;
|
||||
const int64_t n = p == 0 ? R : T - R;
|
||||
const int32_t* pos = batch->positions + r0;
|
||||
ln_q.gemm_rows(c, w.q, r0, n);
|
||||
ln_k.gemm_rows(c, w.k, r0, n);
|
||||
ln_v.gemm_rows(c, w.v, r0, n);
|
||||
if (op_qnr) {
|
||||
RAD_ISSUE_N(c, op_qnr, n, brow_slice(w.q, r0, n, qd), brow_slice(w.k, r0, n, kvd),
|
||||
brow_slice(w.v, r0, n, kvd), praw(pos, RAD_I32, n), RAD_W(w_qn), RAD_W(w_kn));
|
||||
} else {
|
||||
RAD_ISSUE_N(c, op_qn, n * cls.n_head, brow_slice(w.q, r0, n, qd), RAD_W(w_qn),
|
||||
brow_slice(w.q, r0, n, qd));
|
||||
RAD_ISSUE_N(c, op_kn, n * cls.n_head_kv, brow_slice(w.k, r0, n, kvd), RAD_W(w_kn),
|
||||
brow_slice(w.k, r0, n, kvd));
|
||||
RAD_ISSUE_N(c, op_rq, n, brow_slice(w.q, r0, n, qd), praw(pos, RAD_I32, n));
|
||||
RAD_ISSUE_N(c, op_rk, n, brow_slice(w.k, r0, n, kvd), praw(pos, RAD_I32, n));
|
||||
}
|
||||
RAD_ISSUE_N(c, op_kv, n, brow_slice(w.k, r0, n, kvd), brow_slice(w.v, r0, n, kvd),
|
||||
praw(slot + r0, RAD_I32, n), kv_cache(kv, layer));
|
||||
RAD_ISSUE_N(c, op_attn, n, brows(w.q, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, 1, tpitch),
|
||||
praw(p == 0 ? used0 : used, RAD_I32, 1),
|
||||
RAD_NONE, RAD_NONE, praw(pc->cu + p, RAD_I32, 2), brows(w.attn, T));
|
||||
ln_o.step_rows(c, w.attn, w.h, r0, n);
|
||||
if (p == 0) pc->hand(r0, n);
|
||||
}
|
||||
}
|
||||
|
||||
void Gemma3Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tail_fused,
|
||||
bool ar_fused) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
@@ -538,6 +658,10 @@ struct Gemma3Mlp {
|
||||
/* Calibration: gate|up's input and down's (this rank's columns). */
|
||||
G3Tap tap_gu{}, tap_dn{};
|
||||
const bool* tap_live = nullptr;
|
||||
/* Set before declare by a pipelined deployment, as Gemma3Attn's. */
|
||||
int ar_overlap = 0;
|
||||
rad_op op_ar_ov = 0;
|
||||
const G3Linear* pipe_in = nullptr;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire);
|
||||
void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false,
|
||||
@@ -545,11 +669,30 @@ struct Gemma3Mlp {
|
||||
void post(RadCtx* c, int64_t T) const {
|
||||
RAD_ISSUE_N(c, op_post, T, brows(w.h, T), RAD_W(w_post), brows(w.h, T));
|
||||
}
|
||||
/* The pipelined prefill: the block over rows [r0, r0 + n), its input pair already written, up
|
||||
* to the down projection; then the tail a piece at a time on the second lane. */
|
||||
void body_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
ln_gu.gemm_rows(c, w.gu, r0, n);
|
||||
RAD_ISSUE_N(c, op_act, n, brow_slice(w.gu, r0, n, 2 * g.n_ff), brow_slice(w.ffn, r0, n, g.n_ff));
|
||||
ln_down.step_rows(c, w.ffn, w.h, r0, n);
|
||||
}
|
||||
void ar_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_ar_ov, n * g.n_embd, brow_slice(w.h, r0, n, g.n_embd), RAD_NONE);
|
||||
}
|
||||
void post_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_post, n, brow_slice(w.h, r0, n, g.n_embd), RAD_W(w_post),
|
||||
brow_slice(w.h, r0, n, g.n_embd));
|
||||
}
|
||||
void add_rows(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op_add, n, brow_slice(w.x, r0, n, g.n_embd), brow_slice(w.h, r0, n, g.n_embd),
|
||||
brow_slice(w.x, r0, n, g.n_embd));
|
||||
}
|
||||
};
|
||||
|
||||
int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const Wire& wire) {
|
||||
g = geom; layer = l; w = wire;
|
||||
const char* pre = kLayers;
|
||||
if (pipe_in) { ln_gu.q8_into = pipe_in->q8; ln_gu.s8_into = pipe_in->s8; }
|
||||
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_norm.weight", l), nm.ckpt("%s.%lld.pre_feedforward_layernorm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy (b, nm.f("blk.%d.ffn_post_norm.weight", l), nm.ckpt("%s.%lld.post_feedforward_layernorm.weight", pre, (long long)l)));
|
||||
@@ -589,6 +732,13 @@ int Gemma3Mlp::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
if (g.world > 1 && ar_overlap > 0)
|
||||
op_ar_ov = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes), RAD_INT("overlap", ar_overlap)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
op_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
@@ -651,7 +801,7 @@ struct G3Junction {
|
||||
const rad_buf wr[3] = { q8, s8, res };
|
||||
rad_op_reads (b, op, rd, res ? 2 : 1);
|
||||
rad_op_writes(b, op, wr, res ? 3 : 2);
|
||||
if (res && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
|
||||
if (res && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
|
||||
const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("world_size", g.world),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("wadd", g.wadd) };
|
||||
@@ -678,8 +828,11 @@ struct G3Junction {
|
||||
* embedding stream. */
|
||||
struct G3JunctionFP8 {
|
||||
rad_op op = 0;
|
||||
/* At two ranks on the exact wire: the branch's all-reduce and post-norm folded in front
|
||||
* (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. */
|
||||
/* At two ranks: the branch's all-reduce and post-norm folded in front
|
||||
* (ar_rmsnorm_post_quant_fp8), `x` then being this rank's partial sum. One launch. The kernel
|
||||
* sends the exact wire only, so under --tp-wire it is declared all the same and taken by the
|
||||
* steps whose message goes out exact anyway (ar_wire_is_exact: a decode step of a few rows,
|
||||
* under --tp-wire-min-kb); a wider step keeps the lossy all-reduce, unfused. */
|
||||
rad_op op_ar = 0;
|
||||
rad_buf x = 0, res = 0, q = 0, s = 0;
|
||||
rad_weight w = 0, wp = 0;
|
||||
@@ -700,7 +853,7 @@ struct G3JunctionFP8 {
|
||||
const rad_buf wr[3] = { q, s, res };
|
||||
rad_op_reads (b, op, rd, res ? 2 : 1);
|
||||
rad_op_writes(b, op, wr, res ? 3 : 2);
|
||||
if (res && wp && g.world == 2 && g.wire_exact && rad_op_declared(b, "ar_rmsnorm_post_quant_fp8")) {
|
||||
if (res && wp && g.world == 2 && rad_op_declared(b, "ar_rmsnorm_post_quant_fp8")) {
|
||||
const rad_weight ws[2] = { w, wp };
|
||||
const RadParam pa[] = { RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n), RAD_F64("eps", g.eps),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_INT("world_size", g.world),
|
||||
@@ -723,6 +876,12 @@ struct G3JunctionFP8 {
|
||||
RAD_ISSUE_N(c, op, T, brows(x, T), res ? brows(res, T) : RAD_NONE, RAD_W(w),
|
||||
brows(q, T), brows(s, T), RAD_NONE);
|
||||
}
|
||||
/* Rows [r0, r0 + n), without the all-reduce: the pipelined prefill's second lane. */
|
||||
void step_rows(RadCtx* c, int64_t r0, int64_t rows) const {
|
||||
RAD_ISSUE_N(c, op, rows, brow_slice(x, r0, rows, n), res ? brow_slice(res, r0, rows, n) : RAD_NONE,
|
||||
RAD_W(w), brow_slice(q, r0, rows, n), brow_slice(s, r0, rows, n / RAD_FP8_BLOCK),
|
||||
RAD_NONE);
|
||||
}
|
||||
};
|
||||
|
||||
struct Layer {
|
||||
@@ -773,10 +932,31 @@ struct Model {
|
||||
bool calib = false, tap_live = false;
|
||||
int64_t calib_lo = 0, calib_hi = 0;
|
||||
long long calib_rows = 0;
|
||||
|
||||
/* The pipelined prefill (step_pipelined): on where declare allowed it; the input pair every
|
||||
* block's q|k|v and gate|up read (the junctions write it); the bounds buffer and its pinned
|
||||
* table of {0, pipe_rows(T), T}; whether rank 0 has said it pipelines, or why not. */
|
||||
bool pipe_on = false;
|
||||
G3Linear pipe_in{};
|
||||
rad_buf b_pipe_cu = 0;
|
||||
/* Each KV group's seqused for the first piece, [2] (sliding, global): the step's less the
|
||||
* second piece's rows (sub_i32 from b_pipe_cu[3] = T - R). A window group's seqused counts from
|
||||
* its rebased first block, not from position 0, so the first piece's position cannot stand in. */
|
||||
rad_buf b_pipe_used = 0;
|
||||
rad_op op_pipe_used = 0;
|
||||
int32_t* pipe_tbl = nullptr;
|
||||
bool pipe_tbl_tried = false;
|
||||
bool pipe_noted = false;
|
||||
bool pipe_serial_noted = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
|
||||
* to 64 rows (qwen35_fp8 says why). */
|
||||
static const int64_t kPipeMinRows = 1024;
|
||||
static int64_t pipe_rows(int64_t T) { return ((T + 1) / 2 + 63) / 64 * 64; }
|
||||
|
||||
/* ================================================================== the DFlash2 drafter
|
||||
*
|
||||
* A second model at absolute layers n_layer.. with its own KV group (rad_block_dflash2.h), as
|
||||
@@ -793,6 +973,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "gemma3 DFlash2"));
|
||||
|
||||
Dflash2::Config dc{};
|
||||
dc.short_block = 1; /* rad_drafter_short_block below */
|
||||
dc.n_taps = m.n_taps;
|
||||
dc.block = ctx->max_spec + 1;
|
||||
dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2);
|
||||
@@ -904,6 +1085,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
if (m.df.block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, m.df.block_lo));
|
||||
rad_note(b, "DFlash2 drafter: %lld layers at absolute %d.., %lld heads / %lld kv x %lld, ffn %lld, "
|
||||
"%s attention with a %lld-token window, %d trunk taps, embedding x %g, %s head",
|
||||
(long long)dg.n_layer, base_layer, (long long)dg.n_head, (long long)dg.n_head_kv,
|
||||
@@ -917,6 +1099,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
@@ -1034,6 +1217,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("mult", emult)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
/* The second lane's window (rad_lane1_window_begin): from the embedding's reduction to the final
|
||||
* norm, where the pipelined prefill runs its boundaries; the drafter and the heads lie outside it
|
||||
* and can share the concurrent buffers' bytes. */
|
||||
RAD_ARCH_TRY(rad_lane1_window_begin(b));
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
@@ -1042,6 +1229,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
/* The pipelined prefill (step_pipelined), at two ranks wherever a step can be wide enough, on
|
||||
* an MXFP4 trunk with fused junctions (decided below); two ranks only, as in qwen35_fp8. Its
|
||||
* second lane touches the stream, the branch output, the shared input pair and the bounds, so
|
||||
* those leave the sharing pool (Ctx::lane1_; the drafter taps are copied on the first lane,
|
||||
* pipe_taps). The pair is one for every block so that this costs one pair, not one a
|
||||
* linear. */
|
||||
m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows && !calib_dir();
|
||||
if (m.pipe_on) {
|
||||
m.pipe_in.mx = true;
|
||||
m.pipe_in.K = g.n_embd;
|
||||
m.pipe_in.q8 = decl_b(b, nm.f("pipe_in.q8"), RAD_F8E4M3, {g.max_tok, g.n_embd});
|
||||
m.pipe_in.s8 = decl_b(b, nm.f("pipe_in.s8"), RAD_F32, {g.max_tok, g.n_embd / RAD_FP8_BLOCK});
|
||||
if (!m.pipe_in.q8 || !m.pipe_in.s8) return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
Gemma3Attn::Wire aw{}; aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_q; aw.k = m.b_k; aw.v = m.b_v; aw.attn = m.b_attn;
|
||||
Gemma3Mlp::Wire mw{}; mw.x = m.b_x; mw.h = m.b_h; mw.gu = m.b_gu; mw.ffn = m.b_ffn;
|
||||
|
||||
@@ -1052,6 +1254,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
const ClassGeom& cgeo = lay.global ? m.cg : m.cs;
|
||||
const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
|
||||
if (m.pipe_on) {
|
||||
lay.attn.ar_overlap = lay.mlp.ar_overlap = 1;
|
||||
lay.attn.pipe_in = lay.mlp.pipe_in = &m.pipe_in;
|
||||
}
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, attn_scale));
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw));
|
||||
}
|
||||
@@ -1119,6 +1325,38 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
m.fuse_mx_ar = ar;
|
||||
}
|
||||
/* The pipeline needs the fused fp8 junctions and every block's overlap all-reduce. */
|
||||
if (m.pipe_on) {
|
||||
bool ok = m.fuse_mx;
|
||||
/* ... and the pieces' row-sliced linears are the E4M3 (MXFP4) path throughout. */
|
||||
for (const Layer& lay : m.layers)
|
||||
ok = ok && lay.attn.op_ar_ov && lay.mlp.op_ar_ov && lay.attn.ln_o.mx && lay.mlp.ln_down.mx;
|
||||
if (!ok)
|
||||
rad_note(b, "the pipelined prefill is off: it needs an MXFP4 trunk with the fused fp8 "
|
||||
"junctions and an overlap all-reduce for every block");
|
||||
m.pipe_on = ok;
|
||||
}
|
||||
if (m.pipe_on) {
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.pipe_in.q8));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.pipe_in.s8));
|
||||
m.b_pipe_cu = decl_b(b, nm.f("pipe_cu"), RAD_I32, {4});
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_cu));
|
||||
m.b_pipe_used = decl_b(b, nm.f("pipe_used"), RAD_I32, {2});
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_used));
|
||||
m.op_pipe_used = rad_op_declared(b, "sub_i32")
|
||||
? RAD_OP(b, "sub_i32", RAD_PARAMS(RAD_RANGE("M", 1, 1)), RAD_NOWEIGHTS) : 0;
|
||||
if (m.op_pipe_used) {
|
||||
const rad_buf rd[1] = { m.b_pipe_cu };
|
||||
const rad_buf wr[1] = { m.b_pipe_used };
|
||||
rad_op_reads (b, m.op_pipe_used, rd, 1);
|
||||
rad_op_writes(b, m.op_pipe_used, wr, 1);
|
||||
} else {
|
||||
m.pipe_on = false; /* no way to put the first piece's seqused on the card */
|
||||
rad_note(b, "the pipelined prefill is off: no plugin serves sub_i32");
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the calibration tap. It reads the bf16 input of every linear, which the fused junctions
|
||||
* never write, so under it none is declared (above): any container calibrates, unfused. */
|
||||
@@ -1154,6 +1392,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out)),
|
||||
{m.b_x}, {m.b_h});
|
||||
RAD_ARCH_TRY(rad_lane1_window_end(b));
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
@@ -1180,6 +1419,191 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* ============================== A prefill step in two pieces ==============================
|
||||
*
|
||||
* qwen35_fp8's step_pipelined on Gemma 3's trunk: at two ranks every layer of a prefill chunk makes
|
||||
* two all-reduces, each in a hard chain behind its block (all-reduce, post-norm, the junction's add
|
||||
* and next norm, then the next block). A step of one prefill sequence of at least kPipeMinRows tokens
|
||||
* is cut into two pieces of about half; every block runs a piece at a time on the first lane, and
|
||||
* the work between two blocks -- the block's all-reduce at `overlap` 1, its post-norm and the fp8
|
||||
* junction, and after the last block its add and the final norm -- runs a
|
||||
* piece at a time on the second; the drafter taps run on the first (pipe_taps). The ops are the serial step's at a narrower width, so a pipelined
|
||||
* step is bit for bit the serial one where a chunk's rows do not depend on its width.
|
||||
*
|
||||
* The second lane's requirements (Ctx::lane1_) hold as in qwen35_fp8: every collective of the step
|
||||
* is on it, the embedding's included; none carries a device-wide arrival counter; the buffers it
|
||||
* touches left the sharing pool at declare, the per-linear input pairs replaced by one shared pair. */
|
||||
|
||||
template <class F>
|
||||
static void pipe_on1(RadCtx* c, const F& issue) {
|
||||
rad_lane(c, 1);
|
||||
rad_lane_join(c, 0, 1);
|
||||
issue();
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
static void pipe_wait1(RadCtx* c) { rad_lane_join(c, 1, 0); }
|
||||
|
||||
/* The work after block `s` (2l the attention of layer l, 2l + 1 its feed-forward), rows
|
||||
* [r0, r0 + n). */
|
||||
static void pipe_boundary(RadCtx* c, const Model& m, int64_t s, int64_t r0, int64_t n) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t li = s / 2;
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
const bool last = li + 1 == (int64_t)m.layers.size();
|
||||
if (s % 2 == 0) {
|
||||
l.attn.ar_rows(c, r0, n);
|
||||
l.attn.post_rows(c, r0, n);
|
||||
l.jf_am.step_rows(c, r0, n);
|
||||
return;
|
||||
}
|
||||
l.mlp.ar_rows(c, r0, n);
|
||||
l.mlp.post_rows(c, r0, n);
|
||||
if (!last) l.jf_ma.step_rows(c, r0, n);
|
||||
else l.mlp.add_rows(c, r0, n);
|
||||
if (last)
|
||||
RAD_ISSUE_N(c, m.op_final, n, brow_slice(m.b_x, r0, n, g.n_embd), RAD_W(m.w_out),
|
||||
brow_slice(m.b_h, r0, n, g.n_embd));
|
||||
}
|
||||
|
||||
/* Layer `li`'s drafter taps of rows [r0, r0 + n), on lane 0. Issued once lane 0 has waited for that
|
||||
* piece's feed-forward boundary (its junction is the last write to those rows of x before the next
|
||||
* block's boundary, which lane 1 starts only behind lane 0's next issues), so the taps buffer is
|
||||
* never touched from lane 1 and stays in the sharing pool: rad_buf_concurrent would hold its
|
||||
* [max_tok, n_taps * n_embd] for the whole program. */
|
||||
static void pipe_taps(RadCtx* c, const Model& m, int64_t li, int64_t r0, int64_t n) {
|
||||
for (int t = 0; t < m.n_taps; ++t) {
|
||||
if (m.tap_layer[t] != (int)li) continue;
|
||||
RAD_ISSUE_N(c, m.op_tap, n, brow_slice(m.b_x, r0, n, m.g.n_embd),
|
||||
bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * m.g.n_embd, (int64_t)t * m.g.n_embd,
|
||||
m.g.n_embd, n));
|
||||
}
|
||||
}
|
||||
|
||||
/* An attention block's first piece is done (ArPieces): lane 0 takes the previous block's second
|
||||
* boundary before the second piece (and the previous layer's second-piece taps behind it), and
|
||||
* lane 1 this block's first behind it. */
|
||||
struct PipeHand {
|
||||
RadCtx* c = nullptr;
|
||||
const Model* m = nullptr;
|
||||
int64_t s = 0;
|
||||
int64_t T = 0;
|
||||
};
|
||||
static void pipe_hand(void* u, int64_t r0, int64_t n) {
|
||||
const PipeHand& h = *(const PipeHand*)u;
|
||||
pipe_wait1(h.c);
|
||||
if (h.s >= 2) {
|
||||
const int64_t R = pipe_rows(h.T);
|
||||
pipe_taps(h.c, *h.m, h.s / 2 - 1, R, h.T - R);
|
||||
}
|
||||
pipe_on1(h.c, [&] { pipe_boundary(h.c, *h.m, h.s, r0, n); });
|
||||
}
|
||||
|
||||
/* The bounds of this step's pieces on the card, {0, pipe_rows(T), T}, if the step is pipelined;
|
||||
* null for a serial step, and null with `failed` set when the step has been failed (a rank-local
|
||||
* failure past the batch's own conditions: the other rank would pipeline). */
|
||||
static const int32_t* pipe_ready(RadCtx* c, const RadBatch* batch, Model& m, bool* failed) {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (!m.pipe_on || !m.b_pipe_cu || T < kPipeMinRows || T > m.g.max_tok ||
|
||||
batch->phase != RAD_PHASE_PREFILL)
|
||||
return nullptr;
|
||||
auto serial = [&](const char* why) -> const int32_t* {
|
||||
if (!m.pipe_serial_noted && m.g.rank == 0)
|
||||
fprintf(stderr, "radiance: gemma3: a %lld-row prefill step runs serially: %s\n",
|
||||
(long long)T, why);
|
||||
m.pipe_serial_noted = true;
|
||||
return nullptr;
|
||||
};
|
||||
if (batch->n_seq != 1 || batch->n_seq_decode != 0) return serial("more than one sequence");
|
||||
if (!batch->positions || batch->rope_pos) return serial("no one-component positions");
|
||||
const RadKVGroupBatch* kvs = kv_batch(batch, m.kv_s);
|
||||
const RadKVGroupBatch* kvg = kv_batch(batch, m.kv_g);
|
||||
if (!kvs || !kvg || !kvs->slot_mapping || !kvg->slot_mapping || !kvs->block_table ||
|
||||
!kvg->block_table || !kvs->seqused || !kvg->seqused)
|
||||
return serial("a KV group without slots, tables or lengths");
|
||||
int32_t* d = (int32_t*)rad_buf_ptr(c, m.b_pipe_cu);
|
||||
if (!d || !rad_buf_ptr(c, m.b_pipe_used)) {
|
||||
rad_step_fail(c, "gemma3: the pipelined prefill's bounds have no storage");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
if (!m.pipe_tbl_tried) {
|
||||
m.pipe_tbl_tried = true;
|
||||
const int64_t n = m.g.max_tok + 1;
|
||||
m.pipe_tbl = (int32_t*)rad_dev_alloc(4 * n * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED);
|
||||
if (m.pipe_tbl)
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
m.pipe_tbl[4 * t] = 0;
|
||||
m.pipe_tbl[4 * t + 1] = (int32_t)pipe_rows(t);
|
||||
m.pipe_tbl[4 * t + 2] = (int32_t)t;
|
||||
m.pipe_tbl[4 * t + 3] = (int32_t)(t - pipe_rows(t));
|
||||
}
|
||||
}
|
||||
if (!m.pipe_tbl ||
|
||||
rad_memcpy_async(d, m.pipe_tbl + 4 * T, 4 * (int64_t)sizeof(int32_t), rad_stream(c)) !=
|
||||
RAD_OK) {
|
||||
rad_step_fail(c, "gemma3: the pipelined prefill's piece bounds could not be put on the card "
|
||||
"(no pinned host memory, or the copy failed)");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
int32_t* u = (int32_t*)rad_buf_ptr(c, m.b_pipe_used);
|
||||
RAD_ISSUE_N(c, m.op_pipe_used, 1, praw(kvs->seqused, RAD_I32, 1), praw(d + 3, RAD_I32, 1),
|
||||
praw(u, RAD_I32, 1));
|
||||
RAD_ISSUE_N(c, m.op_pipe_used, 1, praw(kvg->seqused, RAD_I32, 1), praw(d + 3, RAD_I32, 1),
|
||||
praw(u + 1, RAD_I32, 1));
|
||||
return d;
|
||||
}
|
||||
|
||||
static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, R = pipe_rows(T);
|
||||
const int64_t L = (int64_t)m.layers.size();
|
||||
if (!m.pipe_noted) {
|
||||
m.pipe_noted = true;
|
||||
if (g.rank == 0)
|
||||
fprintf(stderr, "radiance: gemma3: prefill steps of one sequence from %lld rows are "
|
||||
"pipelined: two pieces, block boundaries on the second lane\n",
|
||||
(long long)kPipeMinRows);
|
||||
}
|
||||
RAD_ISSUE(c, m.op_embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
/* The embedding's reduction and layer 0's norm over the whole step, on lane 1 with every other
|
||||
* collective. */
|
||||
pipe_on1(c, [&] {
|
||||
if (m.op_embed_ar) RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.b_x, T), RAD_NONE);
|
||||
m.jf0.step(c, T);
|
||||
});
|
||||
pipe_wait1(c);
|
||||
for (int64_t li = 0; li < L; ++li) {
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
PipeHand h{c, &m, 2 * li, T};
|
||||
ArPieces pc{};
|
||||
pc.rows = R; pc.done = pipe_hand; pc.u = &h; pc.cu = pcu; pc.in_ready = true;
|
||||
const int32_t* used0 = (const int32_t*)rad_buf_ptr(c, m.b_pipe_used) + (l.global ? 1 : 0);
|
||||
l.attn.step_pieces(c, batch, &pc, used0);
|
||||
if (pc.handed != 1) {
|
||||
rad_step_fail(c, "gemma3: an attention block did not run its two pieces");
|
||||
return;
|
||||
}
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li, R, T - R); });
|
||||
l.mlp.body_rows(c, 0, R);
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li + 1, 0, R); });
|
||||
l.mlp.body_rows(c, R, T - R);
|
||||
pipe_wait1(c);
|
||||
pipe_taps(c, m, li, 0, R);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, 2 * li + 1, R, T - R); });
|
||||
}
|
||||
pipe_wait1(c);
|
||||
if (L > 0) pipe_taps(c, m, L - 1, R, T - R);
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out, brows(m.b_h, T),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out, brows(m.b_hout, batch->n_out), RAD_W(m.w_lm),
|
||||
brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
if (batch->enc) {
|
||||
@@ -1197,6 +1621,14 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
else m.df.context(c, batch);
|
||||
return;
|
||||
}
|
||||
{
|
||||
bool pipe_failed = false;
|
||||
if (const int32_t* pcu = pipe_ready(c, batch, m, &pipe_failed)) {
|
||||
step_pipelined(c, batch, m, pcu);
|
||||
return;
|
||||
}
|
||||
if (pipe_failed) return;
|
||||
}
|
||||
const int64_t T = batch->n_tok;
|
||||
/* The drafter conditions on a tapped layer's output, which the next layer overwrites: copy it
|
||||
* into the tap's column slice once the layer's residual is complete. */
|
||||
@@ -1217,7 +1649,8 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
for (size_t li = 0; li < m.layers.size(); ++li) {
|
||||
const Layer& l = m.layers[li];
|
||||
const bool last = li + 1 == m.layers.size();
|
||||
const bool far = m.fuse_mx_ar;
|
||||
/* Per step: the fused junction sends the exact wire only (G3JunctionFP8::op_ar). */
|
||||
const bool far = m.fuse_mx_ar && ar_wire_is_exact(m.g, T);
|
||||
l.attn.step(c, batch, true, true, far);
|
||||
if (!far) l.attn.post(c, T);
|
||||
l.jf_am.step(c, T, far);
|
||||
@@ -1233,10 +1666,11 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
for (size_t li = 0; !m.fuse_mx && li < m.layers.size(); ++li) {
|
||||
const Layer& l = m.layers[li];
|
||||
const bool last = li + 1 == m.layers.size();
|
||||
l.attn.step(c, batch, m.fuse, m.fuse, m.fuse_ar);
|
||||
if (m.fuse) l.j_am.step(c, T, m.fuse_ar);
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last, m.fuse_ar);
|
||||
if (m.fuse && !last) l.j_ma.step(c, T, m.fuse_ar);
|
||||
const bool ar = m.fuse_ar && ar_wire_is_exact(m.g, T); /* exact wire only, as above */
|
||||
l.attn.step(c, batch, m.fuse, m.fuse, ar);
|
||||
if (m.fuse) l.j_am.step(c, T, ar);
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last, ar);
|
||||
if (m.fuse && !last) l.j_ma.step(c, T, ar);
|
||||
tap(li);
|
||||
}
|
||||
/* With fused junctions the last layer's tail ran unfused (tail_fused false), so the stream is
|
||||
|
||||
@@ -8,11 +8,11 @@
|
||||
* norm on the value, and a GELU (not SwiGLU) feed-forward. The final logits are soft-capped to
|
||||
* cap * tanh(x / cap).
|
||||
*
|
||||
* Two draft models, whichever the container carries under `draft.`: Google's assistant head (a
|
||||
* serial head over the trunk's own cache, the Gemma4Head below) or z-lab's DFlash drafter (a
|
||||
* Three draft models, whichever the container carries under `draft.`: Google's assistant head (a
|
||||
* serial head over the trunk's own cache, the Gemma4Head below), z-lab's DFlash drafter (a
|
||||
* five-layer block drafter with its own cache, reading the trunk's residual stream at six layers,
|
||||
* arch/common/rad_gemma4_dflash.h) -- the 31B's z-lab/gemma-4-31B-it-DFlash proposes 15 tokens a
|
||||
* pass where the assistant proposes one a round.
|
||||
* arch/common/rad_gemma4_dflash.h; 15 tokens a pass on the 31B), or a DFlash2 drafter such as
|
||||
* RedHatAI's gemma-4-31B-it-speculator.dflash2 (arch/common/rad_block_dflash2.h; 7 a pass).
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_gemma4_vision.h>
|
||||
@@ -104,7 +104,25 @@ struct G4Linear {
|
||||
rad_op op = 0, op_q = 0; /* the quantised GEMM and, for w4a8, its activation quantiser */
|
||||
rad_buf q8 = 0, s8 = 0; /* the int8 pair (i8 codes + f32 row scale) the quantiser writes */
|
||||
int64_t N = 0, K = 0;
|
||||
bool quant = false; /* true: w4a8 */
|
||||
bool quant = false; /* true: w4a8 / w8a8 over a per-row int8 activation */
|
||||
/* true: i8a8 as arch/gemma3's G3Linear: int8 codes with a bf16 scale per [1 x 128] (libquant
|
||||
* `codes=i8 group=128 scale=bf16`) over quant_act_i8g, an activation scale per (row, 128).
|
||||
* Gemma 4 E4B's activations carry a few channels 40-200 times the row's median (the down
|
||||
* projection's input most), and one int8 scale a row spends its codes on them. There is no
|
||||
* fused norm/quantiser at this grid, so the junctions stay off for a model that uses it. */
|
||||
bool i8g = false;
|
||||
/* true: asymmetric int4 as arch/gemma3's G3Linear: u4 codes, a u8 zero point and an f16 scale
|
||||
* per [1 x 128] (libquant `codes=u4 zero=u8 group=128 scale=f16`), gemm_nt_q at w4a8i8_asym
|
||||
* over the same per-(row, 128) int8 activation as i8g. */
|
||||
bool a4 = false;
|
||||
bool grouped() const { return i8g || a4; }
|
||||
/* a4 at decode heights, as LinearFP8's w4 (rad_fp8.h): up to kA4Split rows the bf16 input is
|
||||
* cast to f16 (`a16`) for w4a16_asym's skinny kernel; w4a8i8_asym has only a prefill kernel,
|
||||
* which at one row does 16 times the matrix work and reads its weight a quarter as fast. */
|
||||
static constexpr int64_t kA4Split = 64;
|
||||
int64_t a4_split = 0; /* rows up to which op_dec serves; 0: no decode band */
|
||||
rad_buf a16 = 0;
|
||||
rad_op op_a16 = 0, op_dec = 0;
|
||||
/* Reads another linear's int8 pair. q, k and v quantise the same norm output on the same
|
||||
* per-row grid, so with `in_from` set at declare this linear reads that linear's pair and
|
||||
* declares no quantiser of its own: one dispatch instead of three. */
|
||||
@@ -175,6 +193,73 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
* at w8a8 reads the same int8 activation and per-row scale as w4a8, so the quantiser is
|
||||
* shared. A recipe uses it for linears int4 hurts (attention, down_proj). */
|
||||
const uint32_t cdt = known && enc.n_planes > 0 ? enc.plane[0].dtype : 0;
|
||||
i8g = known && linear_is_w8(enc);
|
||||
{
|
||||
const RadEncPlane* sp = rad_enc_plane(&enc, "scale");
|
||||
const RadEncPlane* zp = rad_enc_plane(&enc, "zero");
|
||||
a4 = known && rad_enc_is(&enc, "affine") && enc.n_planes == 3 && !enc.transform[0] &&
|
||||
cdt == RAD_U4 && enc.plane[0].block[1] == 1 && sp && sp->dtype == RAD_F16 &&
|
||||
sp->block[0] == 1 && sp->block[1] == RAD_FP8_BLOCK && zp && zp->dtype == RAD_U8 &&
|
||||
zp->block[0] == 1 && zp->block[1] == RAD_FP8_BLOCK;
|
||||
}
|
||||
if (i8g || a4) {
|
||||
if (N % 16 || K % RAD_FP8_BLOCK) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; it takes rows in 16s and K in "
|
||||
"whole %d-column activation scale groups\n", base, (long long)N,
|
||||
(long long)K, RAD_FP8_BLOCK);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (a4) {
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_U4, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale,zero", RAD_F16, { N, K },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
} else {
|
||||
w = decl_view(b, wn, nullptr, "codes", RAD_I8, { N, K }, RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
ws = decl_view(b, nm.f("%s.scale", base), wn, "scale", RAD_BF16, { N, K / RAD_FP8_BLOCK },
|
||||
RAD_ACCESS_PER_TOKEN, shard, grp, parts, np);
|
||||
}
|
||||
if (!w || !ws) return RAD_E_INVAL;
|
||||
/* not an a4 linear's pair: below its decode band it writes none */
|
||||
if (in_from && in_from->grouped() && !in_from->a4 && in_from->q8 && in_from->K == K) {
|
||||
q8 = in_from->q8;
|
||||
s8 = in_from->s8;
|
||||
shared_in = true;
|
||||
} else {
|
||||
q8 = decl_b(b, nm.f("%s.q8", base), RAD_I8, { g.max_tok, K });
|
||||
s8 = decl_b(b, nm.f("%s.s8", base), RAD_F32, { g.max_tok, K / RAD_FP8_BLOCK });
|
||||
if (!q8 || !s8) return RAD_E_INVAL;
|
||||
op_q = rw(b, RAD_OP(b, "quant_act_i8g",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { q8, s8 });
|
||||
if (!op_q) return RAD_E_INVAL;
|
||||
}
|
||||
op = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK),
|
||||
RAD_STR("dtype", a4 ? "w4a8i8_asym" : "i8a8")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ q8, s8 }, { y });
|
||||
if (!op) return RAD_E_INVAL;
|
||||
if (a4) {
|
||||
a4_split = std::min<int64_t>(kA4Split, g.max_tok);
|
||||
a16 = decl_b(b, nm.f("%s.a16", base), RAD_F16, { a4_split, K });
|
||||
if (!a16) return RAD_E_INVAL;
|
||||
op_a16 = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("n", K),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", "f16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{ a }, { a16 });
|
||||
op_dec = rw(b, RAD_OP(b, "gemm_nt_q",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, a4_split), RAD_INT("N", N), RAD_INT("K", K),
|
||||
RAD_INT("group", RAD_FP8_BLOCK), RAD_STR("dtype", "w4a16_asym")),
|
||||
RAD_WEIGHTS(w, ws)),
|
||||
{ a16 }, { y });
|
||||
if (!op_a16 || !op_dec) return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
if (known && g4_grid_w4(enc)) {
|
||||
if (N % 16 || K % 128) {
|
||||
fprintf(stderr, "radiance: '%s' is %lldx%lld per rank; a w4 weight takes rows in "
|
||||
@@ -216,8 +301,8 @@ inline int G4Linear::declare(RadBuilder* b, Names& nm, const Geom& g, const char
|
||||
|
||||
char en[256];
|
||||
rad_enc_format(&enc, en, sizeof en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16, w4a8 or w8a8 -- "
|
||||
"neither matches\n", wn, en);
|
||||
fprintf(stderr, "radiance: '%s' is %s, and this model's linears are plain bf16, w4a8, w8a8, "
|
||||
"int8 a 128 (i8a8) or asymmetric int4 a 128 -- none matches\n", wn, en);
|
||||
return RAD_E_DTYPE;
|
||||
}
|
||||
|
||||
@@ -229,6 +314,16 @@ inline void G4Linear::step(RadCtx* c, rad_buf a, rad_buf y, int64_t T) const {
|
||||
if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T), RAD_NONE);
|
||||
gemm(c, y, T);
|
||||
} else if (a4 && T <= a4_split) {
|
||||
/* the decode band: f16 copy of the input, the skinny kernel; operands as LinearFP8's w4 */
|
||||
RAD_ISSUE_N(c, op_a16, T, brows(a, T), brows(a16, T));
|
||||
RAD_ISSUE_N(c, op_dec, T, brows(a16, T), RAD_NONE, RAD_W(w), RAD_W(ws), brows(y, T),
|
||||
RAD_NONE, RAD_NONE);
|
||||
} else if (grouped()) {
|
||||
/* quant_act_i8g takes x, q, scale: no optional `asum`. */
|
||||
if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, T, brows(a, T), brows(q8, T), brows(s8, T));
|
||||
gemm(c, y, T);
|
||||
} else
|
||||
RAD_ISSUE(c, op, brows(a, T), RAD_W(w), brows(y, T));
|
||||
}
|
||||
@@ -239,18 +334,29 @@ inline void G4Linear::gemm(RadCtx* c, rad_buf y, int64_t T) const {
|
||||
}
|
||||
|
||||
inline void G4Linear::step_rows(RadCtx* c, rad_buf a, rad_buf y, int64_t r0, int64_t n) const {
|
||||
if (!quant) {
|
||||
if (a4 && n <= a4_split) {
|
||||
RAD_ISSUE_N(c, op_a16, n, brow_slice(a, r0, n, K), brows(a16, n));
|
||||
RAD_ISSUE_N(c, op_dec, n, brows(a16, n), RAD_NONE, RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE);
|
||||
return;
|
||||
}
|
||||
if (!quant && !grouped()) {
|
||||
RAD_ISSUE_N(c, op, n, brow_slice(a, r0, n, K), RAD_W(w), brow_slice(y, r0, n, N));
|
||||
return;
|
||||
}
|
||||
if (!shared_in)
|
||||
const int64_t sw = grouped() ? K / RAD_FP8_BLOCK : 1; /* the scale plane's row width */
|
||||
if (!shared_in && grouped())
|
||||
RAD_ISSUE_N(c, op_q, n, brow_slice(a, r0, n, K), brow_slice(q8, r0, n, K),
|
||||
brow_slice(s8, r0, n, sw));
|
||||
else if (!shared_in)
|
||||
RAD_ISSUE_N(c, op_q, n, brow_slice(a, r0, n, K), brow_slice(q8, r0, n, K),
|
||||
brow_slice(s8, r0, n, 1), RAD_NONE);
|
||||
gemm_rows(c, y, r0, n);
|
||||
}
|
||||
|
||||
inline void G4Linear::gemm_rows(RadCtx* c, rad_buf y, int64_t r0, int64_t n) const {
|
||||
RAD_ISSUE_N(c, op, n, brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, 1), RAD_W(w), RAD_W(ws),
|
||||
const int64_t sw = grouped() ? K / RAD_FP8_BLOCK : 1;
|
||||
RAD_ISSUE_N(c, op, n, brow_slice(q8, r0, n, K), brow_slice(s8, r0, n, sw), RAD_W(w), RAD_W(ws),
|
||||
brow_slice(y, r0, n, N), RAD_NONE, RAD_NONE);
|
||||
}
|
||||
|
||||
@@ -265,6 +371,11 @@ struct Gemma4Attn {
|
||||
ClassGeom cls{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
/* KV sharing (num_kv_shared_layers, Gemma 4 E2B/E4B): a shared layer has no k or v of its own
|
||||
* and attends over the cache of `kv_layer`, the last earlier layer of its class that keeps
|
||||
* one. A layer with its own cache has kv_layer == layer. */
|
||||
bool shared = false;
|
||||
int kv_layer = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_qn = 0, w_kn = 0, w_post = 0; /* the norms (always bf16) */
|
||||
G4Linear ln_q{}, ln_k{}, ln_v{}, ln_o{}; /* the GEMM weights (bf16 or w4a8) */
|
||||
@@ -297,12 +408,16 @@ struct Gemma4Attn {
|
||||
/* The linear whose int8 pair a junction writes, and whether every projection reads it. */
|
||||
const G4Linear& ln_in() const { return fused ? ln_qkv : ln_q; }
|
||||
bool reads_pair() const {
|
||||
if (shared) return ln_q.quant;
|
||||
return fused ? ln_qkv.quant
|
||||
: ln_q.quant && ln_k.shared_in && (!cls.has_v || ln_v.shared_in);
|
||||
}
|
||||
|
||||
/* `kv_src` < 0: the layer keeps its own cache; else the layer whose cache it reads. */
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot);
|
||||
rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot,
|
||||
int kv_src = -1);
|
||||
int declare_shared(RadBuilder* b, Names& nm, const char* pre);
|
||||
/* `entry_done`: a junction op already wrote this block's quantised input (ln_q's pair).
|
||||
* `tail_fused`: the caller issues the post-norm and the add as a junction op. */
|
||||
void step(RadCtx* c, const RadBatch* batch, bool entry_done = false, bool tail_fused = false,
|
||||
@@ -323,8 +438,12 @@ struct Gemma4Attn {
|
||||
};
|
||||
|
||||
int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const ClassGeom& cgeo,
|
||||
rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot) {
|
||||
rad_kvgroup group, const Wire& wire, const char* pre, rad_buf* qkv_slot,
|
||||
int kv_src) {
|
||||
g = geom; cls = cgeo; layer = l; kv = group; w = wire;
|
||||
shared = kv_src >= 0;
|
||||
kv_layer = shared ? kv_src : l;
|
||||
if (shared) return declare_shared(b, nm, pre);
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
const int64_t qkvd = qd + kvd + (cls.has_v ? kvd : 0);
|
||||
|
||||
@@ -363,13 +482,18 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
if (cls.has_v) RAD_ARCH_TRY(map_concat(b, qkv_wn, { q_src, k_src, v_src }));
|
||||
else RAD_ARCH_TRY(map_concat(b, qkv_wn, { q_src, k_src }));
|
||||
{
|
||||
/* one q|k|v GEMM wherever the weight is on a quantised grid: w4a8 / w8a8, i8a8 or a4 */
|
||||
RadEncoding e{};
|
||||
fused = weight_enc(b, qkv_wn, &e) && g4_grid_w4(e);
|
||||
fused = weight_enc(b, qkv_wn, &e) && (g4_grid_w4(e) || linear_is_w8(e) ||
|
||||
(rad_enc_is(&e, "affine") && e.n_planes == 3 &&
|
||||
e.plane[0].dtype == RAD_U4));
|
||||
}
|
||||
if (fused) {
|
||||
if (!qkv_slot) return RAD_E_INVAL;
|
||||
if (!*qkv_slot)
|
||||
*qkv_slot = decl_b(b, nm.f(cls.has_v ? "attn_qkvs" : "attn_qkvg"), g.act_dtype,
|
||||
/* named by class, not by the value path: a global class with its own v (E2B/E4B,
|
||||
* attention_k_eq_v false) has one too, and the two rows differ in width */
|
||||
*qkv_slot = decl_b(b, nm.f(cls.head_ladder ? "attn_qkvg" : "attn_qkvs"), g.act_dtype,
|
||||
{g.max_tok, qkvd});
|
||||
w.qkv = *qkv_slot;
|
||||
if (cls.has_v)
|
||||
@@ -589,6 +713,78 @@ int Gemma4Attn::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, const
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A KV-shared layer (transformers' Gemma4TextAttention with is_kv_shared_layer): q_proj, the per-head
|
||||
* q norm and the class's rotary, attention over the source layer's cache, o_proj and the two norms.
|
||||
* No k or v projection, no k or v norm and no cache store: the source layer, earlier in the same
|
||||
* step, wrote the keys and values these queries read. The checkpoint's k_proj / v_proj / k_norm of
|
||||
* these layers (the "frozen shared kv" file) are unused, as in the reference. */
|
||||
int Gemma4Attn::declare_shared(RadBuilder* b, Names& nm, const char* pre) {
|
||||
const int l = layer;
|
||||
const int64_t qd = cls.q_dim();
|
||||
fused = false;
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), nm.ckpt("%s.%lld.input_layernorm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_q_norm.weight", l), nm.ckpt("%s.%lld.self_attn.q_norm.weight", pre, (long long)l)));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_post_norm.weight", l), nm.ckpt("%s.%lld.post_attention_layernorm.weight", pre, (long long)l)));
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_BF16, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_qn = decl_w(b, nm.f("blk.%d.attn_q_norm.weight", l), RAD_BF16, {cls.head_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_post = decl_w(b, nm.f("blk.%d.attn_post_norm.weight", l), RAD_BF16, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
RAD_ARCH_TRY(ln_q.declare(b, nm, g, nm.f("blk.%d.attn_q", l),
|
||||
{ nm.ckpt("%s.%lld.self_attn.q_proj.weight", pre, (long long)l) },
|
||||
qd, g.n_embd, RAD_SHARD_ROW, grp_layer(l), w.h, w.q));
|
||||
RAD_ARCH_TRY(ln_o.declare(b, nm, g, nm.f("blk.%d.attn_o", l),
|
||||
{ nm.ckpt("%s.%lld.self_attn.o_proj.weight", pre, (long long)l) },
|
||||
g.n_embd, qd, RAD_SHARD_COL, grp_layer(l), w.attn, w.h));
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
op_qn = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * cls.n_head), RAD_INT("n", cls.head_dim),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd_qk), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qn)),
|
||||
{w.q}, {w.q});
|
||||
op_rq = rw(b, RAD_OP(b, "rope",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", cls.head_dim),
|
||||
RAD_INT("n_head", cls.n_head), RAD_INT("n_head_kv", 0),
|
||||
RAD_F64("theta", cls.theta), RAD_F64("scale", cls.scale),
|
||||
RAD_STR("mode", "neox"), RAD_INT("rotary_dim", cls.n_rot),
|
||||
RAD_STR("ladder", cls.head_ladder ? "head" : "rotary")),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.q});
|
||||
op_attn = rw(b, RAD_OP(b, "attn_paged",
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok),
|
||||
RAD_INT("head_dim", cls.head_dim),
|
||||
RAD_INT("gqa", cls.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", cls.window), RAD_INT("n_head", cls.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_F64("scale", 1.0),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.attn});
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world), RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
op_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_post)),
|
||||
{w.h}, {w.h});
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h}, {w.x});
|
||||
return (op_norm && op_qn && op_rq && op_attn && op_post && op_add) ? RAD_OK : RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ---- Prefetch beside the reductions (prefetch_beside, rad_arch.h). The all-reduce in front of
|
||||
* each GEMM leaves the card's memory idle for its round trip (~20 us at a DFlash2 verify's rows on
|
||||
* 4x R9700), so the trunk reads the next GEMM's leading bytes in that window -- gate_up's after
|
||||
@@ -609,7 +805,13 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
bool ar_fused) const {
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
if (fused) {
|
||||
if (shared) {
|
||||
if (entry_done) ln_q.gemm(c, w.q, T);
|
||||
else {
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
ln_q.step(c, w.h, w.q, T);
|
||||
}
|
||||
} else if (fused) {
|
||||
if (!entry_done) RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
if (entry_done) ln_qkv.gemm(c, w.qkv, T);
|
||||
else ln_qkv.step(c, w.h, w.qkv, T);
|
||||
@@ -637,6 +839,10 @@ void Gemma4Attn::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool ta
|
||||
}
|
||||
|
||||
void Gemma4Attn::project(RadCtx* c, int64_t r0, int64_t n) const {
|
||||
if (shared) {
|
||||
ln_q.gemm_rows(c, w.q, r0, n);
|
||||
return;
|
||||
}
|
||||
if (fused) {
|
||||
ln_qkv.gemm_rows(c, w.qkv, r0, n);
|
||||
return;
|
||||
@@ -657,6 +863,19 @@ void Gemma4Attn::attend(RadCtx* c, const RadBatch* batch) const {
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
const int64_t T = batch->n_tok;
|
||||
const int64_t qd = cls.q_dim(), kvd = cls.kv_dim();
|
||||
if (shared) {
|
||||
/* q only: its norm and rotary, then attention over the source layer's cache. */
|
||||
RAD_ISSUE_N(c, op_qn, T * cls.n_head, brows(w.q, T), RAD_W(w_qn), brows(w.q, T));
|
||||
RAD_ISSUE(c, op_rq, brows(w.q, T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
brows(w.q, T), kv_cache(kv, kv_layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
return;
|
||||
}
|
||||
/* q, k and v where the prologue works on them: their own buffers, or on a fused layer with the
|
||||
* one-op prologue the row's column slices (a k_eq_v class's v is its own buffer either way). */
|
||||
const bool row = fused && op_qnr;
|
||||
@@ -869,43 +1088,24 @@ void Gemma4Mlp::step(RadCtx* c, const RadBatch* batch, bool entry_done, bool tai
|
||||
/* ---- one residual junction as one op: [post-norm of the branch `x`, the add into `res`, the
|
||||
* layer scalar,] the next block's norm and its int8 quantiser (libr4d `rmsnorm_quant_i8`). With
|
||||
* `res` null it is the plain norm of `x`, the first block's entry. */
|
||||
/* The four-rank fold's band. libr4d's exact all-reduce is a one-shot up to this many elements
|
||||
* (R4D_AR_WIDE_ONESHOT_MAX_ELEMS) and a two-shot above, and the fused junction at four ranks is
|
||||
* that one-shot with the junction as its epilogue: three times the message per rank on the link,
|
||||
* which pays at decode heights and not at a prefill's. So at four ranks op_ar serves the rows a
|
||||
* one-shot would, 97 at 5376, and a taller step issues the all-reduce and the junction apart.
|
||||
*
|
||||
* Within that band the fold pays only at the bottom. On 4x R9700 (2026-10-17, same image) a plain
|
||||
* decode step (1 row) ran 5.6% slower without it (89 against 94 tok/s), and a DFlash verify
|
||||
* (16 rows) 9% faster (300 against 276): at 16 rows the standalone all-reduce is the exact
|
||||
* two-shot, while the fold's one block a row each takes a fenced handshake. The per-row costs
|
||||
* cross near 4-5 rows. From 5 rows libr4d's four-rank row takes its tail form instead (axis
|
||||
* `tail`): the standalone two-shot with the junction run after it in the same launch, behind a
|
||||
* card-local count, so the junction costs neither a handshake nor a launch. With it a DFlash2
|
||||
* verify (8 rows) folds and gains ~1% (348 / 258 / 187 / 516 against 345 / 255 / 185 / 511 tok/s,
|
||||
* code / prose / story / long, 4x R9700; replies identical), where the one-shot fold there lost
|
||||
* 6%. So the fold serves up to kAr4FoldRows rows, a z-lab DFlash verify's 16 included, and a
|
||||
* taller step issues the pair. */
|
||||
static constexpr int64_t kArOneShotElems = 524288;
|
||||
/* The four-rank fold's band. libr4d's four-rank row serves it in three forms, all byte-identical
|
||||
* to all_reduce + rmsnorm_quant_i8. Up to 4 rows it is the exact one-shot with the junction as its
|
||||
* epilogue: three times the message per rank and one fenced handshake a row, which wins at one row
|
||||
* (plain decode about 5% faster on 4x R9700) and loses to the standalone two-shot by 16. From 5
|
||||
* rows it is that two-shot with the junction as its tail (axis `tail`), behind a card-local count,
|
||||
* so the junction costs neither a handshake nor a launch. Above kAr4FoldRows a step issues the
|
||||
* pair. */
|
||||
static constexpr int64_t kAr4FoldRows = 16;
|
||||
/* From kArSpMinRows rows to the same band's top, libr4d's four-rank row takes `sp` instead: the
|
||||
* all-reduce split around the junction. Each rank reduces only the rows it owns (a quarter, in
|
||||
* rank order), runs the junction on them and gathers the int8 codes the next GEMM reads, so the
|
||||
* second hop carries a byte a column instead of two and the junction a quarter of the rows. The
|
||||
* fold and the sums are the whole form's, so q and the scales are byte for byte the same; the
|
||||
* residual stream then holds this rank's rows only, which is all the next junction reads. A
|
||||
* junction whose stream anything else reads next asks for the residual on every row too (sp 2):
|
||||
/* From kArSpMinRows rows to kArSpMaxRows, libr4d's four-rank row takes `sp`: the all-reduce split
|
||||
* around the junction. Each rank reduces only the rows it owns (a quarter, in rank order), runs the
|
||||
* junction on them and gathers the int8 codes the next GEMM reads, so the second hop carries a byte
|
||||
* a column instead of two and the junction runs on a quarter of the rows. q and the scales are
|
||||
* the whole form's bytes; the residual stream then holds this rank's rows only, which is all the
|
||||
* next junction reads. A junction whose stream anything else reads next asks for every row (sp 2):
|
||||
* the layers the drafter taps, and the last layer's attention junction, since that layer's
|
||||
* feed-forward closes with its own all-reduce, post-norm and add over every row. One launch at a
|
||||
* time on 4x R9700 (2026-10-19): 19.8 against 21.9 us at 4 rows of 5376 (the one-shot fold), 22.9
|
||||
* against 24.5 at 8 and 30.8 against 34.9 at 16 (the tail), 72.3 against 89.2 at 64. Below 4 rows
|
||||
* a rank would idle (31.7 against 18.7 us at one).
|
||||
*
|
||||
* In the engine it pays only where it replaces the fold: a DFlash2 verify (8 rows) ran 402 / 297 /
|
||||
* 216 / 603 tok/s code / prose / story / long against 392 / 290 / 210 / 585, replies identical,
|
||||
* but steps of 24-64 rows, where the pair runs instead, lost ~10% under load (4 users 588 against
|
||||
* 698 aggregate, 8 users 781 against 867; 12 users even; 4x R9700, 2026-10-19). So it serves to
|
||||
* kArSpMaxRows, the fold's band, within the one-shot's. */
|
||||
* feed-forward closes with its own all-reduce, post-norm and add over every row. Below 4 rows a
|
||||
* rank would idle (on 4x R9700, 31.7 against 18.7 us at one row); at 24-64 rows, where the pair
|
||||
* runs, the split form lost about 10% of aggregate throughput under load. */
|
||||
static constexpr int64_t kArSpMinRows = 4;
|
||||
static constexpr int64_t kArSpMaxRows = 16;
|
||||
|
||||
@@ -941,11 +1141,10 @@ struct G4Junction {
|
||||
rad_op_writes(b, op, wr, res ? 3 : 2);
|
||||
/* With the all-reduce in front, at two or four ranks on the exact wire: `x` is then a
|
||||
* rank's partial sum of a column-sharded linear. With the lossy wire allowed, the
|
||||
* standalone all-reduce is kept, since it may choose that wire. At four ranks the fold is
|
||||
* the one-shot's and serves only its band (kArOneShotElems, kAr4FoldRows). */
|
||||
* standalone all-reduce is kept, since it may choose that wire. At four ranks the fold
|
||||
* serves steps of up to kAr4FoldRows rows. */
|
||||
const bool four = g.world == 4;
|
||||
const int64_t hi = four ? std::min<int64_t>(kAr4FoldRows, std::min<int64_t>(g.max_tok, kArOneShotElems / g.n_embd))
|
||||
: g.max_tok;
|
||||
const int64_t hi = four ? std::min<int64_t>(kAr4FoldRows, g.max_tok) : g.max_tok;
|
||||
if (res && g.wire_exact && (g.world == 2 || four) && hi >= 1 &&
|
||||
rad_op_declared(b, "ar_rmsnorm_quant_i8")) {
|
||||
const RadParam pa[] = { RAD_RANGE("M", 1, hi), RAD_INT("n", g.n_embd),
|
||||
@@ -960,8 +1159,7 @@ struct G4Junction {
|
||||
}
|
||||
/* The split form from kArSpMinRows to kArSpMaxRows rows. It needs the post-norm, as
|
||||
* every trunk junction past the first has; `x` is declared written, as the fold's. */
|
||||
const int64_t top = std::min<int64_t>(
|
||||
std::min<int64_t>(g.max_tok, kArOneShotElems / g.n_embd), kArSpMaxRows);
|
||||
const int64_t top = std::min<int64_t>(g.max_tok, kArSpMaxRows);
|
||||
if (op_ar && four && wp && top >= kArSpMinRows) {
|
||||
const RadParam ps[] = { RAD_RANGE("M", 1, top), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_INT("world_size", g.world),
|
||||
@@ -1468,6 +1666,11 @@ struct Layer {
|
||||
Gemma4Mlp mlp{};
|
||||
rad_weight w_scalar = 0; /* the per-layer [1] residual scalar, `cur = cur * scalar` */
|
||||
rad_op op_scale = 0;
|
||||
/* Per-layer embeddings (Gemma 4 E2B/E4B), after the feed-forward's residual add and before the
|
||||
* scalar: x += norm(proj(gelu(gate(x)) * pli[l])). `ple_post` is the norm's gain. */
|
||||
G4Linear ln_pg{}, ln_pp{};
|
||||
rad_weight w_ple_post = 0;
|
||||
rad_op op_ple_act = 0, op_ple_post = 0, op_ple_add = 0;
|
||||
/* The fused junctions (see "Residual junctions" above): attention -> this layer's
|
||||
* feed-forward, and this layer's feed-forward -> the next layer's attention, scalar included.
|
||||
* The last layer has no j_ma: its stream goes to the final norm, which feeds the lm_head, not
|
||||
@@ -1506,6 +1709,22 @@ struct Model {
|
||||
rad_weight w_tok = 0, w_out = 0, w_lm = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_final = 0, op_gather = 0, op_logits = 0, op_cap = 0;
|
||||
|
||||
/* Per-layer embeddings (hidden_size_per_layer_input > 0): the token-identity table
|
||||
* (embed_tokens_per_layer, n_layer x n_ple wide), the context projection of the scaled
|
||||
* embedding and its per-(token, layer) norm, combined into `b_ple` [max_tok, n_layer * n_ple]
|
||||
* that every layer reads its slice of. */
|
||||
int64_t n_ple = 0;
|
||||
rad_weight w_ple_tok = 0, w_ple_norm = 0;
|
||||
G4Linear ln_ple_proj{};
|
||||
rad_buf b_ple = 0, b_ple_tok = 0, b_pg = 0;
|
||||
rad_op op_ple_tok = 0, op_ple_norm = 0, op_ple_add = 0;
|
||||
/* An image's placeholder positions take the token-identity row of pad_token_id, as the
|
||||
* reference looks them up (Gemma4Model.forward: llm_input_ids = pad where multimodal): that row
|
||||
* times sqrt(n_ple), made as fill(sqrt(n_ple)) * the row, scattered over the image rows. */
|
||||
rad_weight w_ple_pad = 0;
|
||||
rad_buf b_ple_pad = 0;
|
||||
rad_op op_ple_pfill = 0, op_ple_pmul = 0, op_ple_pscat = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
|
||||
/* The assistant head, declared only when the container carries one and the deployment
|
||||
@@ -1768,7 +1987,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
Names& nm = m.nm;
|
||||
|
||||
/* ---- geometry RadModelMeta does not name. */
|
||||
const int64_t kv_g_all = meta_text_geti(meta, "num_global_key_value_heads", 0);
|
||||
/* num_global_key_value_heads may be null (Gemma 4 E2B/E4B): the global layers then take the
|
||||
* model's num_key_value_heads, as transformers' per-layer config does. */
|
||||
const int64_t kv_g_all = meta_text_geti(meta, "num_global_key_value_heads",
|
||||
meta_text_geti(meta, "num_key_value_heads", 0));
|
||||
const int64_t head_g = meta_text_geti(meta, "global_head_dim", 0);
|
||||
const int64_t sliding_win = meta_text_geti(meta, "sliding_window", 0);
|
||||
const int64_t kv_shared = meta_text_geti(meta, "num_kv_shared_layers", 0);
|
||||
@@ -1798,12 +2020,28 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
if (!(softcap > 0.0)) { fprintf(stderr, "radiance: gemma4: final_logit_softcapping is required\n"); return RAD_E_INVAL; }
|
||||
if (kv_shared < 0) { fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld is negative\n", (long long)kv_shared); return RAD_E_INVAL; }
|
||||
if (kv_shared > 0) {
|
||||
fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld needs a shared-KV reuse path; refusing\n",
|
||||
(long long)kv_shared);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
if (kv_shared >= g.n_layer) {
|
||||
fprintf(stderr, "radiance: gemma4: num_kv_shared_layers %lld leaves no layer with a cache of "
|
||||
"its own (%lld layers)\n", (long long)kv_shared, (long long)g.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (sliding_win <= 0) { fprintf(stderr, "radiance: gemma4: sliding_window %lld is required\n", (long long)sliding_win); return RAD_E_INVAL; }
|
||||
m.n_ple = meta_text_geti(meta, "hidden_size_per_layer_input", 0);
|
||||
if (m.n_ple < 0) { fprintf(stderr, "radiance: gemma4: hidden_size_per_layer_input %lld is negative\n", (long long)m.n_ple); return RAD_E_INVAL; }
|
||||
if (m.n_ple > 0) {
|
||||
const int64_t v_ple = meta_text_geti(meta, "vocab_size_per_layer_input", g.n_vocab_all);
|
||||
if (g.world > 1) {
|
||||
fprintf(stderr, "radiance: gemma4: per-layer embeddings (hidden_size_per_layer_input %lld) "
|
||||
"are served at one rank only; this model is small enough for one card\n",
|
||||
(long long)m.n_ple);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (v_ple != g.n_vocab_all) {
|
||||
fprintf(stderr, "radiance: gemma4: vocab_size_per_layer_input %lld differs from the "
|
||||
"vocabulary (%lld)\n", (long long)v_ple, (long long)g.n_vocab_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
if (!(prf > 0.0)) prf = 1.0;
|
||||
const int64_t n_rot_g = (int64_t)(head_g * prf + 0.5);
|
||||
if (n_rot_g <= 0 || n_rot_g > head_g || (n_rot_g & 1)) {
|
||||
@@ -1828,6 +2066,26 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
int n_global = 0;
|
||||
for (int v : is_global) n_global += v;
|
||||
|
||||
/* KV sharing: from layer n_layer - num_kv_shared_layers on, a layer keeps no cache and reads the
|
||||
* last earlier non-shared layer of its own class (transformers' store_full_length_kv; E4B:
|
||||
* sliding layers read 22, full layers 23). kv_src[l] is that layer, or -1 for an own cache. */
|
||||
const int64_t first_shared = g.n_layer - kv_shared;
|
||||
std::vector<int> kv_src((size_t)g.n_layer, -1);
|
||||
if (kv_shared > 0) {
|
||||
int last_s = -1, last_f = -1;
|
||||
for (int64_t l = 0; l < first_shared; ++l) (is_global[(size_t)l] ? last_f : last_s) = (int)l;
|
||||
for (int64_t l = first_shared; l < g.n_layer; ++l) {
|
||||
const int src = is_global[(size_t)l] ? last_f : last_s;
|
||||
if (src < 0) {
|
||||
fprintf(stderr, "radiance: gemma4: KV-shared layer %lld is %s and no earlier layer of "
|
||||
"that class keeps a cache\n", (long long)l,
|
||||
is_global[(size_t)l] ? "full" : "sliding");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
kv_src[(size_t)l] = src;
|
||||
}
|
||||
}
|
||||
|
||||
/* The sliding class comes from geom_from (head_dim 256, 16 kv heads, full rotation, theta_s);
|
||||
* the global class is built from the container header. */
|
||||
m.cs.n_head = g.n_head; m.cs.n_head_kv = g.n_head_kv; m.cs.head_dim = g.head_dim;
|
||||
@@ -1929,6 +2187,78 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
/* ---- per-layer embeddings (transformers' get_per_layer_inputs / project_per_layer_inputs):
|
||||
* tok = embed_tokens_per_layer[id] * sqrt(n_ple) (bf16, sqrt(256) = 16)
|
||||
* ctx = rmsnorm( (e @ W_proj^T) * n_embd^-0.5 ) per (token, layer) over n_ple, gain w_norm
|
||||
* pli = (ctx + tok) * 2^-0.5
|
||||
* `e` is the scaled embedding (after any image rows are scattered in). The projection's scale
|
||||
* is folded into the norm's eps, as embgemma2 does: rmsnorm(s x, eps) = rmsnorm(x, eps / s^2),
|
||||
* so no bf16 rounding of s x. The table is read a row a token, so the placement puts it in the
|
||||
* pinned host pool by default (--embedding-placement ram), off the card. */
|
||||
if (m.n_ple > 0) {
|
||||
const int64_t P = g.n_layer * m.n_ple;
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("ple_token_embd.weight"),
|
||||
nm.ckpt("model.language_model.embed_tokens_per_layer.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("ple_proj_norm.weight"),
|
||||
nm.ckpt("model.language_model.per_layer_projection_norm.weight")));
|
||||
m.w_ple_tok = decl_w(b, nm.f("ple_token_embd.weight"), RAD_BF16, {g.n_vocab, P},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.w_ple_norm = decl_w(b, nm.f("ple_proj_norm.weight"), RAD_BF16, {m.n_ple},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.b_ple = decl_b(b, nm.f("ple_in"), g.act_dtype, {g.max_tok, P});
|
||||
m.b_ple_tok = decl_b(b, nm.f("ple_tok"), g.act_dtype, {g.max_tok, P});
|
||||
m.b_pg = decl_b(b, nm.f("ple_gate"), g.act_dtype, {g.max_tok, m.n_ple});
|
||||
if (!m.w_ple_tok || !m.w_ple_norm || !m.b_ple || !m.b_ple_tok || !m.b_pg) return RAD_E_INVAL;
|
||||
m.op_ple_tok = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", P),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off),
|
||||
RAD_F64("mult", std::sqrt((double)m.n_ple))),
|
||||
RAD_WEIGHTS(m.w_ple_tok)),
|
||||
{}, {m.b_ple_tok});
|
||||
RAD_ARCH_TRY(m.ln_ple_proj.declare(b, nm, g, nm.f("ple_model_proj"),
|
||||
{ nm.ckpt("model.language_model.per_layer_model_projection.weight") },
|
||||
P, g.n_embd, RAD_SHARD_NONE, grp_model(), m.b_x, m.b_ple));
|
||||
m.op_ple_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok * g.n_layer), RAD_INT("n", m.n_ple),
|
||||
RAD_F64("eps", (double)g.eps * (double)g.n_embd),
|
||||
RAD_F64("wadd", 0.0), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_ple_norm)),
|
||||
{m.b_ple}, {m.b_ple});
|
||||
m.op_ple_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P),
|
||||
RAD_STR("dtype", g.dtype), RAD_F64("div", std::sqrt(2.0))),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_ple, m.b_ple_tok}, {m.b_ple});
|
||||
if (!m.op_ple_tok || !m.op_ple_norm || !m.op_ple_add) return RAD_E_INVAL;
|
||||
if (m.op_mm) {
|
||||
const int pad = (int)meta_text_geti(meta, "pad_token_id", 0);
|
||||
RAD_ARCH_TRY(map_slice(b, nm.f("ple_pad_row.weight"),
|
||||
nm.ckpt("model.language_model.embed_tokens_per_layer.weight"), pad));
|
||||
m.w_ple_pad = decl_w(b, nm.f("ple_pad_row.weight"), RAD_BF16, {P}, RAD_ACCESS_PER_TOKEN,
|
||||
RAD_SHARD_NONE, grp_model());
|
||||
m.b_ple_pad = decl_b(b, nm.f("ple_pad"), g.act_dtype, {g.max_tok, P});
|
||||
if (!m.w_ple_pad || !m.b_ple_pad) return RAD_E_INVAL;
|
||||
m.op_ple_pfill = rw(b, RAD_OP(b, "fill",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P),
|
||||
RAD_STR("dtype", g.dtype),
|
||||
RAD_F64("value", std::sqrt((double)m.n_ple))),
|
||||
RAD_NOWEIGHTS),
|
||||
{}, {m.b_ple_pad});
|
||||
m.op_ple_pmul = rw(b, RAD_OP(b, "mul_weight",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("scalar", 0)),
|
||||
RAD_WEIGHTS(m.w_ple_pad)),
|
||||
{m.b_ple_pad}, {m.b_ple_pad});
|
||||
m.op_ple_pscat = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", P),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_ple_pad, m.b_ple_tok}, {m.b_ple_tok});
|
||||
if (!m.op_ple_pfill || !m.op_ple_pmul || !m.op_ple_pscat) return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the layers. */
|
||||
Gemma4Attn::Wire sw{}; sw.x = m.b_x; sw.h = m.b_h; sw.q = m.b_qs; sw.k = m.b_ks; sw.v = m.b_vs; sw.attn = m.b_attns;
|
||||
Gemma4Attn::Wire gw{}; gw.x = m.b_x; gw.h = m.b_h; gw.q = m.b_qg; gw.k = m.b_kg; gw.v = m.b_vg; gw.attn = m.b_atting;
|
||||
@@ -1941,9 +2271,10 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
const ClassGeom& cgeo = lay.global ? m.cg : m.cs;
|
||||
const rad_kvgroup kg = lay.global ? m.kv_g : m.kv_s;
|
||||
const Gemma4Attn::Wire& aw = lay.global ? gw : sw;
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
|
||||
/* A KV-shared layer is not bound: the group's pages hold only the layers that write. */
|
||||
if (kv_src[(size_t)l] < 0) RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, kg));
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, cgeo, kg, aw, pre,
|
||||
lay.global ? &m.b_qkvg : &m.b_qkvs));
|
||||
lay.global ? &m.b_qkvg : &m.b_qkvs, kv_src[(size_t)l]));
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, pre));
|
||||
|
||||
/* The per-layer scalar: `cur = cur * scalar`, a [1] bf16 over the residual stream. */
|
||||
@@ -1957,11 +2288,48 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_WEIGHTS(lay.w_scalar)),
|
||||
{mw.x}, {mw.x});
|
||||
|
||||
/* The per-layer embedding branch (transformers' Gemma4TextDecoderLayer, after the
|
||||
* feed-forward's residual add): gate n_embd -> n_ple, gelu_tanh times this layer's slice of
|
||||
* `ple_in`, projection back to n_embd into `h`, its norm, the residual add. The scalar
|
||||
* follows it. */
|
||||
if (m.n_ple > 0) {
|
||||
RAD_ARCH_TRY(lay.ln_pg.declare(b, nm, g, nm.f("blk.%d.ple_gate", (int)l),
|
||||
{ nm.ckpt("%s.%lld.per_layer_input_gate.weight", pre, (long long)l) },
|
||||
m.n_ple, g.n_embd, RAD_SHARD_NONE, grp_layer((int)l),
|
||||
m.b_x, m.b_pg));
|
||||
RAD_ARCH_TRY(lay.ln_pp.declare(b, nm, g, nm.f("blk.%d.ple_proj", (int)l),
|
||||
{ nm.ckpt("%s.%lld.per_layer_projection.weight", pre, (long long)l) },
|
||||
g.n_embd, m.n_ple, RAD_SHARD_NONE, grp_layer((int)l),
|
||||
m.b_pg, m.b_h));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ple_post_norm.weight", (int)l),
|
||||
nm.ckpt("%s.%lld.post_per_layer_input_norm.weight", pre, (long long)l)));
|
||||
lay.w_ple_post = decl_w(b, nm.f("blk.%d.ple_post_norm.weight", (int)l), RAD_BF16, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer((int)l));
|
||||
lay.op_ple_act = rw(b, RAD_OP(b, "act_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", m.n_ple),
|
||||
RAD_STR("act", "gelu_tanh"), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_pg, m.b_ple}, {m.b_pg});
|
||||
lay.op_ple_post = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_ple_post)),
|
||||
{m.b_h}, {m.b_h});
|
||||
lay.op_ple_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x, m.b_h}, {m.b_x});
|
||||
if (!lay.w_ple_post || !lay.op_ple_act || !lay.op_ple_post || !lay.op_ple_add)
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* The tap: a row copy of the layer's output (after the scalar, HF's hidden_states[l + 1])
|
||||
* into the column slice the tap owns. It is declared here, in the layer it is issued
|
||||
* after, because the buffer planner's liveness is declaration order. A tap declared once
|
||||
* after the trunk made `dflash_src` look born at its end and free to share with what every
|
||||
* layer writes, which on arch/gemma4 cost 98% of the drafts with the reply still fluent. */
|
||||
* after, because the buffer planner's liveness is declaration order. Declared after the
|
||||
* trunk, `dflash_src` would look born at its end and free to share with what every layer
|
||||
* writes: the drafts would fail while the reply stays fluent. */
|
||||
for (int t = 0; t < m.n_taps; ++t)
|
||||
if (m.tap_layer[t] == (int)l && !lay.op_tap)
|
||||
lay.op_tap = rw(b, RAD_OP(b, "cast",
|
||||
@@ -1996,7 +2364,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
ok = lay.j_am.op != 0;
|
||||
if (ok && l + 1 < m.n_main) {
|
||||
const Layer& nx = m.layers[(size_t)l + 1];
|
||||
RAD_ARCH_TRY(lay.j_ma.declare(b, g, m.b_h, m.b_x, nx.attn.w_norm, lay.mlp.w_post,
|
||||
/* With per-layer embeddings the junction closes the PLE branch instead of the
|
||||
* feed-forward (whose post-norm and add then run apart): the branch's norm,
|
||||
* its add, the scalar, the next norm and quantiser, in the reference's order. */
|
||||
RAD_ARCH_TRY(lay.j_ma.declare(b, g, m.b_h, m.b_x, nx.attn.w_norm,
|
||||
m.n_ple > 0 ? lay.w_ple_post : lay.mlp.w_post,
|
||||
lay.w_scalar, nx.attn.ln_in(), tapped));
|
||||
ok = lay.j_ma.op != 0;
|
||||
}
|
||||
@@ -2019,8 +2391,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* attention block's all-reduce and the next layer's q|k|v's (q alone, unfused; after the last
|
||||
* layer, the lm_head's) beside the feed-forward's (gemma4::kPrefetchBytes), then down_proj's
|
||||
* first 9 MB beside the attention (gemma4::kPrefetchDownBytes). Only at more than one rank,
|
||||
* where there are reductions to sit beside. RADIANCE_PREFETCH=0 declares none
|
||||
* (decl_prefetch). */
|
||||
* where there are reductions to sit beside. */
|
||||
if (g.world > 1 && rad_op_declared(b, "prefetch")) {
|
||||
for (size_t l = 0; l < m.layers.size(); ++l) {
|
||||
Layer& lay = m.layers[l];
|
||||
@@ -2046,9 +2417,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* the bits it gives the whole. The buffer the second lane reduces in place is taken out of the
|
||||
* arena's sharing, which the runtime asks of every buffer a second lane touches; it lives
|
||||
* across the whole trunk already. */
|
||||
const char* ov = std::getenv("RADIANCE_GEMMA4_OVERLAP"); /* 0: every step whole */
|
||||
const bool ov_off = ov && !std::strcmp(ov, "0");
|
||||
m.overlap = !ov_off && g.world > 1 && g.wire_exact && m.fuse && g.max_tok >= 2 * kOverlapRows;
|
||||
m.overlap = g.world > 1 && g.wire_exact && m.fuse && g.max_tok >= 2 * kOverlapRows;
|
||||
for (const Layer& lay : m.layers)
|
||||
m.overlap = m.overlap && lay.attn.op_ar && lay.mlp.op_ar;
|
||||
if (m.overlap) RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_h));
|
||||
@@ -2081,11 +2450,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* feed-forward reduction only slice A's junction and q|k|v. Per slice (A's projection,
|
||||
* prologue, attention and o_proj, then B's), each of the four reductions sits beside a whole
|
||||
* block: on 4x R9700 the exact two-shot of a 1024-row slice takes ~1.05 ms alone and ~1.4x
|
||||
* that beside any card-filling compute (a four-card microbenchmark, 2026-10-18). Slice A's
|
||||
* attention reads its context end from kv_len_trim, one a KV group. A one-sequence step only
|
||||
* (the slices' rows are then one sequence's), with the one-launch prologue and no
|
||||
* multi-component rotary. Byte-identical: every greedy reply matches the whole attention's
|
||||
* (4x R9700, two rounds, and 16 of 16 fresh starts on a 5310-token prompt); prefill +5%. */
|
||||
* that beside card-filling compute, so the reductions want whole blocks to hide behind. Slice
|
||||
* A's attention reads its context end from kv_len_trim, one a KV group. A one-sequence step
|
||||
* only (the slices' rows are then one sequence's), with the one-launch prologue and no
|
||||
* multi-component rotary. A slice's attention rows see exactly the keys they see in the whole
|
||||
* step, so the output is the whole attention's byte for byte. */
|
||||
if (m.overlap) {
|
||||
bool ok = !g.rope_mc && rad_op_declared(b, "kv_len_trim");
|
||||
for (const Layer& lay : m.layers) ok = ok && lay.attn.slicable();
|
||||
@@ -2136,7 +2505,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* the deployment speculates; otherwise its ~0.5 GB of weights stay off the card. */
|
||||
if (ctx->max_spec > 0 && has_assistant(meta)) {
|
||||
int last_s = -1, last_f = -1;
|
||||
for (int64_t l = 0; l < m.n_main; ++l) (is_global[(size_t)l] ? last_f : last_s) = (int)l;
|
||||
/* the last layer of each class that keeps a cache (a KV-shared layer reads another's) */
|
||||
for (int64_t l = 0; l < m.n_main; ++l)
|
||||
if (kv_src[(size_t)l] < 0) (is_global[(size_t)l] ? last_f : last_s) = (int)l;
|
||||
RAD_ARCH_TRY(m.head.declare(b, nm, meta, g, m.cs, m.cg, m.kv_s, m.kv_g, last_s, last_f,
|
||||
m.n_main, m.w_tok, m.b_h, m.b_logits));
|
||||
m.have_head = true;
|
||||
@@ -2196,6 +2567,15 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
g.rank, g.world, (long long)g.n_layer, (long long)n_global,
|
||||
(long long)(g.n_layer - n_global), (long long)sliding_win,
|
||||
(long long)g.n_head, (long long)g.head_dim, (long long)g.n_head, (long long)head_g);
|
||||
if (kv_shared > 0) {
|
||||
int src_s = -1, src_f = -1;
|
||||
for (int64_t l = first_shared; l < g.n_layer; ++l)
|
||||
(is_global[(size_t)l] ? src_f : src_s) = kv_src[(size_t)l];
|
||||
rad_note(b, "KV sharing: layers %lld..%lld keep no cache and read the last earlier layer of "
|
||||
"their class (sliding %d, full %d); %lld of %lld layers hold KV",
|
||||
(long long)first_shared, (long long)(g.n_layer - 1), src_s, src_f,
|
||||
(long long)first_shared, (long long)g.n_layer);
|
||||
}
|
||||
{
|
||||
int64_t n_fused = 0, n_row = 0, n_dec = 0, dec_hi = 0;
|
||||
for (const Layer& lay : m.layers) {
|
||||
@@ -2220,8 +2600,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
(long long)(2 * kOverlapRows));
|
||||
else
|
||||
rad_note(b, "prefill overlap: off (%s)",
|
||||
ov_off ? "RADIANCE_GEMMA4_OVERLAP=0"
|
||||
: !g.wire_exact ? "the lossy all-reduce wire"
|
||||
!g.wire_exact ? "the lossy all-reduce wire"
|
||||
: !m.fuse ? "the residual junctions are not fused"
|
||||
: "a step holds fewer than two slices");
|
||||
}
|
||||
@@ -2445,6 +2824,23 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, batch->n_tok));
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
if (m.n_ple > 0) {
|
||||
RAD_ISSUE(c, m.op_ple_tok, praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_ple_tok),
|
||||
brows(m.b_ple_tok, T));
|
||||
if (m.op_ple_pscat && batch->n_mm_rows > 0) {
|
||||
const int64_t nm_rows = batch->n_mm_rows;
|
||||
RAD_ISSUE_N(c, m.op_ple_pfill, nm_rows, brows(m.b_ple_pad, nm_rows));
|
||||
RAD_ISSUE_N(c, m.op_ple_pmul, nm_rows, brows(m.b_ple_pad, nm_rows), RAD_W(m.w_ple_pad),
|
||||
brows(m.b_ple_pad, nm_rows));
|
||||
RAD_ISSUE_N(c, m.op_ple_pscat, nm_rows, brows(m.b_ple_pad, nm_rows),
|
||||
praw(batch->mm_rows, RAD_I32, nm_rows), brows(m.b_ple_tok, T));
|
||||
}
|
||||
m.ln_ple_proj.step(c, m.b_x, m.b_ple, T);
|
||||
/* [T, n_layer * n_ple] read as [T * n_layer, n_ple]: one norm row per (token, layer). */
|
||||
RAD_ISSUE_N(c, m.op_ple_norm, T * m.g.n_layer, brows(m.b_ple, T), RAD_W(m.w_ple_norm),
|
||||
brows(m.b_ple, T));
|
||||
RAD_ISSUE(c, m.op_ple_add, brows(m.b_ple, T), brows(m.b_ple_tok, T), brows(m.b_ple, T));
|
||||
}
|
||||
const int64_t cut = split_at(m, T);
|
||||
if (cut > 0) trunk_overlap(c, m, batch, cut);
|
||||
else if (m.fuse) m.j0.step(c, T);
|
||||
@@ -2455,7 +2851,18 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
const bool last = li + 1 == m.layers.size();
|
||||
l.attn.step(c, batch, m.fuse, m.fuse, far);
|
||||
if (m.fuse) l.j_am.step(c, T, far);
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last, far);
|
||||
const bool ple = m.n_ple > 0;
|
||||
l.mlp.step(c, batch, m.fuse, m.fuse && !last && !ple, far);
|
||||
if (ple) {
|
||||
l.ln_pg.step(c, m.b_x, m.b_pg, T);
|
||||
RAD_ISSUE(c, l.op_ple_act, brows(m.b_pg, T),
|
||||
bcol(m.b_ple, (int64_t)li * m.n_ple, m.n_ple, T), brows(m.b_pg, T));
|
||||
l.ln_pp.step(c, m.b_pg, m.b_h, T);
|
||||
if (!(m.fuse && !last)) {
|
||||
RAD_ISSUE(c, l.op_ple_post, brows(m.b_h, T), RAD_W(l.w_ple_post), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, l.op_ple_add, brows(m.b_x, T), brows(m.b_h, T), brows(m.b_x, T));
|
||||
}
|
||||
}
|
||||
if (m.fuse && !last) {
|
||||
/* [all-reduce,] post-norm, add, layer scalar, next block's norm and quantiser: one op */
|
||||
l.j_ma.step(c, T, far);
|
||||
@@ -2521,7 +2928,7 @@ RAD_ARCH_PLUGIN(gemma4_bf16, "gemma4", "compressed-tensors", "0.1.0",
|
||||
"Gemma 4 dense (text and images), w4a8 or w8a8 from its bf16 or its CT-INT4 (QAT) "
|
||||
"release: sliding-window and proportional-RoPE global attention over a plain "
|
||||
"RMSNorm stream with GELU feed-forward, per-layer scalar scaling and soft-capped "
|
||||
"logits; Google's assistant head or z-lab's DFlash drafter")
|
||||
"logits; Google's assistant head, z-lab's DFlash drafter or a DFlash2 drafter")
|
||||
RAD_ARCH_CHAT_FORMAT(gemma4_bf16)
|
||||
RAD_ARCH_PROBE(gemma4_bf16)
|
||||
#endif
|
||||
|
||||
+64
-10
@@ -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;
|
||||
@@ -386,18 +407,50 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (!b || !meta || !ctx || ctx->is_draft || ctx->rank < 0 || ctx->rank >= MAX_RANKS)
|
||||
return RAD_E_INVAL;
|
||||
const int world = ctx->world_size ? ctx->world_size : 1;
|
||||
if (!GlmTp::world_ok(world) || meta->n_embd != 4096 || meta->n_layers != 45 ||
|
||||
meta->n_vocab != 154880 || cfg(meta, "num_nextn_predict_layers", 0) != 1 ||
|
||||
cfg(meta, "hc_mult", 0) != 4 || cfg(meta, "n_routed_experts", 0) != 288 ||
|
||||
cfg(meta, "index_topk", 0) != 2048 || ctx->max_spec > 31 ||
|
||||
(ctx->kv_dtype && ctx->kv_dtype != RAD_BF16))
|
||||
if (!GlmTp::world_ok(world)) {
|
||||
fprintf(stderr, "radiance: glm5next: --tp %d; the head, KDA channel and expert splits of "
|
||||
"this plugin are built for 1, 2, 4 or 8 ranks\n", world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The graph is written for the released GLM-5.3-Flash and reads none of these from the
|
||||
* checkpoint, so a checkpoint that differs in any of them is refused by name. */
|
||||
const struct {
|
||||
const char* what;
|
||||
int64_t got, want;
|
||||
} shape[] = { { "hidden_size", meta->n_embd, 4096 },
|
||||
{ "num_hidden_layers", meta->n_layers, 45 },
|
||||
{ "vocab_size", meta->n_vocab, 154880 },
|
||||
{ "num_nextn_predict_layers", cfg(meta, "num_nextn_predict_layers", 0), 1 },
|
||||
{ "hc_mult", cfg(meta, "hc_mult", 0), 4 },
|
||||
{ "n_routed_experts", cfg(meta, "n_routed_experts", 0), 288 },
|
||||
{ "index_topk", cfg(meta, "index_topk", 0), 2048 } };
|
||||
for (const auto& s : shape)
|
||||
if (s.got != s.want) {
|
||||
fprintf(stderr, "radiance: glm5next: the checkpoint's %s is %lld; this plugin serves "
|
||||
"the GLM-5.3-Flash geometry, where it is %lld\n",
|
||||
s.what, (long long)s.got, (long long)s.want);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->max_spec > 31) {
|
||||
fprintf(stderr, "radiance: glm5next: --num-speculative-tokens %d; the KDA verify pass "
|
||||
"takes at most 32 rows a sequence, so the MTP depth is at most 31\n",
|
||||
ctx->max_spec);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (ctx->kv_dtype && ctx->kv_dtype != RAD_BF16) {
|
||||
fprintf(stderr, "radiance: glm5next: --kv-cache-dtype %s; this plugin keeps its latent "
|
||||
"attention, index tail and KDA caches in bf16 and has no fp8 cache, so "
|
||||
"run it with --kv-cache-dtype bf16\n",
|
||||
ctx->kv_dtype == RAD_F8E4M3 ? "fp8" : rad_dtype_name(ctx->kv_dtype));
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
auto& slot = ctx->shape_probe ? probe_model : models[ctx->rank];
|
||||
slot = std::make_unique<Model>();
|
||||
auto& m = *slot;
|
||||
auto& g = m.g;
|
||||
m.nm = Names(ctx->scope);
|
||||
auto& nm = m.nm;
|
||||
m.form = ctx->tp_attn_rows ? GlmMla::Form::rows : GlmMla::Form::heads;
|
||||
RAD_ARCH_TRY(geometry(g, meta, ctx, world));
|
||||
RAD_ARCH_TRY(stream_buffers(b, m));
|
||||
RAD_ARCH_TRY(kda_buffers(b, m));
|
||||
@@ -547,6 +600,7 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (k > 0) out->enc_merge = k * k;
|
||||
}
|
||||
out->shape_probe_ok = 1;
|
||||
out->tp_attn_rows_ok = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
} // namespace glm5next
|
||||
|
||||
+11
-5
@@ -139,6 +139,7 @@ struct Model {
|
||||
std::vector<TeLayer> te;
|
||||
rad_buf b_taps = 0; /* [T * 12, n_embd]: token t's tap i at row 12 t + i */
|
||||
std::string tap_mul[kNTaps]; /* chan_affine's `mul` for each tap's rebalance gain */
|
||||
std::string tap_add; /* chan_affine's `add`: zeros */
|
||||
|
||||
/* ---- the text fusion: the layer-wise blocks over the taps themselves, the refiner blocks
|
||||
* over the mixed rows `b_ft` */
|
||||
@@ -383,7 +384,12 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
* scaled copy goes through te.h2, free between a layer's add and the next layer's projections,
|
||||
* so the residual stream itself is never scaled. */
|
||||
enum { kGainCh = 64 };
|
||||
if (g.n_embd % kGainCh) return RAD_E_INVAL;
|
||||
if (g.n_embd % kGainCh) {
|
||||
fprintf(stderr, "radiance: krea2: the text encoder's hidden size %lld is not a multiple of "
|
||||
"%d, the rows the rebalance gains are applied in\n", (long long)g.n_embd,
|
||||
(int)kGainCh);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
for (int t = 0; t < kNTaps; ++t) {
|
||||
char v[32];
|
||||
std::snprintf(v, sizeof v, "%.9g", kRebalance[t]);
|
||||
@@ -393,9 +399,8 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
m.tap_mul[t] += v;
|
||||
}
|
||||
}
|
||||
static std::string zeros64;
|
||||
if (zeros64.empty())
|
||||
for (int k = 0; k < kGainCh; ++k) zeros64 += k ? " 0" : "0";
|
||||
m.tap_add.clear();
|
||||
for (int k = 0; k < kGainCh; ++k) m.tap_add += k ? " 0" : "0";
|
||||
|
||||
/* Layers up to the last tap only. */
|
||||
const int n_run = kTaps[kNTaps - 1];
|
||||
@@ -480,7 +485,7 @@ static int declare_te(RadBuilder* b, const RadModelMeta* meta, Model& m) {
|
||||
L.op_gain = rw(b, RAD_OP(b, "chan_affine",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, kTeRows), RAD_INT("n", kGainCh),
|
||||
RAD_STR("mul", m.tap_mul[L.tap].c_str()),
|
||||
RAD_STR("add", zeros64.c_str()),
|
||||
RAD_STR("add", m.tap_add.c_str()),
|
||||
RAD_STR("mode", "fma"), RAD_STR("dtype", "bf16"),
|
||||
RAD_INT("round", 0)),
|
||||
RAD_NOWEIGHTS),
|
||||
@@ -1181,6 +1186,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
d.cond_rows = kCondRows;
|
||||
d.rope_hw_scale = 1.0;
|
||||
d.rope_text_l = 0;
|
||||
d.cond_opts = RAD_GEN_COND_REBALANCE;
|
||||
RAD_ARCH_TRY(rad_declare_generator(b, &d));
|
||||
}
|
||||
rad_note(b, "rank %d/%d: Krea 2%s -- text encoder %d of %lld layers, text fusion %zu + %zu "
|
||||
|
||||
@@ -193,10 +193,28 @@ struct Model {
|
||||
MediaRows mrows{};
|
||||
|
||||
std::vector<Layer> layers;
|
||||
|
||||
/* The pipelined prefill (step_pipelined): on where declare allowed it; the bounds buffer it
|
||||
* cuts a step by, rewritten by every pipelined step from the pinned table `pipe_tbl` of
|
||||
* {0, pipe_rows(T), T} for every T, made once; and whether rank 0 has said it pipelines. */
|
||||
bool pipe_on = false;
|
||||
rad_buf b_pipe_cu = 0;
|
||||
int32_t* pipe_tbl = nullptr;
|
||||
bool pipe_tbl_tried = false;
|
||||
bool pipe_noted = false;
|
||||
bool pipe_serial_noted = false;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* The narrowest step the pipelined prefill takes, and its first piece: half the step rounded up
|
||||
* to 64 rows, so both pieces sit in one bucket band (core/runtime/ctx.h) and the second is never
|
||||
* wider than the first. */
|
||||
static const int64_t kPipeMinRows = 1024;
|
||||
static int64_t pipe_rows(int64_t T) { return ((T + 1) / 2 + 63) / 64 * 64; }
|
||||
#endif
|
||||
|
||||
/* Checks the container's statement of its format, since every mismatch is silent: a
|
||||
* `weight_block_size` of [64,64] against kernels that shift by 7 reads the right bytes with the
|
||||
* wrong gain, and e5m2 decoded as e4m3 gives merely implausible numbers. A container that states
|
||||
@@ -264,6 +282,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
RAD_ARCH_TRY(drafter_geom(dg, m.g, meta, "DFlash2"));
|
||||
|
||||
Dflash2::Config dc{};
|
||||
dc.short_block = 1; /* rad_drafter_short_block below */
|
||||
dc.n_taps = m.n_taps;
|
||||
dc.block = ctx->max_spec + 1;
|
||||
dc.taps = rad_meta_geti(meta, "draft.dflash_config.conv_kernel_size", 2);
|
||||
@@ -414,6 +433,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
|
||||
return RAD_E_FORMAT;
|
||||
}
|
||||
RAD_ARCH_TRY(rad_declare_drafter(b, &drf));
|
||||
if (m.df.block_lo > 0) RAD_ARCH_TRY(rad_drafter_short_block(b, m.df.block_lo));
|
||||
|
||||
rad_note(b, "DFlash2 drafter: %lld layers at absolute %d..%d, %lld heads / %lld kv x %lld, "
|
||||
"ffn %lld, %s attention with a %lld-token window, %d trunk tap(s); one forward "
|
||||
@@ -430,6 +450,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
if (m.pipe_tbl) rad_dev_free(m.pipe_tbl, RAD_MEM_HOST_PINNED);
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(check_format(meta));
|
||||
@@ -583,17 +604,17 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
"and head instead of %lld", kvq_name, kvq == RAD_KVQ_V4 ? "E4M3" : "int6",
|
||||
(long long)(g.head_dim * row16 / 16), (long long)(2 * g.head_dim));
|
||||
|
||||
/* The SSM state cache is f32.
|
||||
/* The SSM state cache is f32, or f16 under --state-cache-dtype f16 (RadBuildCtx::state_dtype).
|
||||
*
|
||||
* State reads and writes dominate the two GDN kernels: one [128,128] state is 64 KiB at f32,
|
||||
* and a speculative step writes one per candidate token per head, since the surviving
|
||||
* candidate is unknown until after the layer. At depth 7 that is hundreds of MB per rank per
|
||||
* step; f16 would halve it. libr4d compiles both widths (`SDT`) and the f16 round-trip error is
|
||||
* ~5e-4 relative (elements are O(0.1)); vLLM's `--mamba-ssm-cache-dtype` is commonly float16.
|
||||
* It stays f32 because f16 changes the generated text. */
|
||||
* and a step reads a sequence's state and writes it back (under the anchor form once, whatever
|
||||
* the draft depth). libr4d compiles both widths (`SDT`, from the cache's dtype); the f16
|
||||
* round trip is ~5e-4 relative (elements are O(0.1)). f16 halves the state pool, its host
|
||||
* checkpoints and the state traffic, and changes the generated text, so f32 is the default. */
|
||||
RadKVGroupDecl sd{};
|
||||
sd.kind = RAD_KV_LINEAR;
|
||||
sd.dtype = RAD_F32;
|
||||
sd.dtype = ctx->state_dtype == RAD_F16 ? RAD_F16 : RAD_F32;
|
||||
if (sd.dtype == RAD_F16) rad_note(b, "GDN state cache f16 (--state-cache-dtype f16)");
|
||||
sd.n_head_kv = gc.n_head_v;
|
||||
sd.state_dim[0] = gc.head_v;
|
||||
sd.state_dim[1] = gc.head_k;
|
||||
@@ -717,6 +738,14 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
}
|
||||
/* GPTQ calibration run (MoeFP8::Config::calib), on when the output directory is set. */
|
||||
mc.calib = calib_dir() != nullptr ? 1 : 0;
|
||||
/* Each rank holds a width slice of every expert (n_ff is per rank), so its down
|
||||
* projection's Hessian would be of the slice, without the cross terms between slices. */
|
||||
if (mc.calib && g.world > 1) {
|
||||
fprintf(stderr, "radiance: qwen35moe: calibration (RADIANCE_CALIB_DIR) runs at one "
|
||||
"rank; at %d ranks each holds a slice of every expert's width, and "
|
||||
"the down projection's Hessian would be of the slice\n", g.world);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The experts' stored format, read from layer 0's first expert as qwen4exp does, so a
|
||||
* container with four-bit experts is served in that format. */
|
||||
{
|
||||
@@ -846,7 +875,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
if (m.media) RAD_ARCH_TRY(m.mrows.declare(b, g.max_tok, g.n_embd, m.b_x));
|
||||
/* Always exact, not g.wire_exact: this all_reduce sums disjoint rows (each token's embedding
|
||||
* comes from one rank, the others contribute zero), so a lossy wire would only add error.
|
||||
* min_bytes stays 0 for the same reason. */
|
||||
* min_bytes stays 0 for the same reason.
|
||||
*
|
||||
* The second lane's window opens here and closes after the final norm (rad_lane1_window_begin):
|
||||
* the embedding's reduction and the pipelined prefill's boundaries are declared inside it, so
|
||||
* the concurrent buffers stay live only there and the drafter and the heads can share their
|
||||
* bytes. */
|
||||
RAD_ARCH_TRY(rad_lane1_window_begin(b));
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
@@ -854,6 +889,35 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
#if !QWEN35_MOE
|
||||
/* The pipelined prefill (step_pipelined), at two ranks wherever a step can be wide enough.
|
||||
* Its second lane needs a narrow `overlap` all-reduce beside the GEMMs; two ranks is the only
|
||||
* rank count where the step has been timed against the serial one, so elsewhere prefill stays
|
||||
* serial. The second lane touches the residual stream, the normed input in both forms and the
|
||||
* bounds, so those leave the sharing pool (Ctx::lane1_; the drafter taps are copied on the
|
||||
* first lane, pipe_taps); the bounds also because no declared op reads them, which would leave
|
||||
* a transient dead before the kernels that take them raw.
|
||||
*
|
||||
* Not on a trunk whose norms write rotated int8 codes (qwen35_w8a8 where libr4d serves the
|
||||
* `_had_quant_i8g` forms, a_h.q8_fed): the boundary norms on the second lane
|
||||
* (NormQuantFP8::step_plain) issue the E4M3 pair only, so such a trunk prefills serially. */
|
||||
if (m.a_h.q8_fed) {
|
||||
if (g.world == 2 && g.max_tok >= kPipeMinRows && ctx->rank == 0)
|
||||
fprintf(stderr, "radiance: qwen35: the pipelined prefill stays off on this trunk: its norms "
|
||||
"write rotated int8 codes, which the pipeline's boundary norms do not\n");
|
||||
} else {
|
||||
m.pipe_on = g.world == 2 && g.max_tok >= kPipeMinRows;
|
||||
}
|
||||
if (m.pipe_on) {
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.x));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.q));
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.a_h.s));
|
||||
m.b_pipe_cu = decl_b(b, nm.f("pipe_cu"), RAD_I32, {4});
|
||||
RAD_ARCH_TRY(rad_buf_concurrent(b, m.b_pipe_cu));
|
||||
}
|
||||
#endif
|
||||
|
||||
/* ---- the layers. */
|
||||
/* The rope table's fill, declared before the layers that read it. If it does not resolve,
|
||||
* `aw.cos_sin` is cleared and every attention block uses its unfused norm + rope pair. Its band
|
||||
@@ -896,6 +960,13 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
for (int64_t l = 0; l < m.n_main; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.full = is_full_attention(l, interval) ? 1 : 0;
|
||||
#if !QWEN35_MOE
|
||||
/* The pipelined prefill runs every block's all-reduce beside the other piece's work, so
|
||||
* each declares its collective a second time at `overlap` 1, a launch that leaves the CUs
|
||||
* to that work (the lane rows of libr4d/r4d_rows.cpp); the fused all-reduce and norm
|
||||
* would hold the card while it waits on the link. */
|
||||
lay.attn.ar_overlap = lay.gdn.ar_overlap = lay.mlp.ar_overlap = m.pipe_on ? 1 : 0;
|
||||
#endif
|
||||
|
||||
const LayerFold f = layer_fold(g, l, m.n_main, m.tap_layer, m.n_taps, m.op_embed_ar != 0);
|
||||
|
||||
@@ -960,6 +1031,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", final_wadd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out_norm)),
|
||||
{m.b_x}, {m.a_h.x});
|
||||
RAD_ARCH_TRY(rad_lane1_window_end(b));
|
||||
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
@@ -1130,6 +1202,235 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
#if !QWEN35_MOE
|
||||
/* ============================== A prefill step in two pieces ==============================
|
||||
*
|
||||
* At two ranks every layer of a prefill chunk makes two all-reduces, each folded into the next
|
||||
* block's norm (layer_fold) and each in a hard chain on one stream: block -> all-reduce + norm ->
|
||||
* block. On a 2048-token chunk they are about a fifth of the step, nearly all of it the link, with
|
||||
* nothing beside them.
|
||||
*
|
||||
* A step of one prefill sequence of at least kPipeMinRows tokens is cut into two pieces of about
|
||||
* half (pipe_rows), each the chunk a narrower batch makes. Every block runs a piece at a time on
|
||||
* the first lane, and the work between two blocks runs a piece at a time on the second: the
|
||||
* block's all-reduce at `overlap` 1 (a narrow launch that leaves the CUs to the compute beside it;
|
||||
* the fused all-reduce and norm would hold its blocks on the card while it waits on the link and
|
||||
* slow the GEMM beside it by a third), then the next block's plain norm, and after a feed-forward
|
||||
* that keeps its add, the add and the final norm (the drafter taps go on the first lane, pipe_taps).
|
||||
*
|
||||
* mixer the delta net and the dense attention run whole a piece at a time and hand the
|
||||
* first piece off behind its out projection (ArPieces), so its boundary runs beside
|
||||
* the second piece's mixer;
|
||||
* ffn its first piece runs beside the mixer's second boundary, its second beside its own
|
||||
* first boundary; the next mixer's first piece runs beside its second.
|
||||
*
|
||||
* A piece computes the bytes the narrower chunk does: every op is per row, both pieces sit in the
|
||||
* band of a whole step (pipe_rows), the all-reduce reduces within a row, the delta net carries its
|
||||
* state through the cache as between two chunks, and each attention piece sees the cache up to its
|
||||
* own end. The narrow all-reduce and the plain norm write the fused op's bytes, so a pipelined
|
||||
* step is bit for bit the serial one.
|
||||
*
|
||||
* The second lane's requirements (Ctx::lane1_) hold: every collective of the step is on it, the
|
||||
* embedding's included; none carries a device-wide arrival counter (the all-reduce's sequence
|
||||
* counters order its own launches, which one lane keeps in order); and the buffers it touches left
|
||||
* the sharing pool at declare (the drafter taps it does not touch: pipe_taps). */
|
||||
|
||||
template <class F>
|
||||
static void pipe_on1(RadCtx* c, const F& issue) {
|
||||
rad_lane(c, 1);
|
||||
rad_lane_join(c, 0, 1);
|
||||
issue();
|
||||
rad_lane(c, 0);
|
||||
}
|
||||
/* Lane 0 waits for everything issued on lane 1 so far. */
|
||||
static void pipe_wait1(RadCtx* c) { rad_lane_join(c, 1, 0); }
|
||||
|
||||
/* The work after block `s` (2l the mixer of layer l, 2l + 1 its feed-forward) for rows
|
||||
* [r0, r0 + n). */
|
||||
static void pipe_boundary(RadCtx* c, const Model& m, int64_t T, int64_t s, int64_t r0, int64_t n) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t li = s / 2;
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
if (s % 2 == 0) {
|
||||
if (l.full) l.attn.issue_ar(c, r0, n);
|
||||
else l.gdn.issue_ar(c, r0, n);
|
||||
l.mlp.nq_h.step_plain(c, T, r0, n);
|
||||
return;
|
||||
}
|
||||
l.mlp.issue_ar(c, r0, n);
|
||||
if (l.mlp.op_add)
|
||||
RAD_ISSUE_N(c, l.mlp.op_add, n, brow_slice(m.b_x, r0, n, g.n_embd),
|
||||
brow_slice(m.a_h.x, r0, n, g.n_embd), brow_slice(m.b_x, r0, n, g.n_embd));
|
||||
if (li + 1 < (int64_t)m.layers.size()) {
|
||||
const Layer& nx = m.layers[(size_t)li + 1];
|
||||
(nx.full ? nx.attn.nq_h : nx.gdn.nq_h).step_plain(c, T, r0, n);
|
||||
} else {
|
||||
RAD_ISSUE_N(c, m.op_final_norm, n, brow_slice(m.b_x, r0, n, g.n_embd), RAD_W(m.w_out_norm),
|
||||
brow_slice(m.a_h.x, r0, n, g.n_embd));
|
||||
}
|
||||
}
|
||||
|
||||
/* Layer `li`'s drafter taps of rows [r0, r0 + n), on lane 0. Issued once lane 0 has waited for that
|
||||
* piece's feed-forward boundary (its add is the last write to those rows of x before the next
|
||||
* block's boundary, which lane 1 starts only behind lane 0's next issues), so the taps buffer is
|
||||
* never touched from lane 1 and stays in the sharing pool: rad_buf_concurrent would hold its
|
||||
* [max_tok, n_taps * n_embd] for the whole program. */
|
||||
static void pipe_taps(RadCtx* c, const Model& m, int64_t li, int64_t r0, int64_t n) {
|
||||
for (int t = 0; t < m.n_taps; ++t) {
|
||||
if (m.tap_layer[t] != (int)li) continue;
|
||||
RAD_ISSUE_N(c, m.op_tap, n, brow_slice(m.b_x, r0, n, m.g.n_embd),
|
||||
bcol_at(m.b_dfsrc, r0, (int64_t)m.n_taps * m.g.n_embd, (int64_t)t * m.g.n_embd,
|
||||
m.g.n_embd, n));
|
||||
}
|
||||
}
|
||||
|
||||
/* A mixer's first piece is done (ArPieces): lane 0 takes the previous block's second boundary
|
||||
* before the second piece (and the previous layer's second-piece taps behind it), and lane 1 this
|
||||
* block's first behind it. */
|
||||
struct PipeHand {
|
||||
RadCtx* c = nullptr;
|
||||
const Model* m = nullptr;
|
||||
int64_t T = 0, s = 0;
|
||||
};
|
||||
static void pipe_hand(void* u, int64_t r0, int64_t n) {
|
||||
const PipeHand& h = *(const PipeHand*)u;
|
||||
pipe_wait1(h.c);
|
||||
if (h.s >= 2) {
|
||||
const int64_t R = pipe_rows(h.T);
|
||||
pipe_taps(h.c, *h.m, h.s / 2 - 1, R, h.T - R);
|
||||
}
|
||||
pipe_on1(h.c, [&] { pipe_boundary(h.c, *h.m, h.T, h.s, r0, n); });
|
||||
}
|
||||
|
||||
/* The bounds of this step's pieces on the card, {0, pipe_rows(T), T}, if the step is pipelined;
|
||||
* null for a serial step, and null with `failed` set when the step has been failed. Copied on the
|
||||
* step's stream ahead of every layer from the pinned table, whose rows never change, so a captured
|
||||
* step replays the same copy. */
|
||||
static const int32_t* pipe_ready(RadCtx* c, const RadBatch* batch, Model& m, bool* failed) {
|
||||
const int64_t T = batch->n_tok;
|
||||
if (!m.pipe_on || !m.b_pipe_cu || T < kPipeMinRows || T > m.g.max_tok ||
|
||||
batch->phase != RAD_PHASE_PREFILL)
|
||||
return nullptr;
|
||||
/* A prefill step wide enough that runs serially says why, once, so a deployment that never
|
||||
* pipelines does not look like one that gains nothing from it. */
|
||||
auto serial = [&](const char* why) -> const int32_t* {
|
||||
if (!m.pipe_serial_noted && m.g.rank == 0)
|
||||
fprintf(stderr, "radiance: qwen35: a %lld-row prefill step runs serially: %s\n",
|
||||
(long long)T, why);
|
||||
m.pipe_serial_noted = true;
|
||||
return nullptr;
|
||||
};
|
||||
if (batch->n_seq != 1 || batch->n_seq_decode != 0) return serial("more than one sequence");
|
||||
if (!batch->positions) return serial("no positions");
|
||||
if (rope_mixed(batch) || batch->n_mm_rows > 0) return serial("media rows in the step");
|
||||
if (dbg_resid_on()) return serial("residual debugging is on");
|
||||
int32_t* d = (int32_t*)rad_buf_ptr(c, m.b_pipe_cu);
|
||||
if (!d) {
|
||||
/* Not a rank-local fallback to the serial step: the other rank would pipeline, and the two
|
||||
* would issue different collectives. Fail the step, as gemma3 does. */
|
||||
rad_step_fail(c, "qwen35: the pipelined prefill's bounds have no storage");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
const int64_t R = pipe_rows(T);
|
||||
ArPieces pc{};
|
||||
pc.rows = R; pc.done = pipe_hand; pc.cu = d; pc.in_ready = true;
|
||||
for (const Layer& l : m.layers) {
|
||||
if (!(l.full ? l.attn.takes_pieces(batch, &pc) : l.gdn.takes_pieces(batch, &pc)))
|
||||
return serial(l.full ? "an attention block cannot run in pieces"
|
||||
: "a delta-net block cannot run in pieces");
|
||||
/* Every boundary issues its block's all-reduce itself, narrow, then the plain norm. */
|
||||
if (!(l.full ? l.attn.op_ar_ov : l.gdn.op_ar_ov) || !l.mlp.op_ar_ov)
|
||||
return serial("a block declares no overlap all-reduce");
|
||||
}
|
||||
if (!m.pipe_tbl_tried) {
|
||||
m.pipe_tbl_tried = true;
|
||||
const int64_t n = m.g.max_tok + 1;
|
||||
m.pipe_tbl = (int32_t*)rad_dev_alloc(3 * n * (int64_t)sizeof(int32_t), RAD_MEM_HOST_PINNED);
|
||||
if (m.pipe_tbl) {
|
||||
for (int64_t t = 0; t < n; ++t) {
|
||||
m.pipe_tbl[3 * t] = 0;
|
||||
m.pipe_tbl[3 * t + 1] = (int32_t)pipe_rows(t);
|
||||
m.pipe_tbl[3 * t + 2] = (int32_t)t;
|
||||
}
|
||||
}
|
||||
}
|
||||
/* Everything above depends only on the batch and the build, the same on every rank; what
|
||||
* follows is this rank's own, and falling back to the serial step here would leave the other
|
||||
* rank pipelining, the two issuing different collectives on the shared all-reduce instance
|
||||
* (a hang or a wrong sum). So it fails the step. */
|
||||
if (!m.pipe_tbl ||
|
||||
rad_memcpy_async(d, m.pipe_tbl + 3 * T, 3 * (int64_t)sizeof(int32_t), rad_stream(c)) !=
|
||||
RAD_OK) {
|
||||
rad_step_fail(c, "qwen35: the pipelined prefill's piece bounds could not be put on the card "
|
||||
"(no pinned host memory, or the copy failed)");
|
||||
*failed = true;
|
||||
return nullptr;
|
||||
}
|
||||
return d;
|
||||
}
|
||||
|
||||
static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int32_t* pcu) {
|
||||
const Geom& g = m.g;
|
||||
const int64_t T = batch->n_tok, R = pipe_rows(T);
|
||||
const int64_t L = (int64_t)m.layers.size();
|
||||
if (!m.pipe_noted) {
|
||||
m.pipe_noted = true;
|
||||
if (g.rank == 0)
|
||||
fprintf(stderr, "radiance: qwen35: prefill steps of one sequence from %lld rows are "
|
||||
"pipelined: two pieces, block boundaries on the second lane\n",
|
||||
(long long)kPipeMinRows);
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_embed,
|
||||
praw(batch->token_ids, RAD_I32, T), RAD_W(m.w_tok), brows(m.b_x, T));
|
||||
/* The embedding's reduction and layer 0's norm over the whole step, on lane 1 with every
|
||||
* other collective (the norm takes the reduction where the wire is exact). */
|
||||
pipe_on1(c, [&] {
|
||||
if (m.op_embed_ar && !ar_wire_is_exact(g, T))
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, T * g.n_embd, brows(m.b_x, T), RAD_NONE);
|
||||
if (L > 0) (m.layers[0].full ? m.layers[0].attn.nq_h : m.layers[0].gdn.nq_h).step(c, T);
|
||||
});
|
||||
pipe_wait1(c);
|
||||
if (m.op_rope_cs && T <= qk_fuse_rows(g) && !rope_mixed(batch))
|
||||
RAD_ISSUE_N(c, m.op_rope_cs, T, rope_pos1(batch, T), RAD_B(m.b_rope_cs));
|
||||
|
||||
for (int64_t li = 0; li < L; ++li) {
|
||||
const Layer& l = m.layers[(size_t)li];
|
||||
PipeHand h{c, &m, T, 2 * li};
|
||||
ArPieces pc{};
|
||||
pc.rows = R; pc.done = pipe_hand; pc.u = &h; pc.cu = pcu; pc.in_ready = true;
|
||||
if (l.full) l.attn.step(c, batch, false, &pc);
|
||||
else l.gdn.step(c, batch, false, &pc);
|
||||
if (pc.handed != 1) {
|
||||
rad_step_fail(c, "qwen35: a mixer did not run its two pieces in a pipelined prefill "
|
||||
"step (pipe_ready and the block's takes_pieces disagree)");
|
||||
return;
|
||||
}
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li, R, T - R); });
|
||||
l.mlp.body(c, T, 0, R);
|
||||
pipe_wait1(c);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li + 1, 0, R); });
|
||||
l.mlp.body(c, T, R, T - R);
|
||||
pipe_wait1(c);
|
||||
pipe_taps(c, m, li, 0, R);
|
||||
pipe_on1(c, [&] { pipe_boundary(c, m, T, 2 * li + 1, R, T - R); });
|
||||
}
|
||||
pipe_wait1(c);
|
||||
if (L > 0) pipe_taps(c, m, L - 1, R, T - R);
|
||||
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
|
||||
brows(m.a_h.x, T), praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out,
|
||||
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
|
||||
brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
#endif
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
|
||||
@@ -1168,6 +1469,15 @@ static void step(RadCtx* c, const RadBatch* batch) {
|
||||
return;
|
||||
}
|
||||
|
||||
#if !QWEN35_MOE
|
||||
bool pipe_failed = false;
|
||||
if (const int32_t* pcu = pipe_ready(c, batch, m, &pipe_failed)) {
|
||||
step_pipelined(c, batch, m, pcu);
|
||||
return;
|
||||
}
|
||||
if (pipe_failed) return;
|
||||
#endif
|
||||
|
||||
RAD_ISSUE(c, m.op_embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
@@ -1242,6 +1552,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (hd == 256 && nkv > 0 && meta->n_head == 6 * nkv)
|
||||
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
|
||||
}
|
||||
/* The delta-net state cache is declared at RadBuildCtx::state_dtype. */
|
||||
out->state_f16_ok = 1;
|
||||
const char* da = rad_meta_gets(meta, "draft.architectures", "");
|
||||
if (da && std::strstr(da, "DFlash2")) {
|
||||
const long long bs = rad_meta_geti(meta, "draft.dflash_config.block_size", 8);
|
||||
|
||||
@@ -9,7 +9,7 @@
|
||||
* input_audio part. The reference is transformers' modeling_qwen3_asr (5.18) with its
|
||||
* Qwen3ASRFeatureExtractor, which core/mm reproduces (AudioFamily::Qwen3ASR).
|
||||
*
|
||||
* ============================== THE SHAPE, AT 1.7B ==============================
|
||||
* ============================== The shape, at 1.7B ==============================
|
||||
*
|
||||
* audio encoder: log-mel [frames, 128], convolved one second (100 frames) at a time: three
|
||||
* Conv2d 3x3 / stride 2 / pad 1 over [mel, time] with 480 channels and exact gelu, 128 mel ->
|
||||
@@ -23,7 +23,7 @@
|
||||
* q/k RMS norms, NeoX rope over the whole head at theta 1e6, SwiGLU 6144, RMS eps 1e-6,
|
||||
* vocab 151936, the lm_head tied to the embedding.
|
||||
*
|
||||
* ============================== WHAT IS EASY TO GET WRONG ==============================
|
||||
* ============================== What is easy to get wrong ==============================
|
||||
*
|
||||
* Each second is convolved on its own. The core lays a clip out so one convolution over it does
|
||||
* that (core/mm/processor.h, AudioFamily::Qwen3ASR): a whole second is staged as 104 frames whose
|
||||
|
||||
@@ -174,6 +174,10 @@ struct Model {
|
||||
rad_buf b_mtp_hin = 0, b_mtp_hw = 0, b_mtp_e = 0, b_mtp_hout = 0;
|
||||
rad_buf b_mtp_dq = 0, b_mtp_ds = 0, b_mtp_dsum = 0;
|
||||
rad_buf b_mtp_dlog = 0, b_mtp_didx = 0, b_mtp_dval = 0;
|
||||
/* --draft-coupling: [max_seqs] draws staged before the serial passes and [max_spec,
|
||||
* max_seqs] states read back after them. PERSIST: the engine writes them from the host and the
|
||||
* head writes the states on the card, across a step boundary. */
|
||||
rad_buf b_mtp_couple_draws = 0, b_mtp_couple_state = 0;
|
||||
rad_buf b_mtp_dpair = 0, b_mtp_dgath = 0;
|
||||
|
||||
HcEnter enter;
|
||||
@@ -1261,6 +1265,30 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
* vocab-parallel all-gather a 16-byte row (rad_block_mtp_hc.h, kDraftTopR). */
|
||||
m.b_mtp_didx = decl_b(b, nm.f("mtp_didx"), RAD_I32, {g.max_logit_rows, kDraftTopR});
|
||||
m.b_mtp_dval = decl_b(b, nm.f("mtp_dval"), RAD_F32, {g.max_logit_rows, kDraftTopR});
|
||||
|
||||
/* --draft-coupling (RadBuildCtx::draft_coupling). Q is the law of the 2-bit candidate
|
||||
* head's reranked top-8; a plain bf16 head leaves one candidate and nothing to couple
|
||||
* over. The engine checks the drafter shape (a linear serial chain). */
|
||||
if (ctx->draft_coupling) {
|
||||
if (!m.b_mtp_didx || g.max_spec < 1 || g.max_spec > RAD_MTP_COUPLE_MAX_ROUNDS) {
|
||||
rad_note(b, "--draft-coupling on requires the 2-bit candidate head's reranked "
|
||||
"top8 and max_spec 1..%d",
|
||||
RAD_MTP_COUPLE_MAX_ROUNDS);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
m.b_mtp_couple_draws = decl_b(b, nm.f("mtp_couple_draws"), RAD_U32,
|
||||
{g.max_seqs, RAD_MTP_COUPLE_DRAW_WORDS},
|
||||
RAD_BUF_PERSIST);
|
||||
m.b_mtp_couple_state = decl_b(b, nm.f("mtp_couple_state"), RAD_U32,
|
||||
{g.max_spec, g.max_seqs,
|
||||
RAD_MTP_COUPLE_STATE_WORDS},
|
||||
RAD_BUF_PERSIST);
|
||||
if (!m.b_mtp_couple_draws || !m.b_mtp_couple_state) return RAD_E_INVAL;
|
||||
rad_note(b, "MTP coupled: the head samples x~Q from its reranked top8 each round "
|
||||
"(FP64), and the sampler couples the target's own draw to it; %lld "
|
||||
"round(s), fixed-seed tokens are NOT preserved",
|
||||
(long long)g.max_spec);
|
||||
}
|
||||
}
|
||||
|
||||
MtpHcBlock::Wire tw{};
|
||||
@@ -1270,6 +1298,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
tw.dq = m.b_mtp_dq; tw.ds = m.b_mtp_ds; tw.dsum = m.b_mtp_dsum;
|
||||
tw.dlog = m.b_mtp_dlog; tw.didx = m.b_mtp_didx; tw.dval = m.b_mtp_dval;
|
||||
tw.dpair = m.b_mtp_dpair; tw.dgath = m.b_mtp_dgath;
|
||||
tw.couple_draws = m.b_mtp_couple_draws; tw.couple_state = m.b_mtp_couple_state;
|
||||
/* The head reuses the trunk's working buffers, all dead by the time a draft round runs (a
|
||||
* second set would be 150 MiB). Only the wide stream and the carry are its own, since
|
||||
* they must survive the round that produced them. */
|
||||
@@ -1555,7 +1584,7 @@ static void step_pipelined(RadCtx* c, const RadBatch* batch, Model& m, const int
|
||||
if (p == K - 1) wait1();
|
||||
l.hc_ffn.write(c, T, r0(p), rn(p));
|
||||
/* The projection of this piece, before the next layer reads it. */
|
||||
l.proj.step(c, r0(p), rn(p));
|
||||
l.proj.step(c, batch, r0(p), rn(p));
|
||||
if (nx && !ple_next) nx->hc_mix.read(c, T, r0(p), rn(p));
|
||||
}
|
||||
if (ple_next) {
|
||||
@@ -1600,7 +1629,7 @@ static void step_serial(RadCtx* c, const RadBatch* batch, Model& m, const int32_
|
||||
l.mlp.step(c, batch);
|
||||
l.hc_ffn.write(c, T, 0, T);
|
||||
/* The request's control vector, on the stream the write just finished. */
|
||||
l.proj.step(c, 0, T);
|
||||
l.proj.step(c, batch, 0, T);
|
||||
dbg_resid(c, (int)li, "ffn", g.n_embd, m.b_h, m.a_x.x);
|
||||
}
|
||||
}
|
||||
@@ -1677,6 +1706,8 @@ static int probe(const RadModelMeta* meta, RadArchProbe* out) {
|
||||
if (hd == 256 && nkv > 0 && meta->n_head == 12 * nkv)
|
||||
out->kv_quant_ok = (1 << RAD_KVQ_V4) | (1 << RAD_KVQ_K6V4);
|
||||
}
|
||||
/* The gated residual applies a control vector after every block's write (HcProject). */
|
||||
out->control_vector_ok = 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
# A plugin like any other: built here inside radiance's tree, or on its own against an installed
|
||||
# radiance (`cmake -S arch/unlimitedocr_bf16 -B build -DCMAKE_PREFIX_PATH=<radiance prefix>`) -- the
|
||||
# same rad_add_plugin either way (cmake/RadAddPlugin.cmake).
|
||||
if(NOT COMMAND rad_add_plugin)
|
||||
cmake_minimum_required(VERSION 3.21)
|
||||
project(unlimitedocr_bf16 LANGUAGES CXX)
|
||||
find_package(radiance REQUIRED)
|
||||
rad_plugin_defaults()
|
||||
endif()
|
||||
|
||||
rad_add_plugin(unlimitedocr_bf16 architectures
|
||||
SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/unlimitedocr_bf16.cpp)
|
||||
@@ -0,0 +1,247 @@
|
||||
/* attn_llama.h -- one plain multi-head attention block, bf16 operands, paged KV. PRIVATE to
|
||||
* arch/unlimitedocr_bf16 (the arch/qwen35_bf16 + siglip2.h precedent: a header beside the plugin
|
||||
* that composes it).
|
||||
*
|
||||
* rmsnorm -> q gemm, k gemm, v gemm -> rope(q), rope(k)
|
||||
* -> kv_store -> paged attention (causal) -> o gemm -> [all_reduce] -> residual add
|
||||
*
|
||||
* It is rad_block_attn_gated.h with the Qwen3.5-specific parts removed, and the removals are the
|
||||
* model: Unlimited-OCR's decoder is a plain Llama-MoE (modeling_deepseekv2.py's
|
||||
* SlidingWindowLlamaAttention is MHA with `use_mla: false`), so
|
||||
*
|
||||
* * there is NO output gate: `q_proj` is [n_embd, n_head*head_dim] and holds only the query, so
|
||||
* no de-interleaving, no `sigmoid`, no `mul`;
|
||||
* * there is NO per-head q/k norm: the config's `qk_nope_head_dim`/`qk_rope_head_dim` are 0 and
|
||||
* the reference rotates the projections straight;
|
||||
* * the rotary is FULL head_dim (rot = head_dim = 128) and NeoX-half (`rotate_half` in the
|
||||
* reference), not partial, not mrope;
|
||||
* * q, k and v are three [1280, 1280] projections fused into ONE stacked-rows GEMM: the
|
||||
* rank-local q|k|v weight rows are staged once into a PERSIST plane, and q, k and v are
|
||||
* column views of one fused output plane (RadOperand::cols, abi/rad_runtime.h) that the
|
||||
* rope, kv_store and attention readers walk by row pitch -- the rad_block_attn_gated.h
|
||||
* argument against a fused [k|v] row does not apply to the stacked-rows form.
|
||||
*
|
||||
* Everything the gated block gets right about paged KV is copied through unchanged: the attention
|
||||
* declared BEFORE the store so block_size derives from the resolved kernel, the ranged `q_len`
|
||||
* band, the ragged-step cu_seqlens, the collective emitted by the plugin and not the core.
|
||||
*/
|
||||
#ifndef UNLIMITEDOCR_ATTN_LLAMA_H
|
||||
#define UNLIMITEDOCR_ATTN_LLAMA_H
|
||||
|
||||
#include <arch/rad_arch.h>
|
||||
|
||||
namespace rad {
|
||||
namespace arch {
|
||||
|
||||
struct AttnLlamaBF16 {
|
||||
struct Wire {
|
||||
rad_buf x = 0; /* [max_tok, n_embd] the residual stream */
|
||||
rad_buf h = 0; /* [max_tok, n_embd] normed input, then the o output */
|
||||
rad_buf q = 0; /* [max_tok, q_dim + 2*kv_dim] fused q|k|v plane; q, k, v are the
|
||||
* column views [0, q_dim), [q_dim, q_dim+kv_dim), [q_dim+kv_dim, ...) */
|
||||
rad_buf qs = 0; /* [max_tok, q_dim] dense q lifted out of the fused plane for
|
||||
* attn_paged, whose kernels read q only contiguous (see step) */
|
||||
rad_buf k = 0; /* the same plane: the rope/kv_store readers take the k columns */
|
||||
rad_buf v = 0; /* the same plane: the v columns */
|
||||
rad_buf attn = 0; /* [max_tok, q_dim] */
|
||||
};
|
||||
|
||||
struct Src {
|
||||
const char* norm = nullptr; /* input_layernorm.weight */
|
||||
const char* q = nullptr;
|
||||
const char* k = nullptr;
|
||||
const char* v = nullptr;
|
||||
const char* o = nullptr;
|
||||
};
|
||||
|
||||
Geom g{};
|
||||
Wire w{};
|
||||
int layer = 0;
|
||||
rad_kvgroup kv = 0;
|
||||
int64_t n_rot = 0;
|
||||
|
||||
rad_weight w_norm = 0, w_qkv = 0, w_o = 0;
|
||||
rad_op op_norm = 0, op_qkv = 0;
|
||||
rad_op op_rope_q = 0, op_rope_k = 0;
|
||||
rad_op op_qs = 0; /* cast: lift the fused plane's q slice into dense qs */
|
||||
int qrow = 0; /* attn_paged_qrow served: q is read in place at its pitch */
|
||||
rad_op op_attn = 0, op_kv_store = 0, op_o = 0, op_ar = 0, op_add = 0;
|
||||
|
||||
int declare(RadBuilder* b, Names& nm, const Geom& geom, int l, rad_kvgroup group,
|
||||
int64_t rotary_dim, const Wire& wire, const Src& src);
|
||||
void step(RadCtx* c, const RadBatch* batch) const;
|
||||
};
|
||||
|
||||
inline int AttnLlamaBF16::declare(RadBuilder* b, Names& nm, const Geom& geom, int l,
|
||||
rad_kvgroup group, int64_t rotary_dim, const Wire& wire,
|
||||
const Src& src) {
|
||||
g = geom; w = wire; layer = l; kv = group; n_rot = rotary_dim;
|
||||
|
||||
const int64_t q_dim = g.q_dim();
|
||||
const int64_t kv_dim = g.kv_dim();
|
||||
|
||||
if (n_rot <= 0 || n_rot > g.head_dim || (n_rot & 1)) {
|
||||
fprintf(stderr, "radiance: rotary_dim %lld is not an even width inside head_dim %lld\n",
|
||||
(long long)n_rot, (long long)g.head_dim);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The KV-head-replication refusal rad_block_attn_gated.h states: this block declares its k/v
|
||||
* with the plain even row-shard and passes no row span, so a world above the KV head count
|
||||
* would hand a rank half of one KV head. Say so at declare. */
|
||||
if (g.world > g.n_head_kv_all) {
|
||||
fprintf(stderr, "radiance: %s declares no KV row span and cannot serve world_size = %d "
|
||||
"with n_head_kv = %lld.\n", __func__, g.world,
|
||||
(long long)g.n_head_kv_all);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_norm.weight", l), src.norm));
|
||||
/* The convert-time q|k|v fusion, the gate_up form rad_block_mlp.h states: one weight, one
|
||||
* GEMM, one movement unit; `row_parts` keeps the row-shard on q_local|k_local|v_local
|
||||
* boundaries so the column views stay exact per rank. */
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.attn_qkv.weight", l), { src.q, src.k, src.v }, 0));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.attn_output.weight", l), src.o));
|
||||
|
||||
w_norm = decl_w(b, nm.f("blk.%d.attn_norm.weight", l), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
w_qkv = decl_w(b, nm.f("blk.%d.attn_qkv.weight", l), RAD_BF16,
|
||||
{q_dim + 2 * kv_dim, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{q_dim, kv_dim, kv_dim});
|
||||
w_o = decl_w(b, nm.f("blk.%d.attn_output.weight", l), RAD_BF16, {g.n_embd, q_dim},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
|
||||
|
||||
op_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_norm)),
|
||||
{w.x}, {w.h});
|
||||
|
||||
/* One GEMM over the fused [q|k|v] rows: N = q_dim + 2*kv_dim, the readers below take the
|
||||
* q, k and v column views of `w.q`. Same K, same per-column tile as the three-GEMM form,
|
||||
* so the bf16 outputs are bit-identical; the win is one launch, not arithmetic. */
|
||||
op_qkv = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", q_dim + 2 * kv_dim),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_qkv)),
|
||||
{w.h}, {w.q});
|
||||
|
||||
/* Full-head rotary, NeoX halves: the reference's rotate_half. The q call names n_head query
|
||||
* heads and no kv heads (the buffers are separate); the k call names the kv heads. */
|
||||
op_rope_q = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head, 0, n_rot, "neox"),
|
||||
{w.q}, {w.q});
|
||||
op_rope_k = rw(b, decl_rope(b, g, g.max_tok, g.head_dim, g.n_head_kv, 0, n_rot, "neox"),
|
||||
{w.k}, {w.k});
|
||||
|
||||
/* attn_paged's prefill kernels read q only contiguous, and here q is a column slice of the
|
||||
* fused q|k|v plane (row pitch q_dim + 2*kv_dim). attn_paged_qrow reads that pitch in place
|
||||
* (libr4d's qrow rows cover head_dim 128/256/512). It is a separate op so no `--kernels` order
|
||||
* can hand the slice to a kernel that reads q only dense (gemma4.cpp:1001-1023). Where the op
|
||||
* is not declared or does not resolve, the slice is lifted into dense qs first. The cast is
|
||||
* always declared but issued only in the fallback. */
|
||||
op_qs = rw(b, RAD_OP(b, "cast",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", q_dim),
|
||||
RAD_STR("from", g.dtype), RAD_STR("to", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.q}, {w.qs});
|
||||
auto declare_attn = [&](const char* op, rad_buf q) {
|
||||
/* Declared before kv_store so block_size derives from the resolved attention kernel (spec
|
||||
* §7.2), pinned to RAD_KV_BLOCK for the same reason rad_arch.h states. This op keeps the
|
||||
* plain causal rule through the R-SWA ring: the ring's visible set is the block table's
|
||||
* job (the runtime window prunes the table, not the kernel), so no re-declaration. */
|
||||
return rw(b, RAD_OP(b, op,
|
||||
RAD_PARAMS(RAD_RANGE("q_len", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1),
|
||||
RAD_INT("window", 0),
|
||||
RAD_INT("n_head", g.n_head),
|
||||
RAD_INT("block_size", RAD_KV_BLOCK),
|
||||
RAD_INT("max_seqs", g.max_seqs),
|
||||
RAD_INT("max_ctx", g.max_ctx),
|
||||
RAD_STR("q_dtype", g.dtype), RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{q}, {w.attn});
|
||||
};
|
||||
if (rad_op_declared(b, "attn_paged_qrow") != 0)
|
||||
op_attn = declare_attn("attn_paged_qrow", w.q);
|
||||
if (op_attn) {
|
||||
qrow = 1;
|
||||
} else {
|
||||
qrow = 0;
|
||||
op_attn = declare_attn("attn_paged", w.qs);
|
||||
}
|
||||
|
||||
op_kv_store = rw(b, RAD_OP(b, "kv_store",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
|
||||
RAD_INT("n_head_kv", g.n_head_kv),
|
||||
RAD_INT("block_size", rad_kv_block_size(b, kv)),
|
||||
RAD_STR("kv_dtype", g.kv_dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.k, w.v}, {});
|
||||
|
||||
op_o = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", q_dim), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(w_o)),
|
||||
{w.attn}, {w.h});
|
||||
|
||||
if (g.world > 1)
|
||||
op_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.h}, {w.h});
|
||||
|
||||
op_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{w.x, w.h}, {w.x});
|
||||
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
inline void AttnLlamaBF16::step(RadCtx* c, const RadBatch* batch) const {
|
||||
const RadKVGroupBatch* kvb = kv_batch(batch, kv);
|
||||
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
|
||||
const int32_t* table = kvb ? kvb->block_table : nullptr;
|
||||
const int32_t* used = kvb ? kvb->seqused : nullptr;
|
||||
|
||||
const int64_t T = batch->n_tok;
|
||||
|
||||
RAD_ISSUE(c, op_norm, brows(w.x, T), RAD_W(w_norm), brows(w.h, T));
|
||||
RAD_ISSUE(c, op_qkv, brows(w.h, T), RAD_W(w_qkv), brows(w.q, T));
|
||||
|
||||
/* q, k and v are column views of the fused plane, walked by its row pitch: the rope and
|
||||
* kv_store kernels take the slice's pitch (r4d_rows_pitch). Attention reads the q slice in
|
||||
* place when attn_paged_qrow is served; otherwise it needs q dense, so the slice is lifted
|
||||
* into qs after rope and before the store. */
|
||||
RAD_ISSUE(c, op_rope_q, bcol(w.q, 0, g.q_dim(), T), rope_posmc(g, batch, T));
|
||||
RAD_ISSUE(c, op_rope_k, bcol(w.q, g.q_dim(), g.kv_dim(), T), rope_posmc(g, batch, T));
|
||||
|
||||
if (op_qs) RAD_ISSUE(c, op_qs, bcol(w.q, 0, g.q_dim(), T), brows(w.qs, T));
|
||||
|
||||
RAD_ISSUE(c, op_kv_store,
|
||||
bcol(w.q, g.q_dim(), g.kv_dim(), T),
|
||||
bcol(w.q, g.q_dim() + g.kv_dim(), g.kv_dim(), T),
|
||||
praw(slot, RAD_I32, T), kv_cache(kv, layer));
|
||||
|
||||
RAD_ISSUE_N(c, op_attn, batch->max_q_len,
|
||||
qrow ? bcol(w.q, 0, g.q_dim(), T) : brows(w.qs, T), kv_cache(kv, layer),
|
||||
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
|
||||
praw(used, RAD_I32, batch->n_seq),
|
||||
RAD_NONE, RAD_NONE,
|
||||
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1),
|
||||
brows(w.attn, T));
|
||||
|
||||
RAD_ISSUE(c, op_o, brows(w.attn, T), RAD_W(w_o), brows(w.h, T));
|
||||
if (op_ar) RAD_ISSUE_N(c, op_ar, T * g.n_embd, brows(w.h, T), RAD_NONE);
|
||||
RAD_ISSUE(c, op_add, brows(w.x, T), brows(w.h, T), brows(w.x, T));
|
||||
}
|
||||
|
||||
} /* namespace arch */
|
||||
} /* namespace rad */
|
||||
|
||||
#endif /* UNLIMITEDOCR_ATTN_LLAMA_H */
|
||||
@@ -0,0 +1,553 @@
|
||||
/* unlimitedocr_bf16 -- baidu/Unlimited-OCR's decoder: a small Llama-MoE, bf16 weights and bf16
|
||||
* activations.
|
||||
*
|
||||
* Scope: the text trunk plus the DeepEncoder vision tower
|
||||
* (arch/common/rad_block_sam.h: SAM ViT-B/16 -> map -> CLIP ViT-L/14 -> the projector
|
||||
* -> the 273-row layout of a 1024 view / 110 rows of a 640 tile, declared with
|
||||
* rad_declare_encoder(RAD_MM_IMAGE), patch_dim 768 = 3*16*16, merge 16, n_embd 1280). The tower
|
||||
* serves both view geometries the processor stages -- the gundam mode's 640 tiles and global
|
||||
* view, and the base mode's pages -- as two op sets over the same weights, the 40 grid's absolute
|
||||
* position tables bicubic+antialias resamples of the checkpoint's (arch/common/rad_resample.h).
|
||||
* The tower's weights are mapped always; its ops and the encoder pass are declared only when
|
||||
* SAM's `sam_attn` op resolves, because no existing op
|
||||
* can carry the decomposed rel_pos_h/rel_pos_w attention bias (rad_block_sam.h's header states the
|
||||
* op and why). Without it this plugin is the text-only trunk and refuses images by name. The
|
||||
* decoder's KV is one RAD_KV_RING group with the checkpoint's `sliding_window_size` (128), the
|
||||
* reference's own R-SWA: prefill is fully causal, and from the end of the prefill the ring of the
|
||||
* last W generated tokens is appended to the prompt (`SlidingWindowLlamaAttention`, which keeps
|
||||
* the prompt as reference and overwrites ring slots in place). The checkpoint's windowed
|
||||
* no-repeat-ngram ban is the sampler's `sample_ngram_ban` stage.
|
||||
*
|
||||
* ============================== THE SHAPE (config.json) ==============================
|
||||
*
|
||||
* 12 layers, hidden 1280, 10 heads x 128 head_dim, 10 kv-heads (MHA, `use_mla: false` -- the
|
||||
* DeepseekV2 class names in the repo are packaging, the graph is Llama)
|
||||
* full rotary over head_dim, theta 10000, plain RMSNorm eps 1e-6 (NOT 1 + w)
|
||||
* vocab 129280, lm_head TIED to embed_tokens (the checkpoint ships both tensors)
|
||||
* layer 0 dense (first_k_dense_replace 1, inter 6848); layers 1..11 MoE:
|
||||
* 64 routed experts (moe_intermediate_size 896), top-6, scoring softmax,
|
||||
* norm_topk_prob False, routed_scaling_factor 1.0 -- an ordinary softmax gate,
|
||||
* 2 shared experts packed as ONE dense MLP 2x896 = 1792 wide, summed ungated
|
||||
*
|
||||
* The MoE block is arch/common/rad_block_moe_fp8.h in its plain-bf16 expert mode (probe() reads
|
||||
* format 3 off the first expert's encoding), declared EXTERNAL-INPUT (src.norm null): its
|
||||
* post-attention norm is declared by this plugin because the shared expert reads the SAME normed
|
||||
* input and the block's gather overwrites that input with the routed delta (`h.x` is the
|
||||
* fold target). The shared arm therefore lives here: gate|up -> silu_mul -> down -> add, beside
|
||||
* the routed arm, exactly `y = y + shared_experts(x)` in modeling_deepseekv2.py:627.
|
||||
*
|
||||
* The attention is this plugin's private attn_llama.h: the gated bf16 block minus the output gate
|
||||
* and the q/k head norms, which this model does not have.
|
||||
*/
|
||||
#include <arch/rad_arch.h>
|
||||
#include <arch/rad_block_mlp.h>
|
||||
#include <arch/rad_block_moe_fp8.h>
|
||||
#include <arch/rad_block_sam.h>
|
||||
|
||||
#include "attn_llama.h"
|
||||
|
||||
#include <vector>
|
||||
|
||||
namespace unlimitedocr_bf16 {
|
||||
|
||||
using namespace rad::arch;
|
||||
|
||||
struct Layer {
|
||||
int dense = 0; /* 1 = the first_k_dense layer, plain SwiGLU */
|
||||
AttnLlamaBF16 attn;
|
||||
MlpBF16 mlp; /* dense layers */
|
||||
MoeFP8 moe; /* routed layers */
|
||||
/* The routed layer's external norm and the plugin-owned shared arm: the gain, the two dense
|
||||
* linears' weights, and the ops. Per layer -- the ACTIVATION buffers are shared across the
|
||||
* layers (spec §8) and the ops are declared per layer, as every block here does. */
|
||||
rad_weight w_norm = 0, w_sh_gate_up = 0, w_sh_down = 0;
|
||||
rad_op op_moe_norm = 0; /* x -> h.x, the MoE block's external prepared input */
|
||||
rad_op op_sh_gu = 0, op_sh_act = 0, op_sh_down = 0, op_sh_ar = 0, op_sh_add = 0;
|
||||
};
|
||||
|
||||
struct Model {
|
||||
Names nm{""};
|
||||
Geom g{};
|
||||
int64_t n_rot = 0;
|
||||
int64_t first_dense = 1; /* layers [0, first_dense) are dense MLPs */
|
||||
|
||||
rad_kvgroup kv = 0;
|
||||
|
||||
/* the residual stream and the vocabulary edges */
|
||||
rad_buf b_x = 0, b_h = 0, b_hout = 0, b_logits = 0;
|
||||
/* attention */
|
||||
rad_buf b_qkv = 0, b_qs = 0, b_attn = 0;
|
||||
/* dense feed-forward (layer 0) */
|
||||
rad_buf b_gate_up = 0, b_ffn = 0;
|
||||
/* routing -- one row per token */
|
||||
rad_buf b_rlogits = 0, b_eids = 0, b_ew = 0, b_eoff = 0, b_ecnt = 0;
|
||||
/* expert planes -- one row per (token, slot), a pass tall */
|
||||
rad_buf b_sorted = 0, b_egu = 0, b_edn = 0;
|
||||
ActFP8 a_eff{};
|
||||
/* the shared arm reads the block's prepared input (h) before the gather overwrites it, then
|
||||
* the dense linear's planes */
|
||||
rad_buf b_sgu = 0, b_sff = 0, b_sout = 0;
|
||||
|
||||
MoeFP8::Config moecfg{};
|
||||
/* The DeepEncoder vision tower (arch/common/rad_block_sam.h). Its weights are mapped always;
|
||||
* its ops and the encoder pass only when SAM's attention op resolves. */
|
||||
DeepEncoder enc;
|
||||
|
||||
rad_weight w_tok = 0, w_out_norm = 0, w_lm_head = 0;
|
||||
rad_op op_embed = 0, op_embed_ar = 0, op_mm = 0, op_final_norm = 0, op_gather = 0,
|
||||
op_logits = 0;
|
||||
|
||||
std::vector<Layer> layers;
|
||||
};
|
||||
|
||||
static Model g_model[MAX_RANKS];
|
||||
|
||||
/* The per-MoE-layer norm and shared arm. The MoE block declares no norm in external-input mode,
|
||||
* and the shared expert must read the same normed row the routed experts do; the block's gather
|
||||
* folds the routed delta into h.x, so the shared arm is issued while h.x still holds the normed
|
||||
* row, BEFORE the block. */
|
||||
static int declare_moe_norm_and_shared(RadBuilder* b, Model& m, int l) {
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
|
||||
const char* wname = nm.f("blk.%d.ffn_norm.weight", l);
|
||||
RAD_ARCH_TRY(map_copy(b, wname, nm.ckpt("model.layers.%lld.post_attention_layernorm.weight",
|
||||
(long long)l)));
|
||||
lay.w_norm = decl_w(b, wname, RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_layer(l));
|
||||
|
||||
const int64_t n_ff_sh = m.moecfg.n_ff_shared;
|
||||
RAD_ARCH_TRY(map_concat(b, nm.f("blk.%d.ffn_gate_up_shexp.weight", l),
|
||||
{ nm.ckpt("model.layers.%lld.mlp.shared_experts.gate_proj.weight",
|
||||
(long long)l),
|
||||
nm.ckpt("model.layers.%lld.mlp.shared_experts.up_proj.weight",
|
||||
(long long)l) }, 0));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("blk.%d.ffn_down_shexp.weight", l),
|
||||
nm.ckpt("model.layers.%lld.mlp.shared_experts.down_proj.weight",
|
||||
(long long)l)));
|
||||
lay.w_sh_gate_up = decl_w(b, nm.f("blk.%d.ffn_gate_up_shexp.weight", l), RAD_BF16,
|
||||
{2 * n_ff_sh, g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW, grp_layer(l), 0,
|
||||
{n_ff_sh, n_ff_sh});
|
||||
lay.w_sh_down = decl_w(b, nm.f("blk.%d.ffn_down_shexp.weight", l), RAD_BF16,
|
||||
{g.n_embd, n_ff_sh},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_COL, grp_layer(l));
|
||||
|
||||
/* The routed arm's own norm: x -> h.x, the buffer the block takes as its prepared input and
|
||||
* the buffer its gather writes the routed delta back into. */
|
||||
lay.op_moe_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", g.wadd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_norm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
|
||||
lay.op_sh_gu = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", 2 * n_ff_sh),
|
||||
RAD_INT("K", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_sh_gate_up)),
|
||||
{m.b_h}, {m.b_sgu});
|
||||
lay.op_sh_act = rw(b, RAD_OP(b, "silu_mul",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", n_ff_sh),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_sgu}, {m.b_sff});
|
||||
lay.op_sh_down = rw(b, RAD_OP(b, "gemm_nt",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("N", g.n_embd),
|
||||
RAD_INT("K", n_ff_sh), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(lay.w_sh_down)),
|
||||
{m.b_sff}, {m.b_sout});
|
||||
/* Column-sharded like the dense MLP's down_proj: every rank holds a partial sum, reduced
|
||||
* once per step before the residual add. */
|
||||
if (g.world > 1)
|
||||
lay.op_sh_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", g.wire_exact),
|
||||
RAD_INT("min_bytes", g.wire_min_bytes)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_sout}, {m.b_sout});
|
||||
lay.op_sh_add = rw(b, RAD_OP(b, "add",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x, m.b_sout}, {m.b_x});
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
|
||||
if (!b || !meta || !ctx) return RAD_E_INVAL;
|
||||
if (ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
|
||||
|
||||
Model& m = g_model[ctx->rank];
|
||||
m = Model{};
|
||||
m.nm = Names(ctx->scope);
|
||||
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
|
||||
Geom& g = m.g;
|
||||
Names& nm = m.nm;
|
||||
|
||||
/* Plain RMSNorm (DeepseekV2RMSNorm is x_hat * w), not the GemmaRMSNorm `1 + w`. */
|
||||
g.wadd = 0.0f;
|
||||
/* The linears are the checkpoint's own bf16: no scale planes, no quantised activations. The
|
||||
* MoeFP8 block in particular requires it (its external-input check reads it). */
|
||||
g.w_bf16 = true;
|
||||
|
||||
/* ---- geometry RadModelMeta does not name. */
|
||||
const int64_t n_expert_all = meta->n_expert > 0
|
||||
? meta->n_expert : rad_meta_geti(meta, "n_routed_experts", 0);
|
||||
const int64_t top_k = meta->n_expert_used > 0
|
||||
? meta->n_expert_used : rad_meta_geti(meta, "num_experts_per_tok", 0);
|
||||
const int64_t moe_ff = rad_meta_geti(meta, "moe_intermediate_size", 0);
|
||||
const int64_t n_shared = rad_meta_geti(meta, "n_shared_experts", 0);
|
||||
m.first_dense = rad_meta_geti(meta, "first_k_dense_replace", 1);
|
||||
if (n_expert_all <= 0 || top_k <= 0 || top_k > n_expert_all || moe_ff <= 0 ||
|
||||
m.first_dense < 0 || m.first_dense >= g.n_layer) {
|
||||
fprintf(stderr, "radiance: unlimitedocr: the container does not describe the routed "
|
||||
"decoder (n_routed_experts %lld, num_experts_per_tok %lld, "
|
||||
"moe_intermediate_size %lld, first_k_dense_replace %lld of %lld layers)\n",
|
||||
(long long)n_expert_all, (long long)top_k, (long long)moe_ff,
|
||||
(long long)m.first_dense, (long long)g.n_layer);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* The gate is an ordinary softmax top-k. A container that states a scheme this plugin does not
|
||||
* serve is refused by name rather than served as a softmax gate (spec §17). */
|
||||
if (const char* sf = rad_meta_gets(meta, "scoring_func", nullptr); sf && *sf &&
|
||||
std::strcmp(sf, "softmax") != 0) {
|
||||
fprintf(stderr, "radiance: unlimitedocr: scoring_func '%s' is not implemented; the gate "
|
||||
"this plugin declares is the softmax top-k\n", sf);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const double rsf = rad_meta_getf(meta, "routed_scaling_factor", 1.0);
|
||||
if (!(rsf > 0.0) || rsf != 1.0) {
|
||||
fprintf(stderr, "radiance: unlimitedocr: routed_scaling_factor %g is not 1.0 and this "
|
||||
"plugin declares no router output scale\n", rsf);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const int64_t topk_group = rad_meta_geti(meta, "topk_group", 1);
|
||||
const int64_t n_group = rad_meta_geti(meta, "n_group", 1);
|
||||
if (topk_group != 1 || n_group != 1) {
|
||||
fprintf(stderr, "radiance: unlimitedocr: grouped routing (n_group %lld, topk_group %lld) "
|
||||
"is not implemented; the reference's greedy top-k over one group is\n",
|
||||
(long long)n_group, (long long)topk_group);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (rad_meta_geti(meta, "use_mla", 0)) {
|
||||
fprintf(stderr, "radiance: unlimitedocr: use_mla is set; this decoder is the MHA graph "
|
||||
"(q/k/v projections), not the DeepSeek MLA\n");
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The full-head rotary: no rope_parameters object is present, so yarn_from answers
|
||||
* "default" and theta stays the container's (the reference default 10000). */
|
||||
m.n_rot = g.head_dim;
|
||||
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
|
||||
|
||||
/* ---- the routed geometry. n_expert is NOT divided (every rank holds every expert and routes
|
||||
* identically); the intermediate width is. */
|
||||
MoeFP8::Config& mc = m.moecfg;
|
||||
mc.n_expert = n_expert_all;
|
||||
mc.n_expert_all = n_expert_all;
|
||||
mc.top_k = top_k;
|
||||
int s;
|
||||
if ((s = divide_or_fail(moe_ff, g.world, "moe_intermediate_size", &mc.n_ff_exp)) < 0)
|
||||
return s;
|
||||
/* The shared experts are packed as ONE dense MLP n_shared x moe_ff wide (DeepseekV2Model:
|
||||
* `intermediate_size = moe_intermediate_size * n_shared_experts`), summed ungated. The
|
||||
* MoeFP8 shared arm is the SIGMOID-gated family's shape; this model's arm is declared by the
|
||||
* plugin (declare_moe_norm_and_shared) and the block declares none. */
|
||||
const int64_t sh_all = n_shared * moe_ff;
|
||||
mc.n_ff_shared = 0;
|
||||
int64_t n_ff_sh = 0;
|
||||
if (sh_all > 0 && (s = divide_or_fail(sh_all, g.world, "n_shared_experts width",
|
||||
&n_ff_sh)) < 0)
|
||||
return s;
|
||||
mc.norm_topk = rad_meta_geti(meta, "norm_topk_prob", 0) ? 1 : 0;
|
||||
const int64_t moe_rows = 2048;
|
||||
mc.rows = g.max_tok < moe_rows ? g.max_tok : moe_rows;
|
||||
|
||||
/* ---- KV: one R-SWA ring group.
|
||||
*
|
||||
* The reference's `SlidingWindowLlamaAttention` keeps the prefill as reference and from the
|
||||
* prefill's end keeps the last `sliding_window_size` generated tokens in a ring it overwrites
|
||||
* in place, attending over both. RAD_KV_RING is that: paged like a window group, but the floor
|
||||
* is per sequence and armed at admission (`visible_lo = prefill length`), so a decode query
|
||||
* sees [0, prefill) U [prefill, prefill + W). Prefill itself stays fully causal, which is why
|
||||
* the attention op keeps `causal=1` and `window=0`: the visible set is the block table's job,
|
||||
* and `causal=0` would make a prefill chunk non-causal.
|
||||
*
|
||||
* A checkpoint that states no window gets the plain full cache, so the text trunk still
|
||||
* serves. Prefix caching and speculation switch off for the group automatically (a runtime
|
||||
* window's KV before the prompt end is not reusable and a draft cannot know where the ring
|
||||
* starts). */
|
||||
const int64_t sw_size = rad_meta_geti(meta, "sliding_window_size", 0);
|
||||
const int64_t win = sw_size > 0 ? sw_size : rad_meta_geti(meta, "sliding_window", 0);
|
||||
RadKVGroupDecl fd{};
|
||||
fd.kind = win > 0 ? RAD_KV_RING : RAD_KV_FULL;
|
||||
fd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
|
||||
fd.window = win > 0 ? win : 0;
|
||||
fd.n_head_kv = g.n_head_kv;
|
||||
fd.head_dim = g.head_dim;
|
||||
m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &fd);
|
||||
g.kv_dtype = rad_dtype_name(fd.dtype);
|
||||
|
||||
/* ---- activation buffers. */
|
||||
m.b_x = decl_b(b, nm.f("x"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_h = decl_b(b, nm.f("h"), g.act_dtype, {g.max_tok, g.n_embd});
|
||||
m.b_qkv = decl_b(b, nm.f("attn_qkv"), g.act_dtype,
|
||||
{g.max_tok, g.q_dim() + 2 * g.kv_dim()});
|
||||
/* The dense q lifted out of the fused plane for attn_paged (attn_llama.h's cast). */
|
||||
m.b_qs = decl_b(b, nm.f("attn_q"), g.act_dtype, {g.max_tok, g.q_dim()});
|
||||
m.b_attn = decl_b(b, nm.f("attn_out"), g.act_dtype, {g.max_tok, g.q_dim()});
|
||||
|
||||
m.b_gate_up = decl_b(b, nm.f("gate_up"), g.act_dtype, {g.max_tok, 2 * g.n_ff});
|
||||
m.b_ffn = decl_b(b, nm.f("ffn"), g.act_dtype, {g.max_tok, g.n_ff});
|
||||
|
||||
const int64_t R = g.max_tok, K = mc.rows * mc.top_k;
|
||||
m.b_rlogits = decl_b(b, nm.f("moe_logits"), g.act_dtype, {R, mc.n_expert_all});
|
||||
m.b_eids = decl_b(b, nm.f("moe_ids"), RAD_I32, {R, mc.top_k});
|
||||
m.b_ew = decl_b(b, nm.f("moe_w"), g.act_dtype, {R, mc.top_k});
|
||||
m.b_sorted = decl_b(b, nm.f("moe_sorted"), RAD_I32, {K});
|
||||
m.b_eoff = decl_b(b, nm.f("moe_off"), RAD_I32, {mc.n_expert_all + 1});
|
||||
/* PERSIST: its only reader, rad_route_report, is not a declared op. See qwen4exp_fp8. */
|
||||
m.b_ecnt = decl_b(b, nm.f("moe_cnt"), RAD_I32, {mc.n_expert}, RAD_BUF_PERSIST);
|
||||
m.b_egu = decl_b(b, nm.f("moe_gate_up"), g.act_dtype, {K, 2 * mc.n_ff_exp});
|
||||
m.a_eff.x = decl_b(b, nm.f("moe_ffn"), g.act_dtype, {K, mc.n_ff_exp});
|
||||
m.b_edn = decl_b(b, nm.f("moe_down"), g.act_dtype, {K, g.n_embd});
|
||||
|
||||
if (n_ff_sh > 0) {
|
||||
mc.n_ff_shared = n_ff_sh; /* sizes nothing in the block (arm null there); kept for
|
||||
the shared-arm ops below */
|
||||
m.b_sgu = decl_b(b, nm.f("shexp_gate_up"), g.act_dtype, {R, 2 * n_ff_sh});
|
||||
m.b_sff = decl_b(b, nm.f("shexp_ffn"), g.act_dtype, {R, n_ff_sh});
|
||||
m.b_sout = decl_b(b, nm.f("shexp_out"), g.act_dtype, {R, g.n_embd});
|
||||
}
|
||||
|
||||
m.b_hout = decl_b(b, nm.f("h_out"), g.act_dtype, {g.max_logit_rows, g.n_embd});
|
||||
m.b_logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
|
||||
RAD_ARCH_TRY(rad_declare_logits(b, m.b_logits));
|
||||
|
||||
/* ---- vocabulary edges. The lm_head is TIED: the checkpoint ships lm_head.weight, and a
|
||||
* release that ships only the embedding is served by the same map (first source present
|
||||
* wins). Both edges are row-sharded with the vocabulary (spec §9). */
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("token_embd.weight"), nm.ckpt("model.embed_tokens.weight")));
|
||||
RAD_ARCH_TRY(map_copy(b, nm.f("output_norm.weight"), nm.ckpt("model.norm.weight")));
|
||||
RAD_ARCH_TRY(map_copy_alt(b, nm.f("output.weight"), nm.ckpt("lm_head.weight"),
|
||||
nm.ckpt("model.embed_tokens.weight")));
|
||||
|
||||
m.w_tok = decl_w(b, nm.f("token_embd.weight"), RAD_BF16, {g.n_vocab, g.n_embd},
|
||||
RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
m.w_out_norm = decl_w(b, nm.f("output_norm.weight"), RAD_F32, {g.n_embd},
|
||||
RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE, grp_model());
|
||||
m.w_lm_head = decl_w(b, nm.f("output.weight"),
|
||||
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
|
||||
{g.n_vocab, g.n_embd}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
|
||||
|
||||
m.op_embed = rw(b, RAD_OP(b, "embed_lookup",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n_embd", g.n_embd),
|
||||
RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", g.dtype),
|
||||
RAD_INT("vocab_offset", g.vocab_off)),
|
||||
RAD_WEIGHTS(m.w_tok)),
|
||||
{}, {m.b_x});
|
||||
if (g.world > 1)
|
||||
m.op_embed_ar = rw(b, RAD_OP(b, "all_reduce",
|
||||
RAD_PARAMS(RAD_INT("world_size", g.world),
|
||||
RAD_RANGE("numel", g.n_embd, g.max_tok * g.n_embd),
|
||||
RAD_STR("dtype", g.dtype), RAD_INT("exact", 1)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
/* ---- the expert format: the checkpoint's plain bf16, read off the first routed layer's
|
||||
* first expert. A quantised container would be a sibling plugin's. */
|
||||
{
|
||||
MoeFP8::Src probe_src{};
|
||||
probe_src.experts = nm.ckpt("model.layers.%lld.mlp.experts",
|
||||
(long long)m.first_dense);
|
||||
RAD_ARCH_TRY(MoeFP8::probe(b, nm, (int)m.first_dense, probe_src, &mc));
|
||||
if (!mc.expert_bf16) {
|
||||
fprintf(stderr, "radiance: unlimitedocr_bf16 serves plain bf16 experts; layer %lld's "
|
||||
"expert 0 is quantised. Serve that container with its quantised "
|
||||
"plugin.\n", (long long)m.first_dense);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- the DeepEncoder tower: map and declare its weights, then (when `sam_attn` resolves) its
|
||||
* ops and the encoder pass. Without that op the tower stays off and images are refused. */
|
||||
RAD_ARCH_TRY(m.enc.declare(b, ctx, nm, g.n_embd, (int)g.n_layer + 64));
|
||||
|
||||
/* A picture's rows overwrite its placeholders' embeddings after the (all-reduced) lookup and
|
||||
* before the first block. Declared only when the tower is, since otherwise no step can carry
|
||||
* media rows. */
|
||||
if (m.enc.on)
|
||||
m.op_mm = rw(b, RAD_OP(b, "scatter_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_STR("dtype", "bf16")),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_x}, {m.b_x});
|
||||
|
||||
AttnLlamaBF16::Wire aw{};
|
||||
aw.x = m.b_x; aw.h = m.b_h; aw.q = m.b_qkv; aw.k = m.b_qkv; aw.v = m.b_qkv;
|
||||
aw.qs = m.b_qs;
|
||||
aw.attn = m.b_attn;
|
||||
|
||||
MlpBF16::Wire mw{};
|
||||
mw.x = m.b_x; mw.h = m.b_h; mw.gate_up = m.b_gate_up; mw.ffn = m.b_ffn;
|
||||
|
||||
MoeFP8::Wire fw{};
|
||||
fw.x = m.b_x;
|
||||
fw.h.x = m.b_h; /* external input: the plugin's own rmsnorm writes it */
|
||||
fw.logits = m.b_rlogits; fw.ids = m.b_eids; fw.ew = m.b_ew;
|
||||
fw.eoff = m.b_eoff; fw.ecnt = m.b_ecnt;
|
||||
fw.sorted = m.b_sorted; fw.egu = m.b_egu;
|
||||
fw.eff.x = m.a_eff.x;
|
||||
fw.edn = m.b_edn; /* moe, sgu, sff, sout, sgate stay null: no block arm */
|
||||
|
||||
m.layers.resize((size_t)g.n_layer);
|
||||
for (int64_t l = 0; l < g.n_layer; ++l) {
|
||||
Layer& lay = m.layers[(size_t)l];
|
||||
lay.dense = (l < m.first_dense) ? 1 : 0;
|
||||
|
||||
AttnLlamaBF16::Src as{};
|
||||
as.norm = nm.ckpt("model.layers.%lld.input_layernorm.weight", (long long)l);
|
||||
as.q = nm.ckpt("model.layers.%lld.self_attn.q_proj.weight", (long long)l);
|
||||
as.k = nm.ckpt("model.layers.%lld.self_attn.k_proj.weight", (long long)l);
|
||||
as.v = nm.ckpt("model.layers.%lld.self_attn.v_proj.weight", (long long)l);
|
||||
as.o = nm.ckpt("model.layers.%lld.self_attn.o_proj.weight", (long long)l);
|
||||
RAD_ARCH_TRY(rad_bind_layer_kv(b, (int)l, m.kv));
|
||||
RAD_ARCH_TRY(lay.attn.declare(b, nm, g, (int)l, m.kv, m.n_rot, aw, as));
|
||||
|
||||
if (lay.dense) {
|
||||
MlpBF16::Src ms{};
|
||||
ms.norm = nm.ckpt("model.layers.%lld.post_attention_layernorm.weight", (long long)l);
|
||||
ms.gate = nm.ckpt("model.layers.%lld.mlp.gate_proj.weight", (long long)l);
|
||||
ms.up = nm.ckpt("model.layers.%lld.mlp.up_proj.weight", (long long)l);
|
||||
ms.down = nm.ckpt("model.layers.%lld.mlp.down_proj.weight", (long long)l);
|
||||
RAD_ARCH_TRY(lay.mlp.declare(b, nm, g, (int)l, mw, ms));
|
||||
} else {
|
||||
/* The block's norm, the shared arm and its linears, then the block. The block's norm
|
||||
* is declared by the plugin (external input) because its gather folds the routed
|
||||
* delta into h.x, and the shared arm reads its own copy of the normed row. */
|
||||
RAD_ARCH_TRY(declare_moe_norm_and_shared(b, m, (int)l));
|
||||
|
||||
MoeFP8::Src fs{};
|
||||
fs.cfg = mc;
|
||||
fs.norm = nullptr; /* external: declared above */
|
||||
fs.router = nm.ckpt("model.layers.%lld.mlp.gate.weight", (long long)l);
|
||||
fs.experts = nm.ckpt("model.layers.%lld.mlp.experts", (long long)l);
|
||||
fs.shared = nullptr; /* the ungated shared arm lives in the plugin */
|
||||
RAD_ARCH_TRY(lay.moe.declare(b, nm, g, (int)l, fw, fs));
|
||||
}
|
||||
}
|
||||
|
||||
m.op_final_norm = rw(b, RAD_OP(b, "rmsnorm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("n", g.n_embd),
|
||||
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0),
|
||||
RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_out_norm)),
|
||||
{m.b_x}, {m.b_h});
|
||||
|
||||
m.op_gather = rw(b, RAD_OP(b, "gather_rows",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_NOWEIGHTS),
|
||||
{m.b_h}, {m.b_hout});
|
||||
|
||||
m.op_logits = rw(b, RAD_OP(b, "logits_gemm",
|
||||
RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
|
||||
RAD_INT("n_vocab", g.n_vocab),
|
||||
RAD_INT("n_embd", g.n_embd), RAD_STR("dtype", g.dtype)),
|
||||
RAD_WEIGHTS(m.w_lm_head)),
|
||||
{m.b_hout}, {m.b_logits});
|
||||
|
||||
rad_note(b, "rank %d/%d: %lld layers, layer 0 dense (n_ff %lld), layers %lld..%lld MoE: "
|
||||
"%lld experts top-%lld (softmax, norm_topk %d), shared arm %lld wide, "
|
||||
"n_head=%lld n_head_kv=%lld head_dim=%lld vocab=[%lld,%lld) tied head",
|
||||
g.rank, g.world, (long long)g.n_layer, (long long)g.n_ff,
|
||||
(long long)m.first_dense, (long long)(g.n_layer - 1),
|
||||
(long long)mc.n_expert_all, (long long)mc.top_k, mc.norm_topk,
|
||||
(long long)mc.n_ff_shared,
|
||||
(long long)g.n_head, (long long)g.n_head_kv, (long long)g.head_dim,
|
||||
(long long)g.vocab_off, (long long)(g.vocab_off + g.n_vocab));
|
||||
if (win > 0)
|
||||
rad_note(b, "R-SWA: the KV group is a runtime ring (RAD_KV_RING), window %lld tokens from "
|
||||
"the prefill's end (the reference's SlidingWindowLlamaAttention); prefill is "
|
||||
"fully causal, and prefix cache and speculation are off for it", (long long)win);
|
||||
else
|
||||
rad_note(b, "R-SWA: the checkpoint states no sliding_window_size, so the KV group is a "
|
||||
"plain full cache");
|
||||
/* Only when the container states the processor: gen-convert copies the checkpoint's
|
||||
* generation_config into `generation.*`, so a checkpoint without it gets no note. */
|
||||
const int64_t ng_n = rad_meta_geti(meta, "generation.no_repeat_ngram_size", 0);
|
||||
if (ng_n > 0)
|
||||
rad_note(b, "generation_config asks for SlidingWindowNoRepeatNgramProcessor n=%lld over "
|
||||
"the last %lld tokens -- served by the sample_ngram_ban stage, overridable "
|
||||
"per request (ngram_ban_n / ngram_window); temp-0 parity checks run with it off",
|
||||
(long long)ng_n,
|
||||
(long long)rad_meta_geti(meta, "generation.no_repeat_ngram_window_size", 0));
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
static void step(RadCtx* c, const RadBatch* batch) {
|
||||
Model& m = g_model[rad_rank(c)];
|
||||
|
||||
if (batch->enc) {
|
||||
m.enc.step(c, batch);
|
||||
return;
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_embed,
|
||||
praw(batch->token_ids, RAD_I32, batch->n_tok), RAD_W(m.w_tok),
|
||||
brows(m.b_x, batch->n_tok));
|
||||
if (m.op_embed_ar)
|
||||
RAD_ISSUE_N(c, m.op_embed_ar, (int64_t)batch->n_tok * m.g.n_embd,
|
||||
brows(m.b_x, batch->n_tok), RAD_NONE);
|
||||
if (m.op_mm && batch->n_mm_rows > 0)
|
||||
RAD_ISSUE_N(c, m.op_mm, batch->n_mm_rows,
|
||||
praw2(batch->mm_embd, RAD_BF16, batch->n_mm_rows, m.g.n_embd),
|
||||
praw(batch->mm_rows, RAD_I32, batch->n_mm_rows), brows(m.b_x, batch->n_tok));
|
||||
|
||||
for (const Layer& l : m.layers) {
|
||||
l.attn.step(c, batch);
|
||||
if (l.dense) {
|
||||
l.mlp.step(c, batch);
|
||||
} else {
|
||||
const int64_t T = batch->n_tok;
|
||||
/* The MoE block's norm (x -> h.x), then the shared arm beside the routed arm: both
|
||||
* read the same prepared input, so the shared arm is issued while h.x still holds the
|
||||
* normed row and BEFORE the block's gather overwrites it with the routed delta. The
|
||||
* two residual adds commute: x += shared, then the block's x += routed. */
|
||||
RAD_ISSUE(c, l.op_moe_norm, brows(m.b_x, T), RAD_W(l.w_norm), brows(m.b_h, T));
|
||||
RAD_ISSUE(c, l.op_sh_gu, brows(m.b_h, T), RAD_W(l.w_sh_gate_up),
|
||||
brows(m.b_sgu, T));
|
||||
RAD_ISSUE(c, l.op_sh_act, brows(m.b_sgu, T), brows(m.b_sff, T));
|
||||
RAD_ISSUE(c, l.op_sh_down, brows(m.b_sff, T), RAD_W(l.w_sh_down),
|
||||
brows(m.b_sout, T));
|
||||
if (l.op_sh_ar)
|
||||
RAD_ISSUE_N(c, l.op_sh_ar, T * m.g.n_embd, brows(m.b_sout, T), RAD_NONE);
|
||||
RAD_ISSUE(c, l.op_sh_add, brows(m.b_x, T), brows(m.b_sout, T), brows(m.b_x, T));
|
||||
l.moe.step(c, batch);
|
||||
}
|
||||
}
|
||||
|
||||
RAD_ISSUE(c, m.op_final_norm,
|
||||
brows(m.b_x, batch->n_tok), RAD_W(m.w_out_norm), brows(m.b_h, batch->n_tok));
|
||||
|
||||
if (batch->n_out > 0) {
|
||||
RAD_ISSUE_N(c, m.op_gather, batch->n_out,
|
||||
brows(m.b_h, batch->n_tok),
|
||||
praw(batch->out_ids, RAD_I32, batch->n_out),
|
||||
brows(m.b_hout, batch->n_out));
|
||||
RAD_ISSUE_N(c, m.op_logits, batch->n_out,
|
||||
brows(m.b_hout, batch->n_out), RAD_W(m.w_lm_head),
|
||||
brows(m.b_logits, batch->n_out));
|
||||
}
|
||||
}
|
||||
|
||||
} /* namespace unlimitedocr_bf16 */
|
||||
|
||||
#ifndef RAD_ARCH_NO_EXPORTS
|
||||
RAD_ARCH_PLUGIN(unlimitedocr_bf16, "unlimitedocr", "", "0.1.0",
|
||||
"baidu/Unlimited-OCR decoder: 12-layer Llama-MoE (64 experts top-6 + 2 shared), "
|
||||
"bf16 weights and activations, full rotary MHA, with the DeepEncoder "
|
||||
"(SAM ViT-B + CLIP ViT-L) vision tower")
|
||||
#endif
|
||||
@@ -128,6 +128,7 @@ public:
|
||||
int lora_root(const char* native, const char* spellings);
|
||||
int lora_alias(const char* native, const char* from, const char* to, int64_t from_lo,
|
||||
int64_t from_hi, int64_t to_lo);
|
||||
int drafter_short_block(int64_t block);
|
||||
int declare_encoder(const RadEncoderDecl* d);
|
||||
int declare_generator(const RadGeneratorDecl* d);
|
||||
int declare_audio_generator(const RadAudioGenDecl* d);
|
||||
@@ -140,6 +141,7 @@ public:
|
||||
int op_reads (rad_op h, const rad_buf* b, int n);
|
||||
int op_writes(rad_op h, const rad_buf* b, int n);
|
||||
int buf_concurrent(rad_buf b);
|
||||
int lane1_window(bool end);
|
||||
int weight_shard_span(rad_weight w, int64_t lo, int64_t hi);
|
||||
int weight_shard_span_parts(rad_weight w, const int64_t* lo, const int64_t* hi,
|
||||
const int64_t* total, int n);
|
||||
@@ -220,6 +222,8 @@ private:
|
||||
/* Buffers touched from the second lane (rad_buf_concurrent). Their declared op range does not
|
||||
* bound when their bytes are in use, so they are live for the whole program. */
|
||||
std::set<rad_buf> concurrent_bufs_;
|
||||
/* The second lane's window (rad_lane1_window_begin), first and last op handle; -1 when none. */
|
||||
int32_t lane1_w0_ = -1, lane1_w1_ = -1;
|
||||
|
||||
/* Parallel to prog_.kv_groups: where in the op list the group was declared, and the op found
|
||||
* to consume it. Declaration order is the only link between an op and a group; see
|
||||
@@ -254,7 +258,5 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
|
||||
/* The same walk as JSON, for the server's Model view, grouped by (op, band table): an op declared
|
||||
* once per layer with one bucket table is one row with a count. */
|
||||
std::string dump_graph_json(const Program& p);
|
||||
void dump_graph (const Program& p, FILE* out,
|
||||
const std::vector<std::string>* errors = nullptr);
|
||||
|
||||
} /* namespace rad */
|
||||
+176
-8
@@ -87,6 +87,7 @@ const char* bld_kv_kind_name(int k) {
|
||||
case RAD_KV_WINDOW: return "window";
|
||||
case RAD_KV_LINEAR: return "linear";
|
||||
case RAD_KV_CONV: return "conv";
|
||||
case RAD_KV_RING: return "ring";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
@@ -336,7 +337,7 @@ rad_buf Builder::decl_buffer(const char* name, const RadBufDecl* d) {
|
||||
rad_kvgroup Builder::decl_kv_group(const char* name, const RadKVGroupDecl* d) {
|
||||
if (finished_) return err(RAD_E_STATE, "decl_kv_group('%s') after declare finished", name ? name : "");
|
||||
if (!name || !*name || !d) return err(RAD_E_INVAL, "decl_kv_group: null name or declaration");
|
||||
if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_CONV)
|
||||
if (d->kind < RAD_KV_FULL || d->kind > RAD_KV_RING)
|
||||
return err(RAD_E_INVAL, "kv group '%s': unknown kind %d", name, d->kind);
|
||||
|
||||
std::string n = scoped(name);
|
||||
@@ -840,6 +841,26 @@ int Builder::buf_concurrent(rad_buf b) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* See rad_lane1_window_begin. The window is the ops declared between the two calls. */
|
||||
int Builder::lane1_window(bool end) {
|
||||
if (finished_) { err(RAD_E_STATE, "rad_lane1_window after declare finished"); return RAD_E_STATE; }
|
||||
const int32_t next = (int32_t)prog_.ops.size(); /* the next op's handle */
|
||||
if (!end) {
|
||||
if (lane1_w0_ >= 0) {
|
||||
err(RAD_E_STATE, "rad_lane1_window_begin called twice: one window a program");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
lane1_w0_ = next;
|
||||
} else {
|
||||
if (lane1_w0_ < 0 || lane1_w1_ >= 0 || next - 1 < lane1_w0_) {
|
||||
err(RAD_E_STATE, "rad_lane1_window_end without a begin, twice, or around no op");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
lane1_w1_ = next - 1;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* See rad_weight_shard_span. Checked against the declaration here, where the plugin can be named;
|
||||
* the loader checks it against the container. */
|
||||
int Builder::weight_shard_span(rad_weight h, int64_t lo, int64_t hi) {
|
||||
@@ -923,7 +944,7 @@ int Builder::kv_group_zero(rad_kvgroup h) {
|
||||
* state is saved and cleared on every rank, so a zero-sized one would mismatch those
|
||||
* copies. */
|
||||
const int kind = prog_.kv_groups[h].decl.kind;
|
||||
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW) {
|
||||
if (kind != RAD_KV_FULL && kind != RAD_KV_WINDOW && kind != RAD_KV_RING) {
|
||||
err(RAD_E_INVAL, "kv group '%s': kv_group_zero on a group that is not paged",
|
||||
prog_.kv_groups[h].name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
@@ -942,7 +963,10 @@ int Builder::kv_group_replicated(rad_kvgroup h) {
|
||||
err(RAD_E_STATE, "kv_group_replicated after declare finished");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (h == 0 || h >= prog_.kv_groups.size()) return RAD_E_INVAL;
|
||||
if (h == 0 || h >= prog_.kv_groups.size()) {
|
||||
err(RAD_E_INVAL, "kv_group_replicated: %u is not a declared KV group", (unsigned)h);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* Paged groups only: the tiers move blocks. A linear or conv group's state travels in the
|
||||
* checkpoint store, which has no such window. */
|
||||
const int kind = prog_.kv_groups[h].decl.kind;
|
||||
@@ -1204,6 +1228,11 @@ int Builder::declare_encoder(const RadEncoderDecl* d) {
|
||||
(long long)d->n_embd);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->one_grid != 0 && d->one_grid != 1) {
|
||||
err(RAD_E_INVAL, "declare_encoder '%s': one_grid %d is neither 0 nor 1", nm,
|
||||
(int)d->one_grid);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
slot = *d;
|
||||
slot_name = nm;
|
||||
slot.name = nullptr; /* the plugin's storage; the name is the copy */
|
||||
@@ -1389,7 +1418,12 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
: prog_.generator.layout != 0 ? "an image generator" : "a video generator");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (!d->tmpl || !std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}")) {
|
||||
if (!d->tmpl && !d->tmpl_plain) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': no prompt template (tmpl or tmpl_plain)",
|
||||
nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->tmpl && (!std::strstr(d->tmpl, "{input}") || !std::strstr(d->tmpl, "{instructions}"))) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl needs {instructions} and {input}", nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
@@ -1399,6 +1433,45 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
"instructions and needs {input} alone", nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* References: a template with both of its slots, an item with one transcript before its one
|
||||
* clip, and the clips' geometry; read whole by one branch's prompt (an unconditional branch
|
||||
* would need references of its own). */
|
||||
if (d->tmpl_ref) {
|
||||
auto once = [](const char* t, const char* k) {
|
||||
const char* a = t ? std::strstr(t, k) : nullptr;
|
||||
return a && !std::strstr(a + 1, k);
|
||||
};
|
||||
const char* au = d->ref_item ? std::strstr(d->ref_item, "{audio}") : nullptr;
|
||||
const char* tx = d->ref_item ? std::strstr(d->ref_item, "{text}") : nullptr;
|
||||
if (!once(d->tmpl_ref, "{references}") || !once(d->tmpl_ref, "{input}") ||
|
||||
std::strstr(d->tmpl_ref, "{instructions}") || !once(d->ref_item, "{audio}") ||
|
||||
!once(d->ref_item, "{text}") || !au || !tx || tx > au) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': tmpl_ref needs {references} and "
|
||||
"{input} once each, and ref_item {text} before its one {audio}", nm);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->branches != 1 || !d->prompt_whole || d->ref_rate <= 0 || d->ref_hop <= 0 ||
|
||||
d->ref_max <= 0 || d->ref_max_samples < d->ref_hop) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': references are read by a model of one "
|
||||
"branch from whole prompts, clips at a rate (%lld Hz) in frames of "
|
||||
"%lld samples, at most %d of them and %lld samples a request", nm,
|
||||
(long long)d->ref_rate, (long long)d->ref_hop, (int)d->ref_max,
|
||||
(long long)d->ref_max_samples);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (d->branches != 0 && d->branches != 1 && d->branches != 2) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': branches is %d; a request runs 1 sequence "
|
||||
"or 2 (0 means 2)", nm, (int)d->branches);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* One branch has no unconditional prompt to render and no guidance to apply. */
|
||||
if (d->branches == 1 && (d->neg_tmpl || d->default_cfg != 1.0)) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': a model of one branch has no "
|
||||
"unconditional template and no guidance (default_cfg %g)", nm,
|
||||
d->default_cfg);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->neg_tmpl && !d->prompt_whole) {
|
||||
err(RAD_E_INVAL, "declare_audio_generator '%s': an unconditional template makes branches "
|
||||
"of different lengths, which step together only as whole prompts; set "
|
||||
@@ -1476,15 +1549,24 @@ int Builder::declare_audio_generator(const RadAudioGenDecl* d) {
|
||||
!buf_ok(d->audio_out, RAD_F32, win_samples * d->channels, "audio_out"))
|
||||
return RAD_E_INVAL;
|
||||
prog_.agen_str.name = nm;
|
||||
prog_.agen_str.tmpl = d->tmpl;
|
||||
prog_.agen_str.tmpl = d->tmpl ? d->tmpl : "";
|
||||
prog_.agen_str.tmpl_plain = d->tmpl_plain ? d->tmpl_plain : "";
|
||||
prog_.agen_str.neg_tmpl = d->neg_tmpl ? d->neg_tmpl : "";
|
||||
prog_.agen_str.tmpl_ref = d->tmpl_ref ? d->tmpl_ref : "";
|
||||
prog_.agen_str.ref_item = d->tmpl_ref && d->ref_item ? d->ref_item : "";
|
||||
prog_.audio_gen = *d;
|
||||
/* As for the image generator: the Program is moved after declare; strings live in agen_str. */
|
||||
prog_.audio_gen.name = nullptr;
|
||||
prog_.audio_gen.tmpl = nullptr;
|
||||
prog_.audio_gen.tmpl_plain = nullptr;
|
||||
prog_.audio_gen.neg_tmpl = nullptr;
|
||||
prog_.audio_gen.tmpl_ref = nullptr;
|
||||
prog_.audio_gen.ref_item = nullptr;
|
||||
/* Without references the clips' geometry is nothing: the driver stages none. */
|
||||
if (!d->tmpl_ref) {
|
||||
prog_.audio_gen.ref_rate = prog_.audio_gen.ref_hop = prog_.audio_gen.ref_max_samples = 0;
|
||||
prog_.audio_gen.ref_max = 0;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1771,6 +1853,13 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
|
||||
(long long)d->proposal_pitch);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (d->kind == RAD_DRAFT_BLOCK && d->proposal_pitch > 0 && d->proposal_pitch < d->depth) {
|
||||
err(RAD_E_INVAL, "declare_drafter '%s': proposal_pitch %lld under depth %d. A block pass "
|
||||
"writes each sequence's %d proposals into one row of the proposal buffer, "
|
||||
"so a row must hold them.", nm, (long long)d->proposal_pitch, d->depth,
|
||||
d->depth);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* A block pass embeds the mask id at every unfilled position, so it needs one. */
|
||||
if (d->kind == RAD_DRAFT_BLOCK && d->mask_token < 0) {
|
||||
err(RAD_E_INVAL, "declare_drafter '%s': RAD_DRAFT_BLOCK with no mask_token. Every "
|
||||
@@ -1814,7 +1903,11 @@ int Builder::declare_drafter(const RadDrafterDecl* d) {
|
||||
prog_.drafter_name = nm;
|
||||
prog_.drafter.name = nullptr;
|
||||
prog_.drafter.block = block;
|
||||
if (prog_.drafter.proposal_pitch == 0) prog_.drafter.proposal_pitch = 1;
|
||||
/* A block drafter's proposal row holds its whole block's tokens, and the engine reads row s
|
||||
* at s * pitch (a short block fills only its front), so its pitch defaults to depth; a serial
|
||||
* one writes a token a pass, at pitch 1 by default. */
|
||||
if (prog_.drafter.proposal_pitch == 0)
|
||||
prog_.drafter.proposal_pitch = prog_.drafter.kind == RAD_DRAFT_BLOCK ? prog_.drafter.depth : 1;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -1906,6 +1999,33 @@ int Builder::lora_alias(const char* native, const char* from, const char* to, in
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* A block drafter's shorter block (rad_builder.h). Validated at declare: the core stages the block
|
||||
* from it, and a block the plugin did not declare its ops at would fail the step. */
|
||||
int Builder::drafter_short_block(int64_t block) {
|
||||
if (finished_) {
|
||||
err(RAD_E_STATE, "drafter_short_block after declare finished");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (prog_.drafter.kind != RAD_DRAFT_BLOCK) {
|
||||
err(RAD_E_STATE, "drafter_short_block: %s. Only a BLOCK drafter proposes a block; declare "
|
||||
"it with rad_declare_drafter first.",
|
||||
prog_.drafter.kind == RAD_DRAFT_NONE ? "no drafter is declared"
|
||||
: "the declared drafter is a SERIAL head");
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
const int64_t full = prog_.drafter.block > 0 ? prog_.drafter.block : prog_.drafter.depth + 1;
|
||||
const int64_t lead = full - prog_.drafter.depth; /* rows ahead of the proposing ones */
|
||||
if (block >= full || block - lead < 1) {
|
||||
err(RAD_E_INVAL, "drafter_short_block '%s': %lld rows. The short block must be shorter "
|
||||
"than the drafter's own (%lld) and still propose a token (more than %lld "
|
||||
"rows).", prog_.drafter_name.c_str(), (long long)block, (long long)full,
|
||||
(long long)lead);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
prog_.drafter_short_block = block;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
void Builder::note_v(const char* f, va_list ap) {
|
||||
char msg[1024];
|
||||
vsnprintf(msg, sizeof msg, f ? f : "", ap);
|
||||
@@ -2108,7 +2228,8 @@ void Builder::finish_kv_groups() {
|
||||
KVGroupInfo& gi = prog_.kv_groups[g];
|
||||
const RadKVGroupDecl& d = gi.decl;
|
||||
|
||||
if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW) && gi.block_size == 0) {
|
||||
if ((d.kind == RAD_KV_FULL || d.kind == RAD_KV_WINDOW || d.kind == RAD_KV_RING) &&
|
||||
gi.block_size == 0) {
|
||||
/* The plugin may never have asked; the manifest still needs the answer. */
|
||||
kv_block_size((rad_kvgroup)g);
|
||||
}
|
||||
@@ -2121,6 +2242,7 @@ void Builder::finish_kv_groups() {
|
||||
switch (d.kind) {
|
||||
case RAD_KV_FULL:
|
||||
case RAD_KV_WINDOW:
|
||||
case RAD_KV_RING:
|
||||
/* One block holds K and V for block_size tokens, the block manager's unit. */
|
||||
gi.bytes_per_block =
|
||||
rad_dtype_bytes(d.dtype, 2 * gi.block_size * elem_n_head * d.head_dim) * n_bound;
|
||||
@@ -2167,6 +2289,10 @@ void Builder::finish_buffer_liveness() {
|
||||
/* A second lane, signalled by any concurrent buffer, gets a second scratch region
|
||||
* (Program::scratch_regions). */
|
||||
prog_.scratch_regions = concurrent_bufs_.empty() ? 1 : 2;
|
||||
if (lane1_w0_ >= 0 && lane1_w1_ < 0)
|
||||
err(RAD_E_STATE, "rad_lane1_window_begin without rad_lane1_window_end");
|
||||
prog_.lane1_w0 = lane1_w1_ >= 0 ? lane1_w0_ : -1;
|
||||
prog_.lane1_w1 = lane1_w1_;
|
||||
|
||||
/* Each buffer's first and last declaring op, in one pass over the op lists. */
|
||||
const size_t nb = prog_.buffers.size();
|
||||
@@ -2184,11 +2310,19 @@ void Builder::finish_buffer_liveness() {
|
||||
* rule); a buffer on the second lane, whose declared range does not bound when its bytes
|
||||
* are in use; and one with no declared use, since an op may issue any handle in any
|
||||
* order (--debug-graph reports the cost). */
|
||||
if (b.decl.kind != RAD_BUF_TRANSIENT || concurrent_bufs_.count((rad_buf)i) || first[i] < 0) {
|
||||
if (b.decl.kind != RAD_BUF_TRANSIENT || first[i] < 0 ||
|
||||
(concurrent_bufs_.count((rad_buf)i) && lane1_w1_ < 0)) {
|
||||
b.first_def = 0;
|
||||
b.last_use = last_op;
|
||||
continue;
|
||||
}
|
||||
/* A concurrent buffer under a declared window (rad_lane1_window_begin): live across the
|
||||
* window, when lane 1 may touch it, and over its own uses. */
|
||||
if (concurrent_bufs_.count((rad_buf)i)) {
|
||||
b.first_def = std::min(first[i], lane1_w0_);
|
||||
b.last_use = std::max(last[i], lane1_w1_);
|
||||
continue;
|
||||
}
|
||||
b.first_def = first[i];
|
||||
b.last_use = last[i];
|
||||
|
||||
@@ -2199,6 +2333,25 @@ void Builder::finish_buffer_liveness() {
|
||||
* output likewise: the engine reads it after the last op. */
|
||||
if ((rad_buf)i == prog_.logits_buf || (rad_buf)i == prog_.pooled_buf) b.last_use = last_op;
|
||||
}
|
||||
|
||||
/* Region 1 holds what an op the second lane may issue asks for (Program::scratch_bytes_lane1):
|
||||
* every transient buffer of such an op is concurrent (Ctx::lane1_ rule 3). Ctx::issue refuses a
|
||||
* larger request on lane 1 by name, so an op that breaks the rule fails rather than overruns. */
|
||||
prog_.scratch_bytes_lane1 = 0;
|
||||
if (prog_.scratch_regions > 1)
|
||||
for (size_t o = 1; o < prog_.ops.size() && o < op_bufs_.size(); ++o) {
|
||||
bool lane1 = true;
|
||||
for (const std::vector<rad_buf>* v : { &op_bufs_[o].reads, &op_bufs_[o].writes })
|
||||
for (rad_buf h : *v)
|
||||
if (prog_.buffers[h].decl.kind == RAD_BUF_TRANSIENT && !concurrent_bufs_.count(h))
|
||||
lane1 = false;
|
||||
if (!lane1) continue;
|
||||
for (const Band& bd : prog_.ops[o].bands)
|
||||
if (bd.dom[RAD_DOMAIN_DEVICE] &&
|
||||
bd.dom[RAD_DOMAIN_DEVICE].scratch_bytes > prog_.scratch_bytes_lane1)
|
||||
prog_.scratch_bytes_lane1 = bd.dom[RAD_DOMAIN_DEVICE].scratch_bytes;
|
||||
}
|
||||
if (prog_.scratch_bytes_lane1 > prog_.scratch_bytes) prog_.scratch_bytes_lane1 = prog_.scratch_bytes;
|
||||
}
|
||||
|
||||
int Builder::finish() {
|
||||
@@ -2331,6 +2484,16 @@ int rad_buf_concurrent(RadBuilder* b, rad_buf buf) {
|
||||
return B(b)->buf_concurrent(buf);
|
||||
}
|
||||
|
||||
int rad_lane1_window_begin(RadBuilder* b) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->lane1_window(false);
|
||||
}
|
||||
|
||||
int rad_lane1_window_end(RadBuilder* b) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->lane1_window(true);
|
||||
}
|
||||
|
||||
int rad_weight_shard_span(RadBuilder* b, rad_weight w, int64_t lo, int64_t hi) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->weight_shard_span(w, lo, hi);
|
||||
@@ -2390,6 +2553,11 @@ int rad_lora_alias(RadBuilder* b, const char* native, const char* from, const ch
|
||||
|
||||
int rad_chain_on(void) { return rad_dev_chain_enabled(); }
|
||||
|
||||
int rad_drafter_short_block(RadBuilder* b, int64_t block) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->drafter_short_block(block);
|
||||
}
|
||||
|
||||
int rad_declare_encoder(RadBuilder* b, const RadEncoderDecl* d) {
|
||||
if (!b) return RAD_E_INVAL;
|
||||
return B(b)->declare_encoder(d);
|
||||
|
||||
@@ -364,12 +364,6 @@ std::string dump_graph_str(const Program& p, const std::vector<std::string>* err
|
||||
return s;
|
||||
}
|
||||
|
||||
void dump_graph(const Program& p, FILE* out, const std::vector<std::string>* errors) {
|
||||
std::string s = dump_graph_str(p, errors);
|
||||
fwrite(s.data(), 1, s.size(), out ? out : stderr);
|
||||
fflush(out ? out : stderr);
|
||||
}
|
||||
|
||||
/* ================================================================== the graph, as JSON
|
||||
*
|
||||
* dump_graph_str's content and more, for the server's Model view. It walks the same Program with
|
||||
|
||||
@@ -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,12 @@ static const Flag g_flags[] = {
|
||||
{ "--kv-cache-dtype", "T", "bf16 | fp8 | fp8_v4 | k6_v4 -- fp8 halves what a token of\n"
|
||||
"context costs; fp8_v4 keeps V in 4 bits (0.78 of fp8), k6_v4\n"
|
||||
"also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" },
|
||||
{ "--state-cache-dtype", "T", "f32 (default) | f16 -- the recurrent state cache (delta net):\n"
|
||||
"f16 halves the state pool, its checkpoints and its traffic,\n"
|
||||
"and is lossy; the qwen35 plugins serve it" },
|
||||
{ "--attn-prefill-fp8", "MODE", "off (default) | qk | pv | both -- the prefill attention's\n"
|
||||
"Q.K^T, P.V or both as e4m3 WMMA over an fp8, fp8_v4 or\n"
|
||||
"k6_v4 cache: faster at long context, and lossy" },
|
||||
{ "--host-pool-mib", "N", "pinned host tier" },
|
||||
{ "--host-headroom-mib", "N", "host RAM to leave free for the system when radiance\n"
|
||||
" pins its host memory at startup (default 4096)" },
|
||||
@@ -155,6 +165,13 @@ static const Flag g_flags[] = {
|
||||
" own operating point, which the plugin states. A container\n"
|
||||
" with no draft head is unaffected -- auto resolves to 0." },
|
||||
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
|
||||
{ "--draft-short-from", "N", "a block drafter that also serves a shorter block runs it\n"
|
||||
"from N decoding sequences on (0 never, the default): the\n"
|
||||
"long block pays at one sequence, the short one at many" },
|
||||
{ "--draft-coupling", "MODE", "off (default) | on -- a linear MTP drafter samples each proposal\n"
|
||||
" from its own shortlist and the sampler couples the target's draw\n"
|
||||
" to it: more accepted drafts on sampled requests, the same output\n"
|
||||
" law, other tokens than off for a fixed seed" },
|
||||
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
|
||||
|
||||
{ "--host", "ADDR", "listen address" },
|
||||
@@ -438,6 +455,12 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
else if (!std::strcmp(v, "wht6")) c->tp_wire_exact = 0;
|
||||
else { RAD_ERR("--tp-wire takes exact or wht6, not '%s'", v); return RAD_E_INVAL; }
|
||||
}
|
||||
else if (S("--tp-attn-split")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "heads")) c->tp_attn_rows = 0;
|
||||
else if (!std::strcmp(v, "rows")) c->tp_attn_rows = 1;
|
||||
else { RAD_ERR("--tp-attn-split takes heads or rows, not '%s'", v); return RAD_E_INVAL; }
|
||||
}
|
||||
else if (S("--p2p")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "auto")) c->p2p = RAD_P2P_AUTO;
|
||||
@@ -489,6 +512,25 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
c->kv_cache_dtype = v;
|
||||
}
|
||||
else if (S("--state-cache-dtype")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (std::strcmp(v, "f32") && std::strcmp(v, "f16")) {
|
||||
RAD_ERR("--state-cache-dtype takes f32 or f16, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
c->state_cache_dtype = v;
|
||||
}
|
||||
else if (S("--attn-prefill-fp8")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "off")) c->attn_prefill_fp8 = 0;
|
||||
else if (!std::strcmp(v, "qk")) c->attn_prefill_fp8 = RAD_ATTN_FP8_QK;
|
||||
else if (!std::strcmp(v, "pv")) c->attn_prefill_fp8 = RAD_ATTN_FP8_PV;
|
||||
else if (!std::strcmp(v, "both")) c->attn_prefill_fp8 = RAD_ATTN_FP8_QK | RAD_ATTN_FP8_PV;
|
||||
else {
|
||||
RAD_ERR("--attn-prefill-fp8 takes off, qk, pv or both, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--host-pool-mib")) { if (!num(0, INT64_MAX, &c->host_pool_mib)) return RAD_E_INVAL; }
|
||||
else if (S("--embedding-placement") || S("--ngram-placement")) {
|
||||
const bool emb = S("--embedding-placement");
|
||||
@@ -638,6 +680,16 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-short-from")) { if (!num(0, INT32_MAX, &c->draft_short_from)) return RAD_E_INVAL; }
|
||||
else if (S("--draft-coupling")) {
|
||||
if (!(v = need(i))) return RAD_E_INVAL;
|
||||
if (!std::strcmp(v, "off")) c->draft_coupling = false;
|
||||
else if (!std::strcmp(v, "on")) c->draft_coupling = true;
|
||||
else {
|
||||
RAD_ERR("--draft-coupling takes off or on, not '%s'", v);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
else if (S("--draft-model")) {
|
||||
/* Refused, not ignored: separate draft models are not supported (spec §10), and the
|
||||
* drafter comes from the container (rad-convert --draft-model merges one in; an MTP
|
||||
@@ -971,6 +1023,16 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
const char* attn_prefill_fp8_name(int bits) {
|
||||
switch (bits) {
|
||||
case 0: return "off";
|
||||
case RAD_ATTN_FP8_QK: return "qk";
|
||||
case RAD_ATTN_FP8_PV: return "pv";
|
||||
case RAD_ATTN_FP8_QK | RAD_ATTN_FP8_PV: return "both";
|
||||
}
|
||||
return "?";
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the startup report's rows */
|
||||
namespace {
|
||||
|
||||
@@ -1010,6 +1072,7 @@ const ShowRow kShow[] = {
|
||||
return or_none(s, "every library found"); } },
|
||||
{ "--tp", [](const Config& c) { return num(c.tp); } },
|
||||
{ "--tp-wire", [](const Config& c) { return std::string(c.tp_wire_exact ? "exact" : "wht6"); } },
|
||||
{ "--tp-attn-split", [](const Config& c) { return std::string(c.tp_attn_rows ? "rows" : "heads"); } },
|
||||
{ "--tp-wire-min-kb", [](const Config& c) { return num(c.tp_wire_min_kb); } },
|
||||
{ "--p2p", [](const Config& c) {
|
||||
return std::string(c.p2p == RAD_P2P_ON ? "on" : c.p2p == RAD_P2P_OFF ? "off" : "auto"); } },
|
||||
@@ -1025,6 +1088,9 @@ const ShowRow kShow[] = {
|
||||
{ "--rope-scaling", [](const Config& c) { return or_none(c.rope_scaling, "the checkpoint's own"); } },
|
||||
{ "--gpu-headroom-mib", [](const Config& c) { return num(c.gpu_headroom_mib); } },
|
||||
{ "--kv-cache-dtype", [](const Config& c) { return c.kv_cache_dtype; } },
|
||||
{ "--state-cache-dtype", [](const Config& c) { return c.state_cache_dtype; } },
|
||||
{ "--attn-prefill-fp8", [](const Config& c) {
|
||||
return std::string(attn_prefill_fp8_name(c.attn_prefill_fp8)); } },
|
||||
{ "--host-pool-mib", [](const Config& c) { return num(c.host_pool_mib); } },
|
||||
{ "--host-headroom-mib", [](const Config& c) { return num(c.host_headroom_mib); } },
|
||||
{ "--embedding-placement", [](const Config& c) { return std::string(table_placement_name(c.embedding_placement)); } },
|
||||
@@ -1061,6 +1127,9 @@ const ShowRow kShow[] = {
|
||||
{ "--checkpoint-policy", [](const Config& c) { return c.checkpoint_policy; } },
|
||||
{ "--num-speculative-tokens", [](const Config& c) { return c.n_spec < 0 ? std::string("auto") : num(c.n_spec); } },
|
||||
{ "--draft-window", [](const Config& c) { return std::string(draft_window_name(c.draft_window)); } },
|
||||
{ "--draft-short-from", [](const Config& c) {
|
||||
return c.draft_short_from > 0 ? num(c.draft_short_from) : std::string("0 (never)"); } },
|
||||
{ "--draft-coupling", [](const Config& c) { return onoff(c.draft_coupling); } },
|
||||
{ "--draft-model", [](const Config&) { return std::string("not implemented (the container's own drafter)"); } },
|
||||
{ "--host", [](const Config& c) { return c.host; } },
|
||||
{ "--port", [](const Config& c) { return num(c.port); } },
|
||||
|
||||
+24
-39
@@ -1,18 +1,5 @@
|
||||
/* cvec.cpp -- loading and validating a GGUF control vector (core/cvec.h).
|
||||
*
|
||||
* The format is llama.cpp's `controlvector` package: one `direction.<l>` tensor of unit f32 per
|
||||
* layer, plus three metadata keys. The reader is core/text/gguf.cpp, which already mmaps a GGUF
|
||||
* and computes tensor byte sizes, so nothing here parses bytes by hand.
|
||||
*
|
||||
* The published package (hf.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection) is what the checks
|
||||
* below are written against, and its own JSON states the operation's parameters:
|
||||
*
|
||||
* {"mode": "project", "dir": "per-layer", "scale": 1.0, "layer_range": [4, 44], ...}
|
||||
*
|
||||
* so a file is only accepted for a model whose hidden size equals the directions' width and whose
|
||||
* architecture the file names. Everything else is refused at startup, by name, rather than
|
||||
* steered along a direction from another residual basis.
|
||||
*/
|
||||
/* cvec.cpp -- loading and validating a GGUF control vector (core/cvec.h). The reader is
|
||||
* core/text/gguf.cpp, which maps the file and sizes its tensors. */
|
||||
#include "cvec.h"
|
||||
|
||||
#include "text/gguf.h"
|
||||
@@ -98,10 +85,10 @@ int control_vector_discover(const std::string& model_path, const std::string& ar
|
||||
}
|
||||
|
||||
|
||||
/* The package's own JSON, if it is beside the vector: `{"mode": "project", "scale": 1.0,
|
||||
* "layer_range": [4, 44]}` is what the published Flash-Next vector ships. It is the only place
|
||||
* the operation's parameters are stated, so they are read from there rather than configured; a
|
||||
* malformed or absent file only means the defaults below. */
|
||||
/* The package's own JSON beside the vector (`<stem>.json`), the only place the operation's
|
||||
* parameters are stated: `{"mode": "project", "scale": 1.0, "layer_range": [4, 44]}` for the
|
||||
* published Flash-Next vector. Absent, the defaults apply. A file that is not JSON or names a mode
|
||||
* other than `project` is refused: the directions were tuned for that operation. */
|
||||
namespace {
|
||||
|
||||
struct PackageJson {
|
||||
@@ -109,8 +96,8 @@ struct PackageJson {
|
||||
float scale = 1.0f;
|
||||
};
|
||||
|
||||
PackageJson read_package_json(const std::string& gguf_path) {
|
||||
PackageJson out;
|
||||
int read_package_json(const std::string& gguf_path, PackageJson* out, std::string* why) {
|
||||
*out = PackageJson{};
|
||||
std::string stem = gguf_path;
|
||||
const size_t dot = stem.find_last_of('.');
|
||||
const size_t slash = stem.find_last_of("/\\");
|
||||
@@ -118,28 +105,28 @@ PackageJson read_package_json(const std::string& gguf_path) {
|
||||
stem = stem.substr(0, dot);
|
||||
const std::string path = stem + ".json";
|
||||
std::ifstream f(path);
|
||||
if (!f) return out;
|
||||
if (!f) return RAD_OK;
|
||||
try {
|
||||
const nlohmann::json j = nlohmann::json::parse(f);
|
||||
if (const auto m = j.find("mode"); m != j.end() && m->is_string() &&
|
||||
m->get<std::string>() != "project") {
|
||||
RAD_WARN("control vector: %s says mode '%s'; only 'project' is implemented, so the "
|
||||
"defaults apply", path.c_str(), m->get<std::string>().c_str());
|
||||
return out;
|
||||
*why = "control vector " + path + ": mode '" + m->get<std::string>() +
|
||||
"'; only 'project' is implemented";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (const auto r = j.find("layer_range"); r != j.end() && r->is_array() && r->size() == 2 &&
|
||||
(*r)[0].is_number_integer() &&
|
||||
(*r)[1].is_number_integer()) {
|
||||
out.first = (*r)[0].get<int>();
|
||||
out.last = (*r)[1].get<int>();
|
||||
out->first = (*r)[0].get<int>();
|
||||
out->last = (*r)[1].get<int>();
|
||||
}
|
||||
if (const auto s = j.find("scale"); s != j.end() && s->is_number())
|
||||
out.scale = (float) s->get<double>();
|
||||
out->scale = (float) s->get<double>();
|
||||
} catch (const std::exception& e) {
|
||||
RAD_WARN("control vector: %s is not readable JSON (%s); the defaults apply", path.c_str(),
|
||||
e.what());
|
||||
*why = "control vector " + path + ": not readable JSON (" + e.what() + ")";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return out;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
@@ -206,16 +193,14 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_
|
||||
}
|
||||
if (n_dir == 0) return fail("control vector " + path + ": the file holds no directions");
|
||||
|
||||
/* The package's parameters: its JSON, else the published selection where the file covers it,
|
||||
* else every direction the file carries. A deployment therefore has nothing to configure, and
|
||||
* a file published with a different selection states it itself. */
|
||||
const PackageJson pj = read_package_json(path);
|
||||
/* The package's parameters: its JSON, else every direction the file carries at scale 1, as
|
||||
* llama.cpp applies a control vector given no layer range. */
|
||||
PackageJson pj;
|
||||
std::string pj_why;
|
||||
if (const int prc = read_package_json(path, &pj, &pj_why); prc != RAD_OK) return fail(pj_why);
|
||||
int first = pj.first, last = pj.last;
|
||||
float scale = pj.scale;
|
||||
if (last < 0) {
|
||||
if (n_model_layers >= 45 && dir_last >= 44) { first = 4; last = 44; }
|
||||
else { first = (int) dir_first; last = (int) dir_last; }
|
||||
}
|
||||
if (last < 0) { first = (int) dir_first; last = (int) dir_last; }
|
||||
if (first < 1 || last < first)
|
||||
return fail("control vector " + path + ": the layer range " + std::to_string(first) + ":" +
|
||||
std::to_string(last) + " is empty");
|
||||
|
||||
+18
-32
@@ -1,36 +1,26 @@
|
||||
/* cvec.h -- control vectors: one GGUF direction per layer, projected out of the residual stream.
|
||||
*
|
||||
* ============================== what it is ==============================
|
||||
* The format is llama.cpp's `controlvector` GGUF: `direction.<l>` tensors of f32, n_embd wide. The
|
||||
* operation is llama.cpp's `--cvec-mode project`
|
||||
*
|
||||
* The package at huggingface.co/Cudecnik/Qwen3.8-Flash-Next-refusal-projection carries one unit
|
||||
* direction per layer (`direction.1` .. `direction.47`, 2560 f32 each) and the configuration its
|
||||
* authors selected: the llama.cpp `--cvec-mode project` operation
|
||||
* h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l| * package scale
|
||||
*
|
||||
* h <- h - s_l (h . v_l) v_l v_l = d_l / |d_l|, s_l = |d_l|
|
||||
* applied by an architecture plugin that declares RadArchProbe::control_vector_ok (qwen4exp_fp8
|
||||
* issues `hc_project` on every stream of its gated residual). The layer range and scale come from
|
||||
* the package's JSON beside the file; without one, every direction the file carries steers at
|
||||
* scale 1.
|
||||
*
|
||||
* over layers 4..44, applied to every stream of the gated residual. Strata ports the same
|
||||
* package (`data/experimental-speed-projection`) with the same operation, range and per-request
|
||||
* switch; this is that port for radiance, which has its own graph and cannot use llama.cpp's
|
||||
* patch (arch/qwen4exp_fp8 issues `hc_project` from the op vocabulary instead).
|
||||
* The vector shipped in data/vectors/ is a refusal-direction projection for Qwen3.8-Flash-Next:
|
||||
* with it on, the model declines far fewer requests. It is loaded only with --control-vector, and
|
||||
* each request can name its own choice.
|
||||
*
|
||||
* The vector is a refusal-direction projection: with it on the model declines far fewer requests.
|
||||
* Removing refusals removes a safety behaviour, so the default is OFF and every request names its
|
||||
* own choice, and the file is only read when the engine finds one for this container.
|
||||
*
|
||||
* ============================== compatibility, checked, not assumed ==============================
|
||||
*
|
||||
* Nothing here trusts the file's provenance. A vector is refused unless
|
||||
* A file is refused unless
|
||||
*
|
||||
* - `general.architecture` is `controlvector`,
|
||||
* - `controlvector.model_hint`, when present, names this model's architecture plugin
|
||||
* (`qwen4exp`), since a direction from another architecture's residual basis is noise,
|
||||
* - every tensor is `direction.<l>`, F32, one dimension, and exactly the model's `n_embd`,
|
||||
* - `controlvector.model_hint`, when present, is this model's architecture id,
|
||||
* - every tensor is `direction.<l>`, F32, one dimension, exactly the model's `n_embd`, and
|
||||
* 1 <= l < the model's layer count,
|
||||
* - the layer range lies inside the model and every layer in it has a direction.
|
||||
*
|
||||
* The published Flash-Next vector passes all four against a Flash-Next container: 47 tensors of
|
||||
* 2560 f32, hint `qwen4exp`, range 4..44 of 48 layers. A 27B, Gemma or Qwen3.6 container refuses
|
||||
* it at startup with the reason, rather than serving a model whose hidden states are moved along
|
||||
* an unrelated direction.
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_internal.h"
|
||||
@@ -62,12 +52,9 @@ struct ControlVector {
|
||||
}
|
||||
};
|
||||
|
||||
/* Read and validate `path` against a model of `n_embd` and `n_model_layers`.
|
||||
*
|
||||
* The operation's parameters come with the package, never from a command line: `path`'s own
|
||||
* `<stem>.json` (the JSON the vector is published with) supplies `layer_range` and `scale` when it
|
||||
* says `"mode": "project"`. Without one, the range is the published Qwen3.8-Flash-Next selection
|
||||
* (4..44) where the file has directions there, else every layer the file carries, at scale 1. */
|
||||
/* Read and validate `path` against a model of `n_embd` and `n_model_layers`. `path`'s own
|
||||
* `<stem>.json` supplies `layer_range` and `scale`; one that is not JSON or names a mode other than
|
||||
* `project` is refused. Without it, every layer the file carries steers at scale 1. */
|
||||
int control_vector_load(const std::string& path, const std::string& arch, int64_t n_embd,
|
||||
int64_t n_model_layers, ControlVector* out, std::string* err);
|
||||
|
||||
@@ -77,8 +64,7 @@ int control_vector_load(const std::string& path, const std::string& arch, int64_
|
||||
* already knows the generation-config convention knows this one. */
|
||||
std::string control_vector_sidecar_path(const std::string& model_path);
|
||||
|
||||
/* Resolve `auto`: sets *found to the first candidate that exists and is non-empty, or to "" when
|
||||
* none does. *tried receives the candidates, for the log line that says why the feature is
|
||||
/* Sets *found to the first candidate that exists and is non-empty, or to "" when none does. *tried receives the candidates, for the log line that says why the feature is
|
||||
* unavailable on this deployment. Discovery is a filesystem test only; whether the file is
|
||||
* compatible is control_vector_load's answer. */
|
||||
int control_vector_discover(const std::string& model_path, const std::string& arch,
|
||||
|
||||
+74
-7
@@ -241,6 +241,9 @@ Global& G() {
|
||||
return *g;
|
||||
}
|
||||
|
||||
/* Set by aql_force_host_kargs before the backend starts. */
|
||||
std::atomic<bool> g_force_host_kargs{false};
|
||||
|
||||
std::string agent_isa(hsa_agent_t a) {
|
||||
char name[64] = {0};
|
||||
hsa_agent_get_info(a, HSA_AGENT_INFO_NAME, name);
|
||||
@@ -423,13 +426,10 @@ bool init_devices() {
|
||||
"difference where the slot allows it",
|
||||
i, bus);
|
||||
}
|
||||
/* The fallback on a card that needs none, to measure what reading each dispatch's
|
||||
* arguments across the link costs against the same card's VRAM rings. */
|
||||
const char* force_host_kargs = std::getenv("RADIANCE_DEBUG_AQL_HOST_KARGS");
|
||||
if (force_host_kargs && *force_host_kargs && *force_host_kargs != '0') {
|
||||
if (g_force_host_kargs.load(std::memory_order_acquire) && !g.dev[(size_t)i].host_kargs) {
|
||||
g.dev[(size_t)i].host_kargs = true;
|
||||
RAD_WARN("device: card %d (%s): RADIANCE_DEBUG_AQL_HOST_KARGS puts the kernel argument "
|
||||
"rings in host memory", i, bus);
|
||||
RAD_INFO("device: card %d (%s) keeps kernel arguments in pinned host memory, as a "
|
||||
"test asked", i, bus);
|
||||
}
|
||||
}
|
||||
/* Without the handler a fault falls back to the runtime's own handling, which the
|
||||
@@ -829,7 +829,7 @@ hsa_status_t on_system_event(const hsa_amd_event_t* e, void*) {
|
||||
/* The running kernel and its arguments. A queue's read index stays on a packet until it
|
||||
* completes, so the packet there is in flight. Every pointer-shaped argument word is located
|
||||
* like the address, which names the operand that got a stale or short buffer. Only card
|
||||
* `card`'s queues; arguments are read back through the BAR. */
|
||||
* `card`'s queues; the host reads the arguments at the packet's kernarg_address. */
|
||||
std::lock_guard<std::mutex> sl(G().streams_mu);
|
||||
for (Stream* s : G().streams) {
|
||||
if (s->ord != card) continue;
|
||||
@@ -3049,9 +3049,70 @@ int vres_ord(const void* addr) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* The DRM interface version of card `gpu_id`'s render node, false when it cannot be read. */
|
||||
bool drm_version(uint32_t gpu_id, int* major, int* minor, std::string* name) {
|
||||
/* struct drm_version, a layout fixed since DRM's first release. */
|
||||
struct DrmVersion {
|
||||
int major, minor, patch;
|
||||
size_t name_len;
|
||||
char* name;
|
||||
size_t date_len;
|
||||
char* date;
|
||||
size_t desc_len;
|
||||
char* desc;
|
||||
};
|
||||
const int rm = render_minor(gpu_id);
|
||||
if (rm < 0) return false;
|
||||
char path[64];
|
||||
std::snprintf(path, sizeof path, "/dev/dri/renderD%d", rm);
|
||||
const int fd = open(path, O_RDWR | O_CLOEXEC);
|
||||
if (fd < 0) return false;
|
||||
char nm[32] = {0};
|
||||
DrmVersion v{};
|
||||
v.name = nm;
|
||||
v.name_len = sizeof nm - 1;
|
||||
const bool ok = ioctl(fd, _IOWR('d', 0x00, DrmVersion), &v) == 0;
|
||||
close(fd);
|
||||
if (!ok) return false;
|
||||
*major = v.major;
|
||||
*minor = v.minor;
|
||||
*name = std::string(nm, std::min(v.name_len, sizeof nm - 1));
|
||||
return true;
|
||||
}
|
||||
|
||||
/* Whether hsa_amd_vmem mappings on card `dev` return. From HIP 7.16 (ROCm 10.1) the runtime maps
|
||||
* a vmem handle with DRM_AMDGPU_GEM_VA, asks the kernel to signal a VM timeline syncobj once the
|
||||
* page tables are written, and waits on that point with no timeout. amdgpu reads the timeline
|
||||
* fields of GEM_VA from interface 3.64 (Linux 6.16) on; an older kernel ignores them, never
|
||||
* signals the point, and the first commit waits forever in drm_syncobj_array_wait_timeout. The
|
||||
* ROCm 7.2 runtime maps through the KFD and has no such wait. A card that would hang this way
|
||||
* gets no virtual memory management: its pools are carved whole, as on a driver without it. */
|
||||
bool vmem_maps_return(int dev) {
|
||||
static std::once_flag once[kMaxDevices];
|
||||
static bool ok[kMaxDevices];
|
||||
std::call_once(once[dev], [dev] {
|
||||
ok[dev] = true;
|
||||
int hip = 0;
|
||||
if (hipRuntimeGetVersion(&hip) != hipSuccess || hip < 71600000) return;
|
||||
int major = 0, minor = 0;
|
||||
std::string name;
|
||||
if (!drm_version(G().dev[(size_t)dev].kfd_id, &major, &minor, &name) || name != "amdgpu")
|
||||
return;
|
||||
if (major > 3 || (major == 3 && minor >= 64)) return;
|
||||
ok[dev] = false;
|
||||
RAD_WARN("device %d: this kernel's amdgpu interface is %d.%d, and the HIP %d.%d runtime "
|
||||
"waits after every virtual-memory map for a page-table timeline that amdgpu "
|
||||
"signals only from 3.64 (Linux 6.16) on, so a map here would never return. The "
|
||||
"card runs without virtual memory management; a 6.16 or later kernel restores it",
|
||||
dev, major, minor, hip / 10000000, hip / 100000 % 100);
|
||||
});
|
||||
return ok[dev];
|
||||
}
|
||||
|
||||
int64_t a_vmem_granularity(void) {
|
||||
int dev = 0;
|
||||
if (hipGetDevice(&dev) != hipSuccess || dev < 0 || dev >= (int)G().dev.size()) return 0;
|
||||
if (!vmem_maps_return(dev)) return 0;
|
||||
size_t gran = 0;
|
||||
if (hsa_amd_memory_pool_get_info(G().dev[(size_t)dev].vram,
|
||||
HSA_AMD_MEMORY_POOL_INFO_RUNTIME_ALLOC_REC_GRANULE, &gran) !=
|
||||
@@ -3550,6 +3611,12 @@ const DeviceBackend* aql_backend_if_present(void) {
|
||||
|
||||
int64_t aql_pageable_bytes(void) { return aql::g_pageable_bytes.load(std::memory_order_relaxed); }
|
||||
|
||||
int aql_force_host_kargs(void) {
|
||||
if (aql::G().ok) return RAD_E_STATE;
|
||||
aql::g_force_host_kargs.store(true, std::memory_order_release);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int aql_vmem_device_of(const void* addr, int* dev) {
|
||||
const int d = vres_ord(addr);
|
||||
if (d < 0) return RAD_E_NOTFOUND;
|
||||
|
||||
@@ -38,11 +38,9 @@ extern "C" int rad_event_create_as(RadEvent* out, unsigned flags);
|
||||
extern "C" void rad_dev_host_wrote(void);
|
||||
/* Chained launches: chainable rows run their chained forms (RadKernelChainFn), and the backend
|
||||
* lets a chained kernel (named r4dchain*) wait in its prologue instead of behind the barrier bit.
|
||||
* Only on the AQL backend, whose queues keep the completion counter. On by default where the
|
||||
* model's plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays: the
|
||||
* Gemma 4 31B and 26B) and that drafter decodes speculatively (rad_dev_chain_infer, from the
|
||||
* engine before any row resolves). RADIANCE_CHAIN=0 turns them off and =1 on wherever the backend
|
||||
* chains; `auto` is the default. */
|
||||
* Only on the AQL backend, whose queues keep the completion counter, and only where the model's
|
||||
* plugin measured a gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter
|
||||
* decodes speculatively (rad_dev_chain_infer, from the engine before any row resolves). */
|
||||
extern "C" int rad_dev_chain_enabled(void);
|
||||
extern "C" void rad_dev_chain_infer(int pays);
|
||||
|
||||
@@ -472,6 +470,10 @@ const DeviceBackend* hip_backend_if_present(void);
|
||||
/* The HIP backend with streams, events, copies and fills replaced by AQL packets the engine writes
|
||||
* itself (aql.cpp). Aborts with the reason on a machine it cannot run on. */
|
||||
const DeviceBackend* aql_backend_if_present(void);
|
||||
/* For tests: every card keeps its kernel argument rings and recorded-pass argument blocks in pinned
|
||||
* host memory, the placement a card whose PCI BAR is smaller than its VRAM gets, so that path runs
|
||||
* on any card. Takes effect only before the backend starts; RAD_E_STATE after. */
|
||||
int aql_force_host_kargs(void);
|
||||
/* Bytes copied to or from pageable host memory so far; each such copy is a host wait. */
|
||||
int64_t aql_pageable_bytes(void);
|
||||
/* Fat binaries registered so far, counted whichever backend runs: the registration hooks are this
|
||||
|
||||
@@ -557,7 +557,7 @@ int rad_event_sync(RadEvent e) {
|
||||
}
|
||||
void rad_dev_host_wrote(void) { dev()->host_wrote(); }
|
||||
|
||||
/* Chaining's default, from the engine (rad_dev_chain_infer), and the answer once taken. Only
|
||||
/* Whether launches chain, from the engine (rad_dev_chain_infer), and the answer once taken. Only
|
||||
* where the backend chains: the AQL backend writes the record a chained form reads, while a HIP
|
||||
* launch carries only the kernel's own arguments. */
|
||||
static std::atomic<int> g_chain_pays{0};
|
||||
@@ -569,11 +569,10 @@ void rad_dev_chain_infer(int pays) {
|
||||
int rad_dev_chain_enabled(void) {
|
||||
int on = g_chain.load(std::memory_order_relaxed);
|
||||
if (on < 0) {
|
||||
const char* e = std::getenv("RADIANCE_CHAIN");
|
||||
const bool want = e && *e && std::strcmp(e, "auto") != 0
|
||||
? *e != '0'
|
||||
: g_chain_pays.load(std::memory_order_relaxed) != 0;
|
||||
on = want && std::strcmp(rad::device_backend_name(), "aql") == 0 ? 1 : 0;
|
||||
on = g_chain_pays.load(std::memory_order_relaxed) != 0 &&
|
||||
std::strcmp(rad::device_backend_name(), "aql") == 0
|
||||
? 1
|
||||
: 0;
|
||||
g_chain.store(on, std::memory_order_relaxed);
|
||||
}
|
||||
return on;
|
||||
|
||||
+61
-43
@@ -156,6 +156,7 @@ int Engine::declare_sampler(int rank, RadBuilder* b, int64_t logits_width, bool
|
||||
sc.max_spec = cfg_.n_spec;
|
||||
sc.rank = rank;
|
||||
sc.world_size = cfg_.tp;
|
||||
sc.draft_coupling = cfg_.draft_coupling;
|
||||
RAD_TRY(smp.declare(b, sc));
|
||||
|
||||
/* Where the chain writes the sampled ids. The engine declares it because rad-kbench drives the
|
||||
@@ -354,7 +355,7 @@ int Engine::issue_ahead(const RadBatch** out) {
|
||||
for (int i = 0; i < serial_rows_ && serial_done_ > 0; ++i)
|
||||
sched_.expect_draft(serial_row_[(size_t)i].seq, serial_done_);
|
||||
for (int i = 0; i < block_rows_; ++i)
|
||||
sched_.expect_draft(block_row_[(size_t)i].seq, drafter_.depth);
|
||||
sched_.expect_draft(block_row_[(size_t)i].seq, block_steps_);
|
||||
const RadBatch* nb = sched_.step_next();
|
||||
if (!nb) return RAD_OK;
|
||||
/* Its rows' tokens, positions and slots, advanced on the card behind this step's acceptance
|
||||
@@ -405,13 +406,9 @@ int Engine::step_loop() {
|
||||
int idle = 0;
|
||||
std::vector<uint64_t> cancel;
|
||||
/* Not in KL mode: its scored rows are copied out of the logits buffer after collection, and a
|
||||
* pass issued ahead would overwrite them. A block drafter pipelines only on the card
|
||||
* (engine_draft.cpp); the host's driver stages from the committed sequence. */
|
||||
block_card_ = drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0 && !cfg_.kld() &&
|
||||
!embedding_ && [] { const char* v = std::getenv("RADIANCE_DRAFT_BLOCK_HOST");
|
||||
return !(v && *v && *v != '0'); }();
|
||||
pipelining_ = !cfg_.kld() && !embedding_ && (drafter_.kind != RAD_DRAFT_BLOCK || block_card_) &&
|
||||
(serial_drafting() || block_card_ || cfg_.n_spec <= 0);
|
||||
* pass issued ahead would overwrite them. */
|
||||
pipelining_ = !cfg_.kld() && !embedding_ &&
|
||||
(serial_drafting() || block_drafting() || cfg_.n_spec <= 0);
|
||||
const bool t_on = (int)log_level() >= (int)Log::Debug;
|
||||
/* The next step's forward pass when already issued behind the previous step, before its
|
||||
* readback (Scheduler::step_next). */
|
||||
@@ -456,22 +453,7 @@ int Engine::step_loop() {
|
||||
idle = 0;
|
||||
if (t_on) phase_mark(PH_PLAN);
|
||||
|
||||
/* Zero freshly assigned recurrent slots before the step that reads them. The manager
|
||||
* records the grab but cannot write (StateClear in core/mem/kv.h); the list is empty except
|
||||
* on a sequence's first step. Each rank clears by its own plan: the slot number is the
|
||||
* scheduler's, but the state size depends on the heads this rank holds, which can differ
|
||||
* per rank (rad_arch.h remainder_place). */
|
||||
for (const StateClear& c : ranks_[0]->kv.state_clears()) {
|
||||
for (auto& rk : ranks_) {
|
||||
const KVGroupPlan* gp = rk->kv.plan(c.group);
|
||||
if (!gp || !gp->stateful()) continue;
|
||||
const int64_t bytes = gp->layer_bytes_per_state();
|
||||
for (int64_t l = 0; l < gp->n_layers; ++l)
|
||||
if (void* p = rk->kv.state_ptr(c.group, (int32_t)l, c.slot))
|
||||
rad_memset_async(p, 0, bytes, rk->ctx.stream());
|
||||
}
|
||||
}
|
||||
ranks_[0]->kv.clear_state_clears();
|
||||
clear_fresh_states();
|
||||
|
||||
/* Entries that want logits rows, in BatchBuilder's out_ids order: those with
|
||||
* produces_token, 1 + n_spec rows each. Row and sequence indices differ (a mid-prompt
|
||||
@@ -530,7 +512,7 @@ int Engine::step_loop() {
|
||||
}
|
||||
if (t_on) phase_mark(PH_BEGIN);
|
||||
for (auto& rk : ranks_) {
|
||||
const int s = rk->sampler.build_step(so.reqs);
|
||||
const int s = rk->sampler.build_step(so.reqs, b->step);
|
||||
if (s < 0) { RAD_ERR("sampler build_step: %s", rad_strerror(s)); return s; }
|
||||
/* A request the sampler could not serve is cancelled; the step goes on. */
|
||||
for (uint64_t id : rk->sampler.take_failed()) cancel.push_back(id);
|
||||
@@ -705,7 +687,8 @@ int Engine::step_loop() {
|
||||
/* Queue the drafter's passes behind the step before waiting: the card computes acceptance
|
||||
* itself and every pass reads it there (sched/advance.h), so one wait covers the whole
|
||||
* step. */
|
||||
st = block_card_ ? issue_block_drafter(b->step, so) : issue_serial_drafter(b->step, so);
|
||||
st = block_drafting() ? issue_block_drafter(b->step, so)
|
||||
: issue_serial_drafter(b->step, so);
|
||||
if (st < 0) return fail_loop(st);
|
||||
st = mark_step_end(b, so);
|
||||
if (st < 0) return fail_loop(st);
|
||||
@@ -717,6 +700,9 @@ int Engine::step_loop() {
|
||||
st = embedding_ ? collect_pooled(b, so) : collect_step(b, so);
|
||||
if (t_on) phase_mark(PH_COLLECT);
|
||||
if (st < 0) return fail_loop(st);
|
||||
/* The step's sampler chain, verify op included, has returned: one line at the first
|
||||
* coupled verify that actually completed. */
|
||||
couple_verify_evidence(b->step);
|
||||
if (cfg_.kld()) {
|
||||
st = score_rows(b, so);
|
||||
if (st < 0) return fail_loop(st);
|
||||
@@ -769,13 +755,10 @@ int Engine::step_loop() {
|
||||
if (t_on) phase_mark(PH_COMMIT);
|
||||
if (st < 0) { RAD_ERR("commit: %s", rad_strerror(st)); return fail_loop(st); }
|
||||
|
||||
/* The drafter for the next step. The host's block driver runs here, since it stages from
|
||||
* the committed sequence. A serial one, or a block one on the card, already ran; what
|
||||
* remains is to check its acceptance against the host's and publish its proposals. Each
|
||||
* driver returns immediately for a kind that is not its own. */
|
||||
st = drafter_.kind != RAD_DRAFT_BLOCK ? finish_serial_drafter(so)
|
||||
: block_card_ ? finish_block_drafter(so)
|
||||
: run_block_drafter(b->step);
|
||||
/* The drafter for the next step already ran on the card; what remains is to check its
|
||||
* acceptance against the host's and publish its proposals. Each driver returns
|
||||
* immediately for a kind that is not its own. */
|
||||
st = block_drafting() ? finish_block_drafter(so) : finish_serial_drafter(so);
|
||||
if (st < 0) return fail_loop(st);
|
||||
/* The step ends here, after its draft rounds, so step timing includes them
|
||||
* (Scheduler::step_finished). */
|
||||
@@ -1370,6 +1353,25 @@ void Engine::drain_completed() {
|
||||
for (uint64_t id : done_) for (auto& rk : ranks_) rk->sampler.end_request(id);
|
||||
}
|
||||
|
||||
/* Zero freshly assigned recurrent slots before the step that reads them. The manager records the
|
||||
* grab but cannot write (StateClear in core/mem/kv.h); the list is empty except on a sequence's
|
||||
* first step. Each rank clears by its own plan: the slot number is the scheduler's, but the state
|
||||
* size depends on the heads this rank holds, which can differ per rank (rad_arch.h
|
||||
* remainder_place). */
|
||||
void Engine::clear_fresh_states() {
|
||||
for (const StateClear& c : ranks_[0]->kv.state_clears()) {
|
||||
for (auto& rk : ranks_) {
|
||||
const KVGroupPlan* gp = rk->kv.plan(c.group);
|
||||
if (!gp || !gp->stateful()) continue;
|
||||
const int64_t bytes = gp->layer_bytes_per_state();
|
||||
for (int64_t l = 0; l < gp->n_layers; ++l)
|
||||
if (void* p = rk->kv.state_ptr(c.group, (int32_t)l, c.slot))
|
||||
rad_memset_async(p, 0, bytes, rk->ctx.stream());
|
||||
}
|
||||
}
|
||||
ranks_[0]->kv.clear_state_clears();
|
||||
}
|
||||
|
||||
int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
startup_watch_ = std::move(watch);
|
||||
if (ranks_.empty() || !ranks_[0]->ctx.program()) {
|
||||
@@ -1491,15 +1493,16 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
auto* b = static_cast<PCBinding<PrefixCache>*>(pc_iface_.get());
|
||||
/* Called inside Scheduler::step() under its lock, which makes touching the cache and rank
|
||||
* 0's manager safe; nothing here may call back into the scheduler. */
|
||||
b->restore_fn = [this, b](const Request& req) {
|
||||
b->restore_fn = [this, b](const Request& req, bool whole_only) -> RestoreResult {
|
||||
const uint64_t t0 = rad_mono_ns();
|
||||
PrefixCache& pc = ranks_[0]->prefix;
|
||||
/* Room is made before anything is planned (PCBinding::restore_plan): a chain the free
|
||||
* list cannot hold would otherwise come back only as far as it reaches. One block
|
||||
* table serves every rank, so what rank 0's cache gives up is room on every rank. */
|
||||
const std::vector<BlockHash> want =
|
||||
b->restore_plan(req, cvec_salt_for(req.sp.use_control_vector));
|
||||
if (want.empty()) return;
|
||||
RestoreResult res = RestoreResult::Whole;
|
||||
const std::vector<BlockHash> want = b->restore_plan(
|
||||
req, cvec_salt_for(req.sp.use_control_vector), whole_only, &res);
|
||||
if (want.empty()) return res;
|
||||
/* The whole chain in one restore. With 4-token blocks a long conversation is tens of
|
||||
* thousands of entries; batched, it is one launch per (group, layer) per staging batch
|
||||
* and one copy per run of arena slots instead of a round trip per entry. */
|
||||
@@ -1510,7 +1513,9 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
if (!ranks_[0]->tierx.plan_promote(h, &j)) break;
|
||||
jobs.push_back(std::move(j));
|
||||
}
|
||||
if (jobs.empty()) return;
|
||||
/* A record still in flight ends the chain here, as a short reservation does below. */
|
||||
if (jobs.size() < want.size()) res = RestoreResult::Cut;
|
||||
if (jobs.empty()) return res;
|
||||
std::vector<char> ok(jobs.size(), 1);
|
||||
for (auto& r : ranks_) {
|
||||
std::vector<char> mine;
|
||||
@@ -1525,7 +1530,7 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
const std::vector<int32_t>& cg = pc.cached_groups();
|
||||
for (size_t i = 0; i < jobs.size(); ++i) {
|
||||
TierJob& j = jobs[i];
|
||||
if (!ok[i]) continue;
|
||||
if (!ok[i]) { res = RestoreResult::Cut; continue; }
|
||||
const int rb = pc.rebind(j.key, j.blocks);
|
||||
if (rb != RAD_OK) {
|
||||
/* No entry to land in: release the reserved blocks and forget the tier record,
|
||||
@@ -1537,6 +1542,7 @@ int Engine::serve(std::unique_ptr<StallWatch> watch) {
|
||||
}
|
||||
}
|
||||
ranks_[0]->tiers.note_restore((int64_t)(rad_mono_ns() - t0));
|
||||
return res;
|
||||
};
|
||||
/* An eviction that would lose an entry waits for its copy instead. Called by the prefix
|
||||
* cache binding under the scheduler's lock when dropping already-copied entries did not
|
||||
@@ -1690,6 +1696,8 @@ std::string Engine::engine_info() const {
|
||||
e["tensor_parallel"] = cfg_.tp;
|
||||
e["tp_wire"] = cfg_.tp > 1 ? (cfg_.tp_wire_exact ? "exact" : "wht6") : "n/a";
|
||||
e["tp_wire_min_kb"] = cfg_.tp_wire_exact ? 0 : cfg_.tp_wire_min_kb;
|
||||
e["attn_prefill_fp8"] = attn_prefill_fp8_name(cfg_.attn_prefill_fp8);
|
||||
e["tp_attn_split"] = cfg_.tp_attn_rows ? "rows" : "heads";
|
||||
e["max_num_batched_tokens"] = cfg_.max_tok;
|
||||
e["placement"] = cfg_.placement;
|
||||
/* Each lookup table's requested and resolved placement. */
|
||||
@@ -2540,6 +2548,7 @@ int Engine::run_server() {
|
||||
in.chunk_bos = gd.chunk_bos;
|
||||
in.chunk_eos = gd.chunk_eos;
|
||||
in.chunk_pad = gd.pad_token;
|
||||
in.cond_opts = gd.cond_opts;
|
||||
image_bridge.drv = img_gen_;
|
||||
image_bridge.proc = mm_proc.get();
|
||||
d.images = &image_bridge;
|
||||
@@ -2570,8 +2579,9 @@ int Engine::run_server() {
|
||||
std::string* why) const override {
|
||||
const int s = rad_tools_text_prepare(*plugins, field, in, out);
|
||||
if (s < 0 && why)
|
||||
*why = s == RAD_E_INVAL ? "the model cannot take this text"
|
||||
: std::string(rad_strerror(s));
|
||||
*why = !out->empty() ? *out
|
||||
: s == RAD_E_INVAL ? "the model cannot take this text"
|
||||
: std::string(rad_strerror(s));
|
||||
return s;
|
||||
}
|
||||
int submit(std::unique_ptr<gen::AudioRequest> r, std::string* why) override {
|
||||
@@ -2597,6 +2607,14 @@ int Engine::run_server() {
|
||||
in.default_steps = ad.voc_chunk > 0 ? 0 : ad.default_steps;
|
||||
in.default_cfg = ad.default_cfg;
|
||||
in.max_lanes = ad.max_lanes;
|
||||
in.branches = ad.branches == 1 ? 1 : 2;
|
||||
in.input_special = ad.input_special != 0;
|
||||
in.tmpl_ref = pg.agen_str.tmpl_ref;
|
||||
in.ref_item = pg.agen_str.ref_item;
|
||||
in.ref_rate = ad.ref_rate;
|
||||
in.ref_hop = ad.ref_hop;
|
||||
in.ref_max_samples = ad.ref_max_samples;
|
||||
in.ref_max = ad.ref_max;
|
||||
audio_bridge.drv = aud_gen_;
|
||||
audio_bridge.plugins = &plugins_;
|
||||
d.audio = &audio_bridge;
|
||||
@@ -2737,8 +2755,8 @@ int Engine::run_server() {
|
||||
RAD_INFO("chat: the template takes reasoning_effort %s, and none or minimal turn "
|
||||
"thinking off%s%s", list.c_str(), mapped.empty() ? "" : "; mapped: ",
|
||||
mapped.c_str());
|
||||
/* What a request naming no effort gets, which a client cannot see: Qwen3.8's template
|
||||
* renders xhigh into a system prompt (#113). */
|
||||
/* What a request naming no effort gets, which a client cannot see: a template may
|
||||
* render a level into a system prompt (Qwen3.8's renders xhigh). */
|
||||
const std::string& dflt = srv.template_default_effort();
|
||||
if (cfg_.reasoning_effort.empty() && !dflt.empty())
|
||||
RAD_INFO("chat: a request naming no reasoning_effort renders as '%s', the "
|
||||
|
||||
+38
-8
@@ -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>
|
||||
@@ -185,7 +186,6 @@ public:
|
||||
std::shared_ptr<void>* hold, std::string* note, std::string* err);
|
||||
/* The adapter files a generator request may name: --lora's and those under --lora-dir. */
|
||||
std::vector<std::string> gen_lora_names() const;
|
||||
bool gen_lora_enabled() const { return lora_gen_; }
|
||||
private:
|
||||
/* A generator's adapter files by name (--lora, POST /v1/load_lora_adapter, --lora-dir), opened
|
||||
* once and kept mapped; compositions read them when a combination is put in a slot. */
|
||||
@@ -339,6 +339,10 @@ private:
|
||||
* string because RadDrafterDecl::name points into the Program. */
|
||||
RadDrafterDecl drafter_{};
|
||||
std::string drafter_name_;
|
||||
/* The block drafter's shorter block (rad_drafter_short_block), 0 when it has none or
|
||||
* --draft-short-from is 0. */
|
||||
int64_t drafter_short_ = 0;
|
||||
bool short_on_ = false; /* the short block runs now (block_shape) */
|
||||
|
||||
/* Serial driver (spec §10): `depth` dependent passes after the step commits, each embedding
|
||||
* the previous proposal. MTP, EAGLE and Medusa-serial have this shape. */
|
||||
@@ -374,6 +378,9 @@ private:
|
||||
gen::AudioDriver* aud_gen_ = nullptr;
|
||||
gen::VideoDriver* vid_gen_ = nullptr;
|
||||
int gen_loop();
|
||||
/* Zeroes the state slots the KV manager granted since the last step, on every rank's stream,
|
||||
* before the step or pass that first reads them. */
|
||||
void clear_fresh_states();
|
||||
bool serial_drafting() const;
|
||||
int advance_all(int mode, int round, bool from_proposal, int rows = -1);
|
||||
int issue_serial_drafter(int step, StepOut& so);
|
||||
@@ -383,7 +390,7 @@ private:
|
||||
/* The arena level and the followers' pools, before any release that runs a forward pass. */
|
||||
int prepare_release(const RadBatch* b);
|
||||
/* Whether a step may be issued ahead: requires that the drafter, if any, runs on the card (the
|
||||
* prompt-lookup drafter and the host's block driver both read the committed sequence). */
|
||||
* prompt-lookup drafter reads the committed sequence). */
|
||||
bool pipelining_ = false;
|
||||
int finish_serial_drafter(const StepOut& so);
|
||||
/* Handed from issue_serial_drafter to finish_serial_drafter: the drafting rows, the rounds
|
||||
@@ -396,6 +403,25 @@ private:
|
||||
void step_state_fini();
|
||||
StepSlot* slots_host_ = nullptr;
|
||||
|
||||
/* --draft-coupling (engine_draft.cpp). The head declares `mtp_couple_draws` and
|
||||
* `mtp_couple_state`; the engine stages one draw per drafting row before the serial passes and
|
||||
* reads the states back once, then binds each to the verify row it will be coupled at. */
|
||||
bool mtp_couple_ = false;
|
||||
rad_buf couple_draws_buf_ = 0, couple_state_buf_ = 0;
|
||||
int64_t couple_rows_ = 0; /* the state plane's rows per round */
|
||||
RadMtpCoupleDraw* couple_draw_stage_ = nullptr; /* pinned [max_seqs] */
|
||||
RadMtpCoupleState* couple_readback_ = nullptr; /* pinned [rounds, couple_rows_] */
|
||||
std::vector<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. */
|
||||
@@ -407,19 +433,23 @@ private:
|
||||
void phase_mark(int p);
|
||||
|
||||
/* Block driver (spec §10): a context pass mirroring the step just run, then one pass that
|
||||
* fills every drafted position at once. DFlash2 has this shape. run_block_drafter stages both
|
||||
* after the commit; on the card (`block_card_`, the default), issue_block_drafter queues them
|
||||
* behind the step before its readback and finish_block_drafter publishes the proposals after
|
||||
* the commit, so the step can be issued ahead. RADIANCE_DRAFT_BLOCK_HOST=1 keeps the host's. */
|
||||
int run_block_drafter(int step);
|
||||
* fills every drafted position at once. DFlash2 has this shape. issue_block_drafter queues
|
||||
* both behind the step before its readback and finish_block_drafter publishes the proposals
|
||||
* after the commit, so the step can be issued ahead. */
|
||||
bool block_drafting() const;
|
||||
int block_pass(const RadBatch* db, const char* what, int step);
|
||||
bool block_card_ = false;
|
||||
int issue_block_drafter(int step, StepOut& so);
|
||||
int finish_block_drafter(const StepOut& so);
|
||||
/* The block and proposal count this step's query pass runs at: the drafter's own, or its short
|
||||
* block once --draft-short-from sequences decode, back to its own only two below. */
|
||||
void block_shape(int* block, int* steps);
|
||||
/* Handed from issue_block_drafter to finish_block_drafter and issue_ahead: the drafting rows,
|
||||
* in the query pass's order, and how many there are (0 when no query pass ran). */
|
||||
std::vector<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. */
|
||||
|
||||
+177
-58
@@ -84,6 +84,25 @@ struct MissReport {
|
||||
}
|
||||
};
|
||||
|
||||
/* The kernels --attn-prefill-fp8 reached: the resolved rows, in any band and domain, that
|
||||
* constrain `prefill_fp8`. An exact kernel ignores the parameter and states no constraint on it. */
|
||||
static std::vector<std::string> prefill_fp8_rows(const Program& p) {
|
||||
std::vector<std::string> names;
|
||||
for (const OpInfo& op : p.ops)
|
||||
for (const Band& band : op.bands)
|
||||
for (const Resolved& r : band.dom) {
|
||||
if (!r || !r.row->info) continue;
|
||||
const RadKernelInfo* k = r.row->info;
|
||||
bool takes = false;
|
||||
for (int c = 0; c < k->n_constraints; ++c)
|
||||
if (k->constraints[c].key && !std::strcmp(k->constraints[c].key, "prefill_fp8"))
|
||||
takes = true;
|
||||
if (takes && std::find(names.begin(), names.end(), k->name) == names.end())
|
||||
names.push_back(k->name);
|
||||
}
|
||||
return names;
|
||||
}
|
||||
|
||||
static MissReport miss_report(const Program& p, bool host_backend) {
|
||||
MissReport r;
|
||||
std::vector<std::string> host_ops; /* in first-seen order */
|
||||
@@ -885,6 +904,10 @@ RadBuildCtx Engine::build_ctx(int rank, int64_t max_tok) const {
|
||||
bc.kv_dtype = cfg_.kv_cache_dtype == "bf16" ? RAD_BF16 : RAD_F8E4M3;
|
||||
bc.kv_quant = cfg_.kv_cache_dtype == "fp8_v4" ? RAD_KVQ_V4
|
||||
: cfg_.kv_cache_dtype == "k6_v4" ? RAD_KVQ_K6V4 : RAD_KVQ_NONE;
|
||||
bc.attn_prefill_fp8 = cfg_.attn_prefill_fp8;
|
||||
bc.tp_attn_rows = cfg_.tp_attn_rows;
|
||||
bc.state_dtype = cfg_.state_cache_dtype == "f16" ? RAD_F16 : 0;
|
||||
bc.draft_coupling = cfg_.draft_coupling ? 1 : 0;
|
||||
bc.tp_wire_min_bytes = cfg_.tp_wire_min_kb * 1024;
|
||||
bc.scope = "";
|
||||
bc.max_enc_patches = cfg_.mm_max_patches > 0 ? cfg_.mm_max_patches : 0;
|
||||
@@ -1019,6 +1042,40 @@ int Engine::declare() {
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
/* The row split is a graph only the plugin can declare, and it splits over ranks. A plugin
|
||||
* that does not say it serves it (RadArchProbe::tp_attn_rows_ok), or a single rank, would
|
||||
* serve the head split under a name that promised the other, so the flag is refused rather
|
||||
* than ignored. */
|
||||
if (cfg_.tp_attn_rows) {
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
if (!pb.tp_attn_rows_ok) {
|
||||
RAD_ERR("--tp-attn-split rows: the '%s' plugin does not split attention by rows for "
|
||||
"this model (heads does)", plugins_.arch_plugin.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (cfg_.tp < 2) {
|
||||
RAD_ERR("--tp-attn-split rows splits a prefill's attention over tensor-parallel ranks, "
|
||||
"and --tp %d has none to split over (heads does)", cfg_.tp);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
RAD_WARN("attention: a prefill-sized step splits by rows over the %d ranks "
|
||||
"(--tp-attn-split rows): every card holds the attention's projections at full "
|
||||
"width, and the result is not bit-identical to the head split", cfg_.tp);
|
||||
}
|
||||
/* Likewise an f16 recurrent state: a plugin that does not say it declares one would keep f32
|
||||
* under a flag that promised half the state memory. */
|
||||
if (cfg_.state_cache_dtype == "f16") {
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
if (!pb.state_f16_ok) {
|
||||
RAD_ERR("--state-cache-dtype f16: the '%s' plugin does not declare its recurrent state "
|
||||
"at f16 for this model (f32 does)", plugins_.arch_plugin.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
RAD_INFO("recurrent state cache: f16 (--state-cache-dtype), half the state memory; lossy, "
|
||||
"the generated text differs from f32");
|
||||
}
|
||||
/* Resolved here, not at argument parsing: the plugin states its drafter's depth, and it is
|
||||
* selected only once the container is open. Every consumer of `n_spec` (buffer sizing, kernel
|
||||
* bands, the scheduler's window) runs after this. rad_arch_probe is the core's only source of
|
||||
@@ -1036,24 +1093,23 @@ int Engine::declare() {
|
||||
cfg_.n_spec > 0 ? "the depth the drafter in this container states as its operating point"
|
||||
: "this container carries no draft head");
|
||||
}
|
||||
/* Chained launches pay on some speculative steps and cost plain decode (4x R9700: the 31B
|
||||
* with DFlash2 +13%, the 26B-A4B with DFlash +1%, Qwen3.8-27B with DFlash2 even; the 31B with
|
||||
* no drafter -6.5%), so they are on by default only where the model's plugin measured a gain
|
||||
* with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
|
||||
/* Chained launches pay on some speculative steps and cost plain decode (on 4x R9700 the 31B
|
||||
* with DFlash2 gained 13%, the 26B-A4B with DFlash 1%, Qwen3.8-27B with DFlash2 nothing, and
|
||||
* the 31B without a drafter lost 6.5%), so they are on only where the model's plugin measured a
|
||||
* gain with its speculative drafter (RadArchProbe::chain_pays) and that drafter decodes
|
||||
* speculatively. */
|
||||
{
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
rad_dev_chain_infer(cfg_.n_spec > 0 && pb.chain_pays);
|
||||
const char* e = std::getenv("RADIANCE_CHAIN");
|
||||
const bool pays = cfg_.n_spec > 0 && pb.chain_pays;
|
||||
rad_dev_chain_infer(pays);
|
||||
const bool on = rad_dev_chain_enabled() != 0;
|
||||
const char* why = e && *e && std::strcmp(e, "auto") != 0
|
||||
? (on || *e == '0' ? "RADIANCE_CHAIN says so" : "the backend does not chain")
|
||||
: on ? "the model's plugin measured a gain with its speculative drafter"
|
||||
: "no drafter whose plugin measured a gain with them decodes "
|
||||
"speculatively, or the backend does not chain";
|
||||
const char* why = on ? "the model's plugin measured a gain with its speculative drafter"
|
||||
: pays ? "the device backend does not chain"
|
||||
: "no drafter whose plugin measured a gain with them decodes "
|
||||
"speculatively";
|
||||
RAD_INFO("chained launches: %s -- %s", on ? "on" : "off", why);
|
||||
decide("RADIANCE_CHAIN", on ? "1" : "0", why);
|
||||
decide("chained launches", on ? "on" : "off", why);
|
||||
}
|
||||
/* The audio encoder's pass: the plugin's longest clip, when the model file carries an audio
|
||||
* encoder (`radiance.encoder` names one) and the deployment is not text-only. */
|
||||
@@ -1072,7 +1128,10 @@ int Engine::declare() {
|
||||
* area, which would need 16x the activation memory on every card. */
|
||||
if (cfg_.mm_max_patches < 0) {
|
||||
const char* enc = rad_meta_gets(&meta_, "radiance.encoder", "");
|
||||
const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0;
|
||||
/* A checkpoint's vision_config states a tower as a flat patch_size, or (Unlimited-OCR's
|
||||
* DeepEncoder) only the per-width tables under a `vision_config.image_size`. */
|
||||
const bool tower = rad_meta_geti(&meta_, "vision_config.patch_size", 0) > 0 ||
|
||||
rad_meta_geti(&meta_, "vision_config.image_size", 0) > 0;
|
||||
cfg_.mm_max_patches = (enc && *enc) || (!file_ && tower) ? 16384 : 0;
|
||||
/* Whole output rows a pass: the plugin's merge, when it states one. */
|
||||
RadArchProbe pb{};
|
||||
@@ -1091,54 +1150,44 @@ int Engine::declare() {
|
||||
: "the model carries no vision tower");
|
||||
}
|
||||
|
||||
/* Declare once per rank (rank and world_size in RadBuildCtx; the plugin declares dimensions
|
||||
* already divided, spec §9), every rank concurrently on its own thread. Concurrency is
|
||||
* required: kernel init() runs during declare, and a collective's init is a rendezvous
|
||||
* (libr4d's all-reduce publishes its peer scratch pointer and waits for every other rank), so
|
||||
* a serial loop times out. Registry::select() and init_instance() share a mutex for this. Each
|
||||
* thread binds its device first, because the current device is thread-local and the init
|
||||
* allocates on it. */
|
||||
/* Control vectors are resolved here, before any rank declares: the plugin reads the direction
|
||||
* table from RadBuildCtx, so a table that failed validation must stop the server before a graph
|
||||
* is built around it.
|
||||
*
|
||||
* The feature is loaded only when the deployment asks: `--control-vector off|on`. Without it
|
||||
* nothing is looked for, the graph declares no projection op, and a request that asks for one
|
||||
* is refused by name -- so a deployment that does not use the feature pays nothing. With the
|
||||
* flag, the engine looks beside the container (or in the directory, or in
|
||||
* $RADIANCE_HOME/vectors) and uses the file if it is compatible; its operation parameters come
|
||||
* from the package's own JSON. A file that does not fit is reported and skipped -- a sidecar
|
||||
* must never stop a server nobody pointed at it. The flag's value is the startup switch: `off`
|
||||
* leaves requests off until one asks (or the dashboard flips the default), `on` starts them on. */
|
||||
const std::string arch = meta_.arch_id ? meta_.arch_id : "";
|
||||
/* Control vectors are resolved before any rank declares, because the plugin reads the
|
||||
* direction table from RadBuildCtx. Only `--control-vector off|on` loads one; without it
|
||||
* nothing is looked for and the graph declares no projection op. With it, a plugin that does
|
||||
* not apply control vectors (RadArchProbe::control_vector_ok), no file found, or a file that
|
||||
* does not fit this model is refused: the operator asked for the feature. The operation's
|
||||
* parameters come from the package's own JSON. The flag's value is the request default. */
|
||||
if (cfg_.control_vector == "disabled") {
|
||||
RAD_INFO("control vectors: not loaded (no --control-vector); a request that asks for one is "
|
||||
"refused");
|
||||
} else if (!arch.empty()) {
|
||||
} else {
|
||||
RadArchProbe pb{};
|
||||
(void)rad_tools_probe(plugins_, meta_, &pb);
|
||||
if (!pb.control_vector_ok) {
|
||||
RAD_ERR("--control-vector %s: the '%s' plugin does not apply control vectors for this "
|
||||
"model", cfg_.control_vector.c_str(), plugins_.arch_plugin.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
const std::string arch = meta_.arch_id ? meta_.arch_id : "";
|
||||
std::string proj_path, tried;
|
||||
(void) control_vector_discover(cfg_.model, arch, cfg_.radiance_home, &proj_path, &tried);
|
||||
if (proj_path.empty()) {
|
||||
RAD_INFO("control vectors: none found (%s)", tried.c_str());
|
||||
} else if (arch != "qwen4exp") {
|
||||
RAD_WARN("control vectors: %s is for this family only (qwen4exp, whose gated residual "
|
||||
"carries the projection op); this container is '%s' -- ignoring it",
|
||||
proj_path.c_str(), arch.c_str());
|
||||
} else {
|
||||
std::string why;
|
||||
const int rc = control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers,
|
||||
&cvec_, &why);
|
||||
if (rc != RAD_OK) {
|
||||
RAD_WARN("%s -- serving without it", why.c_str());
|
||||
cvec_ = ControlVector{};
|
||||
}
|
||||
RAD_ERR("--control-vector %s: no control vector found for this model (looked at %s)",
|
||||
cfg_.control_vector.c_str(), tried.c_str());
|
||||
return RAD_E_NOTFOUND;
|
||||
}
|
||||
std::string why;
|
||||
if (control_vector_load(proj_path, arch, meta_.n_embd, meta_.n_layers, &cvec_, &why) !=
|
||||
RAD_OK) {
|
||||
RAD_ERR("--control-vector %s: %s", cfg_.control_vector.c_str(), why.c_str());
|
||||
cvec_ = ControlVector{};
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
if (cvec_.loaded()) {
|
||||
cvec_views_.assign(ranks_.size(), RadControlVector{});
|
||||
cvec_salt_ = control_vector_salt(cvec_);
|
||||
/* `--control-vector on` starts the request default on, which is also how `--kld-record`/
|
||||
* `--kld-ref` score the projection itself: those modes serve no request to carry the
|
||||
* switch. The switch still decides per request. */
|
||||
/* The request default; --kld-record / --kld-ref score documents with it, as they serve no
|
||||
* request that could carry the field. */
|
||||
const bool default_on = cfg_.control_vector == "on";
|
||||
cvec_default_.store(default_on);
|
||||
RAD_INFO("control vectors: %s: %lld directions of %lld, layers %d..%d, scale %.3f -- "
|
||||
@@ -1156,6 +1205,13 @@ int Engine::declare() {
|
||||
cvec_default_.store(false);
|
||||
}
|
||||
|
||||
/* Declare once per rank (rank and world_size in RadBuildCtx; the plugin declares dimensions
|
||||
* already divided, spec §9), every rank concurrently on its own thread. Concurrency is
|
||||
* required: kernel init() runs during declare, and a collective's init is a rendezvous
|
||||
* (libr4d's all-reduce publishes its peer scratch pointer and waits for every other rank), so
|
||||
* a serial loop times out. Registry::select() and init_instance() share a mutex for this. Each
|
||||
* thread binds its device first, because the current device is thread-local and the init
|
||||
* allocates on it. */
|
||||
std::vector<int> st(ranks_.size(), RAD_OK);
|
||||
std::vector<std::thread> th;
|
||||
th.reserve(ranks_.size());
|
||||
@@ -1246,6 +1302,28 @@ int Engine::declare() {
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
}
|
||||
/* --attn-prefill-fp8 is a permission an exact kernel also satisfies, so whether it acts is
|
||||
* read off the resolution: a kernel that implements a lossy leg constrains `prefill_fp8`. A
|
||||
* flag nothing takes stops the start rather than serving the exact form under its name. */
|
||||
if (cfg_.attn_prefill_fp8 != 0) {
|
||||
const std::vector<std::string> rows = prefill_fp8_rows(ranks_[0]->program);
|
||||
const char* mode = attn_prefill_fp8_name(cfg_.attn_prefill_fp8);
|
||||
if (rows.empty() && !cfg_.debug_graph) {
|
||||
RAD_ERR("not starting: --attn-prefill-fp8 %s, but no attention kernel resolved for "
|
||||
"this model takes e4m3 products at its geometry, cache (--kv-cache-dtype %s) "
|
||||
"and kernel libraries; --attn-prefill-fp8 off serves it exactly", mode,
|
||||
cfg_.kv_cache_dtype.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
std::string names;
|
||||
for (const std::string& r : rows) names += (names.empty() ? "" : ", ") + r;
|
||||
RAD_WARN("attention: LOSSY prefill (--attn-prefill-fp8 %s). %s rounded to e4m3 for fp8 "
|
||||
"WMMA in %s, so this process does not compute the same function the exact "
|
||||
"attention does; bands those kernels do not serve stay exact", mode,
|
||||
cfg_.attn_prefill_fp8 == RAD_ATTN_FP8_QK ? "Q.K^T's query is"
|
||||
: cfg_.attn_prefill_fp8 == RAD_ATTN_FP8_PV ? "P.V's probabilities are"
|
||||
: "Q.K^T's query and P.V's probabilities are", names.c_str());
|
||||
}
|
||||
/* Checkpoint weights that cannot be served as stored cannot be loaded; name them all with the
|
||||
* remedy. */
|
||||
if (ckpt_src_) {
|
||||
@@ -1272,6 +1350,24 @@ int Engine::declare() {
|
||||
drafter_name_ = p0.drafter_name;
|
||||
drafter_.name = drafter_name_.c_str();
|
||||
if (cfg_.n_spec <= 0) drafter_ = RadDrafterDecl{};
|
||||
drafter_short_ = drafter_.kind == RAD_DRAFT_BLOCK && cfg_.draft_short_from > 0
|
||||
? p0.drafter_short_block : 0;
|
||||
if (cfg_.draft_short_from > 0 && drafter_.kind == RAD_DRAFT_NONE)
|
||||
RAD_WARN("--draft-short-from %lld: this deployment runs no drafter, so there is no block "
|
||||
"to shorten", (long long)cfg_.draft_short_from);
|
||||
else if (cfg_.draft_short_from > 0 && !drafter_short_)
|
||||
RAD_WARN("--draft-short-from %lld: '%s' %s", (long long)cfg_.draft_short_from,
|
||||
drafter_name_.c_str(),
|
||||
drafter_.kind == RAD_DRAFT_BLOCK ? "declares no shorter block, so it keeps its own"
|
||||
: "is a serial head, which proposes no block");
|
||||
if (drafter_short_)
|
||||
RAD_INFO("speculation: from %lld decoding sequences on, '%s' runs its short block of %lld "
|
||||
"row(s), %lld token(s)", (long long)cfg_.draft_short_from,
|
||||
drafter_name_.c_str(),
|
||||
(long long)drafter_short_,
|
||||
(long long)(drafter_short_ - ((drafter_.block > 0 ? drafter_.block
|
||||
: drafter_.depth + 1) -
|
||||
drafter_.depth)));
|
||||
if (drafter_.kind != RAD_DRAFT_NONE) {
|
||||
/* A zero proposal handle means the sampler's token buffer: the head's logits go through
|
||||
* the ordinary sampler chain. */
|
||||
@@ -1399,6 +1495,21 @@ void Engine::probe_arena_levels() {
|
||||
}
|
||||
|
||||
/* ================================================================== 5. plan */
|
||||
|
||||
/* R-SWA: a RAD_KV_RING group names its ring's W in the declaration (`window`). Tell the manager
|
||||
* before it plans, so the group is planned for per-sequence windows: sized for the whole context
|
||||
* plus one ring a sequence (the ring in the fixed costs), never capped at the declare-time
|
||||
* window, never snapshotted. Every plan (each sizing probe and the real manager) goes through
|
||||
* here, so they all plan the same bytes. */
|
||||
static int declare_ring_windows(KVManager& kv, const Program& prog) {
|
||||
for (size_t g = 1; g < prog.kv_groups.size(); ++g) {
|
||||
const RadKVGroupDecl& d = prog.kv_groups[g].decl;
|
||||
if (d.kind != RAD_KV_RING) continue;
|
||||
RAD_TRY(kv.declare_runtime_window((int32_t)g, d.window));
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Engine::plan() {
|
||||
/* The budget is resolved once, for every rank, before any rank allocates. vram_budget_resolve
|
||||
* folds the smallest capacity with the largest program so one split fits every card, and
|
||||
@@ -1485,7 +1596,8 @@ int Engine::plan() {
|
||||
* memory, and the real pool does not exist yet. */
|
||||
KVManager probe;
|
||||
host_arenas += arena_host_bytes(r->program);
|
||||
if (probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
|
||||
if (declare_ring_windows(probe, r->program) == RAD_OK &&
|
||||
probe.plan_groups(r->program.kv_groups, cfg_) == RAD_OK) {
|
||||
ck_slot += probe.checkpoint_bytes();
|
||||
f.kv_ceiling = probe.ceiling(ctx);
|
||||
f.kv_fixed = probe.fixed_bytes();
|
||||
@@ -1621,7 +1733,8 @@ int Engine::plan() {
|
||||
* its carve). */
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
probes[i] = std::make_unique<KVManager>();
|
||||
if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
|
||||
if (declare_ring_windows(*probes[i], ranks_[i]->program) != RAD_OK ||
|
||||
probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
|
||||
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
|
||||
break;
|
||||
}
|
||||
@@ -2959,6 +3072,7 @@ int Engine::configure_kv() {
|
||||
for (size_t i = 0; i < ranks_.size(); ++i) {
|
||||
auto& r = ranks_[i];
|
||||
LogRank lr(r->index);
|
||||
RAD_TRY(declare_ring_windows(r->kv, r->program));
|
||||
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
|
||||
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
|
||||
/* A rank plan() re-sized for the common token count must page at least that count (same
|
||||
@@ -3193,13 +3307,16 @@ int Engine::configure_kv() {
|
||||
/* Can the pool hold one max-length sequence? The context limit and KV pool come from unrelated
|
||||
* flags; otherwise such a request is accepted and then refused at admission with a message
|
||||
* about blocks. Only full paged groups apply: a window group costs the window, and a linear
|
||||
* group is O(1) in context. */
|
||||
* group is O(1) in context. A runtime-window (RAD_KV_RING) group is not checked here either:
|
||||
* it is sized for the whole context plus one ring a sequence and its tokens are a per-sequence
|
||||
* reference rather than the pool's capacity, so the comparison would be about the wrong
|
||||
* number. */
|
||||
{
|
||||
const int64_t want = cfg_.max_ctx ? cfg_.max_ctx : meta_.n_ctx_train;
|
||||
const KVManager& kv = ranks_[0]->kv;
|
||||
for (int32_t g = 0; g < kv.n_groups(); ++g) {
|
||||
const KVGroupPlan* p = kv.plan(g);
|
||||
if (!p || !p->paged() || p->window_blocks > 0) continue;
|
||||
if (!p || !p->paged() || p->window_blocks > 0 || p->runtime_win) continue;
|
||||
const int64_t cap = p->n_blocks * p->block_size;
|
||||
if (cap >= want) continue;
|
||||
/* A hard limit, unlike the backing ratio (how much of every-sequence-at-max_ctx the
|
||||
@@ -3487,16 +3604,18 @@ int Engine::start() {
|
||||
(void)rad_dev_set(ranks_[0]->device);
|
||||
|
||||
/* The most the cache can hold: the whole carve, including lent blocks (a request reclaims them
|
||||
* in the same step). Tokens are the smallest over the full paged groups; a windowed group
|
||||
* bounds history, not capacity. /stats and /metrics report the same numbers (kv_tokens_max,
|
||||
* radiance:kv_cache_max_tokens). */
|
||||
* in the same step). Tokens are the smallest over the full paged groups; a fixed-window group
|
||||
* bounds history, not capacity. A runtime-window (RAD_KV_RING) group does hold its sequences'
|
||||
* references, so it counts like a full group. /stats and /metrics report the same numbers
|
||||
* (kv_tokens_max, radiance:kv_cache_max_tokens). */
|
||||
{
|
||||
const KVManager& kv = ranks_[0]->kv;
|
||||
int64_t bytes = 0, state = 0, tokens = 0;
|
||||
for (const KVGroupPlan& p : kv.plans()) {
|
||||
bytes += kv.pool_bytes_carved(p.index);
|
||||
if (p.stateful()) state += kv.pool_bytes_carved(p.index);
|
||||
if (!p.paged() || p.kind == RAD_KV_WINDOW || p.block_size <= 0) continue;
|
||||
if (!p.paged() || (p.kind == RAD_KV_WINDOW && !p.runtime_win) || p.block_size <= 0)
|
||||
continue;
|
||||
const int64_t t = p.n_blocks * p.block_size;
|
||||
if (tokens == 0 || t < tokens) tokens = t;
|
||||
}
|
||||
|
||||
+185
-61
@@ -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;
|
||||
}
|
||||
@@ -276,11 +427,8 @@ int Engine::finish_serial_drafter(const StepOut& so) {
|
||||
*
|
||||
* Proposals go out through set_draft() like every other.
|
||||
*
|
||||
* Two drivers run these passes. run_block_drafter, after the step commits, stages both from the
|
||||
* committed sequence and reads the proposals back: two host waits a step with the card idle
|
||||
* between them, and no step issued ahead. The card's driver (issue_block_drafter, the default)
|
||||
* queues both behind the step before its readback, from the card's acceptance, as the serial
|
||||
* driver does; RADIANCE_DRAFT_BLOCK_HOST=1 selects the host's.
|
||||
* Both passes are queued behind the step before its readback, from the card's acceptance, as the
|
||||
* serial driver's are (sched/advance.h), so the next step can be issued ahead of the commit.
|
||||
*/
|
||||
|
||||
/* One drafter pass through the barrier. Neither pass samples (no logits in the context pass; the
|
||||
@@ -306,75 +454,51 @@ int Engine::block_pass(const RadBatch* db, const char* what, int step) {
|
||||
return s;
|
||||
}
|
||||
|
||||
int Engine::run_block_drafter(int step) {
|
||||
if (drafter_.kind != RAD_DRAFT_BLOCK || drafter_.depth <= 0) return RAD_OK;
|
||||
|
||||
const int steps = drafter_.depth;
|
||||
/* The row count is the drafter's (defaulted and checked by declare_drafter). */
|
||||
const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
|
||||
std::vector<Scheduler::BlockRow> rows((size_t)cfg_.max_seqs);
|
||||
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
|
||||
rows.data(), (int)rows.size());
|
||||
|
||||
Rank& r0 = *ranks_[0];
|
||||
void* prop = r0.ctx.buf_ptr(drafter_.proposal);
|
||||
if (!prop) {
|
||||
RAD_ERR("drafter '%s': `%s` was declared as the proposal buffer but never planned",
|
||||
drafter_.name, r0.program.buffers[drafter_.proposal].name.c_str());
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
|
||||
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
|
||||
* drafter will need, and skipping would leave a permanent hole in its cache. */
|
||||
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
|
||||
|
||||
/* Cleared so a query batch that could not be built does not republish the previous step's
|
||||
* proposals. */
|
||||
draft_out_.clear();
|
||||
if (n > 0) {
|
||||
if (const RadBatch* qb = sched_.block_query(step)) {
|
||||
RAD_TRY(block_pass(qb, "query", step));
|
||||
const int64_t n_raw = (int64_t)n * steps;
|
||||
int32_t* const raw = readback_.reserve(n_raw);
|
||||
if (!raw) return RAD_E_NOMEM;
|
||||
RAD_TRY(rad_memcpy_async(raw, prop, n_raw * 4, r0.ctx.stream()));
|
||||
RAD_TRY(rad_stream_sync(r0.ctx.stream()));
|
||||
draft_out_.assign(raw, raw + n_raw);
|
||||
}
|
||||
}
|
||||
sched_.block_end();
|
||||
if (n <= 0 || draft_out_.empty()) return RAD_OK;
|
||||
|
||||
for (int i = 0; i < n; ++i) {
|
||||
/* A request the sampler will not speculate on gets no draft; see finish_serial_drafter. */
|
||||
if (!r0.sampler.allows_speculation(rows[(size_t)i].seq)) continue;
|
||||
sched_.set_draft(rows[(size_t)i].seq, &draft_out_[(size_t)i * (size_t)steps], steps);
|
||||
}
|
||||
return RAD_OK;
|
||||
bool Engine::block_drafting() const {
|
||||
return drafter_.kind == RAD_DRAFT_BLOCK && drafter_.depth > 0;
|
||||
}
|
||||
|
||||
/* The card's driver: both passes behind the step, without waiting. After the trunk's ranks join,
|
||||
* the acceptance runs on every rank (ADV_ACCEPT), leaving each sequence's anchor and committed
|
||||
* end in its StepSlot. The context pass mirrors the trunk step, whose positions the host knows.
|
||||
/* Both passes behind the step, without waiting. After the trunk's ranks join, the acceptance runs
|
||||
* on every rank (ADV_ACCEPT), leaving each sequence's anchor and committed end in its StepSlot. The context pass mirrors the trunk step, whose positions the host knows.
|
||||
* The query pass's rows are device rows that the card positions at the committed end (ADV_BLOCK),
|
||||
* and its proposals go into the slots behind the anchor (ADV_BTAKE): exactly the token row the
|
||||
* next verify reads (ADV_TRUNK), so the step issued ahead verifies them with no host round trip.
|
||||
* collect_step's wait covers both passes and the slots' readback. */
|
||||
void Engine::block_shape(int* block, int* steps) {
|
||||
*steps = drafter_.depth;
|
||||
/* The row count is the drafter's (defaulted and checked by declare_drafter). */
|
||||
*block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
|
||||
/* Its short block under load (rad_drafter_short_block): the same anchor convention, so as many
|
||||
* fewer proposals as rows. The load is the step just run's, which the next step, the one these
|
||||
* proposals are for, mostly repeats (Scheduler::short_block_on). */
|
||||
if (drafter_short_ <= 0) return;
|
||||
short_on_ = Scheduler::short_block_on(short_on_, sched_.decoded_seqs(), cfg_.draft_short_from);
|
||||
if (short_on_) {
|
||||
*steps -= *block - (int)drafter_short_;
|
||||
*block = (int)drafter_short_;
|
||||
}
|
||||
}
|
||||
|
||||
int Engine::issue_block_drafter(int step, StepOut& so) {
|
||||
block_rows_ = 0;
|
||||
if (!block_card_) return RAD_OK;
|
||||
if (!block_drafting()) return RAD_OK;
|
||||
|
||||
RAD_TRY(advance_all(ADV_ACCEPT, 0, false));
|
||||
/* The sampled ids before either pass, as the serial driver reads them. */
|
||||
RAD_TRY(collect_issue(so));
|
||||
|
||||
const int steps = drafter_.depth;
|
||||
const int block = drafter_.block > 0 ? (int)drafter_.block : drafter_.depth + 1;
|
||||
/* The short block too (block_shape): its query pass is a shorter batch the card positions
|
||||
* the same way, its proposals the front of each row at the drafter's pitch (ADV_BTAKE), and
|
||||
* the step issued ahead verifies that many (issue_ahead). */
|
||||
int block = 0, steps = 0;
|
||||
block_shape(&block, &steps);
|
||||
block_steps_ = steps;
|
||||
block_row_.resize((size_t)cfg_.max_seqs);
|
||||
const int n = sched_.block_begin(block, steps, (int)drafter_.window, drafter_.mask_token,
|
||||
block_row_.data(), (int)block_row_.size(), /*on_card=*/true);
|
||||
|
||||
/* Even when nothing drafts; see run_block_drafter. */
|
||||
/* The context pass runs even when nothing drafts: a mid-prompt sequence has hidden states the
|
||||
* drafter will need, and skipping would leave a permanent hole in its cache. */
|
||||
if (const RadBatch* cb = sched_.block_context(step)) RAD_TRY(block_pass(cb, "context", step));
|
||||
if (n <= 0) return RAD_OK;
|
||||
const RadBatch* qb = sched_.block_query(step);
|
||||
@@ -393,7 +517,7 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
|
||||
* (a disagreement is a defect and the step is refused, as in finish_serial_drafter), move the
|
||||
* drafter's filled range, and publish each row's proposal from the slots. */
|
||||
int Engine::finish_block_drafter(const StepOut& so) {
|
||||
if (!block_card_) return RAD_OK;
|
||||
if (!block_drafting()) return RAD_OK;
|
||||
if (block_rows_ > 0) {
|
||||
const StepPlan& plan = sched_.plan();
|
||||
for (size_t i = 0; i < plan.e.size(); ++i) {
|
||||
@@ -414,7 +538,7 @@ int Engine::finish_block_drafter(const StepOut& so) {
|
||||
if (block_rows_ <= 0) return RAD_OK;
|
||||
|
||||
Rank& r0 = *ranks_[0];
|
||||
const int steps = drafter_.depth;
|
||||
const int steps = block_steps_;
|
||||
draft_out_.assign((size_t)block_rows_ * (size_t)steps, 0);
|
||||
for (int i = 0; i < block_rows_; ++i) {
|
||||
const StepSlot& S = slots_host_[block_row_[(size_t)i].card];
|
||||
|
||||
@@ -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);
|
||||
|
||||
@@ -124,6 +124,8 @@ int Engine::run_kld() {
|
||||
r->ignore_eos = true;
|
||||
r->sp.temp = 0.0f;
|
||||
r->score = true;
|
||||
/* A loaded control vector scores at the deployment's default (--control-vector on|off). */
|
||||
r->sp.use_control_vector = cvec_default_on();
|
||||
/* --kld-lora-sources: the other documents run as the base, in the same steps. */
|
||||
const bool via = cfg_.kld_lora_sources.empty() ||
|
||||
kld_->source(d).rfind(cfg_.kld_lora_sources, 0) == 0;
|
||||
|
||||
@@ -275,7 +275,11 @@ int Engine::lora_copy(int slot, const std::vector<std::vector<lora::PackedSite>>
|
||||
char* da = (char*)P.buffers[lp.a].ptr;
|
||||
char* db = (char*)P.buffers[lp.b].ptr;
|
||||
char* ds = (char*)P.buffers[lp.scale].ptr;
|
||||
if (!da || !db || !ds) { rc = RAD_E_STATE; *err = "a pool has no address"; break; }
|
||||
if (!da || !db || !ds) {
|
||||
rc = RAD_E_STATE;
|
||||
*err = "the adapter pool of '" + lp.weight + "' has no buffer address";
|
||||
break;
|
||||
}
|
||||
da += (int64_t)slot * ab; db += (int64_t)slot * bb; ds += (int64_t)slot * sb;
|
||||
/* A pool this adapter does not touch is zeroed, not left as it was: the bytes are what
|
||||
* the slot's last adapter or the arena held, and a scale of 0 times a NaN is a NaN. */
|
||||
|
||||
+81
-4
@@ -20,6 +20,8 @@
|
||||
#include <chrono>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -47,6 +49,33 @@ int Engine::run_encodes() {
|
||||
|
||||
Rank& r0 = *ranks_[0];
|
||||
const Program& prog = r0.program;
|
||||
|
||||
/* Diagnostic: RADIANCE_DEBUG_MM_BUFFERS names encoder buffers (comma separated, with an
|
||||
* optional `:rows` cap) and each pass writes them, as raw bytes, to `<dump dir>/buf.<name>`.
|
||||
* The pass has finished and been read back, so the copy sees each buffer's last writer; the
|
||||
* tower's per-stage intermediates are tapped inside the pass instead (rad_block_sam.h). */
|
||||
struct DumpBuf { std::string name; int64_t rows; };
|
||||
std::vector<DumpBuf> dump_bufs;
|
||||
static const char* const dump_list = std::getenv("RADIANCE_DEBUG_MM_BUFFERS");
|
||||
if (dump_dir && *dump_dir && dump_list) {
|
||||
for (const char* s = dump_list; *s; ) {
|
||||
const char* e = s;
|
||||
while (*e && *e != ',') ++e;
|
||||
std::string want(s, (size_t)(e - s));
|
||||
s = *e ? e + 1 : e;
|
||||
int64_t rows = 0;
|
||||
if (const size_t colon = want.find(':'); colon != std::string::npos) {
|
||||
rows = std::strtoll(want.c_str() + colon + 1, nullptr, 10);
|
||||
want.resize(colon);
|
||||
}
|
||||
if (!want.empty()) dump_bufs.push_back({ want, rows });
|
||||
}
|
||||
}
|
||||
auto answers_to = [](const std::string& name, const std::string& want) {
|
||||
if (name.size() < want.size() ||
|
||||
name.compare(name.size() - want.size(), want.size(), want) != 0) return false;
|
||||
return name.size() == want.size() || name[name.size() - want.size() - 1] == '.';
|
||||
};
|
||||
for (auto& ip : items) {
|
||||
if (ip->encoded) continue;
|
||||
const RadEncoderDecl& e = ip->kind == mm::Kind::Audio ? prog.audio_encoder : prog.encoder;
|
||||
@@ -74,6 +103,10 @@ int Engine::run_encodes() {
|
||||
|
||||
size_t i = 0;
|
||||
int32_t seg = 0;
|
||||
/* The pass's grid, when the encoder declares that a pass is one geometry
|
||||
* (RadEncoderDecl::one_grid). */
|
||||
const bool one_grid = enc.one_grid != 0;
|
||||
int32_t seg_grid = 0;
|
||||
while (i < mine.size()) {
|
||||
std::vector<BatchBuilder::EncoderPart> parts;
|
||||
int64_t np = 0;
|
||||
@@ -81,16 +114,31 @@ int Engine::run_encodes() {
|
||||
mm::Item& it = *mine[i];
|
||||
const int32_t first = seg;
|
||||
for (; seg < it.n_seg; ++seg) {
|
||||
const int32_t g = it.seg_h(seg);
|
||||
/* The one-output-row view separator (core/mm marks it explicitly) belongs to
|
||||
* the pass of the view before it, so it neither breaks at a "grid change" nor
|
||||
* sets the pass's grid. A square segment that is a real view (a chunked line
|
||||
* of one tile) keeps the ordinary geometry rule below. */
|
||||
const bool sep = it.seg_is_sep(seg);
|
||||
const int64_t seg_p = it.patch_at(seg + 1) - it.patch_at(seg);
|
||||
if (seg_p > max_p) {
|
||||
RAD_ERR("encoder: a segment of %lld patches does not fit a pass of %lld",
|
||||
(long long)seg_p, (long long)max_p);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
if (one_grid && !sep && np > 0 && seg_grid != 0 && g != seg_grid) break;
|
||||
if (np + seg_p > max_p) break;
|
||||
np += seg_p;
|
||||
if (!sep) seg_grid = g;
|
||||
}
|
||||
if (seg == first) {
|
||||
/* Nothing of this item packed into the pass: its first segment did not fit
|
||||
* a pass that already has content (a segment larger than the whole pass was
|
||||
* refused above). `seg` addresses a real segment only below `it.n_seg`;
|
||||
* a degenerate zero-segment item leaves seg_grid alone. */
|
||||
if (seg_grid == 0 && seg < it.n_seg) seg_grid = it.seg_h(seg);
|
||||
break;
|
||||
}
|
||||
if (seg == first) break;
|
||||
parts.push_back({ &it, first, seg - first });
|
||||
if (seg == it.n_seg) { ++i; seg = 0; }
|
||||
}
|
||||
@@ -132,6 +180,35 @@ int Engine::run_encodes() {
|
||||
}
|
||||
/* Sync every rank's stream: the next pass rewrites every rank's staging and arena. */
|
||||
for (auto& rk : ranks_) RAD_TRY(rad_stream_sync(rk->ctx.stream()));
|
||||
|
||||
if (dump_dir && *dump_dir && !dump_bufs.empty()) {
|
||||
for (const DumpBuf& d : dump_bufs) {
|
||||
for (size_t bi = 1; bi < prog.buffers.size(); ++bi) {
|
||||
const BufferInfo& info = prog.buffers[bi];
|
||||
if (!answers_to(info.name, d.name) || info.bytes <= 0) continue;
|
||||
const int64_t nrow = info.decl.rank >= 1 ? info.decl.shape[0] : 1;
|
||||
const int64_t rowb = nrow > 0 ? info.bytes / nrow : info.bytes;
|
||||
const int64_t rows = d.rows > 0 ? std::min<int64_t>(d.rows, nrow) : nrow;
|
||||
void* ptr = r0.ctx.buf_ptr((rad_buf)bi);
|
||||
std::vector<char> raw((size_t)(rows * rowb));
|
||||
if (!ptr || rad_memcpy_async(raw.data(), ptr, raw.size(),
|
||||
r0.ctx.stream()) < 0)
|
||||
continue;
|
||||
rad_stream_sync(r0.ctx.stream());
|
||||
char path[512];
|
||||
std::snprintf(path, sizeof path, "%s/mm_%016llx%016llx_buf.%s.raw",
|
||||
dump_dir, (unsigned long long)parts.front().item->key_hi,
|
||||
(unsigned long long)parts.front().item->key_lo,
|
||||
info.name.c_str());
|
||||
if (FILE* f = std::fopen(path, "wb")) {
|
||||
std::fwrite(raw.data(), 1, raw.size(), f);
|
||||
std::fclose(f);
|
||||
RAD_INFO("encoder: wrote %s (%lld rows of %lld bytes)", path,
|
||||
(long long)rows, (long long)rowb);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -143,9 +220,9 @@ int Engine::run_encodes() {
|
||||
it.pixels.shrink_to_fit();
|
||||
if (dump_dir && *dump_dir) dump(it, ".bf16", it.embd.data(), it.embd.size());
|
||||
}
|
||||
RAD_DEBUG("encoder: %zu item(s) encoded in %.1f ms", items.size(),
|
||||
std::chrono::duration<double, std::milli>(std::chrono::steady_clock::now() - t0)
|
||||
.count());
|
||||
const double ms = std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - t0).count();
|
||||
RAD_DEBUG("encoder: %zu item(s) encoded in %.1f ms", items.size(), ms);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
|
||||
@@ -247,6 +247,9 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
|
||||
m.n_ff = gi("intermediate_size", gi("moe_intermediate_size", 0));
|
||||
m.n_vocab = gi("vocab_size", 0);
|
||||
m.n_ctx_train = gi("max_position_embeddings", 0);
|
||||
/* The DeepSeek spelling: Unlimited-OCR's decoder is a DeepSeek-V2 MoE and states its expert
|
||||
* count as `n_routed_experts`; a routed config names the count under one of the three and
|
||||
* never under more than one, so the chain is a rename, not a guess. */
|
||||
m.n_expert = gi("num_experts", gi("num_local_experts", gi("n_routed_experts", 0)));
|
||||
m.n_expert_used = gi("num_experts_per_tok", 0);
|
||||
m.n_expert_shared = gi("n_shared_experts", gi("num_shared_experts",
|
||||
@@ -852,7 +855,10 @@ int Checkpoint::open_safetensors(const std::string& path) {
|
||||
RAD_TRY(meta_merge_generation_config(md, &meta_));
|
||||
RAD_TRY(meta_merge_preprocessor_configs(md, &meta_));
|
||||
if (!meta_dir_.empty() && !path_exists(dir_ + "/tokenizer.json")) tok_dir_ = meta_dir_;
|
||||
if (!is_file && !is_index) RAD_TRY(add_companions());
|
||||
if (!is_file && !is_index) {
|
||||
RAD_TRY(add_companions());
|
||||
RAD_TRY(add_torch_files());
|
||||
}
|
||||
/* FP8's block, where the checkpoint states one. */
|
||||
if (const char* bs = meta_.get("quantization_config.weight_block_size")) {
|
||||
long long r = 0, c = 0;
|
||||
@@ -895,6 +901,55 @@ int Checkpoint::add_companions() {
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* PyTorch checkpoints beside the safetensors (torch_zip.h): a model whose part ships only as a
|
||||
* torch.save file, such as Fish Audio drama-3's codec.pth, read as data, never unpickled. Each is
|
||||
* read under `<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() {
|
||||
@@ -2950,7 +3005,6 @@ int ckpt_import_form(CkptWeight* w, const ImportForm& f, std::string* why) {
|
||||
return refuse(RAD_E_FORMAT, "the import rule's form of '" + w->name + "' is malformed");
|
||||
w->enc = e;
|
||||
w->form = f;
|
||||
w->reform = true;
|
||||
w->imported = true;
|
||||
w->trivial = false;
|
||||
w->why = "it is re-expressed by an import rule";
|
||||
|
||||
@@ -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>
|
||||
@@ -212,6 +213,7 @@ private:
|
||||
int open_diffusers();
|
||||
int open_sgm();
|
||||
int add_companions();
|
||||
int add_torch_files();
|
||||
int open_gguf(const std::string& path);
|
||||
void detect_import();
|
||||
|
||||
@@ -220,6 +222,7 @@ private:
|
||||
GgufFile gguf_;
|
||||
MetaOwn meta_;
|
||||
std::vector<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 */
|
||||
@@ -287,10 +290,9 @@ struct CkptWeight {
|
||||
* values in the logical shape, which ckpt_rows_f32 serves. Not trivial, so a recipe rule
|
||||
* stores it. */
|
||||
std::vector<float> derived;
|
||||
/* An `import` rule's form, applied by ckpt_plane_rows (also `imported`). `rounded` counts the
|
||||
* shipped scales `form.scale` does not hold exactly and `max_rel` is their largest relative
|
||||
* change, both found by ckpt_import_form. */
|
||||
bool reform = false;
|
||||
/* An `import` rule's form, applied by ckpt_plane_rows (the weight is then `imported`).
|
||||
* `rounded` counts the shipped scales `form.scale` does not hold exactly and `max_rel` is their
|
||||
* largest relative change, both found by ckpt_import_form. */
|
||||
ImportForm form{};
|
||||
int64_t rounded = 0;
|
||||
double max_rel = 0;
|
||||
|
||||
@@ -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 */
|
||||
|
||||
+207
-45
@@ -64,12 +64,25 @@ namespace {
|
||||
|
||||
constexpr int64_t kAlign = 256;
|
||||
|
||||
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
|
||||
|
||||
struct Sizes {
|
||||
int64_t T = 0, S = 0, L = 0, NB = 0;
|
||||
int64_t NG = 0; /* stateful KV groups */
|
||||
int64_t RS = 0, RN = 0; /* references: samples and clips a request */
|
||||
};
|
||||
|
||||
/* The paged full-attention group, and how many stateful groups sit beside it. */
|
||||
int32_t full_group(const Program& prog, int64_t* n_state) {
|
||||
int32_t full = 0;
|
||||
int64_t ns = 0;
|
||||
for (size_t g = 1; g < prog.kv_groups.size(); ++g) {
|
||||
const int kind = prog.kv_groups[g].decl.kind;
|
||||
if (kind == RAD_KV_FULL && !full) full = (int32_t)g;
|
||||
else if (kind == RAD_KV_LINEAR || kind == RAD_KV_CONV) ++ns;
|
||||
}
|
||||
if (n_state) *n_state = ns;
|
||||
return full;
|
||||
}
|
||||
|
||||
Sizes sizes_of(const Program& prog, int64_t block_size) {
|
||||
const RadAudioGenDecl& d = prog.audio_gen;
|
||||
Sizes z;
|
||||
@@ -77,6 +90,9 @@ Sizes sizes_of(const Program& prog, int64_t block_size) {
|
||||
z.S = prog.ctx.max_seqs;
|
||||
z.L = d.max_lanes;
|
||||
z.NB = block_size > 0 ? (AudioDriver::max_seq_rows(d) + block_size - 1) / block_size : 0;
|
||||
full_group(prog, &z.NG);
|
||||
z.RS = d.ref_max_samples;
|
||||
z.RN = d.ref_max;
|
||||
return z;
|
||||
}
|
||||
|
||||
@@ -110,12 +126,22 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) {
|
||||
z.S * I, /* R_ESLOT */
|
||||
z.S * I, /* R_LROW */
|
||||
z.S * I, /* R_PREFIX */
|
||||
z.S * I, /* R_CTX */
|
||||
z.S * I, /* R_ACC */
|
||||
z.NG * z.S * I, /* R_SBT */
|
||||
z.NG * z.S * AudioDriver::kMaxStateWidth * I, /* R_SIDX */
|
||||
z.S * I, /* R_PSLOT */
|
||||
z.S * I, /* R_PPOS */
|
||||
z.S * I, /* R_PUSED */
|
||||
z.RS * 4, /* R_RAUD */
|
||||
z.RN > 0 ? (z.RN + 1) * I : 0, /* R_RCU */
|
||||
z.RN > 0 ? z.T * I : 0, /* R_RFRM */
|
||||
};
|
||||
int64_t off = 0;
|
||||
for (int r = 0; r < n; ++r) {
|
||||
bytes[r][0] = off;
|
||||
bytes[r][1] = want[r];
|
||||
off = align_up(off + want[r]);
|
||||
off = align_up(off + want[r], kAlign);
|
||||
}
|
||||
return off;
|
||||
}
|
||||
@@ -123,8 +149,10 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) {
|
||||
} /* namespace */
|
||||
|
||||
int64_t AudioDriver::device_bytes(const Program& prog) {
|
||||
if (!prog.is_audio_generator() || prog.kv_groups.size() < 2) return 0;
|
||||
const Sizes z = sizes_of(prog, prog.kv_groups[1].block_size);
|
||||
if (!prog.is_audio_generator()) return 0;
|
||||
const int32_t fg = full_group(prog, nullptr);
|
||||
if (!fg) return 0;
|
||||
const Sizes z = sizes_of(prog, prog.kv_groups[(size_t)fg].block_size);
|
||||
int64_t b[R_N][2];
|
||||
return carve(z, b, R_N);
|
||||
}
|
||||
@@ -136,15 +164,39 @@ int AudioDriver::init(const Program& prog, IKVManager* kv, const std::vector<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;
|
||||
@@ -154,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;
|
||||
@@ -193,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;
|
||||
@@ -224,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)
|
||||
@@ -236,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 "
|
||||
@@ -309,16 +382,19 @@ int AudioDriver::admit_locked() {
|
||||
const float cfg = r.cfg > 0.0f ? r.cfg : (float)decl_.default_cfg;
|
||||
/* The unconditional prompt: the request's own (the conditional one at guidance 1, which
|
||||
* makes the guided logits the conditional ones), or derived from the conditional one. */
|
||||
std::vector<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;
|
||||
@@ -390,7 +466,7 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
RadBatch& B = out_[r];
|
||||
RadAudioGenBatch& A = aout_[r];
|
||||
RadKVGroupBatch& K = kout_[r];
|
||||
RadKVGroupBatch& K = kout_[r * (1 + state_groups_.size())];
|
||||
const int ri = (int)r;
|
||||
B = RadBatch{};
|
||||
B.step = step;
|
||||
@@ -412,8 +488,23 @@ void AudioDriver::base_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int3
|
||||
K.seqused = dptr<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);
|
||||
@@ -434,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;
|
||||
@@ -517,12 +636,13 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
|
||||
for (int g = 0; g < R_N; ++g) reg_[g].used = 0;
|
||||
/* Each branch's rows: both whole, or the same chunk of both (their lengths are then equal). */
|
||||
const int64_t p0 = j.prompt_done;
|
||||
int64_t cb[2];
|
||||
int64_t cb[2] = { 0, 0 };
|
||||
if (decl_.prompt_whole) {
|
||||
cb[0] = j.T;
|
||||
cb[1] = j.Tn;
|
||||
cb[1] = nb_ > 1 ? j.Tn : 0;
|
||||
} else {
|
||||
cb[0] = cb[1] = std::min<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);
|
||||
@@ -530,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) {
|
||||
@@ -549,26 +669,47 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
|
||||
btab[b * pitch + k] = k < (int64_t)bt.size() ? bt[(size_t)k] : -1;
|
||||
used[b] = (int32_t)(p0 + cb[b]);
|
||||
}
|
||||
const int64_t rows = cu[2];
|
||||
const int64_t rows = cu[nb_];
|
||||
const bool last = p0 + cb[0] == j.T;
|
||||
for (int b = 0; b < 2; ++b) {
|
||||
hptr<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) {
|
||||
@@ -577,6 +718,16 @@ const RadBatch* AudioDriver::build_prompt(Job& j, int step) {
|
||||
A.n_lane = 1;
|
||||
A.lane_h = h_lane_.data();
|
||||
A.last_h = h_last_.data();
|
||||
if (n_ref > 0) {
|
||||
const int ri = (int)r;
|
||||
A.n_ref = n_ref;
|
||||
A.ref_samples = (int64_t)q.ref_audio.size();
|
||||
A.ref_audio = dptr<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);
|
||||
@@ -586,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);
|
||||
@@ -599,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;
|
||||
@@ -618,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;
|
||||
@@ -630,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;
|
||||
@@ -637,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 */
|
||||
|
||||
+10
-3
@@ -13,8 +13,6 @@ namespace {
|
||||
|
||||
constexpr int64_t kAlign = 256;
|
||||
|
||||
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
|
||||
|
||||
/* Upper bound on a reference picture's latent tokens: its area plus slack for rounding its sides
|
||||
* to the size multiple. */
|
||||
int64_t ref_tokens_max(const RadGeneratorDecl& d) {
|
||||
@@ -97,7 +95,7 @@ int64_t carve(const Sizes& z, int64_t pixel_ch, int64_t (*bytes)[2], int n) {
|
||||
for (int r = 0; r < n; ++r) {
|
||||
bytes[r][0] = off;
|
||||
bytes[r][1] = want[r][1];
|
||||
off = align_up(off + want[r][1]);
|
||||
off = align_up(off + want[r][1], kAlign);
|
||||
}
|
||||
return off;
|
||||
}
|
||||
@@ -121,6 +119,12 @@ int Driver::init(const Program& prog, IKVManager* kv, const std::vector<RankIO>&
|
||||
kv_ = kv;
|
||||
ranks_ = ranks;
|
||||
table_ = DiscreteTable{};
|
||||
if (decl_.cond_opts & ~(uint32_t)RAD_GEN_COND_REBALANCE) {
|
||||
RAD_ERR("image generator: '%s' declares conditioning options 0x%x, and this engine knows "
|
||||
"only RAD_GEN_COND_REBALANCE (0x%x)", decl_.name ? decl_.name : "",
|
||||
(unsigned)decl_.cond_opts, (unsigned)RAD_GEN_COND_REBALANCE);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (discrete()) {
|
||||
std::string why;
|
||||
if (discrete_table(decl_, &table_, &why) < 0) {
|
||||
@@ -258,6 +262,8 @@ int Driver::submit(std::unique_ptr<Request> r, std::string* why) {
|
||||
!(decl_.samplers & (1u << r->sampler)) || r->scheduler < 0 ||
|
||||
r->scheduler >= RAD_GEN_SCHED_COUNT))
|
||||
return no("the sampler or scheduler is not one this model serves");
|
||||
if ((uint32_t)r->cond_opts & ~decl_.cond_opts)
|
||||
return no("a conditioning option (rebalance) this model does not serve");
|
||||
r->ticket->t_submit_ns = (int64_t)rad_mono_ns();
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
if (closed_) {
|
||||
@@ -530,6 +536,7 @@ void Driver::finish_batches(int64_t n_tok, int64_t n_seq, int32_t max_q, int ste
|
||||
G.size_px = nullptr;
|
||||
G.entry_h = nullptr;
|
||||
G.tokens_h = nullptr;
|
||||
G.cond_opts = 0;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -125,7 +125,6 @@ private:
|
||||
R_BT, R_USED, R_ROPEF, R_ICU, R_IROWS, R_MCU, R_VCU, R_MROWS, R_MSRC, R_MCCU, R_MROPE,
|
||||
R_AUX, R_SIGP, R_TSTEP, R_SAMP, R_STEPI, R_SIZE, R_N };
|
||||
|
||||
int layout_regions();
|
||||
template <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 {
|
||||
return reinterpret_cast<T*>((char*)dev_[(size_t)rank] + reg_[r].off);
|
||||
|
||||
@@ -195,7 +195,6 @@ constexpr int64_t kAlign = 256;
|
||||
* accept up to 4096. */
|
||||
constexpr int64_t kSegCap = 64;
|
||||
|
||||
int64_t align_up(int64_t v) { return (v + kAlign - 1) / kAlign * kAlign; }
|
||||
|
||||
/* Region offsets and sizes, in the enum's order (video_driver.h), and the total; shared by the
|
||||
* allocation and the VRAM budget. `ep` and `pd` are the conditioning encoder's pass bound and
|
||||
@@ -239,7 +238,7 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t ep, int64_t pd,
|
||||
for (int r = 0; r < n; ++r) {
|
||||
bytes[r][0] = off;
|
||||
bytes[r][1] = want[r];
|
||||
off = align_up(off + want[r]);
|
||||
off = align_up(off + want[r], kAlign);
|
||||
}
|
||||
return off;
|
||||
}
|
||||
|
||||
+85
-3
@@ -22,6 +22,13 @@ void take(const char* what, const char* src, double v, double lo, double hi, boo
|
||||
src, what, v, lo_open ? "(" : "[", lo, hi);
|
||||
}
|
||||
|
||||
/* An integer field (a token count), same contract. */
|
||||
void take_i(const char* what, const char* src, int64_t v, int64_t lo, int64_t hi, int* dst) {
|
||||
if (v >= lo && v <= hi) { *dst = (int)v; return; }
|
||||
RAD_WARN("%s states %s %lld, which is outside [%lld, %lld]; ignoring it",
|
||||
src, what, (long long)v, (long long)lo, (long long)hi);
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
SamplingParams GenSampling::onto(SamplingParams base) const {
|
||||
@@ -29,16 +36,36 @@ SamplingParams GenSampling::onto(SamplingParams base) const {
|
||||
if (top_p >= 0.0f) base.top_p = top_p;
|
||||
if (min_p >= 0.0f) base.min_p = min_p;
|
||||
if (top_k >= 0) base.top_k = top_k;
|
||||
if (ngram_ban_n >= 0) base.ngram_ban_n = ngram_ban_n;
|
||||
if (ngram_window >= 0) base.ngram_window = ngram_window;
|
||||
if (!ngram_whitelist.empty()) base.ngram_whitelist = ngram_whitelist;
|
||||
return base;
|
||||
}
|
||||
|
||||
/* The one-line statement of a served sampling configuration. The wording is pinned by
|
||||
* gen_config_test.cpp (gen_config_reads_the_ngram_ban) -- change it there in the same change.
|
||||
* It spells the values out for a log reader; `onto` fills the fields from defaults. The two
|
||||
* share values, not logic, and the duplication of the ban clause is a string, not a rule. */
|
||||
std::string GenSampling::describe(const SamplingParams& sp) {
|
||||
char buf[200];
|
||||
char buf[320];
|
||||
std::snprintf(buf, sizeof buf, "temperature %.2f, top_k %d%s, top_p %.2f, min_p %.2f",
|
||||
(double)sp.temp, sp.top_k,
|
||||
sp.top_k == 0 ? " (the 1024 most likely tokens, the sampler's candidate width)" : "",
|
||||
(double)sp.top_p, (double)sp.min_p);
|
||||
return buf;
|
||||
std::string s(buf);
|
||||
if (sp.ngram_ban_n > 0) {
|
||||
char ban[96];
|
||||
if (sp.ngram_window > 0)
|
||||
std::snprintf(ban, sizeof ban, ", ngram ban n %d over the last %d tokens",
|
||||
sp.ngram_ban_n, sp.ngram_window);
|
||||
else
|
||||
std::snprintf(ban, sizeof ban, ", ngram ban n %d over the whole sequence",
|
||||
sp.ngram_ban_n);
|
||||
s += ban;
|
||||
if (!sp.ngram_whitelist.empty())
|
||||
s += ", whitelist " + std::to_string(sp.ngram_whitelist.size()) + " ids";
|
||||
}
|
||||
return s;
|
||||
}
|
||||
|
||||
std::vector<GenFieldSource> gen_sampling_sources(const GenSampling& stated, const std::string& src,
|
||||
@@ -88,6 +115,47 @@ bool gen_sampling_parse(const std::string& json_text, const char* src, GenSampli
|
||||
if (v >= -1) out->top_k = (int)(v < 0 ? 0 : v);
|
||||
else RAD_WARN("%s states top_k %lld, which is not a count; ignoring it", src, (long long)v);
|
||||
}
|
||||
|
||||
/* The windowed no-repeat-n-gram ban. Its checkpoint name in transformers is
|
||||
* no_repeat_ngram_size / no_repeat_ngram_window_size (Unlimited-OCR ships 35 over the last
|
||||
* 128); this sampler's own names are taken too. The reference's negative window means the
|
||||
* whole sequence, which this sampler spells 0. */
|
||||
it = j.find("no_repeat_ngram_size");
|
||||
if (it == j.end() || !it->is_number_integer()) it = j.find("ngram_ban_n");
|
||||
if (it != j.end() && it->is_number_integer())
|
||||
take_i("no_repeat_ngram_size", src, it->get<int64_t>(), 0, 256, &out->ngram_ban_n);
|
||||
|
||||
it = j.find("no_repeat_ngram_window_size");
|
||||
if (it == j.end() || !it->is_number_integer()) it = j.find("ngram_window");
|
||||
if (it != j.end() && it->is_number_integer()) {
|
||||
const int64_t v = it->get<int64_t>();
|
||||
take_i("no_repeat_ngram_window_size", src, v < 0 ? 0 : v, 0, 131072, &out->ngram_window);
|
||||
}
|
||||
|
||||
/* The ban's whitelist, a JSON array of token ids (the reference's whitelist_token_ids).
|
||||
* Values are warned about and dropped, like every other field here: an id is a vocabulary
|
||||
* coordinate, so a negative one is not a value at all. */
|
||||
it = j.find("no_repeat_ngram_whitelist");
|
||||
if (it != j.end() && !it->is_array()) {
|
||||
/* The legacy key is only a problem when nothing rescues it: a config that states a bad
|
||||
* reference name beside a good sampler-spelled one reads the good one, silently. */
|
||||
const auto own = j.find("ngram_whitelist");
|
||||
if (own == j.end() || !own->is_array())
|
||||
RAD_WARN("%s states a no_repeat_ngram_whitelist that is not an array; ignoring it",
|
||||
src);
|
||||
it = own;
|
||||
}
|
||||
if (it != j.end() && it->is_array()) {
|
||||
for (const auto& v : *it) {
|
||||
const int64_t id = v.is_number_integer() ? v.get<int64_t>() : -1;
|
||||
if (id < 0 || id > INT32_MAX) {
|
||||
RAD_WARN("%s states a no_repeat_ngram_whitelist entry outside [0, %d]; ignoring it",
|
||||
src, INT32_MAX);
|
||||
continue;
|
||||
}
|
||||
out->ngram_whitelist.push_back((int)id);
|
||||
}
|
||||
}
|
||||
return out->any();
|
||||
}
|
||||
|
||||
@@ -105,7 +173,9 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
|
||||
/* Rebuilt as JSON and passed to gen_sampling_parse, so container metadata and the original
|
||||
* file share one set of range checks and one reading of `do_sample`. */
|
||||
nlohmann::json j = nlohmann::json::object();
|
||||
static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k" };
|
||||
static const char* const kFields[] = { "do_sample", "temperature", "top_p", "min_p", "top_k",
|
||||
"no_repeat_ngram_size", "no_repeat_ngram_window_size",
|
||||
"no_repeat_ngram_whitelist" };
|
||||
for (const char* k : kFields) {
|
||||
const char* v = get(k);
|
||||
if (!v || !*v) continue;
|
||||
@@ -114,6 +184,17 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
|
||||
j[k] = (std::strcmp(v, "0") != 0);
|
||||
continue;
|
||||
}
|
||||
if (std::strcmp(k, "no_repeat_ngram_whitelist") == 0) {
|
||||
/* Not a number: the container's metadata is string-valued, and the whitelist is a
|
||||
* JSON array spelled as JSON text. */
|
||||
try {
|
||||
j[k] = nlohmann::json::parse(v);
|
||||
} catch (const std::exception& e) {
|
||||
RAD_WARN("the container states generation.%s as \"%s\", which is not a JSON "
|
||||
"array of ids (%s); ignoring it", k, v, e.what());
|
||||
}
|
||||
continue;
|
||||
}
|
||||
char* end = nullptr;
|
||||
const double d = std::strtod(v, &end);
|
||||
if (end == v) {
|
||||
@@ -122,6 +203,7 @@ bool gen_sampling_from_kv(const std::function<const char*(const char*)>& get, Ge
|
||||
continue;
|
||||
}
|
||||
if (std::strcmp(k, "top_k") == 0) j[k] = (int64_t)d;
|
||||
else if (std::strncmp(k, "no_repeat_ngram", 15) == 0) j[k] = (int64_t)d;
|
||||
else j[k] = d;
|
||||
}
|
||||
if (j.empty()) return false;
|
||||
|
||||
+16
-3
@@ -20,17 +20,30 @@
|
||||
namespace rad {
|
||||
|
||||
/* One config's sampler fields. -1 means "not stated", since 0 is a legal value of each (greedy
|
||||
* temperature, top_k off, min_p off). */
|
||||
* temperature, top_k off, min_p off, n-gram ban off). */
|
||||
struct GenSampling {
|
||||
float temp = -1.0f, top_p = -1.0f, min_p = -1.0f;
|
||||
int top_k = -1;
|
||||
/* The windowed no-repeat-n-gram ban (transformers' no_repeat_ngram_size /
|
||||
* no_repeat_ngram_window_size; Unlimited-OCR ships 35 over the last 128). `ngram_window` is
|
||||
* normalized to 0, this sampler's "the whole sequence", when the config states it negative. */
|
||||
int ngram_ban_n = -1, ngram_window = -1;
|
||||
/* The ban's whitelist: token ids the ban must never ban (the reference processor's
|
||||
* `whitelist_token_ids`, removed from the banned set before the -inf writes). Transformers
|
||||
* has no field for it; a container states it as `generation.no_repeat_ngram_whitelist`, a
|
||||
* JSON array of ids. Empty means not stated. */
|
||||
std::vector<int32_t> ngram_whitelist;
|
||||
|
||||
bool any() const { return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0; }
|
||||
bool any() const {
|
||||
return temp >= 0.0f || top_p >= 0.0f || min_p >= 0.0f || top_k >= 0 ||
|
||||
ngram_ban_n >= 0 || ngram_window >= 0 || !ngram_whitelist.empty();
|
||||
}
|
||||
|
||||
/* Overlay onto `base` field by field; unstated fields keep base's, so sources stack. */
|
||||
SamplingParams onto(SamplingParams base) const;
|
||||
|
||||
/* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00", for the startup log line. */
|
||||
/* "temperature 0.70, top_k 20 (off), top_p 0.95, min_p 0.00, ngram ban n 35 over the last 128
|
||||
* tokens", for the startup log line (the last part only when a ban is on). */
|
||||
static std::string describe(const SamplingParams& sp);
|
||||
};
|
||||
|
||||
|
||||
+2
-7
@@ -39,11 +39,6 @@ bool repo_part(const std::string& p) {
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ends_with(const std::string& s, const char* suf) {
|
||||
const size_t n = std::strlen(suf);
|
||||
return s.size() >= n && s.compare(s.size() - n, n, suf) == 0;
|
||||
}
|
||||
|
||||
/* <exe>/../libexec/radiance/hfget.sh, which is where the install puts it and where the build
|
||||
* copies it. */
|
||||
std::string hfget_path() {
|
||||
@@ -85,7 +80,7 @@ bool hf_repo_id(const std::string& s) {
|
||||
const std::string owner = s.substr(0, slash), name = s.substr(slash + 1);
|
||||
if (!repo_part(owner) || !repo_part(name)) return false;
|
||||
for (const char* suf : { ".rad", ".safetensors", ".gguf", ".json" })
|
||||
if (ends_with(name, suf)) return false;
|
||||
if (name.ends_with(suf)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -102,7 +97,7 @@ std::string hf_served_path(const std::string& dir, std::string* why) {
|
||||
std::error_code ec;
|
||||
for (const fs::directory_entry& e : fs::directory_iterator(dir, ec)) {
|
||||
std::error_code fe;
|
||||
if (e.is_regular_file(fe) && ends_with(e.path().filename().string(), ".rad"))
|
||||
if (e.is_regular_file(fe) && e.path().filename().string().ends_with(".rad"))
|
||||
rad.push_back(e.path().filename().string());
|
||||
}
|
||||
if (ec) {
|
||||
|
||||
@@ -36,11 +36,6 @@ int fail(std::string* err, int code, const std::string& m) {
|
||||
return code;
|
||||
}
|
||||
|
||||
bool ends_with(const std::string& s, const char* p) {
|
||||
const size_t n = std::strlen(p);
|
||||
return s.size() >= n && s.compare(s.size() - n, n, p) == 0;
|
||||
}
|
||||
|
||||
std::string shape_str(const std::vector<int64_t>& s) {
|
||||
std::string r = "[";
|
||||
for (size_t i = 0; i < s.size(); ++i) r += (i ? ", " : "") + std::to_string(s[i]);
|
||||
@@ -290,7 +285,7 @@ int AdapterFile::open(const std::string& path, std::string* err) {
|
||||
for (const StTensor& t : st_.tensors()) {
|
||||
const Suffix* hit = nullptr;
|
||||
for (const Suffix& s : kSuffix)
|
||||
if (ends_with(t.name, s.s) && (!hit || std::strlen(s.s) > std::strlen(hit->s))) hit = &s;
|
||||
if (t.name.ends_with(s.s) && (!hit || std::strlen(s.s) > std::strlen(hit->s))) hit = &s;
|
||||
if (!hit) {
|
||||
skipped_.push_back({ t.name, "not an adapter tensor" });
|
||||
continue;
|
||||
@@ -610,7 +605,7 @@ std::regex pattern(const std::string& from, bool kohya) {
|
||||
}
|
||||
|
||||
std::string module_of(const std::string& src) {
|
||||
return ends_with(src, ".weight") ? src.substr(0, src.size() - 7) : std::string();
|
||||
return src.ends_with(".weight") ? src.substr(0, src.size() - 7) : std::string();
|
||||
}
|
||||
|
||||
} /* namespace */
|
||||
|
||||
+7
-16
@@ -41,15 +41,6 @@ int fail(std::string* err, int code, const std::string& m) {
|
||||
return code;
|
||||
}
|
||||
|
||||
bool starts_with(const std::string& s, const char* p) {
|
||||
const size_t n = std::strlen(p);
|
||||
return s.size() >= n && s.compare(0, n, p) == 0;
|
||||
}
|
||||
bool ends_with(const std::string& s, const char* p) {
|
||||
const size_t n = std::strlen(p);
|
||||
return s.size() >= n && s.compare(s.size() - n, n, p) == 0;
|
||||
}
|
||||
|
||||
std::vector<std::string> split_dots(const std::string& s) {
|
||||
std::vector<std::string> v;
|
||||
size_t at = 0;
|
||||
@@ -64,7 +55,7 @@ std::vector<std::string> split_dots(const std::string& s) {
|
||||
|
||||
/* `<module>.weight` -> module and its leaf; "" when the source is not a `.weight` tensor. */
|
||||
std::string module_of(const std::string& src, std::string* leaf) {
|
||||
if (!ends_with(src, ".weight")) return "";
|
||||
if (!src.ends_with(".weight")) return "";
|
||||
std::string m = src.substr(0, src.size() - 7);
|
||||
if (m.empty()) return "";
|
||||
const size_t d = m.rfind('.');
|
||||
@@ -100,7 +91,7 @@ const char* excluded_weight(const Program& prog, const WeightInfo& w) {
|
||||
return "a drafter / MTP layer (layer group at or above meta.n_layers)";
|
||||
static const char* const kScopes[] = { "draft.", "vision.", "audio.", "mtp." };
|
||||
for (const char* s : kScopes)
|
||||
if (starts_with(w.name, s)) return "a non-trunk builder scope";
|
||||
if (w.name.starts_with(s)) return "a non-trunk builder scope";
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
@@ -743,9 +734,9 @@ int build_sites(const Program& prog, const TargetSet& targets, int max_rank,
|
||||
std::string explain_module(const Program& prog, const TargetSet& targets, const std::string& module) {
|
||||
const std::string want[3] = {
|
||||
module,
|
||||
starts_with(module, "model.") && !starts_with(module, "model.language_model.")
|
||||
module.starts_with("model.") && !module.starts_with("model.language_model.")
|
||||
? "model.language_model." + module.substr(6) : "",
|
||||
starts_with(module, "model.language_model.") ? "model." + module.substr(21) : "" };
|
||||
module.starts_with("model.language_model.") ? "model." + module.substr(21) : "" };
|
||||
std::string first;
|
||||
bool any = false;
|
||||
for (const RadNameMap& m : prog.name_map) {
|
||||
@@ -939,7 +930,7 @@ int load_adapter(const std::string& dir, const std::vector<Site>& sites, int max
|
||||
if (!std::regex_match(k, m, key_re)) {
|
||||
std::string why = "is not a linear LoRA A/B tensor";
|
||||
if (k.find("lora_embedding_") != std::string::npos) why = "is an embedding LoRA tensor";
|
||||
else if (ends_with(k, ".bias")) why = "is a trained bias";
|
||||
else if (k.ends_with(".bias")) why = "is a trained bias";
|
||||
else if (k.find("modules_to_save") != std::string::npos) why = "is a modules_to_save copy";
|
||||
else if (k.find("lora_magnitude_vector") != std::string::npos) why = "is a DoRA magnitude";
|
||||
return fail(err, RAD_E_UNSUPPORTED, st_path + ": tensor " + k + " " + why +
|
||||
@@ -1034,9 +1025,9 @@ int pack_modules(const std::vector<Site>& sites, int max_rank,
|
||||
for (auto& kv : mods) {
|
||||
const AdModule& am = kv.second;
|
||||
std::vector<std::string> cand{ am.name };
|
||||
if (starts_with(am.name, "model.") && !starts_with(am.name, "model.language_model."))
|
||||
if (am.name.starts_with("model.") && !am.name.starts_with("model.language_model."))
|
||||
cand.push_back("model.language_model." + am.name.substr(6));
|
||||
if (starts_with(am.name, "model.language_model."))
|
||||
if (am.name.starts_with("model.language_model."))
|
||||
cand.push_back("model." + am.name.substr(21));
|
||||
std::vector<std::string> hit;
|
||||
for (const std::string& c : cand) if (where.count(c)) hit.push_back(c);
|
||||
|
||||
+261
-16
@@ -2,6 +2,7 @@
|
||||
#include "mem/kv.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
|
||||
namespace rad {
|
||||
@@ -76,6 +77,7 @@ static const char* kv_kind_name(int k) {
|
||||
case RAD_KV_WINDOW: return "window";
|
||||
case RAD_KV_LINEAR: return "linear";
|
||||
case RAD_KV_CONV: return "conv";
|
||||
case RAD_KV_RING: return "ring";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
@@ -126,7 +128,10 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
KVGroupPlan p;
|
||||
p.index = (int32_t)i;
|
||||
p.name = g.name.empty() ? fmt("kv%zu", i) : g.name;
|
||||
p.kind = g.decl.kind;
|
||||
/* R-SWA: RAD_KV_RING is a window group whose floor is per sequence (declare_runtime_window
|
||||
* / SeqWindow), so it plans as a RAD_KV_WINDOW group with `runtime_win` set below. No
|
||||
* other plan-path code has to know the kind. */
|
||||
p.kind = g.decl.kind == RAD_KV_RING ? RAD_KV_WINDOW : g.decl.kind;
|
||||
p.n_layers = (int64_t)g.layers.size();
|
||||
|
||||
if (p.n_layers <= 0) {
|
||||
@@ -161,7 +166,9 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
}
|
||||
if (p.kind == RAD_KV_WINDOW) {
|
||||
if (g.decl.window <= 0) {
|
||||
RAD_ERR("KV group '%s': RAD_KV_WINDOW with window 0", p.name.c_str());
|
||||
RAD_ERR("KV group '%s': %s with window 0", p.name.c_str(),
|
||||
g.decl.kind == RAD_KV_RING ? "RAD_KV_RING (the ring's W)"
|
||||
: "RAD_KV_WINDOW");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
/* +1 because a window that is not block-aligned straddles one extra block. */
|
||||
@@ -233,6 +240,28 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
}
|
||||
bundling_ = compare_bundling(bundles);
|
||||
|
||||
/* R-SWA: a declared runtime window turns the group's plan over to per-sequence windows (see
|
||||
* declare_runtime_window). Applied after every declaration above, so a fixed-window group's
|
||||
* plan is exactly what it was. */
|
||||
for (auto& p : plans_) apply_runtime_window(p);
|
||||
/* A RAD_KV_RING group carries a runtime window by its kind, whether or not the caller had a
|
||||
* manager to declare it on first (the engine's sizing probes declare it, but plan_groups must
|
||||
* not depend on that). `window` is the ring's W. */
|
||||
for (size_t i = 1; i < plans_.size(); ++i) {
|
||||
KVGroupPlan& p = plans_[i];
|
||||
if (groups[i].decl.kind != RAD_KV_RING || p.runtime_win) continue;
|
||||
p.runtime_win = true;
|
||||
p.runtime_tokens = groups[i].decl.window;
|
||||
p.win_snap = false;
|
||||
}
|
||||
for (const auto& [g, w] : runtime_decl_) {
|
||||
if (g < 0 || g >= (int32_t)plans_.size() || !plans_[(size_t)g].runtime_win) {
|
||||
RAD_ERR("declare_runtime_window(%d): the group is not a RAD_KV_WINDOW or RAD_KV_RING "
|
||||
"group in this program (a runtime window needs a windowed group)", (int)g);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
/* ---- fixed costs first: they are not per-token ---- */
|
||||
checkpoint_bytes_ = 0;
|
||||
window_ck_bytes_ = 0;
|
||||
@@ -243,7 +272,7 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
for (size_t i = 1; i < plans_.size(); ++i) {
|
||||
KVGroupPlan& p = plans_[i];
|
||||
p.win_snap = !has_state && p.kind == RAD_KV_WINDOW && p.window_blocks > 0 &&
|
||||
!groups[i].drafter;
|
||||
!p.runtime_win && !groups[i].drafter;
|
||||
if (p.win_snap && !p.zero && p.n_layers > 0)
|
||||
window_ck_bytes_ += p.window_blocks * p.bytes_per_block;
|
||||
}
|
||||
@@ -257,26 +286,107 @@ int KVManager::plan_groups(const std::vector<KVGroupInfo>& groups, const Config&
|
||||
if (p.stateful()) fixed += align_up(p.bytes_per_state * p.n_states, RAD_ALIGN_UNIT);
|
||||
/* And one unit per paged group, whose size need not be a multiple of the alignment. */
|
||||
for (const auto& p : plans_) if (p.paged()) fixed += RAD_ALIGN_UNIT;
|
||||
/* A runtime window's ring is per sequence and on top of the context the split sizes: one
|
||||
* ring a sequence, carved as a fixed cost. Its reference is the context itself, which the
|
||||
* split already covers (the group is not capped at window_blocks). */
|
||||
for (const auto& p : plans_)
|
||||
if (p.runtime_win && !p.zero)
|
||||
fixed += align_up(max_seqs_ * p.ring_blocks_max() * p.bytes_per_block, RAD_ALIGN_UNIT);
|
||||
|
||||
fixed_ = fixed;
|
||||
ckpts_ = budget_ckpts;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* Windowed groups are capped at window_pool_cap, as in carve(). */
|
||||
/* Windowed groups are capped at window_pool_cap, as in carve(). A runtime-window group is not:
|
||||
* its blocks are the reference (one context a sequence, as a FULL group) plus the ring its fixed
|
||||
* costs already carry. */
|
||||
int64_t KVManager::ceiling(int64_t ctx) const {
|
||||
if (ctx <= 0) return 0;
|
||||
int64_t need = fixed_;
|
||||
for (const auto& p : plans_) {
|
||||
if (!p.paged() || p.block_size <= 0) continue;
|
||||
int64_t blocks = max_seqs_ * ((ctx + p.block_size - 1) / p.block_size);
|
||||
if (p.kind == RAD_KV_WINDOW && p.window_blocks > 0)
|
||||
if (p.kind == RAD_KV_WINDOW && !p.runtime_win && p.window_blocks > 0)
|
||||
blocks = std::min(blocks, window_pool_cap(p));
|
||||
need += blocks * p.bytes_per_block;
|
||||
}
|
||||
return need;
|
||||
}
|
||||
|
||||
/* Moves a WINDOW group's plan to per-sequence runtime windows (declare_runtime_window). Returns
|
||||
* false for any other group, so plan_groups() can apply it to every plan unconditionally. */
|
||||
bool KVManager::apply_runtime_window(KVGroupPlan& p) const {
|
||||
auto it = runtime_decl_.find(p.index);
|
||||
if (it == runtime_decl_.end() || p.kind != RAD_KV_WINDOW || p.runtime_win) return false;
|
||||
p.runtime_win = true;
|
||||
p.runtime_tokens = it->second;
|
||||
/* The window a sequence may inherit (a fixed-window cap) is no longer the bound, and the
|
||||
* declare-time window is not the sequence's own, so nothing here is snapshot-able. */
|
||||
p.win_snap = false;
|
||||
return true;
|
||||
}
|
||||
|
||||
int KVManager::declare_runtime_window(int32_t g, int64_t window_tokens) {
|
||||
if (g <= 0 || window_tokens <= 0) {
|
||||
RAD_ERR("declare_runtime_window: group %d with a window of %lld (a runtime window needs a "
|
||||
"real group and a positive W)", (int)g, (long long)window_tokens);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const KVGroupPlan* p = plan(g);
|
||||
if (p && p->kind != RAD_KV_WINDOW) {
|
||||
RAD_ERR("group '%s' is not RAD_KV_WINDOW or RAD_KV_RING, so it cannot carry a runtime "
|
||||
"window", p->name.c_str());
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (p && p->runtime_win && p->runtime_tokens != window_tokens) {
|
||||
/* A RAD_KV_RING group's W is its declaration's `window`, and one already planned for
|
||||
* another W has its ring in the fixed costs. */
|
||||
RAD_ERR("declare_runtime_window(%d): group '%s' already carries a runtime window of %lld "
|
||||
"tokens, and its ring is sized for that", (int)g, p->name.c_str(),
|
||||
(long long)p->runtime_tokens);
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (configured_) {
|
||||
RAD_ERR("declare_runtime_window(%d) after the carve: the group's blocks and fixed costs "
|
||||
"are already sized for a different window", (int)g);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
runtime_decl_[g] = window_tokens;
|
||||
/* A plan built before the declaration (the engine's probes, or plan_groups() then declare)
|
||||
* is updated in place; the next plan_groups() picks the declaration up on its own.
|
||||
*
|
||||
* A plan set shorter than `g` returns RAD_E_INVAL below with this store kept: deliberate.
|
||||
* The declaration is the caller's standing intent (it survives forget(), whose vectors are
|
||||
* emptied together and are not this map), and the short plan set is the probe ordering the
|
||||
* declaration exists for -- the next plan_groups() applies it to a plan that has the group. */
|
||||
if (!plans_.empty()) {
|
||||
if (g >= (int32_t)plans_.size()) return RAD_E_INVAL;
|
||||
KVGroupPlan& q = plans_[(size_t)g];
|
||||
/* Whether the plan counted this group's window snapshot section (plan_groups' rule). */
|
||||
const bool counted = q.win_snap && !q.zero && q.n_layers > 0;
|
||||
if (!apply_runtime_window(q)) return RAD_OK; /* already applied */
|
||||
/* The cost this declaration adds, against the plan as published: the ring is one a
|
||||
* sequence, and the group gives up its window snapshot section. */
|
||||
fixed_ += align_up(max_seqs_ * q.ring_blocks_max() * q.bytes_per_block, RAD_ALIGN_UNIT);
|
||||
if (counted) {
|
||||
const int64_t was = q.window_blocks * q.bytes_per_block;
|
||||
/* The plan counted this group's snapshot section, so both totals carry `was`.
|
||||
* Saturating hides an accounting bug; surface it in debug builds. */
|
||||
assert(window_ck_bytes_ >= was && checkpoint_bytes_ >= was &&
|
||||
"runtime window: snapshot byte totals below the section being removed");
|
||||
window_ck_bytes_ = window_ck_bytes_ > was ? window_ck_bytes_ - was : 0;
|
||||
checkpoint_bytes_ = checkpoint_bytes_ > was ? checkpoint_bytes_ - was : 0;
|
||||
}
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t KVManager::runtime_window_tokens(int32_t g) const {
|
||||
const KVGroupPlan* p = plan(g);
|
||||
return p && p->runtime_win ? p->runtime_tokens : 0;
|
||||
}
|
||||
|
||||
/* The vectors parallel to plans_ are filled at different points of the carve, so a partial carve
|
||||
* would leave plans_ passing bounds checks (reserve_block checks plans_, then reads free_usable_)
|
||||
* over empty block state. On failure forget() empties both, so every entry point refuses
|
||||
@@ -329,11 +439,11 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
|
||||
if (tokens_cap_ > 0 && tokens > tokens_cap_) tokens = tokens_cap_;
|
||||
|
||||
/* A windowed group cannot address past its pool cap; cap it and give the bytes back to
|
||||
* the others. */
|
||||
* the others. A runtime-window group's cap is the context plus its ring (a fixed cost). */
|
||||
int32_t capped = -1;
|
||||
for (int32_t i : open) {
|
||||
const auto& p = plans_[i];
|
||||
if (p.kind != RAD_KV_WINDOW) continue;
|
||||
if (p.kind != RAD_KV_WINDOW || p.runtime_win) continue;
|
||||
if (tokens / p.block_size > window_pool_cap(p)) { capped = i; break; }
|
||||
}
|
||||
if (capped < 0) break;
|
||||
@@ -370,7 +480,8 @@ int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
|
||||
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
|
||||
if (tokens == kUnboundedTokens) return 0;
|
||||
const int64_t b = tokens / p.block_size;
|
||||
if (p.kind == RAD_KV_WINDOW && b > window_pool_cap(p)) return window_pool_cap(p);
|
||||
if (p.kind == RAD_KV_WINDOW && !p.runtime_win && b > window_pool_cap(p))
|
||||
return window_pool_cap(p);
|
||||
return b;
|
||||
}
|
||||
|
||||
@@ -509,20 +620,31 @@ int KVManager::carve_into(Pool& kv_pool) {
|
||||
|
||||
configured_ = true;
|
||||
report_ = bundling_.report();
|
||||
/* A runtime-window group reads as "ring": its window is the sequence's own, not the plan's. */
|
||||
auto kind_of = [](const KVGroupPlan& p) {
|
||||
return p.runtime_win ? "ring" : kv_kind_name(p.kind);
|
||||
};
|
||||
for (const auto& p : plans_) {
|
||||
if (p.paged())
|
||||
report_ += fmt(" %-14s %-6s %3lld layers block %4lld tok page %8s "
|
||||
"%7lld blocks = %9s (%lld tokens)\n",
|
||||
p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers,
|
||||
p.name.c_str(), kind_of(p), (long long)p.n_layers,
|
||||
(long long)p.block_size, humanb(p.bytes_per_block).c_str(),
|
||||
(long long)p.n_blocks, humanb(p.pool_bytes).c_str(),
|
||||
(long long)(p.n_blocks * p.block_size));
|
||||
else
|
||||
report_ += fmt(" %-14s %-6s %3lld layers state %8s %7lld slots = %9s\n",
|
||||
p.name.c_str(), kv_kind_name(p.kind), (long long)p.n_layers,
|
||||
p.name.c_str(), kind_of(p), (long long)p.n_layers,
|
||||
humanb(p.bytes_per_state).c_str(),
|
||||
(long long)p.n_states, humanb(p.pool_bytes).c_str());
|
||||
}
|
||||
for (const auto& p : plans_) {
|
||||
if (!p.runtime_win) continue;
|
||||
report_ += fmt(" %-14s runtime window W=%lld: a sequence keeps its reference and a ring "
|
||||
"of at most %lld block(s), rewritten in place\n",
|
||||
p.name.c_str(), (long long)p.runtime_tokens,
|
||||
(long long)p.ring_blocks_max());
|
||||
}
|
||||
/* The pool's address range, so a GPU fault address can be placed in the carve. */
|
||||
report_ += fmt(" pool at %p, %s; groups at +%lld..+%lld\n",
|
||||
pool_base_, humanb(pool_ ? pool_->bytes() : 0).c_str(),
|
||||
@@ -805,7 +927,17 @@ int64_t KVManager::blocks_for(int32_t g, int64_t n_tokens) const {
|
||||
const KVGroupPlan* p = plan(g);
|
||||
if (!p || !p->paged() || n_tokens <= 0) return 0;
|
||||
int64_t n = ceil_div(n_tokens, p->block_size);
|
||||
if (p->kind == RAD_KV_WINDOW) n = std::min(n, window_seq_cap(*p));
|
||||
if (p->kind == RAD_KV_WINDOW) {
|
||||
if (p->runtime_win) {
|
||||
/* The reference's blocks up to n, plus one ring. Without a sequence the floor is
|
||||
* unknown, so the whole context is the bound on the reference. */
|
||||
const int64_t ring = p->ring_blocks_max();
|
||||
const int64_t ctx = max_ctx_ > 0 ? max_ctx_ : n_tokens;
|
||||
n = std::min(n, ceil_div(ctx, p->block_size)) + ring;
|
||||
} else {
|
||||
n = std::min(n, window_seq_cap(*p));
|
||||
}
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
@@ -836,6 +968,7 @@ int KVManager::add_sequence(uint64_t id) {
|
||||
s.id = id;
|
||||
s.blocks.resize(plans_.size());
|
||||
s.first_block_pos.assign(plans_.size(), 0);
|
||||
s.win.resize(plans_.size());
|
||||
s.state.assign(plans_.size(), -1);
|
||||
s.dirty_from.assign(plans_.size(), 0);
|
||||
seqs_.emplace(id, std::move(s));
|
||||
@@ -853,6 +986,9 @@ int KVManager::preempt(uint64_t id) {
|
||||
for (int32_t b : s->blocks[g]) drop_block((int32_t)g, b);
|
||||
s->blocks[g].clear();
|
||||
s->first_block_pos[g] = 0;
|
||||
/* The runtime window goes with the blocks: re-admission re-arms it at the prompt end
|
||||
* (the scheduler's admission path calls set_window again before the KV grows). */
|
||||
s->win[g] = SeqWindow{};
|
||||
s->dirty_from[g] = 0;
|
||||
/* The recurrent state goes too (see preempt in kv.h, spec §7.1). */
|
||||
if (s->state[g] >= 0) { drop_state((int32_t)g, s->state[g]); s->state[g] = -1; }
|
||||
@@ -870,6 +1006,12 @@ int KVManager::rollback(uint64_t id, int64_t n_tokens) {
|
||||
if (n_tokens < 0) return RAD_E_INVAL;
|
||||
/* Nothing to free; RAD_OK so "every draft accepted" needs no special path in the caller. */
|
||||
if (n_tokens >= s->n_tokens) return RAD_OK;
|
||||
/* A runtime-windowed sequence unwinds nothing: the ring's slots are reused once it is full,
|
||||
* so the slots a rejected verify wrote may already hold newer keys. The scheduler gates
|
||||
* drafting on has_runtime_window, so this refuses rather than corrupts, and only a caller
|
||||
* that drafts beside a runtime window can reach it. */
|
||||
for (const SeqWindow& w : s->win)
|
||||
if (w.set) return RAD_E_UNSUPPORTED;
|
||||
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const auto& p = plans_[g];
|
||||
@@ -899,6 +1041,80 @@ int64_t KVManager::first_block_pos(uint64_t id, int32_t g) const {
|
||||
return s->first_block_pos[(size_t)g];
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ the runtime window */
|
||||
|
||||
int KVManager::set_window(uint64_t id, int64_t visible_lo, int64_t window_tokens) {
|
||||
if (!configured_) return RAD_E_STATE;
|
||||
Seq* s = find(id);
|
||||
if (!s) return RAD_E_NOTFOUND;
|
||||
if (visible_lo < 0 || window_tokens <= 0) return RAD_E_INVAL;
|
||||
/* The reference is written linearly, so the floor cannot be behind KV the sequence already
|
||||
* holds: rebasing would have to move blocks the ring has not been shaped for. */
|
||||
if (visible_lo < s->n_tokens) {
|
||||
RAD_ERR("sequence %llu: runtime window floor %lld is behind its %lld held tokens",
|
||||
(unsigned long long)id, (long long)visible_lo, (long long)s->n_tokens);
|
||||
return RAD_E_STATE;
|
||||
}
|
||||
bool any = false;
|
||||
/* With a declared runtime window in the program, arm exactly the declared groups: a plain
|
||||
* fixed-window group beside them is carved for its fixed window, and arming it silently
|
||||
* converts it. With none declared this is the caller-sizes-the-pool path kv.h states, and
|
||||
* every windowed group arms as before. */
|
||||
bool declared = false;
|
||||
for (const KVGroupPlan& p : plans_)
|
||||
if (p.kind == RAD_KV_WINDOW && p.runtime_win) declared = true;
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
if (p.kind != RAD_KV_WINDOW) continue;
|
||||
if (declared && !p.runtime_win) {
|
||||
RAD_ERR("sequence %llu: set_window meets fixed-window group '%s' beside a declared "
|
||||
"runtime window; its pool is carved for its fixed window and the mix is not "
|
||||
"supported", (unsigned long long)id, p.name.c_str());
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
SeqWindow w;
|
||||
w.set = true;
|
||||
w.window = window_tokens;
|
||||
w.visible_lo = visible_lo;
|
||||
/* Whole blocks: the ring starts at the first boundary at or after the floor, and the
|
||||
* tokens in [visible_lo, ring_pos) stay in the reference's last block (SeqWindow). The
|
||||
* ring itself must span all of W: the frozen tokens are the oldest of the tail, so a
|
||||
* smaller ring would lose the last W - span positions. */
|
||||
w.ring_pos = ceil_div(visible_lo, p.block_size) * p.block_size;
|
||||
w.ring_blocks = ceil_div(window_tokens, p.block_size);
|
||||
if (w.ring_blocks < 1) w.ring_blocks = 1; /* the ring always has somewhere to write */
|
||||
/* What the sequence can hold: the reference's blocks, then the whole ring. */
|
||||
const int64_t need = w.ring_pos / p.block_size + w.ring_blocks;
|
||||
if (p.n_blocks > 0 && need > p.n_blocks) return RAD_E_FULL;
|
||||
s->win[g] = w;
|
||||
any = true;
|
||||
}
|
||||
if (!any) return RAD_E_UNSUPPORTED;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
bool KVManager::runtime_window(uint64_t id, int32_t g, SeqWindow* out) const {
|
||||
const Seq* s = find(id);
|
||||
if (!s || g < 0 || g >= (int32_t)s->win.size() || !s->win[(size_t)g].set) return false;
|
||||
if (out) *out = s->win[(size_t)g];
|
||||
return true;
|
||||
}
|
||||
|
||||
bool KVManager::has_runtime_window(uint64_t id) const {
|
||||
const Seq* s = find(id);
|
||||
if (!s) return false;
|
||||
for (const SeqWindow& w : s->win) if (w.set) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* What ensure() must have in the table for `n_tokens`: the reference grows linearly until the
|
||||
* floor, then the ring fills up to its whole span and never grows again. */
|
||||
int64_t KVManager::window_table_len(const KVGroupPlan& p, const SeqWindow& w, int64_t n_tokens) {
|
||||
const int64_t ref = w.ring_pos / p.block_size;
|
||||
if (n_tokens <= w.ring_pos) return ceil_div(n_tokens, p.block_size);
|
||||
return ref + std::min(w.ring_blocks, ceil_div(n_tokens - w.ring_pos, p.block_size));
|
||||
}
|
||||
|
||||
int64_t KVManager::seq_tokens(uint64_t id) const { const Seq* s = find(id); return s ? s->n_tokens : 0; }
|
||||
|
||||
int64_t KVManager::take_table_changes(uint64_t id, int32_t g) const {
|
||||
@@ -1023,11 +1239,15 @@ int64_t KVManager::step_blocks(const KVGroupPlan& p) const {
|
||||
/* Slides from the step's first query, not its last. The query at keep_from reads keys down to
|
||||
* keep_from - window + 1, which lies in block keep_from / block - (window_blocks - 1) or later
|
||||
* (window_blocks - 1 >= window / block). A target from the step's end is the same for a decode
|
||||
* step but drops keys the earlier rows of a prefill chunk still need. */
|
||||
* step but drops keys the earlier rows of a prefill chunk still need.
|
||||
*
|
||||
* A sequence with a runtime window is left alone. Its visible set is anchored at 0, so nothing in
|
||||
* the table is below a sliding floor to recycle; the ring's blocks are rewritten in place and
|
||||
* the table never moves (SeqWindow). */
|
||||
void KVManager::recycle_window(Seq* s, int64_t keep_from) {
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const auto& p = plans_[g];
|
||||
if (p.kind != RAD_KV_WINDOW) continue;
|
||||
if (p.kind != RAD_KV_WINDOW || s->win[g].set) continue;
|
||||
int64_t first = s->first_block_pos[g] / p.block_size;
|
||||
int64_t target = std::max<int64_t>(first,
|
||||
keep_from / p.block_size - (p.window_blocks - 1));
|
||||
@@ -1066,7 +1286,9 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
|
||||
const auto& p = plans_[g];
|
||||
if (p.paged()) {
|
||||
int64_t first = s->first_block_pos[g] / p.block_size;
|
||||
int64_t want = ceil_div(n_tokens, p.block_size) - first;
|
||||
int64_t want = s->win[g].set
|
||||
? window_table_len(p, s->win[g], n_tokens) - first
|
||||
: ceil_div(n_tokens, p.block_size) - first;
|
||||
need[g] = want - (int64_t)s->blocks[g].size();
|
||||
if (need[g] < 0) need[g] = 0;
|
||||
/* Copy-on-write: the partial block is the only one a write reaches; if it is shared,
|
||||
@@ -1102,7 +1324,9 @@ int KVManager::ensure(uint64_t id, int64_t n_tokens, int64_t keep_from) {
|
||||
}
|
||||
}
|
||||
}
|
||||
int64_t want = ceil_div(n_tokens, p.block_size) - first;
|
||||
int64_t want = s->win[g].set
|
||||
? window_table_len(p, s->win[g], n_tokens) - first
|
||||
: ceil_div(n_tokens, p.block_size) - first;
|
||||
if ((int64_t)s->blocks[g].size() < want)
|
||||
s->dirty_from[g] = std::min<int64_t>(s->dirty_from[g],
|
||||
(int64_t)s->blocks[g].size());
|
||||
@@ -1126,6 +1350,10 @@ int KVManager::adopt(uint64_t id, int32_t g, const std::vector<int32_t>& blocks,
|
||||
if (!s) return RAD_E_NOTFOUND;
|
||||
const KVGroupPlan* p = plan(g);
|
||||
if (!p || !p->paged()) return RAD_E_INVAL;
|
||||
/* A runtime window's table is its own reference plus ring, laid out against a floor no cache
|
||||
* entry knows (set_window), so blocks adopted from a prefix hit would sit at the wrong
|
||||
* positions. Prefix publish is skipped for such a sequence; this is the backstop. */
|
||||
if (s->win[(size_t)g].set) return RAD_E_STATE;
|
||||
/* Whole blocks only (see adopt in kv.h). */
|
||||
if (n_tokens % p->block_size != 0) return RAD_E_INVAL;
|
||||
if ((int64_t)blocks.size() != n_tokens / p->block_size) return RAD_E_INVAL;
|
||||
@@ -1146,6 +1374,14 @@ int KVManager::fork(uint64_t parent, uint64_t child) {
|
||||
Seq* pa = find(parent);
|
||||
if (!pa) return RAD_E_NOTFOUND;
|
||||
if (seqs_.count(child)) return RAD_E_DUPLICATE;
|
||||
/* The window is runtime data: a child that shared the table without it would read the ring
|
||||
* as if it were a reference. A forking model (speculative decoding) does not carry one. */
|
||||
for (const SeqWindow& w : pa->win)
|
||||
if (w.set) {
|
||||
RAD_ERR("sequence %llu: fork refused, it carries a runtime window",
|
||||
(unsigned long long)parent);
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
|
||||
/* Pass 1: the child needs its own state slot in every stateful group before anything is
|
||||
* shared (see fork in kv.h, spec §7.3). */
|
||||
@@ -1160,6 +1396,7 @@ int KVManager::fork(uint64_t parent, uint64_t child) {
|
||||
if (plans_[g].paged()) {
|
||||
ch->blocks[g] = pa->blocks[g];
|
||||
ch->first_block_pos[g] = pa->first_block_pos[g];
|
||||
ch->win[g] = pa->win[g];
|
||||
for (int32_t b : ch->blocks[g]) add_ref(g, b);
|
||||
} else {
|
||||
grab_state((int32_t)g, &ch->state[g]);
|
||||
@@ -1189,7 +1426,10 @@ int KVManager::make_room(uint64_t id, int64_t n_tokens,
|
||||
if (p.paged()) {
|
||||
int64_t first = s->first_block_pos[g] / p.block_size;
|
||||
int64_t want = ceil_div(n_tokens, p.block_size) - first;
|
||||
if (p.kind == RAD_KV_WINDOW) want = std::min(want, window_seq_cap(p));
|
||||
if (p.kind == RAD_KV_WINDOW) {
|
||||
if (s->win[g].set) want = window_table_len(p, s->win[g], n_tokens) - first;
|
||||
else want = std::min(want, window_seq_cap(p));
|
||||
}
|
||||
int64_t extra = want - (int64_t)s->blocks[g].size() + 1; /* +1 for a COW copy */
|
||||
if (extra > available_blocks((int32_t)g)) return false;
|
||||
} else if (p.stateful() && s->state[g] < 0 && free_states_[g].empty()) return false;
|
||||
@@ -1369,6 +1609,9 @@ bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector<int32_t>* out)
|
||||
out->clear();
|
||||
const Seq* s = find(id);
|
||||
if (!s || pos <= 0) return false;
|
||||
/* A runtime window is excluded from window snapshots (set_window): the window length is
|
||||
* runtime data and the table is a reference plus a ring, not [lo, pos). */
|
||||
for (const SeqWindow& w : s->win) if (w.set) return false;
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
if (!p.win_snap) continue;
|
||||
@@ -1390,6 +1633,8 @@ bool KVManager::window_rows(uint64_t id, int64_t pos, std::vector<int32_t>* out)
|
||||
int KVManager::seed_window(uint64_t id, int64_t pos) {
|
||||
Seq* s = find(id);
|
||||
if (!s) return RAD_E_NOTFOUND;
|
||||
/* A sequence with a runtime window is never resumed from a window snapshot (set_window). */
|
||||
for (const SeqWindow& w : s->win) if (w.set) return RAD_E_STATE;
|
||||
/* Check every group before taking anything, as ensure() does. */
|
||||
for (size_t g = 0; g < plans_.size(); ++g) {
|
||||
const KVGroupPlan& p = plans_[g];
|
||||
|
||||
+113
-3
@@ -11,6 +11,10 @@
|
||||
* RAD_KV_LINEAR per-sequence, fixed size: the GDN recurrent state
|
||||
* RAD_KV_CONV per-sequence, fixed size: a rolling window of conv_width-1 + n_spec entries
|
||||
*
|
||||
* A RAD_KV_RING group is a RAD_KV_WINDOW whose floor is per sequence and set at runtime (R-SWA,
|
||||
* see SeqWindow); it is planned as a WINDOW group with `runtime_win` set, so no kind of its own
|
||||
* reaches the plan.
|
||||
*
|
||||
* The two stateful kinds are also allocated, mapped and freed here, so one allocator decides what
|
||||
* a sequence owns. With two, a freed sequence's state slot could still be handed to the next
|
||||
* request by the other.
|
||||
@@ -50,6 +54,45 @@ struct BundleComparison {
|
||||
};
|
||||
BundleComparison compare_bundling(const std::vector<int64_t>& bundles);
|
||||
|
||||
/* ------------------------------------------------------------------ the runtime window */
|
||||
/* A sequence's per-sequence window on a RAD_KV_WINDOW group, set at runtime (R-SWA, the
|
||||
* "reference + ring" attention of Unlimited-OCR: a full causal prefill over the prompt and image
|
||||
* tokens, then a ring of W decode slots right after it, rewritten in place forever).
|
||||
*
|
||||
* A fixed sliding window (`KVGroupPlan::window_blocks`, gemma4's) keeps the last W tokens: the
|
||||
* table starts where the window begins and blocks leave from its front. A runtime window instead
|
||||
* retains the whole prefill as the reference and appends into a ring after it:
|
||||
*
|
||||
* visible = [0, visible_lo) U [visible_lo, visible_lo + W)
|
||||
*
|
||||
* `visible_lo` is the sequence's own prefill length (image tokens included), so the visible set is
|
||||
* per sequence. The reference is never recycled and first_block_pos stays 0 (the table still
|
||||
* starts at position 0); only the ring's slot mapping recycles, so RoPE positions keep increasing
|
||||
* with the token's own position and a decode query sees the whole reference plus the ring.
|
||||
*
|
||||
* Blocks are whole, so the ring can start only on a block boundary: it starts at
|
||||
* `ring_pos = ceil(visible_lo / block) * block` with `ceil(W / block)` blocks, and the tokens in
|
||||
* [visible_lo, ring_pos) stay in the reference's last block (they are the oldest of the tail and
|
||||
* are never rewritten). The visible tail is therefore W .. W + block - 1 tokens when W is a block
|
||||
* multiple -- with block_size 128 = W the 128-256 token granularity of the plan, exact even when
|
||||
* the floor is not aligned -- and up to one block more otherwise, always a superset of the
|
||||
* reference implementation's last W. The ring's blocks hold the newest positions in place (no
|
||||
* block is allocated past them, so the sequence's bytes are flat once the floor is set):
|
||||
*
|
||||
* block index = ring_pos / block + ((pos - ring_pos) / block) % ring_blocks
|
||||
*
|
||||
* A sequence with a runtime window is excluded from prefix-cache reuse, window snapshots, forking
|
||||
* and speculative rollback: all three assume the declare-time window, and the runtime length is
|
||||
* not in any cache key (see KVManager::set_window). */
|
||||
struct SeqWindow {
|
||||
bool set = false;
|
||||
int64_t window = 0; /* W as set */
|
||||
int64_t visible_lo = 0; /* the retained reference ends here */
|
||||
int64_t ring_pos = 0; /* block-aligned first ring token position */
|
||||
int64_t ring_blocks = 0; /* whole blocks the ring holds */
|
||||
int64_t ring_span(int64_t block) const { return ring_blocks * block; }
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ per-group plan */
|
||||
struct KVGroupPlan {
|
||||
int32_t index = -1; /* position in Program::kv_groups */
|
||||
@@ -62,6 +105,18 @@ struct KVGroupPlan {
|
||||
int64_t bytes_per_state = 0; /* LINEAR/CONV: per sequence, every layer */
|
||||
int64_t conv_slots = 0; /* CONV: conv_width - 1 + n_spec */
|
||||
int64_t window_blocks = 0; /* WINDOW: the per-sequence block cap */
|
||||
/* WINDOW: sequences may be given a runtime window (declare_runtime_window). Such a group is
|
||||
* sized for the whole context plus one ring per sequence instead of being capped at
|
||||
* window_blocks, its window is not snapshotted, and a sequence armed with one is bounded by
|
||||
* its own reference + ring rather than by window_blocks. */
|
||||
bool runtime_win = false;
|
||||
int64_t runtime_tokens = 0; /* the W set_window arms a sequence with */
|
||||
/* The most ring blocks one sequence needs: ceil(W / block), the reference's fraction d of
|
||||
* the ring's first block being frozen in it (see SeqWindow). */
|
||||
int64_t ring_blocks_max() const {
|
||||
return runtime_tokens > 0 && block_size > 0
|
||||
? (runtime_tokens + block_size - 1) / block_size : 0;
|
||||
}
|
||||
/* WINDOW: a checkpoint slot carries this group's window (has_window_snapshot). Set only for a
|
||||
* trunk group of a model with no linear state. A drafter's window is recomputed by draft
|
||||
* refill, and a model with linear state re-prefills a hit on a windowed trunk, so neither
|
||||
@@ -206,9 +261,49 @@ public:
|
||||
/* Recycles a committed chunk's window blocks. ensure() keeps a chunk's blocks beside the
|
||||
* window and only the next ensure() recycles them, so a prefill waiting for its next chunk
|
||||
* would hold a whole chunk of blocks; several such prefills can exhaust the pool. The
|
||||
* scheduler calls this when it advances n_computed, passing the new n_computed. */
|
||||
* scheduler calls this when it advances n_computed, passing the new n_computed.
|
||||
*
|
||||
* A sequence with a runtime window retains its reference and rewrites its ring in place, so
|
||||
* nothing below the floor may be recycled and this is a no-op for it. */
|
||||
void trim_window(uint64_t seq, int64_t keep_from);
|
||||
|
||||
/* ---------------- the runtime window (R-SWA; see SeqWindow) ---------------- */
|
||||
/* Mark a WINDOW group as carrying per-sequence runtime windows of `window_tokens`. Call before
|
||||
* plan_groups()/configure(): it changes the plan (the group is sized for the whole context
|
||||
* plus one ring a sequence, its window is not snapshotted, and the ring joins the fixed
|
||||
* costs), so a group declared after the plan is refused. A fixed-window group is untouched.
|
||||
*
|
||||
* A group that is not marked still accepts set_window() -- the caller then sizes the pool
|
||||
* itself, e.g. by declaring the group's window as the whole context -- and each sequence's
|
||||
* capacity is checked at set_window()/ensure() against the blocks actually carved. Once any
|
||||
* group is marked, set_window() arms only marked groups: a plain fixed-window group beside a
|
||||
* declared runtime window is refused, not silently converted (its pool is carved for the
|
||||
* fixed window). */
|
||||
int declare_runtime_window(int32_t group, int64_t window_tokens);
|
||||
|
||||
/* Give a sequence a runtime window with `visible_lo` (its prefill length, image tokens
|
||||
* included) as the retained reference's end and a ring of `window_tokens` after it. Every
|
||||
* paged WINDOW group of the sequence gets the same floor. Call it before the sequence's KV
|
||||
* grows past `visible_lo` -- at admission, where the scheduler knows the prompt length -- so
|
||||
* the reference is written linearly and no checkpoint can be reserved for it (a snapshot
|
||||
* would describe a window the sequence no longer has).
|
||||
*
|
||||
* RAD_E_UNSUPPORTED no windowed group, or the fixed/runtime-window mix above;
|
||||
* RAD_E_INVAL a negative floor or a window of 0;
|
||||
* RAD_E_STATE the sequence already holds tokens past the floor;
|
||||
* RAD_E_FULL the reference plus the ring exceeds what this group carved. */
|
||||
int set_window(uint64_t seq, int64_t visible_lo, int64_t window_tokens);
|
||||
|
||||
/* The sequence's window in `group`, or false when it has none (a fixed-window group keeps
|
||||
* KVGroupPlan::window_blocks and first_block_pos). The step batch maps a ring position with
|
||||
* SeqWindow's rule; every other position maps as (pos - first_block_pos) / block_size. */
|
||||
bool runtime_window(uint64_t seq, int32_t group, SeqWindow* out) const;
|
||||
/* Whether any group has a runtime window set for the sequence. Prefix publish, checkpoint
|
||||
* reservation and snapshots are skipped for it (see set_window). */
|
||||
bool has_runtime_window(uint64_t seq) const;
|
||||
/* The W declare_runtime_window gave the group, 0 if it carries no runtime windows. */
|
||||
int64_t runtime_window_tokens(int32_t group) const;
|
||||
|
||||
/* Adopt blocks a prefix-cache hit found. `n_tokens` must be a whole multiple of the group's
|
||||
* block size: a partial block is never shared, because the next token written into it would
|
||||
* corrupt the cache entry. Bumps each block's refcount. */
|
||||
@@ -363,7 +458,11 @@ public:
|
||||
/* The absolute token position block_table(seq, group)[0] covers: zero for a FULL group, the
|
||||
* recycled prefix for a WINDOW group. The slot mapping is (pos - first_block_pos) /
|
||||
* block_size; without the offset a sliding-window sequence writes to the wrong slot once it
|
||||
* passes its window. */
|
||||
* passes its window.
|
||||
*
|
||||
* A sequence with a runtime window (set_window) keeps 0 for the group's whole life: its table
|
||||
* is [reference][ring] from position 0 and only the ring's slot index recycles (SeqWindow),
|
||||
* so the mapping above holds for the reference and SeqWindow's rule for the ring. */
|
||||
int64_t first_block_pos(uint64_t seq, int32_t group) const;
|
||||
|
||||
/* The first table entry changed since the last call; entries below it are unchanged, and
|
||||
@@ -461,6 +560,9 @@ private:
|
||||
* for a windowed group. 0 for kUnboundedTokens, which is not a count. */
|
||||
int64_t zero_blocks(const KVGroupPlan& p, int64_t tokens) const;
|
||||
void forget();
|
||||
/* Turns a WINDOW group into a runtime-window one (declare_runtime_window). Returns false for a
|
||||
* group that is not windowed. */
|
||||
bool apply_runtime_window(KVGroupPlan& p) const;
|
||||
|
||||
/* One traversal serving both checkpoint directions; see checkpoint_save. */
|
||||
int checkpoint_copy(const int32_t* state_slots, int n_slots, int32_t ck_slot, bool save,
|
||||
@@ -471,6 +573,7 @@ private:
|
||||
int64_t n_tokens = 0;
|
||||
std::vector<std::vector<int32_t>> blocks; /* per group */
|
||||
std::vector<int64_t> first_block_pos; /* WINDOW: token pos of blocks[0] */
|
||||
std::vector<SeqWindow> win; /* per group: the runtime window, if any */
|
||||
std::vector<int32_t> state; /* per group, -1 when not stateful */
|
||||
/* Per group, the lowest table entry written since the batch builder last staged this
|
||||
* sequence. An append or truncation lowers it to where it touched; a shift lowers it to
|
||||
@@ -486,8 +589,12 @@ private:
|
||||
void drop_state(int32_t g, int32_t s);
|
||||
Seq* find(uint64_t seq);
|
||||
const Seq* find(uint64_t seq) const;
|
||||
/* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. */
|
||||
/* Recycle a WINDOW group's blocks no query at or past `keep_from` can read. A runtime window
|
||||
* (SeqWindow) is not trimmed: its reference must stay and its ring rewrites slots in place. */
|
||||
void recycle_window(Seq* s, int64_t keep_from);
|
||||
/* The table length a runtime-windowed sequence needs to hold `n_tokens`: the reference's
|
||||
* blocks, then the ring's up to its whole span. */
|
||||
static int64_t window_table_len(const KVGroupPlan& p, const SeqWindow& w, int64_t n_tokens);
|
||||
|
||||
std::vector<KVGroupPlan> plans_;
|
||||
std::vector<std::vector<int32_t>> free_blocks_; /* per group */
|
||||
@@ -515,6 +622,9 @@ private:
|
||||
int64_t fixed_ = 0; /* the non-negotiable floor: states, conv slots, padding */
|
||||
int64_t ckpts_ = 0; /* --checkpoint-slots, kept for the warning on a model with none */
|
||||
int64_t tokens_cap_ = 0; /* cap_paged_tokens(): the least any rank can carve; 0 is none */
|
||||
/* declare_runtime_window(): group -> W. Survives forget(), which plan_groups() calls at its
|
||||
* start: it is a declaration about the program, not about a plan. */
|
||||
std::unordered_map<int32_t, int64_t> runtime_decl_;
|
||||
|
||||
/* ---- the loan (see the public block) ----
|
||||
*
|
||||
|
||||
@@ -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. */
|
||||
|
||||
+96
-7
@@ -368,11 +368,16 @@ int PrefixCache::insert(uint64_t session,
|
||||
for (int64_t b = 0; b < n_full; ++b) {
|
||||
const BlockHash& h = hs[(size_t)b];
|
||||
auto it = map_.find(h);
|
||||
if (it != map_.end() && it->second.in_lru) continue; /* touched below */
|
||||
/* With snapshots (recurrent state or a sliding window) an existing entry keeps the bytes
|
||||
* it was published with, wherever it is held: a snapshot deeper in the chain was computed
|
||||
* from them, and a recompute in another step shape can round the KV differently. The
|
||||
* recomputed blocks go with the request's sequence; a later hit restores the tier copy. */
|
||||
if (it != map_.end() && (it->second.in_lru || has_linear_)) continue; /* touched below */
|
||||
if (it != map_.end()) {
|
||||
/* An off-device entry this request recomputed (a restore that did not fit, or a chain
|
||||
* cut short). Its blocks become the entry's device copy and the tier copy goes
|
||||
* (IdleTiers::rebound). An entry with a promotion in flight is left alone. */
|
||||
/* Without snapshots, an off-device entry this request recomputed (a restore that did
|
||||
* not fit, or a chain cut short): its blocks become the entry's device copy and the
|
||||
* tier copy goes (IdleTiers::rebound). An entry with a promotion in flight is left
|
||||
* alone. */
|
||||
if (!tiers_ || !tiers_->resident_off_device(h)) continue;
|
||||
std::vector<int32_t> mine(groups_.size(), -1);
|
||||
size_t held = 0;
|
||||
@@ -462,8 +467,9 @@ void PrefixCache::take_over(uint64_t session, const std::vector<BlockHash>& hs,
|
||||
|
||||
std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
int64_t fit) const {
|
||||
int64_t fit, bool* cut) const {
|
||||
std::vector<BlockHash> out;
|
||||
if (cut) *cut = false;
|
||||
if (!enabled_ || !tiers_ || tokens.empty()) return out;
|
||||
|
||||
/* Only blocks a hit can use: one token must remain, so a prompt ending on a block boundary
|
||||
@@ -488,13 +494,16 @@ std::vector<BlockHash> PrefixCache::restorable_from(const std::vector<int32_t>&
|
||||
if (out.empty() || (int64_t)out.size() <= fit) return out;
|
||||
|
||||
/* Restored up to `fit`, the hit ends at the first entry left behind. */
|
||||
++stats_.restore_cuts;
|
||||
if (cut) *cut = true;
|
||||
int64_t keep = std::max<int64_t>(0, fit);
|
||||
if (has_linear_) {
|
||||
const auto best = deepest_ckpt(hs, at[(size_t)keep] * block_size_);
|
||||
const int64_t upto = best == ck_by_prefix_.end() ? 0 : best->second.pos / block_size_;
|
||||
keep = std::lower_bound(at.begin(), at.begin() + keep, upto) - at.begin();
|
||||
}
|
||||
RAD_DEBUG("prefix cache: restore of %zu entries cut to %lld: the pool holds %lld of them, and "
|
||||
"the hit ends at token %lld", out.size(), (long long)keep,
|
||||
(long long)std::max<int64_t>(0, fit), (long long)(at[(size_t)keep] * block_size_));
|
||||
out.resize((size_t)keep);
|
||||
return out;
|
||||
}
|
||||
@@ -508,7 +517,8 @@ int64_t PrefixCache::restore_room() const {
|
||||
|
||||
int64_t PrefixCache::trim_for(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm, int64_t n_blocks) {
|
||||
if (!enabled_ || n_blocks <= 0) return 0;
|
||||
/* Without a host tier a trim erases, and making room for a restore must lose nothing. */
|
||||
if (!enabled_ || n_blocks <= 0 || !tiers_ || !tiers_->host_on()) return 0;
|
||||
const std::vector<BlockHash> hs = chain_all(tokens, mm, (int64_t)tokens.size() / block_size_);
|
||||
std::unordered_set<BlockHash, BlockHashHash> spare(hs.begin(), hs.end());
|
||||
for (const auto& h : held_) spare.insert(h.first);
|
||||
@@ -981,4 +991,83 @@ int64_t PrefixCache::expire(uint64_t now_ns, uint64_t ttl_ns) {
|
||||
stats_.ckpt_expired += (int64_t)gone.size();
|
||||
return n;
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ release on request */
|
||||
|
||||
int PrefixCache::release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
|
||||
SessionRelease* out) {
|
||||
if (!out) return RAD_E_INVAL;
|
||||
*out = SessionRelease{};
|
||||
if (!enabled_ || !tiers_ || block_size_ <= 0) return RAD_E_UNSUPPORTED;
|
||||
if (label.empty() && id == 0) return RAD_E_INVAL;
|
||||
if (keep_tokens < 0) return RAD_E_INVAL;
|
||||
|
||||
std::vector<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 */
|
||||
+40
-9
@@ -174,6 +174,23 @@ CheckpointSlots checkpoint_slots_auto(const CheckpointPolicy& policy, int64_t ma
|
||||
int64_t ctx, int64_t interval, int64_t slot_bytes,
|
||||
int64_t share_bytes, int64_t room_bytes);
|
||||
|
||||
/* ------------------------------------------------------------------ a release */
|
||||
/* What PrefixCache::release_session took out and what it left. Blocks are left for three
|
||||
* reasons, counted apart so a caller can tell a half-shared conversation from a busy one: the
|
||||
* caller asked for them (`keep_tokens`), another stored session's chain runs through them (a
|
||||
* system prompt two conversations open with belongs to both), or a live sequence holds them. */
|
||||
struct SessionRelease {
|
||||
int64_t sessions = 0; /* rows the label or id named */
|
||||
int64_t entries = 0; /* blocks forgotten, from VRAM or the host tier */
|
||||
int64_t tokens = 0; /* entries x block size */
|
||||
int64_t device_bytes = 0; /* pool bytes given back */
|
||||
int64_t host_bytes = 0; /* host-tier slots given back */
|
||||
int64_t snapshots = 0;
|
||||
int64_t kept_tokens = 0; /* the chain's start, as asked, whole blocks */
|
||||
int64_t kept_shared = 0; /* blocks beyond that on another stored session's chain */
|
||||
int64_t kept_live = 0; /* blocks a running or waiting request holds */
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the cache */
|
||||
class PrefixCache {
|
||||
public:
|
||||
@@ -256,20 +273,19 @@ public:
|
||||
* on a miss or token mismatch. Separate from lookup because lookup is const and has no
|
||||
* device; a promotion allocates blocks and runs a scatter between steps.
|
||||
*
|
||||
* `fit` is how many entries the pool can take. A longer chain is cut, and counted
|
||||
* (Stats::restore_cuts): with recurrent state at the deepest snapshot the shorter prefix
|
||||
* reaches, since the hit resumes there and blocks past it would come back for nothing;
|
||||
* without, at `fit`. */
|
||||
* `fit` is how many entries the pool can take. A longer chain is cut, and `*cut` set: with
|
||||
* recurrent state at the deepest snapshot the shorter prefix reaches, since the hit resumes
|
||||
* there and blocks past it would come back for nothing; without, at `fit`. */
|
||||
std::vector<BlockHash> restorable_from(const std::vector<int32_t>& tokens,
|
||||
const std::vector<MMContentKey>& mm,
|
||||
int64_t fit = INT64_MAX) const;
|
||||
int64_t fit = INT64_MAX, bool* cut = nullptr) const;
|
||||
/* Entries a restore can place now: free blocks against the carve, the least over the cached
|
||||
* groups. Lent blocks count, since KVManager::reserve_blocks recalls the loan for them. */
|
||||
int64_t restore_room() const;
|
||||
/* Room for a restore of this prompt's chain: trim(), sparing the chain itself (its blocks
|
||||
* would only have to come back too) and every chain a waiting request holds (hold()), whose
|
||||
* next attempt would restore it again. Nothing is lost; the reserve's trim after the next
|
||||
* publish puts the pool's free quarter back. */
|
||||
* next attempt would restore it again. Only entries whose host copy has landed leave VRAM,
|
||||
* so nothing is lost; with no host tier it takes nothing. */
|
||||
int64_t trim_for(const std::vector<int32_t>& tokens, const std::vector<MMContentKey>& mm,
|
||||
int64_t n_blocks);
|
||||
|
||||
@@ -315,6 +331,21 @@ public:
|
||||
* than what follows it: conversations expire from the tip inwards and a shared system prompt
|
||||
* outlives its readers. Returns how many entries went. */
|
||||
int64_t expire(uint64_t now_ns, uint64_t ttl_ns);
|
||||
|
||||
/* ---------------- release on request ----------------
|
||||
*
|
||||
* Forget one stored conversation now instead of at the TTL: a client that deleted it, or
|
||||
* replaced everything past a prefix (a compaction) and knows the rest is dead. `label` names
|
||||
* every row carrying it, `id` (nonzero) one row by its engine id (IdleTiers::SessionInfo).
|
||||
* The chain goes from the tip inwards like expire(): VRAM blocks to the pool, the host copy
|
||||
* with them, the session's snapshots on the released blocks to the store. `keep_tokens`
|
||||
* leaves the chain's first blocks standing (rounded up to whole blocks), so the prefix the
|
||||
* client kept still hits. A block another stored session's chain shares stays, as does one a
|
||||
* live sequence holds or a waiting request has restored; snapshots handed out or reserved
|
||||
* this step stay too. RAD_E_NOTFOUND when nothing matches, RAD_E_UNSUPPORTED without the
|
||||
* session table (no tiers attached). */
|
||||
int release_session(const std::string& label, uint64_t id, int64_t keep_tokens,
|
||||
SessionRelease* out);
|
||||
/* ---------------- linear checkpoints ---------------- */
|
||||
/* The next position strictly after `pos` at which the scheduler must split a chunk so that a
|
||||
* checkpoint lands on a boundary (spec §7.1, §7.3). */
|
||||
@@ -357,8 +388,8 @@ public:
|
||||
int64_t drops = 0;
|
||||
/* Entries and snapshots removed by --prefix-cache-ttl, from any tier. */
|
||||
int64_t expired = 0, ckpt_expired = 0;
|
||||
/* Restores from the host tier cut short because the pool could not hold the chain. */
|
||||
int64_t restore_cuts = 0;
|
||||
/* Entries and snapshots a client released (release_session). */
|
||||
int64_t released = 0, ckpt_released = 0;
|
||||
};
|
||||
const Stats& stats() const { return stats_; }
|
||||
|
||||
|
||||
@@ -82,9 +82,8 @@ struct VramFacts {
|
||||
bool lends = false;
|
||||
/* A loaded control vector's direction table: device bytes the engine already holds, which are
|
||||
* not part of the program or the pools and must not shrink what the plan may claim. It comes
|
||||
* out of the headroom, as every deployment keeps that unclaimed. Without this, a deployment
|
||||
* that merely *offers* a vector would plan its expert cache against a smaller card than one
|
||||
* that does not, which is exactly the difference "off == stock" cannot allow. */
|
||||
* out of the headroom, as every deployment keeps that unclaimed, so a deployment that only
|
||||
* offers a vector plans its expert cache against the same card as one that does not. */
|
||||
int64_t held_out = 0;
|
||||
/* Integrated graphics: host memory the card must leave to the host, since device memory is
|
||||
* host memory there. 0 on a discrete card. */
|
||||
|
||||
+12
-5
@@ -33,11 +33,18 @@ void Item::coords(int64_t first, int64_t count, int32_t* planes) const {
|
||||
while (s + 1 < n_seg && patch_at(s + 1) <= first + k) ++s;
|
||||
const int64_t within = first + k - patch_at(s);
|
||||
const int64_t bw = seg_w(s) / merge;
|
||||
const int64_t in_col = within % merge;
|
||||
const int64_t in_row = (within / merge) % merge;
|
||||
const int64_t blk = within / (merge * merge);
|
||||
const int64_t row = (blk / bw) * merge + in_row;
|
||||
const int64_t col = (blk % bw) * merge + in_col;
|
||||
int64_t row, col;
|
||||
if (patch_raster) {
|
||||
/* Raster order is its own inverse: patch i is row i / w, column i % w. */
|
||||
row = within / seg_w(s);
|
||||
col = within % seg_w(s);
|
||||
} else {
|
||||
const int64_t in_col = within % merge;
|
||||
const int64_t in_row = (within / merge) % merge;
|
||||
const int64_t blk = within / (merge * merge);
|
||||
row = (blk / bw) * merge + in_row;
|
||||
col = (blk % bw) * merge + in_col;
|
||||
}
|
||||
planes[k] = (int32_t)row;
|
||||
planes[count + k] = (int32_t)col;
|
||||
planes[2 * count + k] = seg_h(s);
|
||||
|
||||
+6
-1
@@ -46,7 +46,12 @@ int decode_image_rgba(const uint8_t* data, size_t n, int64_t max_pixels, FrameRG
|
||||
/* Encodes `px`, [h, w, ch] 8-bit with ch 3 (RGB) or 4 (RGBA), as an image file; `format` is png,
|
||||
* jpeg or webp. `quality` 0..100 applies to jpeg and lossy webp (0 or above 100 picks the
|
||||
* format's default); png is lossless and webp is lossless at 100. jpeg refuses alpha. Returns
|
||||
* RAD_E_UNSUPPORTED, with the reason, for a format this build cannot encode. */
|
||||
* RAD_E_UNSUPPORTED, with the reason, for a format this build cannot encode.
|
||||
*
|
||||
* Lossless webp is written by libwebp; FFmpeg's native VP8L decoder refuses some valid
|
||||
* libwebp streams ("Invalid data", reproducible with ffmpeg 8.0.1 on a low-colour picture),
|
||||
* so an FFmpeg-based consumer may not read every lossless file this writes. libwebp and
|
||||
* browsers do. */
|
||||
int encode_image(const uint8_t* px, int32_t w, int32_t h, int32_t ch, const std::string& format,
|
||||
int32_t quality, std::vector<uint8_t>* out, std::string* why);
|
||||
|
||||
|
||||
+693
-55
@@ -6,10 +6,19 @@
|
||||
#include "rad_plugin.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <cmath>
|
||||
#include <cstdio>
|
||||
#include <cstdlib>
|
||||
#include <cstring>
|
||||
#include <functional>
|
||||
#include <sstream>
|
||||
#include <thread>
|
||||
|
||||
#if defined(__x86_64__) || defined(__i386__) || defined(_M_X64)
|
||||
#include <immintrin.h>
|
||||
#define RAD_MM_HAVE_AVX2 1
|
||||
#endif
|
||||
|
||||
namespace rad {
|
||||
namespace mm {
|
||||
@@ -41,6 +50,49 @@ static bool meta_bool(const RadModelMeta& m, const char* key, bool dflt) {
|
||||
}
|
||||
|
||||
int VisionConfig::from_meta(const RadModelMeta& m, std::string* why) {
|
||||
/* Unlimited-OCR: one processor class, two modes, both stated in preprocessor_config.json and
|
||||
* processor_config.json (`processor.*`). Every key has the reference's default, so a container
|
||||
* converted before the tower landed still states a processor. */
|
||||
if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "unlimited_ocr")) {
|
||||
family = Family::UnlimitedOcr;
|
||||
patch = (int32_t)rad_meta_geti(&m, "processor.patch_size",
|
||||
rad_meta_geti(&m, "vision_config.patch_size", 16));
|
||||
downsample = (int32_t)rad_meta_geti(&m, "processor.downsample_ratio", 4);
|
||||
merge = downsample;
|
||||
temporal = 1;
|
||||
base_size = (int32_t)rad_meta_geti(&m, "preprocessor.size.height", 1024);
|
||||
tile = (int32_t)rad_meta_geti(&m, "preprocessor.tile_size", 640);
|
||||
/* The base mode's whole view: what the reference states for its input, and what the
|
||||
* preprocessor's `size` is. Multi-page inference may ask for the tile instead. */
|
||||
image_size = (int32_t)rad_meta_geti(&m, "preprocessor.size.width", base_size);
|
||||
crop_mode = meta_bool(m, "preprocessor.crop_to_patches", true);
|
||||
if (const char* t = rad_meta_gets(&m, "processor.image_token", nullptr); t && *t)
|
||||
image_token = t;
|
||||
min_tiles = (int32_t)rad_meta_geti(&m, "preprocessor.min_patches", 2);
|
||||
max_tiles = (int32_t)rad_meta_geti(&m, "preprocessor.max_patches", 32);
|
||||
tok_image = (int32_t)rad_meta_geti(&m, "image_token_id", -1);
|
||||
if (!read_triple(m, "preprocessor.image_mean", mean)) mean[0] = mean[1] = mean[2] = 0.5f;
|
||||
if (!read_triple(m, "preprocessor.image_std", stdv)) stdv[0] = stdv[1] = stdv[2] = 0.5f;
|
||||
/* 3 is PIL's bicubic, the only filter this processor stages. */
|
||||
const int64_t resample = rad_meta_geti(&m, "preprocessor.resample", 3);
|
||||
if (resample != 3) {
|
||||
if (why) *why = "the container resamples pictures with filter " +
|
||||
std::to_string(resample) + "; this processor stages PIL's bicubic (3)";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* No video; the bands only have to be consistent for check(). */
|
||||
const int64_t f2 = (int64_t)factor() * factor();
|
||||
image_min_pixels = video_min_pixels = f2;
|
||||
image_max_pixels = video_max_pixels = (int64_t)base_size * base_size;
|
||||
min_frames = 1;
|
||||
std::string bad;
|
||||
if (check(&bad) < 0) {
|
||||
if (why) *why = "the container's Unlimited-OCR processor configuration is "
|
||||
"inconsistent: " + bad;
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
return RAD_OK;
|
||||
}
|
||||
/* LFM2-VL states its processor twice, in config.json and in processor_config.json's
|
||||
* image_processor; the latter is what the reference processor reads, so it goes first. */
|
||||
if (!std::strcmp(rad_meta_gets(&m, "model_type", ""), "lfm2_vl")) {
|
||||
@@ -260,6 +312,20 @@ int VisionConfig::check(std::string* why) const {
|
||||
if (!(max_pixels_tolerance > 0.0) || max_segment_patches <= 0)
|
||||
return no("max_pixels_tolerance and max_num_patches must be positive");
|
||||
}
|
||||
if (family == Family::UnlimitedOcr) {
|
||||
if (patch <= 0 || downsample <= 0 || merge != downsample)
|
||||
return no("the tower's geometry (patch_size " + std::to_string(patch) +
|
||||
", downsample_ratio " + std::to_string(downsample) +
|
||||
") does not cut a whole merged patch");
|
||||
if (base_size <= 0 || base_size % factor() || image_size <= 0 || image_size % factor())
|
||||
return no("the global view's side (" + std::to_string(base_size) + " and " +
|
||||
std::to_string(image_size) + " pixels) is not a whole number of merged "
|
||||
"patches");
|
||||
if (min_tiles < 1 || max_tiles < min_tiles || tile <= 0 || tile % factor())
|
||||
return no("the tiling (min_patches " + std::to_string(min_tiles) + ", max_patches " +
|
||||
std::to_string(max_tiles) + ", tile_size " + std::to_string(tile) +
|
||||
") is not a range of whole merged patches");
|
||||
}
|
||||
if (family == Family::Glm5Next && (min_image_tokens < 1 || max_image_tokens < min_image_tokens))
|
||||
return no("the image token band [" + std::to_string(min_image_tokens) + ", " +
|
||||
std::to_string(max_image_tokens) + "] is empty");
|
||||
@@ -533,69 +599,314 @@ int coeffs(int32_t in_size, int32_t out_size, std::vector<int32_t>* bounds,
|
||||
|
||||
} /* namespace */
|
||||
|
||||
/* ================================================================== AVX2 resample helpers
|
||||
*
|
||||
* The two passes below are fixed-point int32 per tap. Integer addition is exact and associative at
|
||||
* these magnitudes (the coefficients of one output sum to 1 << prec and 255 << prec is about
|
||||
* 1.07e9, so no wrapper), so evaluating eight output pixels at once in any tap order is the same
|
||||
* function as the scalar loop; the rounding is only the final shift and clip. The horizontal pass
|
||||
* has variable tap counts and arbitrary stride-3 starts, so its lanes gather one 32-bit word per
|
||||
* tap (the RGB bytes of a pixel) and mask off inactive taps; the vertical pass reads whole rows,
|
||||
* where eight pixels are 24 contiguous bytes.
|
||||
*
|
||||
* Dispatch is local rather than through libavx: this file is core host code, and the AVX2 bodies
|
||||
* are target-attributed so the baseline object they live in still cannot execute AVX2 before the
|
||||
* check. mm_force_scalar() selects the scalar path for the bit-exactness test. */
|
||||
|
||||
static std::atomic<bool> g_force_scalar{ false };
|
||||
|
||||
void mm_force_scalar(bool on) { g_force_scalar.store(on, std::memory_order_relaxed); }
|
||||
|
||||
static bool mm_use_avx2() {
|
||||
#ifdef RAD_MM_HAVE_AVX2
|
||||
static const bool cpu = [] {
|
||||
__builtin_cpu_init();
|
||||
return __builtin_cpu_supports("avx2");
|
||||
}();
|
||||
return cpu && !g_force_scalar.load(std::memory_order_relaxed);
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(RAD_MM_HAVE_AVX2)
|
||||
#define RAD_MM_AVX2 __attribute__((target("avx2")))
|
||||
#define RAD_MM_INLINE_AVX2 __attribute__((target("avx2"), always_inline)) inline
|
||||
#define RAD_MM_EXTRACT16(v) _mm256_extracti128_si256((v), 1)
|
||||
|
||||
/* Eight RGB pixels from 24 contiguous bytes (bytes 0..23 of p). */
|
||||
RAD_MM_INLINE_AVX2 void load_rgb8(const uint8_t* p, __m256i* r, __m256i* g, __m256i* b) {
|
||||
const __m128i a = _mm_loadu_si128((const __m128i*)p);
|
||||
const __m128i c = _mm_loadl_epi64((const __m128i*)(p + 16));
|
||||
const __m128i mr0 = _mm_setr_epi8(0, 3, 6, 9, 12, 15, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i mg0 = _mm_setr_epi8(1, 4, 7, 10, 13, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i mb0 = _mm_setr_epi8(2, 5, 8, 11, 14, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i mr1 = _mm_setr_epi8(2, 5, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i mg1 = _mm_setr_epi8(0, 3, 6, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i mb1 = _mm_setr_epi8(1, 4, 7, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1);
|
||||
const __m128i rb = _mm_or_si128(_mm_shuffle_epi8(a, mr0), _mm_slli_si128(_mm_shuffle_epi8(c, mr1), 6));
|
||||
const __m128i gb = _mm_or_si128(_mm_shuffle_epi8(a, mg0), _mm_slli_si128(_mm_shuffle_epi8(c, mg1), 5));
|
||||
const __m128i bb = _mm_or_si128(_mm_shuffle_epi8(a, mb0), _mm_slli_si128(_mm_shuffle_epi8(c, mb1), 5));
|
||||
*r = _mm256_cvtepu8_epi32(rb);
|
||||
*g = _mm256_cvtepu8_epi32(gb);
|
||||
*b = _mm256_cvtepu8_epi32(bb);
|
||||
}
|
||||
|
||||
/* Eight rounded, clipped int32 sums written as eight RGB triplets (exactly 24 bytes). */
|
||||
RAD_MM_INLINE_AVX2 void store_rgb8(uint8_t* o, __m256i s0, __m256i s1, __m256i s2, int prec) {
|
||||
const __m256i sh = _mm256_set1_epi32(prec);
|
||||
const __m256i v0 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s0, sh), _mm256_setzero_si256()),
|
||||
_mm256_set1_epi32(255));
|
||||
const __m256i v1 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s1, sh), _mm256_setzero_si256()),
|
||||
_mm256_set1_epi32(255));
|
||||
const __m256i v2 = _mm256_min_epi32(_mm256_max_epi32(_mm256_srav_epi32(s2, sh), _mm256_setzero_si256()),
|
||||
_mm256_set1_epi32(255));
|
||||
const __m128i r16 = _mm_packus_epi32(_mm256_castsi256_si128(v0), RAD_MM_EXTRACT16(v0));
|
||||
const __m128i g16 = _mm_packus_epi32(_mm256_castsi256_si128(v1), RAD_MM_EXTRACT16(v1));
|
||||
const __m128i b16 = _mm_packus_epi32(_mm256_castsi256_si128(v2), RAD_MM_EXTRACT16(v2));
|
||||
const __m128i r8 = _mm_packus_epi16(r16, r16);
|
||||
const __m128i g8 = _mm_packus_epi16(g16, g16);
|
||||
const __m128i b8 = _mm_packus_epi16(b16, b16);
|
||||
/* Layout [r0..r3 g0..g3 b0..b3] then shuffle to 12 RGB bytes; twice for eight pixels.
|
||||
* Mask the low four bytes before shifting, or each shift would overwrite the previous
|
||||
* channel's bytes. */
|
||||
const __m128i low4 = _mm_set_epi64x(0, 0xffffffffll);
|
||||
const __m128i m = _mm_setr_epi8(0, 4, 8, 1, 5, 9, 2, 6, 10, 3, 7, 11, -1, -1, -1, -1);
|
||||
const __m128i lo = _mm_shuffle_epi8(
|
||||
_mm_or_si128(_mm_or_si128(_mm_and_si128(r8, low4),
|
||||
_mm_slli_si128(_mm_and_si128(g8, low4), 4)),
|
||||
_mm_slli_si128(_mm_and_si128(b8, low4), 8)),
|
||||
m);
|
||||
const __m128i hi = _mm_shuffle_epi8(
|
||||
_mm_or_si128(_mm_or_si128(_mm_and_si128(_mm_srli_si128(r8, 4), low4),
|
||||
_mm_slli_si128(_mm_and_si128(_mm_srli_si128(g8, 4), low4), 4)),
|
||||
_mm_slli_si128(_mm_and_si128(_mm_srli_si128(b8, 4), low4), 8)),
|
||||
m);
|
||||
_mm_storel_epi64((__m128i*)o, lo);
|
||||
_mm_storeu_si32(o + 8, _mm_srli_si128(lo, 8));
|
||||
_mm_storel_epi64((__m128i*)(o + 12), hi);
|
||||
_mm_storeu_si32(o + 20, _mm_srli_si128(hi, 8));
|
||||
}
|
||||
|
||||
/* One horizontal row, eight output pixels a step. plans is [group][tap] of eight (offset, coeff,
|
||||
* mask) int32s. The gather reads four bytes at the last input pixel's B channel, so the caller
|
||||
* keeps the buffer's final row on the scalar path. */
|
||||
RAD_MM_AVX2 void hpass_row(const uint8_t* row, uint8_t* o, int32_t ngroups, int32_t ksh,
|
||||
int prec, const int32_t* plans) {
|
||||
const __m256i zero = _mm256_setzero_si256();
|
||||
const __m256i round = _mm256_set1_epi32(1 << (prec - 1));
|
||||
const __m256i mask8 = _mm256_set1_epi32(0xff);
|
||||
for (int32_t g = 0; g < ngroups; ++g) {
|
||||
__m256i s0 = round, s1 = round, s2 = round;
|
||||
const int32_t* pl = plans + (size_t)g * (size_t)ksh * 24;
|
||||
for (int32_t t = 0; t < ksh; ++t, pl += 24) {
|
||||
const __m256i off = _mm256_loadu_si256((const __m256i*)pl);
|
||||
const __m256i coef = _mm256_loadu_si256((const __m256i*)(pl + 8));
|
||||
const __m256i msk = _mm256_loadu_si256((const __m256i*)(pl + 16));
|
||||
const __m256i word = _mm256_mask_i32gather_epi32(zero, (const int*)row, off, msk, 1);
|
||||
const __m256i r = _mm256_and_si256(word, mask8);
|
||||
const __m256i gg = _mm256_and_si256(_mm256_srli_epi32(word, 8), mask8);
|
||||
const __m256i bb = _mm256_and_si256(_mm256_srli_epi32(word, 16), mask8);
|
||||
s0 = _mm256_add_epi32(s0, _mm256_mullo_epi32(r, coef));
|
||||
s1 = _mm256_add_epi32(s1, _mm256_mullo_epi32(gg, coef));
|
||||
s2 = _mm256_add_epi32(s2, _mm256_mullo_epi32(bb, coef));
|
||||
}
|
||||
store_rgb8(o + (size_t)g * 24, s0, s1, s2, prec);
|
||||
}
|
||||
}
|
||||
|
||||
/* One vertical row: every tap is a whole source row, eight output pixels at a time. */
|
||||
RAD_MM_AVX2 void vpass_row(const Frame& src, int32_t ymin, int32_t ymax, const int32_t* k,
|
||||
uint8_t* o, int prec) {
|
||||
const __m256i round = _mm256_set1_epi32(1 << (prec - 1));
|
||||
int32_t xx = 0;
|
||||
for (; xx + 8 <= src.w; xx += 8) {
|
||||
__m256i s0 = round, s1 = round, s2 = round;
|
||||
for (int32_t y = 0; y < ymax; ++y) {
|
||||
const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3;
|
||||
__m256i r, g, b;
|
||||
load_rgb8(p, &r, &g, &b);
|
||||
const __m256i kk = _mm256_set1_epi32(k[y]);
|
||||
s0 = _mm256_add_epi32(s0, _mm256_mullo_epi32(r, kk));
|
||||
s1 = _mm256_add_epi32(s1, _mm256_mullo_epi32(g, kk));
|
||||
s2 = _mm256_add_epi32(s2, _mm256_mullo_epi32(b, kk));
|
||||
}
|
||||
store_rgb8(o + (size_t)xx * 3, s0, s1, s2, prec);
|
||||
}
|
||||
for (; xx < src.w; ++xx) {
|
||||
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
|
||||
for (int32_t y = 0; y < ymax; ++y) {
|
||||
const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3;
|
||||
s0 += p[0] * k[y];
|
||||
s1 += p[1] * k[y];
|
||||
s2 += p[2] * k[y];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0, prec);
|
||||
o[xx * 3 + 1] = clip8(s1, prec);
|
||||
o[xx * 3 + 2] = clip8(s2, prec);
|
||||
}
|
||||
}
|
||||
|
||||
/* One patch row: for each channel, P strided source bytes through that channel's LUT. lut32 is
|
||||
* the same LUT as 32-bit words, so one gather gets all three channels' table entries. */
|
||||
RAD_MM_AVX2 void patch_row(const uint8_t* row, uint16_t* dst, int32_t P, size_t chstride,
|
||||
const uint32_t* lut32, const uint16_t* lut) {
|
||||
for (int32_t x = 0; x + 8 <= P; x += 8) {
|
||||
__m256i r, g, b;
|
||||
load_rgb8(row + (size_t)x * 3, &r, &g, &b);
|
||||
const __m256i idx[3] = { r, g, b };
|
||||
for (int ch = 0; ch < 3; ++ch) {
|
||||
const __m256i ii = _mm256_add_epi32(idx[ch], _mm256_set1_epi32(ch * 256));
|
||||
const __m256i v = _mm256_i32gather_epi32((const int*)lut32, ii, 4);
|
||||
const __m128i h = _mm_packus_epi32(_mm256_castsi256_si128(v), RAD_MM_EXTRACT16(v));
|
||||
_mm_storeu_si128((__m128i*)(dst + (size_t)ch * chstride + x), h);
|
||||
}
|
||||
}
|
||||
for (int ch = 0; ch < 3; ++ch)
|
||||
for (int32_t x = (P / 8) * 8; x < P; ++x)
|
||||
dst[(size_t)ch * chstride + x] = lut[ch * 256 + row[(size_t)x * 3 + ch]];
|
||||
}
|
||||
#endif /* RAD_MM_HAVE_AVX2 */
|
||||
|
||||
/* One pass over an axis. `horizontal` reads rows [y0, y0 + rows) of `src` and writes w columns;
|
||||
* `vertical` reads rows from `shift` on and writes h rows. Both accumulate in fixed point and
|
||||
* round each output to eight bits, as Pillow does -- the intermediate's rounding is part of the
|
||||
* function, and the scalar tap order must not change.
|
||||
*
|
||||
* Both passes are row-independent: every output row reads only its own input rows and writes only
|
||||
* its own output row, in the same per-tap order, so splitting the rows across threads is bit-exact
|
||||
* (the goldens pin it). */
|
||||
static void run_rows(int32_t rows, const std::function<void(int32_t)>& row) {
|
||||
unsigned hw = std::thread::hardware_concurrency();
|
||||
const int32_t nt = (int32_t)std::min<int32_t>(rows, (int32_t)std::min<unsigned>(hw ? hw : 1, 8));
|
||||
if (nt <= 1) {
|
||||
for (int32_t y = 0; y < rows; ++y) row(y);
|
||||
return;
|
||||
}
|
||||
std::vector<std::thread> ts;
|
||||
ts.reserve((size_t)nt);
|
||||
for (int32_t t = 0; t < nt; ++t)
|
||||
ts.emplace_back([&row, t, nt, rows] { for (int32_t y = t; y < rows; y += nt) row(y); });
|
||||
for (std::thread& th : ts) th.join();
|
||||
}
|
||||
|
||||
static void pass_horizontal(const Frame& src, int32_t y0, int32_t rows, int32_t w,
|
||||
const std::vector<int32_t>& bh, const std::vector<int32_t>& kh,
|
||||
int32_t ksh, int prec, Frame* out) {
|
||||
out->w = w;
|
||||
out->h = rows;
|
||||
out->rgb.assign((size_t)w * (size_t)rows * 3, 0);
|
||||
const bool simd = mm_use_avx2();
|
||||
const int32_t ngroups = simd ? w / 8 : 0;
|
||||
std::vector<int32_t> plans;
|
||||
if (ngroups) {
|
||||
plans.resize((size_t)ngroups * (size_t)ksh * 24);
|
||||
for (int32_t g = 0; g < ngroups; ++g)
|
||||
for (int32_t t = 0; t < ksh; ++t) {
|
||||
int32_t* p = plans.data() + ((size_t)g * (size_t)ksh + (size_t)t) * 24;
|
||||
for (int32_t j = 0; j < 8; ++j) {
|
||||
const int32_t xx = g * 8 + j;
|
||||
const int32_t xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
|
||||
const bool on = t < xmax;
|
||||
p[j] = on ? (xmin + t) * 3 : 0;
|
||||
p[8 + j] = on ? kh[(size_t)xx * (size_t)ksh + (size_t)t] : 0;
|
||||
p[16 + j] = on ? -1 : 0;
|
||||
}
|
||||
}
|
||||
}
|
||||
auto scalar_row = [&](const uint8_t* row, uint8_t* o, int32_t x0) {
|
||||
for (int32_t xx = x0; xx < w; ++xx) {
|
||||
const int32_t xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
|
||||
const int32_t* k = kh.data() + (size_t)xx * (size_t)ksh;
|
||||
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
|
||||
for (int32_t x = 0; x < xmax; ++x) {
|
||||
const uint8_t* p = row + (size_t)(x + xmin) * 3;
|
||||
s0 += p[0] * k[x];
|
||||
s1 += p[1] * k[x];
|
||||
s2 += p[2] * k[x];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0, prec);
|
||||
o[xx * 3 + 1] = clip8(s1, prec);
|
||||
o[xx * 3 + 2] = clip8(s2, prec);
|
||||
}
|
||||
};
|
||||
run_rows(rows, [&](int32_t yy) {
|
||||
const uint8_t* row = src.rgb.data() + (size_t)(yy + y0) * (size_t)src.w * 3;
|
||||
uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)w * 3;
|
||||
/* The gather reads one byte past the row, which stays in the buffer on every row but its
|
||||
* last; that one stays scalar. */
|
||||
if (!ngroups || yy + y0 == src.h - 1) { scalar_row(row, o, 0); return; }
|
||||
#ifdef RAD_MM_HAVE_AVX2
|
||||
hpass_row(row, o, ngroups, ksh, prec, plans.data());
|
||||
scalar_row(row, o, ngroups * 8);
|
||||
#endif
|
||||
});
|
||||
}
|
||||
|
||||
static void pass_vertical(const Frame& src, int32_t shift, int32_t h,
|
||||
const std::vector<int32_t>& bv, const std::vector<int32_t>& kv,
|
||||
int32_t ksv, int prec, Frame* out) {
|
||||
out->w = src.w;
|
||||
out->h = h;
|
||||
out->rgb.assign((size_t)src.w * (size_t)h * 3, 0);
|
||||
const bool simd = mm_use_avx2();
|
||||
run_rows(h, [&](int32_t yy) {
|
||||
const int32_t ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1];
|
||||
const int32_t* k = kv.data() + (size_t)yy * (size_t)ksv;
|
||||
uint8_t* o = out->rgb.data() + (size_t)yy * (size_t)src.w * 3;
|
||||
#ifdef RAD_MM_HAVE_AVX2
|
||||
if (simd) { vpass_row(src, ymin, ymax, k, o, prec); return; }
|
||||
#endif
|
||||
(void)simd;
|
||||
for (int32_t xx = 0; xx < src.w; ++xx) {
|
||||
int32_t s0 = 1 << (prec - 1), s1 = s0, s2 = s0;
|
||||
for (int32_t y = 0; y < ymax; ++y) {
|
||||
const uint8_t* p = src.rgb.data() + ((size_t)(y + ymin) * (size_t)src.w + xx) * 3;
|
||||
s0 += p[0] * k[y];
|
||||
s1 += p[1] * k[y];
|
||||
s2 += p[2] * k[y];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0, prec);
|
||||
o[xx * 3 + 1] = clip8(s1, prec);
|
||||
o[xx * 3 + 2] = clip8(s2, prec);
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
static void resize_bicubic_impl(const Frame& in, int32_t w, int32_t h, Frame* out, bool torch) {
|
||||
if (in.w == w && in.h == h) { *out = in; return; }
|
||||
std::vector<int32_t> bh, kh, bv, kv;
|
||||
int ph = kPrec, pv = kPrec;
|
||||
const int ksh = coeffs(in.w, w, &bh, &kh, torch, &ph);
|
||||
const int ksv = coeffs(in.h, h, &bv, &kv, torch, &pv);
|
||||
const bool need_h = w != in.w, need_v = h != in.h;
|
||||
|
||||
/* The source rows the vertical pass reads, which is all the horizontal pass has to produce. */
|
||||
const int y_first = bv[0];
|
||||
const int y_last = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1];
|
||||
const bool need_h = w != in.w;
|
||||
const bool need_v = h != in.h;
|
||||
/* Pillow's pass order (libImaging/Resample.c): vertical first when the height shrinks and by
|
||||
* more than twice what the width does, so the horizontal pass runs over fewer rows. The
|
||||
* intermediate is eight bits, so the order changes the picture: both are the reference's.
|
||||
* torchvision's on a uint8 tensor (ATen's CPU kernel) is horizontal first at every size. */
|
||||
const bool horizontal_first =
|
||||
torch || !((int64_t)in.h - h > 0 && (int64_t)in.h - h > 2 * ((int64_t)in.w - w));
|
||||
|
||||
Frame tmp;
|
||||
const Frame* src = ∈
|
||||
if (need_h && need_v) {
|
||||
if (horizontal_first) {
|
||||
/* Only the source rows the vertical pass reads are resampled horizontally. */
|
||||
const int32_t y0 = bv[0];
|
||||
const int32_t rows = bv[(size_t)h * 2 - 2] + bv[(size_t)h * 2 - 1] - y0;
|
||||
pass_horizontal(in, y0, rows, w, bh, kh, ksh, ph, &tmp);
|
||||
pass_vertical(tmp, y0, h, bv, kv, ksv, pv, out);
|
||||
} else {
|
||||
pass_vertical(in, 0, h, bv, kv, ksv, pv, &tmp);
|
||||
pass_horizontal(tmp, 0, h, w, bh, kh, ksh, ph, out);
|
||||
}
|
||||
return;
|
||||
}
|
||||
if (need_h) {
|
||||
const int rows = need_v ? y_last - y_first : in.h;
|
||||
const int y0 = need_v ? y_first : 0;
|
||||
tmp.w = w;
|
||||
tmp.h = rows;
|
||||
tmp.rgb.assign((size_t)w * rows * 3, 0);
|
||||
for (int yy = 0; yy < rows; ++yy) {
|
||||
const uint8_t* row = in.rgb.data() + (size_t)(yy + y0) * in.w * 3;
|
||||
uint8_t* o = tmp.rgb.data() + (size_t)yy * w * 3;
|
||||
for (int xx = 0; xx < w; ++xx) {
|
||||
const int xmin = bh[(size_t)xx * 2], xmax = bh[(size_t)xx * 2 + 1];
|
||||
const int32_t* k = kh.data() + (size_t)xx * ksh;
|
||||
int32_t s0 = 1 << (ph - 1), s1 = s0, s2 = s0;
|
||||
for (int x = 0; x < xmax; ++x) {
|
||||
const uint8_t* p = row + (size_t)(x + xmin) * 3;
|
||||
s0 += p[0] * k[x];
|
||||
s1 += p[1] * k[x];
|
||||
s2 += p[2] * k[x];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0, ph);
|
||||
o[xx * 3 + 1] = clip8(s1, ph);
|
||||
o[xx * 3 + 2] = clip8(s2, ph);
|
||||
}
|
||||
}
|
||||
src = &tmp;
|
||||
}
|
||||
if (!need_v) { *out = std::move(tmp); return; }
|
||||
const int shift = need_h ? y_first : 0;
|
||||
out->w = src->w;
|
||||
out->h = h;
|
||||
out->rgb.assign((size_t)src->w * h * 3, 0);
|
||||
for (int yy = 0; yy < h; ++yy) {
|
||||
const int ymin = bv[(size_t)yy * 2] - shift, ymax = bv[(size_t)yy * 2 + 1];
|
||||
const int32_t* k = kv.data() + (size_t)yy * ksv;
|
||||
uint8_t* o = out->rgb.data() + (size_t)yy * src->w * 3;
|
||||
for (int xx = 0; xx < src->w; ++xx) {
|
||||
int32_t s0 = 1 << (pv - 1), s1 = s0, s2 = s0;
|
||||
for (int y = 0; y < ymax; ++y) {
|
||||
const uint8_t* p = src->rgb.data() + ((size_t)(y + ymin) * src->w + xx) * 3;
|
||||
s0 += p[0] * k[y];
|
||||
s1 += p[1] * k[y];
|
||||
s2 += p[2] * k[y];
|
||||
}
|
||||
o[xx * 3 + 0] = clip8(s0, pv);
|
||||
o[xx * 3 + 1] = clip8(s1, pv);
|
||||
o[xx * 3 + 2] = clip8(s2, pv);
|
||||
}
|
||||
pass_horizontal(in, 0, in.h, w, bh, kh, ksh, ph, out);
|
||||
return;
|
||||
}
|
||||
pass_vertical(in, 0, h, bv, kv, ksv, pv, out);
|
||||
}
|
||||
|
||||
void resize_bicubic(const Frame& in, int32_t w, int32_t h, Frame* out) {
|
||||
@@ -795,6 +1106,19 @@ int Processor::init(const VisionConfig& cfg,
|
||||
encode_text_ = std::move(encode_text);
|
||||
return RAD_OK;
|
||||
}
|
||||
if (cfg.family == Family::UnlimitedOcr) {
|
||||
/* The vocabulary spells the marker (`processor.image_token`), and every placeholder of a
|
||||
* picture is that same id: there is nothing else to resolve. */
|
||||
if (!token_id) return RAD_E_INVAL;
|
||||
if (cfg_.tok_image < 0) cfg_.tok_image = token_id(cfg_.image_token);
|
||||
if (cfg_.tok_image < 0) return RAD_E_NOTFOUND;
|
||||
/* A tile's line and the global view are each one segment, so each must fit one pass. */
|
||||
const int64_t q = cfg.tile / cfg.patch;
|
||||
const int64_t g = std::max(cfg.base_size, cfg.image_size) / cfg.patch;
|
||||
if (q * (q + 4) > cfg.max_patches || g * (g + 4) > cfg.max_patches) return RAD_E_INVAL;
|
||||
encode_text_ = std::move(encode_text);
|
||||
return RAD_OK;
|
||||
}
|
||||
/* The largest image one encoder pass takes, in pixels. Lowering the band's ceiling to it makes
|
||||
* smart_resize keep every image inside a pass. */
|
||||
const int64_t pass_px = cfg.max_patches * cfg.patch * cfg.patch;
|
||||
@@ -844,6 +1168,75 @@ void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32
|
||||
}
|
||||
}
|
||||
|
||||
/* Unlimited-OCR's ratios of one tile count tie only when they are each other's transpose: two
|
||||
* ratios of the same count are equally near an aspect only if one mirrors the other about it. So
|
||||
* the reference's set order matters for exactly the (c, r) pairs below, the tall ones (c < r)
|
||||
* its `sorted(set(...), key=area)` visits after their wide transpose -- the order CPython's set
|
||||
* has for the 2..32-tile range the checkpoint states. It comes from the reference itself
|
||||
* (tests/mkuocrgolden.py dumps it); outside that range the wide side is taken as last. */
|
||||
static constexpr int8_t kTallLast[][2] = {
|
||||
{1, 3}, {1, 4}, {1, 5}, {1, 6}, {1, 7}, {1, 9}, {1, 13}, {1, 14},
|
||||
{1, 16}, {1, 18}, {1, 20}, {1, 22}, {1, 27}, {1, 29}, {2, 3}, {2, 4},
|
||||
{2, 5}, {2, 6}, {2, 7}, {2, 8}, {2, 9}, {2, 14}, {2, 15}, {2, 16},
|
||||
{3, 5}, {3, 7}, {3, 9}, {4, 5}, {4, 6}, {4, 7}, {4, 8},
|
||||
};
|
||||
bool uocr_tall_last(int32_t c, int32_t r) {
|
||||
for (const auto& p : kTallLast)
|
||||
if (p[0] == c && p[1] == r) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
/* One n defers at most its divisor pairs with c < n/c, at most the divisors below its square
|
||||
* root. Over the 2..32-tile range the checkpoints state the table is built for, no n defers
|
||||
* more than this; uocr_grid's deferred buffer is sized from it and the static_assert below
|
||||
* keeps the bound checked against the table, not empirical. */
|
||||
static constexpr int32_t deferred_pairs_max(int32_t max_n) {
|
||||
int32_t best = 0;
|
||||
for (int32_t n = 2; n <= max_n; ++n) {
|
||||
int32_t cnt = 0;
|
||||
for (const auto& p : kTallLast)
|
||||
if (p[0] < p[1] && (int32_t)p[0] * (int32_t)p[1] == n) ++cnt;
|
||||
if (cnt > best) best = cnt;
|
||||
}
|
||||
return best;
|
||||
}
|
||||
static_assert(deferred_pairs_max(32) <= 8,
|
||||
"uocr_grid's 8-slot deferred buffer must cover the stated 2..32 tile range");
|
||||
|
||||
void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
|
||||
int32_t* cols, int32_t* rows) {
|
||||
*cols = *rows = 1;
|
||||
if (h <= 0 || w <= 0 || min_tiles < 1 || max_tiles < min_tiles) return;
|
||||
const double aspect = (double)w / (double)h;
|
||||
const double area = (double)w * (double)h;
|
||||
const double half = 0.5 * (double)tile * (double)tile;
|
||||
double best = INFINITY;
|
||||
for (int32_t n = min_tiles; n <= max_tiles; ++n) {
|
||||
int32_t deferred[8]; /* the transposed ratios the reference visits last */
|
||||
int32_t n_deferred = 0;
|
||||
auto visit = [&](int32_t c, int32_t r) {
|
||||
const double diff = std::fabs(aspect - (double)c / (double)r);
|
||||
if (diff < best) {
|
||||
best = diff; *cols = c; *rows = r;
|
||||
} else if (diff == best && area > half * (double)n) {
|
||||
*cols = c; *rows = r;
|
||||
}
|
||||
};
|
||||
for (int32_t c = 1; c <= n; ++c) {
|
||||
if (n % c) continue;
|
||||
if (c < n / c && uocr_tall_last(c, n / c)) {
|
||||
/* Defensive: the static_assert proves 8 covers the stated 2..32 range. Beyond
|
||||
* it the reference's tie order is not guaranteed, and a drop is a last resort
|
||||
* against overflow, not a designed path. */
|
||||
if (n_deferred < 8) deferred[n_deferred++] = c;
|
||||
continue;
|
||||
}
|
||||
visit(c, n / c);
|
||||
}
|
||||
for (int32_t k = 0; k < n_deferred; ++k) visit(deferred[k], n / deferred[k]);
|
||||
}
|
||||
}
|
||||
|
||||
/* LFM2-VL's image processor (transformers' Lfm2VlImageProcessor), segment by segment: the tiles
|
||||
* in row-major order, then the thumbnail. Within a segment, patches are in merge-block order (each
|
||||
* merge x merge block consecutive, dy then dx, as the projector's pixel unshuffle reads them, so
|
||||
@@ -921,6 +1314,240 @@ int Processor::image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::strin
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t* base_size,
|
||||
int32_t* image_size, std::string* why) {
|
||||
auto no = [why](const std::string& w) {
|
||||
if (why) *why = w;
|
||||
return RAD_E_INVAL;
|
||||
};
|
||||
if (c.family != Family::UnlimitedOcr) return no("this model has one picture mode, not two");
|
||||
const int32_t F = c.factor();
|
||||
const bool cr = mode.kind == ImageMode::Base ? false
|
||||
: mode.kind == ImageMode::Gundam ? true
|
||||
: mode.several ? false
|
||||
: c.crop_mode;
|
||||
const int32_t bs = mode.base_size > 0 ? mode.base_size : c.base_size;
|
||||
const int32_t is = mode.image_size > 0 ? mode.image_size : c.image_size;
|
||||
if (cr) {
|
||||
/* The crops are the tile the checkpoint was trained at; the reference's image_size is
|
||||
* that same number, so a request may only restate it. */
|
||||
if (bs % F)
|
||||
return no("base_size " + std::to_string(bs) + " is not a whole number of merged "
|
||||
"patches (" + std::to_string(F) + ")");
|
||||
if (bs < 4 * F)
|
||||
return no("base_size " + std::to_string(bs) + " is under two output rows");
|
||||
if (bs / c.patch != 64 && bs / c.patch != 40)
|
||||
return no("the DeepEncoder serves base grids 64 and 40 (base_size 1024 or 640); "
|
||||
"base_size " + std::to_string(bs) + " is neither");
|
||||
if (mode.image_size > 0 && mode.image_size != c.tile)
|
||||
return no("crop mode cuts pictures into " + std::to_string(c.tile) + "-pixel tiles; "
|
||||
"image_size " + std::to_string(mode.image_size) + " is not one");
|
||||
*crop = true; *base_size = bs; *image_size = c.tile;
|
||||
return RAD_OK;
|
||||
}
|
||||
if (is % F)
|
||||
return no("image_size " + std::to_string(is) + " is not a whole number of merged patches "
|
||||
"(" + std::to_string(F) + ")");
|
||||
if (is < 4 * F) return no("image_size " + std::to_string(is) + " is under two output rows");
|
||||
if (is / c.patch != 64 && is / c.patch != 40)
|
||||
return no("the DeepEncoder serves base grids 64 and 40 (image_size 1024 or 640); "
|
||||
"image_size " + std::to_string(is) + " is neither");
|
||||
if (mode.base_size > 0 && mode.base_size != bs)
|
||||
return no("the base mode pads a page to image_size, not base_size");
|
||||
*crop = false; *base_size = bs; *image_size = is;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int64_t uocr_tokens(const VisionConfig& c, const ImageMode& mode, int32_t cols, int32_t rows) {
|
||||
bool crop = false;
|
||||
int32_t bs = 0, is = 0;
|
||||
if (uocr_mode(c, mode, &crop, &bs, &is, nullptr) < 0) return -1;
|
||||
const int32_t P = c.patch, D = c.downsample;
|
||||
/* The global view: `g` lines of `g` features, each followed by a newline, then the view
|
||||
* separator (`[tok] * g + [tok]) * g + [tok]`). */
|
||||
const int32_t g = (crop ? bs : is) / P / D;
|
||||
int64_t t = (int64_t)(g + 1) * g + 1;
|
||||
/* The local views, when the picture is tiled: one line per feature row holding every tile's
|
||||
* row, a newline after it (`[tok] * q * cols + [tok]) * q * rows`). */
|
||||
if (crop && (int64_t)cols * rows > 1) {
|
||||
const int32_t q = c.tile / P / D;
|
||||
t += (int64_t)(q * cols + 1) * q * rows;
|
||||
}
|
||||
return t;
|
||||
}
|
||||
|
||||
void pad_bicubic(const Frame& in, int32_t w, int32_t h, uint8_t fill, Frame* out) {
|
||||
/* ImageOps.pad: contain() fits the picture inside w x h at its own aspect (PIL's bicubic,
|
||||
* rounded as its round() does), then it is pasted centred on `fill`. */
|
||||
int32_t nw = w, nh = h;
|
||||
if (in.w > 0 && in.h > 0) {
|
||||
const double im_ratio = (double)in.w / (double)in.h;
|
||||
const double dst_ratio = (double)w / (double)h;
|
||||
if (im_ratio != dst_ratio) {
|
||||
if (im_ratio > dst_ratio) {
|
||||
nh = (int32_t)pyround((double)in.h / (double)in.w * (double)w);
|
||||
if (nh == 0) nh = 1;
|
||||
} else {
|
||||
nw = (int32_t)pyround((double)in.w / (double)in.h * (double)h);
|
||||
if (nw == 0) nw = 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
const Frame* src = ∈
|
||||
Frame fitted;
|
||||
if (nw != in.w || nh != in.h) {
|
||||
resize_bicubic(in, nw, nh, &fitted);
|
||||
src = &fitted;
|
||||
}
|
||||
out->w = w;
|
||||
out->h = h;
|
||||
out->rgb.assign((size_t)w * (size_t)h * 3, fill);
|
||||
const int32_t x = nw != w ? (int32_t)pyround((double)(w - nw) * 0.5) : 0;
|
||||
const int32_t y = nw != w ? 0 : (int32_t)pyround((double)(h - nh) * 0.5);
|
||||
for (int32_t yy = 0; yy < src->h; ++yy)
|
||||
std::memcpy(out->rgb.data() + ((size_t)(y + yy) * (size_t)w + (size_t)x) * 3,
|
||||
src->rgb.data() + (size_t)yy * (size_t)src->w * 3, (size_t)src->w * 3);
|
||||
}
|
||||
|
||||
/* Unlimited-OCR's picture processor, the reference's infer() and infer_multi() exactly: the
|
||||
* global view is the picture ImageOps.pad-ed to base_size (in the base mode, to image_size,
|
||||
* squared first when that side is a tile or less), and in the gundam mode a picture larger than a
|
||||
* tile is cut the way dynamic_preprocess cuts it. Each view is staged as its feature grid plus
|
||||
* `downsample` patch columns nothing is read from, because the reference's layout puts a newline
|
||||
* after every line of features: one output row per downsample x downsample patches, and the last
|
||||
* column's rows are where those newlines go. The segments are, in the reference's order, the
|
||||
* local grid's lines (one per tile row; a line wider than a pass is cut into chunks of whole
|
||||
* tiles, its last chunk carrying the newline column), then the global view's grid, then the view
|
||||
* separator's single row. */
|
||||
int Processor::image_unlimitedocr(const Frame& f, const ImageMode& mode,
|
||||
std::shared_ptr<Item>* out, std::string* why) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
const int32_t P = c.patch, M = c.merge;
|
||||
bool crop = false;
|
||||
int32_t base_size = 0, image_size = 0;
|
||||
RAD_TRY(uocr_mode(c, mode, &crop, &base_size, &image_size, why));
|
||||
if (f.w <= 0 || f.h <= 0) {
|
||||
if (why) *why = "the picture has no size";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
const int32_t q = c.tile / P; /* a tile's patch rows */
|
||||
int32_t cols = 1, rows = 1;
|
||||
const bool tiled = crop && (f.w > c.tile || f.h > c.tile);
|
||||
if (tiled) uocr_grid(f.h, f.w, c.min_tiles, c.max_tiles, c.tile, &cols, &rows);
|
||||
|
||||
/* The global view. The base mode squares a page of a tile or less before padding it, as the
|
||||
* reference's multi-page path does. */
|
||||
Frame global;
|
||||
if (crop) {
|
||||
pad_bicubic(f, base_size, base_size, 127, &global);
|
||||
} else if (image_size <= c.tile) {
|
||||
/* The reference's multi-page path squares the page first, so a non-square page is
|
||||
* aspect-distorted by this resize, and the pad below is a no-op by construction (the
|
||||
* square already is the pad target). Square-first kept for reference parity. */
|
||||
Frame sq;
|
||||
resize_bicubic(f, image_size, image_size, &sq);
|
||||
pad_bicubic(sq, image_size, image_size, 127, &global);
|
||||
} else {
|
||||
pad_bicubic(f, image_size, image_size, 127, &global);
|
||||
}
|
||||
const int32_t g = (crop ? base_size : image_size) / P;
|
||||
if ((int64_t)g * (g + 4) > c.max_patches) {
|
||||
if (why) *why = "the global view's " + std::to_string((long long)g * (g + 4)) +
|
||||
" patches are more than one encoder pass holds (" +
|
||||
std::to_string(c.max_patches) + ")";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
|
||||
/* ToTensor then Normalize, in f32: (u / 255 - mean) / std, rounded to bf16. */
|
||||
uint16_t lut[3][256];
|
||||
uint32_t lut32[3 * 256];
|
||||
for (int ch = 0; ch < 3; ++ch)
|
||||
for (int v = 0; v < 256; ++v) {
|
||||
const float p = (float)v / 255.0f;
|
||||
lut[ch][v] = rad_f32_to_bf16((p - c.mean[ch]) / c.stdv[ch]);
|
||||
lut32[ch * 256 + v] = lut[ch][v];
|
||||
}
|
||||
const bool simd = mm_use_avx2();
|
||||
|
||||
auto it = std::make_shared<Item>();
|
||||
it->kind = Kind::Image;
|
||||
it->patch_dim = c.patch_dim();
|
||||
it->rope_1d = true;
|
||||
it->patch_raster = true;
|
||||
int64_t seg_row = 0;
|
||||
/* One segment of `gh` x `gw` patches from (x0, y0) of `src`, of which the first `real_w`
|
||||
* patches a row carry pixels; the rest are the newline column. */
|
||||
auto append = [&](const Frame& src, int32_t x0, int32_t y0, int32_t gh, int32_t gw,
|
||||
int32_t real_w, bool sep = false) {
|
||||
it->segments.push_back({ gh, gw, it->n_patch, sep });
|
||||
it->seg_at.push_back((int32_t)seg_row);
|
||||
it->expand.insert(it->expand.end(), (size_t)(gh / M) * (size_t)(gw / M), c.tok_image);
|
||||
seg_row += (int64_t)(gh / M) * (gw / M);
|
||||
it->n_patch += (int64_t)gh * gw;
|
||||
const size_t at = it->pixels.size();
|
||||
it->pixels.resize(at + (size_t)gh * (size_t)gw * (size_t)it->patch_dim, 0);
|
||||
uint16_t* dst = it->pixels.data() + at;
|
||||
/* Each patch row writes its own disjoint run of dst, in the same order, so splitting the
|
||||
* rows across threads is bit-exact. */
|
||||
run_rows(gh, [&](int32_t py) {
|
||||
for (int32_t px = 0; px < real_w; ++px) {
|
||||
uint16_t* pp = dst + ((size_t)py * (size_t)gw + (size_t)px) * (size_t)it->patch_dim;
|
||||
const int32_t py0 = y0 + py * P, px0 = x0 + px * P;
|
||||
for (int y = 0; y < P; ++y) {
|
||||
const uint8_t* row = src.rgb.data() +
|
||||
((size_t)(py0 + y) * (size_t)src.w + (size_t)px0) * 3;
|
||||
#ifdef RAD_MM_HAVE_AVX2
|
||||
if (simd) {
|
||||
patch_row(row, pp + (size_t)y * P, P, (size_t)P * P, lut32, &lut[0][0]);
|
||||
continue;
|
||||
}
|
||||
#endif
|
||||
(void)simd;
|
||||
for (int ch = 0; ch < 3; ++ch) {
|
||||
const uint8_t* r = row + (size_t)ch;
|
||||
uint16_t* q = pp + ((size_t)ch * P + (size_t)y) * P;
|
||||
for (int x = 0; x < P; ++x) q[x] = lut[ch][r[(size_t)x * 3]];
|
||||
}
|
||||
}
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
if (tiled) {
|
||||
Frame big;
|
||||
resize_bicubic(f, cols * c.tile, rows * c.tile, &big);
|
||||
/* A chunk of a line must fit one pass: q rows of q patches a tile, plus the newline
|
||||
* column its last chunk holds. */
|
||||
int64_t per_row = c.max_patches / q;
|
||||
const int64_t chunk = per_row > 4 ? (per_row - 4) / q : 0;
|
||||
if (chunk < 1) {
|
||||
if (why) *why = "one encoder pass holds no line of " + std::to_string(q) +
|
||||
"-patch tiles (" + std::to_string(c.max_patches) + " patches)";
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
for (int32_t r = 0; r < rows; ++r)
|
||||
for (int32_t c0 = 0; c0 < cols; c0 += (int32_t)chunk) {
|
||||
const int32_t n = std::min<int32_t>((int32_t)chunk, cols - c0);
|
||||
const bool last = c0 + n == cols;
|
||||
append(big, c0 * c.tile, r * c.tile, q, q * n + (last ? 4 : 0), q * n);
|
||||
}
|
||||
}
|
||||
append(global, 0, 0, g, g + 4, g);
|
||||
/* The view separator: one output row, from a grid of exactly one merged cell and no pixels. */
|
||||
append(global, 0, 0, M, M, 0, /*sep=*/true);
|
||||
|
||||
it->n_seg = (int32_t)it->segments.size();
|
||||
it->grid_t = 1;
|
||||
it->grid_h = it->segments[0].h;
|
||||
it->grid_w = it->segments[0].w;
|
||||
it->rows_h = it->grid_h / M;
|
||||
it->rows_w = it->grid_w / M;
|
||||
it->seg_rows = it->rows_h * it->rows_w;
|
||||
content_key(*it, &it->key_hi, &it->key_lo);
|
||||
*out = std::move(it);
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
/* GLM-5.3's image processor (transformers' Glm5NextImageProcessor, torchvision backend): the
|
||||
* picture, resized only when its size changes, in the top left of a canvas of zero bytes, which
|
||||
* the normalisation turns into each channel's -mean / std as it does the reference's padding. */
|
||||
@@ -960,11 +1587,17 @@ int Processor::image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::s
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const {
|
||||
int Processor::image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why,
|
||||
const ImageMode& mode) const {
|
||||
const VisionConfig& c = cfg_;
|
||||
if (mode.kind != ImageMode::Default && c.family != Family::UnlimitedOcr) {
|
||||
if (why) *why = "this model has one picture mode; images_config names one of two";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (c.family == Family::Gemma4) return image_gemma4(f, c.image_soft_tokens, out, why);
|
||||
if (c.family == Family::Lfm2) return image_lfm2(f, out, why);
|
||||
if (c.family == Family::Glm5Next) return image_glm5next(f, out, why);
|
||||
if (c.family == Family::UnlimitedOcr) return image_unlimitedocr(f, mode, out, why);
|
||||
int64_t h = 0, w = 0;
|
||||
RAD_TRY(smart_resize_image(f.h, f.w, c.factor(), c.image_min_pixels, c.image_max_pixels,
|
||||
&h, &w, why));
|
||||
@@ -1140,7 +1773,12 @@ int Processor::video_from(const Video& v, std::shared_ptr<Item>* out, std::strin
|
||||
}
|
||||
|
||||
int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
|
||||
std::shared_ptr<Item>* out, std::string* why, int64_t max_pixels) const {
|
||||
std::shared_ptr<Item>* out, std::string* why, int64_t max_pixels,
|
||||
const ImageMode& mode) const {
|
||||
if (mode.kind != ImageMode::Default && cfg_.family != Family::UnlimitedOcr) {
|
||||
if (why) *why = "this model has one picture mode; images_config names one of two";
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
if (image_tokens != 0) {
|
||||
if (cfg_.family == Family::Glm5Next) {
|
||||
if (why) *why = "this model's image token budget is the server's (--image-tokens), "
|
||||
@@ -1169,7 +1807,7 @@ int Processor::image(const uint8_t* bytes, size_t n, int32_t image_tokens,
|
||||
}
|
||||
if (cfg_.family == Family::Gemma4)
|
||||
return image_gemma4(f, image_tokens ? image_tokens : cfg_.image_soft_tokens, out, why);
|
||||
return image_from(f, out, why);
|
||||
return image_from(f, out, why, mode);
|
||||
}
|
||||
|
||||
int Processor::encoder_image(const uint8_t* bytes, size_t n, int32_t ratio, int32_t max_side,
|
||||
|
||||
+74
-5
@@ -56,6 +56,18 @@ enum class Kind { Image, Video, Audio };
|
||||
* own, followed by the whole picture at the budgeted size as a thumbnail. Patches
|
||||
* (y, x, channel) normalised by the mean and deviation, resized with torchvision's
|
||||
* fixed-point bicubic; images only, and the tokens rotate at their positions.
|
||||
* UnlimitedOcr
|
||||
* Unlimited-OCR's DeepSeek-OCR shape, in the checkpoint's two modes (ImageMode): the
|
||||
* picture padded (ImageOps.pad) to base_size x base_size on a 127 grey as the global
|
||||
* view, and, in the gundam mode, a picture larger than one tile cut into min_tiles..
|
||||
* max_tiles tile x tile crops at the tile in the ratio nearest its own (its
|
||||
* dynamic_preprocess). The SAM neck downsamples by `downsample`, so patch * downsample
|
||||
* is one output row. A view's rows are laid out as the reference's feature grid plus a
|
||||
* column of newlines, which is why every segment carries `downsample` extra patch
|
||||
* columns that nothing is read from: patches are raster order (Item::patch_raster), one
|
||||
* patch (channel, y, x), each value (u / 255 - mean) / std in f32, rounded to bf16.
|
||||
* Every placeholder is one id (the picture marker itself); the tokens rotate at their
|
||||
* positions.
|
||||
* Glm5Next GLM-5.3's: a canvas whose sides are multiples of patch * merge and whose tokens fall
|
||||
* in [min_image_tokens, max_image_tokens] (the sides rounded up, a picture under the
|
||||
* floor grown, one over the budget fitted by the reference's search); the picture keeps
|
||||
@@ -64,7 +76,7 @@ enum class Kind { Image, Video, Audio };
|
||||
* bottom, is zero bytes. Patches as QwenVL's. Images only, spelled <begin_of_image>
|
||||
* placeholders <end_of_image>, the tokens at their positions (the language model has no
|
||||
* rotary). */
|
||||
enum class Family { QwenVL, Gemma4, Lfm2, Glm5Next };
|
||||
enum class Family { QwenVL, Gemma4, Lfm2, UnlimitedOcr, Glm5Next };
|
||||
|
||||
struct VisionConfig {
|
||||
Family family = Family::QwenVL;
|
||||
@@ -91,6 +103,17 @@ struct VisionConfig {
|
||||
double max_pixels_tolerance = 0.0;
|
||||
int64_t max_segment_patches = 0;
|
||||
|
||||
/* UnlimitedOcr: the two modes' sizes, from the checkpoint's preprocessor config. The gundam
|
||||
* mode pads the global view to `base_size` and cuts crops at `tile`; the base mode (a page of
|
||||
* a multi-page document) pads the whole picture to `image_size`. `downsample` is the SAM
|
||||
* neck's ratio: one output row is `patch * downsample` pixels a side. `crop_mode` is the
|
||||
* deployment's mode when a request names none. */
|
||||
int32_t base_size = 0, image_size = 0, downsample = 0;
|
||||
bool crop_mode = false;
|
||||
/* The vocabulary's spelling of the picture marker (`processor.image_token`); every
|
||||
* placeholder of a picture is that one id. */
|
||||
std::string image_token = "<image>";
|
||||
|
||||
/* Deployment bounds, not the checkpoint's. `max_patches` is the encoder's pass size: an image
|
||||
* is one segment and a segment is never split, so the image band's ceiling is lowered to fit
|
||||
* it. `max_source_pixels` bounds what the decoder may hold before any resize. */
|
||||
@@ -112,6 +135,20 @@ struct VisionConfig {
|
||||
int from_meta(const RadModelMeta& m, std::string* why);
|
||||
};
|
||||
|
||||
/* Which picture processor a request gets, for a checkpoint that has more than one: Unlimited-OCR
|
||||
* states two modes and the reference names them gundam (one picture: the global view at base_size
|
||||
* plus crops) and base (a page of a multi-page document: the global view only, at image_size).
|
||||
* `Default` is the deployment's (`VisionConfig::crop_mode`), or base when `several` says the
|
||||
* request carries more than one picture; a request may pick either mode and, with it, the sizes
|
||||
* the checkpoint states differently. `base_size` and `image_size` of 0 keep the mode's own. A
|
||||
* processor with one mode refuses a named mode and ignores `several`. */
|
||||
struct ImageMode {
|
||||
enum Kind : int32_t { Default = 0, Gundam = 1, Base = 2 };
|
||||
int32_t kind = Default;
|
||||
int32_t base_size = 0, image_size = 0;
|
||||
bool several = false;
|
||||
};
|
||||
|
||||
/* The audio feature extractor family, from the container's audio_config.model_type. The
|
||||
* families differ in the spectrogram and in how a clip's frames are laid out for the encoder;
|
||||
* the Item they produce is shared.
|
||||
@@ -204,14 +241,20 @@ struct Item {
|
||||
* thumbnail): each is `h` x `w` patches starting at patch `patch0`. Empty means every segment
|
||||
* is grid_h x grid_w. The rest of the engine reads segments only through the accessors below,
|
||||
* so both forms look alike. */
|
||||
struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; };
|
||||
struct Segment { int32_t h = 0, w = 0; int64_t patch0 = 0; bool sep = false; };
|
||||
std::vector<Segment> segments;
|
||||
/* The model rotates this item's tokens at their token positions (LFM2-VL's 1-D rotary), not
|
||||
* on the grid the Qwen-VL family's M-RoPE lays out (RopeLayout). */
|
||||
bool rope_1d = false;
|
||||
/* Patches are in raster order (row by row), not merge-block order: the coordinate planes
|
||||
* invert the one or the other (Unlimited-OCR's tower reads a picture patch by patch). */
|
||||
bool patch_raster = false;
|
||||
|
||||
int32_t seg_h(int32_t s) const { return segments.empty() ? grid_h : segments[(size_t)s].h; }
|
||||
int32_t seg_w(int32_t s) const { return segments.empty() ? grid_w : segments[(size_t)s].w; }
|
||||
/* The one-output-row view separator (Unlimited-OCR stages it as a merge-grid cell of zeros).
|
||||
* A square segment is not enough: a chunked line of one tile is q x q too. */
|
||||
bool seg_is_sep(int32_t s) const { return !segments.empty() && segments[(size_t)s].sep; }
|
||||
/* Segment s's first patch and first output row; s == n_seg is the end of the item. */
|
||||
int64_t patch_at(int32_t s) const {
|
||||
if (segments.empty()) return (int64_t)s * grid_h * grid_w;
|
||||
@@ -319,13 +362,15 @@ public:
|
||||
|
||||
/* `image_tokens` is a Gemma 4 soft-token budget for this image (0: the configured one); a
|
||||
* processor that sizes images by pixels refuses a non-zero one. `max_pixels`, when set, first
|
||||
* scales a larger picture down to that area with PIL's bicubic. */
|
||||
* scales a larger picture down to that area with PIL's bicubic. `mode` picks one of the
|
||||
* checkpoint's picture modes where it has more than one (Unlimited-OCR). */
|
||||
int image(const uint8_t* bytes, size_t n, int32_t image_tokens, std::shared_ptr<Item>* out,
|
||||
std::string* why, int64_t max_pixels = 0) const;
|
||||
std::string* why, int64_t max_pixels = 0, const ImageMode& mode = ImageMode{}) const;
|
||||
int video(const uint8_t* bytes, size_t n, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
/* From an already-decoded picture or frame list; for tests. */
|
||||
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int image_from(const Frame& f, std::shared_ptr<Item>* out, std::string* why,
|
||||
const ImageMode& mode = ImageMode{}) const;
|
||||
int video_from(const Video& v, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
|
||||
/* A picture in the video VAE's own form: decoded under the same `max_source_pixels` guard as
|
||||
@@ -381,6 +426,8 @@ private:
|
||||
int image_gemma4(const Frame& f, int32_t soft, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
int image_lfm2(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
int image_unlimitedocr(const Frame& f, const ImageMode& mode, std::shared_ptr<Item>* out,
|
||||
std::string* why) const;
|
||||
int image_glm5next(const Frame& f, std::shared_ptr<Item>* out, std::string* why) const;
|
||||
/* Lfm2's markers: <|img_thumbnail|>, and <|img_row_R_col_C|> at (R-1) * max_tiles + C-1. */
|
||||
int32_t tok_thumbnail_ = -1;
|
||||
@@ -444,6 +491,28 @@ void cap_area(const Frame& in, int64_t max_pixels, Frame* out);
|
||||
* aspect, the larger grid of two equally near when the picture fills over half of it. */
|
||||
void lfm2_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
|
||||
int32_t* cols, int32_t* rows);
|
||||
/* Whether the reference's ratio set visits the tall side (c, r), c < r, of a transposed pair after
|
||||
* the wide one: the only tie two ratios of one tile count can have. From the reference itself. */
|
||||
bool uocr_tall_last(int32_t c, int32_t r);
|
||||
/* Unlimited-OCR's tile grid (its dynamic_preprocess): the min..max-tile grid nearest the picture's
|
||||
* aspect, the one whose area the picture covers over half of when two are equally near, exactly
|
||||
* as the reference's set ordering resolves it. The reference calls it only for a picture larger
|
||||
* than one tile; this answers for any size. */
|
||||
void uocr_grid(int64_t h, int64_t w, int32_t min_tiles, int32_t max_tiles, int32_t tile,
|
||||
int32_t* cols, int32_t* rows);
|
||||
/* The placeholders a picture takes: the global view's rows plus its separator, and, when tiled,
|
||||
* one line of `cols` tiles per feature row with a newline after it. `cols` * `rows` is the tile
|
||||
* grid. */
|
||||
int64_t uocr_tokens(const VisionConfig& c, const ImageMode& mode, int32_t cols, int32_t rows);
|
||||
/* The mode `mode` resolves to for this deployment; RAD_E_INVAL names an unsupported size. */
|
||||
int uocr_mode(const VisionConfig& c, const ImageMode& mode, bool* crop, int32_t* base_size,
|
||||
int32_t* image_size, std::string* why);
|
||||
/* Runs the resample and patch staging on their scalar path even where AVX2 is available, for a
|
||||
* test that compares the two; process-wide. */
|
||||
void mm_force_scalar(bool on);
|
||||
/* PIL's ImageOps.pad: `in` fitted inside w x h keeping its aspect (its bicubic), centred on `fill`
|
||||
* in the channels' order (127 127 127 for the reference's 0.5 mean). */
|
||||
void pad_bicubic(const Frame& in, int32_t w, int32_t h, uint8_t fill, Frame* out);
|
||||
|
||||
} /* namespace mm */
|
||||
} /* namespace rad */
|
||||
@@ -461,6 +461,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;
|
||||
@@ -471,7 +474,7 @@ int Registry::commit_(Staged& s, int order) {
|
||||
const int coll = collective ? collective(sr.second) : 0;
|
||||
row.collective = coll != 0;
|
||||
row.releases_link = coll == 2;
|
||||
row.reference = p.reference;
|
||||
row.reference = kern_ref ? kern_ref(sr.second) != 0 : p.reference;
|
||||
row.chain = chainable && chainable(sr.second) != 0;
|
||||
rows_.push_back(row);
|
||||
}
|
||||
|
||||
+45
-5
@@ -129,6 +129,8 @@ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped =
|
||||
* embedding takes Ram or Vram. */
|
||||
enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 };
|
||||
const char* table_placement_name(TablePlacement p);
|
||||
/* --attn-prefill-fp8's spelling of RAD_ATTN_FP8_* bits: off, qk, pv or both. */
|
||||
const char* attn_prefill_fp8_name(int bits);
|
||||
/* --draft-window: how many drafts a step verifies per sequence (core/sched/draft.h).
|
||||
* Fixed every sequence drafts --num-speculative-tokens.
|
||||
* Adaptive that is the ceiling; head depth per step and each sequence's stop follow measured
|
||||
@@ -390,6 +392,8 @@ public:
|
||||
* for drafters that did not ask. */
|
||||
bool drafter_shared_kv = false;
|
||||
int32_t drafter_pos_offset = 0;
|
||||
/* A block drafter's shorter block (rad_drafter_short_block), 0 when it serves only its own. */
|
||||
int64_t drafter_short_block = 0;
|
||||
|
||||
/* The declared media encoder (rad_declare_encoder). `modalities == 0` when none: every
|
||||
* text-only program, and every deployment with RadBuildCtx::max_enc_patches 0.
|
||||
@@ -414,7 +418,8 @@ public:
|
||||
* strings point at `agen_str`, as the image generator's do at `gen_str`. */
|
||||
RadAudioGenDecl audio_gen{};
|
||||
struct AudioGenStrings {
|
||||
std::string name, tmpl, tmpl_plain, neg_tmpl; /* "" for an absent template */
|
||||
/* "" for an absent template; tmpl_ref and ref_item RadAudioGenDecl's references */
|
||||
std::string name, tmpl, tmpl_plain, neg_tmpl, tmpl_ref, ref_item;
|
||||
} agen_str;
|
||||
bool is_audio_generator() const { return audio_gen.max_lanes != 0; }
|
||||
/* The declared video generator (rad_declare_video_generator); `max_lanes` 0 when none. */
|
||||
@@ -456,6 +461,14 @@ public:
|
||||
* region safely through in-order launch; a second lane is a second stream and needs its own.
|
||||
* Two when the architecture declared a buffer rad_buf_concurrent. */
|
||||
int32_t scratch_regions = 1;
|
||||
/* Region 1's size when there are two: the largest device scratch of an op the second lane may
|
||||
* issue. By Ctx::lane1_'s rule 3 such an op touches only rad_buf_concurrent buffers, so an op
|
||||
* with any other transient buffer never runs there; one naming no transient buffer counts.
|
||||
* At most scratch_bytes; -1 (a program not built by the Builder) means scratch_bytes. */
|
||||
int64_t scratch_bytes_lane1 = -1;
|
||||
/* The second lane's window (rad_lane1_window_begin): the first and last op handle lane 1 may run;
|
||||
* -1 when the architecture declared none (concurrent buffers then live for the whole program). */
|
||||
int32_t lane1_w0 = -1, lane1_w1 = -1;
|
||||
|
||||
/* Everything that resolved to nothing, reported whole rather than stopping at the first
|
||||
* failure (spec §3.1). Structured because the domains are reported differently: a device miss
|
||||
@@ -620,11 +633,22 @@ struct SamplingParams {
|
||||
|
||||
/* The control vector (core/cvec.h): whether this request's steps project the vector found for
|
||||
* this deployment out of the residual stream. The server sets it from the request's
|
||||
* `control_vector` field (`experimental_speed_projection` is Strata's spelling of the same
|
||||
* switch), or from the deployment's runtime default when the request names none; it needs no
|
||||
* reload and leaves the graph untouched. A deployment with no vector refuses `true` at
|
||||
* admission rather than serving the stock model. */
|
||||
* `control_vector` field, or from the deployment's runtime default when the request names
|
||||
* none. A deployment with no vector refuses `true` at admission. */
|
||||
bool use_control_vector = false;
|
||||
/* The windowed no-repeat-ngram ban (core/sample/sampler.h, `sample_ngram_ban`): a token that
|
||||
* would complete an `ngram_ban_n`-gram already present in the last `ngram_window` tokens of
|
||||
* the sequence is banned. `ngram_ban_n` 0 is off, the default; `ngram_window` <= 0 searches
|
||||
* the whole staged history (the un-windowed processor). Unlimited-OCR's generation_config
|
||||
* asks for 35 and 128 (the model card's document mode uses 1024). */
|
||||
int ngram_ban_n = 0;
|
||||
int ngram_window = 0;
|
||||
/* The ids exempt from that ban: the reference processor's whitelist
|
||||
* (SlidingWindowNoRepeatNgramProcessor's `whitelist_token_ids`, whose set is removed from
|
||||
* the banned set after it is built -- modeling_unlimitedocr.py:359,379). Global token ids,
|
||||
* duplicates ignored. Empty (the default) is off: the ban is then bit-identical to the
|
||||
* no-whitelist form. */
|
||||
std::vector<int32_t> ngram_whitelist;
|
||||
};
|
||||
|
||||
/* Raw logits at chosen vocabulary ids at the prompt's last position, for a caller that answers
|
||||
@@ -741,6 +765,9 @@ struct Config {
|
||||
* element plus a bf16 scale per 64) instead of 16 bits per element, 2.4x fewer bytes over
|
||||
* PCIe. The received sum then differs undetectably, hence a named flag, not a heuristic. */
|
||||
int tp_wire_exact = 1; /* --tp-wire exact|wht6 */
|
||||
/* --tp-attn-split heads|rows: 1 runs a prefill-sized step's attention by rows over the ranks
|
||||
* (RadBuildCtx::tp_attn_rows). Not bit-identical to the head split, so heads is the default. */
|
||||
int tp_attn_rows = 0;
|
||||
/* Smallest all-reduce message, in KiB, that the lossy wire compresses; smaller ones are sent
|
||||
* exact. Compression pays only when the transfer is bandwidth-bound: a decode step's handful
|
||||
* of residual rows costs more to rotate than it saves, while a prefill chunk is far larger.
|
||||
@@ -787,6 +814,11 @@ struct Config {
|
||||
* explicit and bf16 is the default. No "auto": it would always resolve to bf16 and only add
|
||||
* another name. */
|
||||
std::string kv_cache_dtype = "bf16";
|
||||
std::string state_cache_dtype = "f32"; /* --state-cache-dtype: f32 | f16 */
|
||||
/* --attn-prefill-fp8 off|qk|pv|both: RAD_ATTN_FP8_* bits, the prefill attention's products
|
||||
* accepted in e4m3 (RadBuildCtx::attn_prefill_fp8). Lossy, so off is the default.
|
||||
* attn_prefill_fp8_name() spells it as the flag does. */
|
||||
int attn_prefill_fp8 = 0;
|
||||
int64_t host_pool_mib = 0;
|
||||
int64_t host_headroom_mib = 4096; /* --host-headroom-mib: RAM left free for the system at startup */
|
||||
/* File tier for weights: what fits in neither the VRAM slab nor the pinned host pool is read
|
||||
@@ -881,6 +913,14 @@ struct Config {
|
||||
* VRAM and still decode one token a step. */
|
||||
int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */
|
||||
DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */
|
||||
/* A block drafter's short block (rad_drafter_short_block) from this many decoding sequences in
|
||||
* the step just run; 0 never. Ignored without a drafter that declares one. */
|
||||
int64_t draft_short_from = 0; /* --draft-short-from */
|
||||
|
||||
/* --draft-coupling off|on: a linear serial drafter samples its proposals and the sampler
|
||||
* applies the maximal coupling at the verify (RadBuildCtx::draft_coupling, abi/rad_spechub.h).
|
||||
* Off by default; on changes which tokens a fixed seed yields, not their law. */
|
||||
bool draft_coupling = false;
|
||||
|
||||
/* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ----------------
|
||||
*
|
||||
|
||||
+12
-5
@@ -5,15 +5,18 @@
|
||||
|
||||
namespace rad {
|
||||
|
||||
int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions) {
|
||||
int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions,
|
||||
int64_t scratch_bytes1) {
|
||||
release();
|
||||
if (plan_bytes < 0 || scratch_bytes < 0 || regions < 1) return RAD_E_INVAL;
|
||||
if (scratch_bytes1 < 0 || scratch_bytes1 > scratch_bytes) scratch_bytes1 = scratch_bytes;
|
||||
|
||||
/* Scratch starts on a page boundary, so a workspace gets 4 KiB alignment for at most one
|
||||
* page of padding. */
|
||||
const int64_t off = align_up(plan_bytes, RAD_ALIGN_UNIT);
|
||||
const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT);
|
||||
const int64_t tail = pitch * regions;
|
||||
const int64_t pitch = align_up(scratch_bytes, RAD_ALIGN_UNIT);
|
||||
const int64_t pitch1 = align_up(scratch_bytes1, RAD_ALIGN_UNIT);
|
||||
const int64_t tail = pitch + pitch1 * (regions - 1);
|
||||
int64_t total = off + tail;
|
||||
|
||||
/* Never zero bytes: a null base would turn a plan bug into an anonymous segfault. */
|
||||
@@ -33,6 +36,8 @@ int Arena::init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions
|
||||
scratch_off_ = off;
|
||||
scratch_bytes_ = scratch_bytes;
|
||||
scratch_pitch_ = pitch;
|
||||
scratch_bytes1_ = regions > 1 ? scratch_bytes1 : 0;
|
||||
scratch_pitch1_ = regions > 1 ? pitch1 : 0;
|
||||
scratch_regions_ = regions;
|
||||
return RAD_OK;
|
||||
}
|
||||
@@ -87,8 +92,10 @@ int64_t arena_plan_bytes(const Program& P, int64_t* dev_out, int64_t* total_out)
|
||||
/* The staging region sits above every buffer, so it is a separate term. */
|
||||
if (P.arena_stage_bytes > 0 && P.arena_stage_off >= 0)
|
||||
dev_bytes = std::max(dev_bytes, P.arena_stage_off + P.arena_stage_bytes);
|
||||
int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) +
|
||||
align_up(P.scratch_bytes, RAD_ALIGN_UNIT) * std::max<int64_t>(P.scratch_regions, 1);
|
||||
const int64_t s1 = P.scratch_bytes_lane1 < 0 || P.scratch_bytes_lane1 > P.scratch_bytes
|
||||
? P.scratch_bytes : P.scratch_bytes_lane1;
|
||||
int64_t total = align_up(dev_bytes, RAD_ALIGN_UNIT) + align_up(P.scratch_bytes, RAD_ALIGN_UNIT) +
|
||||
align_up(s1, RAD_ALIGN_UNIT) * (std::max<int64_t>(P.scratch_regions, 1) - 1);
|
||||
if (total == 0) total = RAD_ALIGN_UNIT; /* Arena::init's floor, for the same reason */
|
||||
if (dev_out) *dev_out = dev_bytes;
|
||||
if (total_out) *total_out = total;
|
||||
|
||||
+13
-4
@@ -25,18 +25,25 @@ public:
|
||||
Arena& operator=(const Arena&) = delete;
|
||||
|
||||
/* `kind` is a RAD_MEM_* class: RAD_MEM_DEVICE for the device arena, RAD_MEM_HOST for the
|
||||
* second arena a program with RAD_DOMAIN_HOST buffers gets. `regions` scratch regions of
|
||||
* `scratch_bytes` each sit at the tail, one per lane. */
|
||||
int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1);
|
||||
* second arena a program with RAD_DOMAIN_HOST buffers gets. `regions` scratch regions sit at the
|
||||
* tail, one per lane: region 0 of `scratch_bytes`, the others of `scratch_bytes1` (-1: the same;
|
||||
* Program::scratch_bytes_lane1). */
|
||||
int init(int64_t plan_bytes, int64_t scratch_bytes, int kind, int regions = 1,
|
||||
int64_t scratch_bytes1 = -1);
|
||||
void release();
|
||||
|
||||
char* base() const { return base_; }
|
||||
/* Region `r`, or region 0 when the arena holds fewer. */
|
||||
void* scratch(int r = 0) const {
|
||||
if (!base_) return nullptr;
|
||||
return base_ + scratch_off_ + (r > 0 && r < scratch_regions_ ? r * scratch_pitch_ : 0);
|
||||
return base_ + scratch_off_ +
|
||||
(r > 0 && r < scratch_regions_ ? scratch_pitch_ + (r - 1) * scratch_pitch1_ : 0);
|
||||
}
|
||||
/* Region 0's size (the program's largest kernel), or region `r`'s. */
|
||||
int64_t scratch_bytes() const { return scratch_bytes_; }
|
||||
int64_t scratch_bytes(int r) const {
|
||||
return r > 0 && r < scratch_regions_ ? scratch_bytes1_ : scratch_bytes_;
|
||||
}
|
||||
int scratch_regions() const { return scratch_regions_; }
|
||||
int64_t bytes() const { return bytes_; }
|
||||
bool live() const { return base_ != nullptr; }
|
||||
@@ -48,6 +55,8 @@ private:
|
||||
int64_t scratch_off_ = 0;
|
||||
int64_t scratch_bytes_ = 0;
|
||||
int64_t scratch_pitch_ = 0; /* scratch_bytes_ padded to RAD_ALIGN_UNIT */
|
||||
int64_t scratch_bytes1_ = 0; /* each region past 0 */
|
||||
int64_t scratch_pitch1_ = 0;
|
||||
int scratch_regions_ = 1;
|
||||
};
|
||||
|
||||
|
||||
+17
-5
@@ -153,13 +153,20 @@ int Ctx::bind_arena() {
|
||||
int64_t dev_bytes = 0, total = 0;
|
||||
arena_plan_bytes(P, &dev_bytes, &total);
|
||||
|
||||
RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1)));
|
||||
RAD_TRY(arena_.init(dev_bytes, P.scratch_bytes, RAD_MEM_DEVICE, std::max(P.scratch_regions, 1),
|
||||
P.scratch_bytes_lane1));
|
||||
/* The arena is in no pool and scales with max_tok, so core/mem/vram_budget.cpp charges it by
|
||||
* name rather than leaving it to --gpu-headroom-mib. This log line must agree with that
|
||||
* charge. */
|
||||
RAD_INFO("arena: %s device + %d x %s scratch = %s, charged to the VRAM budget before it was "
|
||||
"split", humanb(dev_bytes).c_str(), arena_.scratch_regions(),
|
||||
humanb(P.scratch_bytes).c_str(), humanb(total).c_str());
|
||||
if (arena_.scratch_regions() > 1)
|
||||
RAD_INFO("arena: %s device + %s scratch + %s for the second lane = %s, charged to the VRAM "
|
||||
"budget before it was split", humanb(dev_bytes).c_str(),
|
||||
humanb(P.scratch_bytes).c_str(), humanb(arena_.scratch_bytes(1)).c_str(),
|
||||
humanb(total).c_str());
|
||||
else
|
||||
RAD_INFO("arena: %s device + %s scratch = %s, charged to the VRAM budget before it was "
|
||||
"split", humanb(dev_bytes).c_str(), humanb(P.scratch_bytes).c_str(),
|
||||
humanb(total).c_str());
|
||||
|
||||
if (host_hw > 0) {
|
||||
/* RAD_MEM_HOST_MAPPED, not RAD_MEM_HOST: nothing copies between the two arenas, so device
|
||||
@@ -333,6 +340,8 @@ int Ctx::bind_ops() {
|
||||
p.billed = (oi.op == "all_reduce");
|
||||
p.collective = p.billed;
|
||||
p.lora_site = oi.lora_site;
|
||||
p.order = oi.anchor > 0 && (size_t)oi.anchor < P.ops.size() ? P.ops[(size_t)oi.anchor].index
|
||||
: oi.index;
|
||||
|
||||
for (const Band& b : oi.bands) band_table_.push_back(b.hi);
|
||||
|
||||
@@ -908,6 +917,7 @@ int Ctx::lane_join(int from, int to) {
|
||||
RAD_TRY(rad_event_record(lane_ev_[from], fs));
|
||||
RAD_TRY(rad_event_wait(ts, lane_ev_[from]));
|
||||
scratch_open_[from] = false; /* `to` is now behind every scratch user `from` issued */
|
||||
if (from == 1 && to == 0) lane1_pending_ = false;
|
||||
return RAD_OK;
|
||||
}
|
||||
|
||||
@@ -918,7 +928,7 @@ int Ctx::lane_join(int from, int to) {
|
||||
* field added to RadBatch changes its size: decide whether the key must read it, then update the
|
||||
* size here. `agen_b` and `vgen_b` are set only on generator passes, which are never recorded
|
||||
* (below). */
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 336,
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadBatch) == 360,
|
||||
"RadBatch changed: check that Ctx::pass_key reads every new field a pass depends on");
|
||||
static_assert(sizeof(void*) != 8 || sizeof(RadKVGroupBatch) == 72,
|
||||
"RadKVGroupBatch changed: check that Ctx::pass_key reads every new field");
|
||||
@@ -949,6 +959,8 @@ uint64_t Ctx::pass_key(const RadBatch* b) const {
|
||||
/* Null on a step with no adapter row, which then issues no adapter op (Ctx::issue_lora): the
|
||||
* two are different passes. The slots themselves are read on the card. */
|
||||
ptr(b->lora_slot);
|
||||
/* Zero issues no projection op (RadBatch::control_vector). */
|
||||
mix((uint64_t)b->control_vector);
|
||||
for (int g = 0; g < b->n_kv_groups; ++g) {
|
||||
const RadKVGroupBatch& k = b->kv[g];
|
||||
mix((uint64_t)k.group); ptr(k.slot_mapping); ptr(k.block_table);
|
||||
|
||||
+13
-2
@@ -94,6 +94,9 @@ struct OpPlan {
|
||||
bool billed = false;
|
||||
/* Runtime LoRA: this gemm's row in Program::lora_sites, -1 for every op that is not one. */
|
||||
int32_t lora_site = -1;
|
||||
/* Its position in the declared order, or its anchor's for a core-appended op: what the second
|
||||
* lane's window (Program::lane1_w0..lane1_w1) is checked against. */
|
||||
int32_t order = 0;
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ routing handoff */
|
||||
@@ -294,6 +297,8 @@ public:
|
||||
void dump_profile() const; /* spec §16, opt-in, with its caveat printed */
|
||||
const char* step_error() const { return step_fail_.c_str(); }
|
||||
int64_t stream_waits() const { return n_stream_waits_; }
|
||||
/* Lane 1 has work lane 0 has not joined (lane1_pending_). */
|
||||
bool lane1_pending() const { return lane1_pending_; }
|
||||
/* Host synchronisations on the step path. Always zero unless per-op timing is on (spec §16);
|
||||
* tests read it. Teardown's drain is not counted. */
|
||||
int64_t host_syncs() const { return n_host_syncs_; }
|
||||
@@ -552,6 +557,9 @@ public:
|
||||
/* Backs rad_step_fail(): stops the step like an operand rejection, with the caller's
|
||||
* message. */
|
||||
int step_fail(const char* what);
|
||||
/* The device kernel `h` resolved to on this rank ("?" if it resolved none). For log
|
||||
* attribution only. */
|
||||
const char* ip_kernel_name(rad_op h) const;
|
||||
private:
|
||||
[[noreturn]] void fatal_issue(rad_op h, int64_t n, const char* why) const;
|
||||
|
||||
@@ -578,7 +586,6 @@ private:
|
||||
* byte-compares the two results, finding kernels that are not a function of their inputs,
|
||||
* which a host-vs-device comparison cannot detect. */
|
||||
void oracle_repeat(rad_op h, const IssuePlan& dip, int64_t seq, int n_opd);
|
||||
const char* ip_kernel_name(rad_op h) const;
|
||||
/* The reference library's host plan for (op, band): the band's own host plan when a reference
|
||||
* library won it, else one resolved from `registry_` on first use. Null when none exists. */
|
||||
const IssuePlan* oracle_reference(rad_op h, int band);
|
||||
@@ -625,7 +632,8 @@ private:
|
||||
* 3. The buffer planner packs from one linear order, so two lanes can alias arena bytes
|
||||
* through buffers with disjoint declared lifetimes. The architecture passes every buffer
|
||||
* its second lane touches to `rad_buf_concurrent`, which makes it live for the whole
|
||||
* program.
|
||||
* program, or, where the architecture declares the second lane's window
|
||||
* (rad_lane1_window_begin / _end), across the window and its own declared uses.
|
||||
*
|
||||
* 4. A slice must land in the same bucket-table band as the whole, or it picks a kernel with
|
||||
* a different summation order and silently changes output. `--debug-graph` prints a model's
|
||||
@@ -647,6 +655,9 @@ private:
|
||||
bool own_lane1_ = false;
|
||||
int lane_ = 0;
|
||||
RadEvent lane_ev_[2] = { nullptr, nullptr };
|
||||
/* An op was issued on lane 1 since lane 1 was last joined into lane 0; lane 0 joins it before
|
||||
* an op outside the second lane's window (Ctx::issue_body). */
|
||||
bool lane1_pending_ = false;
|
||||
/* The last device op on each lane that touched host-domain memory. A host op runs at issue on
|
||||
* this thread and must be ordered behind every earlier device op that touched the host arena;
|
||||
* on each lane those complete no later than the last one. So a device op with a host-domain
|
||||
|
||||
+32
-2
@@ -592,6 +592,25 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
? "has no host kernel for this band, and the placement planner put "
|
||||
"it on the host anyway"
|
||||
: "has no device kernel for this band");
|
||||
/* The second lane's window (rad_lane1_window_begin): its concurrent buffers are live only across
|
||||
* it, so lane 1 runs nothing outside it, and lane 0 joins lane 1 before it runs an op outside
|
||||
* it, on either side: a transient of such an op may share bytes with a concurrent buffer. */
|
||||
if (program_ && program_->lane1_w1 >= 0) {
|
||||
const bool outside = p.order < program_->lane1_w0 || p.order > program_->lane1_w1;
|
||||
if (lane_ == 1 && outside)
|
||||
return abort_step_msg(h, RAD_E_STATE,
|
||||
fmt("issued on the second lane outside its declared window (ops "
|
||||
"%d..%d, this one %d): the buffers it may touch there are "
|
||||
"live only across the window",
|
||||
(int)program_->lane1_w0, (int)program_->lane1_w1, (int)p.order));
|
||||
if (lane_ == 0 && lane1_pending_ && outside) {
|
||||
const int js = lane_join(1, 0);
|
||||
if (js < 0)
|
||||
return abort_step_msg(h, js, "joining the second lane outside its window failed");
|
||||
}
|
||||
}
|
||||
if (lane_ == 1) lane1_pending_ = true;
|
||||
|
||||
/* The row's DIV on the ranged parameter held at the band's upper bound, maybe not here. */
|
||||
if (ip.ranged_div > 1 && n % ip.ranged_div != 0)
|
||||
return abort_step_msg(h, RAD_E_SHAPE,
|
||||
@@ -884,7 +903,18 @@ int Ctx::issue_body(rad_op h, const RadOperand* opd, int n_opd, int64_t n) {
|
||||
* correctness. That also covers lane 0 before lane 1 exists, since a lane built later has
|
||||
* nothing ordering it behind lane 0's earlier work. */
|
||||
if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST && arena_.scratch_regions() > 1) {
|
||||
/* Per-lane regions: nothing to order. */
|
||||
/* Per-lane regions: nothing to order. Region 1 holds what an op the second lane may issue
|
||||
* asked for at declare (Program::scratch_bytes_lane1); a larger request there comes from an
|
||||
* op with a transient buffer outside rad_buf_concurrent, which breaks Ctx::lane1_'s rule 3
|
||||
* in its buffers too, so it is refused by name rather than let overrun the region. */
|
||||
if (ip.args.scratch_bytes > arena_.scratch_bytes(lane_)) {
|
||||
return abort_step_msg(h, RAD_E_SCRATCH,
|
||||
fmt("kernel %s at n=%lld asks for %lld bytes of scratch on lane %d, whose region "
|
||||
"holds %lld: an op on the second lane may touch only buffers named to "
|
||||
"rad_buf_concurrent (Ctx::lane1_ rule 3)",
|
||||
ip.row && ip.row->info ? ip.row->info->name : "?", (long long)n,
|
||||
(long long)ip.args.scratch_bytes, lane_, (long long)arena_.scratch_bytes(lane_)));
|
||||
}
|
||||
ip.args.scratch = scratch_take(lane_, ip.args.scratch_bytes);
|
||||
} else if (ip.args.scratch_bytes > 0 && dom != RAD_DOMAIN_HOST) {
|
||||
ip.args.scratch = scratch_take(0, ip.args.scratch_bytes);
|
||||
@@ -1058,7 +1088,7 @@ void* Ctx::scratch_take(int region, int64_t bytes) {
|
||||
constexpr int64_t kAlign = 256;
|
||||
const int64_t need = (bytes + kAlign - 1) / kAlign * kAlign;
|
||||
int64_t off = scratch_cur_[region];
|
||||
if (off + need > arena_.scratch_bytes()) off = 0;
|
||||
if (off + need > arena_.scratch_bytes(region)) off = 0;
|
||||
scratch_cur_[region] = off + need;
|
||||
return (char*)arena_.scratch(region) + off;
|
||||
}
|
||||
|
||||
@@ -32,6 +32,7 @@ void bind_kv_pools(const Program& p, const std::function<const KVGroupPlan*(int3
|
||||
switch (gp->kind) {
|
||||
case RAD_KV_FULL:
|
||||
case RAD_KV_WINDOW:
|
||||
case RAD_KV_RING:
|
||||
b.rank = 4;
|
||||
b.shape[0] = gp->n_blocks;
|
||||
b.shape[1] = d.n_head_kv;
|
||||
|
||||
@@ -226,8 +226,18 @@ int TierExec::device_init() {
|
||||
bool ev = rad_event_create(&ev_compute_) == RAD_OK && rad_event_create(&ev_copy_) == RAD_OK &&
|
||||
rad_event_create(&ev_restore_) == RAD_OK;
|
||||
for (int i = 0; i < kRing && ev; ++i) ev = rad_event_create(&ring_ev_[i]) == RAD_OK;
|
||||
if (verify_rep_) vrep_ = (char*)rad_dev_alloc(copy_idx_ * rep_bytes_, RAD_MEM_HOST_PINNED);
|
||||
if (!stage_ || !idx_dev_ || !idx_host_ || !ev || (verify_rep_ && !vrep_)) {
|
||||
/* The verify scratch is a diagnostic's: without it the replicated groups go unchecked, and
|
||||
* the tiers run as they would without RADIANCE_DEBUG_TIER_VERIFY. */
|
||||
if (verify_rep_) {
|
||||
vrep_ = (char*)rad_dev_alloc(copy_idx_ * rep_bytes_, RAD_MEM_HOST_PINNED);
|
||||
if (!vrep_) {
|
||||
RAD_WARN("kv tiers: RADIANCE_DEBUG_TIER_VERIFY: no pinned host memory (%s) for this "
|
||||
"rank's copy of the replicated groups, so they are not compared",
|
||||
humanb(copy_idx_ * rep_bytes_).c_str());
|
||||
verify_rep_ = false;
|
||||
}
|
||||
}
|
||||
if (!stage_ || !idx_dev_ || !idx_host_ || !ev) {
|
||||
release_device();
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include <cfloat>
|
||||
#include <cmath>
|
||||
#include <numeric>
|
||||
#include <unordered_set>
|
||||
|
||||
namespace rad {
|
||||
|
||||
@@ -51,12 +52,6 @@ static uint64_t stream_key(uint32_t stream) {
|
||||
}
|
||||
}
|
||||
|
||||
/* rad_sample_uniform01's bits before the float conversion: one splitmix64 round over
|
||||
* ((seed ^ key) * golden ratio + pos), cheap and stateless enough for a kernel. */
|
||||
uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream) {
|
||||
return rad_sample_splitmix64((seed ^ stream_key(stream)) * 0x9E3779B97F4A7C15ull + pos);
|
||||
}
|
||||
|
||||
float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream) {
|
||||
/* 24 bits: 32 bits divided by 2^32 can round to 1.0f, which walks off the end of an inverse
|
||||
* CDF. Calls rad_sample_uniform01 itself so host and device cannot drift apart. */
|
||||
@@ -526,8 +521,48 @@ int32_t host_argmax(const float* logits, int64_t n_vocab) {
|
||||
return (int32_t)best;
|
||||
}
|
||||
|
||||
/* ================================================================== the chain */
|
||||
void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n,
|
||||
int32_t window, const uint32_t* whitelist, int64_t wl_words) {
|
||||
if (n <= 0 || !history || n_history < (int64_t)n) return;
|
||||
const int64_t len = n_history;
|
||||
const int64_t win = (window > 0 && window < len) ? window : len;
|
||||
const int64_t start = len - win, end = len - n + 1;
|
||||
if (end <= start) return;
|
||||
const int64_t plen = (int64_t)n - 1, p0 = len - plen;
|
||||
|
||||
/* The set of tokens a continuation would complete an n-gram with, as the reference builds it:
|
||||
* every n-gram in the window whose first n-1 tokens equal the current prefix contributes the
|
||||
* token after them. */
|
||||
std::unordered_set<int32_t> banned;
|
||||
for (int64_t idx = start; idx < end; ++idx) {
|
||||
bool match = true;
|
||||
for (int64_t j = 0; j < plen; ++j) {
|
||||
if (history[idx + j] != history[p0 + j]) { match = false; break; }
|
||||
}
|
||||
if (match) banned.insert(history[idx + plen]);
|
||||
}
|
||||
|
||||
/* The reference's `banned.difference_update(self.whitelist)`, before any -inf: a token whose
|
||||
* whitelist bit is set is never banned. A bit past the plane is not set, so a token outside
|
||||
* it stays banned, as an id the reference's set does not contain. */
|
||||
if (whitelist && wl_words > 0) {
|
||||
for (auto it = banned.begin(); it != banned.end();) {
|
||||
const int64_t id = *it;
|
||||
if (id >= 0 && (id >> 5) < wl_words &&
|
||||
(whitelist[(size_t)(id >> 5)] >> ((uint32_t)id & 31u)) & 1u)
|
||||
it = banned.erase(it);
|
||||
else
|
||||
++it;
|
||||
}
|
||||
}
|
||||
|
||||
if (banned.empty()) return;
|
||||
s.sorted = false; /* a -infinity candidate belongs after every finite one */
|
||||
for (Candidate& c : s.c)
|
||||
if (banned.count(c.id) != 0) c.logit = -INFINITY;
|
||||
}
|
||||
|
||||
/* ================================================================== the chain */
|
||||
int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRefInput& in,
|
||||
ChainOrder order) {
|
||||
/* Penalties first in both orders: they act on raw logits, the cuts on probabilities. */
|
||||
@@ -547,6 +582,11 @@ int32_t host_sample_into(CandidateSet& s, const SamplingParams& sp, const HostRe
|
||||
in.dry_breakers ? *in.dry_breakers : kNone);
|
||||
}
|
||||
|
||||
/* The n-gram ban, after the penalties and before the greedy split: the device chain issues it
|
||||
* there, so a greedy request sees the same masked distribution. Off at ngram_ban_n 0. */
|
||||
host_ngram_ban(s, in.history, in.n_history, sp.ngram_ban_n, sp.ngram_window,
|
||||
in.ngram_whitelist, in.ngram_whitelist_words);
|
||||
|
||||
/* Greedy skips the chain: penalties -> mask -> argmax. Temperature 0 collapses every other
|
||||
* logit to -inf, so a mask applied after it could leave nothing. */
|
||||
if (sp.greedy()) {
|
||||
|
||||
+19
-2
@@ -71,7 +71,6 @@ enum : uint32_t {
|
||||
RAD_RNG_XTC = 1 /* XTC's "does this fire at all" coin */
|
||||
};
|
||||
|
||||
uint64_t rng_bits(uint64_t seed, uint64_t pos, uint32_t stream);
|
||||
/* Uniform in [0,1) with 24 bits, the most a float resolves; more would let host and device
|
||||
* disagree in the last place. */
|
||||
float rng_uniform(uint64_t seed, uint64_t pos, uint32_t stream);
|
||||
@@ -177,6 +176,19 @@ void host_dry(CandidateSet& s, const int32_t* history, int64_t n_history,
|
||||
void host_xtc(CandidateSet& s, float probability, float threshold, size_t min_keep,
|
||||
uint64_t seed, uint64_t pos);
|
||||
|
||||
/* The windowed no-repeat-ngram ban (`sample_ngram_ban`, Unlimited-OCR's
|
||||
* SlidingWindowNoRepeatNgramProcessor): a candidate whose token would complete an `n`-gram the
|
||||
* last `window` tokens of `history` already contain gets -infinity. `n` <= 0 is off, `window` <= 0
|
||||
* is the whole history. It runs after the penalties and DRY and before every cut, so the greedy
|
||||
* path sees it too.
|
||||
*
|
||||
* `whitelist` is the reference's whitelist (a SET bit means exempt from the ban, the same plane
|
||||
* form as host_mask's, word w bit b covering token 32w + b): ids removed from the banned set
|
||||
* before anything is written, as `banned.difference_update(self.whitelist)` does. Null or zero
|
||||
* words is off -- the reference's empty whitelist, the default serving form. */
|
||||
void host_ngram_ban(CandidateSet& s, const int32_t* history, int64_t n_history, int32_t n,
|
||||
int32_t window, const uint32_t* whitelist = nullptr, int64_t wl_words = 0);
|
||||
|
||||
/* The grammar mask. One bit per token, set means admissible; a cleared bit sets the logit to -inf
|
||||
* instead of removing the candidate, so nothing downstream is renumbered. `n_words` is
|
||||
* ceil(n_vocab/32). */
|
||||
@@ -203,7 +215,8 @@ constexpr int64_t kSampleCandidates = 1024;
|
||||
constexpr int64_t kSampleMergeCandidates = 4096;
|
||||
|
||||
enum class ChainOrder {
|
||||
Radiance = 0, /* penalties, DRY, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */
|
||||
/* penalties, DRY, n-gram ban, temperature, mask, top-k, top-p/min-p/typical, XTC, pick */
|
||||
Radiance = 0,
|
||||
LlamaCpp = 1 /* penalties, DRY, top-k, typical, top-p, min-p, XTC, temperature, pick */
|
||||
};
|
||||
|
||||
@@ -215,6 +228,10 @@ struct HostRefInput {
|
||||
int64_t total_context = 0; /* DRY's clamp; 0 means use n_history */
|
||||
const uint32_t* bitmask = nullptr; /* grammar mask, or null */
|
||||
int64_t n_words = 0;
|
||||
/* The n-gram ban's whitelist bitmask (a SET bit exempts a token, host_ngram_ban), null =
|
||||
* no exemptions. */
|
||||
const uint32_t* ngram_whitelist = nullptr;
|
||||
int64_t ngram_whitelist_words = 0;
|
||||
uint64_t pos = 0; /* output position: the RNG's second coordinate */
|
||||
const DryBreakers* dry_breakers = nullptr; /* null runs DRY with no breakers */
|
||||
/* The chain's candidate width (SamplerConfig::max_candidates): top-k narrows every row to
|
||||
|
||||
@@ -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
|
||||
+190
-14
@@ -133,6 +133,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
}
|
||||
|
||||
cfg_ = cfg;
|
||||
couple_ = cfg.draft_coupling;
|
||||
if (cfg_.n_vocab_local <= 0) cfg_.n_vocab_local = cfg_.n_vocab / cfg_.world_size;
|
||||
|
||||
/* The staged mask covers this rank's shard; the grammar's covers the whole vocabulary.
|
||||
@@ -178,7 +179,21 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
/* One byte per history token, nonzero where the token is a whole DRY sequence breaker (never
|
||||
* penalised). Resolved on the host, which has the vocabulary. */
|
||||
buf_brk_ = decl("sampler.dry_breakers", RAD_U8, rows, cfg_.max_hist, RAD_BUF_PERSIST);
|
||||
/* The n-gram ban's per-row {n-gram length, window}. Its own tiny plane because the params row
|
||||
* is the fixed RadSampleParams wire format every sampler op shares. */
|
||||
buf_ngram_ = decl("sampler.ngram", RAD_I32, rows, 2, RAD_BUF_PERSIST);
|
||||
/* The ban's whitelist bitmask, this rank's shard, shaped like the mask plane: a SET bit
|
||||
* exempts that column. The ban op indexes it by the sampled row, not by mask_row. */
|
||||
buf_ngram_wl_ = decl("sampler.ngram_wl", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
|
||||
buf_mask_ = decl("sampler.mask", RAD_U32, rows, mask_words_, RAD_BUF_PERSIST);
|
||||
/* The coupled state plane, one row per sampled position, PERSIST because an upload fills it
|
||||
* before the run phase issues anything. A round's state belongs to the verify row that
|
||||
* follows it, so it rides the sampler's row array. */
|
||||
if (couple_) {
|
||||
buf_couple_ = decl("sampler.mtp_couple", RAD_U32, rows, RAD_MTP_COUPLE_STATE_WORDS,
|
||||
RAD_BUF_PERSIST);
|
||||
if (!buf_couple_) return RAD_E_NOMEM;
|
||||
}
|
||||
buf_cand_i_ = decl("sampler.cand_idx", RAD_I32, rows, ncand, RAD_BUF_TRANSIENT);
|
||||
buf_cand_v_ = decl("sampler.cand_val", RAD_F32, rows, ncand, RAD_BUF_TRANSIENT);
|
||||
if (vocab_parallel()) {
|
||||
@@ -197,7 +212,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
buf_lp_g_ = decl("sampler.logprobs_gathered", RAD_F32, rows,
|
||||
lp_width() * cfg_.world_size, RAD_BUF_PERSIST);
|
||||
|
||||
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_mask_ ||
|
||||
if (!buf_params_ || !buf_params_late_ || !buf_hist_ || !buf_brk_ || !buf_ngram_ ||
|
||||
!buf_ngram_wl_ || !buf_mask_ ||
|
||||
!buf_cand_i_ || !buf_cand_v_ || !buf_lp_ ||
|
||||
(vocab_parallel() && (!buf_pairs_ || !buf_gather_ || !buf_lp_g_))) {
|
||||
RAD_ERR("sampler: a staging buffer failed to declare");
|
||||
@@ -239,6 +255,7 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
|
||||
op_penalties_ = op_vocab_off("sample_penalties");
|
||||
op_dry_ = op_vocab_off("sample_dry");
|
||||
op_ngram_ban_ = op_vocab_off("sample_ngram_ban");
|
||||
op_temp_ = op_vocab("sample_temp");
|
||||
op_mask_ = op_vocab("sample_mask");
|
||||
op_topk_ = op_vocab_off("sample_topk");
|
||||
@@ -249,6 +266,19 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
op_typical_ = op_cand("sample_typical");
|
||||
op_xtc_ = op_cand("sample_xtc");
|
||||
op_pick_ = op_cand("sample_pick");
|
||||
/* The coupled verify, over the candidate plane the pick read. A row with no bound state keeps
|
||||
* the pick's token; a step with no bound row does not issue it. */
|
||||
if (couple_) {
|
||||
RadParam pc[3] = {
|
||||
RadParam{ "M", RAD_P_RANGE, 1, rows, nullptr },
|
||||
RadParam{ "n_cand", RAD_P_INT, (long long)ncand, 0, nullptr },
|
||||
RadParam{ "n_vocab", RAD_P_INT, (long long)cfg_.n_vocab, 0, nullptr },
|
||||
};
|
||||
op_couple_ = rad_decl_op(b, "mtp_couple_verify", pc, 3, nullptr, 0);
|
||||
if (!op_couple_) return RAD_E_NOKERNEL;
|
||||
/* No rad_op_reads: the other sampler ops declare no lists, and a list on this op alone
|
||||
* would narrow the candidate planes' lifetime to it and refuse the first sample_topk. */
|
||||
}
|
||||
/* The temperature kernel again, over the candidate plane: `n_vocab` is only a row length to
|
||||
* it, so the candidate width works. */
|
||||
{
|
||||
@@ -308,6 +338,8 @@ int Sampler::declare(RadBuilder* b, const SamplerConfig& cfg) {
|
||||
|
||||
int Sampler::stage_alloc() {
|
||||
const int64_t rows = rows_for(cfg_);
|
||||
/* At most one entry per request; reserved here so a coupled step never allocates. */
|
||||
couple_build_.seqs.reserve((size_t)cfg_.max_seqs);
|
||||
|
||||
/* Pinned: uploaded every step, and a pageable source turns the async copy into a staged one
|
||||
* with a host bounce (spec §8). */
|
||||
@@ -320,7 +352,14 @@ int Sampler::stage_alloc() {
|
||||
greedy_ready_ = false;
|
||||
hist_stage_ = (int32_t*)rad_dev_alloc(rows * cfg_.max_hist * 4, RAD_MEM_HOST_PINNED);
|
||||
brk_stage_ = (uint8_t*)rad_dev_alloc(rows * cfg_.max_hist, RAD_MEM_HOST_PINNED);
|
||||
ngram_stage_ = (int32_t*)rad_dev_alloc(rows * 2 * 4, RAD_MEM_HOST_PINNED);
|
||||
ngram_wl_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
|
||||
mask_stage_ = (uint32_t*)rad_dev_alloc(rows * mask_words_ * 4, RAD_MEM_HOST_PINNED);
|
||||
/* The coupled rows, pinned: uploaded every coupled step, and a pageable source would turn the
|
||||
* async copy into a staged one with a host bounce (spec §8). */
|
||||
if (couple_)
|
||||
couple_stage_ = (RadMtpCoupleState*)rad_dev_alloc(
|
||||
rows * (int64_t)sizeof(RadMtpCoupleState), RAD_MEM_HOST_PINNED);
|
||||
|
||||
/* Logprobs readback; only rank 0 reads it. */
|
||||
if (cfg_.rank == 0) {
|
||||
@@ -337,10 +376,10 @@ int Sampler::stage_alloc() {
|
||||
}
|
||||
|
||||
if (!params_stage_ || !greedy_stage_ || !late_stage_ || !hist_stage_ || !brk_stage_ ||
|
||||
!mask_stage_) {
|
||||
!ngram_stage_ || !ngram_wl_stage_ || !mask_stage_ || (couple_ && !couple_stage_)) {
|
||||
RAD_ERR("sampler: could not pin %s of staging",
|
||||
humanb(rows * (3 * (int64_t)sizeof(DeviceSampleParams) + cfg_.max_hist * 5 +
|
||||
mask_words_ * 4)).c_str());
|
||||
mask_words_ * 8 + 8)).c_str());
|
||||
stage_free();
|
||||
return RAD_E_NOMEM;
|
||||
}
|
||||
@@ -353,7 +392,11 @@ void Sampler::stage_free() {
|
||||
if (late_stage_) rad_dev_free(late_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (hist_stage_) rad_dev_free(hist_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (brk_stage_) rad_dev_free(brk_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (ngram_stage_) rad_dev_free(ngram_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (ngram_wl_stage_) rad_dev_free(ngram_wl_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (mask_stage_) rad_dev_free(mask_stage_, RAD_MEM_HOST_PINNED);
|
||||
if (couple_stage_) rad_dev_free(couple_stage_, RAD_MEM_HOST_PINNED);
|
||||
couple_stage_ = nullptr;
|
||||
if (lp_host_) rad_dev_free(lp_host_, RAD_MEM_HOST_PINNED);
|
||||
if (lp_ci_host_) rad_dev_free(lp_ci_host_, RAD_MEM_HOST_PINNED);
|
||||
if (lp_cv_host_) rad_dev_free(lp_cv_host_, RAD_MEM_HOST_PINNED);
|
||||
@@ -366,6 +409,8 @@ void Sampler::stage_free() {
|
||||
cur_stage_ = nullptr;
|
||||
hist_stage_ = nullptr;
|
||||
brk_stage_ = nullptr;
|
||||
ngram_stage_ = nullptr;
|
||||
ngram_wl_stage_ = nullptr;
|
||||
mask_stage_ = nullptr;
|
||||
}
|
||||
|
||||
@@ -373,9 +418,9 @@ Sampler::~Sampler() { stage_free(); }
|
||||
|
||||
/* ================================================================== admission */
|
||||
|
||||
/* Whether the two history stages run, shared by admission, request setup and step staging so
|
||||
* they agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY
|
||||
* also requires a positive multiplier; a negative one would reward repetition. */
|
||||
/* Whether the history stages run, shared by admission, request setup and step staging so they
|
||||
* agree. As in llama.cpp, a window of 0 turns a stage off and DRY needs a base >= 1. DRY also
|
||||
* requires a positive multiplier; a negative one would reward repetition. */
|
||||
static bool penalties_on(const SamplingParams& sp) {
|
||||
return sp.penalty_last_n != 0 &&
|
||||
(sp.rep_penalty != 1.0f || sp.freq_penalty != 0.0f || sp.pres_penalty != 0.0f);
|
||||
@@ -385,6 +430,14 @@ static bool dry_on(const SamplingParams& sp) {
|
||||
return sp.dry_multiplier > 0.0f && sp.dry_base >= 1.0f && sp.dry_penalty_last_n != 0;
|
||||
}
|
||||
|
||||
/* The windowed no-repeat-ngram ban: n-gram length 0 is off (the request default). A window <= 0
|
||||
* is legal and means the whole staged history, the un-windowed processor; it is not a separate
|
||||
* switch, because the reference's windowed form is what the model ships and a ban with no window
|
||||
* is still a ban. */
|
||||
static bool ngram_ban_on(const SamplingParams& sp) {
|
||||
return sp.ngram_ban_n > 0;
|
||||
}
|
||||
|
||||
int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
auto refuse = [&](const char* what, int st) {
|
||||
if (why) *why = what;
|
||||
@@ -418,6 +471,12 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
/* The DRY kernels read an allowed length below 1 as 2; refused rather than rewritten. */
|
||||
if (dry_on(sp) && sp.dry_allowed_length < 1)
|
||||
return refuse("dry_allowed_length must be >= 1", RAD_E_INVAL);
|
||||
/* The n-gram ban: an n-gram shorter than 2 is a single-token ban, which the reference defines
|
||||
* (an empty prefix) and this chain implements, so 1 is accepted. A negative n or window has no
|
||||
* meaning; window 0 is the whole staged history. */
|
||||
if (sp.ngram_ban_n < 0) return refuse("ngram_ban_n is negative", RAD_E_INVAL);
|
||||
if (sp.ngram_window < 0)
|
||||
return refuse("ngram_window is negative (0 searches the whole history)", RAD_E_INVAL);
|
||||
if (sp.n_probs > RAD_MAX_LOGPROBS) {
|
||||
if (why) *why = "at most " + std::to_string(RAD_MAX_LOGPROBS) +
|
||||
" logprobs alternatives may be asked for";
|
||||
@@ -457,6 +516,7 @@ int Sampler::check_request(const SamplingParams& sp, std::string* why) const {
|
||||
if (!missing) missing = need(!sp.greedy() && sp.temp_last, op_temp_late_,
|
||||
"sample_temp (over the candidates, for temperature last)");
|
||||
if (!missing) missing = need(dry_on(sp), op_dry_, "sample_dry");
|
||||
if (!missing) missing = need(ngram_ban_on(sp), op_ngram_ban_, "sample_ngram_ban");
|
||||
if (!missing) missing = need(!sp.grammar.empty() || sp.thinking_budget >= 0, op_mask_,
|
||||
"sample_mask");
|
||||
if (!missing) missing = need(penalties_on(sp), op_penalties_, "sample_penalties");
|
||||
@@ -573,7 +633,21 @@ bool Sampler::speculation_fixed(uint64_t req_id) const {
|
||||
|
||||
/* ================================================================== the step path */
|
||||
|
||||
int Sampler::build_step(const std::vector<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();
|
||||
@@ -581,8 +655,15 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
n_seq_ = 0;
|
||||
any_brk_ = false;
|
||||
any_late_ = false;
|
||||
any_ngram_ = false;
|
||||
any_ngram_wl_ = false;
|
||||
any_couple_ = false;
|
||||
cur_stage_ = params_stage_;
|
||||
lp_rows_.clear();
|
||||
/* The evidence snapshot this build owns; build_greedy never touches it. */
|
||||
couple_build_.step = step;
|
||||
couple_build_.rows = 0;
|
||||
couple_build_.seqs.clear();
|
||||
|
||||
/* DRY's host half for one row whose history `h[0, take)` is staged. Over the window the
|
||||
* kernel uses (the tail of the row, `dry_penalty_last_n` long when positive) it computes the
|
||||
@@ -635,6 +716,7 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
const int64_t n_total = n_prompt + n_out;
|
||||
const bool pen = penalties_on(sp);
|
||||
const bool dry = dry_on(sp);
|
||||
const bool ngram = ngram_ban_on(sp);
|
||||
|
||||
auto it = seqs_.find(r->id);
|
||||
SeqState* st = it == seqs_.end() ? nullptr : &it->second;
|
||||
@@ -669,6 +751,30 @@ int Sampler::build_step(const std::vector<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);
|
||||
@@ -695,6 +801,26 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
p.dry_penalty_last_n = sp.dry_penalty_last_n;
|
||||
p.mask_row = -1;
|
||||
|
||||
/* The n-gram ban's pair, staged for every row so a row that turns it off cannot inherit
|
||||
* its predecessor's values. */
|
||||
ngram_stage_[2 * row] = (int32_t)sp.ngram_ban_n;
|
||||
ngram_stage_[2 * row + 1] = (int32_t)sp.ngram_window;
|
||||
|
||||
/* The ban's whitelist, cut to this rank's shard like the grammar mask (shard_mask):
|
||||
* global ids outside it exempt nothing here. Every row that runs the ban gets its
|
||||
* words freshly written -- the plane is uploaded whole with the ban, so a row must
|
||||
* never read another request's stale exemptions. */
|
||||
if (ngram) {
|
||||
uint32_t* w = ngram_wl_stage_ + row * mask_words_;
|
||||
std::memset(w, 0, (size_t)mask_words_ * 4);
|
||||
for (int32_t id : sp.ngram_whitelist) {
|
||||
const int64_t at = (int64_t)id - cfg_.vocab_off;
|
||||
if (at < 0 || at >= cfg_.n_vocab_local) continue;
|
||||
w[at >> 5] |= 1u << (uint32_t)(at & 31);
|
||||
any_ngram_wl_ = true;
|
||||
}
|
||||
}
|
||||
|
||||
/* Greedy over a split vocabulary is a top-1 chain row, not an argmax: sample_argmax
|
||||
* writes a column of this rank's shard, not a token id. Top-k plus the merge produce
|
||||
* global ids, and the pick over one candidate is deterministic. A greedy row asking
|
||||
@@ -723,12 +849,14 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
any_late_ = true;
|
||||
}
|
||||
|
||||
/* History for the penalties and DRY, staged only for rows that run one of them:
|
||||
* prompt, output so far and, at draft position k, the k drafts before it (they are
|
||||
* emitted only if accepted, as one token at a time). Oldest first, truncated to
|
||||
/* History for the penalties, DRY and the n-gram ban, staged only for rows that run one
|
||||
* of them: prompt, output so far and, at draft position k, the k drafts before it (they
|
||||
* are emitted only if accepted, as one token at a time). Oldest first, truncated to
|
||||
* max_hist; penalty_last_n still decides how much counts. Each row owns its row of the
|
||||
* plane, so hist_off stays 0. */
|
||||
if (pen || dry) {
|
||||
* plane, so hist_off stays 0. The n-gram ban's own window is `ngram_window`, applied to
|
||||
* this span, so the reference's update order holds at a verify: position k sees the
|
||||
* drafts before it, as the processor would after emitting them. */
|
||||
if (pen || dry || ngram) {
|
||||
const int64_t len = n_total + k;
|
||||
const int64_t take = std::min<int64_t>(len, cfg_.max_hist);
|
||||
int32_t* h = hist_stage_ + row * cfg_.max_hist;
|
||||
@@ -741,6 +869,9 @@ int Sampler::build_step(const std::vector<Request*>& reqs) {
|
||||
p.hist_len = (int32_t)take;
|
||||
if (pen) p.flags |= RAD_SP_PENALTY;
|
||||
if (dry && stage_dry(p, h, take, brk, row)) p.flags |= RAD_SP_DRY;
|
||||
/* A row whose history is shorter than its n-gram has nothing to ban (the reference
|
||||
* skips it too), so the op is issued only when some row has a full n-gram. */
|
||||
if (ngram && take >= sp.ngram_ban_n) any_ngram_ = true;
|
||||
}
|
||||
|
||||
if (gr && !dead && gr->constrains()) {
|
||||
@@ -881,7 +1012,17 @@ int Sampler::build_greedy(int64_t n) {
|
||||
n_seq_ = n;
|
||||
any_brk_ = false;
|
||||
any_late_ = false;
|
||||
any_ngram_ = false;
|
||||
any_ngram_wl_ = false;
|
||||
any_couple_ = false;
|
||||
cur_stage_ = greedy_stage_;
|
||||
/* A drafter's rows run the argmax only, so the n-gram plane is cleared: `run` reads it from
|
||||
* the staging, and a stale pair from an earlier request's build must not issue the ban over
|
||||
* history that was not staged this step. The exemption plane needs no clear: `run` uploads
|
||||
* it only beside an issued ban, every row that runs the ban has its words rewritten in full
|
||||
* by the build that staged the pair (build_step), and rows below a zeroed pair are skipped
|
||||
* by the op before they read a word. */
|
||||
std::memset(ngram_stage_, 0, (size_t)cap * 2 * sizeof(int32_t));
|
||||
if (greedy_ready_) return RAD_OK;
|
||||
for (int64_t i = 0; i < cap; ++i) {
|
||||
DeviceSampleParams& p = greedy_stage_[i];
|
||||
@@ -904,7 +1045,7 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
const RadStream s = rad_stream(c);
|
||||
|
||||
bool any_mask = false, any_greedy = false, any_chain = false;
|
||||
bool any_penalty = false, any_dry = false, any_xtc = false;
|
||||
bool any_penalty = false, any_dry = false, any_xtc = false, any_ngram = false;
|
||||
bool any_topp = false, any_minp = false, any_typ = false, any_temp = false;
|
||||
for (int64_t i = 0; i < n_seq_; ++i) {
|
||||
const DeviceSampleParams& p = cur_stage_[i];
|
||||
@@ -912,6 +1053,11 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
any_penalty |= (p.flags & RAD_SP_PENALTY) != 0;
|
||||
any_dry |= (p.flags & RAD_SP_DRY) != 0;
|
||||
any_xtc |= (p.flags & RAD_SP_XTC) != 0;
|
||||
/* The pair plane is read directly, not through cur_stage_: it is per-step staging the
|
||||
* LAST builder filled (build_step writes a row's pair, build_greedy zeroes every pair),
|
||||
* so it agrees with cur_stage_ by builder contract. A new builder must keep that
|
||||
* contract: stage the pair with the params, zero it with the greedy ones. */
|
||||
any_ngram |= ngram_stage_[2 * i] > 0;
|
||||
if (p.flags & RAD_SP_GREEDY) any_greedy = true;
|
||||
else {
|
||||
any_chain = true;
|
||||
@@ -941,21 +1087,34 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
if (late)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_params_late_), late_stage_,
|
||||
n_seq_ * (int64_t)sizeof(DeviceSampleParams), s));
|
||||
if (any_penalty || any_dry)
|
||||
if (any_penalty || any_dry || any_ngram)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_hist_), hist_stage_,
|
||||
n_seq_ * cfg_.max_hist * 4, s));
|
||||
const bool pass_brk = any_dry && any_brk_;
|
||||
if (pass_brk)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_brk_), brk_stage_,
|
||||
n_seq_ * cfg_.max_hist, s));
|
||||
/* The ban's whitelist rides with the ban, and only a row that runs the ban reads it. */
|
||||
const bool pass_wl = any_ngram && any_ngram_wl_;
|
||||
if (any_ngram)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_ngram_), ngram_stage_,
|
||||
n_seq_ * 2 * (int64_t)sizeof(int32_t), s));
|
||||
if (pass_wl)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_ngram_wl_), ngram_wl_stage_,
|
||||
n_seq_ * mask_words_ * 4, s));
|
||||
if (any_mask)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_mask_), mask_stage_,
|
||||
n_seq_ * mask_words_ * 4, s));
|
||||
if (any_couple_)
|
||||
RAD_TRY(rad_memcpy_async(rad_buf_ptr(c, buf_couple_), couple_stage_,
|
||||
n_seq_ * (int64_t)sizeof(RadMtpCoupleState), s));
|
||||
|
||||
const RadOperand o_logits = opd_rows(logits, n_seq_);
|
||||
const RadOperand o_params = opd_rows(buf_params_, n_seq_);
|
||||
const RadOperand o_hist = opd_rows(buf_hist_, n_seq_);
|
||||
const RadOperand o_brk = opd_rows(buf_brk_, n_seq_);
|
||||
const RadOperand o_ngram = opd_rows(buf_ngram_, n_seq_);
|
||||
const RadOperand o_ngram_wl = opd_rows(buf_ngram_wl_, n_seq_);
|
||||
const RadOperand o_mask = opd_rows(buf_mask_, n_seq_);
|
||||
const RadOperand o_ci = opd_rows(buf_cand_i_, n_seq_);
|
||||
const RadOperand o_cv = opd_rows(buf_cand_v_, n_seq_);
|
||||
@@ -983,6 +1142,17 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
if (any_dry)
|
||||
RAD_TRY(issue(op_dry_, { o_logits, o_params, o_hist, pass_brk ? o_brk : opd_none() }));
|
||||
|
||||
/* The windowed no-repeat-ngram ban (Unlimited-OCR's SlidingWindowNoRepeatNgramProcessor),
|
||||
* after the penalties and before every cut: a banned logit is -infinity for the greedy argmax
|
||||
* below as well as for the chain, which is the reference processor's effect on the
|
||||
* distribution. Off (the default) the op is not issued at all, so a request without it
|
||||
* samples exactly as before. */
|
||||
/* The whitelist operand is passed only when some staged row carries exemptions; absent
|
||||
* means nothing is exempt, the reference's empty whitelist and the bit-identical default. */
|
||||
if (any_ngram)
|
||||
RAD_TRY(issue(op_ngram_ban_, { o_logits, o_params, o_hist, o_ngram,
|
||||
pass_wl ? o_ngram_wl : opd_none() }));
|
||||
|
||||
/* Greedy rows take the argmax after penalties and the mask. In a mixed batch both the argmax
|
||||
* and the chain run over the whole batch: the argmax writes every row, then the candidate
|
||||
* stages skip RAD_SP_GREEDY rows so the pick overwrites only chain rows. One extra logits
|
||||
@@ -1027,6 +1197,12 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
RAD_TRY(issue(op_temp_late_, { o_cv, opd_rows(buf_params_late_, n_seq_) }));
|
||||
|
||||
RAD_TRY(issue(op_pick_, { o_ci, o_cv, o_params, o_tok }));
|
||||
/* After the pick, over the same plane: a coupled row replaces the pick's token and an unbound
|
||||
* row keeps it. The issued step is recorded for the evidence line. */
|
||||
if (any_couple_) {
|
||||
RAD_TRY(issue(op_couple_, { o_ci, o_cv, o_params, opd_rows(buf_couple_, n_seq_), o_tok }));
|
||||
couple_issued_step_ = couple_build_.step;
|
||||
}
|
||||
|
||||
/* Copy the logprobs rows to the host behind the pick, on rank 0 only (collect_step asks
|
||||
* it): the summary and the candidate planes, which logprobs_for reads when the summary lacks
|
||||
|
||||
+67
-3
@@ -9,6 +9,7 @@
|
||||
* Chain order (reordering changes which tokens survive):
|
||||
*
|
||||
* penalties (repetition / frequency / presence, then DRY)
|
||||
* the windowed no-repeat-ngram ban
|
||||
* temperature
|
||||
* the grammar mask
|
||||
* top-k
|
||||
@@ -47,6 +48,9 @@
|
||||
* sample_penalties M(range) n_vocab vocab_off? logits, params, history -> logits (inout)
|
||||
* sample_dry M(range) n_vocab vocab_off? logits, params, history, breakers?
|
||||
* -> logits (inout)
|
||||
* sample_ngram_ban M(range) n_vocab vocab_off? logits, params, history, ngram,
|
||||
* whitelist?
|
||||
* -> logits (inout)
|
||||
* sample_temp M(range) n_vocab logits, params -> logits (inout)
|
||||
* sample_mask M(range) n_vocab logits, params, bitmask -> logits (inout)
|
||||
* sample_topk M(range) n_vocab vocab_off? logits, params -> cand_idx, cand_val,
|
||||
@@ -64,13 +68,16 @@
|
||||
* a verify. `params` is [M] DeviceSampleParams rows. `history` is [M, max_hist] int32 global
|
||||
* token ids, row m addressed by its hist_off/hist_len. `breakers` is [M, max_hist] uint8 beside
|
||||
* it, nonzero where that token is a whole DRY sequence breaker. `bitmask` is [M, mask_words]
|
||||
* uint32, addressed by the row's mask_row. `vocab_off` is this rank's first vocabulary row,
|
||||
* uint32, addressed by the row's mask_row. The ban's `whitelist` is a [M, mask_words] uint32
|
||||
* bitmask (a SET bit exempts that column from the ban) addressed by the row itself, absent when
|
||||
* no staged row carries one. `vocab_off` is this rank's first vocabulary row,
|
||||
* declared only when the vocabulary is split; the three ops that map between token ids and this
|
||||
* rank's logit columns use it. Every op has a libref implementation, which is both its fallback
|
||||
* and its oracle (spec §17).
|
||||
*/
|
||||
#pragma once
|
||||
#include "rad_sample.h"
|
||||
#include "rad_spechub.h"
|
||||
|
||||
#include "../rad_core.h"
|
||||
#include "grammar.h"
|
||||
@@ -80,6 +87,7 @@
|
||||
#include <memory>
|
||||
#include <string>
|
||||
#include <unordered_map>
|
||||
#include <utility>
|
||||
#include <vector>
|
||||
|
||||
namespace rad {
|
||||
@@ -109,6 +117,10 @@ struct SamplerConfig {
|
||||
* from this many of the most likely tokens, not the whole vocabulary. A request asking for a
|
||||
* larger top-k is refused at admission, not silently narrowed. */
|
||||
int64_t max_candidates = kSampleCandidates;
|
||||
|
||||
/* --draft-coupling: declare the coupled verify (`mtp_couple_verify`) behind the pick and the
|
||||
* per-row state plane it reads. */
|
||||
bool draft_coupling = false;
|
||||
};
|
||||
|
||||
/* ================================================================== the driver */
|
||||
@@ -160,13 +172,18 @@ public:
|
||||
/* Whether allows_speculation's answer can no longer change. It changes only when a grammar
|
||||
* whose backend cannot rewind starts to constrain (on a commit). */
|
||||
bool speculation_fixed(uint64_t req_id) const;
|
||||
/* --draft-coupling: bind the per-round states of the linear draft just published, `n` of
|
||||
* them (0 clears). Each must name this request, the round it belongs to, and a `draw.mode` the
|
||||
* row actually ran. RAD_E_NOTFOUND for a request already ended here. */
|
||||
int set_mtp_couple(uint64_t req_id, const RadMtpCoupleState* states, int n);
|
||||
|
||||
/* ---------------------------------------------------------- step path */
|
||||
|
||||
/* Stage this step's parameter rows, penalty history and grammar bitmasks into pinned memory.
|
||||
* Scheduler thread, before the rank threads are released at the barrier. Allocates nothing;
|
||||
* every buffer was sized at declare against max_seqs (spec §3.1). */
|
||||
int build_step(const std::vector<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
|
||||
@@ -200,6 +217,26 @@ public:
|
||||
* meaningful only where the row carries RAD_SP_MASK. */
|
||||
const uint32_t* staged_mask(int64_t row) const { return mask_stage_ + row * mask_words_; }
|
||||
int64_t mask_words() const { return mask_words_; }
|
||||
/* Staged row `row`'s bound coupled state, as `run` uploads it: all-zero where the row carries
|
||||
* none (bonus row, greedy row, uncoupled step). Lets a build be checked without a device. */
|
||||
const RadMtpCoupleState& staged_couple(int64_t row) const { return couple_stage_[row]; }
|
||||
/* Whether any row of the last build carries a bound state, i.e. whether `run` issues the
|
||||
* verify op at all. Cleared by build_greedy: a gate for run(), not for evidence. */
|
||||
bool staged_any_couple() const { return any_couple_; }
|
||||
/* The verify op the last build resolved, for naming its kernel in a log line. */
|
||||
rad_op staged_couple_op() const { return op_couple_; }
|
||||
|
||||
/* What build_step staged for the coupled verify. build_greedy, which runs between that build
|
||||
* and the step's wait, clears any_couple_ but leaves this snapshot. */
|
||||
struct CoupleBuild {
|
||||
int64_t step = -1; /* the engine step this build staged */
|
||||
int64_t rows = 0; /* bound rows */
|
||||
/* The distinct sequences among them, with their bound rows. */
|
||||
std::vector<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
|
||||
@@ -218,6 +255,11 @@ private:
|
||||
* newly committed tokens only. Read only when the request carries a thinking budget. */
|
||||
ReasoningCount think;
|
||||
size_t think_seen = 0;
|
||||
/* --draft-coupling: the linear draft's per-round states for the window the scheduler
|
||||
* published, bound by set_mtp_couple and consumed by build_step. `couple_n` is how many of
|
||||
* `couple` are live; 0 for a request whose drafts carry no coupled proposal. */
|
||||
RadMtpCoupleState couple[RAD_MTP_COUPLE_MAX_ROUNDS]{};
|
||||
int couple_n = 0;
|
||||
};
|
||||
|
||||
/* Mask staged row `row` to the reasoning block's close token, once the budget is spent
|
||||
@@ -232,6 +274,9 @@ private:
|
||||
/* Declared op handles; RAD_NULL_HANDLE means unresolved, which admission refuses by name. */
|
||||
rad_op op_penalties_ = RAD_NULL_HANDLE;
|
||||
rad_op op_dry_ = RAD_NULL_HANDLE;
|
||||
/* The windowed no-repeat-ngram ban (`sample_ngram_ban`), the stage Unlimited-OCR's
|
||||
* generation_config asks for. It reads the same history plane as the two above. */
|
||||
rad_op op_ngram_ban_ = RAD_NULL_HANDLE;
|
||||
rad_op op_temp_ = RAD_NULL_HANDLE;
|
||||
rad_op op_temp_late_ = RAD_NULL_HANDLE; /* sample_temp over the candidates (temp_last) */
|
||||
rad_op op_mask_ = RAD_NULL_HANDLE;
|
||||
@@ -244,6 +289,7 @@ private:
|
||||
rad_op op_argmax_ = RAD_NULL_HANDLE;
|
||||
rad_op op_allgather_ = RAD_NULL_HANDLE;
|
||||
rad_op op_merge_ = RAD_NULL_HANDLE; /* the candidate merge, under tensor parallel */
|
||||
rad_op op_couple_ = RAD_NULL_HANDLE; /* --draft-coupling only */
|
||||
rad_op op_logprobs_ = RAD_NULL_HANDLE; /* summary of the raw distribution */
|
||||
rad_op op_lp_gather_ = RAD_NULL_HANDLE; /* every rank's summary, under a split vocabulary */
|
||||
|
||||
@@ -252,6 +298,10 @@ private:
|
||||
rad_buf buf_params_late_ = RAD_NULL_HANDLE; /* the late temperature's rows */
|
||||
rad_buf buf_hist_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_brk_ = RAD_NULL_HANDLE; /* DRY's single-token breaker marks, beside history */
|
||||
rad_buf buf_ngram_ = RAD_NULL_HANDLE; /* the n-gram ban's {n, window} pair a row */
|
||||
/* The ban's whitelist bitmask, [rows, mask_words] like the grammar mask plane: a SET bit
|
||||
* exempts that column from the ban. Uploaded with the ban, only when a staged row has one. */
|
||||
rad_buf buf_ngram_wl_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_mask_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_cand_i_ = RAD_NULL_HANDLE;
|
||||
rad_buf buf_cand_v_ = RAD_NULL_HANDLE;
|
||||
@@ -259,6 +309,12 @@ private:
|
||||
rad_buf buf_pairs_ = RAD_NULL_HANDLE; /* this rank's candidates as (global id, logit) */
|
||||
rad_buf buf_lp_ = RAD_NULL_HANDLE; /* sample_logprobs' stats, [rows, lp_width()] */
|
||||
rad_buf buf_lp_g_ = RAD_NULL_HANDLE; /* and every rank's side by side */
|
||||
rad_buf buf_couple_ = RAD_NULL_HANDLE; /* [rows, RAD_MTP_COUPLE_STATE_WORDS], flag only */
|
||||
RadMtpCoupleState* couple_stage_ = nullptr; /* pinned, one row per sampled position */
|
||||
bool couple_ = false; /* --draft-coupling */
|
||||
bool any_couple_ = false; /* does any row this step carry a bound state? */
|
||||
CoupleBuild couple_build_{}; /* what the last build_step staged, for the evidence line */
|
||||
int64_t couple_issued_step_ = -1; /* step whose verify op run() last issued */
|
||||
|
||||
/* Pinned staging, allocated once at declare. */
|
||||
DeviceSampleParams* params_stage_ = nullptr;
|
||||
@@ -275,6 +331,8 @@ private:
|
||||
const DeviceSampleParams* cur_stage_ = nullptr; /* what the last build staged */
|
||||
int32_t* hist_stage_ = nullptr;
|
||||
uint8_t* brk_stage_ = nullptr;
|
||||
int32_t* ngram_stage_ = nullptr; /* [rows][2]: n-gram length, window */
|
||||
uint32_t* ngram_wl_stage_ = nullptr; /* [rows][mask_words] exemption bitmask */
|
||||
uint32_t* mask_stage_ = nullptr;
|
||||
|
||||
int64_t mask_words_ = 0; /* words for this rank's shard; what the mask op indexes */
|
||||
@@ -282,6 +340,12 @@ private:
|
||||
/* Whether any DRY row this step has breakers; only then is the breaker plane uploaded and
|
||||
* passed to sample_dry. */
|
||||
bool any_brk_ = false;
|
||||
/* Whether any row this step runs the n-gram ban. Its history is the plane the penalties use,
|
||||
* so this only decides whether that plane is uploaded and the op issued. */
|
||||
bool any_ngram_ = false;
|
||||
/* Whether any banned row this step whitelists a column of this rank's shard; only then is
|
||||
* the exemption plane uploaded and passed to sample_ngram_ban. */
|
||||
bool any_ngram_wl_ = false;
|
||||
|
||||
/* The whole-vocabulary mask the grammar fills, from which this rank's shard is cut. Used
|
||||
* only when the head is sharded; see declare(). */
|
||||
|
||||
@@ -60,6 +60,16 @@ struct AdvGroup {
|
||||
int64_t used_off; /* [n_seq] seqused */
|
||||
int64_t bt_off; /* [n_seq][pitch] block table */
|
||||
int64_t first_off; /* [n_seq] the position each row's block table starts at */
|
||||
/* The runtime window (KVManager::set_window / SeqWindow), so the card computes the same
|
||||
* `used` and slots the host builder staged: a ring sequence keeps its reference and rewrites
|
||||
* a fixed ring of blocks, so its held span stops at its own table and a position past its
|
||||
* ring_pos maps modulo ring_blocks. Without it (ring 0) the advance is the linear mapping, as
|
||||
* before. ring_pos and the table length are per sequence (each prompt has its own floor and
|
||||
* table), ring_blocks is the same for the group (one W). */
|
||||
int32_t ring; /* 1: the group carries runtime windows */
|
||||
int32_t ring_blocks; /* whole blocks the ring holds */
|
||||
int64_t rpos_off; /* [n_seq] the sequence's block-aligned first ring position, 0 if none */
|
||||
int64_t tlen_off; /* [n_seq] the sequence's block-table length in blocks, 0 if none */
|
||||
};
|
||||
|
||||
/* One advance: a mode, the build it patches, and where its inputs are. Passed by value as the
|
||||
|
||||
@@ -30,21 +30,43 @@ RAD_ADV_FN bool adv_is_eog(const AdvanceArgs& a, int32_t t) {
|
||||
|
||||
/* Every group's slots for the row's `n` positions (from the positions just written) and its
|
||||
* length from `base`. A position past the block table gets slot -1 ("no slot"); the builder sizes
|
||||
* tables for the furthest reachable position, so only a row whose output is unused hits this. */
|
||||
* tables for the furthest reachable position, so only a row whose output is unused hits this.
|
||||
*
|
||||
* A runtime window (e.ring, KVManager::set_window) must be computed exactly as the host builder
|
||||
* staged it (BatchBuilder::build_groups), because this runs after the build and overwrites what it
|
||||
* wrote:
|
||||
* - `used` stops at the table: the ring reuses its blocks, so the sequence's held span is the
|
||||
* table's, not the context's. Without this the decode walks bt[(used-1)/block] past the end,
|
||||
* reads the -1 padding the builder fills and faults the card on a negative block;
|
||||
* - a position at or past ring_pos lives in the ring, at block
|
||||
* ring_pos/block + ((p - ring_pos)/block) % ring_blocks, not at (p - first)/block, which runs
|
||||
* off the table once the ring wraps. */
|
||||
RAD_ADV_FN void adv_groups(const AdvanceArgs& a, int i, int32_t k, int32_t base, int32_t n) {
|
||||
const AdvGroup* G = reinterpret_cast<const AdvGroup*>(a.slab + a.grp_off);
|
||||
const int32_t* pos = adv_i32(a, a.pos_off);
|
||||
for (int g = 0; g < a.n_groups; ++g) {
|
||||
const AdvGroup& e = G[g];
|
||||
const int32_t first = adv_i32(a, e.first_off)[i];
|
||||
adv_i32(a, e.used_off)[i] = base + n - first;
|
||||
/* Per sequence: each prompt has its own floor and its own table (advance.h). */
|
||||
const int32_t rpos = e.ring ? adv_i32(a, e.rpos_off)[i] : 0;
|
||||
const int32_t tlen = e.ring ? adv_i32(a, e.tlen_off)[i] : 0;
|
||||
const bool ring = e.ring && tlen > 0;
|
||||
int64_t used = (int64_t)base + n - first;
|
||||
if (ring) {
|
||||
const int64_t span = (int64_t)tlen * e.block_size;
|
||||
if (used > span) used = span;
|
||||
}
|
||||
adv_i32(a, e.used_off)[i] = (int32_t)used;
|
||||
if (!e.paged) continue;
|
||||
const int32_t* bt = adv_i32(a, e.bt_off) + (int64_t)i * e.pitch;
|
||||
int32_t* slot = adv_i32(a, e.slot_off);
|
||||
for (int32_t j = 0; j < n; ++j) {
|
||||
const int32_t p = pos[k + j];
|
||||
const int32_t bi = (p - first) / e.block_size;
|
||||
slot[k + j] = (p >= first && bi < e.pitch && bt[bi] >= 0)
|
||||
int32_t bi = (p - first) / e.block_size;
|
||||
if (ring && p >= rpos && e.ring_blocks > 0)
|
||||
bi = rpos / e.block_size +
|
||||
((p - rpos) / e.block_size) % e.ring_blocks;
|
||||
slot[k + j] = (p >= first && bi >= 0 && bi < e.pitch && bt[bi] >= 0)
|
||||
? bt[bi] * e.block_size + p % e.block_size : -1;
|
||||
}
|
||||
}
|
||||
|
||||
+61
-3
@@ -6,6 +6,7 @@
|
||||
#include "device/device.h"
|
||||
|
||||
#include <algorithm>
|
||||
#include <cassert>
|
||||
#include <cstring>
|
||||
#include <cstdlib>
|
||||
|
||||
@@ -112,6 +113,9 @@ void BatchBuilder::carve(Set& s, char* h) {
|
||||
pair(&s.h_dout, &s.d_dout, S);
|
||||
pair(&s.h_rows, &s.d_rows, 4 * S);
|
||||
pair(&s.h_first, &s.d_first, S * (int64_t)s.groups.size());
|
||||
/* The advance's per-sequence runtime-window data (advance.h); 0 when there is none. */
|
||||
pair(&s.h_rpos, &s.d_rpos, S);
|
||||
pair(&s.h_tlen, &s.d_tlen, S);
|
||||
s.h_grp = ::rad::carve<AdvGroup>(h, oh, (int64_t)s.groups.size());
|
||||
s.d_grp = ::rad::carve<AdvGroup>(d, od, (int64_t)s.groups.size());
|
||||
for (size_t gi = 0; gi < s.groups.size(); ++gi) {
|
||||
@@ -686,17 +690,37 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
}
|
||||
|
||||
int64_t t = 0;
|
||||
/* The group's ring block count, read off the first armed sequence: declare_runtime_window
|
||||
* fixes one W per group, so every armed sequence computes the same count. Collected here,
|
||||
* with the table walk that already opens each window, so the group header below needs no
|
||||
* second pass over the plan. */
|
||||
int32_t ring_blocks = 0;
|
||||
for (int64_t i = 0; i < n_seq; ++i) {
|
||||
const StepEntry& e = plan.e[(size_t)i];
|
||||
|
||||
int64_t first = 0;
|
||||
SeqWindow win;
|
||||
bool has_win = false;
|
||||
int64_t bt_len = 0; /* the sequence's block table, in blocks */
|
||||
int64_t table_end = 0; /* the table's last position, for a runtime window's used */
|
||||
if (L.paged) {
|
||||
/* The manager's block table, by sequence id; Request::blocks is not the source
|
||||
* of truth (see IKVManager). */
|
||||
const std::vector<int32_t>& bt = kv.block_table(e.seq, (int32_t)gi);
|
||||
first = kv.first_block_pos(e.seq, (int32_t)gi);
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j)
|
||||
g.h_slot[t + j] = kvgeom_.slot((int)gi, bt, first, (int64_t)e.ctx_len + j);
|
||||
has_win = kv.runtime_window(e.seq, (int32_t)gi, &win);
|
||||
if (has_win) {
|
||||
assert(!ring_blocks || ring_blocks == (int32_t)win.ring_blocks);
|
||||
ring_blocks = (int32_t)win.ring_blocks;
|
||||
}
|
||||
bt_len = (int64_t)bt.size();
|
||||
table_end = bt_len * L.block_size;
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j) {
|
||||
const int64_t pos = (int64_t)e.ctx_len + j;
|
||||
g.h_slot[t + j] = has_win
|
||||
? kvgeom_.slot_ring((int)gi, bt, first, pos, win)
|
||||
: kvgeom_.slot((int)gi, bt, first, pos);
|
||||
}
|
||||
/* Restage relative to what the card holds (BtMirror). The same sequence in the
|
||||
* same row keeps entries below the first changed one and below the end of both
|
||||
* old and new tables, so a decode step stages nothing or one appended block. A
|
||||
@@ -737,6 +761,11 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
s.h_convslot[(int64_t)gi * max_seqs_ + i] = st;
|
||||
}
|
||||
s.h_first[(int64_t)gi * max_seqs_ + i] = (int32_t)first;
|
||||
/* The advance recomputes this row's used and slots after the build (advance_impl.h),
|
||||
* so it needs the same per-sequence ring data this build staged: the row's floor and
|
||||
* its table's length, 0 when the sequence has no runtime window. */
|
||||
s.h_rpos[i] = has_win ? (int32_t)win.ring_pos : 0;
|
||||
s.h_tlen[i] = has_win ? (int32_t)bt_len : 0;
|
||||
t += e.n_tokens;
|
||||
|
||||
/* Tokens the sequence holds in this table, not min(length, window). `seqused` counts
|
||||
@@ -745,8 +774,16 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
* unwritten slots at the end of the table, read as the newest context; a non-causal
|
||||
* window group would attend to them. Do not clamp to `window` either: the held span
|
||||
* may exceed it by under a block, and clamping would drop the newest tokens. Attending
|
||||
* a few extra old positions is the cost of paging a window (vLLM does the same). */
|
||||
* a few extra old positions is the cost of paging a window (vLLM does the same).
|
||||
*
|
||||
* A runtime window (R-SWA) has reused its ring's slots once the sequence is past the
|
||||
* ring's span, so the held span is the table's, not the context's: every slot of the
|
||||
* reference and of the ring holds live KV, and the ring's blocks are what a non-causal
|
||||
* decode reads. Before the ring is full the shorter of the two is the written count. */
|
||||
int64_t used = (int64_t)e.ctx_len + e.n_tokens - first;
|
||||
if (has_win) {
|
||||
used = std::min<int64_t>(used, table_end);
|
||||
}
|
||||
if (used < 0) used = 0;
|
||||
g.h_used[i] = (int32_t)used;
|
||||
if (L.paged) {
|
||||
@@ -773,6 +810,15 @@ int BatchBuilder::build_groups(const StepPlan& plan, const IKVManager& kv, Set&
|
||||
a.used_off = (const char*)g.d_used - d0;
|
||||
a.bt_off = (const char*)g.d_bt - d0;
|
||||
a.first_off = (const char*)(s.d_first + (int64_t)gi * max_seqs_) - d0;
|
||||
/* The runtime window (KVManager::set_window): the advance runs after this build and
|
||||
* overwrites `used` and the slots, so it must reproduce the ring's mapping rather
|
||||
* than the linear one (advance_impl.h). The floor and table length are per sequence
|
||||
* (s.h_rpos / s.h_tlen), the ring's block count is the group's W, collected with the
|
||||
* table walk above. */
|
||||
a.ring = ring_blocks ? 1 : 0;
|
||||
a.ring_blocks = ring_blocks;
|
||||
a.rpos_off = (const char*)s.d_rpos - d0;
|
||||
a.tlen_off = (const char*)s.d_tlen - d0;
|
||||
}
|
||||
|
||||
for (size_t r = 0; r < ranks_.size(); ++r) {
|
||||
@@ -872,6 +918,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
int32_t rope_mixed = 0;
|
||||
int64_t n_mm = 0;
|
||||
bool lora_rows = false;
|
||||
int32_t cvec_rows = 0;
|
||||
s.h_cu[0] = 0;
|
||||
for (int64_t i = 0; i < n_seq; ++i) {
|
||||
const StepEntry& e = plan.e[(size_t)i];
|
||||
@@ -905,6 +952,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
for (int32_t j = 0; j < e.n_tokens; ++j) s.h_lora[k + j] = ls;
|
||||
if (ls >= 0 && e.n_tokens > 0) lora_rows = true;
|
||||
}
|
||||
/* The same rows derive.cpp's projection_on_rows sets (RadBatch::control_vector). */
|
||||
if (e.req && e.req->sp.use_control_vector && e.n_tokens > 0) cvec_rows = 1;
|
||||
/* Rotary position of each row at its own position (draft-head rows rotate at the index
|
||||
* they write, not the token they embed). Three planes of n_tok. */
|
||||
if (mm_on_) {
|
||||
@@ -1113,6 +1162,7 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
/* Null on a step with no adapter row: the core then issues no adapter op, and the step
|
||||
* runs the same pass as an engine serving no adapters. */
|
||||
B.lora_slot = lora_rows ? on_rank(base, b0, s.d_lora) : nullptr;
|
||||
B.control_vector = cvec_rows;
|
||||
B.enc = 0;
|
||||
B.enc_n_patch = 0;
|
||||
B.enc_pixels = nullptr;
|
||||
@@ -1120,6 +1170,8 @@ const RadBatch* BatchBuilder::build(const StepPlan& plan, const IKVManager& kv,
|
||||
B.enc_n_seg = 0;
|
||||
B.enc_cu = nullptr;
|
||||
B.enc_max_seg = 0;
|
||||
B.enc_seg_h = nullptr;
|
||||
B.enc_seg_w = nullptr;
|
||||
B.n_checkpoints = n_ck;
|
||||
B.checkpoint_tok = n_ck ? on_rank(base, b0, s.d_cktok) : nullptr;
|
||||
B.checkpoint_slot = n_ck ? on_rank(base, b0, s.d_ckslot) : nullptr;
|
||||
@@ -1188,6 +1240,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
const int64_t max_segs = enc.max_patches / (enc.merge > 0 ? enc.merge : 1) + 1;
|
||||
int64_t n_patch = 0, n_seg = 0, max_seg = 0;
|
||||
enc_cu_host_[0] = 0;
|
||||
enc_seg_h_host_.clear();
|
||||
enc_seg_w_host_.clear();
|
||||
for (const EncoderPart& p : parts) {
|
||||
const mm::Item& it = *p.item;
|
||||
if (p.seg0 < 0 || p.n_seg <= 0 || p.seg0 + p.n_seg > it.n_seg) {
|
||||
@@ -1210,6 +1264,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
for (int32_t q = p.seg0; q < p.seg0 + p.n_seg; ++q) {
|
||||
const int64_t seg_p = it.patch_at(q + 1) - it.patch_at(q);
|
||||
enc_cu_host_[n_seg + 1] = enc_cu_host_[n_seg] + (int32_t)seg_p;
|
||||
enc_seg_h_host_.push_back(it.seg_h(q));
|
||||
enc_seg_w_host_.push_back(it.seg_w(q));
|
||||
++n_seg;
|
||||
if (seg_p > max_seg) max_seg = seg_p;
|
||||
}
|
||||
@@ -1256,6 +1312,8 @@ const RadBatch* BatchBuilder::build_encoder(const std::vector<EncoderPart>& part
|
||||
B.enc_n_seg = n_seg;
|
||||
B.enc_cu = static_cast<const int32_t*>(enc_cu_dev_[r]);
|
||||
B.enc_max_seg = (int32_t)max_seg;
|
||||
B.enc_seg_h = enc_seg_h_host_.data();
|
||||
B.enc_seg_w = enc_seg_w_host_.data();
|
||||
}
|
||||
out_last_ = out_next_;
|
||||
out_next_ = (out_next_ + 1) % kOut;
|
||||
|
||||
Loaded 100 of 285 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user