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
+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
|
||||
Reference in new issue
Block a user