Archived
radiance 1.11.0
New models: - GLM-5.3-Flash reads pictures: its vision tower and processor (--image-tokens sets the budget), with decode kernels for a few rows and the DSA indexer split over the ranks - Sage-A1.5 (fp8 and MXFP4) with its vision tower and a DFlash2 drafter - Unlimited-OCR (bf16) - Gemma 4 31B with z-lab's DFlash and RedHatAI's DFlash2 drafters; at four cards its all-reduces are fused with the junctions, overlapped with the compute and sent compressed - Ornith-1.5-35B-A3B w4a8 compose files Speed: - Block drafters (DFlash, DFlash2) accept their drafts on the card, and the next step is issued ahead - The four-rank all-reduce is faster for every --tp 4 model - qwen35_w8a8: the norms and SiLU write the int8 linears' operands directly - --attn-prefill-fp8 off|qk|pv|both: fp8 QK and PV legs for the h256 prefill attention (about +20% prefill on a 221K-token prompt for the 27B MXFP4 at TP2); lossy, off by default Features: - Control vectors: --control-vector off|on|disabled (disabled by default), a per-request switch, and the published Qwen3.8-Flash-Next refusal-direction vector (its license is in NOTICE) - Krea 2: the `rebalance` request field, as ComfyUI's ConditioningKrea2Rebalance - Cards with a small PCI BAR run, with kernel arguments kept in host memory - Dashboard: live acceptance figures; statsdump rotates its file at a size cap - KV caches every rank holds whole (GLM-5.3's latent and index caches) take one host-tier slot Fixes: - Long conversations taking turns no longer fall back to an early snapshot: a host-tier restore makes room as memory pressure does and waits a step for the previous turn's release (two conversations of 142K and 147K tokens sent back to back: 31.3 s per turn before, 2.8 s now) - Kernels before Linux 6.16 (amdgpu below 3.64) no longer hang at startup: virtual memory management is turned off there, with a warning - Gemma 4 dense scales its token embeddings as Hugging Face does (bf16), which changes its output - The four-rank all-reduce fences prefill-sized messages, for a rare divergence after a fresh start - GLM-5.3: every refusal names the setting and the reason; its template keeps string content - Several pictures in one request no longer refuse processors that take one image at a time Changes: Plugin ABI 26: out-of-tree plugins must be rebuilt. The environment switches the PRs added are fixed rules or flags now (R4D_ATTN_FP8 is --attn-prefill-fp8).
This commit is contained in:
commit
9eaf10da6e
210 files changed
+14363
-2138
No files matched your search
+1
-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.11.0 LANGUAGES C CXX)
|
||||
|
||||
set(CMAKE_CXX_STANDARD 20)
|
||||
set(CMAKE_CXX_STANDARD_REQUIRED ON)
|
||||
|
||||
@@ -33,7 +33,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
|
||||
@@ -48,18 +51,28 @@ Written by Deadcode, with contributions from:
|
||||
R4D_AR_MAX_BLOCKS for two engines on one set of cards, and added tokens decoded as HuggingFace
|
||||
decodes them
|
||||
- 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, and the eight-rank two-shot in ring order
|
||||
- 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
|
||||
|
||||
This product includes software from the following projects, each under the MIT License. The
|
||||
license text is in the file named beside each.
|
||||
|
||||
@@ -45,6 +45,7 @@ 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` |
|
||||
| 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` |
|
||||
@@ -306,27 +307,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
|
||||
|
||||
| | |
|
||||
|
||||
+50
-10
@@ -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.
|
||||
*
|
||||
@@ -351,13 +369,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} */
|
||||
@@ -654,12 +679,11 @@ 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);
|
||||
|
||||
/* ================================================================== the encoder */
|
||||
@@ -692,6 +716,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 +896,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
|
||||
@@ -1300,12 +1335,17 @@ 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;
|
||||
} RadArchProbe;
|
||||
|
||||
int rad_arch_probe(const RadModelMeta* meta, RadArchProbe* out);
|
||||
|
||||
+17
-2
@@ -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. */
|
||||
|
||||
+26
-23
@@ -596,22 +596,17 @@ 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; }
|
||||
inline void prefetch_beside(RadCtx* c, rad_op op, rad_weight w, int64_t T) {
|
||||
if (!op || T > kPrefetchRows) return;
|
||||
@@ -622,15 +617,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 +676,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 +949,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 +1156,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),
|
||||
|
||||
@@ -293,7 +293,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),
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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)) {
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
@@ -1052,8 +1052,9 @@ inline int LinearFP8::declare(RadBuilder* b, Names& nm, const Geom& g, const cha
|
||||
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
|
||||
|
||||
@@ -115,18 +115,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 +163,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 +178,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);
|
||||
@@ -519,7 +516,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 +584,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);
|
||||
|
||||
@@ -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
|
||||
@@ -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>
|
||||
@@ -869,43 +869,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 +922,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 +940,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),
|
||||
@@ -1959,9 +1938,9 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
|
||||
|
||||
/* 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",
|
||||
@@ -2019,8 +1998,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 +2024,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 +2057,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();
|
||||
@@ -2220,8 +2196,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");
|
||||
}
|
||||
@@ -2521,7 +2496,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
|
||||
|
||||
@@ -386,12 +386,43 @@ 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;
|
||||
|
||||
+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 "
|
||||
|
||||
@@ -717,6 +717,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. */
|
||||
{
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -1555,7 +1555,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 +1600,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 +1677,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
|
||||
@@ -254,7 +254,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 */
|
||||
@@ -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);
|
||||
@@ -923,7 +924,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 +943,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 +1208,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 */
|
||||
@@ -2108,7 +2117,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 +2131,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;
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -75,6 +75,9 @@ static const Flag g_flags[] = {
|
||||
{ "--kv-cache-dtype", "T", "bf16 | fp8 | fp8_v4 | k6_v4 -- fp8 halves what a token of\n"
|
||||
"context costs; fp8_v4 keeps V in 4 bits (0.78 of fp8), k6_v4\n"
|
||||
"also K in 6 (0.69); both Qwen3.8-27B and -Flash-Next" },
|
||||
{ "--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)" },
|
||||
@@ -489,6 +492,17 @@ int config_parse(int argc, char** argv, Config* c) {
|
||||
}
|
||||
c->kv_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");
|
||||
@@ -971,6 +985,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 {
|
||||
|
||||
@@ -1025,6 +1049,8 @@ 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; } },
|
||||
{ "--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)); } },
|
||||
|
||||
+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;
|
||||
|
||||
+23
-23
@@ -405,13 +405,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). */
|
||||
@@ -705,7 +701,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);
|
||||
@@ -769,13 +766,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). */
|
||||
@@ -1491,15 +1485,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 +1505,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 +1522,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 +1534,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
|
||||
@@ -1688,6 +1686,7 @@ 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["max_num_batched_tokens"] = cfg_.max_tok;
|
||||
e["placement"] = cfg_.placement;
|
||||
/* Each lookup table's requested and resolved placement. */
|
||||
@@ -2538,6 +2537,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;
|
||||
@@ -2723,8 +2723,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 "
|
||||
|
||||
+5
-8
@@ -185,7 +185,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. */
|
||||
@@ -383,7 +382,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
|
||||
@@ -407,13 +406,11 @@ 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);
|
||||
/* Handed from issue_block_drafter to finish_block_drafter and issue_ahead: the drafting rows,
|
||||
|
||||
+122
-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,7 @@ 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_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;
|
||||
@@ -1026,24 +1046,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. */
|
||||
@@ -1062,7 +1081,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{};
|
||||
@@ -1081,54 +1103,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 -- "
|
||||
@@ -1146,6 +1158,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());
|
||||
@@ -1236,6 +1255,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_) {
|
||||
@@ -1389,6 +1430,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
|
||||
@@ -1475,7 +1531,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();
|
||||
@@ -1611,7 +1668,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;
|
||||
}
|
||||
@@ -2949,6 +3007,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
|
||||
@@ -3183,13 +3242,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
|
||||
@@ -3477,16 +3539,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;
|
||||
}
|
||||
|
||||
+10
-56
@@ -276,11 +276,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,63 +303,19 @@ 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. */
|
||||
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. */
|
||||
@@ -374,7 +327,8 @@ int Engine::issue_block_drafter(int step, StepOut& so) {
|
||||
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 +347,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) {
|
||||
|
||||
@@ -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",
|
||||
@@ -2665,7 +2668,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";
|
||||
|
||||
@@ -262,10 +262,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;
|
||||
|
||||
@@ -64,8 +64,6 @@ 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;
|
||||
};
|
||||
@@ -115,7 +113,7 @@ int64_t carve(const Sizes& z, int64_t (*bytes)[2], int n) {
|
||||
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;
|
||||
}
|
||||
|
||||
+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);
|
||||
|
||||
@@ -181,8 +181,6 @@ namespace {
|
||||
|
||||
constexpr int64_t kAlign = 256;
|
||||
|
||||
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. */
|
||||
int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], int n) {
|
||||
@@ -210,7 +208,7 @@ int64_t carve(const RadVideoGenDecl& d, int64_t max_tok, int64_t (*bytes)[2], in
|
||||
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) ----
|
||||
*
|
||||
|
||||
+8
-3
@@ -462,8 +462,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 +489,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 +512,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);
|
||||
|
||||
+6
-9
@@ -256,20 +256,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);
|
||||
|
||||
@@ -357,8 +356,6 @@ 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;
|
||||
};
|
||||
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
@@ -31,11 +31,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
@@ -5,10 +5,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 {
|
||||
@@ -40,6 +49,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")) {
|
||||
@@ -259,6 +311,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");
|
||||
@@ -532,69 +598,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) {
|
||||
@@ -794,6 +1105,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;
|
||||
@@ -843,6 +1167,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
|
||||
@@ -920,6 +1313,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. */
|
||||
@@ -959,11 +1586,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));
|
||||
@@ -1139,7 +1772,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), "
|
||||
@@ -1168,7 +1806,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);
|
||||
}
|
||||
|
||||
namespace {
|
||||
|
||||
+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;
|
||||
|
||||
/* Audio, when the program declares an audio encoder; `merge` and `max_frames` are the
|
||||
@@ -342,6 +387,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;
|
||||
@@ -405,6 +452,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 */
|
||||
+21
-4
@@ -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
|
||||
@@ -620,11 +622,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
|
||||
@@ -787,6 +800,10 @@ 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";
|
||||
/* --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
|
||||
|
||||
@@ -909,7 +909,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");
|
||||
@@ -940,6 +940,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);
|
||||
|
||||
@@ -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
|
||||
|
||||
+105
-13
@@ -178,6 +178,12 @@ 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);
|
||||
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);
|
||||
@@ -197,7 +203,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 +246,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");
|
||||
@@ -320,6 +328,8 @@ 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);
|
||||
|
||||
/* Logprobs readback; only rank 0 reads it. */
|
||||
@@ -337,10 +347,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_) {
|
||||
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,6 +363,8 @@ 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 (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);
|
||||
@@ -366,6 +378,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 +387,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 +399,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 +440,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 +485,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");
|
||||
@@ -581,6 +610,8 @@ 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;
|
||||
cur_stage_ = params_stage_;
|
||||
lp_rows_.clear();
|
||||
|
||||
@@ -635,6 +666,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;
|
||||
@@ -695,6 +727,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 +775,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 +795,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 +938,16 @@ int Sampler::build_greedy(int64_t n) {
|
||||
n_seq_ = n;
|
||||
any_brk_ = false;
|
||||
any_late_ = false;
|
||||
any_ngram_ = false;
|
||||
any_ngram_wl_ = 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 +970,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 +978,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,13 +1012,21 @@ 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));
|
||||
@@ -956,6 +1035,8 @@ int Sampler::run(RadCtx* c, rad_buf logits, rad_buf out_tokens) {
|
||||
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 +1064,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
|
||||
|
||||
+22
-1
@@ -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,7 +68,9 @@
|
||||
* 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).
|
||||
@@ -232,6 +238,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;
|
||||
@@ -252,6 +261,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;
|
||||
@@ -275,6 +288,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 +297,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;
|
||||
|
||||
@@ -199,6 +199,11 @@ private:
|
||||
int32_t *h_rows = nullptr, *d_rows = nullptr;
|
||||
int32_t *h_first = nullptr, *d_first = nullptr;
|
||||
AdvGroup *h_grp = nullptr, *d_grp = nullptr;
|
||||
/* [max_seqs] per-sequence runtime-window data for the advance: the block-aligned first
|
||||
* ring position and the block table's length in blocks, 0 when the sequence has no
|
||||
* runtime window (advance.h). Per sequence because each prompt has its own floor. */
|
||||
int32_t *h_rpos = nullptr, *d_rpos = nullptr;
|
||||
int32_t *h_tlen = nullptr, *d_tlen = nullptr;
|
||||
|
||||
char* h_derived = nullptr; /* derivation staging, byte-addressed */
|
||||
/* [3][n_tok] rotary positions and [n_tok] encoder-row targets (RadBatch::rope_pos,
|
||||
@@ -328,6 +333,9 @@ private:
|
||||
int32_t* enc_coord_host_ = nullptr;
|
||||
int32_t* enc_cu_host_ = nullptr;
|
||||
std::vector<int32_t> enc_coord_tmp_; /* one item's coordinates; kept for its capacity */
|
||||
/* The pass's per-segment grid, host side (RadBatch::enc_seg_h/w). Filled by build_encoder and
|
||||
* valid until the next build, like the staged coordinates. */
|
||||
std::vector<int32_t> enc_seg_h_host_, enc_seg_w_host_;
|
||||
int64_t last_n_tok_ = 0;
|
||||
struct MediaBytes { int64_t mm = 0, pix = 0, crd = 0, cu = 0; };
|
||||
MediaBytes media_bytes(); /* the four per-rank device regions alloc_media reserves */
|
||||
|
||||
@@ -47,12 +47,16 @@ int chunk_geometry_resolve(const Program& prog, const Config& cfg, ChunkGeometry
|
||||
* served by a different kernel may differ (§7.2). */
|
||||
bool has_linear = false, has_window = false;
|
||||
for (const KVGroupInfo& kg : prog.kv_groups) {
|
||||
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW) {
|
||||
if (kg.decl.kind == RAD_KV_FULL || kg.decl.kind == RAD_KV_WINDOW ||
|
||||
kg.decl.kind == RAD_KV_RING) {
|
||||
if (kg.block_size > 0) {
|
||||
g.attn_block = lcm64(g.attn_block, kg.block_size);
|
||||
note(g.why, "attn_block", kg.block_size, kg.name.c_str());
|
||||
/* A drafter's window is recomputed by draft refill; only the trunk's needs a
|
||||
* snapshot for a prefix hit to resume. */
|
||||
* snapshot for a prefix hit to resume. A RAD_KV_RING group has no snapshot at all
|
||||
* (KVManager::declare_runtime_window): its window is each sequence's own prompt
|
||||
* length, which no slot could describe, so it is sized for the context plus a ring
|
||||
* and is never checkpointed. */
|
||||
if (kg.decl.kind == RAD_KV_WINDOW && !kg.layers.empty() && !kg.drafter)
|
||||
has_window = true;
|
||||
}
|
||||
|
||||
+79
-15
@@ -44,6 +44,24 @@ struct IKVManager {
|
||||
/* After a committed step, a window group frees what no later query can read
|
||||
* (KVManager::trim_window). */
|
||||
virtual void trim_window(uint64_t seq, int64_t keep_from) { (void)seq; (void)keep_from; }
|
||||
/* R-SWA (KVManager::declare_runtime_window): the W this group arms a sequence with, 0 when it
|
||||
* carries no runtime windows. The scheduler arms every sequence it admits with
|
||||
* set_window(seq, prompt length, W); a manager with no runtime window refuses it and the
|
||||
* scheduler never asks. */
|
||||
virtual int64_t runtime_window_tokens(int32_t group) const { (void)group; return 0; }
|
||||
virtual int set_window(uint64_t seq, int64_t visible_lo, int64_t window_tokens) {
|
||||
(void)seq; (void)visible_lo; (void)window_tokens;
|
||||
return RAD_E_UNSUPPORTED;
|
||||
}
|
||||
/* The sequence's runtime window in `group`, if it has one (KVManager::runtime_window). A
|
||||
* sequence with one is excluded from prefix publish, checkpoint snapshots and speculation:
|
||||
* the window is runtime data and the ring rewrites its slots in place. */
|
||||
virtual bool runtime_window(uint64_t seq, int32_t group, SeqWindow* out) const {
|
||||
(void)seq; (void)group; (void)out;
|
||||
return false;
|
||||
}
|
||||
|
||||
virtual bool has_runtime_window(uint64_t seq) const { (void)seq; return false; }
|
||||
/* Window snapshot of a prefix hit (KVManager::has_window_snapshot / seed_window). The
|
||||
* defaults mean no hit on a windowed trunk is ever resumed. */
|
||||
virtual bool has_window_snapshot() const { return false; }
|
||||
@@ -95,7 +113,11 @@ struct IKVManager {
|
||||
|
||||
/* Absolute token position that block_table(seq, group)[0] covers: zero for a full group,
|
||||
* non-zero for a window group once blocks below the window are recycled. The step batch maps
|
||||
* a slot as `(pos - first_block_pos) / block_size`. */
|
||||
* a slot as `(pos - first_block_pos) / block_size`.
|
||||
*
|
||||
* A sequence with a runtime window (runtime_window) keeps first_block_pos 0 even once the ring
|
||||
* recycles: its table is [reference][ring] from position 0 and the ring's positions map
|
||||
* modulo ring_blocks (SeqWindow), so only the slot index recycles, never the table. */
|
||||
virtual int64_t first_block_pos(uint64_t seq, int32_t group) const = 0;
|
||||
|
||||
/* Index of the first entry of block_table(seq, group) changed since the previous call;
|
||||
@@ -110,13 +132,22 @@ struct IKVManager {
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ the prefix cache */
|
||||
/* What IPrefixCache::restore did: brought back every entry the tiers hold for the prompt (or there
|
||||
* were none), brought back part of them because the pool could not hold the chain, or, asked for
|
||||
* the whole chain only, left it on the host. */
|
||||
enum class RestoreResult : uint8_t { Whole, Cut, Declined };
|
||||
|
||||
struct IPrefixCache {
|
||||
virtual ~IPrefixCache() = default;
|
||||
|
||||
/* Bring back whatever the idle tiers hold for this prompt, before the lookup. The engine
|
||||
* performs it (it allocates blocks and runs a device scatter). A failure only leaves a
|
||||
* shorter prefix, which is always safe. */
|
||||
virtual void restore(const Request&) {}
|
||||
* shorter prefix, which is always safe. With `whole_only`, a chain the pool cannot be made to
|
||||
* hold whole is left on the host (RestoreResult::Declined). */
|
||||
virtual RestoreResult restore(const Request&, bool whole_only) {
|
||||
(void)whole_only;
|
||||
return RestoreResult::Whole;
|
||||
}
|
||||
/* A step's admissions begin; the last step's lookup results have been consumed. */
|
||||
virtual void begin_step() {}
|
||||
/* Keep this waiting request's chain in VRAM until release(). Called when admission is refused
|
||||
@@ -170,8 +201,6 @@ struct IPrefixCache {
|
||||
virtual CkptCounts ckpt_counts() const { return {}; }
|
||||
/* Entries expired by --prefix-cache-ttl; not counted as evictions. */
|
||||
virtual int64_t expired() const { return 0; }
|
||||
/* Restores the pool could not hold whole (PrefixCache::Stats::restore_cuts). */
|
||||
virtual int64_t restore_cuts() const { return 0; }
|
||||
virtual int64_t ckpt_expired() const { return 0; }
|
||||
|
||||
/* Tokens of context held only by the cache right now. Blocks a running sequence also reads
|
||||
@@ -215,7 +244,7 @@ struct KVGeom {
|
||||
for (const KVGroupInfo& gi : groups) {
|
||||
G e;
|
||||
e.kind = gi.decl.kind;
|
||||
e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW);
|
||||
e.paged = (e.kind == RAD_KV_FULL || e.kind == RAD_KV_WINDOW || e.kind == RAD_KV_RING);
|
||||
e.block_size = gi.block_size > 0 ? gi.block_size : 1;
|
||||
e.window = gi.decl.window;
|
||||
k.g.push_back(e);
|
||||
@@ -231,6 +260,23 @@ struct KVGeom {
|
||||
if (bi < 0 || bi >= (int64_t)bt.size()) return -1;
|
||||
return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size));
|
||||
}
|
||||
|
||||
/* The same slot for a runtime window (SeqWindow): the reference maps linearly (first_pos is
|
||||
* 0 there), and a position at or past the ring's start lives in block
|
||||
* ring_pos/block + ((pos - ring_pos)/block) % ring_blocks, which is what rewrites the ring's
|
||||
* slots in place. ring_pos is block-aligned, so `pos % block` stays the in-block offset. */
|
||||
int32_t slot_ring(int gi, const std::vector<int32_t>& bt, int64_t first_pos, int64_t pos,
|
||||
const SeqWindow& w) const {
|
||||
const G& e = g[(size_t)gi];
|
||||
int64_t bi;
|
||||
if (w.set && pos >= w.ring_pos) {
|
||||
bi = w.ring_pos / e.block_size + ((pos - w.ring_pos) / e.block_size) % w.ring_blocks;
|
||||
} else {
|
||||
bi = (pos - first_pos) / e.block_size;
|
||||
}
|
||||
if (bi < 0 || bi >= (int64_t)bt.size()) return -1;
|
||||
return (int32_t)(bt[(size_t)bi] * e.block_size + (pos % e.block_size));
|
||||
}
|
||||
};
|
||||
|
||||
/* ------------------------------------------------------------------ binding the concrete classes */
|
||||
@@ -246,6 +292,12 @@ struct KVBinding final : IKVManager {
|
||||
int ensure(uint64_t s, int64_t n) override { return m->ensure(s, n); }
|
||||
int ensure_from(uint64_t s, int64_t n, int64_t k) override { return m->ensure(s, n, k); }
|
||||
void trim_window(uint64_t s, int64_t k) override { m->trim_window(s, k); }
|
||||
int64_t runtime_window_tokens(int32_t g) const override { return m->runtime_window_tokens(g); }
|
||||
int set_window(uint64_t s, int64_t lo, int64_t w) override { return m->set_window(s, lo, w); }
|
||||
bool runtime_window(uint64_t s, int32_t g, SeqWindow* o) const override {
|
||||
return m->runtime_window(s, g, o);
|
||||
}
|
||||
bool has_runtime_window(uint64_t s) const override { return m->has_runtime_window(s); }
|
||||
bool has_window_snapshot() const override { return m->has_window_snapshot(); }
|
||||
int seed_window(uint64_t s, int64_t p) override { return m->seed_window(s, p); }
|
||||
int adopt(uint64_t s, int32_t g, const std::vector<int32_t>& b, int64_t n) override {
|
||||
@@ -344,16 +396,20 @@ struct PCBinding final : IPrefixCache {
|
||||
}
|
||||
|
||||
/* Installed by the engine when the idle tiers are on; empty otherwise. */
|
||||
std::function<void(const Request&)> restore_fn;
|
||||
void restore(const Request& r) override {
|
||||
if (restore_fn) restore_fn(r);
|
||||
std::function<RestoreResult(const Request&, bool whole_only)> restore_fn;
|
||||
RestoreResult restore(const Request& r, bool whole_only) override {
|
||||
return restore_fn ? restore_fn(r, whole_only) : RestoreResult::Whole;
|
||||
}
|
||||
/* The entries restore_fn brings back, in chain order: the whole chain if the pool can be made
|
||||
* to hold it, otherwise cut (PrefixCache::restorable_from). Room is made as evict() makes it,
|
||||
* dropping entries with a landed host copy, then landing pending copies and dropping those, but
|
||||
* never erasing one: a restore is worth no lost conversation. The pool's free quarter can go
|
||||
* to it; the reserve's trim after the next publish frees it again. */
|
||||
std::vector<BlockHash> restore_plan(const Request& r, uint64_t salt) {
|
||||
* dropping entries with a landed host copy, then landing pending copies and dropping those,
|
||||
* but never erasing one, so no other conversation is lost to a restore. The pool's free
|
||||
* quarter can go to it; the reserve's trim after the next publish frees it again. `*res`
|
||||
* says whether the chain was cut; with `whole_only`, a chain that would be cut comes back
|
||||
* empty and Declined, and the room made stays for the next attempt. */
|
||||
std::vector<BlockHash> restore_plan(const Request& r, uint64_t salt, bool whole_only = false,
|
||||
RestoreResult* res = nullptr) {
|
||||
if (res) *res = RestoreResult::Whole;
|
||||
media_keys(r, &mm_, salt);
|
||||
std::vector<BlockHash> want = m->restorable_from(r.prompt, mm_);
|
||||
const int64_t need = (int64_t)want.size() - m->restore_room();
|
||||
@@ -361,7 +417,16 @@ struct PCBinding final : IPrefixCache {
|
||||
const int64_t k = m->trim_for(r.prompt, mm_, need);
|
||||
if (k < need && flush_fn && flush_fn()) (void)m->trim_for(r.prompt, mm_, need - k);
|
||||
/* Landing copies may have moved records; take the chain again against the room made. */
|
||||
return m->restorable_from(r.prompt, mm_, m->restore_room());
|
||||
if (whole_only) {
|
||||
want = m->restorable_from(r.prompt, mm_);
|
||||
if ((int64_t)want.size() <= m->restore_room()) return want;
|
||||
if (res) *res = RestoreResult::Declined;
|
||||
return {};
|
||||
}
|
||||
bool cut = false;
|
||||
want = m->restorable_from(r.prompt, mm_, m->restore_room(), &cut);
|
||||
if (cut && res) *res = RestoreResult::Cut;
|
||||
return want;
|
||||
}
|
||||
void begin_step() override { m->begin_step(); }
|
||||
void hold(const Request& r) override {
|
||||
@@ -422,7 +487,6 @@ struct PCBinding final : IPrefixCache {
|
||||
return { st.ckpt_retired, st.ckpt_lru, st.ckpt_refused };
|
||||
}
|
||||
int64_t expired() const override { return m->stats().expired; }
|
||||
int64_t restore_cuts() const override { return m->stats().restore_cuts; }
|
||||
int64_t ckpt_expired() const override { return m->stats().ckpt_expired; }
|
||||
int64_t held_tokens() const override { return m->unshared_tokens(); }
|
||||
|
||||
|
||||
@@ -95,15 +95,16 @@ struct SchedMetrics {
|
||||
/* Admissions whose attention hit was cut to nothing: no snapshot at or below it (recurrent
|
||||
* state or a window snapshot), a windowed trunk group no window snapshot covers, or blocks
|
||||
* that could not be adopted. `hit_cut_resumed_below` counts those that resumed at a
|
||||
* snapshot more than one checkpoint interval below the hit: the retention ladder had
|
||||
* nothing nearer, or the restore brought back only part of the chain. `hit_cut_tokens` is
|
||||
* the checkpoint shortfall: prompt tokens the attention cache held and the admission
|
||||
* computed again, because the hit resumed at a snapshot below it or was cut to nothing. */
|
||||
* snapshot more than one checkpoint interval below the hit: the previous reply was longer
|
||||
* than an interval (decode writes no snapshot), the retention policy kept nothing nearer, or
|
||||
* a restore was cut (prefix_restore_cuts). `hit_cut_tokens` is the checkpoint shortfall:
|
||||
* prompt tokens the attention cache held and the admission computed again, because the hit
|
||||
* resumed at a snapshot below it or was cut to nothing. */
|
||||
int64_t hit_cut_no_snapshot = 0, hit_cut_window = 0, hit_cut_adopt = 0;
|
||||
int64_t hit_cut_resumed_below = 0;
|
||||
int64_t hit_cut_tokens = 0;
|
||||
/* Restores from the host tier the pool could not hold whole, even after giving up the VRAM
|
||||
* copies of other conversations (PrefixCache::Stats::restore_cuts). */
|
||||
* copies of other conversations, counted once per admission (RestoreResult::Cut). */
|
||||
int64_t prefix_restore_cuts = 0;
|
||||
/* Tokens of context held only by the cache, i.e. what eviction would free. Excludes blocks
|
||||
* shared with a running sequence. Same token axis as the paged groups, so comparable with
|
||||
|
||||
+81
-13
@@ -70,6 +70,20 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
|
||||
has_linear_state_ = false;
|
||||
for (const auto& g : kvgeom_.g) if (!g.paged) has_linear_state_ = true;
|
||||
|
||||
/* R-SWA: which groups carry runtime per-sequence windows, and the W they arm a sequence
|
||||
* with. Empty unless the engine declared one (KVManager::declare_runtime_window), so a model
|
||||
* with a fixed window (gemma4) takes none of the runtime-window paths. */
|
||||
rswa_windows_.clear();
|
||||
for (size_t i = 1; i < kvgeom_.g.size(); ++i) {
|
||||
const int64_t w = kv->runtime_window_tokens((int32_t)i);
|
||||
if (w > 0) rswa_windows_.push_back({(int32_t)i, w});
|
||||
}
|
||||
if (!rswa_windows_.empty())
|
||||
RAD_INFO("R-SWA: %zu KV group(s) with a runtime window; a sequence keeps its prompt as the "
|
||||
"reference and decodes into a ring of %lld token(s) after it, and is excluded from "
|
||||
"the prefix cache, checkpoints and speculation",
|
||||
rswa_windows_.size(), (long long)rswa_windows_[0].tokens);
|
||||
|
||||
/* A hit can leave a drafter's own cache short only where a paged group is not prefix-cached
|
||||
* (scheduler.h, hit_holes_draft_). With the cache off cached_groups() is empty and this is
|
||||
* true, which costs nothing: no hits are taken, and every first block pass is at ctx_len 0. */
|
||||
@@ -282,6 +296,10 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
|
||||
s.ckpt_src = -1;
|
||||
s.hit_attn = 0;
|
||||
s.hit_owed = false;
|
||||
/* Slots are reused: a request that inherited `restore_waited` would never wait for a deferred
|
||||
* release and its restore would be cut. */
|
||||
s.restore_waited = false;
|
||||
s.restore_cut = false;
|
||||
s.req->state = ReqState::Waiting;
|
||||
|
||||
/* The step path appends to `output`, so its capacity is settled here, on the arrival thread.
|
||||
@@ -407,7 +425,12 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
* and failed requests are published too; their prompts were computed, and a client that hangs
|
||||
* up mid-answer is likely to ask for that prefix again. */
|
||||
if (publish && cfg_.prefix_cache && pc_ && kv_->has_sequence(s.req->id) &&
|
||||
s.req->n_computed > 0) {
|
||||
s.req->n_computed > 0 && !kv_->has_runtime_window(s.req->id)) {
|
||||
/* R-SWA: a sequence with a runtime window is not published (KVManager::set_window). Its
|
||||
* table is a reference plus a ring rather than a prefix from position 0, and the window
|
||||
* length is runtime data that no cache key carries; a hit would adopt blocks for a window
|
||||
* this sequence does not have. prefix.cpp already skips a windowed group -- this makes the
|
||||
* policy explicit, rather than a consequence of the kind declared at build time. */
|
||||
const std::vector<int32_t>& cg = pc_->cached_groups();
|
||||
pub_blocks_.assign(cg.size(), {});
|
||||
bool ok = !cg.empty();
|
||||
@@ -466,6 +489,11 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
|
||||
* refusal leaves the entry without one. */
|
||||
void Scheduler::reserve_ckpt(StepEntry& e, const Request& r, int64_t pos, int32_t tok) {
|
||||
int32_t cs = -1;
|
||||
/* R-SWA: a sequence with a runtime window is never checkpointed. The window is runtime data
|
||||
* (the prompt's own length), so a slot would describe a window the sequence does not have, and
|
||||
* the ring is not the [lo, pos) block list a restore seeds. The prefix cache can never reuse
|
||||
* it either, so the copy would be dead weight. */
|
||||
if (kv_->has_runtime_window(r.id)) return;
|
||||
if (pc_->reserve_checkpoint(r, pos, &cs) < 0 || cs < 0) return;
|
||||
e.ckpt_tok = tok;
|
||||
e.ckpt_slot = cs;
|
||||
@@ -700,6 +728,12 @@ int Scheduler::draft_ngram(SchedReq& s, int depth) const {
|
||||
}
|
||||
|
||||
/* ------------------------------------------------------------------ chunking */
|
||||
int64_t Scheduler::chunk_end(const Request& r, int64_t n_target) const {
|
||||
if (rswa_windows_.empty() || !kv_->has_runtime_window(r.id)) return n_target;
|
||||
const int64_t prompt = (int64_t)r.prompt.size();
|
||||
return std::min(n_target, r.n_computed < prompt ? prompt : r.n_computed + 1);
|
||||
}
|
||||
|
||||
/* A prefill chunk splits at the linear-state checkpoint interval so a checkpoint is always
|
||||
* written (spec §7.3; see scheduler.h).
|
||||
*
|
||||
@@ -918,6 +952,20 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
|
||||
if (!kv_->has_sequence(r.id)) RAD_TRY(kv_->add_sequence(r.id));
|
||||
|
||||
/* R-SWA: the visible set becomes [0, prompt) plus a ring of W once the prompt is placed. The
|
||||
* floor is this sequence's own prompt length (image tokens included, they are prompt rows),
|
||||
* and it is armed here rather than at the prefill's end so no checkpoint is reserved for the
|
||||
* sequence: a snapshot would describe a window the sequence no longer has (set_window). */
|
||||
for (const RswaWindow& w : rswa_windows_) {
|
||||
const int rc = kv_->set_window(r.id, (int64_t)r.prompt.size(), w.tokens);
|
||||
if (rc < 0) {
|
||||
RAD_WARN("request %llu: runtime window of %lld tokens over a %zu-token prompt: %s",
|
||||
(unsigned long long)r.id, (long long)w.tokens, r.prompt.size(),
|
||||
rad_strerror(rc));
|
||||
return rc;
|
||||
}
|
||||
}
|
||||
|
||||
/* A fresh attempt: nothing looked up or counted yet. A request that kept an earlier
|
||||
* attempt's hit (n_computed > 0) keeps what it found. */
|
||||
if (r.n_computed == 0) {
|
||||
@@ -937,8 +985,21 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
if (r.n_computed == 0 && cfg_.prefix_cache) {
|
||||
/* Restore before the lookup, which stops at the first block the tiers hold. This is
|
||||
* where a cold session gets its context back for the cost of a copy instead of a
|
||||
* prefill. */
|
||||
pc_->restore(r);
|
||||
* prefill.
|
||||
*
|
||||
* A sequence closed while a step issued ahead still read its blocks keeps them until the
|
||||
* next commit, and the room a restore makes cannot include them yet: a request right
|
||||
* behind another conversation's last turn would come back cut and prefill the rest. Such
|
||||
* a restore waits one step, once, instead of being cut. */
|
||||
const bool whole_only = n_deferred_ > 0 && !s.restore_waited;
|
||||
const RestoreResult rr = pc_->restore(r, whole_only);
|
||||
if (rr == RestoreResult::Declined) {
|
||||
s.restore_waited = true;
|
||||
RAD_DEBUG("admit %llu: the restore waits a step for %d deferred release(s)",
|
||||
(unsigned long long)r.id, n_deferred_);
|
||||
return RAD_E_FULL;
|
||||
}
|
||||
s.restore_cut = rr == RestoreResult::Cut;
|
||||
HitCap cap;
|
||||
if (draft_refill_ > 0) {
|
||||
cap.tokens = std::max<int64_t>(0, (int64_t)r.prompt.size() - draft_refill_);
|
||||
@@ -974,8 +1035,9 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
"below it", (unsigned long long)r.id, (long long)h.n_attn_tokens);
|
||||
} else if (reuse < h.n_attn_tokens) {
|
||||
/* Within an interval of the hit is the ordinary case: a turn's tail past its last
|
||||
* checkpoint. Further down, the snapshots in between are gone, or the attention
|
||||
* blocks reach past what the tiers could restore of the chain. */
|
||||
* checkpoint. Further down, the previous reply was longer than an interval (decode
|
||||
* writes no snapshot), the retention policy kept nothing nearer, or the attention
|
||||
* blocks reach past the snapshot a cut restore stopped at. */
|
||||
if (geo_.checkpoints() && h.n_attn_tokens - reuse > geo_.checkpoint_interval)
|
||||
s.hit_cut = SchedReq::HitCut::ResumedBelow;
|
||||
RAD_DEBUG("admit %llu: prefix hit of %lld tokens resumes at the snapshot at %lld",
|
||||
@@ -1056,9 +1118,10 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
* queued behind it takes every token left. The hit is known by now, so the cap applies
|
||||
* to what really has to run. */
|
||||
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty());
|
||||
want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at);
|
||||
const int64_t end = chunk_end(r, target);
|
||||
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at);
|
||||
if (cap < budget && want > 0)
|
||||
admit_full_ = plan_chunk(r.n_computed, target, budget, nullptr, r.checkpoint_at);
|
||||
admit_full_ = plan_chunk(r.n_computed, end, budget, nullptr, r.checkpoint_at);
|
||||
}
|
||||
int rc = RAD_OK;
|
||||
if (want <= 0) rc = RAD_E_FULL;
|
||||
@@ -1093,6 +1156,7 @@ int Scheduler::admit_one(SchedReq& s, int64_t budget, int64_t reserve) {
|
||||
m_.attn_cached_tokens += s.hit_attn;
|
||||
m_.linear_cached_tokens += r.n_cached;
|
||||
if (s.hit_attn > r.n_cached) m_.hit_cut_tokens += s.hit_attn - r.n_cached;
|
||||
if (s.restore_cut) ++m_.prefix_restore_cuts;
|
||||
switch (s.hit_cut) {
|
||||
case SchedReq::HitCut::NoSnapshot: ++m_.hit_cut_no_snapshot; break;
|
||||
case SchedReq::HitCut::Window: ++m_.hit_cut_window; break;
|
||||
@@ -1254,9 +1318,10 @@ const RadBatch* Scheduler::step() {
|
||||
const int64_t reserve = share_step ? behind_dec + share_tok * shares : 0;
|
||||
const int64_t cap = busy_cap(r.n_computed, target, budget, reserve, !plan_.e.empty(),
|
||||
/*rows_only=*/shares == 0);
|
||||
want = plan_chunk(r.n_computed, target, cap, &ckpt, r.checkpoint_at);
|
||||
const int64_t end = chunk_end(r, target);
|
||||
want = plan_chunk(r.n_computed, end, cap, &ckpt, r.checkpoint_at);
|
||||
if (cap < budget && want > 0 && capped_at < 0) {
|
||||
const int64_t full = plan_chunk(r.n_computed, target, budget, nullptr,
|
||||
const int64_t full = plan_chunk(r.n_computed, end, budget, nullptr,
|
||||
r.checkpoint_at);
|
||||
if (want < full) { capped_at = (int32_t)plan_.e.size(); capped_full = full; }
|
||||
}
|
||||
@@ -1476,7 +1541,8 @@ const RadBatch* Scheduler::step() {
|
||||
if (cfg_.busy_prefill_chunk > 0) limit = std::min(limit, std::max(had, cfg_.busy_prefill_chunk));
|
||||
int64_t ckpt = -1;
|
||||
const int64_t grown = e.ckpt_slot < 0 && limit > had
|
||||
? plan_chunk(r.n_computed, s.seq_len(), limit, &ckpt, r.checkpoint_at) : had;
|
||||
? plan_chunk(r.n_computed, chunk_end(r, s.seq_len()), limit, &ckpt, r.checkpoint_at)
|
||||
: had;
|
||||
if (grown > had && kv_->ensure_from(r.id, r.n_computed + grown, r.n_computed) >= 0) {
|
||||
e.n_tokens = (int32_t)grown;
|
||||
e.produces_token = (r.n_computed + grown >= s.seq_len());
|
||||
@@ -1607,7 +1673,7 @@ bool Scheduler::prefill_continues() const {
|
||||
std::lock_guard<std::mutex> lk(mu_);
|
||||
/* Only the step being released has a plan to read. Between a commit and the next step (an
|
||||
* encoder pass is prepared there) `plan_` is the committed step's, whose requests in_step() no
|
||||
* longer holds: a cancel and reap may have released one (#127). */
|
||||
* longer holds: a cancel and reap may have released one. */
|
||||
if (stage_rows_ <= 0 || !step_open_) return false;
|
||||
/* The next step is held to decode rows (--prefill-interleave): experts staged for a chunk now
|
||||
* would be dropped by that step. */
|
||||
@@ -2125,7 +2191,10 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
|
||||
* so the host bounds it by all of them. A mid-prompt chunk verified nothing. */
|
||||
const int64_t vstart = (int64_t)e.ctx_len + e.n_tokens - 1 - e.n_spec;
|
||||
const int64_t head_max = vstart + e.n_spec;
|
||||
bool can_draft = may_draft && e.produces_token;
|
||||
/* A runtime-window (R-SWA) sequence is never drafted for: its rollback refuses (the ring
|
||||
* rewrites slots KVManager::rollback cannot unwind), so a rejected draft would only warn
|
||||
* and waste the draft compute. This is the gate kv.cpp's rollback comment states. */
|
||||
bool can_draft = may_draft && e.produces_token && !kv_->has_runtime_window(r.id);
|
||||
|
||||
/* Lookahead KV: round k writes the head's K and V at head + k - 1, past the committed end,
|
||||
* so blocks must exist up to the furthest head acceptance could leave. The next verify
|
||||
@@ -2631,7 +2700,6 @@ SchedMetrics Scheduler::metrics_locked() const {
|
||||
m.prefix_ckpt_refused = cc.refused;
|
||||
m.prefix_expired = pc_->expired();
|
||||
m.prefix_ckpt_expired = pc_->ckpt_expired();
|
||||
m.prefix_restore_cuts = pc_->restore_cuts();
|
||||
m.prefix_held_tokens = pc_->held_tokens(); }
|
||||
m.attn_hit_rate = m.prompt_tokens
|
||||
? (float)((double)m.attn_cached_tokens / (double)m.prompt_tokens) : 0.0f;
|
||||
|
||||
+31
-10
@@ -111,6 +111,12 @@ struct SchedReq {
|
||||
* snapshot more than an interval below it. */
|
||||
enum class HitCut : uint8_t { None, NoSnapshot, Window, Adopt, ResumedBelow };
|
||||
HitCut hit_cut = HitCut::None;
|
||||
/* Admission waited a step for a sequence's deferred release before cutting its restore
|
||||
* (Scheduler::admit_one); it waits once. */
|
||||
bool restore_waited = false;
|
||||
/* That attempt's restore came back cut (SchedMetrics::prefix_restore_cuts, counted once the
|
||||
* admission happens). */
|
||||
bool restore_cut = false;
|
||||
|
||||
/* The whole sequence is prompt ++ output; n_computed indexes into it. */
|
||||
int64_t seq_len() const {
|
||||
@@ -322,25 +328,27 @@ public:
|
||||
* A block-diffusion drafter (RAD_DRAFT_BLOCK) proposes a whole block of `block` positions in
|
||||
* one pass, so there are no rounds; instead it runs two passes of different shapes.
|
||||
*
|
||||
* block_begin right after commit(), while plan() still describes the step just run.
|
||||
* Reserves the draft KV block the query pass writes, and returns which
|
||||
* sequences may draft.
|
||||
* block_begin right after the step is issued, before commit(), while plan() still
|
||||
* describes it. Reserves the draft KV block the query pass writes, and
|
||||
* returns which sequences may draft.
|
||||
* block_context the context pass, draft_pass -1. Its entries mirror the trunk step's
|
||||
* row for row (BlockSeq).
|
||||
* block_query the query pass, draft_pass +1. One entry per drafting sequence: the
|
||||
* anchor at its next position, then `block - 1` masks; `out_ids` names the
|
||||
* last `depth` rows.
|
||||
* block_end moves the filled range over what actually ran.
|
||||
* block_end after commit(): moves the filled range over what actually ran.
|
||||
*
|
||||
* The drafter writes its proposal to its declared proposal buffer, not through the sampler,
|
||||
* and the engine publishes it through set_draft().
|
||||
*
|
||||
* On the card (`on_card`), block_begin runs before commit() instead, right after the step is
|
||||
* issued, so both passes queue behind it with no readback in between. The context pass is
|
||||
* unchanged: it mirrors the trunk step, whose positions the host knows. The query pass's
|
||||
* anchor depends on acceptance, so its rows are device rows (advance.h, ADV_BLOCK) staged at
|
||||
* the furthest position acceptance could leave, and the reservation covers that far.
|
||||
* block_end still runs after commit().
|
||||
* Both passes queue behind the step with no readback in between. The context pass mirrors the
|
||||
* trunk step, whose positions the host knows. The query pass's anchor depends on acceptance,
|
||||
* so its rows are device rows (advance.h, ADV_BLOCK) staged at the furthest position
|
||||
* acceptance could leave, and the reservation covers that far.
|
||||
*
|
||||
* With `on_card` false, block_begin runs after commit() instead and stages the query pass
|
||||
* from the committed sequence. The engine does not use it; it is the reference the
|
||||
* scheduler's tests hold the card's staging to.
|
||||
*/
|
||||
struct BlockRow {
|
||||
uint64_t seq = 0;
|
||||
@@ -397,6 +405,12 @@ public:
|
||||
* --busy-prefill-chunk is off, or when auto has nothing to reserve. */
|
||||
int64_t busy_cap(int64_t n_computed, int64_t n_target, int64_t budget, int64_t reserve,
|
||||
bool shared = false, bool rows_only = false) const;
|
||||
/* Where a prefill chunk of a `n_target`-token sequence may end. For a sequence with a runtime
|
||||
* window (IKVManager::set_window) a chunk ends at the prompt, and past it the output a
|
||||
* recompute replays runs one token a step: the ring rewrites its slots in place, so a
|
||||
* multi-token chunk past the floor would overwrite keys its own earlier rows still read, while
|
||||
* one token a step attends as its decode step did. Otherwise `n_target`. */
|
||||
int64_t chunk_end(const Request& r, int64_t n_target) const;
|
||||
|
||||
private:
|
||||
Program* prog_ = nullptr;
|
||||
@@ -429,6 +443,13 @@ private:
|
||||
* meta.n_layers; drafter layers bind from `base_layer` up) that the cache does not index?
|
||||
* Unlike a drafter hole, recomputing the tail cannot repair it; see admit_one. */
|
||||
bool hit_holes_trunk_ = false;
|
||||
/* R-SWA: the groups whose KV manager carries per-sequence runtime windows, with the W a
|
||||
* sequence is armed with (IKVManager::runtime_window_tokens). Empty for every model that does
|
||||
* not declare one, in which case admission and commit are exactly as before. A sequence with
|
||||
* one keeps its prompt as a reference and decodes into a ring after it; it is excluded from
|
||||
* prefix publish, checkpoints and speculation (the window is runtime data). */
|
||||
struct RswaWindow { int32_t group = -1; int64_t tokens = 0; };
|
||||
std::vector<RswaWindow> rswa_windows_;
|
||||
/* Draft refill: the drafter's window where a hit can leave a hole in a windowed block
|
||||
* drafter's cache, else 0. The drafter would be declined until its window slid past the hole,
|
||||
* which on a chat's follow-up turn is most of the reply, so the hit ends one window before the
|
||||
|
||||
+16
-4
@@ -35,6 +35,7 @@
|
||||
|
||||
#include <algorithm>
|
||||
#include <atomic>
|
||||
#include <chrono>
|
||||
#include <iterator>
|
||||
#include <memory>
|
||||
|
||||
@@ -708,10 +709,21 @@ public:
|
||||
std::shared_ptr<mm::Item>* out, std::string* why) override {
|
||||
if (!accepts(k)) { if (why) *why = "this kind of media is not served"; return RAD_E_UNSUPPORTED; }
|
||||
if (k == MediaKind::Audio) return p_->audio(bytes.data(), bytes.size(), out, why);
|
||||
return k == MediaKind::Image
|
||||
? p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
|
||||
opts.max_pixels)
|
||||
: p_->video(bytes.data(), bytes.size(), out, why);
|
||||
if (k == MediaKind::Video) return p_->video(bytes.data(), bytes.size(), out, why);
|
||||
mm::ImageMode mode;
|
||||
mode.kind = (int32_t)opts.image_mode;
|
||||
mode.base_size = opts.image_base_size;
|
||||
mode.image_size = opts.image_size;
|
||||
mode.several = opts.several_pictures;
|
||||
/* The host share of a picture (decode, resample, patch staging), apart from the tower
|
||||
* pass engine_mm.cpp times. */
|
||||
const auto t0 = std::chrono::steady_clock::now();
|
||||
const int rc = p_->image(bytes.data(), bytes.size(), opts.image_tokens, out, why,
|
||||
opts.max_pixels, mode);
|
||||
RAD_DEBUG("mm: host processor %lld bytes -> %.1f ms (rc %d)", (long long)bytes.size(),
|
||||
std::chrono::duration<double, std::milli>(
|
||||
std::chrono::steady_clock::now() - t0).count(), rc);
|
||||
return rc;
|
||||
}
|
||||
|
||||
int32_t audio_rate() const override {
|
||||
|
||||
@@ -339,9 +339,13 @@ HttpResponse Server::handle_speech(const HttpRequest& req) {
|
||||
std::string pcm;
|
||||
for (const gen::AudioChunk& c : chunks) append_pcm16(c.samples, &pcm);
|
||||
const double secs = (double)pcm.size() / 2.0 / (double)(info.channels * info.sample_rate);
|
||||
RAD_INFO("audio: %.1f s from %lld frames in %lld windows, %.1f s%s", secs,
|
||||
(long long)ticket->frames, (long long)ticket->windows,
|
||||
(double)(ticket->t_done_ns - ticket->t_submit_ns) * 1e-9,
|
||||
auto sec = [](int64_t a, int64_t b) { return a > 0 && b >= a ? (double)(b - a) * 1e-9 : 0.0; };
|
||||
RAD_INFO("audio: %.1f s from %lld frames in %lld windows, %.1f s: queue and prompt %.1f s, "
|
||||
"first audio %.1f s, frames %.1f s%s", secs, (long long)ticket->frames,
|
||||
(long long)ticket->windows, sec(ticket->t_submit_ns, ticket->t_done_ns),
|
||||
sec(ticket->t_submit_ns, ticket->t_prompt_ns),
|
||||
sec(ticket->t_submit_ns, ticket->t_first_audio_ns),
|
||||
sec(ticket->t_prompt_ns, ticket->t_frames_ns),
|
||||
ticket->model_ended ? "" : " (the request's length)");
|
||||
HttpResponse res;
|
||||
res.status = 200;
|
||||
|
||||
+97
-183
@@ -55,6 +55,18 @@ HttpResponse Server::handle_control_vector(const HttpRequest& req) {
|
||||
}
|
||||
|
||||
if (req.method == "POST") {
|
||||
/* The default applies to every client's requests that name no choice, so a server
|
||||
* started without --api-key takes the change from a loopback client only, as it does a
|
||||
* runtime adapter load. */
|
||||
if (opt_.api_key.empty() && !req.peer_is_loopback()) {
|
||||
ApiError e;
|
||||
e.status = 403;
|
||||
e.type = "permission_error";
|
||||
e.message = "without --api-key, the control-vector default is changed only from a "
|
||||
"loopback client; start the server with --api-key to change it from "
|
||||
"elsewhere";
|
||||
return error_response(e, req.peer);
|
||||
}
|
||||
json body;
|
||||
try {
|
||||
body = json::parse(req.body.empty() ? "{}" : req.body);
|
||||
@@ -568,16 +580,10 @@ h1 { margin:0; font-size:13.5px; font-weight:600; letter-spacing:-.005em; }
|
||||
.stack { display:grid; gap:14px; }
|
||||
@media (max-width:1000px) {
|
||||
.body { grid-template-columns:minmax(0,1fr); }
|
||||
/* On a phone the page is one column you drag with your thumb. A nested scroller that
|
||||
* refuses to chain (overscroll-behavior:contain, set for the desktop wheel so a scroll
|
||||
* over the request table does not move the page behind it) traps the drag here: you
|
||||
* scroll the card, it bottoms out, and the page will not follow, so you reach for the
|
||||
* margins where no scroller lives to get the page moving again. On narrow screens let
|
||||
* the scroll chain to the document; the desktop containment stays.
|
||||
* .body .hold, not .hold: the base .hold rule is defined LATER in this file, so a bare
|
||||
* .hold override here would match and still LOSE the cascade (equal specificity, later
|
||||
* wins) -- judge slice 31 caught exactly that dead-code trap, and the operator's thumb
|
||||
* confirmed it on the request table. .body .hold wins on specificity regardless of order. */
|
||||
/* In one column a nested scroller with overscroll-behavior:contain (there so a desktop wheel
|
||||
* over the request table does not move the page) traps a touch drag once it bottoms out, so
|
||||
* narrow screens let the scroll chain to the document. `.body .hold` rather than `.hold`: the
|
||||
* base .hold rule comes later in this sheet and would win at equal specificity. */
|
||||
.body .panel > .pbody, .body .hold { overscroll-behavior:auto; }
|
||||
}
|
||||
|
||||
@@ -1488,66 +1494,31 @@ function setMetric(key, value, text) {
|
||||
spark(key, hist[key]);
|
||||
}
|
||||
|
||||
/* BEST / RECENT / NOW ON THE OTHER FOUR TILES, in the shape the decode step established.
|
||||
*
|
||||
* WHAT THESE ARE NOT: engine figures. The engine publishes a floor and a recent window for the
|
||||
* decode step alone (step_ns_decode_best / _recent); for tok/s, requests in flight and acceptance
|
||||
* it publishes ONE figure per poll and nothing older. So these three figures are page-side, and
|
||||
* they mean:
|
||||
* best / highest - the extreme this page session has seen AT THE CURRENT CONCURRENCY.
|
||||
* Resets on reload, not on restart.
|
||||
* recent - the mean over the last 15 s at that concurrency; 5 s on prefill, whose
|
||||
* events are shorter than the window that would fit them. Shorter
|
||||
* than the sparkline on purpose:
|
||||
* a 60 s mean still read 31 tok/s fifty seconds after the lane went
|
||||
* quiet, which is the lane being remembered rather than measured.
|
||||
/* Best / recent / now on the decode, prefill, in-flight and acceptance tiles. The engine
|
||||
* publishes a floor and a recent window only for the decode step; for these it publishes one
|
||||
* figure per poll, so the three figures are the page's own:
|
||||
* best / highest - the extreme this page has seen at the current concurrency; it resets on
|
||||
* reload, not on a server restart. "highest" where more is not better.
|
||||
* recent - the mean of the last RECENT samples at that concurrency.
|
||||
* now - the current value as a percentage of that extreme.
|
||||
* "highest" rather than "best" on the two tiles where more is not better: a lane at its highest
|
||||
* request count is busy, not good. The word carries a direction the number alone does not.
|
||||
* Figures are kept per concurrency ("@cN" past one), because a batched rate read against the
|
||||
* single-stream best reports a batch arriving as a level change. Requests in flight keeps one
|
||||
* bucket, since its value is the concurrency, and it samples idle polls too. Idle polls record
|
||||
* nothing in a concurrency bucket, and the line keeps the last active concurrency's figures
|
||||
* without a now clause. There is no ~99 cap as on the decode step: the extreme comes from the
|
||||
* same series as `now`, so 100% is exact.
|
||||
*
|
||||
* PER-CONCURRENCY BUCKETS, the decode step's structure: a c8 rate read against the
|
||||
* single-stream best reports the batch arriving as a level change -- the mistake that took
|
||||
* the old drift line out. Every figure on the line describes the current concurrency, and
|
||||
* past c1 the line says so ("@c8"). Requests in flight is the exception: its value IS the
|
||||
* concurrency, so bucketing it by concurrency would pin "highest" to the current number
|
||||
* forever -- it keeps one session-wide bucket. While the lane is idle nothing new is
|
||||
* recorded and the line keeps the last active concurrency's figures: frozen, no now clause,
|
||||
* which is what the Decode Step tile does at idle.
|
||||
*
|
||||
* NO ~99 CAP HERE, unlike the decode step. That cap exists because `now` there is a 500 ms poll
|
||||
* mean measured against a 32-step window mean -- different instruments, so a fast stretch can read
|
||||
* faster than the floor without being one. Here the extreme is computed FROM the same series as
|
||||
* `now`, so exceeding it is arithmetically impossible and 100% is exact: you are at your best.
|
||||
*/
|
||||
/* RECENT'S OWN WINDOW, deliberately shorter than the sparkline's. HIST is 60 s and that is right
|
||||
* for a picture -- a sparkline wants the whole minute to show shape. It is wrong for a number:
|
||||
* measured over real traffic (two 5 s bursts inside a quiet minute), a 60 s mean still read 31.7
|
||||
* tok/s fifty seconds after the lane went quiet, and 30 s only brought that to 26.9. Fifteen
|
||||
* seconds decays to zero within a quarter-minute of silence while still tracking the running mean
|
||||
* mid-burst (52.8 against an actual 53.3). Ten and five overshoot -- 79 and 144 against that same
|
||||
* 53 -- which is the current value wearing a different name, and the big number above already is
|
||||
* that. `best`/`highest` stay full-session: an extreme wants every chance to be broken.
|
||||
* Idle polls do not enter an active bucket -- the lane is not at that concurrency while it
|
||||
* sleeps -- but they DO count in requests in flight's window, whose value is meaningful
|
||||
* while nothing runs.
|
||||
*
|
||||
* PREFILL GETS ITS OWN WINDOW (RECENT_PREFILL, 5 s). Measured: small prompts prefill in 1.5-6 s
|
||||
* above 100 tok/s; the operator's compaction reload -- the big one -- runs 7-15 s by his own
|
||||
* count. A 15 s mean cannot report a 7 s event while it is running: it reaches barely half the
|
||||
* peak by the event's end, then spends a quarter-minute averaging it down. Five seconds is
|
||||
* shorter than the shortest event, so `recent` rides the prefill while it happens instead of
|
||||
* diluting it. The engine's own figure is already a windowed rate (its help text: "over the
|
||||
* scheduler's recent window"), so this window sits on top of the engine's smoothing -- it
|
||||
* decides how long the page remembers, not how sharply the engine measures. */
|
||||
const RECENT = 30; /* 15 s at the 500 ms poll WHILE the quantity keeps updating; a quantity
|
||||
that skips polls (acceptance, which only samples when it drafts) spans
|
||||
30 UPDATES, which under sparse drafting is minutes, not 15 s. */
|
||||
const RECENT_PREFILL = 10; /* 5 s: shorter than the shortest prefill event (see above) */
|
||||
* RECENT is shorter than the sparkline's 60 s: a 60 s mean still shows a burst long after the lane
|
||||
* went quiet, and 15 s decays within a quarter-minute while still tracking the mean mid-burst.
|
||||
* Prefill's window is 5 s, so `recent` follows a prefill of several seconds while it runs instead
|
||||
* of diluting it; the engine's prefill rate is itself already windowed. */
|
||||
const RECENT = 30; /* 15 s at the 500 ms poll for a figure sampled every poll; acceptance is
|
||||
sampled only on polls that drafted, so its 30 samples can span minutes */
|
||||
const RECENT_PREFILL = 10; /* 5 s */
|
||||
const extAt = {}, winAt = {};
|
||||
let lastActiveC = 0;
|
||||
/* `win` false records the extreme only. Acceptance keeps its own pooled ring (accPool) and
|
||||
* reads `highest` from extAt, so a window here would be a second, never-read copy of the
|
||||
* same samples -- dead weight that a reviewer reasonably reads as a second figure. */
|
||||
/* `win` false records the extreme only: acceptance pools its window in accPool and reads only
|
||||
* `highest` from extAt. */
|
||||
function noteSample(key, c, value, cap, win) {
|
||||
if (value == null || !finite(value)) return;
|
||||
const e = extAt[key] || (extAt[key] = {});
|
||||
@@ -1558,12 +1529,11 @@ function noteSample(key, c, value, cap, win) {
|
||||
s.push(value); if (s.length > (cap || RECENT)) s.shift();
|
||||
}
|
||||
function triple(key, c, label, fmt, showNow) {
|
||||
/* RECENT IS A WINDOW MEAN, not a window maximum -- a maximum would sit equal to `best` on
|
||||
* any steady lane, and two figures that always agree read as a broken instrument. */
|
||||
/* `recent` is a window mean: a window maximum would equal `best` on any steady lane. */
|
||||
const e = extAt[key];
|
||||
if (!e || !(c in e)) return "";
|
||||
/* A bucket whose extreme is zero still has a story -- requests in flight has seen nothing yet --
|
||||
* so it renders. Only the `now` clause needs a nonzero extreme to divide by. */
|
||||
/* A bucket whose extreme is zero still renders (requests in flight before the first request);
|
||||
* only the `now` clause needs a nonzero extreme to divide by. */
|
||||
const s = winAt[key][c];
|
||||
let sum = 0;
|
||||
for (const v of s) sum += v;
|
||||
@@ -1571,14 +1541,13 @@ function triple(key, c, label, fmt, showNow) {
|
||||
const now = s[s.length - 1];
|
||||
const tag = typeof c === "number" && c > 1 ? "@c" + c : "";
|
||||
let out = label + " " + fmt(e[c]) + " · recent " + fmt(recent);
|
||||
/* THE SAME GUARD THE DECODE STEP USES: no `now` clause while nothing is running. A rate of
|
||||
* zero is the lane being idle, not the lane being slow, and "now 0% of best" reads as a
|
||||
* fault. The "@cN" tag rides the tail, exactly where the decode step puts it. */
|
||||
/* No `now` clause while nothing runs, as on the decode step: a zero rate is an idle lane, and
|
||||
* "now 0% of best" would read as a fault. */
|
||||
if (showNow !== false && e[c] > 0) out += " · now " + Math.round(100 * now / e[c]) + "% of " + label + tag;
|
||||
return out;
|
||||
}
|
||||
/* The acceptance tile's detail line: highest stays the full-session extreme of window ratios
|
||||
* (an extreme is an extreme), but recent and now are POOLED ratios of sums (see above). */
|
||||
/* The acceptance tile's detail line. `highest` is the session's extreme of per-poll ratios;
|
||||
* `recent` is a pooled ratio of sums over the ring (accWindow) and `now` the newest poll's. */
|
||||
function acceptTriple(c, showNow) {
|
||||
const e = extAt["accept"];
|
||||
const ring = accPool[c];
|
||||
@@ -1594,26 +1563,20 @@ function acceptTriple(c, showNow) {
|
||||
return out;
|
||||
}
|
||||
|
||||
/* WINDOWED ACCEPTANCE. The engine's figure is cumulative and exact -- tot_accepted_/tot_drafted_
|
||||
* over the life of the process -- so a best/recent/now line built on it would print the same
|
||||
* number three times and call it a trend. The per-position counters the acceptance chart already
|
||||
* reads are cumulative too, and the DIFFERENCE between two polls is exact acceptance over that
|
||||
* interval, which is the only figure a detail line can move on. Each sample is one poll's delta
|
||||
* (~500 ms, and only when it drafted); `recent` POOLS the last RECENT such deltas AT THAT
|
||||
* CONCURRENCY and `now` is the newest one -- different windows, free to disagree.
|
||||
* The counters go backwards when the engine restarts; that poll resets the window rather than
|
||||
* reporting a negative draft. */
|
||||
/* Acceptance over a window. The engine's draft_accept is accepted / drafted over the life of
|
||||
* the process, so it barely moves on a long-running server. The per-position counters are
|
||||
* cumulative too, and their difference between two polls is the exact conditional acceptance
|
||||
* (accepted / reached) over that interval. Each ring entry is one poll that drafted; the ring is
|
||||
* kept per concurrency and pooled as sum(accepted) / sum(reached), because polls carry unequal
|
||||
* draft counts and a mean of their ratios would weigh a quiet poll like a busy one. */
|
||||
const accPool = {}; /* per concurrency: ring of {dr, da} for the pooled tile window */
|
||||
let accPrev = null, accUp = -1;
|
||||
function accWindow(s) {
|
||||
let reach = 0, hit = 0;
|
||||
for (const p of (s.draft_positions || [])) { reach += p.reached || 0; hit += p.accepted || 0; }
|
||||
/* RESTART DETECTION (2026-10-20, Turnstone audit). Counters going BACKWARDS catches a restart
|
||||
* the page was watching. uptime_s going backwards catches the one it missed: a backgrounded
|
||||
* tab whose accPrev froze while a new process drafted past the old process's lifetime total,
|
||||
* where the delta is positive and the first guard never fires. Either clears every pooled
|
||||
* ring -- a pre-restart pair must not pool with a post-restart one -- and yields no delta,
|
||||
* so the headline reads the idle 0 rather than a dead process's ratio. */
|
||||
/* A server restart: the counters go backwards, or, for a hidden tab that stopped polling while
|
||||
* a new process drafted past the old totals, uptime_s does. Either clears every ring, so counts
|
||||
* from two processes never pool, and yields no delta for this poll. */
|
||||
const up = s.uptime_s;
|
||||
const restart = accPrev !== null && (reach < accPrev.r || hit < accPrev.a ||
|
||||
(typeof up === "number" && up < accUp));
|
||||
@@ -1674,13 +1637,9 @@ function kvPanel(host, keys) {
|
||||
return out;
|
||||
}
|
||||
const totals = kvPanel($("totals"), ["Requests", "Steps"]);
|
||||
/* "Accepted of drafted" is the LIFETIME MARGINAL ratio -- the engine's figure, unchanged, and
|
||||
* the one this panel used to carry as its headline. A bullet now rather than the big number:
|
||||
* see the note at the accept tile. It divides by every token DRAFTED, so it is not comparable
|
||||
* with the live figure above it, which divides by the positions actually REACHED; the two bases
|
||||
* are worked through in README.md, section "Draft acceptance", and both are derivable from the
|
||||
* log. Each label names its own denominator, which is the whole distinction -- so neither needs
|
||||
* a tooltip, and a tooltip would be invisible on the phone anyway. */
|
||||
/* "Accepted of drafted" is the engine's lifetime draft_accept, accepted / drafted. The panel's
|
||||
* big figure divides by the positions reached instead, so the two are not comparable; each label
|
||||
* names its denominator (docs/GUIDE.md, section 6.1). */
|
||||
const spec = kvPanel($("spec"), ["Drafter", "Depth", "Accepted of drafted"]);
|
||||
|
||||
/* ---------------------------------------------------------------- meters */
|
||||
@@ -1915,7 +1874,7 @@ function renderRequests(list, poolTokens) {
|
||||
|
||||
/* ---------------------------------------------------------------- update */
|
||||
let prev = null, prevAt = 0, bars = [], devs = [], layerBars = [];
|
||||
let lastStepMs = null; /* lastTps retired with the per-step freeze (slice 26) */
|
||||
let lastStepMs = null;
|
||||
|
||||
/* The single-stream floor and the engine's most recent window, shown as two numbers with no
|
||||
* verdict. The engine records the fastest single-sequence decode window it has measured
|
||||
@@ -1937,13 +1896,9 @@ function update(s, dt) {
|
||||
* mixed load the answer is the mean of two populations. `step_ns_decode / steps_decode` is
|
||||
* neither -- it is what a decode step cost.
|
||||
*
|
||||
* A window with no decode steps in it reads 0, not the last reading (operator ruling
|
||||
* 2026-10-20, second pass): every other live figure on this page shows 0 when the lane is idle
|
||||
* -- tps() renders 0 as "0" and the engine publishes 0 rates -- so 0 IS the idle signal here,
|
||||
* and the dash stays reserved for a quantity that has no value at all. A held value was the
|
||||
* original sin (a stale number wearing a current name); a dash was an over-correction that
|
||||
* broke the convention. The floor and the engine's recent window below are the engine's own
|
||||
* figures and stay put. */
|
||||
* A window with no decode steps reads 0, the page's idle figure for every live value; a dash
|
||||
* is kept for a quantity that has no value at all, and a held value would present a stale
|
||||
* reading as current. The engine's floor and recent window below keep their values. */
|
||||
const dSteps = prev ? s.steps_decode - prev.steps_decode : 0;
|
||||
const stepMs = dSteps > 0 ? (s.step_ns_decode - prev.step_ns_decode) / 1e6 / dSteps : null;
|
||||
if (stepMs != null) lastStepMs = stepMs;
|
||||
@@ -1967,10 +1922,8 @@ function update(s, dt) {
|
||||
* ~500 ms poll mean and `best` a 32-step window mean, so a short fast stretch can beat the
|
||||
* floor; the figure is capped at 99 and shown as ~99, "at the best", rather than claiming a
|
||||
* record the window cannot confirm. */
|
||||
/* Gated on this window HAVING decode steps, not on the lane being busy: during a
|
||||
* prefill-only stretch the lane is busy, lastStepMs holds the last DECODE poll, and the
|
||||
* headline correctly reads 0 -- printing "now X% of best" under it would put a stale
|
||||
* value under the word "now", the exact defect the idle-0 ruling exists to kill. */
|
||||
/* Only for a window with decode steps in it: during a prefill-only stretch the headline reads
|
||||
* 0 and lastStepMs is an older poll's, which `now` must not show. */
|
||||
if (stepMs != null && s.running > 0) {
|
||||
const k = s.running;
|
||||
if (!(k in bestAt) || lastStepMs < bestAt[k]) bestAt[k] = lastStepMs;
|
||||
@@ -2022,41 +1975,22 @@ function update(s, dt) {
|
||||
const aw = accWindow(s);
|
||||
const awR = aw ? aw.ratio : null;
|
||||
if (awR != null) noteSample("accept", s.running > 0 ? s.running : lastActiveC, awR, null, false);
|
||||
/* POOLED ACCEPTANCE WINDOW (2026-10-20, math audit before the production roll).
|
||||
* triple()'s `recent` averages the per-poll RATIOS; polls carry unequal draft counts, so a
|
||||
* quiet poll and a 500-draft poll would weigh the same -- a mean of ratios, not a ratio of
|
||||
* sums. Measured on a live c8 burst: avg-of-ratios 65.7% vs pooled 54.7%, a 11-point skew
|
||||
* that grows with burstiness. The honest window figure is sum(accepted)/sum(reached) over
|
||||
* the same span, so the tile keeps its own ring of delta pairs per concurrency. */
|
||||
/* The pooled ring (see accWindow), per concurrency. */
|
||||
if (aw != null && aw.dr > 0) {
|
||||
const c = s.running > 0 ? s.running : lastActiveC;
|
||||
const ring = accPool[c] || (accPool[c] = []);
|
||||
ring.push(aw); if (ring.length > RECENT) ring.shift();
|
||||
}
|
||||
/* THE HEADLINE IS THE LIVE WINDOW, not the cumulative ratio. The engine's figure is exact but
|
||||
* cumulative, so on a process that has been up for hours it cannot move: 559 fresh drafts moved
|
||||
* it one point against a 33,000-draft denominator, and it froze outright the moment the lane
|
||||
* went quiet. Every other tile's big number is the current value, and feeding the cumulative one
|
||||
* here also fed the sparkline a quantity that is flat by construction.
|
||||
* Polls with no new drafts read 0 (operator ruling 2026-10-20, second pass): the page's
|
||||
* convention is that a live figure shows 0 when the lane is doing nothing, and the dash is for
|
||||
* quantities with no value at all. The original freeze was the real defect -- a held value
|
||||
* reads as a live measurement of a lane that drafted nothing. The lifetime ratio stays on
|
||||
* /stats and /metrics; what the tile answers is "what is it accepting now", and now, idle,
|
||||
* it is accepting nothing.
|
||||
* THE SPARKLINE'S SCALE IS THE SAME as the other tiles -- 120 samples at the 500 ms poll, 60 s
|
||||
* -- because setMetric samples every poll, idle polls included (0 is a value; see above). The
|
||||
* one difference is the dash case: with no draft head there is no value to push, so those polls
|
||||
* leave a gap and the line stretches over more wall-clock than 60 s. (Judge slice 4C: this
|
||||
* comment claimed a 10 s window, then a drafting-only window; neither sampling scheme exists.) */
|
||||
/* The headline is this poll's conditional acceptance, as every other tile's big number is the
|
||||
* current value; the lifetime ratio stays in the Speculation panel, on /stats and on /metrics.
|
||||
* A poll that drafted nothing reads 0, the page's idle figure, and the dash means there is no
|
||||
* draft head. The sparkline takes a sample every poll, idle ones included, like the other
|
||||
* tiles; without a draft head it takes none. */
|
||||
if (!(s.draft_positions && s.draft_positions.length)) setMetric("accept", null, DASH);
|
||||
else if (awR != null) setMetric("accept", 100 * awR, pctn(awR, 0));
|
||||
else setMetric("accept", 0, pctn(0, 0)); /* drafted nothing this poll -> 0, the idle figure */
|
||||
/* `now` is shown only when THIS poll drafted. The guard inside acceptTriple (last.dr > 0)
|
||||
* cannot ever be false -- the ring only stores deltas with dr > 0 -- so the freshness test
|
||||
* belongs here, where the poll's own delta is known. Otherwise a busy lane that drafted
|
||||
* nothing this poll shows 0 in the headline and "now Z% of highest" one line below it,
|
||||
* computed from the last drafted delta. highest/recent are session statistics and stay. */
|
||||
/* `now` only when this poll drafted: the ring holds only polls that did, so its newest entry
|
||||
* may be older than this poll, whose headline then reads 0. */
|
||||
$("m-acceptdet").textContent = acceptTriple(cNow, busy && awR != null);
|
||||
M.flight.u.textContent = "/ " + s.queue_cap;
|
||||
|
||||
@@ -2084,11 +2018,9 @@ function update(s, dt) {
|
||||
const kvLive = Math.max(0, (s.kv_tokens_used || 0) - kvCached);
|
||||
mKv.v.textContent = hbOf(s.kv_bytes_used, s.kv_bytes_total, " / ") + " · " + pct(kvFrac);
|
||||
setSplit(mKv, kvLive, kvCached, s.kv_tokens_total || 0);
|
||||
/* WHAT THE SEGMENTS ARE, IN THE WORDS OF WHAT THEY WOULD COST TO RECLAIM, because a dimmer bar
|
||||
is not self-explanatory and the phrase this line used to carry -- "in flight" against "held
|
||||
for the next turn" -- named neither thing it was measuring. The split is by who references
|
||||
the blocks: the first part is context a request on the card is reading and cannot be taken
|
||||
from it, the second is context nothing is reading and the next eviction frees. */
|
||||
/* The segments named by what reclaiming them would cost, since a dimmer bar is not
|
||||
self-explanatory. The split is by who references the blocks: the first part is context a
|
||||
request on the card is reading, the second context nothing reads and the next eviction frees. */
|
||||
mKvSub.textContent = s.kv_tokens_used > 0
|
||||
? cnt3(kvLive) + " tok read by running requests · " + cnt3(kvCached) + " kept for reuse"
|
||||
: "";
|
||||
@@ -2141,34 +2073,17 @@ function update(s, dt) {
|
||||
* gives tokens a step for the whole batch -- which grows with concurrency and says nothing
|
||||
* about the drafter. What speculation buys is tokens a step for ONE sequence. */
|
||||
const perStep = sps > 0 && s.decode_tps > 0 ? s.decode_tps / sps / seqs : null;
|
||||
/* Reads 0 when this window took no decode steps -- the page's idle figure, same law as
|
||||
* the step tile above it, which this figure is derived from. It used to hold the last
|
||||
* value, so a lane that stopped decoding kept reporting what its steps used to cost.
|
||||
* (Extension of the operator's idle-0 ruling by one figure: same defect, one line down,
|
||||
* flagged by judge slice 26 as "pre-existing, now more visible".) */
|
||||
/* 0 for a window with no decode steps, as on the step tile it derives from. */
|
||||
$("tps_n").firstChild.nodeValue = perStep == null ? "0" : sig3(perStep);
|
||||
/* ACCEPTED IS THE LIVE FIGURE, matching the tile above it. `aw` is the same pooled drafting
|
||||
* window the tile's headline reads, computed earlier in this function -- one derivation, two
|
||||
* readers, so the panel and the tile cannot disagree.
|
||||
* DESIGN DECISION, 10-19, at the Operator's direction: this section shows the REAL-TIME
|
||||
* accepted percentage and the lifetime average sits in the bullets below it. The reasoning is
|
||||
* on the tile; the short form is that a cumulative ratio on a process that has been up for
|
||||
* hours is a number that cannot move, and a headline that cannot move reads as a dead page.
|
||||
* PINNED, NOT PRICED: the Operator may prefer the average back in the big seat, and the swap
|
||||
* is these two lines. What must not happen is the average returning as the headline with no
|
||||
* bullet left behind, because then the live figure is the thing nobody can see.
|
||||
* Nothing drafted this poll reads 0 -- the page's idle figure, same law as the accept tile
|
||||
* (op ruling 2026-10-20, second pass). The defect being fixed is the FREEZE: a held value
|
||||
* reads as a live measurement of a lane that drafted nothing. */
|
||||
/* The same per-poll conditional acceptance as the accept tile's headline (accWindow), so the
|
||||
* two cannot disagree; 0 when this poll drafted nothing. The lifetime ratio is the
|
||||
* "Accepted of drafted" bullet below. */
|
||||
if (awR != null) $("acc_n").firstChild.nodeValue = pctn(awR, 0);
|
||||
else $("acc_n").firstChild.nodeValue = pctn(0, 0); /* idle: 0, the page's idle figure */
|
||||
$("specaside").textContent = "depth " + dp.length;
|
||||
spec["Drafter"].textContent = drafterName;
|
||||
spec["Depth"].textContent = dp.length;
|
||||
/* The lifetime marginal, always shown. Judge 22: guarding on >0 conflated "no drafts yet"
|
||||
* with "drafts made, all rejected" -- a drafter that accepts nothing is exactly the case a
|
||||
* reader needs to see, and a dash hid it. 0 is the honest figure for both, and the README's
|
||||
* "Draft acceptance" section says which question this bullet answers. */
|
||||
/* Always shown: 0% is also what a drafter that accepts nothing reads, which a dash would hide. */
|
||||
spec["Accepted of drafted"].textContent = pct(s.draft_accept, 0);
|
||||
}
|
||||
|
||||
@@ -3312,32 +3227,24 @@ async function identify() {
|
||||
} catch (err) { /* the header simply keeps its placeholder */ }
|
||||
}
|
||||
|
||||
/* THE CONTROL VECTOR, asked when the Model view opens. It is not a polled value: it changes only
|
||||
* when this page (or an admin call) flips it, and a control that silently reverted under the
|
||||
* reader would be worse than one that is a second old. A deployment without a control vector
|
||||
* answers 404 and the panel stays hidden. */
|
||||
/* The control vector, read when the Model view opens rather than polled: only this page or an
|
||||
* admin call changes it. 404 means the deployment has none and hides the panel; any other failure
|
||||
* keeps the panel and says why, so a page without the API key does not look like a build without
|
||||
* the feature. */
|
||||
async function loadControlVector() {
|
||||
/* THREE OUTCOMES, and only one of them hides the panel:
|
||||
* 404 this deployment has no control vector -- there is no such control, so it is omitted;
|
||||
* 200 the vector is loaded -- show the switch and its state;
|
||||
* anything else (most often 401, the page has no API key yet) -- the feature may well be
|
||||
* there, so SAY that instead of hiding the control. A control that silently disappears
|
||||
* because the page has not signed in reads exactly like a build without the feature. */
|
||||
try {
|
||||
const r = await api("admin/control-vector");
|
||||
if (r.status === 404) { $("cvpanel").hidden = true; return; }
|
||||
if (!r.ok) throw new Error(String(r.status));
|
||||
if (!r.ok) { const err = new Error(String(r.status)); err.status = r.status; throw err; }
|
||||
const p = await r.json();
|
||||
$("cvpanel").hidden = false;
|
||||
$("cvbox").disabled = false;
|
||||
$("cvbox").checked = !!p.default;
|
||||
/* The family leads: it is the one term that says whether this file belongs to the model on the
|
||||
* card at all, and it is the loader's own answer, not a label the page invents. */
|
||||
/* The family the loader validated the file against, then its range and scale. */
|
||||
$("cvsum").textContent = (p.arch ? p.arch + " \u00b7 " : "") + "layers " + p.first +
|
||||
"\u2013" + p.last + " \u00b7 " + p.mode + " \u00b7 scale " + p.scale;
|
||||
/* New requests only, because a running request keeps the choice it was admitted with; and a
|
||||
* session whose context already holds a refusal can repeat it, since the refusal is in the
|
||||
* prompt the next turn reads. */
|
||||
/* A running request keeps the choice it was admitted with, and a refusal already in a
|
||||
* session's context is in the prompt the next turn reads. */
|
||||
$("cvnote").textContent = "New requests only. A session with a refusal already in its " +
|
||||
"context may repeat it.";
|
||||
} catch (e) {
|
||||
@@ -3345,9 +3252,10 @@ async function loadControlVector() {
|
||||
$("cvbox").disabled = true;
|
||||
$("cvbox").checked = false;
|
||||
$("cvsum").textContent = "";
|
||||
$("cvnote").textContent =
|
||||
"Sign in with the API key (the field in the header) to read or change this: the vector " +
|
||||
"is present on this deployment, but its state needs the key.";
|
||||
$("cvnote").textContent = e.status === 401
|
||||
? "Sign in with the API key (the field in the header) to read or change this: the vector " +
|
||||
"is present on this deployment, but its state needs the key."
|
||||
: "The server did not report the control vector's state (" + (e.status || e.message) + ").";
|
||||
}
|
||||
}
|
||||
$("cvbox").addEventListener("change", async (e) => {
|
||||
@@ -3360,11 +3268,17 @@ $("cvbox").addEventListener("change", async (e) => {
|
||||
apiKey ? { Authorization: "Bearer " + apiKey } : {}),
|
||||
body: JSON.stringify({ enabled: want }),
|
||||
});
|
||||
if (!r.ok) throw new Error(String(r.status));
|
||||
if (!r.ok) {
|
||||
let msg = String(r.status);
|
||||
try { const j = await r.json(); if (j && j.error && j.error.message) msg = j.error.message; }
|
||||
catch (_) { /* the status alone */ }
|
||||
throw new Error(msg);
|
||||
}
|
||||
const p = await r.json();
|
||||
$("cvbox").checked = !!p.default;
|
||||
} catch (err) {
|
||||
e.target.checked = !want; // the server kept the old value
|
||||
$("cvnote").textContent = "Not changed: " + err.message;
|
||||
} finally {
|
||||
e.target.disabled = false;
|
||||
}
|
||||
|
||||
@@ -527,6 +527,14 @@ struct MediaOpts {
|
||||
/* A picture over this many pixels is first scaled down to that area (PIL's bicubic, sides
|
||||
* truncated), as a model's own pipeline may do before its processor; 0 leaves it as sent. */
|
||||
int64_t max_pixels = 0;
|
||||
/* Which of the checkpoint's picture modes, for one that has two (Unlimited-OCR): 0 is the
|
||||
* processor's choice (mm::ImageMode::Default), 1 gundam, 2 base. */
|
||||
int32_t image_mode = 0;
|
||||
/* The mode's sizes, when the request states them; 0 keeps the mode's own. */
|
||||
int32_t image_base_size = 0, image_size = 0;
|
||||
/* The request carries more than one picture (mm::ImageMode::several): a processor with a
|
||||
* multi-page mode uses it for a picture whose mode the request did not name. */
|
||||
bool several_pictures = false;
|
||||
};
|
||||
|
||||
class IMultimodal {
|
||||
@@ -618,6 +626,8 @@ struct ImageGenInfo {
|
||||
/* The prompt in windows (RadGeneratorDecl::chunk_tokens): tokens a window, its markers and
|
||||
* its padding token; 0 for a prompt read whole. */
|
||||
int32_t chunk_tokens = 0, chunk_bos = 0, chunk_eos = 0, chunk_pad = 0;
|
||||
/* The conditioning options a request may ask for (RadGeneratorDecl::cond_opts, RAD_GEN_COND_*). */
|
||||
uint32_t cond_opts = 0;
|
||||
};
|
||||
|
||||
class IImageGen {
|
||||
|
||||
@@ -397,12 +397,15 @@ HttpResponse Server::handle_images(const HttpRequest& req, bool edit) {
|
||||
r.seed = (uint64_t)body["seed"].get<int64_t>();
|
||||
r.seed_given = body["seed"].is_number_unsigned() || body["seed"].get<int64_t>() != -1;
|
||||
}
|
||||
/* Krea 2's fixed tap gains (ConditioningKrea2Rebalance's defaults, arch/krea2); other models
|
||||
* ignore it. */
|
||||
/* The conditioning at the plugin's fixed rebalance gains (Krea 2: its text taps at
|
||||
* ConditioningKrea2Rebalance's defaults). `false` is accepted everywhere. */
|
||||
if (body.contains("rebalance") && !body["rebalance"].is_null()) {
|
||||
if (!body["rebalance"].is_boolean())
|
||||
return error_response(err_bad("rebalance", "expected true or false"), req.peer);
|
||||
r.rebalance = body["rebalance"].get<bool>();
|
||||
if (r.rebalance && !(info.cond_opts & RAD_GEN_COND_REBALANCE))
|
||||
return error_response(err_unsupported("rebalance", "this model has no rebalance"),
|
||||
req.peer);
|
||||
}
|
||||
if (str("negative_prompt", &r.negative) < 0)
|
||||
return error_response(err_bad("negative_prompt", "expected a string"), req.peer);
|
||||
|
||||
+11
-19
@@ -140,8 +140,7 @@ void Metrics::sample(const SchedMetrics& m) {
|
||||
g_prefill_tps_.set(m.prefill_tps);
|
||||
g_decode_tps_.set(m.decode_tps);
|
||||
g_draft_accept_.set(m.draft_acceptance);
|
||||
/* Nanoseconds in the scheduler, seconds on the wire: the base unit Prometheus expects, and
|
||||
* what radiance:engine_step_seconds_* already use. */
|
||||
/* Nanoseconds in the scheduler, seconds on the wire, as engine_step_seconds_* use. */
|
||||
g_step_best_.set((double)m.step_ns_decode_best / 1e9);
|
||||
g_step_recent_.set((double)m.step_ns_decode_recent / 1e9);
|
||||
const int seen = std::max(0, std::min(m.draft_depth_seen, (int)MAX_DRAFT_POS));
|
||||
@@ -330,25 +329,17 @@ std::string Metrics::render() const {
|
||||
"Prefill throughput over the scheduler's recent window.", L, g_prefill_tps_.get());
|
||||
w.gauge("radiance:decode_tokens_per_second",
|
||||
"Decode throughput over the scheduler's recent window.", L, g_decode_tps_.get());
|
||||
/* THE DECODE FLOOR, the two figures the dashboard's Decode Step tile shows. They were on
|
||||
* /stats only, and /stats is documented as not a stable API -- so the one figure worth
|
||||
* comparing across restarts was reachable only from the surface automation is told not to
|
||||
* use. Omitted until measured: a floor of 0 seconds is not an unmeasured floor, it is an
|
||||
* infinitely fast one, and a scrape would plot it as a record. Both reset on restart, so a
|
||||
* freshly started server simply has no floor to report yet. */
|
||||
/* The decode floor the dashboard's step tile shows. Each series is omitted until its window
|
||||
* has been measured, because a 0-second step would plot as the fastest ever. */
|
||||
if (g_step_best_.get() > 0)
|
||||
w.gauge("radiance:decode_step_seconds_best",
|
||||
"Fastest single-sequence decode step window this process has run, in seconds "
|
||||
"PER STEP. A mean over 32 consecutive single-stream steps, not a stopwatch "
|
||||
"reading. Not seconds per token: with speculation a step can emit several "
|
||||
"tokens, so per-token time is this divided by (1 + accepted per step), "
|
||||
"not by the accepted figure alone. Resets on restart.", L, g_step_best_.get());
|
||||
"Fastest single-sequence decode window this process has run, in seconds per "
|
||||
"step: the mean of 32 consecutive single-stream steps. With speculation a step "
|
||||
"emits 1 + accepted tokens. Resets on restart.", L, g_step_best_.get());
|
||||
if (g_step_recent_.get() > 0)
|
||||
w.gauge("radiance:decode_step_seconds_recent",
|
||||
"Most recent single-sequence decode step window, in seconds PER STEP (see "
|
||||
"_best: not a token rate). The gap "
|
||||
"to _best tracks what else the machine is doing, not wear; see docs/GUIDE.md. "
|
||||
"Freezes while the lane is idle, because no window is completing.",
|
||||
"Most recent single-sequence decode window, in seconds per step (see _best). "
|
||||
"Holds its value while no single-stream window completes.",
|
||||
L, g_step_recent_.get());
|
||||
w.counter("radiance:engine_steps_total",
|
||||
"Scheduler steps executed. One forward pass of the model, plus whatever draft "
|
||||
@@ -463,8 +454,9 @@ std::string Metrics::render() const {
|
||||
c_cut_resumed_below_.get());
|
||||
w.counter("radiance:prefix_restore_cuts_total",
|
||||
"Restores from the host tier the pool could not hold whole, even after giving "
|
||||
"up the VRAM copies of other stored conversations; each came back to a "
|
||||
"snapshot short of its end.", L, c_restore_cuts_.get());
|
||||
"up the VRAM copies of other stored conversations; each came back only in "
|
||||
"part, on a model with recurrent state up to the deepest snapshot the room "
|
||||
"reaches.", L, c_restore_cuts_.get());
|
||||
w.counter("radiance:prefix_hit_cut_tokens_total",
|
||||
"Prompt tokens the attention cache held and admission computed again, because "
|
||||
"the hit resumed at a snapshot below it or reused nothing.", L,
|
||||
|
||||
@@ -113,9 +113,8 @@ private:
|
||||
Gauge g_running_, g_waiting_, g_kv_util_, g_prefix_hit_;
|
||||
Gauge g_kv_max_tokens_, g_kv_max_bytes_;
|
||||
Gauge g_prefill_tps_, g_decode_tps_, g_draft_accept_, g_preempted_;
|
||||
/* The decode floor, in seconds: the fastest single-sequence window this process has run,
|
||||
* and the most recent one. Both stay 0 until a window of 32 single-stream steps completes,
|
||||
* and both reset on restart -- the render omits them rather than expose an unmeasured 0. */
|
||||
/* The decode floor in seconds: the fastest and the most recent single-sequence window. 0
|
||||
* until a window completes, and render() omits a 0. */
|
||||
Gauge g_step_best_, g_step_recent_;
|
||||
Gauge queue_depth_;
|
||||
/* Per-position conditional draft acceptance (see render() and core/sched/draft.h). */
|
||||
|
||||
+129
-16
@@ -240,7 +240,8 @@ const char* kAcceptedCommon[] = {
|
||||
"dry_sequence_breakers", "samplers",
|
||||
"grammar", "json_schema", "priority", "logprobs", "ignore_eos",
|
||||
"timings_per_token", "return_progress", "session_id", "n_probs",
|
||||
"control_vector", "experimental_speed_projection",
|
||||
"control_vector",
|
||||
"ngram_ban_n", "ngram_window", "ngram_whitelist", "no_repeat_ngram_whitelist",
|
||||
};
|
||||
|
||||
const char* kAcceptedChat[] = {
|
||||
@@ -250,6 +251,8 @@ const char* kAcceptedChat[] = {
|
||||
"thinking_token_budget", "thinking_budget", "thinking_budget_tokens",
|
||||
"reasoning_budget_tokens", "reasoning_format", "continue_final_message",
|
||||
"functions", "function_call",
|
||||
/* Unlimited-OCR's picture modes: which of the checkpoint's two a request's pictures get. */
|
||||
"images_config",
|
||||
};
|
||||
|
||||
/* `preserved_tokens` is llama-server's: control tokens a raw completion's text keeps. On chat the
|
||||
@@ -843,19 +846,12 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
|
||||
/* ignore_eos: generate to max_tokens whatever the model emits. See Request::ignore_eos. */
|
||||
if (!get_bool(b, "ignore_eos", &r->ignore_eos, err)) return RAD_E_INVAL;
|
||||
|
||||
/* The control vector (core/cvec.h): an opt-in per request, and the only place an API client
|
||||
* turns it on when the deployment's default is off. `control_vector` is the field's name;
|
||||
* `experimental_speed_projection` is Strata's spelling of the same switch, kept as an alias so
|
||||
* a client written against that reports what it means -- and read only when the request did not
|
||||
* send the field itself, so the field wins when a body carries both. A JSON null is "not sent",
|
||||
* as everywhere else in this parser. */
|
||||
for (const char* key : { "control_vector", "experimental_speed_projection" }) {
|
||||
const auto it = b.find(key);
|
||||
if (it == b.end() || it->is_null()) continue;
|
||||
/* The control vector (core/cvec.h), per request: absent or null takes the deployment's
|
||||
* default. */
|
||||
if (const auto it = b.find("control_vector"); it != b.end() && !it->is_null()) {
|
||||
bool on = false;
|
||||
if (!get_bool(b, key, &on, err)) return RAD_E_INVAL;
|
||||
if (!get_bool(b, "control_vector", &on, err)) return RAD_E_INVAL;
|
||||
r->control_vector = on ? 1 : 0;
|
||||
break;
|
||||
}
|
||||
|
||||
/* stop: a string or an array of strings. Bounded in count and length because every stop
|
||||
@@ -907,6 +903,95 @@ static int parse_sampling(const json& b, const OaiLimits& lim, OaiRequest* r, Ap
|
||||
auto sid = b.find("session_id");
|
||||
if (sid != b.end() && sid->is_string()) r->session_label = session_label_of(sid->get<std::string>());
|
||||
|
||||
/* The windowed no-repeat-ngram ban (core/sample/sampler.h): `ngram_ban_n` is the banned
|
||||
* n-gram's length and `ngram_window` how far back it looks; the checkpoint's own generation
|
||||
* config asks for 35 and 128 (Unlimited-OCR). The reference spells them
|
||||
* no_repeat_ngram_size and no_repeat_ngram_window_size; both are taken. */
|
||||
i64 = r->sp.ngram_ban_n;
|
||||
if (!get_any(b, { "ngram_ban_n", "no_repeat_ngram_size" }, &i64, nullptr, err))
|
||||
return RAD_E_INVAL;
|
||||
if (i64 < 0 || i64 > 256) {
|
||||
*err = err_bad("ngram_ban_n", "must be in [0, 256]");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
r->sp.ngram_ban_n = (int)i64;
|
||||
i64 = r->sp.ngram_window;
|
||||
if (!get_any(b, { "ngram_window", "no_repeat_ngram_window_size" }, &i64, nullptr, err))
|
||||
return RAD_E_INVAL;
|
||||
if (i64 < 0 || i64 > 131072) {
|
||||
/* The reference's negative window spelling belongs to generation_config, where it is
|
||||
* normalized to 0; a request states the whole-sequence form as 0, matching the sampler's
|
||||
* admission check (check_request refuses a negative window). */
|
||||
*err = err_bad("ngram_window", "must be 0 (search the whole sequence) or a count of at "
|
||||
"most 131072 history tokens");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
r->sp.ngram_window = (int)i64;
|
||||
|
||||
/* The ban's whitelist (the reference's `whitelist_token_ids`, which is removed from the
|
||||
* banned set before the -inf writes): token ids the ban must never touch. An array of
|
||||
* non-negative integers; absent, empty or null is off, the reference's empty whitelist and
|
||||
* the form the model's generation_config ships. */
|
||||
auto nwl = b.find("ngram_whitelist");
|
||||
if (nwl == b.end()) nwl = b.find("no_repeat_ngram_whitelist");
|
||||
if (nwl != b.end() && !nwl->is_null()) {
|
||||
if (!nwl->is_array()) {
|
||||
*err = err_bad("ngram_whitelist", "expected an array of integer token ids");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
std::vector<int32_t> wl;
|
||||
for (const auto& v : *nwl) {
|
||||
int32_t id = 0;
|
||||
if (!token_id(v, &id)) {
|
||||
*err = err_bad("ngram_whitelist",
|
||||
"expected token ids in [0, " + std::to_string(INT32_MAX) + "]");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
if (wl.size() >= (size_t)1 << 20) {
|
||||
*err = err_bad("ngram_whitelist", "at most 1048576 ids");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
wl.push_back(id);
|
||||
}
|
||||
r->sp.ngram_whitelist = std::move(wl);
|
||||
}
|
||||
|
||||
/* `images_config`: Unlimited-OCR's two picture modes. A string names one ("gundam" for a
|
||||
* single picture -- the global view plus crops --, "base" for a page of a multi-page
|
||||
* document); an object carries the reference runner's own dict. */
|
||||
auto ic = b.find("images_config");
|
||||
if (ic != b.end() && !ic->is_null()) {
|
||||
if (ic->is_string()) {
|
||||
const std::string m = ic->get<std::string>();
|
||||
if (m == "gundam") r->image_mode = 1;
|
||||
else if (m == "base") r->image_mode = 2;
|
||||
else if (!m.empty()) {
|
||||
*err = err_bad("images_config", "expected \"gundam\" or \"base\", got \"" + m +
|
||||
"\"");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
} else if (ic->is_object()) {
|
||||
const json& o = *ic;
|
||||
int64_t bs = 0, is = 0;
|
||||
if (!get_int(o, "base_size", &bs, err)) return RAD_E_INVAL;
|
||||
if (!get_int(o, "image_size", &is, err)) return RAD_E_INVAL;
|
||||
bool crop = true;
|
||||
if (!get_bool(o, "crop_mode", &crop, err)) return RAD_E_INVAL;
|
||||
if (bs < 0 || bs > 65536 || is < 0 || is > 65536) {
|
||||
*err = err_bad("images_config", "base_size and image_size must be in [0, 65536]");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
r->image_mode = crop ? 1 : 2;
|
||||
r->image_base_size = (int32_t)bs;
|
||||
r->image_size = (int32_t)is;
|
||||
} else {
|
||||
*err = err_bad("images_config",
|
||||
"expected \"gundam\", \"base\", or an object with base_size, "
|
||||
"image_size and crop_mode");
|
||||
return RAD_E_INVAL;
|
||||
}
|
||||
}
|
||||
|
||||
RAD_TRY(apply_sampler_order(b, &r->sp, err));
|
||||
|
||||
auto so = b.find("stream_options");
|
||||
@@ -1488,6 +1573,15 @@ int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
|
||||
out->text = rendered;
|
||||
auto pm = std::make_shared<mm::PromptMedia>();
|
||||
const std::string marker = RAD_MEDIA_MARKER;
|
||||
/* Whether the request carries several pictures: a processor with a multi-page mode picks it
|
||||
* for a picture whose mode the request did not name (mm::ImageMode::several). */
|
||||
size_t n_images = 0;
|
||||
for (const auto& m : media) n_images += m.first == MediaKind::Image ? 1 : 0;
|
||||
auto opts_for = [&](MediaKind k) {
|
||||
MediaOpts mo = opts;
|
||||
if (k == MediaKind::Image) mo.several_pictures = n_images > 1;
|
||||
return mo;
|
||||
};
|
||||
size_t pos = 0, mi = 0;
|
||||
for (;;) {
|
||||
size_t at = rendered.find(marker, pos);
|
||||
@@ -1507,7 +1601,8 @@ int tokenize_with_media(const std::string& rendered, const OaiDeps& d,
|
||||
}
|
||||
std::shared_ptr<mm::Item> item;
|
||||
std::string why;
|
||||
const int s = d.mm->prepare(media[mi].first, media[mi].second, opts, &item, &why);
|
||||
const int s = d.mm->prepare(media[mi].first, media[mi].second, opts_for(media[mi].first),
|
||||
&item, &why);
|
||||
if (s < 0 || !item) {
|
||||
*err = err_bad("messages[].content[]", "the media could not be used: " +
|
||||
(why.empty() ? std::string(rad_strerror(s))
|
||||
@@ -2069,12 +2164,30 @@ int parse_chat_request(const std::string& body, const OaiDeps& d, const OaiLimit
|
||||
|
||||
PromptInput p;
|
||||
if (media.empty()) {
|
||||
/* add_special is false: the template renders the model's special tokens, BOS included;
|
||||
* another would shift every position. */
|
||||
/* add_special is false: the template renders the model's special tokens; BOS is placed
|
||||
* below. */
|
||||
p.tokens = d.tok->encode(rendered, false, /*parse_special=*/true);
|
||||
p.text = rendered;
|
||||
} else {
|
||||
RAD_TRY(tokenize_with_media(rendered, d, media, MediaOpts{}, &p, err));
|
||||
MediaOpts mo;
|
||||
mo.image_mode = out->image_mode;
|
||||
mo.image_base_size = out->image_base_size;
|
||||
mo.image_size = out->image_size;
|
||||
RAD_TRY(tokenize_with_media(rendered, d, media, mo, &p, err));
|
||||
}
|
||||
/* A tokenizer that states add_bos gets exactly one BOS in front. The render drops a BOS the
|
||||
* template writes when add_bos is set (ChatTemplate, as llama.cpp's chat does, which leaves it
|
||||
* to the tokenizer), and some templates never write one, so it is added here unless the
|
||||
* prompt already starts with it. A media run's placeholders shift by one with it. */
|
||||
{
|
||||
const ITokenizer::VocabInfo vi = d.tok->vocab_info();
|
||||
if (vi.add_bos && vi.bos >= 0 && (p.tokens.empty() || p.tokens.front() != vi.bos)) {
|
||||
p.tokens.insert(p.tokens.begin(), vi.bos);
|
||||
if (p.media) {
|
||||
for (auto& pl : p.media->items) pl.tok += 1;
|
||||
p.media->layout();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (p.tokens.empty()) {
|
||||
*err = err_bad("messages", "the rendered prompt tokenised to nothing");
|
||||
|
||||
+7
-4
@@ -94,10 +94,8 @@ struct OaiRequest {
|
||||
|
||||
int n = 1;
|
||||
SamplingParams sp;
|
||||
/* The control vector, tri-state: -1 the request named no choice (the deployment's
|
||||
* runtime default applies), 0 it asked for the stock model, 1 for the loaded control vector.
|
||||
* Parsed from `control_vector` (or Strata's `experimental_speed_projection`); a deployment
|
||||
* with no vector refuses 1 rather than silently serving the stock model. */
|
||||
/* `control_vector`, tri-state: -1 not sent (the deployment's runtime default applies), 0 the
|
||||
* stock model, 1 the loaded control vector. A deployment with no vector refuses 1. */
|
||||
int control_vector = -1;
|
||||
int32_t max_tokens = 0;
|
||||
std::vector<std::string> stop;
|
||||
@@ -163,6 +161,11 @@ struct OaiRequest {
|
||||
/* /v1/embeddings: a soft-token budget for the request's images, 0 the server's. */
|
||||
int32_t image_tokens = 0;
|
||||
|
||||
/* `images_config`: which of the checkpoint's picture modes a request's pictures get, and the
|
||||
* sizes it states (Unlimited-OCR's gundam and base modes). 0 keeps the processor's choice
|
||||
* (mm::ImageMode::Default). */
|
||||
int32_t image_mode = 0, image_base_size = 0, image_size = 0;
|
||||
|
||||
int n_choices() const { return (int)prompts.size() * n; }
|
||||
};
|
||||
|
||||
|
||||
@@ -98,10 +98,6 @@ int unsettled_for(const std::string& delay) {
|
||||
return 6; /* medium */
|
||||
}
|
||||
|
||||
bool starts_with(const std::string& s, const std::string& p) {
|
||||
return s.size() >= p.size() && s.compare(0, p.size(), p) == 0;
|
||||
}
|
||||
|
||||
std::string rtrim(std::string s) {
|
||||
while (!s.empty() && std::isspace((unsigned char)s.back())) s.pop_back();
|
||||
return s;
|
||||
@@ -858,7 +854,7 @@ bool Server::realtime_loop(RealtimeSession& s, WsConn& ws) {
|
||||
const std::string text = detok(ids, /*flush=*/true);
|
||||
const size_t at = speech_transcript_start(f, text, forced, /*closed=*/true);
|
||||
const std::string transcript = rtrim(text.substr(std::min(at, text.size())));
|
||||
if (starts_with(transcript, t->sent)) delta(*t, transcript.substr(t->sent.size()));
|
||||
if (transcript.starts_with(t->sent)) delta(*t, transcript.substr(t->sent.size()));
|
||||
ojson o = event("conversation.item.input_audio_transcription.completed");
|
||||
o["item_id"] = t->id;
|
||||
o["content_index"] = 0;
|
||||
@@ -886,13 +882,13 @@ bool Server::realtime_loop(RealtimeSession& s, WsConn& ws) {
|
||||
const size_t a = speech_transcript_start(f, settled_text, forced, /*closed=*/false);
|
||||
const std::string settled = a == std::string::npos ? std::string()
|
||||
: rtrim(settled_text.substr(a));
|
||||
if (settled.size() > t->sent.size() && starts_with(settled, t->sent))
|
||||
if (settled.size() > t->sent.size() && settled.starts_with(t->sent))
|
||||
delta(*t, settled.substr(t->sent.size()));
|
||||
const std::string all_text = detok(ids, /*flush=*/false);
|
||||
const size_t b = speech_transcript_start(f, all_text, forced, /*closed=*/false);
|
||||
const std::string all = b == std::string::npos ? std::string()
|
||||
: rtrim(all_text.substr(b));
|
||||
const std::string tentative = starts_with(all, t->sent) ? all.substr(t->sent.size())
|
||||
const std::string tentative = all.starts_with(t->sent) ? all.substr(t->sent.size())
|
||||
: std::string();
|
||||
if (tentative != t->tentative) {
|
||||
ojson o = event("radiance.input_audio_transcription.tentative");
|
||||
|
||||
@@ -297,8 +297,8 @@ std::vector<std::string> Server::probe_reasoning_efforts() {
|
||||
if (text == plain) same.push_back(w);
|
||||
}
|
||||
/* The level a request naming none gets: the one level whose render is the same. A template may
|
||||
* spend it in a system prompt the client never sees (#113: Qwen3.8's is xhigh). Several, or
|
||||
* none, say nothing. */
|
||||
* spend it in a system prompt the client never sees (Qwen3.8's is xhigh). Several, or none,
|
||||
* say nothing. */
|
||||
if (same.size() == 1) template_default_effort_ = same[0];
|
||||
lim_.reasoning_efforts = set;
|
||||
return set;
|
||||
@@ -467,9 +467,7 @@ int Server::submit_all(const OaiRequest& r, std::vector<Generation>* gens, ApiEr
|
||||
}
|
||||
|
||||
/* The control vector: the request's own choice, else the deployment's runtime default. A
|
||||
* deployment with no vector refuses the on state by name -- serving the stock model while the
|
||||
* client believes it asked for the vector would be a silent lie about what produced the text.
|
||||
* (Naming: `control_vector` is the field, `experimental_speed_projection` its alias.) */
|
||||
* deployment with no vector refuses the on state by name rather than serve the stock model. */
|
||||
bool projection_on = false;
|
||||
{
|
||||
const bool named = r.control_vector >= 0;
|
||||
|
||||
@@ -327,7 +327,8 @@ private:
|
||||
HttpResponse handle_sessions(const HttpRequest& req);
|
||||
/* The control vector's runtime switch (dashboard.cpp): GET reports the state, POST
|
||||
* {"enabled": bool} sets the default for requests that name no choice. Guarded by the API key
|
||||
* like every other route but the health probes and the page. */
|
||||
* like every other route but the health probes and the page; without a key, POST answers
|
||||
* loopback clients only. */
|
||||
HttpResponse handle_control_vector(const HttpRequest& req);
|
||||
|
||||
HttpResponse error_response(const ApiError& e, const std::string& peer,
|
||||
|
||||
+1
-1
@@ -134,7 +134,7 @@ static size_t json_depth(const ojson& root) {
|
||||
/* The conversation with every system message merged, in order, into one at its head, or false
|
||||
* when that is the conversation already (none, or one leading) or a system message carries more
|
||||
* than text. The Chat Completions API places no constraint on system messages, while many
|
||||
* templates raise unless there is exactly one, first (#137). */
|
||||
* templates raise unless there is exactly one, first. */
|
||||
static bool lead_system(const ojson& messages, ojson* out) {
|
||||
if (!messages.is_array()) return false;
|
||||
std::string text;
|
||||
|
||||
@@ -41,14 +41,10 @@ bool occurs_inside(const std::string& inner, const std::string& outer) {
|
||||
return !inner.empty() && outer.size() > inner.size() && outer.find(inner, 1) != std::string::npos;
|
||||
}
|
||||
|
||||
bool starts_with(const std::string& s, const std::string& p) {
|
||||
return s.size() >= p.size() && s.compare(0, p.size(), p) == 0;
|
||||
}
|
||||
|
||||
/* Two delimiters an automaton scanning for both cannot report in start order: one begins or
|
||||
* occurs inside the other. */
|
||||
bool confusable(const std::string& a, const std::string& b) {
|
||||
return starts_with(a, b) || starts_with(b, a) || occurs_inside(a, b) || occurs_inside(b, a);
|
||||
return a.starts_with(b) || b.starts_with(a) || occurs_inside(a, b) || occurs_inside(b, a);
|
||||
}
|
||||
|
||||
std::string show(const std::string& s) { return nlohmann::json(s).dump(); }
|
||||
|
||||
@@ -72,8 +72,8 @@ void log_emit(Log l, const char* file, int line, const char* fmt, ...) {
|
||||
const char* base = std::strrchr(file, '/');
|
||||
base = base ? base + 1 : file;
|
||||
|
||||
/* A line longer than the stack buffer is formatted again in full: a trace row of many values
|
||||
* (RADIANCE_DUMP_HEAD) was cut at 4 KiB without a mark (#113). */
|
||||
/* A line longer than the stack buffer is formatted again in full, so a trace row of many
|
||||
* values (RADIANCE_DUMP_HEAD) is never cut at 4 KiB. */
|
||||
char buf[4096];
|
||||
std::string big;
|
||||
va_list ap, ap2;
|
||||
|
||||
@@ -12,8 +12,8 @@
|
||||
# - The trunk's linears (attention q/gate, k, v and output, the delta net's qkv/z and output, the
|
||||
# MLP's gate/up and down: the set Qwen's FP8 release quantises) as int8 with a bf16 scale per
|
||||
# (row, 128 of K), each 128 of K rotated by the unnormalised Hadamard before rounding and the
|
||||
# 1/128 kept in the scale (`transform=fwht128`). gemm_nt_q reads them at i8a8h, each linear
|
||||
# quantising its own input under the same rotation (had_quant_act_i8g). `clamp=sym` keeps the
|
||||
# 1/128 kept in the scale (`transform=fwht128`). gemm_nt_q reads them at i8a8h, against the
|
||||
# input quantised under the same rotation (had_quant_act_i8g's rule). `clamp=sym` keeps the
|
||||
# codes in -127..127, the range the int8 kernels are written for. Weight error 6.3e-3 relative.
|
||||
# - The delta net's a/b projections, the norms, the embedding and the vision tower stay bf16, as
|
||||
# in Qwen's FP8 release.
|
||||
|
||||
@@ -0,0 +1,24 @@
|
||||
# unlimited-ocr-bf16.recipe -- baidu/Unlimited-OCR from its bf16 checkpoint, served at the
|
||||
# checkpoint's own precision.
|
||||
#
|
||||
# rad-convert <Unlimited-OCR checkpoint> --recipe data/recipes/unlimited-ocr-bf16.recipe \
|
||||
# -o unlimited-ocr-bf16.rad
|
||||
#
|
||||
# No rules: every decoder weight is plain bf16 as the checkpoint ships it, and the bf16 plugin
|
||||
# (arch/unlimitedocr_bf16) probes the first routed expert, reads the plain encoding and serves the
|
||||
# experts through the bf16 grouped GEMM. The checkpoint carries no quantization_config.
|
||||
#
|
||||
# The container carries the whole checkpoint the plugin's name map covers: the 12-layer Llama-MoE
|
||||
# trunk and its tied head, and the DeepEncoder vision tower (sam_model.*, vision_model.*,
|
||||
# projector.layers.*, image_newline, view_seperator) at the checkpoint's bf16.
|
||||
#
|
||||
# Two shapes the map re-reads as GEMM weights: SAM's patch_embed.proj.weight [768, 3, 16, 16] as
|
||||
# [768, 768] (one bf16 plane reshaped), and the bias-free 3x3 convolutions (neck.2, net_2, net_3)
|
||||
# as [cout, cin*9], which conv2d_unfold + gemm_nt consume. Everything else is copied unchanged.
|
||||
#
|
||||
# Quantisation follow-ups (after P5) get their own recipes: the 64-expert MoE is the qwen4exp
|
||||
# w4/w4nl64 tier's shape (moe_intermediate_size 896 = 7 x 128 scale groups, n_embd 1280 = 10 x 128
|
||||
# -- whole scale blocks both ways), with the tied 331 MB head and the vision tower kept bf16.
|
||||
|
||||
# Nothing here is quantised: a recipe's rules are PATTERN QUANTISER pairs, and a weight no rule
|
||||
# matches keeps the checkpoint's own encoding (bf16 for every tensor here).
|
||||
@@ -0,0 +1,64 @@
|
||||
{#- Unlimited-OCR is a single-shot document parser: it expects the picture marker(s) followed by
|
||||
the reference instruction, e.g. "<__media__>document parsing." (the server replaces each
|
||||
marker with a picture's token run). Chat clients send the picture plus arbitrary text, often
|
||||
nothing, and resend earlier turns including their pictures. A parser without its start
|
||||
instruction free-runs like a language model and first emits prose (the Chinese/Russian
|
||||
preamble seen from LibreChat), and text from earlier turns or a system message would be
|
||||
concatenated into the prompt. This template keeps every picture marker (the server requires
|
||||
the rendered prompt to account for every picture in the request) and the final user turn's
|
||||
text, drops other text, and supplies the reference instruction when the final turn carries
|
||||
none, for any number of pictures: one is "document parsing.", several are "Multi page
|
||||
parsing." -#}
|
||||
{%- set ns = namespace(last=none, at=-1, media=0, text=false) -%}
|
||||
{%- for message in messages -%}
|
||||
{%- if message['role'] == 'user' -%}
|
||||
{%- set ns.last = message -%}
|
||||
{%- set ns.at = loop.index0 -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- if ns.last is not none -%}
|
||||
{%- if ns.last['content'] is string -%}
|
||||
{%- for piece in ns.last['content'].split('<__media__>') -%}
|
||||
{%- if not loop.last -%}{%- set ns.media = ns.media + 1 -%}{%- endif -%}
|
||||
{%- if ((piece | replace('', '')) | trim) != '' -%}{%- set ns.text = true -%}{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- else -%}
|
||||
{#- The OpenAI parts form counts the same way: media from the marker parts, text from any
|
||||
non-empty text part (a client's U+FFFC object placeholder is whitespace). -#}
|
||||
{%- for part in ns.last['content'] -%}
|
||||
{%- if part['type'] == 'media_marker' -%}
|
||||
{%- set ns.media = ns.media + 1 -%}
|
||||
{%- elif part['type'] == 'text' and ((part['text'] | default('', true) | replace('', '')) | trim) != '' -%}
|
||||
{%- set ns.text = true -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
{%- for message in messages -%}
|
||||
{%- set mi = loop.index0 -%}
|
||||
{%- if message['content'] is string -%}
|
||||
{%- set c = message['content'] -%}
|
||||
{%- if mi == ns.at -%}
|
||||
{{- c | replace('', '') -}}
|
||||
{%- else -%}
|
||||
{%- for piece in c.split('<__media__>') -%}
|
||||
{%- if not loop.last -%}<__media__>{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endif -%}
|
||||
{%- else -%}
|
||||
{%- for part in message['content'] -%}
|
||||
{%- if part['type'] == 'media_marker' -%}<__media__>
|
||||
{%- elif part['type'] == 'text' and mi == ns.at and ns.last is not none -%}{{- part['text'] -}}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{%- endif -%}
|
||||
{%- endfor -%}
|
||||
{#- The instruction block serves both content forms: ns.media/ns.text above scanned the final
|
||||
turn whichever it was. Output is whitespace-tight: every tag trims, the newline after
|
||||
"Multi page parsing." is eaten by the next tag's `{%-`, and the rendered prompt ends with
|
||||
the instruction verbatim -- keep the trims when reformatting this block. -#}
|
||||
{%- if ns.last is not none and not ns.text -%}
|
||||
{%- if ns.media > 1 -%}Multi page parsing.
|
||||
{%- elif ns.media == 1 -%}document parsing.
|
||||
{%- endif -%}
|
||||
{%- endif -%}
|
||||
@@ -32,6 +32,7 @@ services:
|
||||
memlock: -1
|
||||
volumes:
|
||||
- ${RADIANCE_MODELS:?set RADIANCE_MODELS in .env}:/models:ro
|
||||
- ${RADIANCE_CHAT_TEMPLATES:-../chat-templates}:/chat-templates:ro
|
||||
# A server finishes the step in flight and releases the cards on SIGTERM.
|
||||
stop_grace_period: 60s
|
||||
healthcheck:
|
||||
|
||||
@@ -7,12 +7,12 @@
|
||||
# generation_config; thinking is switched per request (chat_template_kwargs).
|
||||
#
|
||||
# --tp 4 over four cards; chained launches, the weight reads beside the collectives and the prefill
|
||||
# overlap turn themselves on there (each has its RADIANCE_* override for an A/B, none needed here).
|
||||
# overlap turn themselves on there.
|
||||
# A prompt alone takes 8192-token prefill chunks; beside other users a chunk takes at most 512
|
||||
# tokens of a step, with one decode-only step after it, so a long prompt holds the others up by a
|
||||
# fraction of a chunk rather than all of it. 16 sequences, as measured below.
|
||||
#
|
||||
# On 4x R9700 (PCIe 4.0 x16), 2026-10-20: one user 390 code / 288 prose / 208 story tok/s, and
|
||||
# On 4x R9700 (PCIe 4.0 x16): one user 390 code / 288 prose / 208 story tok/s, and
|
||||
# 590 after a 6442-token prompt (prefill 5962 tok/s); 302 / 512 / 658 / 835 / 981 tok/s aggregate
|
||||
# at 1 / 2 / 4 / 8 / 16 users (BetterBench, thinking off).
|
||||
#
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
# Unlimited-OCR (baidu/Unlimited-OCR), bf16, as data/recipes/unlimited-ocr-bf16.recipe builds it:
|
||||
# a 12-layer Llama-MoE trunk over the DeepEncoder vision tower (SAM + CLIP + projector, layout
|
||||
# tokens included), for document parsing through /v1/chat/completions. One card, RADIANCE_GPU.
|
||||
#
|
||||
# The checkpoint expects a 128-token generated-token ring, so the plugin declares RAD_KV_RING and
|
||||
# the request is kept out of prefix reuse. The towers live on the card (the default placement).
|
||||
# Whole-server footprint is ~7 GiB, so this service needs the card to itself: stop the other
|
||||
# model's compose file first (see common.yaml).
|
||||
#
|
||||
# gundam mode (the default for a single picture) crops a picture larger than 640 px into 640-px
|
||||
# tiles plus the 1024-px global view; base mode is one 640-px page (multi-page documents send one
|
||||
# image per page). `images_config` on the request selects a mode and restates its sizes.
|
||||
name: radiance-unlimited-ocr
|
||||
services:
|
||||
radiance:
|
||||
extends: { file: common.yaml, service: radiance }
|
||||
container_name: radiance-unlimited-ocr
|
||||
environment:
|
||||
ROCR_VISIBLE_DEVICES: "${RADIANCE_GPU:-0}"
|
||||
command: >
|
||||
--model /models/unlimited-ocr-bf16.rad
|
||||
--host :: --port ${PORT:-8000} --api-key ${RADIANCE_API_KEY:?set RADIANCE_API_KEY in .env}
|
||||
--tp 1 --max-num-seqs 8 --max-model-len 32768 --kv-cache-dtype fp8
|
||||
--gpu-headroom-mib 96
|
||||
--override-chat-template /chat-templates/unlimited-ocr-parser.jinja
|
||||
Loaded 100 of 210 files, more files were not shown because too many files have changed in this diff.
Show more
Reference in new issue
Block a user