Compare commits

...
16 Commits
Author SHA1 Message Date
Deadcode ac79f4dc8a radiance 1.2.2
- Static YaRN for the Qwen rotary paths (#37): a container whose config names YaRN gets it in
  attention, the QSA index keys and a DFlash2 drafter; one reader for every rotary type, and a
  LLaMA container whose type is not served (llama3, longrope, dynamic) is refused by name.
- --rope-scaling yarn:FACTOR[:ORIG] (#38) writes YaRN over a container's own rotary keys at load,
  no reconvert; the persisted prefix cache's fingerprint carries the resolved rotary.
- An uneven world's cheaper rank (#36) pages the common token count and gives the rest of its
  VRAM to its experts; a plan and pool that disagree refuse to start.
- MoE prefill (#35): wide gather, parallel scan and run-map prefix, 256-column down tile, early
  weight loads -- by rule, bit-identical.
- MoE decode (#34): the sorted operand's own down kernel, its column tiles by routed rows.
- --draft-window fixed|adaptive (#24): a per-sequence draft window priced by measured step time,
  one head depth per step over the batch; fixed stays the default. New metric
  radiance:draft_position_accepted_total and Grafana panels.
- Out-of-tree plugin builds compile to the tree's device code from any build directory.
2026-10-07 12:37:53 +02:00
baKon 6fa7707dff serve: --rope-scaling writes static YaRN over a container's own rotary keys
yarn:FACTOR[:ORIG] (or none) is written at load into the rotary object yarn_from takes first --
for a Qwen3.8 container text_config.rope_parameters, which already says default, so YaRN written
beside it would never be read -- and resolved and checked exactly as a converted container's is.
An existing container serves past its trained context with no reconvert; a DFlash2 drafter gets
the same factor over its own trained length; a checkpoint's own YaRN has its factor replaced and
its stale attention_factor/mscale dropped; linear or other explicit types are refused. Startup
names the rotary's reach and warns when --max-model-len is past it, and a persisted prefix cache
written under another --rope-scaling is not reused. core/format/rope_override.h is held to
yarn_from in tests/yarn_test.cpp.
2026-10-07 11:13:46 +02:00
keptn42 ee5fcf1024 moe_gemm_q decode form: the sorted operand's own kernel, a block a run tile and G column tiles
At 16 sequences the (tile, run) grid gives down 25 600 blocks. Many find no
run, the others stage 4-8 KB of weight behind a search and a barrier pair,
and a run that crosses a 16-row tile is read twice. R4D_MOE_DOWN2=1 sends
down's decode-form launch to moe_down_dec_kernel: one block per 16-row tile
of a run, found among all runs in one round trip, and G 64-column tiles a
block whose passes form one pipeline. G follows the routed rows (1 below
200, 2 below 480, 4 above) or R4D_MOE_DOWN2_G. Bit-identical, off by
default. 16 concurrent: 36.4 -> 33.9 ms a step.
2026-10-07 11:13:46 +02:00
keptn42 432b50d7dd deploy/grafana: the adaptive draft window, verifies by draft depth
Two panels for RADIANCE_DRAFT_ADAPT: the mean window of the running
sequences (a gap while none runs) and the share of verifies by the drafts
they carried.

Conditional acceptance by position is now accepted(j) / reached(j). The
old reached(j+1) / reached(j) needs every verify to carry the same depth;
on an adaptive instance it showed 0.24 at position 2 where the engine's
own ratio was 0.72, and the last-position series is no longer defined.
2026-10-07 11:10:19 +02:00
keptn42 32cdaa5cc7 metrics: count each draft position's acceptances
radiance:draft_position_accepted_total{position}, next to the reach. At a
fixed depth the next position's reach is this position's acceptances, so
reached(j+1) / reached(j) gives the conditional acceptance over a window.
Under the adaptive window a verify can end at j with j taken, and that
ratio drops wherever windows end; accepted(j) / reached(j) does not.
2026-10-07 11:10:19 +02:00
keptn42 d579bd7d45 docs/GUIDE: the adaptive draft window, its metrics and its environment 2026-10-07 11:10:19 +02:00
keptn42 1e27172c14 draft: the adaptive window is the serial drafter's; a block drafter keeps its depth
RADIANCE_DRAFT_ADAPT prices a draft as one more round of the head. A block
drafter proposes its whole block in one pass, so it is not that trade; with
a block drafter the engine now turns the policy off before the first step
and says so. New sched_test case.
2026-10-07 11:10:19 +02:00
keptn42 76727fa050 draft: cap every adaptive window under load (RADIANCE_DRAFT_ADAPT_BUSY)
The cost table prices a step at one sequence. Under load every row a step
adds is expert bandwidth its neighbours wait on, and the adaptive window
lost 4 % at 8 concurrent requests. With RADIANCE_DRAFT_ADAPT_BUSY=N and
more than N sequences running, every window is capped at
RADIANCE_DRAFT_ADAPT_BUSY_DEPTH (default 3); the estimates keep learning.
The count is taken once a cycle and held to its end, so the plan, the
rounds, expect_draft and set_draft see one cap. Unset, nothing changes.
2026-10-07 11:10:19 +02:00
keptn42 82da8eab69 draft: an adaptive draft window per sequence (RADIANCE_DRAFT_ADAPT)
One depth for every request is too shallow for code and JSON and too deep
for prose. With RADIANCE_DRAFT_ADAPT=1, --num-speculative-tokens becomes
the ceiling and each sequence drafts into the window d that maximises
E(d)/T(d): the tokens a step is expected to emit from the sequence's own
smoothed acceptance at each position, over the step's cost
(RADIANCE_DRAFT_COST, depth:ms pairs). The serial head runs as many rounds
as the deepest window in the step. A window moves only past a hysteresis
and a hold, since a new window is a new pass shape. Acceptance is
unchanged. /metrics gains radiance:draft_depth_adaptive and
radiance:draft_verify_depth_total{depth} while it is on. Unset, nothing
changes. Greedy at up to 6 against fixed 3: code +7.7 %, JSON +16.3 %.
2026-10-07 11:10:19 +02:00
keptn42 73691a1189 r4d_selftest: the R4D_MOE_PF2 aligned-form pass at every class's own geometry, fp8a8 included
moe_q4_gemm holds the run-aligned form under parts 16 and 64 to the form
without them as well, so the block-fp8 instance of the early weight issue
and the narrow classes' pad tiles are compared byte for byte too. Past 512
experts the launcher builds no run map and there is no aligned launch, so
the pass is skipped there rather than failed.
2026-10-07 11:09:45 +02:00
keptn42 92eb44619b moe_gemm_q run-aligned form: the first pass's weight at the map read (R4D_MOE_PF2 64)
In the run-aligned form the map entry names the block's expert, yet the
weight loads wait behind the token load, a barrier, the live count and the
table entry. Part 64 issues the rows and the live count first, then the
table entries and the first pass's weight through the uniform global base,
all unconditional, so the weight stays in flight while the tokens arrive.
The same bytes go to the same registers and LDS slots: bit-identical.
2026-10-07 11:09:45 +02:00
keptn42 e31be583a9 moe prefill forms behind R4D_MOE_PF2: wide gather, parallel scan and map prefix, 256-column down
In a prefill chunk moe_gather loads two bytes a lane and waits on every
slot, moe_scatter scans on one thread, and so does the run map's prefix.
R4D_MOE_PF2=1, or a mask of the parts: 2 a wave a token and 16 bytes a
lane with every slot's row in flight, 4 its column groups last first, 8 a
parallel scan with the tail folded into the placement, 16 the map prefix
in parallel, 32 a 256-column run-aligned down tile (w4). Each part keeps
its sums in the same order or is integers: bit-identical. Unset, every
launch is as before.
2026-10-07 11:09:45 +02:00
baKon 33778b2b8c budget: an uneven world's cheaper rank pages the common tokens and keeps its experts
The resolver derives one split, the dearest rank's, for every card, and one
block table serves every rank. An attention-zero rank keeps no attention cache:
at TP3 on Flash-Next it pages the common 1.45M tokens in ~1.8 GiB of its
10.6 GiB KV pool, the rest is an address reservation nothing ever commits or
lends, and 1091 of its experts can never reach the card even with the cache
idle.

Such a rank now gets a KV pool that pages exactly the common token count (the
new KVManager::pool_mib_for_tokens, the inverse of paged_tokens, plus a 64 MiB
margin) and the difference in its weights pool, no further than every weight
resident. The per-rank split reaches BOTH readers of the resolved sizes --
Pools::configure and the planner -- so the grown pool is planned into. The
token count, the carve, the loan and the dearest ranks' pools are unchanged;
configure_kv names it if a re-sized pool ever binds.

Only a derived split under expert_tiered is re-split: a stated pool is the
operator's, and under auto a fully resident rank would choose all_vram while
its peers spill. Where every rank's cache costs the same -- every world the
heads divide -- no rank qualifies and every rank takes cfg_ as before.
2026-10-07 11:09:36 +02:00
hazyumps 6fd7421f79 Fix rotary compatibility edge cases and document Qwen qualification 2026-10-07 11:09:27 +02:00
hazyumps 59d36ae928 Extend YaRN to Qwen4 attention and compressed index keys 2026-10-07 11:09:27 +02:00
hazyumps 2af7fa4022 Add static YaRN to Qwen rotary paths with independent CPU and ROCm vectors 2026-10-07 11:09:27 +02:00
71 changed files with 5636 additions and 236 deletions

No files matched your search

+1 -1
View File
@@ -2,7 +2,7 @@ cmake_minimum_required(VERSION 3.21)
# VERSION is what /version reports and what a client checks compatibility against. It is NOT the
# ABI version -- that lives in abi/rad_abi.h and is read out of the header below, because
# a plugin contract and a server release do not move together.
project(radiance VERSION 1.2.1 LANGUAGES C CXX)
project(radiance VERSION 1.2.2 LANGUAGES C CXX)
set(CMAKE_CXX_STANDARD 20)
set(CMAKE_CXX_STANDARD_REQUIRED ON)
+6 -4
View File
@@ -7,10 +7,12 @@ Written by Deadcode, with contributions from tcclaviger (the N-rank all-reduce k
and the draft refill on a prefix hit), goodman-b (four-rank tensor parallelism
for Qwen3.8-Flash-Next), keptn42 (the four-rank all-reduce served in place, the fused four-rank
writes, the n-gram table in RAM, the four-class expert split, the Grafana dashboard, the routed
GEMM's decode loads and run search, the gated residual's prefill read form and row groups, and
the fused router launch), mechkbfan (the token embedding in the pinned host pool), Code000 (the
n-gram gather on the card and the MTP head's history-pass skip) and baKon (three-rank tensor
parallelism, serving any world size from the shipped container, and the request log).
GEMM's decode loads and run search, the gated residual's prefill read form and row groups, the
fused router launch, the adaptive draft window, the MoE prefill forms and the sorted operand's
decode kernel), mechkbfan (the token embedding in the pinned host pool), Code000 (the n-gram
gather on the card and the MTP head's history-pass skip), baKon (three-rank tensor parallelism,
serving any world size from the shipped container, the request log, an uneven world's per-rank
KV and weights split, and --rope-scaling) and hazyumps (static YaRN for the Qwen rotary paths).
This product includes software from the following projects, each under the MIT License. The
license text is in the file named beside each.
+4
View File
@@ -39,6 +39,10 @@ typedef struct RadModelMeta {
float rms_eps;
float rope_theta;
/* Always 1. A rotary's scaling is a TYPE with parameters -- linear, YaRN, llama3, longrope --
* and it is carried in the free-form keys below (rope_parameters.* / rope_scaling.*, with
* text_config.* and draft.* forms), which arch/common/rad_arch.h's yarn_from reads and refuses
* by name. A bare factor here would read every scheme as a linear position divide. */
float rope_scale;
/* Free-form key/value from the container header, for anything the struct above does not
+49
View File
@@ -0,0 +1,49 @@
#ifndef RAD_YARN_H
#define RAD_YARN_H
/* Static YaRN coefficients. The architecture resolves the correction bounds using
* the ORIGINAL training length, never the deployment/table length. Kernels share
* the resolved coefficients so direct and table-backed RoPE cannot disagree. */
#include "rad_plugin.h"
#include <cmath>
#if defined(__HIPCC__)
#define RAD_YARN_HD __host__ __device__
#else
#define RAD_YARN_HD
#endif
struct RadYarn {
float factor = 0.0f; /* zero: keep the legacy arithmetic exactly */
float low = 0.0f;
float high = 0.0f;
float magnitude = 1.0f;
RAD_YARN_HD float frequency(float inv, int i) const {
if (factor == 0.0f) return inv;
const float width = high == low ? 0.001f : high - low;
const float ramp = fminf(1.0f, fmaxf(0.0f, ((float)i - low) / width));
/* Keep the blend order used by the reference YaRN implementation. */
const float mask = 1.0f - ramp;
return (inv / factor) * (1.0f - mask) + inv * mask;
}
};
inline RadYarn rad_yarn_args(const RadArgs* a) {
const float factor = (float)rad_args_getf_or(a, "yarn_factor", 0.0);
/* Disabled YaRN ignores every auxiliary coefficient on every backend. */
if (factor == 0.0f) return {};
return { factor,
(float)rad_args_getf_or(a, "yarn_low", 0.0),
(float)rad_args_getf_or(a, "yarn_high", 0.0),
(float)rad_args_getf_or(a, "yarn_magnitude", 1.0) };
}
inline bool rad_yarn_valid(const RadYarn& y) {
return std::isfinite(y.factor) && (y.factor == 0.0f ||
(y.factor >= 1.0f && std::isfinite(y.low) && std::isfinite(y.high) &&
y.high >= y.low && std::isfinite(y.magnitude) && y.magnitude > 0.0f));
}
#undef RAD_YARN_HD
#endif
+126 -3
View File
@@ -16,6 +16,7 @@
#include "rad_builder.h"
#include "rad_device.h"
#include "rad_runtime.h"
#include "rad_yarn.h"
#include <cstdarg>
#include <cstdio>
@@ -626,6 +627,7 @@ struct Geom {
float wadd_qk = 0.0f;
float theta = 1e6f;
float rope_scale = 1.0f;
RadYarn yarn;
/* M-RoPE: the checkpoint's `mrope_section`, when it has one. A model whose rotary has several
* position components declares `rope` with `rope_mode` and these sections and hands it
* RadBatch::rope_pos; empty, the rotary is one-component NeoX over `positions`. Stored here
@@ -789,7 +791,7 @@ inline int geom_from(Geom& g, const RadModelMeta* m, const RadBuildCtx* c,
g.wire_min_bytes = c->tp_wire_min_bytes;
g.eps = m->rms_eps;
g.theta = m->rope_theta;
g.rope_scale= m->rope_scale ? m->rope_scale : 1.0f;
g.rope_scale= 1.0f; /* yarn_from reads the model's rotary scaling */
g.dtype = dtype;
g.act_dtype = act_dtype;
{
@@ -1023,19 +1025,140 @@ inline RadOperand rope_posmc(const Geom& g, const RadBatch* b, int64_t T) {
* cannot rotate. */
inline bool rope_mixed(const RadBatch* b) { return b->rope_pos && b->rope_mixed; }
/* A rotary op declared with the geometry's YaRN coefficients appended. A model without YaRN declares
* exactly the parameters it was given, so its op identities and tune keys are unchanged. */
inline rad_op decl_rotary(RadBuilder* b, const Geom& g, const char* name,
const RadParam* params, int n, const rad_weight* weights, int nw) {
if (g.yarn.factor == 0.0f) return rad_decl_op(b, name, params, n, weights, nw);
std::vector<RadParam> p(params, params + n);
p.push_back(RAD_F64("yarn_factor", g.yarn.factor));
p.push_back(RAD_F64("yarn_low", g.yarn.low));
p.push_back(RAD_F64("yarn_high", g.yarn.high));
p.push_back(RAD_F64("yarn_magnitude", g.yarn.magnitude));
return rad_decl_op(b, name, p.data(), (int)p.size(), weights, nw);
}
/* THE ONE READER OF A MODEL'S ROTARY SCALING. Every architecture calls it after geom_from, for the
* target ("") and for a drafter with a config of its own ("draft."), and it sets `g.rope_scale` and
* `g.yarn` from the free-form keys and from nothing else. RadModelMeta::rope_scale is not read: a
* factor without its type would be a linear position divide for a scheme that is not one.
*
* The object read is the first of `text_config.rope_parameters.`, `rope_parameters.`,
* `text_config.rope_scaling.`, `rope_scaling.` (a drafter: `draft.rope_parameters.`,
* `draft.rope_scaling.`) that names a type in `rope_type` or `type`; a multimodal target's
* text_config is authoritative. core/format/rope_override.h writes --rope-scaling into the same
* object, found in the same order.
*
* default, mrope no scaling (`mrope` is the legacy Qwen2-VL spelling of default + sections)
* linear positions divided by `factor`
* yarn static YaRN: frequencies blended over the correction range that `factor`,
* `original_max_position_embeddings`, `beta_fast`/`beta_slow` and `truncate`
* give, cos/sin scaled by `attention_factor` (default 1 + 0.1 ln factor). The
* factor is the config's, read as vLLM and transformers read it.
*
* Anything else -- llama3, longrope, dynamic -- is refused by name, as is YaRN's `mscale` form. A
* refusal leaves the geometry as it was. */
inline int yarn_from(Geom& g, const RadModelMeta* meta, const char* prefix, int64_t rot) {
const std::string root(prefix);
const char* who = root.empty() ? "target" : "draft";
const std::vector<std::string> homes = root.empty()
? std::vector<std::string>{"text_config.rope_parameters.", "rope_parameters.",
"text_config.rope_scaling.", "rope_scaling."}
: std::vector<std::string>{root + "rope_parameters.", root + "rope_scaling."};
std::string home, type_key;
const char* type = nullptr;
for (const auto& h : homes) {
for (const char* t : {"rope_type", "type"})
if ((type = rad_meta_gets(meta, (h + t).c_str(), nullptr))) { type_key = h + t; break; }
if (type) { home = h; break; }
}
if (!type || !std::strcmp(type, "default") || !std::strcmp(type, "mrope")) {
g.yarn = {};
g.rope_scale = 1.0f;
return RAD_OK;
}
auto get = [&](const char* key, double fallback) {
const char* text = rad_meta_gets(meta, (home + key).c_str(), nullptr);
if (!text) return fallback;
char* end = nullptr;
const double value = std::strtod(text, &end);
if (end == text) return (double)NAN;
while (*end == ' ' || *end == '\t' || *end == '\n') ++end;
return *end ? (double)NAN : value;
};
if (!std::strcmp(type, "linear")) {
const double factor = get("factor", 0.0);
const float scale = (float)factor;
if (!std::isfinite(factor) || factor <= 0.0 || !std::isfinite(scale) || scale <= 0.0f) {
fprintf(stderr, "radiance: %s linear rotary scaling (%s) needs a finite factor > 0\n",
who, home.c_str());
return RAD_E_INVAL;
}
g.yarn = {};
g.rope_scale = scale;
return RAD_OK;
}
if (std::strcmp(type, "yarn")) {
fprintf(stderr, "radiance: %s rotary type '%s' (%s) is not implemented; default, linear "
"and yarn are\n", who, type, type_key.c_str());
return RAD_E_UNSUPPORTED;
}
/* `truncate` is a JSON boolean, which the converter writes as 1 or 0; true and false spelled
* out are the same answer. */
double truncate = 1.0;
if (const char* t = rad_meta_gets(meta, (home + "truncate").c_str(), nullptr))
truncate = !std::strcmp(t, "true") ? 1.0 : !std::strcmp(t, "false") ? 0.0 : get("truncate", 1.0);
const double factor = get("factor", 0.0), original = get("original_max_position_embeddings", 0.0);
const double fast = get("beta_fast", 32.0), slow = get("beta_slow", 1.0);
const double magnitude = get("attention_factor", factor > 1.0 ? 1.0 + 0.1 * std::log(factor) : 1.0);
if (!std::isfinite(factor) || factor < 1.0 || !std::isfinite(original) || original < 1.0 ||
original != std::floor(original) || (truncate != 0.0 && truncate != 1.0) ||
!std::isfinite(fast) || !std::isfinite(slow) || slow <= 0.0 || fast < slow ||
!std::isfinite(magnitude) || magnitude <= 0.0 || !std::isfinite(g.theta) || g.theta <= 1.0f ||
rot < 2 || (rot & 1)) {
fprintf(stderr, "radiance: %s YaRN (%s) needs a finite factor >= 1, an integral "
"original_max_position_embeddings > 0, beta_fast >= beta_slow > 0, "
"attention_factor > 0 and truncate true or false\n", who, home.c_str());
return RAD_E_INVAL;
}
/* mscale variants are a different contract; never silently ignore them. */
for (const char* k : {"mscale", "mscale_all_dim"})
if (rad_meta_gets(meta, (home + k).c_str(), nullptr)) {
fprintf(stderr, "radiance: %s YaRN %s%s is not implemented; attention_factor is\n",
who, home.c_str(), k);
return RAD_E_UNSUPPORTED;
}
auto correction = [&](double beta) {
return rot * std::log(original / (beta * 2.0 * 3.14159265358979323846)) /
(2.0 * std::log((double)g.theta));
};
double low = correction(fast), high = correction(slow);
if (truncate != 0.0) { low = std::floor(low); high = std::ceil(high); }
const RadYarn y = {(float)factor, (float)std::max(0.0, low),
(float)std::min((double)rot - 1, high), (float)magnitude};
if (!rad_yarn_valid(y)) {
fprintf(stderr, "radiance: %s YaRN (%s) resolves to an empty correction range\n", who,
home.c_str());
return RAD_E_INVAL;
}
g.yarn = y;
g.rope_scale = 1.0f; /* YaRN blends frequencies; it does not divide positions. */
return RAD_OK;
}
/* `rope` declared for the geometry's rotary: M-RoPE's mode and sections when the model has them,
* `mode` otherwise. */
inline rad_op decl_rope(RadBuilder* b, const Geom& g, int64_t rows, int64_t head_dim,
int64_t n_head, int64_t n_head_kv, int64_t rot, const char* mode) {
if (g.rope_mc)
return RAD_OP(b, "rope",
return decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", g.rope_mode), RAD_INT("rotary_dim", rot),
RAD_STR("sections", g.rope_sections)),
RAD_NOWEIGHTS);
return RAD_OP(b, "rope",
return decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, rows), RAD_INT("head_dim", head_dim),
RAD_INT("n_head", n_head), RAD_INT("n_head_kv", n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
+1 -1
View File
@@ -121,7 +121,7 @@ inline int AttnFP8::declare(RadBuilder* b, Names& nm, const Geom& geom, int l, r
RAD_SHARD_ROW, grp_layer(l), { src.q, src.k, src.v }, w.h, w.qkv,
0, { q_dim, kv_dim, kv_dim }));
op_rope = rw(b, RAD_OP(b, "rope",
op_rope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, g.max_tok), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", g.n_head_kv),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
+3 -3
View File
@@ -538,7 +538,7 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
* V heads that follow alone, so a K-only tensor is described by n_head = n_head_kv and
* n_head_kv = 0: all the heads there are rotate, none follow them. Weightless, so one op
* serves every layer. */
op_crope = rw(b, RAD_OP(b, "rope",
op_crope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
@@ -712,14 +712,14 @@ inline int Dflash2::declare(RadBuilder* b, Names& nm, const Geom& geom, const Co
RAD_WEIGHTS(w_fcb[i])),
{w.h, w.coef}, {w.h2});
}
op_qrope = rw(b, RAD_OP(b, "rope",
op_qrope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.q}, {w.q});
op_krope = rw(b, RAD_OP(b, "rope",
op_krope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
+3 -3
View File
@@ -508,7 +508,7 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
* THE POSITION IS THE COMMITTED TOKEN'S OWN, which is what makes the split passes equal the
* reference's one concatenated rope: it hands `k` the full position range and `q` only the
* last `q_len` of it, so a context row at absolute position p is rotated by p either way. */
op_crope = rw(b, RAD_OP(b, "rope",
op_crope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, crows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
@@ -667,14 +667,14 @@ inline int Dspark::declare(RadBuilder* b, Names& nm, const Geom& geom, const Con
{w.ffn.q, w.ffn.s}, {w.h.x});
}
op_qrope = rw(b, RAD_OP(b, "rope",
op_qrope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("mode", "neox")),
RAD_NOWEIGHTS),
{w.q}, {w.q});
op_krope = rw(b, RAD_OP(b, "rope",
op_krope = rw(b, decl_rotary(b, g, "rope",
RAD_PARAMS(RAD_RANGE("M", 1, qrows), RAD_INT("head_dim", g.head_dim),
RAD_INT("n_head", g.n_head_kv), RAD_INT("n_head_kv", 0),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
+2 -2
View File
@@ -269,7 +269,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
/* UNDER M-RoPE a block key rotates at its first token's three components, which qsa_work
* writes into a [work, 3] `bpos` when it is handed the step's rotary planes. */
op_bkey = g.rope_mc
? RAD_OP(b, "qsa_block_key",
? decl_rotary(b, g, "qsa_block_key",
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
RAD_INT("block_size", c.ratio),
@@ -278,7 +278,7 @@ inline int QsaIndexer::declare(RadBuilder* b, Names& nm, const Geom& geom, int l
RAD_STR("dtype", g.dtype), RAD_STR("mode", g.rope_mode),
RAD_STR("sections", g.rope_sections)),
RAD_WEIGHTS(w_kn))
: RAD_OP(b, "qsa_block_key",
: decl_rotary(b, g, "qsa_block_key",
RAD_PARAMS(RAD_RANGE("M", 1, c.max_work), RAD_INT("n", c.head_dim),
RAD_INT("ratio", c.ratio), RAD_INT("rotary_dim", c.rot),
RAD_INT("block_size", c.ratio),
+2 -1
View File
@@ -185,7 +185,6 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
rad_meta_getf(meta, "draft.rope_theta", 0.0));
dg.rope_scale = 1.0f;
/* PLAIN RMS NORM: the reference norms with Qwen3RMSNorm and the config says `model_type:
* qwen3`. It happens to agree with this MiniCPM5 target, and it is asked of the DRAFTER's
* config anyway -- two conventions in one process is exactly why this is a second Geom. */
@@ -201,6 +200,7 @@ static int declare_dspark(RadBuilder* b, const RadModelMeta* meta, const RadBuil
(long long)dg.head_dim, (long long)dg.n_ff_all, (double)dg.eps, (double)dg.theta);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
int s;
if ((s = divide_or_fail(dg.n_head_all, dg.world, "draft num_attention_heads", &dg.n_head)) < 0) return s;
if ((s = divide_or_fail(dg.n_head_kv_all, dg.world, "draft num_key_value_heads", &dg.n_head_kv)) < 0) return s;
@@ -431,6 +431,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
"%lld\n", (long long)m.n_rot, (long long)g.head_dim);
return RAD_E_INVAL;
}
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
/* ---- the KV cache. One group: every layer is full attention. */
RadKVGroupDecl fd{};
+2
View File
@@ -237,6 +237,8 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_INVAL;
}
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
/* The linear-attention geometry. llama.cpp maps the GGUF ssm keys onto these:
* ssm.state_size -> the key AND value head width, ssm.group_count -> key heads,
* ssm.time_step_rank -> value heads, ssm.inner_size -> value heads * value width. */
+3 -2
View File
@@ -339,7 +339,7 @@ static int declare_dflash2(RadBuilder* b, const RadModelMeta* meta, const RadBui
dg.eps = (float)rad_meta_getf(meta, "draft.rms_norm_eps", 0.0);
dg.theta = (float)rad_meta_getf(meta, "draft.rope_parameters.rope_theta",
rad_meta_getf(meta, "draft.rope_theta", 0.0));
dg.rope_scale = 1.0f;
RAD_ARCH_TRY(yarn_from(dg, meta, "draft.", dg.head_dim));
/* PLAIN RMS NORM. The drafter uses the ordinary norm where the trunk uses GemmaRMSNorm, and
* the checkpoint agrees rather than only vLLM -- rad_block_dflash2.h has the numbers. Two
* conventions in one process, which is exactly why this is a second Geom and not a flag. */
@@ -635,6 +635,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_INVAL;
}
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
GdnFP8::Config& gc = m.gcfg;
const int64_t n_head_k_all = meta_int2(meta, "qwen35.ssm.group_count",
"linear_num_key_heads", 0);
@@ -952,7 +953,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* which is why `aw.cos_sin` is cleared rather than left pointing at a plane nothing fills. Its
* band is the fused prologue's (qk_fuse_rows), so a step the prologue does not serve -- a
* prefill chunk, where the fill's grid is one block a TOKEN -- issues no fill either. */
m.op_rope_cs = rw(b, RAD_OP(b, "rope_table",
m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)), RAD_INT("rot", m.n_rot),
RAD_F64("theta", g.theta), RAD_F64("scale", g.rope_scale),
RAD_STR("dtype", "f32")),
+2 -1
View File
@@ -364,6 +364,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
return RAD_E_INVAL;
}
}
RAD_ARCH_TRY(yarn_from(g, meta, "", m.n_rot));
/* THERE IS NO BRING-UP SLICE, and the rule is worth stating: if a model ever arrives too large
* for the target device, the answer is a converter flag that writes a NAMED partial container
* -- not an environment variable that makes a full one silently mean something else. A slice
@@ -1000,7 +1001,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
* one step; the symptom is fluent output with one arm of the model reading the other's
* leftovers, which nothing downstream flags.
*/
m.op_rope_cs = rw(b, RAD_OP(b, "rope_table",
m.op_rope_cs = rw(b, decl_rotary(b, g, "rope_table",
RAD_PARAMS(RAD_RANGE("M", 1, qk_fuse_rows(g)),
RAD_INT("rot", m.n_rot), RAD_F64("theta", g.theta),
RAD_F64("scale", g.rope_scale), RAD_STR("dtype", "f32")),
+16
View File
@@ -97,6 +97,22 @@ function(rad_add_plugin name kind)
"because the language a project compiles in is the project's own decision.")
endif()
set_source_files_properties(${P_HIP_SOURCES} PROPERTIES LANGUAGE HIP)
# EVERY DEVICE SOURCE NAMES ITS OWN COMPILATION UNIT ID, from the plugin's name and the
# source's path inside the plugin's directory. Left to clang, the ID is a hash of the absolute
# input path, the output path and the command line, so one source built in two directories --
# the tree and an out-of-tree build of the same plugin -- gets two IDs. The ID becomes a symbol
# (__hip_cuid_<hash of it>) whose name is not of fixed length, and a longer one shifts the code
# object's read-only data and with it every PC-relative address .text forms into it: the same
# instructions, different bytes. Named from what identifies the unit and nothing about where it
# was built, the ID is the same wherever the plugin is built and still differs between any two
# sources, which is the property clang needs of it.
foreach(src ${P_HIP_SOURCES})
get_filename_component(_rad_abs "${src}" ABSOLUTE)
file(RELATIVE_PATH _rad_rel "${CMAKE_CURRENT_SOURCE_DIR}" "${_rad_abs}")
string(SHA256 _rad_cuid "${name}/${_rad_rel}")
string(SUBSTRING "${_rad_cuid}" 0 16 _rad_cuid)
set_property(SOURCE "${src}" APPEND PROPERTY COMPILE_OPTIONS "-cuid=${_rad_cuid}")
endforeach()
list(APPEND srcs ${P_HIP_SOURCES})
endif()
add_library(${name} MODULE ${srcs})
+34
View File
@@ -6,6 +6,7 @@
* (spec §6).
*/
#include "rad_core.h"
#include "format/rope_override.h"
#include "sample/host_ref.h"
#include "server/oai.h"
@@ -28,6 +29,15 @@ struct Flag {
const char* help;
};
/* Built from kDraftWindowDefault, so the default is stated in one place. Defined before the table
* that points at it: the two are initialised in this order. */
static const std::string g_draft_window_help =
std::string("fixed | adaptive: how many drafts each sequence carries. fixed drafts\n"
" --num-speculative-tokens every step; adaptive makes that\n"
" the ceiling and follows each sequence's acceptance and the\n"
" measured step cost (a serial draft head only). Default ") +
draft_window_name(kDraftWindowDefault);
static const Flag g_flags[] = {
{ "--model", "PATH", "the .rad container, or a checkpoint served as it stands" },
{ "--radiance-home", "DIRS", "where kernels/, architectures/ and quantizers/ live; several\n"
@@ -45,6 +55,8 @@ static const Flag g_flags[] = {
{ "--max-num-batched-tokens", "N", "the largest token count one step may carry" },
{ "--max-num-seqs", "N", "the largest number of sequences one step may carry" },
{ "--max-model-len", "N", "context bound; 0 takes the model's training context" },
{ "--rope-scaling", "SPEC", "yarn:FACTOR[:ORIG]: static YaRN over the container's own rotary\n"
"keys, no reconvert (docs/YARN.md); none: off" },
{ "--gpu-headroom-mib", "N", "VRAM left unclaimed on every card (default 96)" },
{ "--vram-weights-mib", "N", "the resident weight slab; 0 derives it from the card" },
@@ -98,6 +110,7 @@ static const Flag g_flags[] = {
{ "--num-speculative-tokens", "N", "speculative window; 0 disables. Default `auto`: the drafter's\n"
" own operating point, which the plugin states. A container\n"
" with no draft head is unaffected -- auto resolves to 0." },
{ "--draft-window", "MODE", g_draft_window_help.c_str() },
{ "--draft-model", "PATH", "NOT IMPLEMENTED -- merge the drafter at convert time" },
{ "--host", "ADDR", "listen address" },
@@ -380,6 +393,18 @@ int config_parse(int argc, char** argv, Config* c) {
else if (S("--max-num-batched-tokens")){ if (!(v = need(i))) return RAD_E_INVAL; c->max_tok = atoll(v); }
else if (S("--max-num-seqs")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_seqs = atoll(v); }
else if (S("--max-model-len")) { if (!(v = need(i))) return RAD_E_INVAL; c->max_ctx = atoll(v); }
else if (S("--rope-scaling")) {
if (!(v = need(i))) return RAD_E_INVAL;
/* Checked here, so a typo is a refusal at the command line and not a model served
* with its trained rotary at a length it cannot reach. */
RopeSpec rs;
if (!rope_spec_parse(v, &rs) || rs.kind == RopeSpec::Keep) {
RAD_ERR("--rope-scaling takes yarn:FACTOR (above 1) with an optional :ORIG trained "
"length, or none -- got '%s'", v);
return RAD_E_INVAL;
}
c->rope_scaling = v;
}
else if (S("--vram-weights-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_weights_mib = atoll(v); }
else if (S("--vram-kv-mib")) { if (!(v = need(i))) return RAD_E_INVAL; c->vram_kv_mib = atoll(v); }
/* --gpu-headroom takes the short name too: it is the flag an operator reaches for and
@@ -443,6 +468,15 @@ int config_parse(int argc, char** argv, Config* c) {
return RAD_E_INVAL;
}
}
else if (S("--draft-window")) {
if (!(v = need(i))) return RAD_E_INVAL;
if (!std::strcmp(v, "fixed")) c->draft_window = DraftWindow::Fixed;
else if (!std::strcmp(v, "adaptive")) c->draft_window = DraftWindow::Adaptive;
else {
RAD_ERR("--draft-window takes fixed or adaptive, not '%s'", v);
return RAD_E_INVAL;
}
}
else if (S("--draft-model")) {
/* REFUSED, NOT QUIETLY IGNORED. Accepting this flag and then serving the container's
* own drafter -- or none -- would hand the caller a server that is not the one they
+12
View File
@@ -93,6 +93,15 @@ private:
std::vector<std::thread> rank_threads_;
Config cfg_;
/* THE SPLIT EACH RANK ACTUALLY TAKES. Equal to cfg_ on every rank whose cache costs as much per
* token as the dearest rank's -- every rank of a world whose ranks all cost the same; a rank
* whose cache costs less (an attention-zero rank) gets a KV pool sized for the common token
* count and the difference in its weights pool. Engine::plan fills it, and every reader of the
* resolved pool sizes -- Pools::configure and the planner -- takes its rank's entry, never
* cfg_: a grown pool the planner never reads is an empty pool, and plan() refuses a rank whose
* plan and weights pool disagree. */
std::vector<Config> rank_cfg_;
int64_t kv_planned_tokens_ = 0; /* the common token count plan() sized the re-split pools for */
/* The model's source, one of the two. A container stays mapped for the life of the engine:
* the mapped and file tiers read it where it lies (spec §4.2). A checkpoint served directly
@@ -117,6 +126,9 @@ private:
int load_plugins();
int read_metadata();
int read_checkpoint_metadata();
/* --rope-scaling over the free-form keys, then the startup line and the context checks;
* runs on meta_kv_k_/meta_kv_v_ before their pointer arrays are built. */
int apply_rope_scaling();
int declare();
int plan();
/* --embedding-placement and --ngram-placement, resolved into Config before the card is split
+214 -18
View File
@@ -14,6 +14,7 @@
#include "device/device.h"
#include "device/directio.h"
#include "format/radfile.h"
#include "format/rope_override.h"
#include "format/share.h"
#include "format/table_copy.h"
#include "rad_plugin.h"
@@ -683,7 +684,9 @@ int Engine::read_metadata() {
meta_.n_expert_shared = geti("n_expert_shared", 0);
meta_.rms_eps = getf("rms_eps", 1e-6);
meta_.rope_theta = getf("rope_theta", 10000.0);
meta_.rope_scale = getf("rope_scale", 1.0);
/* 1 (abi/rad_builder.h): the rotary's scaling is read with its type from the free-form keys.
* An older container's `rope_scale` key holds the factor alone and is not read. */
meta_.rope_scale = 1.0f;
/* A container that says nothing about its own shape is refused HERE, by name, rather than at
* declare as an "invalid argument" from a plugin that was handed zeros. */
@@ -707,6 +710,7 @@ int Engine::read_metadata() {
default: meta_kv_v_.push_back(file_->str(kv.v.s)); break;
}
}
RAD_TRY(apply_rope_scaling());
meta_kv_kp_.clear(); meta_kv_vp_.clear();
for (auto& s : meta_kv_k_) meta_kv_kp_.push_back(s.c_str());
for (auto& s : meta_kv_v_) meta_kv_vp_.push_back(s.c_str());
@@ -741,6 +745,7 @@ int Engine::read_checkpoint_metadata() {
}
meta_kv_k_ = mo.keys;
meta_kv_v_ = mo.vals;
RAD_TRY(apply_rope_scaling());
meta_kv_kp_.clear(); meta_kv_vp_.clear();
for (auto& k : meta_kv_k_) meta_kv_kp_.push_back(k.c_str());
for (auto& v : meta_kv_v_) meta_kv_vp_.push_back(v.c_str());
@@ -754,6 +759,56 @@ int Engine::read_checkpoint_metadata() {
return RAD_OK;
}
/* --rope-scaling (format/rope_override.h): YaRN written into the container's own rotary keys at
* load, where the architecture's reader takes them, so an existing container serves past its
* trained context with no reconvert -- and is checked by the same reader a converted one is. The
* drafter, when there is one, gets the same factor over its own trained length. Then one line says
* what the rotary is, and a context past what it covers is named. */
int Engine::apply_rope_scaling() {
RopeSpec spec;
if (!rope_spec_parse(cfg_.rope_scaling.c_str(), &spec)) {
RAD_ERR("--rope-scaling '%s': yarn:FACTOR (above 1) with an optional :ORIG, or none",
cfg_.rope_scaling.c_str());
return RAD_E_INVAL;
}
if (spec.kind != RopeSpec::Keep) {
std::string why;
if (!rope_override_group(meta_kv_k_, meta_kv_v_, spec, "", meta_.n_ctx_train, &why)) {
RAD_ERR("--rope-scaling %s: %s", cfg_.rope_scaling.c_str(), why.c_str());
return RAD_E_INVAL;
}
RopeKeys kv{ meta_kv_k_, meta_kv_v_ };
if (kv.any_prefix("draft.")) {
int64_t dtrain = meta_.n_ctx_train;
if (const std::string* t = kv.get("draft.max_position_embeddings"))
dtrain = std::atoll(t->c_str());
if (!rope_override_group(meta_kv_k_, meta_kv_v_, spec, "draft.", dtrain, &why)) {
RAD_ERR("--rope-scaling %s: %s", cfg_.rope_scaling.c_str(), why.c_str());
return RAD_E_INVAL;
}
}
}
const RopeResolved r = rope_resolve(meta_kv_k_, meta_kv_v_, "");
const long long want = cfg_.max_ctx > 0 ? (long long)cfg_.max_ctx : (long long)meta_.n_ctx_train;
if (r.type == "yarn" && r.factor > 1.0) {
const long long reach = (long long)(r.orig * r.factor);
RAD_INFO("rope: YaRN factor %g over %lld trained positions -- the rotary reaches %lld; "
"--max-model-len %lld%s", r.factor, (long long)r.orig, reach, want,
spec.kind == RopeSpec::Yarn ? " (--rope-scaling)" : " (the container's own)");
if (want > reach)
RAD_WARN("--max-model-len %lld is past the %lld positions YaRN factor %g covers; "
"positions beyond them are extrapolated", want, reach, r.factor);
} else if (meta_.n_ctx_train > 0 && want > meta_.n_ctx_train &&
!(r.type == "linear" && r.factor > 1.0)) {
RAD_WARN("--max-model-len %lld is past the %lld positions the model was trained on and "
"nothing scales its rotary, so positions beyond them are extrapolated; a model "
"card's YaRN extension is --rope-scaling yarn:FACTOR (docs/YARN.md)", want,
(long long)meta_.n_ctx_train);
}
return RAD_OK;
}
/* ================================================================== 3 + 4. plugins, declare */
int Engine::load_plugins() {
int s = rad_tools_load_plugins(cfg_.radiance_home, cfg_.kernel_hierarchy,
@@ -1233,9 +1288,111 @@ int Engine::plan() {
r->program.arena_stage_bytes = vb.stage;
r->program.arena_bytes = r->program.arena_stage_off + vb.stage;
}
/* ---- AN UNEVEN WORLD: EACH RANK'S OWN POOLS FOR THE ONE TOKEN COUNT -------------------
*
* The split above is the dearest rank's, applied to every card, and one block table serves
* every rank -- configure_kv caps each at the least rank's paged tokens. A rank whose cache
* costs less per token (an attention-zero rank keeps no attention cache, only what its
* other groups cost) would reserve the common KV pool and page a fraction of it, while its
* experts beyond the common weights pool sit in the pinned host pool. So such a rank gets a
* KV pool that pages exactly the common token count and the difference in its weights
* pool, up to every one of its weights resident. The token count, the carve, the loan and
* the dearest ranks' pools are what they were.
*
* Only a DERIVED split under expert_tiered is re-split. An operator who stated either pool
* has decided what every card gets. And under `auto` a rank whose grown pool covers all of
* its weights would choose all_vram while its peers spill -- one strategy per world is the
* contract that keeps their movers alike, so `auto` keeps the common split. A cache that
* does not lend (--deterministic, or a device without virtual memory management) is
* re-split all the same: the bytes it would never page are bytes its experts can hold, and
* without virtual memory management they are allocated whole.
* Where every rank's cache costs the same per token no rank qualifies and rank_cfg_ is cfg_
* on every rank, field for field. A rank that qualifies and is not re-split is named with
* the reason, once. */
rank_cfg_.assign(ranks_.size(), cfg_);
kv_planned_tokens_ = 0;
constexpr int64_t kMiB = (int64_t)1 << 20;
int64_t kv_max = 0;
for (const VramFacts& f : facts) kv_max = std::max(kv_max, f.kv_ceiling);
std::vector<size_t> cheaper;
for (size_t i = 0; i < facts.size() && i < ranks_.size(); ++i)
if (facts[i].kv_ceiling < kv_max) cheaper.push_back(i);
/* Why no cheaper rank is re-split, where the reason holds for the whole world. */
std::string kept;
std::vector<std::unique_ptr<KVManager>> probes(ranks_.size());
int64_t T = -1;
if (cheaper.empty()) {
/* Every rank's cache costs the same per token: there is nothing to re-split. */
} else if (!vb.derived_kv || !vb.derived_weights) {
kept = "a stated --vram-kv-mib or --vram-weights-mib is applied to every card";
} else if (cfg_.placement != "expert_tiered") {
kept = fmt("--placement %s keeps one split for every card; only expert_tiered re-splits",
cfg_.placement.c_str());
} else {
/* THE TOKEN COUNT configure_kv WILL SETTLE ON: every rank's paged tokens in the common
* pool, the least of them. Asked of the same plan configure_kv makes, against the same
* bytes: nothing reserves from a KV pool before its carve. */
for (size_t i = 0; i < ranks_.size(); ++i) {
probes[i] = std::make_unique<KVManager>();
if (probes[i]->plan_groups(ranks_[i]->program.kv_groups, cfg_) != RAD_OK) {
kept = fmt("rank %d's KV groups did not plan", ranks_[i]->index);
break;
}
const int64_t t = probes[i]->paged_tokens(cfg_.vram_kv_mib * kMiB);
if (t == KVManager::kUnboundedTokens) continue;
if (T < 0 || t < T) T = t;
}
if (kept.empty() && T <= 0)
kept = "no rank's cache pages a bounded token count in the common pool";
}
for (size_t i : cheaper) {
const std::string costs =
fmt("kv: rank %d's cache costs %s at the worst case where its dearest peer's costs "
"%s", ranks_[i]->index, humanb(facts[i].kv_ceiling).c_str(),
humanb(kv_max).c_str());
if (!kept.empty()) {
RAD_INFO("%s; its pools stay the common split: %s", costs.c_str(), kept.c_str());
continue;
}
/* EXACT, NO MARGIN: paged_split is monotone in the budget, so the least whole MiB that
* pages T here pages at least T in configure_kv -- the same plan, the same arithmetic,
* a pool whose budget is exactly this many MiB. The pool's own alignment is already
* among the plan's fixed costs (a RAD_ALIGN_UNIT a reservation). */
const int64_t need = probes[i]->pool_mib_for_tokens(T, cfg_.vram_kv_mib);
if (need < 0) {
RAD_INFO("%s; its pools stay the common split: it does not page the common %lld "
"tokens in the common %lld MiB", costs.c_str(), (long long)T,
(long long)cfg_.vram_kv_mib);
continue;
}
const int64_t cap = facts[i].statics + expert_vram_floor(wfs[i], 0);
const RankSplit rs =
vram_budget_rank_split(cfg_.vram_weights_mib, cfg_.vram_kv_mib, need, cap);
if (!rs.resplit) {
RAD_INFO("%s; its pools stay the common split: it needs all %lld MiB of the common "
"pool to page the common %lld tokens", costs.c_str(),
(long long)cfg_.vram_kv_mib, (long long)T);
continue;
}
rank_cfg_[i].vram_kv_mib = rs.kv_mib;
rank_cfg_[i].vram_weights_mib = rs.weights_mib;
kv_planned_tokens_ = T;
RAD_INFO("%s, so its KV pool pages the common %lld tokens in %lld MiB instead of %lld; "
"its weights pool grows %lld -> %lld MiB (every weight resident wants %s)%s",
costs.c_str(), (long long)T, (long long)rs.kv_mib, (long long)cfg_.vram_kv_mib,
(long long)cfg_.vram_weights_mib, (long long)rs.weights_mib,
humanb(cap).c_str(),
rs.unusable_mib > 0
? fmt(", and %lld MiB stay unclaimed", (long long)rs.unusable_mib).c_str()
: "");
}
}
for (auto& r : ranks_) {
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
auto& r = ranks_[ri];
/* This rank's own split: cfg_ field for field unless the block above re-split it. */
const Config& rc = rank_cfg_[ri];
LogRank lr(r->index);
/* THE MAIN THREAD RUNS EVERY RANK'S STARTUP, one rank after another, and every allocator
* reachable from here takes the CURRENT device -- rad_dev_alloc has no device argument.
@@ -1249,18 +1406,18 @@ int Engine::plan() {
/* Every pool is budgeted explicitly. No profiling pass, no utilisation fraction, no
* inference about what the workload will be (spec §6). Pools refuses by name and by how
* much rather than shrinking anything. */
int s = r->pools.configure(cfg_, props.vram_bytes);
int s = r->pools.configure(rc, props.vram_bytes);
RAD_INFO("pools:\n%s", r->pools.fit_report().c_str());
if (s < 0) {
report_pool_refusal(r->index, r->device, r->pools, cfg_);
report_pool_refusal(r->index, r->device, r->pools, rc);
return s;
}
/* Under tensor parallel the placement unit is a SHARD of a weight, so each rank plans
* against its own card's budget (spec §5.3). */
* against its own card's budget (spec §5.3) -- the same split its pools were given. */
PlannerInput in{};
in.program = &r->program;
in.config = &cfg_;
in.config = &rc;
in.rank = r->index;
in.world_size = cfg_.tp;
if (file_ && file_->header().prof_count) {
@@ -1273,6 +1430,16 @@ int Engine::plan() {
if (cfg_.debug_placement || s < 0)
fputs(r->plan.report(r->program).c_str(), stderr);
if (s < 0) return s;
/* The slab the planner filled is the pool the mover will fill: one split, read twice. */
RAD_TRY(plan_check_weights_pool(r->plan, r->pools.weights().bytes()));
/* --host-pool-mib IS ONE NUMBER FOR EVERY RANK, allocated whole by Pools::configure, so a
* re-split rank whose grown weights pool took every weight still holds it. Said, because
* the `kv: rank N ...` line above reads as if that rank's memory were all accounted for. */
if (rc.vram_kv_mib < cfg_.vram_kv_mib && cfg_.host_pool_mib > 0 &&
r->plan.totals.bytes[(int)Tier::HostPinned] == 0)
RAD_INFO("kv: rank %d's weights all fit its grown weights pool, so its pinned host pool "
"holds no weights; its %lld MiB (--host-pool-mib) stay allocated, as on every "
"rank", r->index, (long long)cfg_.host_pool_mib);
}
return RAD_OK;
}
@@ -2559,10 +2726,22 @@ int Engine::configure_kv() {
* every rank is capped at the least before any carves. At an even split the cap is what
* every rank would have carved anyway. */
int64_t least = -1;
for (auto& r : ranks_) {
for (size_t i = 0; i < ranks_.size(); ++i) {
auto& r = ranks_[i];
LogRank lr(r->index);
RAD_TRY(r->kv.plan_groups(r->program.kv_groups, cfg_));
const int64_t t = r->kv.paged_tokens(r->pools.kv().avail());
/* A RANK plan() RE-SIZED FOR THE COMMON TOKEN COUNT PAGES AT LEAST THAT COUNT, by
* construction: its pool is the least whole MiB whose paged split reaches it, asked of the
* same plan against the same bytes. Short of it, this rank would set every rank's count
* under what its dearest peer pages -- a broken construction, refused by name. */
if (rank_cfg_[i].vram_kv_mib < cfg_.vram_kv_mib && t < kv_planned_tokens_) {
RAD_ERR("kv: rank %d's KV pool was sized at %lld MiB to page the common %lld tokens "
"and pages %lld: the pool and the plan that sized it disagree", r->index,
(long long)rank_cfg_[i].vram_kv_mib, (long long)kv_planned_tokens_,
(long long)t);
return RAD_E_STATE;
}
if (t == KVManager::kUnboundedTokens) continue; /* holds no cache; limits nobody */
if (least < 0 || t < least) least = t;
}
@@ -2738,16 +2917,20 @@ int Engine::configure_kv() {
sc.n_ckpt_slots = ck_disk_slots;
sc.n_block_slots = ((cfg_.prefix_cache_disk_mib << 20)
- ck_disk_slots * ck_slot_bytes) / slot_bytes;
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE. A cached block is only
* meaningful under the container and layout that produced it; read back under
* another, it is a lossless function of somebody else's weights. */
/* THE FINGERPRINT IS WHAT MAKES A PERSISTED STORE SAFE, and it is built from
* everything a cached block's bytes actually depend on. Read back under a
* different container, layout or KV width, a block is a lossless function of
* somebody else's weights -- fluent, confident and wrong. There is no cheaper
* check than refusing the whole store, because a block carries no evidence of
* what produced it beyond the tokens it was keyed by. */
* different container, layout, KV width or rotary, a block is a lossless
* function of somebody else's weights -- fluent, confident and wrong. There is
* no cheaper check than refusing the whole store, because a block carries no
* evidence of what produced it beyond the tokens it was keyed by.
*
* The rotary is the RESOLVED one, target and drafter, after --rope-scaling
* (rope_identity): a YaRN container converted from the same checkpoint has the
* same name and shapes as the stock one, and every cached key and QSA block key
* is rotated differently under it. */
{
char theta[32];
std::snprintf(theta, sizeof theta, "%.9g", (double)meta_.rope_theta);
const std::string id =
std::string(meta_.name ? meta_.name : "") + "|" +
std::string(meta_.arch_id ? meta_.arch_id : "") + "|" +
@@ -2755,7 +2938,8 @@ int Engine::configure_kv() {
std::to_string(ranks_[0]->prefix.block_size()) + "|" +
std::to_string(slot_bytes) + "|" + std::to_string(ck_slot_bytes) + "|" +
cfg_.kv_cache_dtype + "|" +
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION;
std::to_string((long long)ranks_.size()) + "|" + RAD_VERSION +
"|theta=" + theta + "|" + rope_identity(meta_kv_k_, meta_kv_v_);
uint64_t h = 1469598103934665603ull;
for (char c : id) { h ^= (unsigned char)c; h *= 1099511628211ull; }
sc.fingerprint = h;
@@ -3356,7 +3540,8 @@ int Engine::start() {
const int64_t MiB = 1024 * 1024;
const int64_t headroom = std::max<int64_t>(cfg_.gpu_headroom_mib, 0) * MiB;
const int64_t allowance = Config{}.gpu_headroom_mib * MiB;
for (auto& r : ranks_) {
for (size_t ri = 0; ri < ranks_.size(); ++ri) {
auto& r = ranks_[ri];
LogRank lr(r->index);
RadDeviceProps props{};
if (rad_dev_props(r->device, &props) < 0 || props.vram_bytes <= 0) continue;
@@ -3399,8 +3584,19 @@ int Engine::start() {
* byte -- a small dense model already at the largest context its cache can hold
* leaves most of the card -- and vram_budget.cpp printed it on the `unusable` line.
* Warning here would contradict that receipt and send the reader looking for a flag
* to set. */
if (cfg_.vram_budget_derived)
* to set. A rank plan() re-split for the common token count also leaves what its
* weights could not use, and the `kv: rank N ...` line said how much. */
const int64_t unclaimed_mib =
(cfg_.vram_weights_mib + cfg_.vram_kv_mib) -
(rank_cfg_[ri].vram_weights_mib + rank_cfg_[ri].vram_kv_mib);
if (cfg_.vram_budget_derived && unclaimed_mib > 0)
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: %lld "
"MiB are what rank %d's weights could not use of what its KV pool did not "
"need, on the `kv: rank %d ...` line above, and the rest is the `unusable` "
"line of the VRAM budget.",
r->device, humanb(got).c_str(), asked.c_str(), (long long)unclaimed_mib,
r->index, r->index);
else if (cfg_.vram_budget_derived)
RAD_INFO("card %d settled at %s free against %s. The split accounted for it: "
"neither pool could address another byte, which is the `unusable` line of "
"the VRAM budget above.",
+46 -2
View File
@@ -253,7 +253,10 @@ int meta_from_config_json(const std::string& dir, MetaOwn* out) {
m.n_expert_shared = gi("shared_expert_intermediate_size", 0) ? 1 : 0;
m.rms_eps = (float)gf("rms_norm_eps", 1e-6);
m.rope_theta = (float)gf("rope_parameters.rope_theta", gf("rope_theta", 10000.0));
m.rope_scale = (float)gf("rope_scaling.factor", 1.0);
/* The rotary's scaling stays in the free-form keys with its type beside it; the architecture
* reads both (arch/common/rad_arch.h, yarn_from). A factor copied here without its type would
* be a linear position divide for llama3, longrope or YaRN. */
m.rope_scale = 1.0f;
/* The quantisation descriptor, which with the architecture selects the plugin (spec §2.4).
* "fp8" plus its format, so qwen35_fp8 and qwen35_bf16 are told apart by the checkpoint
@@ -300,7 +303,48 @@ int meta_from_gguf(GgufFile& g, MetaOwn* out) {
m.n_expert_shared= gi("expert_shared_count", 0);
m.rms_eps = (float)gf("attention.layer_norm_rms_epsilon", 1e-6);
m.rope_theta = (float)gf("rope.freq_base", 10000.0);
m.rope_scale = (float)gf("rope.scaling.factor", 1.0);
m.rope_scale = 1.0f;
/* THE ROTARY'S SCALING, written as the config.json keys a safetensors release carries, because
* those are what the architecture reads (arch/common/rad_arch.h, yarn_from) -- one reader, so
* a type is refused or honoured by name whichever file it came from. llama.cpp's YaRN
* attn_factor, ext_factor and log multiplier modify the magnitude and ramp in ways config.json
* has no spelling for, so a file that sets one to anything but its neutral value is refused
* here rather than served as plain YaRN. */
{
/* llama.cpp's reading: the type defaults to linear, the factor is rope.scaling.factor or
* the older rope.scale_linear, and 0 or 1 is no scaling. */
std::string type = "linear";
g.get_str(a + ".rope.scaling.type", &type);
const double factor = gf("rope.scaling.factor", gf("rope.scale_linear", 0.0));
const bool none = type == "none" || (type == "linear" && (factor == 0.0 || factor == 1.0));
if (!none) {
const struct { const char* key; double neutral; } kOff[] = {
{ "rope.scaling.attn_factor", 1.0 }, { "rope.scaling.yarn_attn_factor", 1.0 },
{ "rope.scaling.yarn_log_multiplier", 0.0 } };
for (const auto& k : kOff)
if (gf(k.key, k.neutral) != k.neutral) {
RAD_ERR("the GGUF sets %s.%s = %g; that modifier of the rotary's scaling is "
"not implemented", a.c_str(), k.key, gf(k.key, k.neutral));
return RAD_E_UNSUPPORTED;
}
const double ext = gf("rope.scaling.yarn_ext_factor", -1.0);
if (ext >= 0.0 && ext != 1.0) {
RAD_ERR("the GGUF sets %s.rope.scaling.yarn_ext_factor = %g; YaRN is implemented "
"at extrapolation factor 1", a.c_str(), ext);
return RAD_E_UNSUPPORTED;
}
out->kv("rope_scaling.type", type);
if (factor != 0.0) out->kv("rope_scaling.factor", fmt("%.17g", factor));
const int64_t orig = gi("rope.scaling.original_context_length", 0);
if (orig > 0) out->kv("rope_scaling.original_max_position_embeddings",
fmt("%lld", (long long)orig));
for (const char* beta : { "beta_fast", "beta_slow" }) {
const double v = gf((std::string("rope.scaling.yarn_") + beta).c_str(), 0.0);
if (v != 0.0) out->kv(std::string("rope_scaling.") + beta, fmt("%.17g", v));
}
}
}
std::vector<std::string> toks;
if (g.get_strs("tokenizer.ggml.tokens", &toks)) m.n_vocab = (int64_t)toks.size();
+209
View File
@@ -0,0 +1,209 @@
/* --rope-scaling, over a container's free-form metadata.
*
* Static YaRN is read by the architecture (arch/common/rad_arch.h, yarn_from) out of the model's
* own keys: `text_config.rope_parameters.`, `rope_parameters.`, `text_config.rope_scaling.`,
* `rope_scaling.`, in that order, the FIRST of them that names a rotary type being the one that
* counts; a DFlash2 drafter reads `draft.rope_parameters.` / `draft.rope_scaling.` on its own. A
* container converted without YaRN therefore needs a reconvert to get it -- or these keys rewritten
* when it is loaded, which is all this does. The architecture then resolves the result exactly as
* it would a converted container, so there is one reader and one set of checks.
*
* The rewrite goes into the object the reader would take, not beside it. A Qwen3.8 container says
* `text_config.rope_parameters.rope_type = default`; a YaRN written under `rope_parameters.` would
* sit behind that and never be read.
*
* Pure functions over two parallel string vectors, so they are tested without an engine
* (tests/yarn_test.cpp holds them to yarn_from). */
#pragma once
#include <algorithm>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
namespace rad {
struct RopeSpec {
enum Kind { Keep, None, Yarn } kind = Keep;
double factor = 0.0;
int64_t orig = 0; /* 0: the container's own trained length */
};
/* "yarn:FACTOR[:ORIG]" with FACTOR > 1 and ORIG > 0, or "none"; empty is Keep. False for anything
* else, so a typo is refused where it was typed. */
inline bool rope_spec_parse(const char* s, RopeSpec* out) {
RopeSpec r;
if (!s || !*s) { *out = r; return true; }
if (!std::strcmp(s, "none")) { r.kind = RopeSpec::None; *out = r; return true; }
if (std::strncmp(s, "yarn:", 5)) return false;
char* e = nullptr;
r.factor = std::strtod(s + 5, &e);
if (e == s + 5 || !(r.factor > 1.0) || r.factor > 1e6) return false;
if (*e == ':') {
char* e2 = nullptr;
const long long o = std::strtoll(e + 1, &e2, 10);
if (e2 == e + 1 || *e2 || o <= 0) return false;
r.orig = o;
} else if (*e) {
return false;
}
r.kind = RopeSpec::Yarn;
*out = r;
return true;
}
struct RopeKeys {
std::vector<std::string>& k;
std::vector<std::string>& v;
int find(const std::string& key) const {
for (size_t i = 0; i < k.size(); ++i)
if (k[i] == key) return (int)i;
return -1;
}
const std::string* get(const std::string& key) const {
const int i = find(key);
return i < 0 ? nullptr : &v[(size_t)i];
}
void set(const std::string& key, const std::string& val) {
const int i = find(key);
if (i >= 0) { v[(size_t)i] = val; return; }
k.push_back(key);
v.push_back(val);
}
void erase(const std::string& key) {
const int i = find(key);
if (i < 0) return;
k.erase(k.begin() + i);
v.erase(v.begin() + i);
}
bool any_prefix(const char* pre) const {
const size_t n = std::strlen(pre);
for (const auto& s : k)
if (!s.compare(0, n, pre)) return true;
return false;
}
};
/* The reader's order -- yarn_from's, kept in step with it. */
inline std::vector<std::string> rope_homes(const char* group) {
if (!*group)
return { "text_config.rope_parameters.", "rope_parameters.", "text_config.rope_scaling.",
"rope_scaling." };
return { std::string(group) + "rope_parameters.", std::string(group) + "rope_scaling." };
}
/* The object the reader takes and the key that names its type, or empty strings when no object
* names one (the model's rotary is then the default). */
inline void rope_authoritative(const RopeKeys& kv, const char* group, std::string* home,
std::string* type_key) {
home->clear();
type_key->clear();
for (const auto& h : rope_homes(group))
for (const char* t : { "rope_type", "type" })
if (kv.get(h + t)) { *home = h; *type_key = h + t; return; }
}
struct RopeResolved {
std::string type; /* "" when nothing names one */
double factor = 1.0;
double orig = 0.0;
};
inline RopeResolved rope_resolve(std::vector<std::string>& k, std::vector<std::string>& v,
const char* group) {
RopeKeys kv{ k, v };
RopeResolved r;
std::string home, tk;
rope_authoritative(kv, group, &home, &tk);
if (home.empty()) return r;
r.type = *kv.get(tk);
if (const std::string* f = kv.get(home + "factor")) r.factor = std::strtod(f->c_str(), nullptr);
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
r.orig = std::strtod(o->c_str(), nullptr);
return r;
}
/* Apply SPEC to one rotary group ("" the target, "draft." a DFlash2 drafter). `trained` is the
* group's own trained length, the default ORIG. Returns false, with *why set, when the group's
* rotary is one this flag does not stack YaRN over (linear position interpolation, say). */
inline bool rope_override_group(std::vector<std::string>& k, std::vector<std::string>& v,
const RopeSpec& spec, const char* group, int64_t trained,
std::string* why) {
if (spec.kind == RopeSpec::Keep) return true;
RopeKeys kv{ k, v };
std::string home, tk;
rope_authoritative(kv, group, &home, &tk);
const std::string type = home.empty() ? std::string() : *kv.get(tk);
if (spec.kind == RopeSpec::None) {
if (type == "yarn") kv.set(tk, "default");
return true;
}
/* `mrope` is the legacy Qwen2-VL spelling of default with sections. */
if (!type.empty() && type != "default" && type != "mrope" && type != "yarn") {
*why = "the " + std::string(*group ? "drafter's" : "model's") + " rotary is '" + type +
"' (" + tk + "); YaRN over it is not --rope-scaling's to decide";
return false;
}
if (home.empty()) {
home = *group ? std::string(group) + "rope_parameters."
: kv.any_prefix("text_config.") ? "text_config.rope_parameters."
: "rope_parameters.";
tk = home + "rope_type";
}
/* A checkpoint's own YaRN keeps its trained length unless one is given; anything that was
* tied to its old factor goes, so the reader derives it for the new one. */
int64_t orig = spec.orig;
if (!orig && type == "yarn")
if (const std::string* o = kv.get(home + "original_max_position_embeddings"))
orig = std::atoll(o->c_str());
if (!orig) orig = trained;
if (orig <= 0) {
*why = "no trained length to scale from; give one: yarn:FACTOR:ORIG";
return false;
}
char buf[64];
kv.set(tk, "yarn");
std::snprintf(buf, sizeof buf, "%.17g", spec.factor);
kv.set(home + "factor", buf);
std::snprintf(buf, sizeof buf, "%lld", (long long)orig);
kv.set(home + "original_max_position_embeddings", buf);
for (const char* stale : { "attention_factor", "mscale", "mscale_all_dim" })
kv.erase(home + stale);
return true;
}
/* THE ROTARY AS A CACHED KEY DEPENDS ON IT: every key with a path component naming `rope` or
* `rotary` -- rope_parameters.*, rope_scaling.*, rope_theta, partial_rotary_factor, their
* text_config. and draft. forms, a GGUF's <arch>.rope.* -- as key=value, sorted, after
* --rope-scaling has been applied. A persisted prefix store is fingerprinted with it: a container
* converted from the same checkpoint with YaRN has the same name and the same shapes, and its
* stock-rotated keys (and QSA block keys) read back under YaRN would be attended to at the wrong
* angles. Key order and unrelated keys do not change it. */
inline std::string rope_identity(const std::vector<std::string>& k,
const std::vector<std::string>& v) {
auto names_rotary = [](const std::string& key) {
size_t s = 0;
while (s <= key.size()) {
size_t e = key.find('.', s);
if (e == std::string::npos) e = key.size();
const std::string part = key.substr(s, e - s);
if (part.find("rope") != std::string::npos || part.find("rotary") != std::string::npos)
return true;
s = e + 1;
}
return false;
};
std::vector<std::string> rows;
for (size_t i = 0; i < k.size() && i < v.size(); ++i)
if (names_rotary(k[i])) rows.push_back(k[i] + "=" + v[i]);
std::sort(rows.begin(), rows.end());
std::string out;
for (const auto& r : rows) { out += r; out += ';'; }
return out;
}
} /* namespace rad */
+21
View File
@@ -395,6 +395,27 @@ int64_t KVManager::paged_split(int64_t budget_bytes, std::vector<int64_t>* block
return tokens;
}
int64_t KVManager::pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const {
const int64_t MiB = (int64_t)1 << 20;
if (max_mib <= 0) return -1;
const auto reaches = [&](int64_t mib) {
/* The fixed costs (recurrent state, its alignment) come first on every rank -- a rank
* whose only paged group is zero still has to hold them. */
if (mib * MiB < fixed_) return false;
const int64_t t = paged_split(mib * MiB, nullptr);
return t == kUnboundedTokens || t >= tokens;
};
if (!reaches(max_mib)) return -1;
/* reaches(hi) holds throughout; lo is the largest size known to fall short (or 0). */
int64_t lo = 0, hi = max_mib;
if (reaches(lo)) return 0;
while (hi - lo > 1) {
const int64_t mid = lo + (hi - lo) / 2;
if (reaches(mid)) hi = mid; else lo = mid;
}
return hi;
}
int64_t KVManager::zero_blocks(const KVGroupPlan& p, int64_t tokens) const {
if (tokens == kUnboundedTokens) return 0;
const int64_t b = tokens / p.block_size;
+5
View File
@@ -182,6 +182,11 @@ public:
* cost it nothing, so it takes what the ranks holding the cache carve and limits nobody. */
static constexpr int64_t kUnboundedTokens = INT64_MAX;
int64_t paged_tokens(int64_t budget_bytes) const { return paged_split(budget_bytes, nullptr); }
/* THE INVERSE OF paged_tokens: the least whole MiB of pool whose paged split reaches `tokens`,
* searched up to max_mib; -1 when even max_mib does not. Pure arithmetic on the plan (no pool,
* no cap), for Engine::plan sizing an uneven world's cheaper rank to the token count its
* dearest peer sets. paged_split is monotone in the budget, so the search is exact. */
int64_t pool_mib_for_tokens(int64_t tokens, int64_t max_mib) const;
void cap_paged_tokens(int64_t tokens) { tokens_cap_ = tokens > 0 ? tokens : 0; }
int carve(Pool& kv_pool);
+22 -2
View File
@@ -47,10 +47,11 @@ static int resolve(Config& cfg, const std::vector<VramFacts>& per_rank, VramBudg
VramBudget b;
if (per_rank.empty()) { if (out) *out = b; return RAD_OK; }
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is applied to every rank. Ranks
/* THE SMALLEST CARD AND THE LARGEST PROGRAM, because one split is derived for every rank. Ranks
* of one deployment normally hold the same shard shapes and the same program, so these folds
* are no-ops -- they exist so that a mixed pair degrades to the card that binds instead of
* overcommitting the smaller one on the first allocation. */
* overcommitting the smaller one on the first allocation. An uneven world's cheaper ranks are
* re-split from this answer afterwards (vram_budget_rank_split, called by Engine::plan). */
b.capacity = per_rank[0].capacity;
int64_t freeb = per_rank[0].free;
int64_t layer_max = 0, kv_one = 0;
@@ -393,4 +394,23 @@ int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank,
return resolve(c, per_rank, out, false);
}
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
int64_t need_kv_mib, int64_t weights_cap_bytes) {
RankSplit s;
s.weights_mib = common_weights_mib;
s.kv_mib = common_kv_mib;
if (need_kv_mib < 0 || need_kv_mib >= common_kv_mib) return s;
const int64_t saved = common_kv_mib - need_kv_mib;
/* NEVER LESS THAN THE COMMON WEIGHTS POOL, and never more than every weight resident: a weights
* pool is one whole allocation, so MiB past what this rank could ever place are left unclaimed
* rather than allocated empty. */
const int64_t cap = std::max(common_weights_mib, to_mib_up(weights_cap_bytes));
const int64_t grown = std::min(common_weights_mib + saved, cap);
s.kv_mib = need_kv_mib;
s.weights_mib = grown;
s.unusable_mib = saved - (grown - common_weights_mib);
s.resplit = true;
return s;
}
} /* namespace rad */
+18 -1
View File
@@ -125,7 +125,8 @@ struct VramBudget {
};
/* Writes the answer into cfg.vram_weights_mib / cfg.vram_kv_mib -- ONE resolved number that every
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree.
* consumer downstream reads, so the planner, the KV manager and the pool report cannot disagree
* (an uneven world's cheaper rank takes its own copy of it: vram_budget_rank_split below).
* Takes the SMALLEST capacity and free across ranks and the LARGEST arena, because a split has to
* fit on every card it is applied to.
*
@@ -137,4 +138,20 @@ int vram_budget_resolve(Config& cfg, const std::vector<VramFacts>& per_rank, Vra
* placement). */
int vram_budget_trial(const Config& cfg, const std::vector<VramFacts>& per_rank, VramBudget* out);
/* AN UNEVEN WORLD'S CHEAPER RANK. The resolver above derives one split, the dearest rank's, and one
* block table serves every rank -- so a rank whose cache costs less per token (an attention-zero
* rank keeps no attention cache) would reserve the common KV pool for tokens configure_kv then caps
* away. Given the common split, the MiB that rank's pool needs to page the SAME tokens, and what
* every one of its weights would take resident (statics + all experts + their spare slots), this
* moves the difference to its weights pool, no further than that cap; what the cap leaves stays
* unclaimed. Nothing changes when the need is not below the common pool. */
struct RankSplit {
int64_t weights_mib = 0;
int64_t kv_mib = 0;
int64_t unusable_mib = 0; /* saved from the KV pool but past the weights cap: never allocated */
bool resplit = false;
};
RankSplit vram_budget_rank_split(int64_t common_weights_mib, int64_t common_kv_mib,
int64_t need_kv_mib, int64_t weights_cap_bytes);
} /* namespace rad */
+9
View File
@@ -113,6 +113,15 @@ int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room) {
return std::min(all, std::max<int64_t>(all + 2 * wf.expert_unit_max - host_room, 0));
}
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes) {
if (p.vram_budget == pool_bytes) return RAD_OK;
RAD_ERR("placement: rank %d planned against a %s weights budget (%lld bytes) and its weights "
"pool holds %s (%lld bytes): the planner and the pool were given different splits",
p.rank, humanb(p.vram_budget).c_str(), (long long)p.vram_budget,
humanb(pool_bytes).c_str(), (long long)pool_bytes);
return RAD_E_STATE;
}
void weight_footprint(const Program& prog, WeightFootprint* out, TablePlacement embedding,
TablePlacement ngram) {
if (!out) return;
+7
View File
@@ -416,6 +416,13 @@ int64_t file_stage_reserve(int64_t widest, bool routed);
* A weight budget of the statics and this much places every expert in VRAM or the host pool. */
int64_t expert_vram_floor(const WeightFootprint& wf, int64_t host_room);
/* THE PLAN AND ITS RANK'S WEIGHTS POOL READ ONE SPLIT. The planner places against
* Plan::vram_budget and the mover fills the pool Pools::configure allocated, each from the Config
* it was handed; a rank given two different Configs plans a slab the pool does not have, or leaves
* part of the pool unplanned and empty, and nothing downstream would say so. RAD_E_STATE, naming
* the rank and both sizes, when they differ. */
int plan_check_weights_pool(const Plan& p, int64_t pool_bytes);
/* THE TABLES THE PLACEMENT FLAGS MOVE, by what reads them and not by name: a model-level weight
* that at least one op reads and that only `embed_lookup` reads is a token embedding table, and
* one only `embed_lookup_q` reads is an n-gram table. A lookup reads M rows a step, which is what
+32 -3
View File
@@ -129,6 +129,27 @@ enum class Tier { VRAM = 0, HostPinned = 1, HostPageable = 2, SSD = 3, Mapped =
* decides it and writes the answer into Config, so every rank plans from one choice. */
enum class TablePlacement { Auto = 0, Vram = 1, Ram = 2, Disk = 3 };
const char* table_placement_name(TablePlacement p);
/* --draft-window: how many drafts a step verifies for each sequence (core/sched/draft.h).
* Fixed every sequence drafts --num-speculative-tokens.
* Adaptive that is the ceiling; each step's head depth and each sequence's stop follow the
* measured acceptance and the measured step cost. A serial drafter's policy only.
* The default is kDraftWindowDefault, and the help text and the startup line read it from there.
*
* FIXED IS THE DEFAULT BECAUSE ADAPTIVE LOSES WHERE A SERVER IS BUSY. Qwen3.8-Flash-Next at TP2 on
* two R9700, distinct prompts a sequence, tokens a second over a steady window against fixed depth 3:
*
* concurrent sequences 1 2 4 8
* adaptive, ceiling 3 +0.4% -0.1% +1.7% -0.3%
* adaptive, ceiling 5 +7.1% -2.3% +7.4% -11.9%
*
* At eight the head runs five rounds for little more text: 43.0 against 36.3 ms a step (1.18x) for
* 23.3 against 22.3 tokens. The cost model's prior puts depth 5 over depth 3 at 1.10x, and a depth
* not yet timed at a load is priced on the prior. */
enum class DraftWindow { Fixed = 0, Adaptive = 1 };
constexpr DraftWindow kDraftWindowDefault = DraftWindow::Fixed;
inline const char* draft_window_name(DraftWindow w) {
return w == DraftWindow::Adaptive ? "adaptive" : "fixed";
}
enum class Site { Device = 0, DeviceStaged = 1, DeviceZeroCopy = 2, Host = 3 };
/* Tier-indexed arrays are sized by this rather than by a literal: the report, the live view and
@@ -623,6 +644,10 @@ struct Config {
int64_t max_tok = 8192; /* --max-num-batched-tokens */
int64_t max_seqs = 256;
int64_t max_ctx = 0; /* 0 = the model's training context */
/* --rope-scaling: "yarn:FACTOR[:ORIG]" writes YaRN over the checkpoint's own rotary keys (the
* model card's extension past its trained context, no reconvert); "none" takes a checkpoint's
* YaRN off; empty serves what the checkpoint says. Engine::apply_rope_scaling. */
std::string rope_scaling;
/* THE OPERATOR STATES A BUDGET OR THE ENGINE DERIVES ONE FROM THE CARD, AND EITHER WAY IT IS
* STATED IN FULL BEFORE ANYTHING IS ALLOCATED.
@@ -634,7 +659,10 @@ struct Config {
* what the driver already holds is measured rather than assumed. core/mem/vram_budget.cpp does
* that sum and writes the answer back into the two fields below, so every consumer downstream
* -- the planner, the KV manager, the pool report -- reads one resolved number and there is no
* second place for them to disagree.
* second place for them to disagree. Engine::plan derives each rank's own copy from it
* (rank_cfg_, see docs/TP3.md §1), and the rank's pools and planner both read that copy --
* still one number per card, and the same number on every card whose cache costs as much per
* token as the dearest rank's.
*
* Zero means "derive"; a stated --vram-weights-mib / --vram-kv-mib still wins outright. */
int64_t vram_weights_mib = 0;
@@ -721,8 +749,8 @@ struct Config {
* code object, which HIP loads on the kernel's FIRST LAUNCH and not at startup, and which
* faults inside the HIP runtime rather than returning an error when there is no room. */
/* The speculative window, and the whole of the draft policy: the depth is constant and this
* is it. See core/sched/draft.h. */
/* The speculative window: the depth, or under --draft-window adaptive its ceiling. See
* core/sched/draft.h. */
/* -1 is `auto`: engine_bringup asks rad_arch_probe for the depth THIS container's drafter was
* trained at, and a container with no draft head resolves to 0 with a line saying so.
*
@@ -732,6 +760,7 @@ struct Config {
* paying for it again in VRAM, and then running at one token a step -- a small fraction of
* the throughput the same container gives at its declared depth. */
int n_spec = -1; /* --num-speculative-tokens; -1 = auto, 0 = off */
DraftWindow draft_window = kDraftWindowDefault; /* --draft-window */
/* ---------------- KL DIVERGENCE AGAINST A REFERENCE (core/kld.h) ----------------
*
+4
View File
@@ -73,6 +73,10 @@ struct StepEntry {
bool draft_out = false;
bool is_prefill = false;
bool produces_token = false; /* this entry's last token is the sequence's last */
/* ITS DRAFTS CAME FROM PROMPT LOOKUP, not from the declared drafter. Their outcome is counted
* in the reported acceptance like any other, and kept out of the adaptive window's estimate,
* which describes the draft head (DraftController, draft.h). */
bool ngram = false;
/* A DEVICE ROW: the card fills its tokens, positions, rollback count and slots from the slot's
* StepSlot before the pass runs (advance.h), and what the host staged for them is replaced.
* `ctx_len` is then an upper bound, which is what the host-side ceilings read. The other three
+255 -1
View File
@@ -1,9 +1,46 @@
/* draft.cpp -- the static draft-depth policy. See draft.h for why it is static.
/* draft.cpp -- the static draft-depth policy, and the adaptive one `--draft-window adaptive` turns
* on. See draft.h for why the first is the default and what the second changes.
*/
#include "draft.h"
#include <cmath>
#include <cstdint>
#include <cstdlib>
namespace rad {
namespace {
/* THE STEP-COST PRIOR, a shape and not a measurement: every draft adds six percent to a step --
* one round of a serial head and one more verify row against a weight-bound step. It prices a
* depth nothing has measured yet, and only its RATIOS are read once anything has been measured:
* an unmeasured depth is the nearest measured one scaled by prior(d) / prior(d'). */
constexpr double kCostSlope = 0.06;
double cost_prior(int d) { return 1.0 + kCostSlope * (double)d; }
/* A STEP TIME'S MEAN IS A RUNNING MEAN FOR ITS FIRST STEPS AND THEN A MOVING AVERAGE WITH A
* HALF-LIFE OF 32 STEPS. Long enough that the scatter of one step against the next -- a tier
* copy, a recording, a prefix-cache trim -- averages out; short enough to follow a context that
* grows by a few thousand tokens over a reply. */
constexpr double kCostHalfLife = 32.0;
/* AND ONE STEP COUNTS FOR AT MOST FOUR TIMES THE KEY'S MEAN, once the mean is over four steps. A
* step that waited on something other than its own work -- a first recording, an allocation, a
* host stall -- says nothing about what its depth costs, and one such step would otherwise move a
* short mean by more than any depth. A mean over fewer steps is not yet a reference to clip
* against: its first step may itself be the odd one. */
constexpr double kCostOutlier = 4.0;
constexpr int64_t kCostClipAfter = 4;
/* THE PRIOR WEIGHS AS MUCH AS THIS MANY VERIFIES. The (n+1)-th real one moves an estimate by
* 1 / (n + k + 1) -- a running mean over the prior and the evidence -- until that step falls below
* the half-life's, and from then on it is the moving average it is meant to be. Without it a
* sequence would spend its first ~16 verifies at whatever window the prior chose, which is most of
* a short answer. */
constexpr double kPriorWeight = 4.0;
} /* namespace */
int DraftController::configure(const Params& p) {
if (p.max_depth < 0 || p.max_depth > RAD_SCHED_MAX_SPEC) {
RAD_ERR("draft depth %d is outside 0..%d -- the verify kernel band is %d query rows",
@@ -14,6 +51,24 @@ int DraftController::configure(const Params& p) {
tot_drafted_ = tot_accepted_ = 0;
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) { reach_[j] = 0; hit_[j] = 0; }
seen_ = 0;
adapt_ = p.adapt && p.max_depth > 0;
alpha_ = 1.0 - std::exp2(-1.0 / kHalfLife);
step_d_ = 0;
step_w_ = 0;
step_held_ = 0;
prior_n_ = 0;
for (int j = 0; j < RAD_SCHED_MAX_SPEC; ++j) prior_[j] = 0.0f;
for (int d = 0; d <= RAD_SCHED_MAX_SPEC; ++d) {
by_depth_[d] = 0;
for (int c = 0; c < kCostClasses; ++c) { cost_ms_[d][c] = 0.0; cost_n_[d][c] = 0; }
}
if (adapt_)
RAD_INFO("draft depth: ADAPTIVE (--draft-window adaptive), %d..%d -- the step's head depth "
"maximises the tokens its sequences are expected to emit over the step's measured "
"cost, and a sequence stops at the first draft emitted less than %.0f%% of the "
"time; moves at +%.0f%% and at most every %d steps",
kMinDepth, p_.max_depth, 100.0 * kDraftMinChance, 100.0 * kHyst, kHold);
return RAD_OK;
}
@@ -34,6 +89,205 @@ void DraftController::observe(int drafted, int accepted) {
if (j < accepted) ++hit_[j];
}
if (drafted > seen_) seen_ = drafted;
if (adapt_) ++by_depth_[drafted];
}
/* ------------------------------------------------------------------ the step's cost */
int DraftController::cost_class(int n_rows) {
int c = 0;
while (c + 1 < kCostClasses && n_rows >= (2 << c)) ++c;
return c;
}
void DraftController::step_time(int depth, int n_rows, double ms) {
if (!adapt_ || depth < 1 || depth > p_.max_depth || n_rows < 1 || !(ms > 0.0) ||
!std::isfinite(ms))
return;
const int c = cost_class(n_rows);
double& m = cost_ms_[depth][c];
int64_t& n = cost_n_[depth][c];
if (n >= kCostClipAfter && ms > kCostOutlier * m) ms = kCostOutlier * m;
const double w = std::fmax(1.0 - std::exp2(-1.0 / kCostHalfLife), 1.0 / (double)(n + 1));
m = n ? m + w * (ms - m) : ms;
++n;
}
int64_t DraftController::cost_samples(int depth, int n_rows) const {
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC || n_rows < 1) return 0;
return cost_n_[depth][cost_class(n_rows)];
}
double DraftController::step_cost(int depth, int n_rows) const {
if (depth < 1 || depth > RAD_SCHED_MAX_SPEC) return 0.0;
const int c = n_rows >= 1 ? cost_class(n_rows) : 0;
if (cost_n_[depth][c] > 0) return cost_ms_[depth][c];
/* THE NEAREST MEASURED KEY: in this class first, the nearest depth and the shallower on a
* tie; then the nearest class. Only its ratio to the prior is borrowed, so a class whose steps
* are twice as dear prices every depth twice as dear, and the comparison D makes -- depths at
* ONE class -- reads the prior's shape until its own depths are measured. */
for (int dc = 0; dc < kCostClasses; ++dc) {
for (int sgn = 0; sgn < 2; ++sgn) {
const int k = sgn ? c + dc : c - dc;
if (k < 0 || k >= kCostClasses || (dc == 0 && sgn)) continue;
int best = -1;
for (int d = 1; d <= p_.max_depth; ++d) {
if (cost_n_[d][k] <= 0) continue;
if (best < 0 || std::abs(d - depth) < std::abs(best - depth)) best = d;
}
if (best > 0) return cost_ms_[best][k] * cost_prior(depth) / cost_prior(best);
}
}
return cost_prior(depth);
}
/* ------------------------------------------------------------------ one sequence */
int DraftController::stop_of(const float* a) const {
double p = 1.0;
int d = 0;
while (d < p_.max_depth) {
p *= (double)a[d];
if (p < kDraftMinChance) break;
++d;
}
return d < kMinDepth ? kMinDepth : d;
}
double DraftController::prior_at(int j) const {
if (j < 0 || j >= RAD_SCHED_MAX_SPEC) return 0.0;
return prior_n_ >= kPriorMinSeqs ? (double)prior_[j] : kPrior;
}
void DraftController::start(DraftAdapt& s) const {
/* Each position from the sequences that finished before it once there are enough of them
* (adapt_retire); otherwise from the fixed prior, which is optimistic on purpose (kPrior). */
for (int j = 0; j < p_.max_depth; ++j) {
s.a[j] = (float)prior_at(j);
s.n[j] = 0;
}
s.depth = stop_of(s.a);
s.held = 0;
}
void DraftController::adapt_retire(const DraftAdapt& s) {
if (!adapt_ || s.depth <= 0 || (double)s.n[0] < kHalfLife) return;
const double w = std::fmax(1.0 - std::exp2(-1.0 / kPriorHalfLifeSeqs),
1.0 / (double)(prior_n_ + 1));
for (int j = 0; j < p_.max_depth; ++j)
prior_[j] = prior_n_ ? (float)((double)prior_[j] + w * ((double)s.a[j] - (double)prior_[j]))
: s.a[j];
++prior_n_;
}
double DraftController::yield(const DraftAdapt& s, int d) const {
if (d > p_.max_depth) d = p_.max_depth;
double e = 1.0, run = 1.0;
for (int k = 1; k <= d; ++k) { run *= (double)s.a[k - 1]; e += run; }
return e;
}
int DraftController::window_of(const DraftAdapt& s) const {
if (!adapt_) return p_.max_depth;
if (s.depth <= 0) return 0;
const int D = step_d_ > 0 ? step_d_ : p_.max_depth;
return s.depth < D ? s.depth : D;
}
int DraftController::window_for(DraftAdapt& s) const {
if (!adapt_) return p_.max_depth;
if (s.depth <= 0) start(s);
return window_of(s);
}
int DraftController::adapt_observe(DraftAdapt& s, int drafted, int accepted) const {
if (!adapt_) return p_.max_depth;
if (s.depth <= 0) start(s);
if (drafted <= 0) return s.depth;
const int D = p_.max_depth;
if (drafted > D) drafted = D;
if (accepted < 0) accepted = 0;
if (accepted > drafted) accepted = drafted;
/* THE POSITIONS THIS VERIFY EVALUATED, by observe()'s rule: every one before the first
* rejection, taken, and the rejected one, refused. A position behind the rejection was drafted
* and never looked at, and says nothing either way. */
const int last = accepted < drafted ? accepted : drafted - 1;
for (int j = 0; j <= last; ++j) {
const double w = std::fmax(alpha_, 1.0 / ((double)s.n[j] + kPriorWeight + 1.0));
const double x = j < accepted ? 1.0 : 0.0;
s.a[j] = (float)((double)s.a[j] + w * (x - (double)s.a[j]));
if (s.n[j] < UINT16_MAX) ++s.n[j];
}
/* AND THE POSITIONS THE WINDOW DID NOT REACH DRIFT TOWARD THE DEEPEST ONE IT DID. Nothing is
* learned about them while the window is shorter -- and a sequence held at three by prose that
* turns into code would otherwise keep pricing positions four and up at whatever they read
* before, and never draft deep enough to find out. The guess is that acceptance decays with
* position rather than falling off a cliff, so the window's edge stands in for what lies past
* it. Where that is wrong it costs a move out, the verifies that refute it, and a move back. */
const double edge = (double)s.a[drafted - 1];
for (int j = drafted; j < D; ++j)
s.a[j] = (float)((double)s.a[j] + alpha_ * (edge - (double)s.a[j]));
/* THE STOP MOVES ONLY PAST THE HOLD: it is this sequence's share of the step's shape. */
if (s.held < INT32_MAX) ++s.held;
if (s.held < kHold) return s.depth;
const int d = stop_of(s.a);
if (d != s.depth) {
s.depth = d;
s.held = 0;
}
return s.depth;
}
/* ------------------------------------------------------------------ the step */
int DraftController::plan_step(DraftAdapt* const* seq, int n_seq, int n_rows) {
if (!adapt_ || n_seq <= 0) return step_d_;
if (n_rows < n_seq) n_rows = n_seq;
const int M = p_.max_depth;
/* THE STEP'S EXPECTED TOKENS AT EVERY HEAD DEPTH: sum_i E_i(min(D, stop_i)), plus one for
* every row that does not draft. A depth past every stop is the deepest stop's step -- no
* sequence drafts further and the head runs no further -- so the candidates end there. */
double tok[RAD_SCHED_MAX_SPEC + 1] = {};
int top = kMinDepth;
for (int i = 0; i < n_seq; ++i) {
DraftAdapt& s = *seq[i];
if (s.depth <= 0) start(s);
if (s.depth > top) top = s.depth;
double e = 1.0, run = 1.0;
for (int d = 1; d <= M; ++d) {
if (d <= s.depth) { run *= (double)s.a[d - 1]; e += run; }
tok[d] += e;
}
}
const double plain = (double)(n_rows - n_seq);
if (top > M) top = M;
int best = kMinDepth;
double best_g = -1.0;
for (int d = kMinDepth; d <= top; ++d) {
const double g = (tok[d] + plain) / step_cost(d, n_rows);
if (g > best_g) { best_g = g; best = d; }
}
/* THE MOVE, rate-limited twice: not within kHold steps of the last one, and only for a depth
* worth kHyst more than the one in force. The first step that drafts takes the best outright. */
if (step_d_ <= 0) {
step_d_ = best;
step_held_ = 0;
} else {
if (step_held_ < INT32_MAX) ++step_held_;
const int cur = step_d_ < top ? step_d_ : top;
const double cur_g = (tok[cur] + plain) / step_cost(cur, n_rows);
if (best != cur && step_held_ >= kHold && best_g > cur_g * (1.0 + kHyst)) {
RAD_DEBUG("draft window: head depth %d -> %d over %d drafting of %d rows (%.3f -> "
"%.3f tokens per unit of step cost)", step_d_, best, n_seq, n_rows, cur_g,
best_g);
step_d_ = best;
step_held_ = 0;
}
}
step_w_ = step_d_ < top ? step_d_ : top;
return step_d_;
}
} /* namespace rad */
+190 -4
View File
@@ -1,8 +1,8 @@
/* draft.h -- the speculative draft-depth controller.
*
* IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
* BY DEFAULT IT IS STATIC. The depth is `--num-speculative-tokens` and nothing moves it.
*
* No dynamic policy sits here, and the reason is structural rather than a tuning failure. The
* No dynamic policy sits there, and the reason is structural rather than a tuning failure. The
* dynamic policy this engine is otherwise modelled on -- a confidence-product gate against a
* decayed per-position acceptance estimate, plus a batch-size ceiling schedule -- gates on the
* DRAFTER's own top-1 confidences, per slot, on device, after the drafter has run. The scheduler
@@ -16,6 +16,42 @@
*
* What survives is the accounting, because the acceptance rate is a reported metric (spec §14)
* and because a verify that accepts nothing has to be visible.
*
* UNDER `--draft-window adaptive` THE PREMISE ABOVE IS WHAT DOES NOT HOLD. On a model whose
* weights stream -- a MoE that reads experts per verify row, a serial head that runs one pass a
* round -- a step is NOT flat in depth: each draft is one more round of the head and one more
* verify row. And the best depth is not a property of the model pair but of the TEXT:
* per-position acceptance stays high deep into the window on code and JSON and falls off after a
* position or two on prose and summaries. No constant is right for all of them, and the one that
* is right for one costs the others either rounds nobody accepts or tokens nobody drafted.
*
* So the adaptive window is a policy on the host, in two halves:
*
* PER SEQUENCE (DraftAdapt): a smoothed estimate of each draft position's conditional
* acceptance, fed by the same verify outcomes observe() counts, and the sequence's STOP -- the
* deepest draft whose chance of being emitted still pays for the verify row it adds
* (kDraftMinChance).
*
* PER STEP (plan_step): the HEAD DEPTH D. A serial head runs as many rounds as the deepest
* window in the step, so depth is a property of the step and not of one sequence: D maximises
* the tokens the whole step is expected to emit, sum_i E_i(min(D, stop_i)), over what a step
* at that depth and that many sequences costs, T(D, n) -- with E(d) = 1 + sum_k prod_{j<=k} a_j
* and T measured online (step_time). Every sequence then drafts min(D, stop_i).
*
* Both move only past a hold, and D also past a hysteresis, because a window is a pass shape and
* a new shape is a new recording before it plays (runtime/ctx.h). `max_depth` stays the ceiling,
* and everything sized for it stays sized for it.
*
* IT IS THE SERIAL DRAFTER'S POLICY. A block drafter proposes its whole block in one pass, and
* prompt lookup runs no pass at all, so neither pays the rounds the policy prices; the scheduler
* turns it on only for a serial drafter (Scheduler::init) and says so when it does not.
*
* IT CHANGES HOW MANY DRAFTS A STEP VERIFIES AND NOTHING ELSE. Acceptance is the rule in
* core/sample/accept.h, so what a step emits is the target's own token at every position whatever
* window it verified. At temperature 0 that is the same text at every window, to exactly the
* degree a speculative run matches a plain one at all: exact given the same logits, and a verify
* row's logits are computed at an M that now moves with the window (accept.h says what that does
* and does not change).
*/
#pragma once
#include "rad_core.h"
@@ -26,18 +62,148 @@ namespace rad {
* band (spec §10), so 64 is the largest window any batch can carry. */
enum { RAD_SCHED_MAX_SPEC = 64 };
/* ONE SEQUENCE'S HALF OF THE ADAPTIVE POLICY: what the drafter has done on this sequence's own
* text, and how deep that makes it worth drafting. It lives in the scheduler's per-request state
* and the controller does the arithmetic, so neither has to look the other up.
*
* `depth` 0 is "not started": the first ask fills the estimate from the prior and sets the stop.
* It belongs to the REQUEST, not to the cache it holds -- a preemption keeps it, because the text
* it describes is still the text the request is writing -- and a recycled slot starts it over. */
struct DraftAdapt {
int32_t depth = 0; /* the sequence's stop; 0 = not started */
int32_t held = 0; /* verifies since `depth` last moved */
float a[RAD_SCHED_MAX_SPEC] = {}; /* conditional acceptance at each draft position */
uint16_t n[RAD_SCHED_MAX_SPEC] = {}; /* verifies that evaluated each one, saturating */
};
class DraftController {
public:
struct Params {
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
int max_depth = 0; /* the deployment's window; 0 disables speculation entirely */
/* THE ADAPTIVE POLICY (see the top of this file): `--draft-window adaptive` with a serial
* drafter, which Scheduler::init decides. Off, the depth is max_depth, as it always was. */
bool adapt = false;
};
/* ---------------------------------------------------------- the policy's constants
* Named rather than configurable: each is a property of how the policy works, not of a
* deployment, and the one property that IS a deployment's -- what a step costs -- is
* measured (step_time). */
/* A WINDOW MOVES ONLY FOR TWO PERCENT MORE YIELD. One draft more or less moves E/T by several
* percent on any drafter worth speculating with, while a smoothed estimate wobbles by about
* a percent verify to verify; below two percent a move would flip D between two near-equal
* neighbours and pay a recording each time. */
static constexpr double kHyst = 0.02;
/* AND NOT WITHIN EIGHT VERIFIES (steps, for D) OF THE LAST MOVE. A pass shape is recorded the
* second time its key is seen and played from the third (runtime/ctx.h), so a shape held for
* eight steps plays from the tape for most of them; and eight verifies at the half-life below
* move an estimate by about a third of the way to a new rate, which is a trend rather than
* one rejection. */
static constexpr int kHold = 8;
/* EACH POSITION'S ESTIMATE HAS A HALF-LIFE OF SIXTEEN VERIFIES THAT EVALUATE IT. At a few
* tokens a verify that is some fifty tokens of text: short enough to follow a reply from prose
* into a code block and back, long enough that a single rejection moves an estimate by four
* percent rather than resetting it. */
static constexpr double kHalfLife = 16.0;
/* A POSITION NOTHING HAS MEASURED STARTS AT 0.8, optimistic on purpose: a window that starts
* deep evaluates every position and learns all of them, one that starts shallow learns nothing
* about the positions it never drafts to. 0.8 sits between what draft heads measure on prose
* and on code at the first positions, so a wrong start is corrected within a hold. */
static constexpr double kPrior = 0.8;
/* ONCE FOUR SEQUENCES HAVE FINISHED, A NEW ONE STARTS FROM WHAT THEY ENDED ON (adapt_retire):
* the mean of their estimates, a running mean and then a moving average with a half-life of 32
* sequences, so a deployment that moves from one kind of traffic to another follows it within
* a few dozen requests. Four, because a mean over fewer is one text's. A sequence counts only
* once it has had a half-life of verifies: before that its estimate is mostly the prior it
* started from, and folding it back would feed the prior to itself. */
static constexpr int kPriorMinSeqs = 4;
static constexpr double kPriorHalfLifeSeqs = 32.0;
/* NEVER FEWER THAN ONE DRAFT. A sequence at zero would evaluate no position, so nothing could
* ever move its estimate off zero again. */
static constexpr int kMinDepth = 1;
/* A SEQUENCE STOPS AT THE FIRST DRAFT WHOSE CHANCE OF BEING EMITTED -- every draft before it
* and itself accepted, prod_{j<=d} a_j -- IS UNDER ONE IN TEN. The draft adds a verify row to
* the step whatever D is, and that row is the only cost a sequence adds once the head runs D
* rounds for its deepest neighbour. At one sequence the step-cost prior (1 + 0.06 d) already
* breaks even near that chance -- one more draft is worth it while p_d / E exceeds the 5-6 %
* it adds to the step, with E around two -- and a verify row alone costs less than a round
* plus a row, so the threshold is never stricter than D's own trade. A constant rather than a
* measurement: a row's share of the step is not separable from the head's rounds in step
* times keyed by depth, and the measured T(D, n) already prices the rounds. */
static constexpr double kDraftMinChance = 0.1;
/* STEP TIMES ARE KEPT IN THESE RUNNING-SEQUENCE CLASSES: 1, 2-3, 4-7, 8-15, 16 and up. A
* step's cost moves with how many rows share its weight reads, and a class a power of two
* wide keeps every key fed often enough to mean something. */
static constexpr int kCostClasses = 5;
int configure(const Params& p);
const Params& params() const { return p_; }
/* The draft depth for the next step. 0 means "do not speculate". Constant by construction. */
/* The draft depth for the next step. 0 means "do not speculate". Constant by construction:
* under the adaptive policy it is the CEILING, and window_for() is the window. */
int next_depth() const { return p_.max_depth; }
/* ---------------------------------------------------------- the adaptive policy */
bool adaptive() const { return adapt_; }
/* The window this sequence may draft into: min(D, its stop), starting its estimate on the
* first ask; max_depth when the policy is off. Before any step has chosen D, D is the
* ceiling. */
int window_for(DraftAdapt& s) const;
/* The same for a sequence whose estimate has started, without starting one: 0 when it has
* not. For reporting. */
int window_of(const DraftAdapt& s) const;
/* One verify of this sequence: `drafted` proposed, a prefix of `accepted` taken. Moves its
* estimate, and its stop past the hold. Returns the stop after. */
int adapt_observe(DraftAdapt& s, int drafted, int accepted) const;
/* A SEQUENCE THAT HAS FINISHED: its estimate joins the prior the next sequences start from.
*
* PER SEQUENCE, NOT PER VERIFY. The deployment's own counts -- accepted(j) / reached(j) over
* every verify -- are what a fixed window would want, and under this policy they are biased:
* only a sequence whose drafts keep being accepted is given a window that reaches the deep
* positions, so those positions are measured almost only on the texts that predict well, and
* a new sequence would start as if every text did. Each finished sequence counts once here, at
* every position, and at a position it never reached its estimate is the extrapolation from
* its own window's edge (adapt_observe) -- a shallow text pulls the deep positions down as
* much as a deep one holds them up. */
void adapt_retire(const DraftAdapt& s);
/* The prior a sequence starting now is given at position `j`. For tests and logs. */
double prior_at(int j) const;
/* D FOR THE STEP THAT IS OPENING. `seq` are the estimates of the `n_seq` sequences that will
* draft in it, `n_rows` the decode rows it carries in all (the rest emit one token each and
* draft nothing). Started here if they have not been. Moves D past the hold and the
* hysteresis; with no sequence to draft, D stays. Returns D. */
int plan_step(DraftAdapt* const* seq, int n_seq, int n_rows);
/* The step depth in force: 0 before the first step chose one. */
int step_depth() const { return step_d_; }
/* The deepest window a step at that depth carries: D, but no deeper than the deepest stop it
* was chosen over, since no head-drafting sequence drafts past its stop; the ceiling before
* any step chose one, and with the policy off. What a proposal from outside the head (prompt
* lookup) is held to, so it adds no deeper pass shape than the head's own. */
int step_window() const { return adapt_ && step_w_ > 0 ? step_w_ : p_.max_depth; }
/* T(depth, n): a decode step whose deepest window was `depth`, with `n_rows` decode rows,
* took `ms` from the end of the step before it. Fed by Scheduler::step_finished; only the
* adaptive policy reads it. */
void step_time(int depth, int n_rows, double ms);
/* What a step at `depth` with `n_rows` rows is expected to cost, in ms when anything has
* been measured: the key's own mean when it has samples; the nearest measured key scaled by
* the prior's ratio (1 + 0.06 d) when it does not; the prior itself when nothing has been
* measured. */
double step_cost(int depth, int n_rows) const;
/* Samples behind a key: for tests and logs. */
int64_t cost_samples(int depth, int n_rows) const;
/* E(d) for `s`'s estimate as it stands: the tokens a verify of d drafts is expected to emit,
* the verified token included. For tests and logs. */
double yield(const DraftAdapt& s, int d) const;
/* Verifies by the window they carried, counted only under the policy: the histogram of the
* depths it actually chose, which the mean gauge on its own cannot show. */
int64_t verified_at(int d) const {
return (d >= 0 && d <= RAD_SCHED_MAX_SPEC) ? by_depth_[d] : 0;
}
/* One verify's outcome: `drafted` tokens were proposed and a prefix of `accepted` of them was
* taken. Feeds the reported metrics and nothing else. */
void observe(int drafted, int accepted);
@@ -76,6 +242,26 @@ private:
int64_t reach_[RAD_SCHED_MAX_SPEC] = {};
int64_t hit_ [RAD_SCHED_MAX_SPEC] = {};
int seen_ = 0;
/* The adaptive policy as configure() resolved it. */
bool adapt_ = false;
double alpha_ = 0.0; /* the smoothing step from kHalfLife */
int64_t by_depth_[RAD_SCHED_MAX_SPEC + 1] = {};
int32_t step_d_ = 0; /* D; 0 until a step chose one */
int32_t step_w_ = 0; /* min(D, the deepest stop it saw) */
int32_t step_held_ = 0; /* steps since D last moved */
/* The prior from finished sequences (adapt_retire), and how many are behind it. */
float prior_[RAD_SCHED_MAX_SPEC] = {};
int64_t prior_n_ = 0;
/* T(d, class): the mean step time of each key, and the steps behind it. */
double cost_ms_[RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
int64_t cost_n_ [RAD_SCHED_MAX_SPEC + 1][kCostClasses] = {};
/* Fill a sequence's estimate from the prior and set its first stop. */
void start(DraftAdapt& s) const;
/* The deepest draft whose chance of being emitted is at least kDraftMinChance. */
int stop_of(const float* a) const;
static int cost_class(int n_rows);
};
} /* namespace rad */
+7
View File
@@ -137,6 +137,13 @@ struct SchedMetrics {
int draft_depth_seen = 0;
int64_t draft_pos_reached [RAD_METRICS_MAX_SPEC] = {};
int64_t draft_pos_accepted[RAD_METRICS_MAX_SPEC] = {};
/* THE ADAPTIVE WINDOW (--draft-window adaptive, draft.h), all zero while it is off. The mean
* window it gives the sequences running now -- at one sequence, that sequence's window -- and
* the verifies by the window they carried, index = drafts verified, cumulative: the gauge says
* where the policy stands, the histogram where it has been. */
bool draft_adaptive = false;
float draft_depth_adaptive = 0.0f;
int64_t draft_verify_depth[RAD_METRICS_MAX_SPEC + 1] = {};
};
} /* namespace rad */
+159 -6
View File
@@ -97,7 +97,29 @@ int Scheduler::init(Program& prog, const Config& cfg, IKVManager* kv, IPrefixCac
DraftController::Params dp;
dp.max_depth = cfg.n_spec;
/* THE ADAPTIVE WINDOW IS THE SERIAL DRAFTER'S POLICY (draft.h): it prices a draft as one more
* round of the head. A block drafter proposes its block in one pass and prompt lookup runs no
* pass at all, so for either the window stays fixed -- decided here, once, before any step
* has counted an acceptance, and said, because a flag that changes nothing reads exactly
* like a flag that made no difference. */
if (cfg.draft_window == DraftWindow::Adaptive) {
const RadDrafterDecl& dd = prog.drafter;
if (cfg.n_spec <= 0)
RAD_WARN("--draft-window adaptive: this deployment does not speculate "
"(--num-speculative-tokens %d), so there is no window to adapt", cfg.n_spec);
else if (dd.kind != RAD_DRAFT_SERIAL || dd.depth <= 0)
RAD_WARN("--draft-window adaptive: the window is fixed at %d with %s -- the adaptive "
"window prices the rounds of a serial draft head, which this deployment does "
"not run", cfg.n_spec,
dd.kind == RAD_DRAFT_BLOCK ? "a block drafter, which proposes its block in one "
"pass"
: "prompt lookup only");
else
dp.adapt = true;
}
RAD_TRY(draft_.configure(dp));
draft_est_.clear();
draft_est_.reserve((size_t)cfg.max_seqs);
RAD_TRY(builder_.init(prog, cfg, geo_, kvgeom_, ranks));
/* The builder's bound and not a second derivation of it: it is what the block tables were
@@ -178,6 +200,9 @@ int Scheduler::add_locked(std::unique_ptr<Request> r) {
s.card = -1;
s.running = false;
s.drafter_reset();
/* A NEW REQUEST'S TEXT, so a new estimate: the slot's last tenant was writing something else. */
s.adapt.depth = 0;
s.adapt.held = 0;
s.sched_tokens = 0;
s.entry = -1;
s.entry_next = -1;
@@ -221,8 +246,15 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
/* THE NEXT STEP ALREADY VERIFIES THESE. It was planned with the count the drafter issued, and
* the card already put the tokens in its batch; the host copy is what that step's commit
* emits the accepted ones from, so it takes exactly those, unclamped. */
* emits the accepted ones from, so it takes exactly those, unclamped.
*
* UNDER THE ADAPTIVE WINDOW THE DRAFTER RAN AS MANY ROUNDS AS THE DEEPEST SEQUENCE WANTED,
* and expect_draft() already cut this one's count to its own window -- the card verifies the
* FIRST draft_next of the proposals, which are these. So a longer proposal is cut to that
* count here, against the number the step was planned with: the window itself may have moved
* at the commit in between, and the planned step is what these tokens are for. */
if (next_open_ && s.entry_next >= 0) {
if (draft_.adaptive() && n > s.draft_next) n = s.draft_next;
if (n != s.draft_next) {
RAD_ERR("request %llu: %d draft(s) published for a step planned to verify %d",
(unsigned long long)id, n, s.draft_next);
@@ -244,7 +276,7 @@ int Scheduler::set_draft(uint64_t id, const int32_t* tokens, int n) {
return RAD_OK;
}
int cap = draft_.next_depth();
int cap = draft_cap(s);
if (n > cap) n = cap;
if (n > RAD_SCHED_MAX_SPEC) n = RAD_SCHED_MAX_SPEC;
for (int i = 0; i < n; ++i) s.draft[i] = tokens[i];
@@ -353,6 +385,12 @@ void Scheduler::close_request(SchedReq& s, ReqState st, const char* reason, bool
}
if (cfg_.prefix_cache && pc_) pc_->release(*s.req);
/* What the draft head did on this text is now part of what the next text starts from --
* once: the estimate is marked unstarted, so a second close of the same request adds nothing. */
if (draft_.adaptive()) {
draft_.adapt_retire(s.adapt);
s.adapt.depth = 0;
}
if (defer_free) {
if (!s.pending_free) ++n_deferred_;
@@ -924,6 +962,8 @@ void Scheduler::undo_hit(SchedReq& s) {
/* ------------------------------------------------------------------ the step */
const RadBatch* Scheduler::step() {
std::lock_guard<std::mutex> lk(mu_);
/* A cycle opens here, so its head depth is chosen here (scheduler.h, draft_cycle). */
draft_cycle();
/* The drafter's snapshots describe the step before this one and nothing reads them from here
* on. block_end() and serial_end() clear them already; this covers a drafter that stopped
@@ -979,10 +1019,22 @@ const RadBatch* Scheduler::step() {
/* THE LAST GATE, and it has to be here rather than only at set_draft, because the
* n-gram fallback below fills any proposal a drafter left empty -- so refusing a
* draft upstream and stopping there hands the request a different draft instead of
* none. Request::may_speculate says why a request can be ineligible. */
* none. Request::may_speculate says why a request can be ineligible.
*
* AND THE CAP IS THE SEQUENCE'S OWN WINDOW, which is `depth` unless the adaptive
* policy is on -- then it is what this sequence's acceptance of the HEAD's drafts pays
* for. The n-gram fallback is not the head and that estimate says nothing about it, so
* it is held to the step's window instead: as deep as the head drafts this step and no
* deeper, which adds no pass shape the head's own windows do not. */
const int cap = draft_.adaptive() ? draft_cap(s) : depth;
bool ngram = false;
if (!r.may_speculate) s.n_draft = 0;
else if (s.n_draft == 0) s.n_draft = (int32_t)draft_ngram(s, depth);
if (s.n_draft > depth) s.n_draft = depth;
else if (s.n_draft == 0) {
s.n_draft = (int32_t)draft_ngram(s, draft_.step_window());
ngram = s.n_draft > 0;
}
if (!ngram && s.n_draft > cap) s.n_draft = cap;
s.draft_ngram = ngram;
/* NO VERIFIED POSITION AT OR PAST THE CONTEXT. The step computes positions n_computed
* .. n_computed + n_draft, and nothing past ctx_limit_ - 1 has a rotary row or a
* block-table column. commit() finishes a sequence before its length reaches the
@@ -1069,6 +1121,7 @@ const RadBatch* Scheduler::step() {
e.draft = s.draft;
e.n_draft = s.n_draft;
e.is_prefill = prefill;
e.ngram = !prefill && s.draft_ngram && s.n_draft > 0;
e.produces_token = (r.n_computed + want >= target);
/* The snapshot a hit resumes from, consumed once: the state is in the slot for the whole
* sequence after this, and restoring it again on a later chunk would rewind it. */
@@ -1335,12 +1388,39 @@ void Scheduler::take_encodes(std::vector<std::shared_ptr<mm::Item>>* out) {
out->swap(enc_want_);
}
/* ------------------------------------------------------------------ the step's head depth */
void Scheduler::draft_cycle() {
if (!draft_.adaptive()) return;
/* THE ROWS THE OPENING STEP WILL DECODE: every running sequence past its prompt. Those that
* may speculate draft, and their estimates choose D; the rest emit one token each, which is
* part of what the step yields and of what it costs. A sequence still prefilling is neither. */
draft_est_.clear();
int n_rows = 0;
for (int32_t slot : running_) {
SchedReq& s = *reqs_[(size_t)slot];
if (!s.req || !s.running) continue;
const Request& r = *s.req;
if (r.n_computed < (int64_t)r.prompt.size() || r.n_computed + 1 < s.seq_len()) continue;
++n_rows;
if (r.may_speculate) draft_est_.push_back(&s.adapt);
}
(void)draft_.plan_step(draft_est_.data(), (int)draft_est_.size(), n_rows);
}
/* ------------------------------------------------------------------ the next step */
void Scheduler::expect_draft(uint64_t id, int n) {
std::lock_guard<std::mutex> lk(mu_);
auto it = by_id_.find(id);
if (it == by_id_.end()) return;
reqs_[(size_t)it->second]->draft_next = n > 0 ? n : 0;
SchedReq& s = *reqs_[(size_t)it->second];
/* UNDER THE ADAPTIVE WINDOW THE ROUNDS RAN FOR THE DEEPEST SEQUENCE, and this one verifies the
* first of them up to its own window -- the cap serial_begin sized the rounds from, unchanged
* since: nothing commits between the two, and D is the cycle's (draft_cycle). */
if (draft_.adaptive() && n > 0) {
const int cap = draft_cap(s);
if (n > cap) n = cap;
}
s.draft_next = n > 0 ? n : 0;
}
const RadBatch* Scheduler::step_next() {
@@ -1424,6 +1504,10 @@ const RadBatch* Scheduler::step_next_locked() {
void Scheduler::promote_next() {
std::lock_guard<std::mutex> lk(mu_);
if (!next_open_) return;
/* The other place a cycle opens: the step issued ahead becomes this one, and step() is not
* called. Its proposals were counted under the last cycle's D; the next ones are drafted
* under this one. */
draft_cycle();
std::swap(plan_, plan_next_);
plan_next_.reset();
step_prefill_tok_ = 0;
@@ -1581,6 +1665,28 @@ int Scheduler::commit(const StepResult& res) {
if (e.n_spec > 0) {
draft_.observe(e.n_spec, a);
/* AND THIS SEQUENCE'S OWN ESTIMATE, from the same outcome, under the adaptive
* window -- when the head drafted it. A prompt-lookup proposal is accepted on
* different text by a different rule, and folding it in would price the head's
* next window on what the lookup found. A move takes effect at the next draft:
* this step's drafter has already run, sized from the estimate as it stood before
* this commit. */
if (draft_.adaptive() && !e.ngram) {
const int was = s.adapt.depth;
const int now = draft_.adapt_observe(s.adapt, e.n_spec, a);
if (now != was && was > 0 && (int)log_level() >= (int)Log::Debug) {
char est[8 * RAD_SCHED_MAX_SPEC];
int o = 0;
for (int j = 0; j < draft_.next_depth() && o < (int)sizeof est - 8; ++j)
o += std::snprintf(est + o, sizeof est - (size_t)o, "%s%.2f",
j ? " " : "", (double)s.adapt.a[j]);
est[o] = 0;
RAD_DEBUG("draft window: request %llu stops at %d, was %d (expected "
"tokens a verify %.3f -> %.3f; acceptance by position %s)",
(unsigned long long)r.id, now, was, draft_.yield(s.adapt, was),
draft_.yield(s.adapt, now), est);
}
}
m_.draft_tokens += e.n_spec;
m_.draft_accepted += a;
server::sink_drafts(r.sink, e.n_spec, a);
@@ -1707,6 +1813,16 @@ void Scheduler::step_finished() {
if (m_.prefill_tps < 0.05f) m_.prefill_tps = 0.0f;
if (m_.decode_tps < 0.05f) m_.decode_tps = 0.0f;
}
/* AND WHAT THE STEP COST AT ITS DEPTH, for the adaptive window (draft.h): the same wall time,
* which is the step's share of the loop -- the draft rounds that followed it included, and a
* step issued ahead counted from the end of the one before rather than twice. A decode step
* only: a prefill chunk's time is the chunk's, not the window's. Keyed by the deepest window
* the step verified, which is the head depth it ran at whenever D held from the step before. */
if (draft_.adaptive() && plan_.phase == RAD_PHASE_DECODE && plan_.n_spec > 0 && wall > 0) {
int rows = 0;
for (const StepEntry& e : plan_.e) rows += (e.produces_token && !e.is_prefill) ? 1 : 0;
draft_.step_time((int)plan_.n_spec, rows, wall * 1e3);
}
last_step_at_ = step_end;
/* So a second call, or one on a loop iteration that ran no step, charges nothing. */
step_start_ = {};
@@ -1740,6 +1856,27 @@ int Scheduler::serial_begin(int* rounds, SerialRow* out, int max) {
if (depth > 0 && *rounds > depth) *rounds = depth;
if (*rounds > RAD_SCHED_MAX_SPEC) *rounds = RAD_SCHED_MAX_SPEC;
/* UNDER THE ADAPTIVE WINDOW, NO MORE ROUNDS THAN THE DEEPEST SEQUENCE WANTS. A round is one
* pass of the head over every drafting row, so the step runs as many as its deepest window,
* and a sequence that wants fewer verifies the first of them (expect_draft, set_draft); a
* round past the deepest window is a pass whose proposal nobody verifies. Only a row that will
* draft and be given its drafts counts. When no row does, the rounds stay as they are: round 0
* is the history pass, and that still has to run. The reservation below is then made for the
* rounds that will actually run, which is what it is for. */
if (may_draft && draft_.adaptive()) {
int want = 0;
for (const StepEntry& e : plan_.e) {
if (!e.produces_token || e.slot < 0 || (size_t)e.slot >= reqs_.size()) continue;
SchedReq& s = *reqs_[(size_t)e.slot];
if (!s.req || s.req->state != ReqState::Running || !s.running ||
!s.req->may_speculate)
continue;
const int c = draft_cap(s);
if (c > want) want = c;
}
if (want > 0 && *rounds > want) *rounds = want;
}
int n_draft_rows = 0;
int64_t cu = 0; /* this entry's first token in the step just run */
for (size_t i = 0; i < plan_.e.size(); ++i) {
@@ -2293,6 +2430,22 @@ SchedMetrics Scheduler::metrics_locked() const {
m.draft_pos_reached [j] = draft_.reached(j);
m.draft_pos_accepted[j] = draft_.hits(j);
}
if (draft_.adaptive()) {
m.draft_adaptive = true;
/* Over the running sequences whose estimate has started; one that has not drafted yet
* has no window to report. */
int64_t sum = 0, n = 0;
for (int32_t slot : running_) {
const SchedReq& s = *reqs_[(size_t)slot];
if (s.adapt.depth <= 0) continue;
/* The window it drafts into: its stop under the step's head depth. */
sum += draft_.window_of(s.adapt);
++n;
}
m.draft_depth_adaptive = n ? (float)((double)sum / (double)n) : 0.0f;
const int kDepth = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
for (int d = 0; d < kDepth; ++d) m.draft_verify_depth[d] = draft_.verified_at(d);
}
return m;
}
+35 -2
View File
@@ -109,6 +109,14 @@ struct SchedReq {
draft_hi = 0;
}
/* THE ADAPTIVE DRAFT WINDOW'S ESTIMATE FOR THIS REQUEST (--draft-window adaptive, draft.h), and
* deliberately NOT in drafter_reset(): it describes the text the request is writing, which a
* preemption does not change, rather than any cache the request holds. A recycled slot starts
* it over in add_locked. Untouched while the policy is off. */
DraftAdapt adapt;
/* The proposal the step being planned carries came from prompt lookup (StepEntry::ngram). */
bool draft_ngram = false;
int32_t sched_tokens = 0; /* tokens given to this request in the current step */
int32_t entry = -1; /* its index in the current StepPlan, or -1 */
/* Its index in the NEXT step, already issued while this one runs (step_next), or -1; and the
@@ -280,7 +288,8 @@ public:
* the one that is stuck. Returns how many were written. */
int requests(ReqStat* out, int max) const;
/* The drafter's proposal for a request's next step. n is clamped to the controller's depth. */
/* The drafter's proposal for a request's next step. n is clamped to the sequence's window
* (draft_cap): the controller's depth, or what the adaptive policy gives the sequence. */
int set_draft(uint64_t id, const int32_t* tokens, int n);
/* ---------------------------------------------------------- media the encoder owes
@@ -318,7 +327,8 @@ public:
* from one to the other.
*
* expect_draft after the drafter is issued: how many drafts it proposes for a sequence,
* which is how many the next step verifies.
* which is how many the next step verifies -- capped at the sequence's window,
* which under the adaptive policy can be fewer than the rounds that ran.
* step_next plans and builds that step: every row of this one, as a device row, at
* the furthest context it can reach. Null -- and the engine plans with step()
* after this one commits -- whenever the step needs a decision only a
@@ -491,6 +501,29 @@ private:
return hit_holes_draft_ ? ctx_len : 0;
}
/* THE WINDOW A SEQUENCE MAY DRAFT INTO: the configured depth, or under the adaptive window
* min(D, its stop) (DraftController::window_for, which starts the estimate on the first ask).
* It is the rule every site that caps a proposal applies -- step(), set_draft(),
* expect_draft() and the rounds in serial_begin() -- and with the policy off it is
* next_depth(), exactly as before. */
int draft_cap(SchedReq& s) const {
return draft_.adaptive() ? draft_.window_for(s.adapt) : draft_.next_depth();
}
/* THE STEP'S HEAD DEPTH D IS CHOSEN ONCE A CYCLE AND HELD, by draft_cycle(), which is the
* first thing step() and promote_next() do -- every cycle opens with exactly one of the two.
* A cycle's proposal passes through four sites -- the plan that verifies it, the rounds that
* draft the next one, expect_draft() and set_draft() -- and the step issued ahead holds them
* to agree: it was built with the count expect_draft() gave it, and set_draft() refuses a
* different one. A D read live could move between them, because a commit or a client hanging
* up changes the running set mid-cycle; held, it moves only where a cycle starts, and a
* proposal drafted under one D and planned under the next is only ever cut shorter.
*
* `draft_est_` is the list plan_step reads, reserved at init so the step path does not
* allocate. */
std::vector<DraftAdapt*> draft_est_;
void draft_cycle();
/* The built-in prompt-lookup drafter (scheduler.cpp). Fills s.draft and returns how many
* tokens it proposed; 0 when the sequence has no repeated pattern to extend. The pattern
* lengths it tries, longest first. */
+7
View File
@@ -280,6 +280,13 @@ public:
o.draft_pos_reached [j] = m.draft_pos_reached [j];
o.draft_pos_accepted[j] = m.draft_pos_accepted[j];
}
o.draft_adaptive = m.draft_adaptive;
o.draft_depth_adaptive = m.draft_depth_adaptive;
{
const int ka = (int)(sizeof m.draft_verify_depth / sizeof m.draft_verify_depth[0]);
const int kb = (int)(sizeof o.draft_verify_depth / sizeof o.draft_verify_depth[0]);
for (int d = 0; d < ka && d < kb; ++d) o.draft_verify_depth[d] = m.draft_verify_depth[d];
}
o.preemptions = m.preemptions;
o.total_requests = m.admitted;
o.steps = m.steps;
+5
View File
@@ -114,6 +114,11 @@ struct SchedMetrics {
int draft_depth_seen = 0;
int64_t draft_pos_reached [MAX_DRAFT_POS] = {};
int64_t draft_pos_accepted[MAX_DRAFT_POS] = {};
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive), all zero while it is off: the mean window
* of the running sequences, and the verifies by the window they carried (index = drafts). */
bool draft_adaptive = false;
double draft_depth_adaptive = 0.0;
int64_t draft_verify_depth[MAX_DRAFT_POS + 1] = {};
int64_t preemptions = 0;
int64_t total_requests = 0;
/* ENGINE STEPS. One forward pass of the model plus whatever draft rounds followed it, which
+38 -1
View File
@@ -140,11 +140,23 @@ void Metrics::sample(const SchedMetrics& m) {
for (int j = 0; j < seen; ++j) {
const int64_t r = m.draft_pos_reached[j];
g_draft_pos_reached_[j].set((double)r);
g_draft_pos_accepted_[j].set((double)m.draft_pos_accepted[j]);
g_draft_pos_[j].set(r ? (double)m.draft_pos_accepted[j] / (double)r : 0.0);
}
/* Published after the gauges it bounds, so a concurrent render never lists a position whose
* gauge has not been written yet. */
draft_pos_seen_.store(seen, std::memory_order_release);
if (m.draft_adaptive) {
g_draft_depth_adapt_.set(m.draft_depth_adaptive);
int top = 0;
for (int d = 1; d <= (int)MAX_DRAFT_POS; ++d) {
g_draft_vdepth_[d].set((double)m.draft_verify_depth[d]);
if (m.draft_verify_depth[d] > 0) top = d;
}
/* After the gauges, for the reason above. */
draft_vdepth_top_.store(top, std::memory_order_release);
draft_adapt_on_.store(true, std::memory_order_release);
}
c_preemptions_.inc(std::max(0.0, (double)m.preemptions - c_preemptions_.get()));
c_steps_.inc(std::max(0.0, (double)m.steps - c_steps_.get()));
c_steps_prefill_.inc(std::max(0.0, (double)m.steps_prefill - c_steps_prefill_.get()));
@@ -382,7 +394,9 @@ std::string Metrics::render() const {
/* CONDITIONAL, per draft position: of the verifies that reached position j -- every earlier
* one accepted -- the fraction that took j as well. The pooled ratio above cannot tell a
* drafter that decays from one whose later rounds are broken; these can, and the companion
* `_reached_total` says how much evidence each position carries. */
* `_reached_total` says how much evidence each position carries. `_accepted_total` gives the
* same ratio over any window: at a fixed depth the next position's reach would do, but an
* adaptive window can end at j with j taken. */
const int seen = draft_pos_seen_.load(std::memory_order_acquire);
if (seen > 0) {
const std::string base = L.substr(0, L.size() - 1);
@@ -397,6 +411,29 @@ std::string Metrics::render() const {
for (int j = 0; j < seen; ++j)
w.out += "radiance:draft_position_reached_total" + base + ",position=\"" +
std::to_string(j) + "\"} " + num(g_draft_pos_reached_[j].get()) + '\n';
w.help("radiance:draft_position_accepted_total",
"Verifies that accepted each draft position.", "counter");
for (int j = 0; j < seen; ++j)
w.out += "radiance:draft_position_accepted_total" + base + ",position=\"" +
std::to_string(j) + "\"} " + num(g_draft_pos_accepted_[j].get()) + '\n';
}
/* THE ADAPTIVE DRAFT WINDOW, only while --draft-window adaptive is in force: where the policy stands --
* at one sequence, that sequence's window -- and where it has been, as verifies by the
* number of drafts they carried. */
if (draft_adapt_on_.load(std::memory_order_acquire)) {
w.gauge("radiance:draft_depth_adaptive",
"Mean draft window the adaptive policy gives the running sequences.",
L, g_draft_depth_adapt_.get());
const int top = draft_vdepth_top_.load(std::memory_order_acquire);
if (top > 0) {
const std::string base = L.substr(0, L.size() - 1);
w.help("radiance:draft_verify_depth_total",
"Verifies by the number of drafts they carried, under the adaptive window.",
"counter");
for (int d = 1; d <= top; ++d)
w.out += "radiance:draft_verify_depth_total" + base + ",depth=\"" +
std::to_string(d) + "\"} " + num(g_draft_vdepth_[d].get()) + '\n';
}
}
w.gauge("radiance:num_requests_preempted",
"Requests currently preempted and awaiting recompute.", L, g_preempted_.get());
+8
View File
@@ -121,7 +121,15 @@ private:
enum { MAX_DRAFT_POS = 64 };
Gauge g_draft_pos_[MAX_DRAFT_POS];
Gauge g_draft_pos_reached_[MAX_DRAFT_POS];
Gauge g_draft_pos_accepted_[MAX_DRAFT_POS];
std::atomic<int> draft_pos_seen_{0};
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive): the mean window of the running sequences,
* and the verifies by the window they carried, index = drafts. Rendered only while the policy
* is on, so a deployment without it exposes exactly what it always did. */
Gauge g_draft_depth_adapt_;
Gauge g_draft_vdepth_[MAX_DRAFT_POS + 1];
std::atomic<bool> draft_adapt_on_{false};
std::atomic<int> draft_vdepth_top_{0}; /* the deepest window with a verify counted */
/* sample() turns the scheduler's cumulative totals into counter increments by reading each
* counter and adding the difference. Two scrapes doing that at once both read the old value
+3 -4
View File
@@ -28,11 +28,10 @@ Window values are counter ratios with the definitions of the since-start gauges:
| prompt from attention cache | `attn_cached_tokens` / `prompt_tokens` | `vllm:gpu_prefix_cache_hit_rate` |
| prompt from linear checkpoint | `linear_cached_tokens` / (`linear_cached_tokens` + `prefill_tokens`) | `radiance:linear_prefix_cache_hit_rate` |
| draft acceptance | `draft_accepted` / `draft_tokens` | `radiance:draft_acceptance_ratio` |
| conditional acceptance at j | `draft_position_reached`(j+1) / `draft_position_reached`(j) | `radiance:draft_position_acceptance_ratio` |
| conditional acceptance at j | `draft_position_accepted`(j) / `draft_position_reached`(j) | `radiance:draft_position_acceptance_ratio` |
Position j+1 is evaluated only when j was accepted, so its reach counts j's acceptances. The last
position's acceptances are the total accepted minus every later reach. Draft blocks per decode step is
the reach of position 0 over `engine_steps_decode_total` (GUIDE §6.3).
Draft blocks per decode step is the reach of position 0 over `engine_steps_decode_total` (GUIDE §6.3).
The adaptive draft window and verifies by draft depth have data only under `--draft-window adaptive`.
Prometheus extrapolates `rate()` inside the window and VictoriaMetrics does not, so short windows at
the edge of a burst differ between the two. The overview's ratios are taken over the dashboard's time
+143 -33
View File
@@ -1252,7 +1252,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"description": "In the window: of the verifies that reached position j, the fraction that took j as well. Position j+1 is reached only when j was accepted, so this is reached(j+1) / reached(j); the last position is the total accepted minus every later reach. A late position that collapses while the pooled rate looks fine shows here first.",
"description": "In the window: of the verifies that reached position j, the fraction that took j as well, accepted(j) / reached(j). A late position that collapses while the pooled rate looks fine shows here first.",
"gridPos": {
"h": 8,
"w": 12,
@@ -1265,7 +1265,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"0\"}[$__rate_interval]))",
"legendFormat": "position 0",
"refId": "A",
"range": true,
@@ -1276,7 +1276,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"1\"}[$__rate_interval]))",
"legendFormat": "position 1",
"refId": "B",
"range": true,
@@ -1287,7 +1287,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"2\"}[$__rate_interval]))",
"legendFormat": "position 2",
"refId": "C",
"range": true,
@@ -1298,7 +1298,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"3\"}[$__rate_interval]))",
"legendFormat": "position 3",
"refId": "D",
"range": true,
@@ -1309,7 +1309,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"4\"}[$__rate_interval]))",
"legendFormat": "position 4",
"refId": "E",
"range": true,
@@ -1320,7 +1320,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"5\"}[$__rate_interval]))",
"legendFormat": "position 5",
"refId": "F",
"range": true,
@@ -1331,7 +1331,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"6\"}[$__rate_interval]))",
"legendFormat": "position 6",
"refId": "G",
"range": true,
@@ -1342,7 +1342,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"7\"}[$__rate_interval]))",
"legendFormat": "position 7",
"refId": "H",
"range": true,
@@ -1353,7 +1353,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"8\"}[$__rate_interval]))",
"legendFormat": "position 8",
"refId": "I",
"range": true,
@@ -1364,7 +1364,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"9\"}[$__rate_interval]))",
"legendFormat": "position 9",
"refId": "J",
"range": true,
@@ -1375,7 +1375,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"10\"}[$__rate_interval]))",
"legendFormat": "position 10",
"refId": "K",
"range": true,
@@ -1386,7 +1386,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"11\"}[$__rate_interval]))",
"legendFormat": "position 11",
"refId": "L",
"range": true,
@@ -1397,7 +1397,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"12\"}[$__rate_interval]))",
"legendFormat": "position 12",
"refId": "M",
"range": true,
@@ -1408,7 +1408,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"13\"}[$__rate_interval]))",
"legendFormat": "position 13",
"refId": "N",
"range": true,
@@ -1419,7 +1419,7 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval]))",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"14\"}[$__rate_interval]))",
"legendFormat": "position 14",
"refId": "O",
"range": true,
@@ -1430,8 +1430,8 @@
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "(sum(rate(radiance:draft_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval])) - sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position!=\"0\"}[$__rate_interval]))) / min(sum by (position) (rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval])))",
"legendFormat": "last position",
"expr": "sum(rate(radiance:draft_position_accepted_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval])) / sum(rate(radiance:draft_position_reached_total{instance=~\"$instance\", model_name=~\"$model_name\", position=\"15\"}[$__rate_interval]))",
"legendFormat": "position 15",
"refId": "P",
"range": true,
"instant": false
@@ -1743,6 +1743,116 @@
}
}
},
{
"type": "timeseries",
"title": "Adaptive draft window",
"id": 42,
"datasource": {
"type": "prometheus",
"uid": "${datasource}"
},
"description": "Mean draft window the adaptive policy gives the running sequences; a gap while none runs. Only under --draft-window adaptive; no data otherwise.",
"gridPos": {
"h": 8,
"w": 12,
"x": 0,
"y": 43
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "max by (instance) (radiance:draft_depth_adaptive{instance=~\"$instance\", model_name=~\"$model_name\"}) > 0",
"legendFormat": "{{instance}}",
"refId": "A",
"range": true,
"instant": false
}
],
"fieldConfig": {
"defaults": {
"unit": "short",
"custom": {
"lineWidth": 1,
"fillOpacity": 5,
"showPoints": "never",
"stacking": {
"mode": "none",
"group": "A"
}
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
}
},
{
"type": "timeseries",
"title": "Verifies by draft depth",
"id": 43,
"datasource": {
"type": "prometheus",
"uid": "${datasource}"
},
"description": "Share of verifies by the number of drafts they carried, under the adaptive window. Only under --draft-window adaptive; no data otherwise.",
"gridPos": {
"h": 8,
"w": 12,
"x": 12,
"y": 43
},
"targets": [
{
"datasource": {
"type": "prometheus",
"uid": "${datasource}"
},
"expr": "sum by (depth) (rate(radiance:draft_verify_depth_total{instance=~\"$instance\", model_name=~\"$model_name\"}[$__rate_interval]))",
"legendFormat": "depth {{depth}}",
"refId": "A",
"range": true,
"instant": false
}
],
"fieldConfig": {
"defaults": {
"unit": "percentunit",
"custom": {
"lineWidth": 1,
"fillOpacity": 40,
"showPoints": "never",
"stacking": {
"mode": "percent",
"group": "A"
}
}
},
"overrides": []
},
"options": {
"legend": {
"displayMode": "list",
"placement": "bottom",
"showLegend": true
},
"tooltip": {
"mode": "multi",
"sort": "desc"
}
}
},
{
"type": "row",
"title": "Scheduler",
@@ -1753,7 +1863,7 @@
"h": 1,
"w": 24,
"x": 0,
"y": 43
"y": 51
}
},
{
@@ -1769,7 +1879,7 @@
"h": 8,
"w": 8,
"x": 0,
"y": 44
"y": 52
},
"targets": [
{
@@ -1846,7 +1956,7 @@
"h": 8,
"w": 8,
"x": 8,
"y": 44
"y": 52
},
"targets": [
{
@@ -1912,7 +2022,7 @@
"h": 8,
"w": 8,
"x": 16,
"y": 44
"y": 52
},
"targets": [
{
@@ -1977,7 +2087,7 @@
"h": 1,
"w": 24,
"x": 0,
"y": 52
"y": 60
}
},
{
@@ -1993,7 +2103,7 @@
"h": 8,
"w": 8,
"x": 0,
"y": 53
"y": 61
},
"targets": [
{
@@ -2070,7 +2180,7 @@
"h": 8,
"w": 8,
"x": 8,
"y": 53
"y": 61
},
"targets": [
{
@@ -2147,7 +2257,7 @@
"h": 8,
"w": 8,
"x": 16,
"y": 53
"y": 61
},
"targets": [
{
@@ -2221,7 +2331,7 @@
"h": 1,
"w": 24,
"x": 0,
"y": 61
"y": 69
}
},
{
@@ -2237,7 +2347,7 @@
"h": 8,
"w": 8,
"x": 0,
"y": 62
"y": 70
},
"targets": [
{
@@ -2294,7 +2404,7 @@
"h": 8,
"w": 8,
"x": 8,
"y": 62
"y": 70
},
"targets": [
{
@@ -2362,7 +2472,7 @@
"h": 8,
"w": 8,
"x": 16,
"y": 62
"y": 70
},
"targets": [
{
@@ -2447,7 +2557,7 @@
"h": 1,
"w": 24,
"x": 0,
"y": 70
"y": 78
}
},
{
@@ -2463,7 +2573,7 @@
"h": 8,
"w": 12,
"x": 0,
"y": 71
"y": 79
},
"targets": [
{
@@ -2518,7 +2628,7 @@
"h": 8,
"w": 12,
"x": 12,
"y": 71
"y": 79
},
"targets": [
{
+46 -2
View File
@@ -454,6 +454,20 @@ The cache never gets less than one `--max-model-len` sequence, and when both sid
whole. With a lending cache, `--host-pool-mib` is what moves the split: a larger pool takes experts
off the card and gives the cache more.
**An uneven world re-splits its cheaper ranks.** The split above is worked out once, for the rank
whose cache costs most, and one block table serves every rank. Where a rank's cache costs less per
token -- an attention-zero rank at `--tp 3` keeps no attention cache -- it gets, under
`expert_tiered` with both pools derived, a KV pool that pages exactly the common token count and the
difference in its weights pool, up to every one of its weights resident; the startup log names the
rank and both sizes (`kv: rank N's cache costs ...`). It holds with or without a lending cache:
under `--deterministic`, or on a device without virtual memory management, the bytes that rank
would never page go to its experts all the same. A stated `--vram-kv-mib` or `--vram-weights-mib`
is applied to every card unchanged, and a rank whose cache costs as much per token as the dearest
rank's is never re-split -- which at `--tp 2` and `--tp 4` is every rank. A rank that costs less and
keeps the common split says why on the same `kv: rank N's cache costs ...` line. Every rank still
allocates its whole `--host-pool-mib`, a re-split rank whose weights all fit on the card included,
and that rank's log says its pinned host pool holds no weights ([`TP3.md`](TP3.md) §1).
**The cache's size decides whether multi-turn works.** The KV side is not only concurrency: prefix
caching holds a finished sequence's blocks so the next turn can reuse them. When the pool cannot
hold the *live sessions*, the cache drops prefixes the next turn wanted and that turn re-prefills
@@ -735,6 +749,33 @@ from the first token. The reply is the same either way. A hit whose nearest chec
point would give back more than two windows is kept whole. `radiance:draft_refills_total` counts
the hits ended early and `radiance:draft_refill_tokens_total` the tokens they recomputed.
**One depth for every request is a compromise; `--draft-window adaptive` lets the text decide.**
Acceptance depends on the text: code and JSON keep accepting deep into the window, prose and
summaries fall off after a position or two. With the adaptive window, `--num-speculative-tokens` is
the ceiling and the engine keeps a smoothed acceptance per draft position for every sequence:
```sh
radiance --model m.rad --num-speculative-tokens 6 --draft-window adaptive
```
A serial draft head runs as many rounds as the deepest window in the step, so the depth is chosen
for the step, not for one sequence: each step's head depth is the one that maximises the tokens all
its sequences are expected to emit over what such a step costs. The cost is measured as the server
runs — the time of every decode step, by its depth and by how many sequences it carried — so there
is nothing to enter; a depth not yet measured is priced from the nearest one that was. Under that
depth each sequence stops at the first draft that would be emitted — it and every draft before it
accepted — less than one time in ten, so a prose reply beside a code reply does not pay verify rows
for drafts nobody takes. The depth moves only after eight steps and for a two-percent gain, because
every new window is a new pass shape and a new recording. A new sequence starts from what the
sequences before it finished on, each counted once.
The adaptive window is the serial draft head's policy. With a block drafter, with prompt lookup
alone, or with speculation off the window stays fixed, and the server says so at startup. Prompt
lookup proposals made when the head declines are counted in the acceptance metrics but do not move
the head's window. At temperature 0 the text is that of a fixed depth wherever fixed depths agree
with each other; above 0 it is distribution-exact. `radiance:draft_depth_adaptive` and
`radiance:draft_verify_depth_total` (§6.3) show where the windows stand. The default is `fixed`.
### 4.7 Two cards
```sh
@@ -953,6 +994,7 @@ one line naming each one the command line moved.
| `--max-num-batched-tokens N` | 8192 | largest token count one step may carry |
| `--max-num-seqs N` | 256 | largest number of sequences one step may carry |
| `--max-model-len N` | 0 | context bound; 0 takes the model's training context |
| `--rope-scaling SPEC` | — | `yarn:FACTOR[:ORIG]`: static YaRN over the container's own rotary keys, no reconvert; `none` takes a checkpoint's YaRN off ([YARN.md](YARN.md)) |
**Memory**
@@ -999,7 +1041,8 @@ one line naming each one the command line moved.
| flag | default | |
|---|---|---|
| `--num-speculative-tokens N` | auto | speculative window; 0 disables |
| `--num-speculative-tokens N` | auto | speculative window; 0 disables. The ceiling under `--draft-window adaptive` |
| `--draft-window MODE` | fixed | `fixed` drafts N every step; `adaptive` follows each sequence's acceptance and the measured step cost, serial draft heads only (§4.6) |
| `--draft-model PATH` | — | **not implemented** — merge at convert time |
**Server**
@@ -1469,9 +1512,10 @@ lists the efforts the chat template takes, or is `null` when it takes any. `serv
| `decode_tokens_total`, `prefill_tokens_total` | |
| `decode_tokens_per_second`, `prefill_tokens_per_second` | |
| `draft_tokens_total`, `draft_accepted_total`, `draft_acceptance_ratio` | |
| `draft_position_reached_total`, `draft_position_acceptance_ratio` | acceptance by position, since start |
| `draft_position_reached_total`, `draft_position_accepted_total`, `draft_position_acceptance_ratio` | acceptance by position: the two counters over any window, the ratio since start |
| `draft_refills_total`, `draft_refill_tokens_total` | prefix hits ended a drafter window early, and the tokens recomputed (§4.6) |
| `decode_rows_unspeculated_total` | rows that never drafted at all |
| `draft_depth_adaptive`, `draft_verify_depth_total{depth}` | the adaptive window's mean over the running sequences, and verifies by the drafts they carried; only with `--draft-window adaptive` (§4.6) |
| `attn_cached_tokens_total`, `linear_cached_tokens_total` | prefix reuse, both halves |
| `linear_checkpoints_written_total`, `linear_prefix_cache_hit_rate` | |
| `prefix_cache_evictions_total`, `prefix_cache_ckpt_evictions_total` | |
+1 -1
View File
@@ -232,7 +232,7 @@ not.
| `ple_gate` | | device | host |
| `qk_norm_rope` | | - | host |
| `qk_norm_rope_gate` | | device | - |
| `qsa_block_key` | | device | - |
| `qsa_block_key` | | device | host |
| `qsa_score` | | device | - |
| `qsa_select` | | device | - |
| `qsa_tail_store` | | device | - |
+11 -5
View File
@@ -371,8 +371,8 @@ that folds dequantisation into its epilogue still receives them.
| `attn_paged` | `q_len`(range) `head_dim` `gqa` `block_size`/der `causal` `window` `q_dtype` `kv_dtype` `scale`:f64/opt `max_ctx`/opt `n_head`/opt `max_seqs`/opt | `q`, `kv_cache`, `block_table`, `seqused`, `k_descale`?, `v_descale`?, `cu_seqlens`? → `out` |
| `attn_dense` | `M`(range) `head_dim` `gqa` `causal` `dtype` `scale`:f64/opt `max_seqlen`/opt | `q`, `k`, `v`, `cu_seqlens` → `out` |
| `kv_store` | `M`(range) `head_dim` `n_head_kv` `block_size` `kv_dtype` `k_scale`:f64/opt `v_scale`:f64/opt | `k`, `v`, `slot_mapping`, `kv_cache`:inout |
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt | `qkv`:inout, `positions` |
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` | `positions` → `cos_sin` |
| `rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `scale`:f64 `mode` `rotary_dim`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `qkv`:inout, `positions` |
| `rope_table` | `M`(range) `rot` `theta`:f64 `scale`:f64 `dtype` `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `positions` → `cos_sin` |
| `qk_norm_rope` | `M`(range) `head_dim` `n_head` `n_head_kv` `theta`:f64 `eps`:f64 `scale`:f64/opt `mode`/opt `rotary_dim`/opt `wadd`:f64/opt | `qkv`:inout, `positions`, `q_w`w, `k_w`w |
`attn_paged` is the ranged op whose band is `q_len`, not `M`: one query row at decode, up to 64 at
@@ -1161,11 +1161,11 @@ stages of its sorting network when the runs are a power of two long and fill the
over two runs of 1024 where a full sort is 66 -- and the whole network otherwise. A producer that
hands it unsorted runs gets a wrong order, not a slow one.
## Sparse attention (QSA) — device-only
## Sparse attention (QSA)
| op | params | operands |
|---|---|---|
| `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt | `k`, `w`w, `page`?, `pos`? → `out` |
| `qsa_block_key` | `M`(range) `n` `ratio` `rotary_dim` `pos0`/opt `block_size`/opt `eps`:f64 `theta`:f64 `scale`:f64/opt `wadd`:f64/opt `dtype` `mode`/opt `sections`/opt `yarn_factor`:f64/opt `yarn_low`:f64/opt `yarn_high`:f64/opt `yarn_magnitude`:f64/opt | `k`, `w`w, `page`?, `pos`? → `out` |
| `qsa_score` | `M`(range) `n` `heads` `blocks` `seqs` `dtype` | `q`, `bk`, `bt`, `cu`, `nc` → `score` |
| `qsa_select` | `M`(range) `blocks` `topk` `ratio` `seqs` | `score`, `bt`, `nc`, `pos`, `cu` → `sel`, `nsel`, `seqused` |
| `qsa_tail_store` | `M`(range) `n` `ratio` `ring` `seqs` `dtype` | `k`, `pos`, `cu`, `state`:inout, `sidx` |
@@ -1173,7 +1173,8 @@ hands it unsorted runs gets a wrong order, not a slow one.
Five ops decompose one thing: an indexer that scores blocks of key history against the query and
hands `attn_paged` a shorter block table. `docs/QSA.md` is that decomposition; these are the
schemas, and `arch/common/rad_qsa.h` issues all five.
schemas, and `arch/common/rad_qsa.h` issues all five. **`qsa_block_key` has a host kernel in libref
and libavx** -- the oracle for libr4d's, YaRN included -- and the other four are **device-only**.
`qsa_block_key` builds the **compressed key**: one vector per `ratio` tokens of key history, which
is what the indexer's block scores are taken against.
@@ -1182,6 +1183,11 @@ is what the indexer's block scores are taken against.
out[b] = rope( rmsnorm( mean over j<ratio of k[b*ratio + j] ), at position pos0 + b*ratio )
```
The rotation is `rope`'s NeoX ladder over the first `rotary_dim` lanes, with `rope`'s YaRN
coefficients (`yarn_factor`, `yarn_low`, `yarn_high`, `yarn_magnitude`) when given -- the
attention's own rotary, so a compressed key and the keys it summarises are rotated alike. With
YaRN, `scale` must be 1.
**`M` is BLOCKS and `k` is `ratio` times taller.** Every other op in this document has one output
row per input row. A caller that sized `k` at the block count would have every block pool three
rows of the next one — plausible numbers and a different model — so libr4d's entry point checks it.
+30
View File
@@ -38,6 +38,36 @@ it, and the tiers skip it when they move an entry. Every rank carves the same bl
is planned, asked what it could page (`KVManager::paged_tokens`; a rank whose only paged groups are
zero limits nobody) and capped at the least before any carves.
**The attention-zero rank's pools are its own.** The budget resolver derives one split for every
card, the dearest rank's -- and an attention-zero rank's cache costs a fraction of its peers' per
token (at TP3 on Flash-Next it keeps only the QSA block keys: 2.3 GiB at the worst case where an
attention rank's costs 15.2). Under `expert_tiered` with both pools derived, `Engine::plan` gives
such a rank a KV pool that pages exactly the common token count (`KVManager::pool_mib_for_tokens`,
the inverse of `paged_tokens`: the least whole MiB whose paged split reaches the count, exact
because the split is monotone in the budget and its alignment is among the fixed costs) and moves the
difference into its weights pool, no further than every one of its weights resident. Both readers
of the resolved sizes take the rank's own split -- `Pools::configure` and the planner -- so the
grown pool is planned into, and startup refuses a rank whose plan and weights pool disagree, or
whose re-sized KV pool pages fewer tokens than it was sized for. The token count, the carve, the
loan and the attention ranks' pools are unchanged; a stated `--vram-kv-mib` / `--vram-weights-mib`
keeps meaning "this many on every card", and `auto` keeps the common split (a fully resident rank
would choose all_vram while its peers spill). `--deterministic` and a device without virtual memory
management re-split like any other: the cache does not lend there, and the bytes the rank never
pages are as much its experts' as they are under a lending cache. The condition is the cost, not
the world: a rank is re-split only where its cache costs less per token than the dearest rank's,
which at TP2/TP4 no rank does. A rank that qualifies and keeps the common split names the reason on
its `kv: rank N's cache costs ...` line. The pinned host pool is not re-split: every rank allocates
its whole `--host-pool-mib`, and a re-split rank whose weights all fit on the card says so
(`its pinned host pool holds no weights`). The log line, and the mover on the third rank:
```
kv: rank 2's cache costs 2.27 GiB at the worst case where its dearest peer's costs 15.16 GiB, so its KV pool pages the common 1446302 tokens in 1811 MiB instead of 10881; its weights pool grows 19747 -> 21692 MiB (every weight resident wants 21.18 GiB), and 7125 MiB stay unclaimed
I[2] mover: 25142 slab slots (64 shadow), 0 pinned pool slots
```
The settle check's INFO line on that card names the unclaimed MiB and points at this line rather
than at the budget's `unusable` line alone.
Under a smaller attention world the plain even shard over `world` is the wrong cut for every
attention projection, so the attention ranks declare **spans** (`rad_weight_shard_span`, the same
call the KV replication uses for k/v): q|gate rows and output columns `[attn_rank * n_head,
+127
View File
@@ -0,0 +1,127 @@
# Static YaRN
Increasing `--max-model-len` reserves a larger serving window; it does not change
the model's rotary embeddings. A checkpoint trained at 262144 positions can
explicitly request static YaRN for a 524288-token deployment. Whether that extension
preserves useful accuracy must be measured on the model and workload.
One reader takes every architecture's rotary scaling (`yarn_from`,
`arch/common/rad_arch.h`). For the target it reads `text_config.rope_parameters`,
then `rope_parameters`, then the legacy `text_config.rope_scaling` and `rope_scaling`,
in that order; the first object with `rope_type` (or legacy `type`) is authoritative.
A drafter (DFlash2, DSpark) reads its own `draft.rope_parameters` /
`draft.rope_scaling`; it does not inherit the target's scaling. The vision tower keeps
its original axial rotations. A GGUF's `rope.scaling.*` keys are carried in as the
same `rope_scaling` keys when it is read.
**The factor convention is the config's**, as vLLM and transformers read it:
`factor` 2 over `original_max_position_embeddings` 262144 reaches 524288 positions.
Validated so far: the Qwen3.8 27B and 35B-A3B containers and both Flash-Next
variants at factor 2, with retrieval at ~500K tokens, and TP3 perplexity with
`--rope-scaling` within roughly ±1% of stock at factor 2. The LLaMA plugins read the
same keys and declare the same ops; YaRN there has had no model run.
## Metadata
| Key within the rotary object | Meaning |
| --- | --- |
| `rope_type` | `yarn`; `default`, absent or legacy `mrope` is no scaling; `linear` divides positions by `factor` |
| `factor` | finite number >= 1, required for YaRN |
| `original_max_position_embeddings` | positive integer, required; the **training** length, not the enlarged deployment/table length |
| `beta_fast`, `beta_slow` | defaults 32 and 1; finite, fast >= slow > 0 |
| `attention_factor` | positive finite cos/sin multiplier; default 1 + 0.1 ln(factor) for factor > 1, otherwise 1 |
| `truncate` | true/1 (default): floor/ceil correction bounds; false/0: retain fractional bounds |
Every other type -- `llama3`, `longrope`, `dynamic` -- is refused by name at load,
as are the `mscale` and `mscale_all_dim` variants (specify `attention_factor`). A
GGUF that sets llama.cpp's YaRN `attn_factor`, `ext_factor` or log multiplier to
anything but its neutral value is refused when read. Rotary width (including
partial rotary), theta and M-RoPE section selection are unchanged.
## Convert a separate container
Use the original target and drafter checkpoints, the same quantization recipe,
and a **new output path**. `--reuse` is valid only for the same source weights and
recipe; it is not a way to mix weights from different model revisions.
```sh
rad-convert /checkpoints/Qwen3.8-27B-FP8 \
--draft-model /checkpoints/Qwen3.8-27B-DFlash2 \
--recipe data/recipes/q38-27b-fp8-df2.recipe \
--reuse /models/qwen3.8-27b-fp8.rad \
--set text_config.rope_parameters.rope_type=yarn \
--set text_config.rope_parameters.factor=2 \
--set text_config.rope_parameters.original_max_position_embeddings=262144 \
--set draft.rope_parameters.rope_type=yarn \
--set draft.rope_parameters.factor=2 \
--set draft.rope_parameters.original_max_position_embeddings=262144 \
--max-ctx 524288 --kv-cache-dtype bf16 \
-o /models/qwen3.8-27b-fp8-yarn2.rad
```
Run with `--plan-only` first. `--max-ctx` is the converter's graph bound, not a
replacement for the explicit YaRN metadata or the server's `--max-model-len`.
The bundled `.rad` by itself is not a converter input; keep the source checkpoints.
Check both target and draft settings with `rad-info --meta` after conversion.
Serve on enough memory for the requested window:
```sh
radiance --model /models/qwen3.8-27b-fp8-yarn2.rad \
--tp 4 --max-model-len 524288 --max-num-seqs 32 --kv-cache-dtype bf16
```
That cache flag controls **both** target and drafter KV. Startup capacity and
successful actual long requests must be checked; the command is not a promise
of concurrency or accuracy. Keep the unmodified model and serving setup until
long-context quality and speed meet the deployment's requirements.
## Serve an existing container: `--rope-scaling`
The same metadata can be written when the container is loaded instead of converted in:
```sh
radiance --model /models/qwen3.8-next-flash-fp8.rad \
--rope-scaling yarn:2 --max-model-len 409600
```
`yarn:FACTOR[:ORIG]` sets `rope_type = yarn`, `factor` and `original_max_position_embeddings`
(`ORIG`, default the container's own trained length) in the rotary object the reader above
takes first -- for a Qwen3.8 container that is `text_config.rope_parameters`, which already says
`default`; YaRN written under plain `rope_parameters` would sit behind it and never be read. A
drafter gets the same factor over its own trained length. Over a checkpoint's own YaRN
the factor is replaced, its trained length kept unless `ORIG` is given, and an explicit
`attention_factor` (or `mscale` variant) dropped so the magnitude is derived for the new factor.
`none` takes a checkpoint's YaRN off. A linear or other explicit rotary type is refused rather
than stacked over. The result is resolved and checked exactly as a converted container's is
(`core/format/rope_override.h`, held to `yarn_from` in `tests/yarn_test.cpp`).
Startup says what the rotary is (`rope: YaRN factor 2 over 262144 trained positions -- the rotary
reaches 524288`) and warns when `--max-model-len` is past what it covers -- also with no scaling
at all, past the trained length. A persisted prefix cache (`--prefix-cache-dir`) is fingerprinted
with the resolved rotary of the target and the drafter, so a store written under a different
one -- another `--rope-scaling`, or a container converted with YaRN -- is not reused: every cached
key was rotated differently.
The flag is for trying a factor, or serving a container whose source checkpoints are not at hand;
a deployment that settles on one can convert it in as above and drop the flag.
## Kernel and test contract
`rope`, `rope_table` and `qsa_block_key` take optional resolved coefficients
`yarn_factor`, `yarn_low`, `yarn_high`, `yarn_magnitude` (docs/OPS.md). Absent factor
is the original path, with the original op identities. With YaRN, `scale` must be 1:
inverse frequencies are blended rather than all positions being divided. Axial
rotary with YaRN is refused. Rebuild the bundled plugins together because their
shared op schemas must match.
The math follows the static YaRN formulation (Peng et al.) as vLLM's
`YaRNScalingRotaryEmbedding` implements it. `tests/yarn_test.cpp` pins the
correction bounds to vLLM's integers (14/22, 28/43, 56/85 for rotary widths 64, 128,
256 at factor 2, theta 1e7, 262144 trained positions); `tests/ref_test.cpp` and
`r4d_selftest` compare libref and libr4d against a double-precision evaluation of the
same formula at positions through 524287, within 8 ulp of each angle -- tight where
the ramp sits, loose only in the fastest pairs at long positions, which no f32 rotary
places better than its angle's own ulp. libavx is held to libref by `avx_check`, and
fused versus unfused HIP rotation is checked byte-for-byte separately.
+118 -1
View File
@@ -54,6 +54,7 @@
*/
#include "avx_vec.h"
#include "avx_common.h"
#include "rad_yarn.h"
using namespace avx;
@@ -836,6 +837,12 @@ AVX_KERNEL(rope) {
}
}
const int pair_mode = mode == ROPE_GPTJ ? ROPE_GPTJ : ROPE_NEOX;
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn)) return RAD_E_INVAL;
if (yarn.factor != 0.0f) {
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
}
const int64_t pcs = multi ? pos->stride[0] : 0, pms = multi ? pos->stride[1] : 0;
AVX_PARALLEL_FOR_IF(M * (n_head + n_head_kv) * rot >= AVX_PAR_MIN)
@@ -851,6 +858,8 @@ AVX_KERNEL(rope) {
} else {
angles(cs, invf, half, (float)ldi(pos, offlin(pos, m)) / div);
}
if (yarn.factor != 0.0f)
for (int64_t i = 0; i < rot; ++i) cs[i] *= yarn.magnitude;
/* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
* this op takes the fused qkv rather than two tensors. */
for (int64_t h = 0; h < n_head + n_head_kv; ++h)
@@ -953,7 +962,11 @@ AVX_KERNEL(rope_table) {
if (M <= 0 || numel(cs) % rot) return RAD_E_SHAPE;
const int64_t rows = numel(cs) / rot;
const int64_t half = rot / 2;
const float* invf = inv_freqs(half, rot, theta);
float* invf = inv_freqs(half, rot, theta);
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL;
if (yarn.factor != 0.0f)
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
AVX_PARALLEL_FOR_IF(M * rot >= AVX_PAR_MIN)
for (int64_t m = 0; m < M; ++m) {
@@ -962,6 +975,8 @@ AVX_KERNEL(rope_table) {
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
float* buf = scratch_f32((size_t)rot);
angles(buf, invf, half, p);
if (yarn.factor != 0.0f)
for (int64_t i = 0; i < rot; ++i) buf[i] *= yarn.magnitude;
/* `cs` may be strided, and offlin has to be evaluated per element there -- which is what
* libref does unconditionally. The dense case is one row store. */
if (rad_tensor_is_contiguous(cs)) {
@@ -972,3 +987,105 @@ AVX_KERNEL(rope_table) {
}
return RAD_OK;
}
/* ------------------------------------------------------------------ qsa_block_key */
/* QSA's compressed key (docs/OPS.md): a block's `ratio` rows of k averaged in f32 and rounded to
* k's dtype, RMS-normed with gain (wadd + w), then NeoX-rotated over `rotary_dim` at the block's
* position, YaRN included. libref's arithmetic in libref's order; what differs is that the angles
* of a block come from one `angles` table, and the inverse frequencies are built once a launch. */
AVX_KERNEL(qsa_block_key) {
const RadTensor* k = rad_arg_in(a, 0);
const RadTensor* w = rad_arg_in(a, 1);
const RadTensor* page = rad_arg_in(a, 2);
const RadTensor* pos = rad_arg_in(a, 3);
const RadTensor* out = rad_arg_in(a, 4);
if (!k || !w || !out) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
const int64_t rot = p_int(a, "rotary_dim", 0), pos0 = p_int(a, "pos0", -1);
if (n <= 0 || ratio <= 0 || (pos0 < 0 && !pos)) return RAD_E_INVAL;
if (rot < 0 || rot > n || (rot & 1) || rot / 2 > 512) return RAD_E_SHAPE;
if (p_int(a, "block_size", ratio) != ratio) return RAD_E_SHAPE;
if (k->rank != 2 || out->rank < 2 || out->shape[0] < 1) return RAD_E_SHAPE;
const int64_t M = page ? numel(page) : out->shape[0];
if (M < 1 || numel(out) / out->shape[0] != n) return RAD_E_SHAPE;
if (k->shape[0] != M * ratio || k->shape[1] != n || numel(w) < n) return RAD_E_SHAPE;
const bool pos2 = pos && pos->rank == 2;
if (pos && (pos2 ? pos->shape[0] < M : numel(pos) < M)) return RAD_E_SHAPE;
const float eps = p_f32(a, "eps", 1e-6f), wadd = p_f32(a, "wadd", 1.0f);
const float theta = p_f32(a, "theta", 10000.0f), rscale = p_f32(a, "scale", 1.0f);
static const char* kModes[] = { "neox", "mrope", "imrope" };
const int mi = p_enum(a, "mode", kModes, 3, 0);
if (mi < 0) return RAD_E_UNSUPPORTED;
int64_t sec[3] = {};
int n_sec = 0;
for (const char* v = p_str(a, "sections", nullptr); v && *v;) {
char* e = nullptr;
const long long x = std::strtoll(v, &e, 10);
if (e == v) break;
if (x <= 0 || n_sec >= 3) return RAD_E_SHAPE;
sec[n_sec++] = x;
v = e;
}
/* Several components only with a mode, its sections and three columns of `pos`. */
const bool mc = mi != 0 && n_sec > 0 && pos2 && pos->shape[1] >= 3;
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f)))
return RAD_E_INVAL;
const int64_t half = rot / 2;
float* invf = inv_freqs(half, rot, theta);
int comp[512] = {};
if (mc) {
int64_t total = 0;
for (int c = 0; c < n_sec; ++c) total += sec[c];
if (mi == 1 && total != half) return RAD_E_SHAPE;
for (int64_t i = 0; i < half; ++i) {
int c = 0;
if (mi == 1) {
int64_t start = 0;
while (c + 1 < n_sec && i >= start + sec[c]) { start += sec[c]; ++c; }
} else if (n_sec >= 3) {
if (i % 3 == 1 && i < 3 * sec[1]) c = 1;
else if (i % 3 == 2 && i < 3 * sec[2]) c = 2;
}
comp[i] = c;
}
}
for (int64_t i = 0; i < half; ++i) invf[i] = yarn.frequency(invf[i], (int)i);
float* gain = (float*)scratch_f32_c((size_t)n);
for (int64_t t = 0; t < n; ++t) gain[t] = wadd + ldt(w, offlin(w, t));
AVX_PARALLEL_FOR_IF(M * ratio * n >= AVX_PAR_MIN)
for (int64_t b = 0; b < M; ++b) {
const int64_t orow = page ? ldi(page, offlin(page, b)) : b;
if (orow < 0) continue;
float* y = scratch_f32((size_t)n);
float* cs = scratch_f32_b((size_t)(rot > 0 ? rot : 1));
double ss = 0.0;
for (int64_t t = 0; t < n; ++t) {
float acc = 0.0f;
for (int64_t j = 0; j < ratio; ++j) acc += ldt(k, offlin(k, (b * ratio + j) * n + t));
uint64_t tmp = 0;
st_elem(&tmp, k->dtype, 0, acc / (float)ratio);
y[t] = ld_elem(&tmp, k->dtype, 0);
ss += (double)y[t] * y[t];
}
const float s = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
for (int64_t t = 0; t < n; ++t) y[t] = y[t] * s * gain[t];
const float div = rscale != 0.0f ? rscale : 1.0f;
float pc[3] = {};
for (int c = 0; c < (mc ? 3 : 1); ++c)
pc[c] = (float)(!pos ? pos0 + b * ratio
: ldi(pos, offlin(pos, pos2 ? b * pos->shape[1] + c : b))) / div;
if (mc) angles_multi(cs, invf, comp, half, pc);
else angles(cs, invf, half, pc[0]);
for (int64_t i = 0; i < half; ++i) {
const float c = cs[i] * yarn.magnitude, sn = cs[half + i] * yarn.magnitude;
const float x0 = y[i], x1 = y[half + i];
y[i] = x0 * c - x1 * sn;
y[half + i] = x0 * sn + x1 * c;
}
for (int64_t t = 0; t < n; ++t) stt(out, offlin(out, orow * n + t), y[t]);
}
return RAD_OK;
}
+30
View File
@@ -206,6 +206,36 @@ std::vector<Case> build_cases() {
}
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 10000.0), HF("scale", 1.0),
HS("dtype", "f32") });
for (const char* dt : { "f32", "bf16" }) {
for (const char* mode : { "neox", "gptj", "imrope" })
add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 1e7), HF("scale", 1), HS("mode", mode),
HI("rotary_dim", 64), HS("sections", "11 11 10"), HS("dtype", dt),
HF("yarn_factor", 2), HF("yarn_low", 14), HF("yarn_high", 22),
HF("yarn_magnitude", 1.069314718) });
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 1e7), HF("scale", 1),
HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14),
HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) });
}
for (double magnitude : {2.0, (double)NAN}) {
add("rope", { HI("M", 12), HI("head_dim", 128), HI("n_head", 4), HI("n_head_kv", 2),
HF("theta", 1e7), HF("scale", 1), HS("mode", "neox"),
HI("rotary_dim", 64), HS("dtype", "bf16"), HF("yarn_factor", 0),
HF("yarn_magnitude", magnitude) });
add("rope_table", { HI("M", 12), HI("rot", 64), HF("theta", 1e7), HF("scale", 1),
HS("dtype", "f32"), HF("yarn_factor", 0), HF("yarn_magnitude", magnitude) });
}
/* QSA's compressed key at Flash-Next's geometry (n 128, ratio 4, a 64-wide rotary), stock and
* with YaRN, positions drawn up to the block count times the ratio. */
for (const char* dt : { "f32", "bf16" }) {
add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64),
HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 1),
HS("dtype", dt) });
add("qsa_block_key", { HI("M", 12), HI("n", 128), HI("ratio", 4), HI("rotary_dim", 64),
HF("eps", 1e-6), HF("theta", 1e7), HF("scale", 1), HF("wadd", 0),
HS("dtype", dt), HF("yarn_factor", 2), HF("yarn_low", 14),
HF("yarn_high", 22), HF("yarn_magnitude", 1.069314718) });
}
/* The multi-component forms: Qwen3-VL's interleaved M-RoPE over a partial rotary, and a vision
* tower's 2-D axial rotary over a whole 72-wide head. */
for (const char* dt : { "f32", "bf16" }) {
+1 -1
View File
@@ -100,7 +100,7 @@ int avx_isa_force(int level);
X(gemm_nt_q_gated) X(embed_lookup) X(embed_lookup_q) X(logits_gemm) \
/* ---- attention */ \
X(attn_paged) X(attn_dense) X(kv_store) X(rope) \
X(rope_table) X(qk_norm_rope) \
X(rope_table) X(qk_norm_rope) X(qsa_block_key) \
/* ---- mixture of experts */ \
X(router_topk) X(moe_scatter) X(moe_gemm) X(moe_gemm_q) \
X(moe_gather) X(row_topk) X(row_topk_merge) X(logit_rerank) \
+25 -2
View File
@@ -218,13 +218,29 @@ static const RadOperandSpec oKvStore[] = { OPD("k"), OPD("v"), OPD("slot_mapping
static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"),
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections") };
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"),
P_F64O("yarn_factor"), P_F64O("yarn_low"),
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"),
P_F64("scale"), P_STR("dtype") };
P_F64("scale"), P_STR("dtype"),
P_F64O("yarn_factor"), P_F64O("yarn_low"),
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") };
/* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio`
* spelled for the KV group the block-key store is, `page` and `pos` are optional. */
static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("ratio"),
P_INT("rotary_dim"), P_INTO("pos0"),
P_INTO("block_size"), P_F64("eps"), P_F64("theta"),
P_F64O("scale"), P_F64O("wadd"), P_STR("dtype"),
P_STRO("mode"), P_STRO("sections"),
P_F64O("yarn_factor"), P_F64O("yarn_low"),
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page"), OPD_O("pos"),
OUT("out") };
static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"),
P_F64O("scale"), P_STRO("mode"),
@@ -506,6 +522,10 @@ static const RadOpSchema kSchemas[] = {
{ "attn_dense", ARR(pAttnDense), ARR(oAttnDense), "dense varlen attention over cu_seqlens." },
{ "kv_store", ARR(pKvStore), ARR(oKvStore), "scatter k and v into the paged cache." },
{ "rope_table", ARR(pRopeTable), ARR(oRopeTable), "cos/sin at each position's own row." },
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
"QSA's compressed key: the mean of a block's `ratio` rows rounded to k's dtype, RMS-normed with "
"gain (wadd + w), rotated at the block's position with `rope`'s ladder and YaRN; libref's "
"arithmetic with the angles from one table a block." },
{ "rope", ARR(pRope), ARR(oRope), "rotary embedding in place." },
{ "qk_norm_rope", ARR(pQkNormRope), ARR(oQkNormRope), "per-head QK norm then rotary embedding." },
{ "scale_rows", ARR(pScaleRows), ARR(oScaleRows),
@@ -693,6 +713,9 @@ ROW("avx_kv_store", "kv_store", "attn", "scatter k and v into the paged cache",
SIMPLE("avx_rope", "rope", "attn", "rotary embedding in place", DT_FLOAT, L(rope)),
SIMPLE("avx_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT,
L(rope_table)),
SIMPLE("avx_qsa_block_key", "qsa_block_key", "attn",
"QSA compressed key: pooled, normed and rotated at the block's position", DT_FLOAT,
L(qsa_block_key)),
SIMPLE("avx_qk_norm_rope", "qk_norm_rope", "attn", "per-head QK norm then rotary embedding",
DT_FLOAT, L(qk_norm_rope)),
+16
View File
@@ -652,6 +652,22 @@ void r4d_moe_gemm_pin_prefill(int form);
// every class's K a multiple of 256, a format that folds scale groups). The two are bit-identical,
// and r4d_selftest compares their bytes.
void r4d_moe_gemm_pin_fk(int pin);
// THE RUN-ALIGNED FORM'S COLUMN TILE, pinned for a test: 0 is the launcher's shape rule (the down
// projection's 256-column tile wherever the sorted operand, one part, a w4 weight and every class's
// width allow it), 1 never that tile, 2 that tile -- refused where the shape cannot take it or the
// launch is not the aligned form. Bit-identical, and r4d_selftest compares their bytes.
void r4d_moe_gemm_pin_down_tile(int pin);
// THE GATHER'S FORM, pinned for a test: 0 is the launcher's rule, 1 a column a thread
// (gather_kernel), 2 a wave a token and sixteen bytes a lane (gather_wide_kernel), refused on a
// shape it cannot take. Bit-identical, and r4d_selftest compares their bytes.
void r4d_moe_gather_pin_form(int form);
// THE SORTED OPERAND'S DECODE KERNEL, pinned for a test: 0 is the launcher's rule
// (moe_down_dec_kernel on the sorted operand, one part, at most 512 experts, at a column-tile count
// set by the routed rows -- kMoeDownDecG2Rows), -1 the (tile, run) form, n > 0 moe_down_dec_kernel
// at n column tiles a block, capped at 16 and refused on a shape the kernel does not serve. Inside
// the decode form only, which r4d_moe_gemm_pin_prefill(2) pins. Bit-identical, and r4d_selftest
// compares their bytes.
void r4d_moe_gemm_pin_down_dec(int pin);
// THE GATED RESIDUAL READ'S PREFILL TILE, pinned for a test: 0 is the launcher's rule, 1 the decode
// tiles' kernels at 128 rows (hc_down_tiled, then hc_up_tiled into `ubuf` and hc_mix), 2 the wide
// kernels (which then refuse a shape they are not built for), 3 the PF2 kernels the rule takes from
+28 -11
View File
@@ -45,6 +45,7 @@
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "rad_yarn.h"
#include "r4d_fp8_wmma.h"
#include <cstdlib>
@@ -356,7 +357,7 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
uint16_t* __restrict__ qkv, const int32_t* __restrict__ pos,
uint32_t head_dim, uint32_t n_rope_heads, uint32_t rot, int gptj,
float theta, float rscale, uint32_t row_pitch,
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane) {
int mode, int s0, int s1, int s2, int n_sec, uint32_t plane, RadYarn yarn) {
const uint32_t m = blockIdx.x;
const uint32_t half = rot / 2;
const float div = rscale != 0.0f ? rscale : 1.0f;
@@ -376,9 +377,11 @@ __global__ __launch_bounds__(kThreads) void rope_kernel(
if (mode == 4)
inv = 1.0f / powf(theta, (float)(2 * j) / (float)(2 * sec[c]));
}
inv = yarn.frequency(inv, (int)i);
const float ang = p * inv;
float c, s;
sincosf(ang, &s, &c);
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
const uint32_t i0 = gptj ? 2 * i : i;
const uint32_t i1 = gptj ? 2 * i + 1 : i + half;
const float x0 = bf2f(hd[i0]), x1 = bf2f(hd[i1]);
@@ -771,11 +774,12 @@ extern "C" int r4d_rope_bf16(long qkv, long pos, int M, int head_dim, int n_rope
row_pitch, 0, nullptr, 0, 0, stream);
}
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
int rot, int gptj, float theta, float rscale, int row_pitch,
int mode, const int* sec, int n_sec, int plane, long stream) {
// THE ONE LAUNCH OF rope_kernel. `yarn` with factor 0 is the plain rotary: the kernel's YaRN
// blend returns the frequency it was given and the magnitude is not applied, so the C entry points
// below and the op without YaRN run the same arithmetic with the same arguments.
static int rope_launch(long qkv, long pos, int M, int head_dim, int n_rope_heads, int rot,
int gptj, float theta, float rscale, int row_pitch, int mode,
const int* sec, int n_sec, int plane, RadYarn yarn, long stream) {
if (!qkv || !pos) return -1;
if (M <= 0 || head_dim <= 0 || n_rope_heads <= 0) return -2;
if (rot <= 0 || rot > head_dim || (rot & 1)) return -3;
@@ -787,10 +791,19 @@ extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_r
hipLaunchKernelGGL(rope_kernel, dim3((uint32_t)M, gy), dim3(kThreads), 0, (hipStream_t)stream,
(uint16_t*)qkv, (const int32_t*)pos, (uint32_t)head_dim,
(uint32_t)n_rope_heads, (uint32_t)rot, gptj, theta, rscale,
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane);
(uint32_t)row_pitch, mode, s0, s1, s2, n_sec, (uint32_t)plane, yarn);
return hipGetLastError() == hipSuccess ? 0 : -4;
}
// The multi-component form: `mode` 2 mrope, 3 imrope, 4 axial, `sec[0..n_sec)` the sections and
// `plane` the component pitch of `pos`; plane 0 is the one-component rotary above.
extern "C" int r4d_rope_mc_bf16(long qkv, long pos, int M, int head_dim, int n_rope_heads,
int rot, int gptj, float theta, float rscale, int row_pitch,
int mode, const int* sec, int n_sec, int plane, long stream) {
return rope_launch(qkv, pos, M, head_dim, n_rope_heads, rot, gptj, theta, rscale, row_pitch,
mode, sec, n_sec, plane, RadYarn{}, stream);
}
extern "C" int r4d_kv_store_bf16(long k, long v, long slot, long kv, int M, int head_dim,
int kv_heads, int block_size, int n_blocks,
int k_ld, int v_ld, long stream) {
@@ -1384,12 +1397,16 @@ extern "C" int r4d_rad_rope(const RadArgs* a, RadStream s) {
const float theta = (float)r4d_getf(a, "theta", 10000.0);
const float rscale = (float)r4d_getf(a, "scale", 1.0);
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn)) return R4D_NO(RAD_E_INVAL);
/* YaRN over the axial vision rotary, or over a linear position divide, is no model's. */
if (yarn.factor != 0.0f && (mc == 4 || rscale != 1.0f)) return R4D_NO(RAD_E_UNSUPPORTED);
/* The Q heads and the K heads rotate; the V heads that follow them do not, which is the whole
* reason this op takes the fused projection rather than two tensors. */
return r4d_rope_mc_bf16(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
mc, sec, n_sec, plane, (long)(uintptr_t)s) == 0 ? RAD_OK
: RAD_E_DEVICE;
return rope_launch(r4d_addr(qkv), r4d_addr(pos), (int)Mp, (int)head_dim,
(int)(n_head + n_head_kv), (int)rot, gptj, theta, rscale, (int)pitch,
mc, sec, n_sec, plane, yarn, (long)(uintptr_t)s) == 0 ? RAD_OK
: RAD_E_DEVICE;
}
/* ------------------------------------------------------------------ kv_store */
+827 -73
View File
File diff suppressed because it is too large. Load diff
+7 -3
View File
@@ -23,6 +23,7 @@
#include "r4d_args.h"
#include "r4d_emit.h"
#include "r4d_common.h"
#include "rad_yarn.h"
#include <hip/hip_bf16.h>
#include <cstdint>
#include <cmath>
@@ -205,7 +206,7 @@ __global__ __launch_bounds__(256) void r4d_qk_norm_rope_gate_kernel(
// those here silently changes the model's output -- a different rope is a different model.
__global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
const void* __restrict__ POS, void* __restrict__ CS, long rows, int rot, float theta,
float rscale, int cs_f32, int pos_i64) {
float rscale, int cs_f32, int pos_i64, RadYarn yarn) {
const int m = blockIdx.x;
const long pp = pos_i64 ? ((const long*)POS)[m] : (long)((const int*)POS)[m];
// A padded row addresses no table row, and a position at or past the table's height writes
@@ -216,9 +217,10 @@ __global__ __launch_bounds__(64) void r4d_qk_rope_table_kernel(
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
const size_t o = (size_t)pp * rot;
for (int i = threadIdx.x; i < half; i += (int)blockDim.x) {
const float inv = 1.0f / powf(theta, (float)(2 * i) / (float)rot);
const float inv = yarn.frequency(1.0f / powf(theta, (float)(2 * i) / (float)rot), i);
float c, s;
sincosf(p * inv, &s, &c);
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
if (cs_f32) {
((float*)CS)[o + i] = c;
((float*)CS)[o + half + i] = s;
@@ -386,8 +388,10 @@ static int rad_rope_table_body(const RadArgs* args, const R4dSink& sk) {
const float theta = (float)r4d_getf(args, "theta", 10000.0);
const float rscale = (float)r4d_getf(args, "scale", 1.0);
const RadYarn yarn = rad_yarn_args(args);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return R4D_NO(RAD_E_INVAL);
return R4D_EMIT(sk, r4d_qk_rope_table_kernel, dim3((int)M), dim3(64), 0,
r4d_p(po), r4d_wp(cs), (long)(r4d_numel(cs) / rot), (int)rot, theta, rscale,
cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0);
cs->dtype == RAD_F32 ? 1 : 0, po->dtype == RAD_I64 ? 1 : 0, yarn);
}
R4D_ENTRY(r4d_rad_rope_table, rad_rope_table_body)
+11 -5
View File
@@ -31,6 +31,7 @@
#include "r4d.h"
#include "r4d_args.h"
#include "rad_yarn.h"
#include "r4d_emit.h"
#include "r4d_common.h" // r4d_wave_sum
@@ -61,7 +62,7 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
const int32_t* __restrict__ page, const int32_t* __restrict__ bpos,
uint16_t* __restrict__ out,
int n, int ratio, int rot, float eps, float wadd, float theta, float rscale,
long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc) {
long long pos0, int k_ld, int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc, RadYarn yarn) {
__shared__ float sh[kMaxN];
__shared__ float red[kMaxN / 32];
@@ -114,9 +115,10 @@ __global__ __launch_bounds__(kMaxN) void qsa_block_key_kernel(
const long long bp = bpos ? (long long)bpos[(size_t)b * bstep + comp]
: (pos0 + (long long)b * ratio);
const float p = (float)bp / (rscale != 0.0f ? rscale : 1.0f);
const float iv = 1.0f / powf(theta, (float)(2 * ci) / (float)rot);
const float iv = yarn.frequency(1.0f / powf(theta, (float)(2 * ci) / (float)rot), ci);
float s, c;
sincosf(p * iv, &s, &c);
if (yarn.factor != 0.0f) { c *= yarn.magnitude; s *= yarn.magnitude; }
const float xp = sh[pt];
res = first ? (res * c - xp * s) : (xp * s + res * c);
}
@@ -148,7 +150,7 @@ static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, lon
int n, int ratio, int rot, float eps, float wadd,
float theta, float rscale, long long pos0, int k_ld,
int o_ld, int mode, int s0, int s1, int s2, int bstep, int mc,
const R4dSink& sk) {
const R4dSink& sk, RadYarn yarn = {}) {
int emit_rc = RAD_OK;
if (!k || !w || !out) return -1;
if (M <= 0 || n <= 0 || n > kMaxN || ratio <= 0) return -2;
@@ -162,7 +164,7 @@ static int r4d_qsa_block_key_bf16_emit(long k, long w, long page, long bpos, lon
emit_rc = R4D_EMIT(sk, qsa_block_key_kernel, dim3((unsigned)M), dim3((unsigned)thr), 0, (const uint16_t*)k, (const float*)w,
(const int32_t*)page, (const int32_t*)bpos, (uint16_t*)out,
n, ratio, rot, eps, wadd, theta, rscale, pos0, k_ld, o_ld, mode, s0, s1,
s2, bstep, mc);
s2, bstep, mc, yarn);
return emit_rc == RAD_OK && (sk.desc || hipGetLastError() == hipSuccess) ? 0 : -4;
}
@@ -244,12 +246,16 @@ static int r4d_rad_qsa_block_key_body(const RadArgs* a, const R4dSink& sk) {
if (r4d_numel(w) < n) return R4D_NO(RAD_E_SHAPE);
const long long kp = r4d_row_pitch(k), op = r4d_row_pitch(o);
if (kp < 0 || op < 0) return R4D_NO(RAD_E_STRIDE);
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) ||
(yarn.factor != 0.0f && (rot <= 0 || r4d_getf(a, "scale", 1.0) != 1.0)))
return R4D_NO(RAD_E_INVAL);
const int e = r4d_qsa_block_key_bf16_emit(
r4d_addr(k), r4d_addr(w), r4d_addr(pg), r4d_addr(bp), r4d_addr(o),
(int)M, (int)n, (int)ratio, (int)rot,
(float)r4d_getf(a, "eps", 1e-6), (float)r4d_getf(a, "wadd", 1.0),
(float)r4d_getf(a, "theta", 10000.0), (float)r4d_getf(a, "scale", 1.0),
pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, sk);
pos0, (int)kp, (int)op, mode, sec[0], sec[1], sec[2], bstep, mc, sk, yarn);
return e == 0 ? RAD_OK : RAD_E_SHAPE;
}
+12
View File
@@ -276,6 +276,10 @@ static const RadParamSpec pRopeTable[] = {
P_F64("theta"),
P_F64("scale"),
{ "dtype", RAD_P_STR, RAD_REQUIRED },
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
};
static const RadOperandSpec oRopeTable[] = {
{ "positions", RAD_OPD_IN, 0 },
@@ -1096,6 +1100,10 @@ static const RadParamSpec pQsaBlockKey[] = {
* its `sections`, read against a [3, M] component-major `pos` list. Absent is NeoX. */
{ "mode", RAD_P_STR, RAD_OPTIONAL },
{ "sections", RAD_P_STR, RAD_OPTIONAL },
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
};
static const RadOperandSpec oQsaBlockKey[] = {
{ "k", RAD_OPD_IN, 0 },
@@ -1574,6 +1582,10 @@ static const RadParamSpec pRope[] = {
{ "mode", RAD_P_STR, RAD_REQUIRED },
{ "rotary_dim", RAD_P_INT, RAD_OPTIONAL },
{ "sections", RAD_P_STR, RAD_OPTIONAL },
{ "yarn_factor", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_low", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_high", RAD_P_F64, RAD_OPTIONAL },
{ "yarn_magnitude", RAD_P_F64, RAD_OPTIONAL },
};
/* ---------------------------------------------------------------------- the vision tower */
+853 -19
View File
File diff suppressed because it is too large. Load diff
+102 -6
View File
@@ -27,6 +27,7 @@
* the two-sided reading libr4d's h128 kernel documents.
*/
#include "ref_common.h"
#include "rad_yarn.h"
/* `row_stride`: which axis carries a row of `cols` elements, at whatever rank the operand arrived
* in. Every q/k/v/out below goes through it rather than through `rank >= 3 ? stride[rank-3] : cols`
* -- the comment above kv_store shows where that shortcut is wrong. */
@@ -412,11 +413,11 @@ static int rope_freqs(int mode, int64_t rot, float theta, const int64_t* sec, in
}
static void rope_head(const RadTensor* t, int64_t base, int64_t ds, int64_t rot, int mode,
const RopeFreq& f, const float* pos) {
const RopeFreq& f, const float* pos, float magnitude = 1.0f) {
const int64_t half = rot / 2;
for (int64_t i = 0; i < half; ++i) {
const float ang = pos[f.comp[i]] * f.inv[i];
const float c = std::cos(ang), s = std::sin(ang);
const float c = std::cos(ang) * magnitude, s = std::sin(ang) * magnitude;
const int64_t i0 = (mode == ROPE_GPTJ) ? 2 * i : i;
const int64_t i1 = (mode == ROPE_GPTJ) ? 2 * i + 1 : i + half;
const float x0 = ldt(t, base + i0 * ds), x1 = ldt(t, base + i1 * ds);
@@ -471,6 +472,12 @@ int ref_rope(const RadArgs* a, RadStream) {
}
RopeFreq f;
RAD_REF_TRY(rope_freqs(mode, rot, theta, sec, multi ? n_sec : 0, &f));
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn)) return RAD_E_INVAL;
if (yarn.factor != 0.0f) {
if (mode == ROPE_AXIAL || rscale != 1.0f) return RAD_E_UNSUPPORTED;
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
}
const int64_t stride_row = (n_head + 2 * n_head_kv) * head_dim;
if (M <= 0 || numel(qkv) < M * stride_row) return RAD_E_SHAPE;
@@ -493,7 +500,7 @@ int ref_rope(const RadArgs* a, RadStream) {
/* Q heads then K heads. The V heads that follow are left alone, which is the whole reason
* this op takes the fused qkv rather than two tensors. */
for (int64_t h = 0; h < n_head + n_head_kv; ++h)
rope_head(qkv, row + h * head_dim * ds, ds, rot, mode, f, p);
rope_head(qkv, row + h * head_dim * ds, ds, rot, mode, f, p, yarn.magnitude);
}
return RAD_OK;
}
@@ -577,17 +584,106 @@ int ref_rope_table(const RadArgs* a, RadStream) {
const int64_t rows = numel(cs) / rot;
const int64_t half = rot / 2;
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && rscale != 1.0f)) return RAD_E_INVAL;
#pragma omp parallel for schedule(static)
for (int64_t m = 0; m < M; ++m) {
const int64_t pp = ld_int(pos->dtype, pos->data, offlin(pos, m));
if (pp < 0 || pp >= rows) continue;
const float p = (float)pp / (rscale != 0.0f ? rscale : 1.0f);
for (int64_t i = 0; i < half; ++i) {
const float inv = 1.0f / std::pow(theta, (float)(2 * i) / (float)rot);
const float inv = yarn.frequency(1.0f / std::pow(theta, (float)(2 * i) / (float)rot), (int)i);
const float ang = p * inv;
stt(cs, offlin(cs, pp * rot + i), std::cos(ang));
stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang));
stt(cs, offlin(cs, pp * rot + i), std::cos(ang) * yarn.magnitude);
stt(cs, offlin(cs, pp * rot + half + i), std::sin(ang) * yarn.magnitude);
}
}
return RAD_OK;
}
/* ------------------------------------------------------------------ qsa_block_key */
/* The QSA indexer's compressed key (docs/OPS.md, docs/QSA.md): for each of M blocks,
*
* pooled = mean of the block's `ratio` rows of k, accumulated in f32 and ROUNDED TO k's dtype
* normed = pooled * rsqrt(mean(pooled^2) + eps) * (wadd + w)
* out = NeoX rotary of normed's first `rotary_dim` lanes at the block's position, the rest
* passed through, rounded once at the store
*
* The rounding after the mean is the reference model's (`.float().mean(dim=1).to(dtype)`) and is
* part of the answer. The block's position is `pos[b]` (a [>= M, 1 or 3] list carries a block's
* components side by side, read under `mode` mrope/imrope and `sections`), or `pos0 + b*ratio`
* without one. `page[b]`, when given, is the output row, and a negative entry writes nothing. The
* rotary is `rope`'s ladder with YaRN's blend and magnitude when the coefficients are given. */
int ref_qsa_block_key(const RadArgs* a, RadStream) {
const RadTensor* k = t_in(a, 0);
const RadTensor* w = t_in(a, 1);
const RadTensor* page = t_in(a, 2);
const RadTensor* pos = t_in(a, 3);
const RadTensor* out = t_in(a, 4);
if (!k || !w || !out) return RAD_E_INVAL;
const int64_t n = p_int(a, "n", 0), ratio = p_int(a, "ratio", 0);
const int64_t rot = p_int(a, "rotary_dim", 0), pos0 = p_int(a, "pos0", -1);
if (n <= 0 || n > REF_HD_MAX || ratio <= 0 || (pos0 < 0 && !pos)) return RAD_E_INVAL;
if (rot < 0 || rot > n || (rot & 1)) return RAD_E_SHAPE;
if (p_int(a, "block_size", ratio) != ratio) return RAD_E_SHAPE;
if (k->rank != 2 || out->rank < 2 || out->shape[0] < 1) return RAD_E_SHAPE;
const int64_t M = page ? numel(page) : out->shape[0];
if (M < 1 || numel(out) / out->shape[0] != n) return RAD_E_SHAPE;
if (k->shape[0] != M * ratio || k->shape[1] != n || numel(w) < n) return RAD_E_SHAPE;
const bool pos2 = pos && pos->rank == 2;
if (pos && (pos2 ? pos->shape[0] < M : numel(pos) < M)) return RAD_E_SHAPE;
const float eps = p_f32(a, "eps", 1e-6f), wadd = p_f32(a, "wadd", 1.0f);
const float theta = p_f32(a, "theta", 10000.0f), rscale = p_f32(a, "scale", 1.0f);
static const char* kModes[] = { "neox", "mrope", "imrope" };
const int mi = p_enum(a, "mode", kModes, 3, 0);
if (mi < 0) return RAD_E_UNSUPPORTED;
const int mode = mi == 1 ? ROPE_MROPE : mi == 2 ? ROPE_IMROPE : ROPE_NEOX;
int64_t sec[8] = {};
const int n_sec = rope_sections(a, sec);
if (n_sec < 0 || n_sec > 3) return RAD_E_SHAPE;
/* Several components only with a mode, its sections and three columns of `pos`; otherwise
* every frequency reads the block's one position, which every mode reads as NeoX. */
const bool mc = mode != ROPE_NEOX && n_sec > 0 && pos2 && pos->shape[1] >= 3;
const RadYarn yarn = rad_yarn_args(a);
if (!rad_yarn_valid(yarn) || (yarn.factor != 0.0f && (rot <= 0 || rscale != 1.0f)))
return RAD_E_INVAL;
RopeFreq f;
RAD_REF_TRY(rope_freqs(mc ? mode : ROPE_NEOX, rot, theta, sec, mc ? n_sec : 0, &f));
for (int64_t i = 0; i < rot / 2; ++i) f.inv[i] = yarn.frequency(f.inv[i], (int)i);
#pragma omp parallel for schedule(static)
for (int64_t b = 0; b < M; ++b) {
const int64_t orow = page ? ld_int(page->dtype, page->data, offlin(page, b)) : b;
if (orow < 0) continue;
float x[REF_HD_MAX], y[REF_HD_MAX];
double ss = 0.0;
for (int64_t t = 0; t < n; ++t) {
float acc = 0.0f;
for (int64_t j = 0; j < ratio; ++j) acc += ldt(k, offlin(k, (b * ratio + j) * n + t));
uint64_t tmp = 0;
st_dt(k->dtype, &tmp, 0, acc / (float)ratio);
x[t] = ld_dt(k->dtype, &tmp, 0);
ss += (double)x[t] * x[t];
}
const float inv = 1.0f / std::sqrt((float)(ss / (double)n) + eps);
for (int64_t t = 0; t < n; ++t) y[t] = x[t] * inv * (wadd + ldt(w, offlin(w, t)));
float p[3] = {};
for (int c = 0; c < (mc ? 3 : 1); ++c) {
const int64_t bp = !pos ? pos0 + b * ratio
: ld_int(pos->dtype, pos->data,
offlin(pos, pos2 ? b * pos->shape[1] + c : b));
p[c] = (float)bp / (rscale != 0.0f ? rscale : 1.0f);
}
const int64_t half = rot / 2;
for (int64_t i = 0; i < half; ++i) {
const float ang = p[f.comp[i]] * f.inv[i];
const float c = std::cos(ang) * yarn.magnitude, s = std::sin(ang) * yarn.magnitude;
const float x0 = y[i], x1 = y[half + i];
y[i] = x0 * c - x1 * s;
y[half + i] = x0 * s + x1 * c;
}
for (int64_t t = 0; t < n; ++t) stt(out, offlin(out, orow * n + t), y[t]);
}
return RAD_OK;
}
+2
View File
@@ -115,6 +115,7 @@ int ref_kv_store (const RadArgs*, RadStream);
int ref_rope (const RadArgs*, RadStream);
int ref_rope_table (const RadArgs*, RadStream);
int ref_qk_norm_rope (const RadArgs*, RadStream);
int ref_qsa_block_key (const RadArgs*, RadStream);
/* ---- mixture of experts */
int ref_router_topk (const RadArgs*, RadStream);
@@ -229,6 +230,7 @@ REF_SHAPE_FN(ref_kv_store);
REF_SHAPE_FN(ref_rope);
REF_SHAPE_FN(ref_rope_table);
REF_SHAPE_FN(ref_qk_norm_rope);
REF_SHAPE_FN(ref_qsa_block_key);
REF_SHAPE_FN(ref_router_topk);
REF_SHAPE_FN(ref_moe_scatter);
+27 -2
View File
@@ -278,16 +278,32 @@ static const RadOperandSpec oKvStore[] = { OPD("k"), OPD("v"), OPD("slot_mapping
static const RadParamSpec pRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("n_head_kv"), P_F64("theta"), P_F64("scale"),
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections") };
P_STR("mode"), P_INTO("rotary_dim"), P_STRO("sections"),
P_F64O("yarn_factor"), P_F64O("yarn_low"),
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
static const RadOperandSpec oRope[] = { INOUT("qkv"), OPD("positions") };
/* The cos/sin plane a fused prologue reads instead of theta: written at each position's OWN row
* of a [max_ctx, rot] table. `rot`, `theta` and `scale` are `rope`'s, spelled the same way,
* because the two have to compute the same angles. */
static const RadParamSpec pRopeTable[] = { P_INT("M"), P_INT("rot"), P_F64("theta"),
P_F64("scale"), P_STR("dtype") };
P_F64("scale"), P_STR("dtype"),
P_F64O("yarn_factor"), P_F64O("yarn_low"),
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
static const RadOperandSpec oRopeTable[] = { OPD("positions"), OUT("cos_sin") };
/* QSA's compressed key, libr4d's schema exactly (libr4d/r4d_rows.cpp): `block_size` is `ratio`
* spelled for the KV group the block-key store is, `page` and `pos` are optional. */
static const RadParamSpec pQsaBlockKey[] = { P_INT("M"), P_INT("n"), P_INT("ratio"),
P_INT("rotary_dim"), P_INTO("pos0"),
P_INTO("block_size"), P_F64("eps"), P_F64("theta"),
P_F64O("scale"), P_F64O("wadd"), P_STR("dtype"),
P_STRO("mode"), P_STRO("sections"),
P_F64O("yarn_factor"), P_F64O("yarn_low"),
P_F64O("yarn_high"), P_F64O("yarn_magnitude") };
static const RadOperandSpec oQsaBlockKey[] = { OPD("k"), WGT("w"), OPD_O("page"), OPD_O("pos"),
OUT("out") };
static const RadParamSpec pQkNormRope[] = { P_INT("M"), P_INT("head_dim"), P_INT("n_head"),
P_INT("n_head_kv"), P_F64("theta"), P_F64("eps"),
P_F64O("scale"), P_STRO("mode"), P_INTO("rotary_dim"),
@@ -747,6 +763,12 @@ static const RadOpSchema kSchemas[] = {
"cos/sin for the positions a step names, at each position's own row of a [max_ctx, rot] plane: "
"rot values a row, cos for the first half and sin for the second. The angles are `rope`'s "
"exactly. A row no position names is not written; a negative position writes nothing." },
{ "qsa_block_key", ARR(pQsaBlockKey), ARR(oQsaBlockKey),
"QSA's compressed key, one vector per `ratio` rows of k: the block's mean accumulated in f32 and "
"rounded to k's dtype, RMS-normed with gain (wadd + w), then NeoX-rotated over `rotary_dim` at "
"the block's position -- `pos[b]` (with `mode` mrope/imrope and `sections`, a [>= M, 3] list's "
"three components) or `pos0 + b*ratio` -- with YaRN's blend and magnitude when given. `page[b]`, "
"when given, is the output row; a negative entry writes nothing." },
{ "rope", ARR(pRope), ARR(oRope),
"Rotary embedding in place over the q and k heads of a fused [q|k|v] row; the v heads are left "
"alone. `mode` is \"neox\" or \"gptj\", or a multi-component form: \"mrope\" (contiguous "
@@ -1080,6 +1102,9 @@ SIMPLE("ref_moe_gemm_q_mod4", "moe_gemm_q_mod4", "moe",
SIMPLE("ref_moe_gather", "moe_gather", "moe", "weighted scatter back to token order", DT_FLOAT,
ref_moe_gather),
SIMPLE("ref_rope_table", "rope_table", "attn", "cos/sin at each position's own row", DT_FLOAT, ref_rope_table),
SIMPLE("ref_qsa_block_key", "qsa_block_key", "attn",
"QSA compressed key: pooled, normed and rotated at the block's position", DT_FLOAT,
ref_qsa_block_key),
SIMPLE("ref_row_topk", "row_topk", "moe", "exact per-row top-R", DT_FLOAT, ref_row_topk),
SIMPLE("ref_row_topk_merge", "row_topk_merge", "moe", "the global top-R of the gathered per-rank candidate sets", DT_FLOAT, ref_row_topk_merge),
SIMPLE("ref_logit_rerank", "logit_rerank", "moe", "R candidates a row rescored exactly against the full-precision head", DT_FLOAT, ref_logit_rerank),
+17
View File
@@ -1040,6 +1040,23 @@ int ref_rope_table_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* ou
return o.finish("rope_table", operand, out);
}
int ref_qsa_block_key_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
const int64_t M = gi(p, n_p, "M", 0);
const int64_t n = gi(p, n_p, "n", 0);
const int64_t r = gi(p, n_p, "ratio", 0);
if (M <= 0 || n <= 0 || r <= 0) return RAD_E_UNSUPPORTED;
const uint32_t D = act_dt(p, n_p);
Opd o;
o.t(D, { M * r, n }); /* k -- `ratio` rows a block */
o.t((uint32_t)RAD_F32, { n }); /* w -- the norm gain */
/* page: absent, so the write is contiguous. A drawn page list may repeat an entry, and two
* blocks onto one row is a race whose winner the comparison would then measure. */
o.skip();
o.t_idx({ M }, M * r, -1, 0); /* pos -- each block's first-token position */
o.t(D, { M, n }); /* out */
return o.finish("qsa_block_key", operand, out);
}
/* ================================================================== mixture of experts */
int ref_scale_rows_shape(const RadParam* p, int n_p, int operand, RadOpdDesc* out) {
+111
View File
@@ -306,6 +306,8 @@ extern "C" void* rad_buf_ptr (RadCtx* c, rad_buf b) { (void)c; return (void
#include "../arch/qwen35_bf16/qwen35_bf16.cpp"
/* And the production architecture, for its sizing declare (RadBuildCtx::shape_probe). */
#include "../arch/qwen4exp_fp8/qwen4exp_fp8.cpp"
/* And the LLaMA family, for how it reads its rotary scaling. */
#include "../arch/llama_fp8/llama_fp8.cpp"
/* The PLE block on its own: no architecture in this file declares it, and what its step() hands
* the two windowed ops is a contract of its own (rad_block_ple.h). */
#include <arch/rad_block_ple.h>
@@ -550,6 +552,86 @@ TEST(declare_is_a_qwen35_trunk) {
CHECK_EQ(count_op(b, "silu_mul"), 8);
}
TEST(qwen35_bf16_yarn_reaches_every_text_rotary_op) {
RadModelMeta meta = qwen35_meta();
std::vector<const char*> keys(meta.kv_key, meta.kv_key + meta.n_kv);
std::vector<const char*> vals(meta.kv_val, meta.kv_val + meta.n_kv);
keys.insert(keys.end(), {"rope_parameters.rope_type", "rope_parameters.factor",
"rope_parameters.original_max_position_embeddings"});
vals.insert(vals.end(), {"yarn", "2", "262144"});
meta.n_kv = (int)keys.size(); meta.kv_key = keys.data(); meta.kv_val = vals.data();
RadBuildCtx ctx = build_ctx();
RadBuilder b;
CHECK_OK(qwen35_bf16::declare(&b, &meta, &ctx));
int rotary = 0;
for (const auto& op : b.ops) if (op.op == "rope") {
++rotary;
int found = 0;
for (const auto& p : op.p) {
if (p.key == "yarn_factor") { CHECK_EQ(p.dval, 2.0); ++found; }
if (p.key == "yarn_magnitude") { CHECK_NEAR(p.dval, 1.069314718, 1e-7); ++found; }
if (p.key == "scale") CHECK_EQ(p.dval, 1.0);
}
CHECK_EQ(found, 2);
}
CHECK_EQ(rotary, 4);
vals[vals.size()-2] = "nan";
RadBuilder invalid;
CHECK_EQ(qwen35_bf16::declare(&invalid, &meta, &ctx), RAD_E_INVAL);
}
/* THE LLAMA FAMILY READS ITS ROTARY SCALING THROUGH THE SAME READER. A Llama 3.1 checkpoint says
* `rope_type: llama3` with a factor of 8; read as a bare factor that is a linear position divide
* by 8 and fluent nonsense, so it is refused by name at declare. Linear stays linear and YaRN
* reaches the rope op. */
TEST(llama_reads_its_rotary_scaling_by_type) {
(void)&llama_fp8::step; /* included for its declare; nothing here runs a step */
(void)&llama_fp8::probe;
auto declare = [](const char* type, const char* factor, RadBuilder* b) {
const char* keys[] = {"rope_scaling.rope_type", "rope_scaling.factor",
"rope_scaling.original_max_position_embeddings"};
const char* vals[] = {type, factor, "8192"};
RadModelMeta m{};
m.arch_id = "llama"; m.name = "test-llama"; m.quant = "fp8_e4m3";
m.n_layers = 2; m.n_embd = 1024; m.n_head = 8; m.n_head_kv = 2; m.head_dim = 128;
m.n_ff = 2048; m.n_vocab = 32000; m.n_ctx_train = 8192;
m.rms_eps = 1e-5f; m.rope_theta = 5e5f; m.rope_scale = 1.0f;
m.n_kv = type ? 3 : 0; m.kv_key = keys; m.kv_val = vals;
RadBuildCtx c = build_ctx();
return llama_fp8::declare(b, &m, &c);
};
for (const char* refused : {"llama3", "longrope", "dynamic"}) {
RadBuilder b;
CHECK_EQ(declare(refused, "8", &b), RAD_E_UNSUPPORTED);
}
{
RadBuilder b;
CHECK_OK(declare("linear", "2", &b));
CHECK(count_op(b, "rope") > 0);
for (const auto& op : b.ops) if (op.op == "rope") {
CHECK_EQ(pflt(&op, "scale"), 2.0);
CHECK(!param(&op, "yarn_factor"));
}
}
{
RadBuilder b;
CHECK_OK(declare("yarn", "4", &b));
CHECK(count_op(b, "rope") > 0);
for (const auto& op : b.ops) if (op.op == "rope") {
CHECK_EQ(pflt(&op, "scale"), 1.0);
CHECK_EQ(pflt(&op, "yarn_factor"), 4.0);
}
}
{
RadBuilder b;
CHECK_OK(declare(nullptr, "", &b));
for (const auto& op : b.ops) if (op.op == "rope") {
CHECK_EQ(pflt(&op, "scale"), 1.0);
CHECK(!param(&op, "yarn_factor"));
}
}
}
TEST(the_alternation_puts_full_attention_at_3_and_7) {
RadBuilder b;
RadModelMeta meta = qwen35_meta();
@@ -1544,6 +1626,35 @@ RadModelMeta qwen4exp_meta() {
* convert and at load. Asked about a model whose recipe made them int4-rotated, E4M3 rows and u2,
* it declares the rotated expert kernels, the E4M3 mix and the 2-bit head; asked about one with
* nothing behind it, the fp8 experts and the bf16 mix. */
TEST(qwen4exp_yarn_reaches_attention_indexer_and_compressed_keys) {
RadModelMeta meta = qwen4exp_meta();
std::vector<const char*> keys(meta.kv_key, meta.kv_key + meta.n_kv);
std::vector<const char*> vals(meta.kv_val, meta.kv_val + meta.n_kv);
keys.insert(keys.end(), {"text_config.rope_parameters.rope_type", "text_config.rope_parameters.factor",
"text_config.rope_parameters.original_max_position_embeddings"});
vals.insert(vals.end(), {"yarn", "2", "262144"});
meta.n_kv = (int)keys.size(); meta.kv_key = keys.data(); meta.kv_val = vals.data();
RadBuildCtx c = build_ctx(0, 1);
c.max_tok = 2048; c.max_seqs = 8; c.max_spec = 3; c.max_ctx = 524288;
RadBuilder b;
REQUIRE_EQ(qwen4exp_fp8::declare(&b, &meta, &c), RAD_OK);
int direct = 0, table = 0, compressed = 0;
for (const auto& op : b.ops) {
if (op.op == "rope") ++direct;
else if (op.op == "rope_table") ++table;
else if (op.op == "qsa_block_key") ++compressed;
else continue;
int found = 0;
for (const auto& p : op.p) {
if (p.key == "yarn_factor") { CHECK_EQ(p.dval, 2.0); ++found; }
if (p.key == "yarn_magnitude") { CHECK_NEAR(p.dval, 1.069314718, 1e-7); ++found; }
if (p.key == "scale") CHECK_EQ(p.dval, 1.0);
}
CHECK_EQ(found, 2);
}
CHECK(direct > 0); CHECK(table > 0); CHECK(compressed > 0);
}
TEST(the_encodings_the_model_holds_choose_the_flash_next_kernels) {
RadModelMeta meta = qwen4exp_meta();
RadEncoding w4 = rad_enc_affine(RAD_I4, RAD_BF16, 1, 128);
+43
View File
@@ -362,6 +362,28 @@ TEST(the_table_placements_are_auto_vram_ram_or_disk) {
CHECK_EQ(parse({ "--ngram-placement" }, &c), RAD_E_INVAL);
}
/* --draft-window takes its two names and nothing else; the default is kDraftWindowDefault, and the
* help text states it from there. Whether the window CAN adapt -- a serial drafter, a depth above
* zero -- is the scheduler's to say with the program in hand, not the parser's. */
TEST(the_draft_window_is_fixed_or_adaptive) {
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK(d.draft_window == kDraftWindowDefault);
Config c;
CHECK_EQ(parse({ "--draft-window", "adaptive" }, &c), RAD_OK);
CHECK(c.draft_window == DraftWindow::Adaptive);
CHECK_EQ(parse({ "--draft-window", "fixed" }, &c), RAD_OK);
CHECK(c.draft_window == DraftWindow::Fixed);
CHECK_EQ(parse({ "--draft-window", "adaptive", "--num-speculative-tokens", "6" }, &c), RAD_OK);
CHECK(c.draft_window == DraftWindow::Adaptive);
CHECK_EQ(c.n_spec, 6);
for (const char* bad : { "Adaptive", "auto", "dynamic", "1", "" })
CHECK_EQ(parse({ "--draft-window", bad }, &c), RAD_E_INVAL);
CHECK_EQ(parse({ "--draft-window" }, &c), RAD_E_INVAL);
CHECK_EQ(std::string(draft_window_name(DraftWindow::Adaptive)), std::string("adaptive"));
CHECK_EQ(std::string(draft_window_name(DraftWindow::Fixed)), std::string("fixed"));
}
/* A POLICY NAME THIS BUILD DOES NOT KNOW WOULD FALL THROUGH TO THE DEFAULT, and a measurement
* comparing the default against itself is the failure that costs the most to notice. */
TEST(the_checkpoint_policy_is_one_of_the_three_that_exist) {
@@ -808,6 +830,9 @@ TEST(usage_names_every_flag_it_documents) {
CHECK(text.find("--host-pool-mib") != std::string::npos);
CHECK(text.find("--kv-cache-dtype") != std::string::npos);
CHECK(text.find("--num-speculative-tokens") != std::string::npos);
CHECK(text.find("--draft-window") != std::string::npos);
CHECK(text.find(std::string("Default ") + draft_window_name(kDraftWindowDefault)) !=
std::string::npos);
CHECK(text.find("--checkpoint-policy") != std::string::npos);
CHECK(text.find("--prefix-cache-host-mib") != std::string::npos);
CHECK(text.find("--tp-wire") != std::string::npos);
@@ -824,4 +849,22 @@ TEST(usage_names_every_flag_it_documents) {
CHECK(text.size() > 1000);
}
/* --rope-scaling is checked at the command line: a typo is a refusal, not a model served with its
* trained rotary at a length it cannot reach. */
TEST(rope_scaling_takes_yarn_with_a_factor_above_one_or_none) {
for (const char* ok : { "yarn:4", "yarn:2.5", "yarn:4:262144", "none" }) {
Config c;
CHECK_EQ(parse({ "--rope-scaling", ok }, &c), RAD_OK);
CHECK_EQ(c.rope_scaling, std::string(ok));
}
for (const char* bad : { "yarn:1", "yarn:0.5", "yarn:4x", "yarn:", "yarn:4:", "yarn:4:0",
"yarn:4:12k", "linear:2", "yarn" }) {
Config c;
CHECK(parse({ "--rope-scaling", bad }, &c) < 0);
}
Config d;
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK(d.rope_scaling.empty());
}
RAD_TEST_MAIN()
+57
View File
@@ -12,6 +12,7 @@
#include "format/tunecache.h"
#include "format/imatrix.h"
#include "format/safetensors.h"
#include "format/checkpoint.h"
#include <cstdio>
#include <cstdlib>
@@ -1901,6 +1902,62 @@ TEST(a_legacy_entry_count_that_is_not_one_is_refused) {
std::remove(path.c_str());
}
/* A GGUF's rotary scaling arrives as the config.json keys the architecture reads, type and all,
* and never as a bare factor in RadModelMeta::rope_scale. A YaRN modifier config.json has no
* spelling for is refused. */
TEST(a_gguf_rotary_scaling_becomes_the_config_keys_with_its_type) {
auto meta = [](const std::vector<GgufKv>& extra, const char* leaf, MetaOwn* out) -> int {
std::vector<GgufKv> kvs = { { "general.architecture", 8, 0, "llama" },
{ "llama.block_count", 4, 2, "" } };
kvs.insert(kvs.end(), extra.begin(), extra.end());
GgufFile g;
if (g.open(write_bin(leaf, gguf_bytes({}, kvs)).c_str()) != RAD_OK) return RAD_E_IO;
return meta_from_gguf(g, out);
};
{
MetaOwn m;
CHECK_OK(meta({ { "llama.rope.scaling.type", 8, 0, "yarn" },
{ "llama.rope.scaling.factor", 12, 4, "" },
{ "llama.rope.scaling.original_context_length", 4, 32768, "" } },
"yarn.gguf", &m));
CHECK_EQ(m.m.rope_scale, 1.0f);
REQUIRE(m.get("rope_scaling.type"));
CHECK_EQ(std::string(m.get("rope_scaling.type")), std::string("yarn"));
CHECK_EQ(std::string(m.get("rope_scaling.factor")), std::string("4"));
CHECK_EQ(std::string(m.get("rope_scaling.original_max_position_embeddings")),
std::string("32768"));
}
{ /* llama.cpp's default type is linear, and the older key names its factor. */
MetaOwn m;
CHECK_OK(meta({ { "llama.rope.scale_linear", 12, 2, "" } }, "linear.gguf", &m));
CHECK_EQ(std::string(m.get("rope_scaling.type")), std::string("linear"));
CHECK_EQ(std::string(m.get("rope_scaling.factor")), std::string("2"));
CHECK_EQ(m.m.rope_scale, 1.0f);
}
{ /* A type the architecture does not implement is carried by name for it to refuse. */
MetaOwn m;
CHECK_OK(meta({ { "llama.rope.scaling.type", 8, 0, "longrope" },
{ "llama.rope.scaling.factor", 12, 4, "" } }, "longrope.gguf", &m));
CHECK_EQ(std::string(m.get("rope_scaling.type")), std::string("longrope"));
}
{
MetaOwn m;
CHECK_OK(meta({ { "llama.rope.scaling.type", 8, 0, "none" },
{ "llama.rope.scaling.factor", 12, 4, "" } }, "none.gguf", &m));
CHECK(!m.get("rope_scaling.type"));
MetaOwn n;
CHECK_OK(meta({}, "plain.gguf", &n));
CHECK(!n.get("rope_scaling.type"));
}
{
MetaOwn m;
CHECK_EQ(meta({ { "llama.rope.scaling.type", 8, 0, "yarn" },
{ "llama.rope.scaling.factor", 12, 4, "" },
{ "llama.rope.scaling.attn_factor", 12, 2, "" } }, "attn.gguf", &m),
RAD_E_UNSUPPORTED);
}
}
TEST(a_gguf_version_this_reader_does_not_know_is_refused) {
const std::string path = write_bin("v2.imatrix", gguf_bytes(
{ { "t.in_sum2", { 2 }, { 1.0f, 2.0f } } }, {}, /*version=*/2));
+152
View File
@@ -591,6 +591,158 @@ TEST(kv_a_rank_whose_only_paged_group_is_zero_takes_the_others_block_count) {
CHECK_EQ(u.kv.carve(u.pools.kv()), RAD_E_STATE);
}
/* AN UNEVEN WORLD'S CHEAPER RANK pages the common token count in a smaller pool. The inverse of
* paged_tokens is exact at the MiB: the size it names reaches the count and one MiB less does not,
* and a rank whose only paged group is zero still has to hold its fixed costs. */
TEST(kv_pool_mib_for_tokens_is_the_inverse_of_paged_tokens) {
constexpr int64_t MiB = 1ll << 20;
Fixture dear, cheap, zero;
for (Fixture* f : { &dear, &cheap, &zero }) { f->cfg.checkpoint_slots = 0; f->cfg.vram_kv_mib = 8; }
std::vector<KVGroupInfo> cg = hybrid_groups();
cg[G_FULL].decl.n_head_kv = 1; /* half the page of the dear rank's */
std::vector<KVGroupInfo> zg = hybrid_groups();
zg[G_FULL].zero = true;
CHECK_OK(dear.kv.plan_groups(hybrid_groups(), dear.cfg));
CHECK_OK(cheap.kv.plan_groups(cg, cheap.cfg));
CHECK_OK(zero.kv.plan_groups(zg, zero.cfg));
const int64_t T = dear.kv.paged_tokens(8 * MiB);
CHECK(T > 0);
const int64_t need = cheap.kv.pool_mib_for_tokens(T, 8);
CHECK(need > 0 && need < 8);
CHECK(cheap.kv.paged_tokens(need * MiB) >= T);
CHECK(cheap.kv.paged_tokens((need - 1) * MiB) < T);
/* The dear rank needs its whole pool for its own count. */
CHECK_EQ(dear.kv.pool_mib_for_tokens(T, 8), (int64_t)8);
/* Past what the largest size pages: no answer, not a short pool. */
CHECK_EQ(cheap.kv.pool_mib_for_tokens(T * 1000, 8), (int64_t)-1);
/* All paged groups zero: the count is never its limit, its fixed state still is. */
const int64_t zn = zero.kv.pool_mib_for_tokens(T, 8);
CHECK(zn >= 0 && zn * MiB >= zero.kv.fixed_bytes());
CHECK(zn == 0 || (zn - 1) * MiB < zero.kv.fixed_bytes());
}
/* THE INVERSE ON A SHAPE, AND THE CARVE IT PROMISES. The dear rank's pool of `common_mib` sets the
* token count; the cheap rank's inverse names the least whole MiB that pages it (one MiB less does
* not, or does not hold the fixed costs); and a pool of exactly that size, capped at the count the
* way configure_kv caps every rank, carves every paged group the dear rank's block count -- the
* one block table. Returns the MiB the cheap rank needed. */
static int64_t check_inverse_and_carve(const std::vector<KVGroupInfo>& dear_g,
const std::vector<KVGroupInfo>& cheap_g, int64_t common_mib) {
constexpr int64_t MiB = 1ll << 20;
Fixture dear, cheap;
dear.cfg.checkpoint_slots = cheap.cfg.checkpoint_slots = 0;
dear.cfg.vram_kv_mib = common_mib;
CHECK_OK(dear.kv.plan_groups(dear_g, dear.cfg));
CHECK_OK(cheap.kv.plan_groups(cheap_g, cheap.cfg));
const int64_t T = dear.kv.paged_tokens(common_mib * MiB);
CHECK(T > 0 && T != KVManager::kUnboundedTokens);
const int64_t need = cheap.kv.pool_mib_for_tokens(T, common_mib);
CHECK(need > 0 && need < common_mib);
if (need <= 0) return need;
CHECK(cheap.kv.paged_tokens(need * MiB) >= T);
CHECK((need - 1) * MiB < cheap.kv.fixed_bytes() || cheap.kv.paged_tokens((need - 1) * MiB) < T);
cheap.cfg.vram_kv_mib = need;
CHECK_OK(dear.pools.configure(dear.cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator()));
CHECK_OK(cheap.pools.configure(cheap.cfg, 0, &rad_malloc_allocator(), &rad_malloc_allocator()));
CHECK_EQ(cheap.pools.kv().avail(), need * MiB);
CHECK_EQ(dear.kv.paged_tokens(dear.pools.kv().avail()), T);
dear.kv.cap_paged_tokens(T);
cheap.kv.cap_paged_tokens(T);
CHECK_OK(dear.kv.carve(dear.pools.kv()));
CHECK_OK(cheap.kv.carve(cheap.pools.kv()));
for (int32_t g = 1; g < (int32_t)dear_g.size(); ++g) {
if (!dear.kv.plan(g)->paged()) continue;
CHECK_EQ(cheap.kv.plan(g)->n_blocks, dear.kv.plan(g)->n_blocks);
CHECK(dear.kv.plan(g)->n_blocks > 0);
}
return need;
}
static KVGroupInfo paged_group(const char* name, int kind, int64_t heads, int64_t block,
std::vector<int32_t> layers, int64_t window = 0) {
KVGroupInfo k;
k.name = name;
k.decl.kind = kind;
k.decl.dtype = RAD_BF16;
k.decl.n_head_kv = heads;
k.decl.head_dim = 8;
k.decl.window = window;
k.block_size = block;
k.layers = std::move(layers);
return k;
}
/* A WINDOWED GROUP is capped at its window on both ranks, and the cap moves the bytes it frees to
* the other groups -- a kink in paged_split the inverse has to cross exactly. Here the dear rank's
* count is past the window, so its window group holds max_seqs x window_blocks on both ranks. */
TEST(kv_pool_mib_for_tokens_crosses_a_windowed_groups_cap) {
std::vector<KVGroupInfo> dear = hybrid_groups();
dear.push_back(paged_group("swa", RAD_KV_WINDOW, 4, 16, { 6, 7, 8, 9 }, 2048));
std::vector<KVGroupInfo> cheap = dear;
cheap[G_FULL].decl.n_head_kv = 1;
check_inverse_and_carve(dear, cheap, 32);
/* And with the cheap rank's window group the cheaper one: what it saves is all in the window. */
cheap = dear;
cheap[3].decl.n_head_kv = 1;
check_inverse_and_carve(dear, cheap, 32);
}
/* TWO PAGED GROUPS AT DIFFERENT BLOCK SIZES: one token count, two block counts, each the dear
* rank's. */
TEST(kv_pool_mib_for_tokens_holds_across_block_sizes) {
std::vector<KVGroupInfo> dear = hybrid_groups();
dear.push_back(paged_group("full32", RAD_KV_FULL, 2, 32, { 6, 7, 8 }));
std::vector<KVGroupInfo> cheap = dear;
cheap[G_FULL].decl.n_head_kv = 1;
check_inverse_and_carve(dear, cheap, 8);
cheap = dear;
cheap[3].decl.n_head_kv = 1;
check_inverse_and_carve(dear, cheap, 8);
}
/* AN ATTENTION-ZERO GROUP BESIDE ANOTHER PAGED GROUP: the zero group costs this rank nothing and
* takes no part in the split, so the other group alone sets what its pool pages -- and the zero
* group still holds the shared table's block count after the carve. */
TEST(kv_pool_mib_for_tokens_with_a_zero_group_beside_a_paged_one) {
std::vector<KVGroupInfo> dear = hybrid_groups();
dear.push_back(paged_group("full32", RAD_KV_FULL, 2, 32, { 6, 7, 8 }));
std::vector<KVGroupInfo> cheap = dear;
cheap[G_FULL].zero = true;
const int64_t need = check_inverse_and_carve(dear, cheap, 8);
/* Cheaper than a rank that keeps the group at half its heads. */
std::vector<KVGroupInfo> kept = dear;
kept[G_FULL].decl.n_head_kv = 1;
CHECK(need < check_inverse_and_carve(dear, kept, 8));
}
/* The re-split moves what the cheaper rank's KV pool saves into its weights pool, never past every
* weight resident and never below the common pool; what the cap leaves is reported, not allocated.
* A need that is not below the common pool changes nothing -- the even world's case. */
TEST(an_uneven_worlds_cheaper_rank_gives_its_saved_kv_to_its_weights_up_to_all_resident) {
constexpr int64_t MiB = 1ll << 20;
RankSplit s = vram_budget_rank_split(1000, 800, 200, 1300 * MiB);
CHECK(s.resplit);
CHECK_EQ(s.kv_mib, (int64_t)200);
CHECK_EQ(s.weights_mib, (int64_t)1300);
CHECK_EQ(s.unusable_mib, (int64_t)300);
CHECK(s.weights_mib + s.kv_mib <= 1000 + 800);
s = vram_budget_rank_split(1000, 800, 200, 5000 * MiB); /* room for all of it */
CHECK_EQ(s.weights_mib, (int64_t)1600);
CHECK_EQ(s.unusable_mib, (int64_t)0);
s = vram_budget_rank_split(1000, 800, 200, 500 * MiB); /* already all resident */
CHECK_EQ(s.weights_mib, (int64_t)1000);
CHECK_EQ(s.kv_mib, (int64_t)200);
CHECK_EQ(s.unusable_mib, (int64_t)600);
s = vram_budget_rank_split(1000, 800, 800, 5000 * MiB); /* costs the same: untouched */
CHECK(!s.resplit);
CHECK_EQ(s.weights_mib, (int64_t)1000);
CHECK_EQ(s.kv_mib, (int64_t)800);
s = vram_budget_rank_split(1000, 800, -1, 5000 * MiB); /* no answer: untouched */
CHECK(!s.resplit);
CHECK_EQ(s.kv_mib, (int64_t)800);
}
TEST(kv_refuses_a_group_with_no_block_size) {
/* Block size comes off the resolved attention kernel. A zero here means the attention op did
* not resolve, and the manager refuses rather than inventing 16. */
+5 -3
View File
@@ -117,9 +117,11 @@ grep -E "passed|failed" "$W/logs/kbench.log" | tail -3
say "4. the installed rad-kbench replays the fixture from the out-of-tree home: $(ls "$HH/kernels" | tr '\n' ' ')"
# 5. The device library's machine code, against the tree's, object by object. A code object also
# carries its compilation unit's ID, which clang hashes from the command line and the output path,
# so two builds of one source never agree byte for byte; their instructions (.text) and kernel
# descriptors do, unless the flags that reach the device compiler differ.
# carries its compilation unit's ID, which rad_add_plugin names from the plugin and the source's
# path inside it rather than leaving clang to hash the build directory into it
# (cmake/RadAddPlugin.cmake) -- so the instructions (.text), the kernel descriptors and the rest of
# the read-only data agree between the two builds wherever each was made, unless the flags that
# reach the device compiler differ.
#
# THE DESCRIPTORS ARE COMPARED BY NAME, NOT AS .rodata's BYTES. The compiler lays them out in an
# order that changes from one run of the same command to the next -- ROCm 7's clang does it to the
+42
View File
@@ -25,6 +25,8 @@
#include "rad_test.h"
#include "device/directio.h"
#include "mem/pools.h"
#include "mem/vram_budget.h"
#include "place/heat.h"
#include "place/mover.h"
#include "place/stager.h"
@@ -410,6 +412,46 @@ TEST(planner_spills_experts_before_dense_weights) {
CHECK_EQ(zero_copy, 6);
}
/* A RE-SPLIT RANK'S CONFIG REACHES BOTH READERS OF THE POOL SIZES. Engine::plan hands a rank whose
* cache costs less per token its own Config (vram_budget_rank_split): Pools::configure allocates
* the weights pool from it and the planner budgets the slab from it (Budgets::from), and the two
* have to read the same copy -- a grown pool the planner never reads is an empty pool, and a plan
* against a pool the rank does not have overruns it. plan_check_weights_pool is the startup check
* that they did. */
TEST(a_resplit_ranks_config_reaches_the_pools_and_the_planner) {
Fixture f;
build_moe(f, 8, 1 * MiB, nullptr);
Config common = base_config();
common.placement = "expert_tiered";
common.vram_weights_mib = 5; /* 1 MiB embedding and room for three experts and a shadow */
common.vram_kv_mib = 8;
common.host_pool_mib = 64;
const RankSplit rs = vram_budget_rank_split(common.vram_weights_mib, common.vram_kv_mib, 2,
64 * MiB);
CHECK(rs.resplit);
Config rc = common;
rc.vram_weights_mib = rs.weights_mib;
rc.vram_kv_mib = rs.kv_mib;
Pools pools;
CHECK_OK(pools.configure(rc, 0, &rad_malloc_allocator(), &rad_malloc_allocator()));
CHECK_EQ(pools.weights().bytes(), rs.weights_mib * MiB);
CHECK_EQ(pools.kv().bytes(), rs.kv_mib * MiB);
CHECK_EQ(Budgets::from(rc).vram_weights, pools.weights().bytes());
Plan grown, flat;
{ PlannerInput in{&f.prog, &rc, 0, 1, nullptr, 0}; CHECK_OK(Planner(in).plan(&grown)); }
{ PlannerInput in{&f.prog, &common, 0, 1, nullptr, 0}; CHECK_OK(Planner(in).plan(&flat)); }
CHECK_EQ(grown.vram_budget, pools.weights().bytes());
CHECK_EQ(plan_check_weights_pool(grown, pools.weights().bytes()), RAD_OK);
/* The grown pool is planned into: more of the experts are on the card. */
CHECK(grown.totals.bytes[(int)Tier::VRAM] > flat.totals.bytes[(int)Tier::VRAM]);
CHECK(grown.totals.bytes[(int)Tier::VRAM] + grown.slab_overhead <= pools.weights().bytes());
/* A planner handed the common split beside the rank's grown pool is refused by name. */
CHECK_EQ(plan_check_weights_pool(flat, pools.weights().bytes()), RAD_E_STATE);
}
/* THE BUDGET'S EXPERT FLOOR PLACES EVERY EXPERT. A lending cache leaves the expert slab exactly
* expert_vram_floor, so a floor short of what the planner spends -- the residents, the slab's
* spare slots beside them, and the slack each first-fit pass can strand -- is experts with no
+221 -1
View File
@@ -268,7 +268,7 @@ TEST(op_vocabulary) {
"gated_had_quant_i8",
"dequant",
"gemm_nt", "gemm_nt_bias", "gemm_nt_q", "gemm_nt_q_bias", "grid_embed",
"attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope",
"attn_paged", "attn_dense", "kv_store", "rope", "rope_table", "qk_norm_rope", "qsa_block_key",
"router_topk", "moe_scatter", "moe_gemm", "moe_gemm_q", "moe_gemm_q_mod4", "moe_gather",
"row_topk",
"row_topk_merge", "logit_rerank",
@@ -1779,6 +1779,226 @@ TEST(op_rope) {
CHECK_EQ(qkv.at(5), 9.0f);
}
/* STATIC YaRN, IN DOUBLE: cos and sin of rotary pair i at one position -- the inverse frequency
* theta^(-2i/rot), blended toward inv/factor over the linear ramp [low, high] as vLLM's
* YaRNScalingRotaryEmbedding blends it, times the magnitude. The bounds are vLLM's correction range
* at factor 2 over 262144 trained positions, theta 1e7 (tests/yarn_test.cpp holds yarn_from to the
* same integers), so these and the formula are the whole of the vLLM agreement.
*
* `tol` is what an f32 evaluation may differ by: 8 ulp of the angle (powf, the reciprocal, the blend
* and the product each cost about one) plus the rounding of the result. It is a few 1e-5 where the
* ramp sits at position 524287 and loose only in the fastest pairs there, which YaRN leaves
* unscaled and no f32 rotary places better than its angle's own ulp. */
struct YarnRef { double c, s, tol; };
YarnRef yarn_ref(double pos, int i, int rot, double low, double high) {
const double theta = 1e7, factor = 2.0, magnitude = 1.0 + 0.1 * std::log(2.0);
const double inv = std::pow(theta, -2.0 * i / rot);
const double ramp = std::min(1.0, std::max(0.0, (i - low) / (high == low ? 0.001 : high - low)));
const double a = pos * (inv / factor * ramp + inv * (1.0 - ramp));
return { std::cos(a) * magnitude, std::sin(a) * magnitude,
magnitude * (std::fabs(a) * 0x1p-20 + 0x1p-21) };
}
TEST(yarn_rotary_matches_a_double_yarn_through_524287) {
const std::vector<int64_t> positions = { 0, 1, 4096, 262143, 262144, 500000, 524287 };
const double magnitude = 1.0 + 0.1 * std::log(2.0);
const struct { int rot; double low, high; } cases[] = { { 64, 14, 22 }, { 128, 28, 43 },
{ 256, 56, 85 } };
for (const auto& c : cases) {
const int rot = c.rot, half = rot / 2, hd = rot + 16;
T pos(RAD_I32, {(int64_t)positions.size()}); pos.n(positions);
T qkv(RAD_F32, {(int64_t)positions.size(), hd * 3});
std::vector<float> values(positions.size() * hd * 3, 9.0f);
for (size_t m = 0; m < positions.size(); ++m)
for (int h = 0; h < 2; ++h)
for (int i = 0; i < rot; ++i) values[m * hd * 3 + h * hd + i] = i < half ? 1.0f : 0.0f;
qkv.f(values);
A direct; direct.t(qkv).t(pos).i("M", positions.size()).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 1)
.i("rotary_dim", rot).d("theta", 1e7).d("scale", 1).s("mode", "neox")
.d("yarn_factor", 2).d("yarn_low", c.low).d("yarn_high", c.high).d("yarn_magnitude", magnitude);
CHECK_OK(run("rope", direct));
/* The table is position-addressed. Allocate its real extent, not a compact stand-in. */
T table(RAD_F32, {524288, rot});
A ta; ta.t(pos).t(table).i("M", positions.size()).i("rot", rot).d("theta", 1e7).d("scale", 1).s("dtype", "f32")
.d("yarn_factor", 2).d("yarn_low", c.low).d("yarn_high", c.high).d("yarn_magnitude", magnitude);
CHECK_OK(run("rope_table", ta));
for (size_t m = 0; m < positions.size(); ++m) {
for (int i = 0; i < half; ++i) {
const YarnRef y = yarn_ref((double)positions[m], i, rot, c.low, c.high);
/* A unit pair (1, 0) rotated is (cos, sin). */
CHECK_NEAR(qkv.at(m * hd * 3 + i), y.c, y.tol);
CHECK_NEAR(qkv.at(m * hd * 3 + half + i), y.s, y.tol);
CHECK_EQ(table.at(positions[m] * rot + i), qkv.at(m * hd * 3 + i));
CHECK_EQ(table.at(positions[m] * rot + half + i), qkv.at(m * hd * 3 + half + i));
CHECK_EQ(qkv.at(m * hd * 3 + hd + i), qkv.at(m * hd * 3 + i));
}
for (int i = rot; i < hd; ++i) CHECK_EQ(qkv.at(m * hd * 3 + i), 9.0f);
for (int i = 0; i < hd; ++i) CHECK_EQ(qkv.at(m * hd * 3 + 2 * hd + i), 9.0f);
}
}
}
/* THE REFERENCE IS NOT VACUOUS: the same op with the bounds one pair off, or without the
* magnitude, lands outside yarn_ref's bound somewhere in the ramp. */
TEST(yarn_reference_bound_sees_a_shifted_ramp_and_a_missing_magnitude) {
const int rot = 64, hd = 64;
const double magnitude = 1.0 + 0.1 * std::log(2.0);
for (int variant = 0; variant < 2; ++variant) {
T pos(RAD_I32, {1}); pos.n({500000});
T qkv(RAD_F32, {1, hd});
std::vector<float> values((size_t)hd, 0.0f);
for (int i = 0; i < rot / 2; ++i) values[(size_t)i] = 1.0f;
qkv.f(values);
A a; a.t(qkv).t(pos).i("M", 1).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 0)
.i("rotary_dim", rot).d("theta", 1e7).d("scale", 1).s("mode", "neox")
.d("yarn_factor", 2).d("yarn_low", variant == 0 ? 15 : 14)
.d("yarn_high", variant == 0 ? 23 : 22).d("yarn_magnitude", variant == 0 ? magnitude : 1.0);
CHECK_OK(run("rope", a));
int outside = 0;
for (int i = 0; i < rot / 2; ++i) {
const YarnRef y = yarn_ref(500000.0, i, rot, 14, 22);
outside += std::fabs(qkv.at(i) - y.c) > y.tol || std::fabs(qkv.at(rot / 2 + i) - y.s) > y.tol;
}
CHECK(outside > 0);
}
}
/* QSA's compressed key. Identical unit keys pool to one and a unit gain with eps 0 norms to one,
* so what is left is the rotation at the block's position: c - s, then s + c, then the unrotated
* tail -- held to yarn_ref with YaRN on. Then the three things the op does besides rotate: the
* mean ROUNDED to k's dtype before the norm, `page` choosing the output row (and -1 none), and a
* [M, 3] position list read per frequency under imrope. */
TEST(op_qsa_block_key) {
const int64_t n = 128, ratio = 4, rot = 64;
const double magnitude = 1.0 + 0.1 * std::log(2.0);
{
const std::vector<int64_t> blocks = { 0, 262144, 524287 };
const int64_t M = (int64_t)blocks.size();
T k(RAD_F32, {M * ratio, n}); k.f(std::vector<float>((size_t)(M * ratio * n), 1.0f));
T w(RAD_F32, {n}); w.f(std::vector<float>((size_t)n, 1.0f));
T pos(RAD_I32, {M}); pos.n(blocks);
T out(RAD_F32, {M, n});
A a; a.t(k).t(w).tnull().t(pos).t(out).i("M", M).i("n", n).i("ratio", ratio)
.i("rotary_dim", rot).d("eps", 0).d("theta", 1e7).d("scale", 1).d("wadd", 0)
.s("dtype", "f32").d("yarn_factor", 2).d("yarn_low", 14).d("yarn_high", 22)
.d("yarn_magnitude", magnitude);
CHECK_OK(run("qsa_block_key", a));
for (int64_t b = 0; b < M; ++b)
for (int64_t i = 0; i < n; ++i) {
if (i >= rot) { CHECK_EQ(out.at(b * n + i), 1.0f); continue; }
const YarnRef y = yarn_ref((double)blocks[(size_t)b], (int)(i % (rot / 2)), (int)rot,
14, 22);
CHECK_NEAR(out.at(b * n + i), i < rot / 2 ? y.c - y.s : y.c + y.s, 2 * y.tol + 1e-6);
}
}
{ /* bf16 keys whose lane-0 mean, 1 + 2^-9, rounds to 1 before the norm reads it. */
T k(RAD_BF16, {ratio, 2});
k.f({ 1.0f, 2.0f, 1.0f, 2.0f, 1.0f, 2.0f, 1.0f + 0x1p-7f, 2.0f });
T w(RAD_F32, {2}); w.f({ 1.0f, 1.0f });
T out(RAD_F32, {1, 2});
A a; a.t(k).t(w).tnull().tnull().t(out).i("M", 1).i("n", 2).i("ratio", ratio)
.i("rotary_dim", 0).i("pos0", 0).d("eps", 0).d("theta", 1e7).d("wadd", 0)
.s("dtype", "bf16");
CHECK_OK(run("qsa_block_key", a));
CHECK_NEAR(out.at(0), 1.0 / std::sqrt(2.5), 1e-6);
CHECK_NEAR(out.at(1), 2.0 / std::sqrt(2.5), 1e-6);
}
{ /* page: block 0 to row 1, block 1 nowhere, block 2 to row 0. Block b's lanes are
* (1, b + 1), so each normed row says which block it came from. */
T k(RAD_F32, {3 * ratio, 2});
std::vector<float> kv;
for (int b = 0; b < 3; ++b)
for (int r = 0; r < ratio; ++r) { kv.push_back(1.0f); kv.push_back((float)(b + 1)); }
k.f(kv);
T w(RAD_F32, {2}); w.f({ 1.0f, 1.0f });
T page(RAD_I32, {3}); page.n({ 1, -1, 0 });
T out(RAD_F32, {2, 2}); out.f({ 7, 7, 7, 7 });
A a; a.t(k).t(w).t(page).tnull().t(out).i("M", 3).i("n", 2).i("ratio", ratio)
.i("rotary_dim", 0).i("pos0", 0).d("eps", 0).d("theta", 1e7).d("wadd", 0)
.s("dtype", "f32");
CHECK_OK(run("qsa_block_key", a));
CHECK_NEAR(out.at(0), 1.0 / std::sqrt(5.0), 1e-6);
CHECK_NEAR(out.at(1), 3.0 / std::sqrt(5.0), 1e-6);
CHECK_NEAR(out.at(2), 1.0, 1e-6);
CHECK_NEAR(out.at(3), 1.0, 1e-6);
}
{ /* imrope with a [M, 3] list: equal components are the one-position rotation, and moving
* component 1 moves frequency 1 (i % 3 == 1) and leaves frequency 0 alone. */
T k(RAD_F32, {ratio, n}); k.f(std::vector<float>((size_t)(ratio * n), 1.0f));
T w(RAD_F32, {n}); w.f(std::vector<float>((size_t)n, 1.0f));
auto key = [&](std::vector<int64_t> p, bool multi) {
T pos(RAD_I32, multi ? std::vector<int64_t>{1, 3} : std::vector<int64_t>{1}); pos.n(p);
T out(RAD_F32, {1, n});
A a; a.t(k).t(w).tnull().t(pos).t(out).i("M", 1).i("n", n).i("ratio", ratio)
.i("rotary_dim", rot).d("eps", 0).d("theta", 1e7).d("wadd", 0).s("dtype", "f32")
.s("mode", "imrope").s("sections", "11 11 10");
CHECK_OK(run("qsa_block_key", a));
std::vector<float> v((size_t)n);
for (int64_t i = 0; i < n; ++i) v[(size_t)i] = out.at(i);
return v;
};
const std::vector<float> one = key({ 5000 }, false), same = key({ 5000, 5000, 5000 }, true);
const std::vector<float> moved = key({ 5000, 9000, 5000 }, true);
for (int64_t i = 0; i < n; ++i) CHECK_EQ(same[(size_t)i], one[(size_t)i]);
CHECK_EQ(moved[0], one[0]);
CHECK(std::fabs(moved[1] - one[1]) > 1e-3);
}
}
TEST(disabled_yarn_ignores_auxiliary_coefficients) {
for (double magnitude : {2.0, (double)NAN}) {
T pos(RAD_I32, {1}); pos.n({0});
T qkv(RAD_F32, {1, 4}); qkv.f({1, 2, 3, 4});
A direct; direct.t(qkv).t(pos).i("M", 1).i("head_dim", 4)
.i("n_head", 1).i("n_head_kv", 0).d("theta", 10000).d("scale", 1)
.s("mode", "neox").d("yarn_factor", 0).d("yarn_low", NAN)
.d("yarn_high", NAN).d("yarn_magnitude", magnitude);
CHECK_OK(run("rope", direct));
for (int i = 0; i < 4; ++i) CHECK_EQ(qkv.at(i), (float)(i + 1));
T table(RAD_F32, {1, 4});
A ta; ta.t(pos).t(table).i("M", 1).i("rot", 4).d("theta", 10000)
.d("scale", 1).s("dtype", "f32").d("yarn_factor", 0)
.d("yarn_low", NAN).d("yarn_high", NAN).d("yarn_magnitude", magnitude);
CHECK_OK(run("rope_table", ta));
CHECK_EQ(table.at(0), 1.0f); CHECK_EQ(table.at(1), 1.0f);
CHECK_EQ(table.at(2), 0.0f); CHECK_EQ(table.at(3), 0.0f);
}
}
TEST(yarn_multimodal_positions_and_invalid_parameters) {
const int rot = 64, hd = 80;
T positions(RAD_I32, {3, 1}); positions.n({262144, 500000, 524287});
T mixed(RAD_F32, {1, hd});
std::vector<float> seed(hd, 9.0f);
for (int i = 0; i < rot; ++i) seed[i] = i < rot/2 ? 1.0f : 0.0f;
mixed.f(seed);
auto params = [&](A& a, const char* mode) -> A& {
return a.i("M", 1).i("head_dim", hd).i("n_head", 1).i("n_head_kv", 0)
.i("rotary_dim", rot).d("theta", 1e7).d("scale", 1).s("mode", mode)
.s("sections", "11 11 10").d("yarn_factor", 2).d("yarn_low", 14)
.d("yarn_high", 22).d("yarn_magnitude", 1.069314718);
};
A ma; ma.t(mixed).t(positions); params(ma, "imrope");
CHECK_OK(run("rope", ma));
for (int component = 0; component < 3; ++component) {
T plain(RAD_F32, {1, hd}); plain.f(seed);
T pos(RAD_I32, {1}); pos.n({positions.iat(component)});
A a; a.t(plain).t(pos); params(a, "neox");
CHECK_OK(run("rope", a));
for (int i = 0; i < 32; ++i) {
const int selected = i % 3 == 1 && i < 33 ? 1 : (i % 3 == 2 && i < 30 ? 2 : 0);
if (selected != component) continue;
CHECK_EQ(mixed.at(i), plain.at(i)); CHECK_EQ(mixed.at(i+32), plain.at(i+32));
}
}
for (int i = rot; i < hd; ++i) CHECK_EQ(mixed.at(i), 9.0f);
T single(RAD_I32, {1}); single.n({1});
A invalid; invalid.t(mixed).t(single); params(invalid, "axial");
CHECK_EQ(run("rope", invalid), RAD_E_UNSUPPORTED);
for (auto& p : invalid.ps) if (!std::strcmp(p.key, "yarn_factor")) p = RAD_F64("yarn_factor", NAN);
CHECK_EQ(run("rope", invalid), RAD_E_INVAL);
}
/* THE EPILOGUE IS THE UNFUSED CHAIN: the biased product, then the activation of it, then the
* residual -- each rounded where a separate tensor would be. */
TEST(op_gemm_nt_bias_epilogue) {
+595
View File
@@ -16,6 +16,9 @@
#include <cstdlib>
#include <cstring>
#include <new>
#include <string>
#include <unistd.h>
using namespace rad;
@@ -1604,6 +1607,598 @@ TEST(the_draft_depth_is_the_configured_one_whatever_the_acceptance_trace) {
CHECK_EQ(d3.next_depth(), 0);
}
/* ------------------------------------------------------------------ the adaptive window
* --draft-window adaptive (draft.h). The controller cases turn the policy on through Params, which
* is what Scheduler::init does with a serial drafter; the scheduler cases start a Fixture whose
* program declares one and whose Config asks for the window. */
namespace {
/* A small deterministic coin, the one the static case above uses. */
struct Coin {
uint64_t s = 12345;
bool operator()(double pr) {
s = s * 6364136223846793005ull + 1442695040888963407ull;
return ((double)((s >> 33) & 0xFFFFFF) / (double)0x1000000) < pr;
}
};
DraftController adaptive_controller(int max_depth) {
DraftController c;
DraftController::Params p;
p.max_depth = max_depth;
p.adapt = true;
CHECK_OK(c.configure(p));
return c;
}
/* An estimate as a test states it: acceptance `a0` at the first position and `rest` after it,
* started, with its stop where the controller puts it. */
DraftAdapt estimate(const DraftController& c, double a0, double rest) {
DraftAdapt s;
s.a[0] = (float)a0;
for (int j = 1; j < RAD_SCHED_MAX_SPEC; ++j) s.a[j] = (float)rest;
/* The stop draft.h states: the deepest draft emitted at least kDraftMinChance of the time. */
double p = 1.0;
int d = 0;
while (d < c.next_depth()) {
p *= (double)s.a[d];
if (p < DraftController::kDraftMinChance) break;
++d;
}
s.depth = d < DraftController::kMinDepth ? DraftController::kMinDepth : d;
return s;
}
/* What a scheduler fixture with the adaptive window looks like: a serial head of `depth`
* declared by the program, --num-speculative-tokens `depth`, --draft-window adaptive. */
void adaptive_fixture(Fixture& f, int depth) {
f.build(/*blocks=*/4096, /*states=*/64);
f.cfg.n_spec = depth;
f.cfg.draft_window = DraftWindow::Adaptive;
f.prog.drafter.kind = RAD_DRAFT_SERIAL;
f.prog.drafter.depth = depth;
}
/* Everything written to stderr while `fn` runs: the log lines a case checks for. */
template <class F> std::string stderr_of(F fn) {
std::string text;
FILE* tmp = std::tmpfile();
if (!tmp) return text;
const Log level = log_level();
log_set_level(Log::Info);
std::fflush(stderr);
const int saved = dup(2);
dup2(fileno(tmp), 2);
fn();
std::fflush(stderr);
dup2(saved, 2);
log_set_level(level);
close(saved);
std::rewind(tmp);
char buf[4096];
size_t n;
while ((n = std::fread(buf, 1, sizeof buf, tmp)) > 0) text.append(buf, n);
std::fclose(tmp);
return text;
}
} /* namespace */
TEST(the_adaptive_window_follows_each_sequences_own_acceptance) {
DraftController c = adaptive_controller(6);
CHECK(c.adaptive());
CHECK_EQ(c.next_depth(), 6); /* the ceiling is still the flag */
CHECK_EQ(c.step_depth(), 0); /* no step has chosen D: the ceiling stands */
/* Nothing measured yet: both start from the prior, which drafts the whole window. */
DraftAdapt code, summary;
CHECK_EQ(c.window_for(code), 6);
CHECK_EQ(c.window_for(summary), 6);
/* Two texts through one controller. The drafter almost always agrees on one; on the other it
* agrees at the first position and rarely after it. Each stop follows its own text. */
Coin coin;
for (int t = 0; t < 600; ++t) {
int d = c.window_for(code), a = 0;
while (a < d && coin(0.95)) ++a;
c.observe(d, a);
c.adapt_observe(code, d, a);
d = c.window_for(summary);
a = 0;
while (a < d && coin(a == 0 ? 0.6 : 0.2)) ++a;
c.observe(d, a);
c.adapt_observe(summary, d, a);
}
CHECK_EQ(c.window_for(code), 6);
CHECK(c.window_for(summary) >= 1);
CHECK(c.window_for(summary) <= 2);
CHECK(code.a[0] > 0.85f);
CHECK_NEAR(summary.a[0], 0.6, 0.2);
CHECK(c.yield(code, 6) > c.yield(summary, 6));
/* The global hazard is still counted, and the windows the verifies carried. */
CHECK(c.reached(0) == 1200);
CHECK(c.verified_at(6) >= 600);
CHECK(c.verified_at(1) + c.verified_at(2) > 0);
CHECK_EQ(c.verified_at(1) + c.verified_at(2) + c.verified_at(3) + c.verified_at(4) +
c.verified_at(5) + c.verified_at(6), (int64_t)1200);
/* And a stop that went shallow comes back when the text changes: the positions it stopped
* drafting drift toward the deepest it still drafts, so a text the drafter predicts again is
* found without anyone drafting deep first. */
for (int t = 0; t < 600; ++t) {
const int d = c.window_for(summary);
int a = 0;
while (a < d && coin(0.95)) ++a;
c.adapt_observe(summary, d, a);
}
CHECK_EQ(c.window_for(summary), 6);
}
/* A STOP MOVES ONLY PAST THE HOLD: it is the sequence's share of the step's pass shape, and a shape
* that followed every flicker of its estimate would re-record its passes for nothing
* (runtime/ctx.h). And it never goes below one draft, or the estimate could never recover. */
TEST(the_adaptive_window_moves_only_past_its_hold_and_never_below_one_draft) {
DraftController c = adaptive_controller(6);
DraftAdapt s;
CHECK_EQ(c.window_for(s), 6);
for (int t = 0; t < DraftController::kHold - 1; ++t) CHECK_EQ(c.adapt_observe(s, 6, 0), 6);
CHECK(c.adapt_observe(s, 6, 0) < 6); /* the kHold-th moves */
for (int t = 0; t < 400; ++t) c.adapt_observe(s, c.window_for(s), 0);
CHECK_EQ(c.window_for(s), DraftController::kMinDepth);
/* Off, the window is the flag and an observation is not taken. */
DraftController off;
DraftController::Params q;
q.max_depth = 5;
CHECK_OK(off.configure(q));
CHECK(!off.adaptive());
DraftAdapt w;
CHECK_EQ(off.window_for(w), 5);
CHECK_EQ(off.adapt_observe(w, 5, 0), 5);
CHECK_EQ(w.depth, 0);
off.observe(5, 2);
CHECK_EQ(off.verified_at(5), (int64_t)0);
off.step_time(3, 1, 12.0); /* and no step is timed */
CHECK_EQ(off.cost_samples(3, 1), (int64_t)0);
/* Adaptive with no speculation is no policy at all. */
DraftController zero = adaptive_controller(0);
CHECK(!zero.adaptive());
}
/* THE STEP COST IS MEASURED. A key -- the step's deepest window and its class of running
* sequences -- with samples is its own mean; one without borrows the nearest measured key's,
* scaled by the prior's shape; nothing measured is the prior. The same times give the same
* choice, which is what makes the policy a function of what it was shown. */
TEST(the_adaptive_window_prices_a_step_from_measured_step_times) {
DraftController c = adaptive_controller(6);
CHECK_NEAR(c.step_cost(1, 1), 1.06, 1e-12); /* the prior */
CHECK_NEAR(c.step_cost(6, 1), 1.36, 1e-12);
for (int i = 0; i < 10; ++i) c.step_time(3, 1, 12.0);
CHECK_EQ(c.cost_samples(3, 1), (int64_t)10);
CHECK_NEAR(c.step_cost(3, 1), 12.0, 1e-9);
CHECK_NEAR(c.step_cost(5, 1), 12.0 * 1.30 / 1.18, 1e-9); /* borrowed, the prior's shape */
CHECK_NEAR(c.step_cost(3, 9), 12.0, 1e-9); /* the nearest class */
CHECK_EQ(c.cost_samples(3, 9), (int64_t)0);
/* The classes: 1, 2-3, 4-7, 8-15, 16 and up. */
c.step_time(3, 2, 20.0);
CHECK_NEAR(c.step_cost(3, 3), 20.0, 1e-9);
CHECK_NEAR(c.step_cost(3, 4), 20.0, 1e-9); /* 4-7 borrows from 2-3 */
c.step_time(3, 16, 40.0);
CHECK_NEAR(c.step_cost(3, 1000), 40.0, 1e-9);
CHECK_NEAR(c.step_cost(3, 9), 40.0, 1e-9); /* 8-15: the nearest, 16 and up */
/* A step that waited on something else counts for at most four times the mean. */
const double before = c.step_cost(3, 1);
c.step_time(3, 1, 1.0e6);
CHECK(c.step_cost(3, 1) <= before * 4.0);
CHECK(c.step_cost(3, 1) > before);
/* Nonsense is not a sample. */
c.step_time(0, 1, 5.0);
c.step_time(7, 1, 5.0);
c.step_time(2, 1, -1.0);
c.step_time(2, 0, 5.0);
CHECK_EQ(c.cost_samples(2, 1), (int64_t)0);
/* One sequence that accepts nearly everything: on the prior the whole window pays... */
DraftController p = adaptive_controller(6);
DraftAdapt s = estimate(p, 0.9, 0.9);
DraftAdapt* one[1] = { &s };
CHECK_EQ(p.plan_step(one, 1, 1), 6);
/* ...and where the steps past three were measured dear, three is what pays. */
DraftController m = adaptive_controller(6);
const double t[7] = { 0, 10.0, 11.0, 12.0, 30.0, 30.0, 30.0 };
for (int d = 1; d <= 6; ++d) m.step_time(d, 1, t[d]);
DraftAdapt u = estimate(m, 0.9, 0.9);
DraftAdapt* mu[1] = { &u };
CHECK_EQ(m.plan_step(mu, 1, 1), 3);
CHECK_EQ(m.window_for(u), 3);
/* Deterministic: the same times and the same estimate give the same depth. */
DraftController m2 = adaptive_controller(6);
for (int d = 1; d <= 6; ++d) m2.step_time(d, 1, t[d]);
DraftAdapt u2 = estimate(m2, 0.9, 0.9);
DraftAdapt* mu2[1] = { &u2 };
CHECK_EQ(m2.plan_step(mu2, 1, 1), 3);
}
/* THE HEAD DEPTH IS THE STEP'S. A serial head runs as many rounds as the deepest window in the
* step, so a sequence that accepts deep is worth deep rounds only while what its neighbours lose
* to them -- every round is a pass over every drafting row -- does not outweigh it. */
TEST(the_adaptive_window_chooses_the_head_depth_over_the_whole_batch) {
DraftController c = adaptive_controller(6);
DraftAdapt deep = estimate(c, 0.95, 0.95);
DraftAdapt shallow = estimate(c, 0.5, 0.15);
CHECK_EQ(deep.depth, 6);
CHECK_EQ(shallow.depth, 1); /* its second draft is emitted 7.5 % of the time */
/* Side by side on the prior: deep rounds pay for the deep sequence, and the shallow one stops
* at its own first draft under them. */
DraftAdapt* two[2] = { &deep, &shallow };
CHECK_EQ(c.plan_step(two, 2, 2), 6);
CHECK_EQ(c.window_for(deep), 6);
CHECK_EQ(c.window_for(shallow), 1);
/* The same deep sequence among seven shallow ones, at a class whose steps were measured to
* grow by three units a round: what the rounds cost is paid by eight rows, and the one
* that gains from them does not repay it. Every window comes down to one. */
DraftController b = adaptive_controller(6);
for (int d = 1; d <= 6; ++d) b.step_time(d, 8, 10.0 + 3.0 * d);
DraftAdapt bd = estimate(b, 0.95, 0.95);
DraftAdapt bs[7];
DraftAdapt* eight[8] = { &bd };
for (int i = 0; i < 7; ++i) { bs[i] = estimate(b, 0.5, 0.15); eight[i + 1] = &bs[i]; }
CHECK_EQ(b.plan_step(eight, 8, 8), 1);
CHECK_EQ(b.window_for(bd), 1);
/* Alone at its own class, unmeasured, the same sequence takes the whole window. */
DraftController a = adaptive_controller(6);
for (int d = 1; d <= 6; ++d) a.step_time(d, 8, 10.0 + 3.0 * d);
DraftAdapt ad = estimate(a, 0.95, 0.95);
DraftAdapt* lone[1] = { &ad };
CHECK(a.plan_step(lone, 1, 1) > 1);
/* Rows that do not draft are part of the step: they emit a token whatever D is and pay for
* every round. Here three plain rows beside one drafting row at the same measured class. */
DraftController r = adaptive_controller(6);
for (int d = 1; d <= 6; ++d) r.step_time(d, 4, 10.0 + 3.0 * d);
DraftAdapt rd = estimate(r, 0.95, 0.95);
DraftAdapt* rone[1] = { &rd };
const int with_plain = r.plan_step(rone, 1, 4);
DraftController r2 = adaptive_controller(6);
for (int d = 1; d <= 6; ++d) r2.step_time(d, 4, 10.0 + 3.0 * d);
DraftAdapt rd2 = estimate(r2, 0.95, 0.95);
DraftAdapt* rone2[1] = { &rd2 };
const int alone = r2.plan_step(rone2, 1, 1); /* class 1 unmeasured: borrows class 4-7 */
CHECK(with_plain <= alone);
/* D MOVES PAST A HOLD AND A HYSTERESIS. The first step that drafts takes the best outright;
* after that a better depth waits kHold steps. */
DraftController h = adaptive_controller(6);
DraftAdapt hs = estimate(h, 0.95, 0.95);
DraftAdapt* hone[1] = { &hs };
CHECK_EQ(h.plan_step(hone, 1, 1), 6);
for (int d = 1; d <= 6; ++d) h.step_time(d, 1, d <= 2 ? 10.0 : 40.0);
for (int t = 0; t < DraftController::kHold - 1; ++t) CHECK_EQ(h.plan_step(hone, 1, 1), 6);
CHECK_EQ(h.plan_step(hone, 1, 1), 2);
/* No drafting sequence: D stays where it is. */
CHECK_EQ(h.plan_step(hone, 0, 3), 2);
}
/* THE FLAG, AND ONLY FOR A SERIAL HEAD. --draft-window adaptive with a block drafter, with prompt
* lookup alone, or with no speculation keeps the configured depth and says so at startup; the
* proposal then reaches the step uncut. The default is the fixed window. */
TEST(the_adaptive_window_is_a_flag_for_a_serial_drafter_and_said_when_it_is_not) {
{
Fixture f;
adaptive_fixture(f, 4);
int st = RAD_E_STATE;
const std::string log = stderr_of([&] { st = f.start(); });
CHECK_OK(st);
CHECK(f.sch.draft().adaptive());
CHECK(log.find("ADAPTIVE") != std::string::npos);
}
{
Fixture f;
adaptive_fixture(f, 4);
f.cfg.draft_window = DraftWindow::Fixed;
CHECK_OK(f.start());
CHECK(!f.sch.draft().adaptive());
Config d;
CHECK(d.draft_window == kDraftWindowDefault); /* the default */
}
for (int kind : { (int)RAD_DRAFT_BLOCK, (int)RAD_DRAFT_NONE }) {
Fixture f;
adaptive_fixture(f, 4);
f.prog.drafter.kind = (decltype(f.prog.drafter.kind))kind;
if (kind == RAD_DRAFT_NONE) f.prog.drafter.depth = 0;
int st = RAD_E_STATE;
const std::string log = stderr_of([&] { st = f.start(); });
CHECK_OK(st);
CHECK(!f.sch.draft().adaptive());
CHECK(log.find("--draft-window adaptive: the window is fixed at 4") != std::string::npos);
CHECK(log.find(kind == RAD_DRAFT_BLOCK ? "a block drafter" : "prompt lookup only") !=
std::string::npos);
const uint64_t a = f.submit(160, 64);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
int32_t draft[4] = { 21, 22, 23, 24 };
CHECK_OK(f.sch.set_draft(a, draft, 4));
CHECK_EQ(f.sch.find(a)->n_draft, 4);
CHECK(!f.sch.metrics().draft_adaptive);
}
{
Fixture f;
adaptive_fixture(f, 4);
f.cfg.n_spec = 0;
const std::string log = stderr_of([&] { CHECK_OK(f.start()); });
CHECK(!f.sch.draft().adaptive());
CHECK(log.find("does not speculate") != std::string::npos);
}
}
/* EACH SEQUENCE ITS OWN STOP, AND THE ROUNDS FOLLOW THE DEEPEST. The step issued ahead of a commit
* verifies, for each sequence, the first of those rounds up to its own window -- and the drafter's
* longer proposal is taken cut to that count rather than refused as a mismatch. */
TEST(the_adaptive_window_is_per_sequence_and_the_rounds_follow_the_deepest) {
Fixture f;
adaptive_fixture(f, 4);
CHECK_OK(f.start());
REQUIRE(f.sch.draft().adaptive());
const uint64_t a = f.submit(160, 2000);
const uint64_t b = f.submit(160, 2000);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
/* `a`'s drafts are never taken and `b`'s always are. */
int32_t draft[4] = { 21, 22, 23, 24 };
auto commit_ab = [&]() {
const StepPlan& pl = f.sch.plan();
std::vector<int32_t> acc(pl.e.size(), 0), tok(pl.e.size(), 9);
std::vector<uint8_t> eos(pl.e.size(), 0);
for (size_t i = 0; i < pl.e.size(); ++i) acc[i] = pl.e[i].seq == b ? pl.e[i].n_spec : 0;
Scheduler::StepResult r;
r.n_seq = (int)pl.e.size();
r.n_accepted = acc.data();
r.token = tok.data();
r.eos = eos.data();
CHECK_OK(f.sch.commit(r));
};
for (int t = 0; t < 64; ++t) {
CHECK_OK(f.sch.set_draft(a, draft, 4));
CHECK_OK(f.sch.set_draft(b, draft, 4));
REQUIRE(f.sch.step() != nullptr);
commit_ab();
}
CHECK_OK(f.sch.set_draft(a, draft, 4));
CHECK_OK(f.sch.set_draft(b, draft, 4));
const RadBatch* s = f.sch.step();
REQUIRE(s != nullptr);
CHECK_EQ(f.sch.draft().step_depth(), 4);
CHECK_EQ(s->n_spec, 4);
CHECK_EQ(s->n_tok, 2 + 5);
for (const StepEntry& e : f.sch.plan().e) CHECK_EQ(e.n_spec, e.seq == a ? 1 : 4);
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 2.5, 1e-6);
/* The head runs for the deepest. */
int rounds = 4;
Scheduler::SerialRow rows[4];
CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 2);
CHECK_EQ(rounds, 4);
REQUIRE(f.sch.serial_batch(0, 1) != nullptr);
for (int rd = 2; rd <= rounds; ++rd) REQUIRE(f.sch.serial_batch(rd, 1) != nullptr);
/* The step issued ahead: `a` verifies one of the four rounds, `b` all four. */
f.sch.find(a)->speculation_fixed = true;
f.sch.find(b)->speculation_fixed = true;
f.sch.expect_draft(a, rounds);
f.sch.expect_draft(b, rounds);
const RadBatch* nb = f.sch.step_next();
REQUIRE(nb != nullptr);
CHECK_EQ(nb->n_spec, 4);
CHECK_EQ(nb->n_tok, 2 + 5);
/* Its commit, the watermark, and the proposals published for the step already on the card:
* four rounds' worth to both, and each keeps what its step was planned to verify. */
commit_ab();
f.sch.serial_end(rounds);
CHECK_OK(f.sch.set_draft(a, draft, rounds));
CHECK_OK(f.sch.set_draft(b, draft, rounds));
CHECK_EQ(f.sch.find(a)->n_draft, 1);
CHECK_EQ(f.sch.find(b)->n_draft, 4);
f.sch.promote_next();
for (const StepEntry& e : f.sch.plan().e) CHECK_EQ(e.n_spec, e.seq == a ? 1 : 4);
CHECK(f.sch.metrics().draft_verify_depth[1] > 0);
CHECK(f.sch.metrics().draft_verify_depth[4] > 0);
}
/* A NEW SEQUENCE STARTS FROM THE SEQUENCES THAT FINISHED, ONE VOTE EACH. Pooled over verifies, a
* deep position is measured almost only on the texts good enough to be given a window that
* reaches it; here two texts the head predicts and two it does not, and the deep positions start
* a new sequence from all four. Until four have finished, the fixed prior. */
TEST(the_adaptive_window_starts_a_sequence_from_finished_sequences_not_pooled_verifies) {
DraftController c = adaptive_controller(6);
/* The pooled counts a deep-drafting good text leaves: position 5 accepted 95 % of the times
* it was reached. They do not set the prior. */
for (int t = 0; t < 1000; ++t) c.observe(6, 6);
CHECK_NEAR(c.prior_at(5), DraftController::kPrior, 1e-9);
DraftAdapt fresh;
(void)c.window_for(fresh);
CHECK_NEAR(fresh.a[5], DraftController::kPrior, 1e-6);
auto finished = [&](double a0, double rest) {
DraftAdapt s = estimate(c, a0, rest);
s.n[0] = 100;
return s;
};
/* Too few verifies to be more than its own prior: not counted. */
DraftAdapt young = finished(0.1, 0.1);
young.n[0] = 3;
c.adapt_retire(young);
c.adapt_retire(finished(0.95, 0.95));
c.adapt_retire(finished(0.95, 0.95));
c.adapt_retire(finished(0.3, 0.2));
CHECK_NEAR(c.prior_at(5), DraftController::kPrior, 1e-9); /* three: not yet */
c.adapt_retire(finished(0.3, 0.2));
CHECK_NEAR(c.prior_at(0), (0.95 + 0.95 + 0.3 + 0.3) / 4.0, 1e-6);
CHECK_NEAR(c.prior_at(5), (0.95 + 0.95 + 0.2 + 0.2) / 4.0, 1e-6);
DraftAdapt next;
(void)c.window_for(next);
CHECK_NEAR(next.a[5], (0.95 + 0.95 + 0.2 + 0.2) / 4.0, 1e-6);
/* An unstarted estimate is not a sequence to count. */
c.adapt_retire(DraftAdapt{});
CHECK_NEAR(c.prior_at(5), (0.95 + 0.95 + 0.2 + 0.2) / 4.0, 1e-6);
/* And through the scheduler: four requests whose head drafts are all refused finish, and the
* fifth starts at one draft where the first four started at the whole window. */
Fixture f;
adaptive_fixture(f, 4);
CHECK_OK(f.start());
std::vector<uint64_t> ids;
for (int i = 0; i < 4; ++i) ids.push_back(f.submit(160, 48));
REQUIRE(f.sch.step() != nullptr);
f.commit_plain(11);
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 0.0, 1e-6); /* none drafted yet */
int32_t draft[4] = { 21, 22, 23, 24 };
for (uint64_t id : ids) CHECK_OK(f.sch.set_draft(id, draft, 4));
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 4.0, 1e-6);
for (int t = 0; t < 200 && f.sch.metrics().finished < 4; ++t) {
for (uint64_t id : ids)
if (f.sch.find(id)) (void)f.sch.set_draft(id, draft, 4);
REQUIRE(f.sch.step() != nullptr);
f.commit_plain(11);
}
CHECK_EQ(f.sch.metrics().finished, (int64_t)4);
CHECK(f.sch.draft().prior_at(0) < 0.2);
/* The step depth came down with them; a fresh sequence that started at the fixed prior would
* take it back to four at its first cycle (the hold has long passed), and this one does not. */
CHECK_EQ(f.sch.draft().step_depth(), 1);
const uint64_t e = f.submit(160, 48);
REQUIRE(f.sch.step() != nullptr);
f.commit_plain(11);
CHECK_OK(f.sch.set_draft(e, draft, 4));
REQUIRE(f.sch.step() != nullptr); /* its first cycle chooses D */
f.commit_plain(11);
CHECK_EQ(f.sch.draft().step_depth(), 1);
CHECK_OK(f.sch.set_draft(e, draft, 4));
CHECK_EQ(f.sch.find(e)->n_draft, 1);
}
/* PROMPT LOOKUP IS NOT THE HEAD. When the head declines and the n-gram fallback proposes, the
* outcome is counted in the reported acceptance like any other draft and kept out of the
* sequence's estimate, which prices the head's next window. A run of lookups that are all refused
* leaves the head's window where it was; the same run of refusals from the head brings it down. */
TEST(the_adaptive_window_is_not_fed_by_prompt_lookup) {
Fixture f;
adaptive_fixture(f, 4);
CHECK_OK(f.start());
REQUIRE(f.sch.draft().adaptive());
/* A prompt that repeats, so the lookup always has a continuation to propose. */
auto r = std::make_unique<Request>();
r->id = f.next_id++;
r->max_tokens = 2000;
r->prompt.resize(160);
for (int i = 0; i < 160; ++i) r->prompt[(size_t)i] = 100 + i % 8;
const uint64_t a = r->id;
CHECK_OK(f.sch.add(std::move(r)));
REQUIRE(f.sch.step() != nullptr);
f.commit_plain(100); /* the pattern goes on */
int lookups = 0;
for (int t = 0; t < 4 * DraftController::kHold; ++t) {
REQUIRE(f.sch.step() != nullptr); /* nothing published: the lookup fills */
const StepEntry& e = f.sch.plan().e[0];
if (e.n_spec > 0) {
CHECK(e.ngram);
CHECK(e.n_spec <= f.sch.draft().step_window());
++lookups;
}
f.commit_plain(100 + (t + 1) % 8); /* every lookup refused */
}
CHECK(lookups >= 2 * DraftController::kHold);
const SchedMetrics m = f.sch.metrics();
CHECK(m.draft_tokens > 0); /* reported, as ever */
CHECK(m.draft_pos_reached[0] >= lookups);
CHECK_EQ(m.draft_accepted, (int64_t)0);
CHECK_NEAR(m.draft_depth_adaptive, 4.0, 1e-6); /* the head's window did not move */
/* The head's own refusals are what move it. */
int32_t draft[4] = { 21, 22, 23, 24 };
for (int t = 0; t < 4 * DraftController::kHold; ++t) {
CHECK_OK(f.sch.set_draft(a, draft, 4));
REQUIRE(f.sch.step() != nullptr);
CHECK(!f.sch.plan().e[0].ngram);
f.commit_plain(100 + (t + 1) % 8);
}
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 1.0, 1e-6);
}
/* THE SCHEDULER'S HALF OF THE COST: a decode step that verified drafts is timed at its deepest
* window and its row count when it finishes, and the head depth the next cycle chooses reads it.
* Measured dear past one round at two rows, both sequences' windows come down to one, and the
* rounds with them. */
TEST(the_adaptive_window_times_its_steps_and_the_next_cycle_reads_them) {
Fixture f;
adaptive_fixture(f, 4);
CHECK_OK(f.start());
REQUIRE(f.sch.draft().adaptive());
const uint64_t a = f.submit(160, 2000);
const uint64_t b = f.submit(160, 2000);
/* Every draft taken, so both stops stay at the whole window and only the cost moves D. */
auto commit_all = [&]() {
const StepPlan& pl = f.sch.plan();
std::vector<int32_t> acc(pl.e.size(), 0), tok(pl.e.size(), 9);
std::vector<uint8_t> eos(pl.e.size(), 0);
for (size_t i = 0; i < pl.e.size(); ++i) acc[i] = pl.e[i].is_prefill ? 0 : pl.e[i].n_spec;
Scheduler::StepResult r;
r.n_seq = (int)pl.e.size();
r.n_accepted = acc.data();
r.token = tok.data();
r.eos = eos.data();
CHECK_OK(f.sch.commit(r));
};
REQUIRE(f.sch.step() != nullptr); /* both prompts */
commit_all();
f.sch.step_finished(); /* a prefill step: not a sample */
for (int d = 1; d <= 4; ++d) CHECK_EQ(f.sch.draft().cost_samples(d, 2), (int64_t)0);
int32_t draft[4] = { 21, 22, 23, 24 };
CHECK_OK(f.sch.set_draft(a, draft, 4));
CHECK_OK(f.sch.set_draft(b, draft, 4));
REQUIRE(f.sch.step() != nullptr);
CHECK_EQ(f.sch.plan().n_spec, 4);
commit_all();
f.sch.step_finished();
CHECK_EQ(f.sch.draft().cost_samples(4, 2), (int64_t)1);
/* The hold, then a cycle that reads steps past one round as four times dearer. */
for (int d = 1; d <= 4; ++d)
for (int i = 0; i < 64; ++i) f.sch.draft().step_time(d, 2, d == 1 ? 10.0 : 40.0);
for (int t = 0; t < DraftController::kHold + 1; ++t) {
CHECK_OK(f.sch.set_draft(a, draft, 4));
CHECK_OK(f.sch.set_draft(b, draft, 4));
REQUIRE(f.sch.step() != nullptr);
commit_all();
}
CHECK_EQ(f.sch.draft().step_depth(), 1);
CHECK_OK(f.sch.set_draft(a, draft, 4));
CHECK_OK(f.sch.set_draft(b, draft, 4));
REQUIRE(f.sch.step() != nullptr);
for (const StepEntry& e : f.sch.plan().e) CHECK_EQ(e.n_spec, 1);
int rounds = 4;
Scheduler::SerialRow rows[4];
CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 2);
CHECK_EQ(rounds, 1);
f.sch.serial_end(0);
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 1.0, 1e-6);
}
/* ================================================================== the step path */
TEST(the_step_path_does_not_allocate) {
Fixture f;
+61
View File
@@ -2444,6 +2444,67 @@ TEST(concurrent_scrapes_count_each_total_once) {
CHECK_EQ(value("radiance:prefill_tokens_total"), 5000.0);
}
/* EACH DRAFT POSITION'S ACCEPTANCES ARE A COUNTER NEXT TO ITS REACH. At a fixed depth position
* j+1's reach is j's acceptances, but an adaptive window can end at j with j taken, so a ratio
* over a window needs both. Here two verifies end at position 1 with it accepted. */
TEST(each_draft_position_counts_its_acceptances) {
Metrics m("m", 1024);
server::SchedMetrics s;
s.draft_depth_seen = 3;
s.draft_pos_reached[0] = 10; s.draft_pos_accepted[0] = 7;
s.draft_pos_reached[1] = 7; s.draft_pos_accepted[1] = 5;
s.draft_pos_reached[2] = 3; s.draft_pos_accepted[2] = 2;
m.sample(s);
PromDoc d = parse_prom(m.render());
CHECK_EQ((int)d.errors.size(), 0);
CHECK_EQ(d.type["radiance:draft_position_accepted_total"], std::string("counter"));
CHECK_EQ(d.type["radiance:draft_position_reached_total"], std::string("counter"));
auto value = [&d](const std::string& name) {
auto it = d.samples.find(name);
return it == d.samples.end() ? -1.0 : it->second;
};
const std::string L = "{model_name=\"m\",engine=\"0\"";
const std::string A = "radiance:draft_position_accepted_total" + L + ",position=";
CHECK_NEAR(value(A + "\"0\"}"), 7.0, 1e-9);
CHECK_NEAR(value(A + "\"1\"}"), 5.0, 1e-9);
CHECK_NEAR(value(A + "\"2\"}"), 2.0, 1e-9);
CHECK_NEAR(value(A + "\"3\"}"), -1.0, 1e-9);
CHECK_NEAR(value("radiance:draft_position_acceptance_ratio" + L + ",position=\"1\"}"),
5.0 / 7.0, 1e-9);
}
/* THE ADAPTIVE DRAFT WINDOW (--draft-window adaptive) IS EXPOSED ONLY WHILE IT IS ON, so a
* deployment without it scrapes exactly what it always did -- and when it is on, the gauge and the
* histogram are well-formed families with the labels every other sample carries. */
TEST(the_adaptive_draft_window_is_exposed_only_while_it_is_on) {
Metrics m("m", 1024);
server::SchedMetrics s;
m.sample(s);
std::string body = m.render();
CHECK(body.find("radiance:draft_depth_adaptive") == std::string::npos);
CHECK(body.find("radiance:draft_verify_depth_total") == std::string::npos);
s.draft_adaptive = true;
s.draft_depth_adaptive = 2.5;
s.draft_verify_depth[2] = 7;
s.draft_verify_depth[5] = 3;
m.sample(s);
PromDoc d = parse_prom(m.render());
CHECK_EQ((int)d.errors.size(), 0);
CHECK_EQ(d.type["radiance:draft_depth_adaptive"], std::string("gauge"));
CHECK_EQ(d.type["radiance:draft_verify_depth_total"], std::string("counter"));
auto value = [&d](const std::string& name) {
auto it = d.samples.find(name);
return it == d.samples.end() ? -1.0 : it->second;
};
const std::string L = "{model_name=\"m\",engine=\"0\"";
CHECK_NEAR(value("radiance:draft_depth_adaptive" + L + "}"), 2.5, 1e-9);
CHECK_NEAR(value("radiance:draft_verify_depth_total" + L + ",depth=\"1\"}"), 0.0, 1e-9);
CHECK_NEAR(value("radiance:draft_verify_depth_total" + L + ",depth=\"2\"}"), 7.0, 1e-9);
CHECK_NEAR(value("radiance:draft_verify_depth_total" + L + ",depth=\"5\"}"), 3.0, 1e-9);
CHECK_NEAR(value("radiance:draft_verify_depth_total" + L + ",depth=\"6\"}"), -1.0, 1e-9);
}
TEST(models_and_health_answer) {
Fixture f;
HttpResponse r = f.get("/v1/models");
+353
View File
@@ -0,0 +1,353 @@
#include "rad_test.h"
#include "../arch/common/rad_arch.h"
#include "format/rope_override.h"
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
using rad::arch::Geom;
using rad::arch::yarn_from;
TEST(yarn_metadata_is_independent_of_deployment_context) {
const char* keys[] = {"rope_parameters.rope_type", "rope_parameters.factor",
"rope_parameters.original_max_position_embeddings", "draft.rope_parameters.rope_type",
"draft.rope_parameters.factor", "draft.rope_parameters.original_max_position_embeddings"};
const char* vals[] = {"yarn", "2", "262144", "yarn", "2", "262144"};
RadModelMeta m{}; m.n_kv = 6; m.kv_key = keys; m.kv_val = vals;
Geom target{}, draft{}; target.theta = draft.theta = 1e7f;
target.max_ctx = draft.max_ctx = 524288;
CHECK_OK(yarn_from(target, &m, "", 64));
CHECK_OK(yarn_from(draft, &m, "draft.", 128));
CHECK_EQ(target.yarn.low, 14.0f); CHECK_EQ(target.yarn.high, 22.0f);
CHECK_EQ(draft.yarn.low, 28.0f); CHECK_EQ(draft.yarn.high, 43.0f);
CHECK_NEAR(target.yarn.magnitude, 1.069314718, 1e-7);
target.max_ctx = 1048576;
CHECK_OK(yarn_from(target, &m, "", 64));
CHECK_EQ(target.yarn.low, 14.0f);
vals[4] = "4";
CHECK_OK(yarn_from(draft, &m, "draft.", 128));
CHECK_EQ(draft.yarn.factor, 4.0f); CHECK_EQ(target.yarn.factor, 2.0f);
}
/* THE CORRECTION BOUNDS ARE vLLM's: _yarn_find_correction_range at beta 32/1 over 262144 trained
* positions and theta 1e7, floored and ceiled, for the three rotary widths the Qwen family uses.
* These integers and the blend formula in abi/rad_yarn.h are the whole of the vLLM agreement; the
* frequency and phase references in tests/ref_test.cpp are pinned to them. */
TEST(yarn_correction_bounds_match_vllm_at_every_rotary_width) {
const char* keys[] = {"rope_parameters.rope_type", "rope_parameters.factor",
"rope_parameters.original_max_position_embeddings"};
const char* vals[] = {"yarn", "2", "262144"};
RadModelMeta m{}; m.n_kv = 3; m.kv_key = keys; m.kv_val = vals;
const struct { int64_t rot; float low, high; } want[] = {
{64, 14.0f, 22.0f}, {128, 28.0f, 43.0f}, {256, 56.0f, 85.0f}};
for (const auto& w : want) {
Geom g{}; g.theta = 1e7f;
CHECK_OK(yarn_from(g, &m, "", w.rot));
CHECK_EQ(g.yarn.low, w.low); CHECK_EQ(g.yarn.high, w.high);
CHECK_NEAR(g.yarn.magnitude, 1.0 + 0.1 * std::log(2.0), 1e-7);
}
}
/* ONE READER, AND IT ANSWERS FOR EVERY TYPE: default and the legacy `mrope` spelling are no
* scaling, linear divides positions, and a scheme it does not implement is refused by name with
* the geometry left as it was -- never read as a linear divide by its factor. */
TEST(the_rotary_reader_names_every_type_it_does_not_implement) {
const char* keys[] = {"rope_scaling.type", "rope_scaling.factor",
"rope_scaling.original_max_position_embeddings"};
const char* vals[] = {"mrope", "8", "8192"};
RadModelMeta m{}; m.n_kv = 3; m.kv_key = keys; m.kv_val = vals;
Geom g{}; g.theta = 5e5f; g.rope_scale = 7.0f;
CHECK_OK(yarn_from(g, &m, "", 128));
CHECK_EQ(g.yarn.factor, 0.0f); CHECK_EQ(g.rope_scale, 1.0f);
for (const char* t : {"llama3", "longrope", "dynamic", "su", "bogus"}) {
vals[0] = t;
g.rope_scale = 7.0f;
CHECK_EQ(yarn_from(g, &m, "", 128), RAD_E_UNSUPPORTED);
CHECK_EQ(g.rope_scale, 7.0f); CHECK_EQ(g.yarn.factor, 0.0f);
}
vals[0] = "linear";
CHECK_OK(yarn_from(g, &m, "", 128));
CHECK_EQ(g.rope_scale, 8.0f); CHECK_EQ(g.yarn.factor, 0.0f);
/* Nothing named at all is the default, whatever a previous read left. */
m.n_kv = 0;
CHECK_OK(yarn_from(g, &m, "", 128));
CHECK_EQ(g.rope_scale, 1.0f);
}
/* `truncate` is a JSON boolean: the converter writes 1/0, and true/false spelled out is the same. */
TEST(yarn_truncate_takes_true_and_false_as_well_as_one_and_zero) {
const char* keys[] = {"rope_parameters.rope_type", "rope_parameters.factor",
"rope_parameters.original_max_position_embeddings",
"rope_parameters.truncate"};
const char* vals[] = {"yarn", "2", "262144", "true"};
RadModelMeta m{}; m.n_kv = 4; m.kv_key = keys; m.kv_val = vals;
Geom a{}, b{}; a.theta = b.theta = 1e7f;
CHECK_OK(yarn_from(a, &m, "", 64));
CHECK_EQ(a.yarn.low, 14.0f); CHECK_EQ(a.yarn.high, 22.0f);
vals[3] = "1"; CHECK_OK(yarn_from(b, &m, "", 64)); CHECK_EQ(b.yarn.low, a.yarn.low);
vals[3] = "false";
CHECK_OK(yarn_from(a, &m, "", 64));
CHECK(a.yarn.low > 14.0f && a.yarn.low < 15.0f);
vals[3] = "0"; CHECK_OK(yarn_from(b, &m, "", 64)); CHECK_EQ(b.yarn.low, a.yarn.low);
for (const char* bad : {"yes", "2", "True"}) {
vals[3] = bad;
CHECK_EQ(yarn_from(a, &m, "", 64), RAD_E_INVAL);
}
}
TEST(yarn_metadata_rejects_bad_inputs_and_preserves_default) {
const char* keys[] = {"rope_parameters.rope_type", "rope_parameters.factor",
"rope_parameters.original_max_position_embeddings"};
const char* vals[] = {"yarn", "2", "262144"};
RadModelMeta m{}; m.n_kv = 3; m.kv_key = keys; m.kv_val = vals;
Geom g{}; g.theta = 1e7f;
for (const char* bad : {"0", "-1", "nan", "inf", "bogus", "2garbage"}) {
vals[1] = bad;
CHECK(yarn_from(g, &m, "", 64) != RAD_OK);
}
vals[1] = "2"; m.n_kv = 2;
CHECK(yarn_from(g, &m, "", 64) != RAD_OK);
vals[0] = "dynamic";
CHECK_EQ(yarn_from(g, &m, "", 64), RAD_E_UNSUPPORTED);
vals[0] = "default"; g.rope_scale = 1.0f;
CHECK_OK(yarn_from(g, &m, "", 64));
CHECK_EQ(g.yarn.factor, 0.0f); CHECK_EQ(g.rope_scale, 1.0f);
vals[0] = "linear";
CHECK_OK(yarn_from(g, &m, "", 64)); CHECK_EQ(g.rope_scale, 2.0f);
}
TEST(linear_metadata_rejects_fp32_overflow_and_underflow) {
const char* keys[] = {"rope_parameters.rope_type", "rope_parameters.factor"};
const char* vals[] = {"linear", "2"};
RadModelMeta m{}; m.n_kv = 2; m.kv_key = keys; m.kv_val = vals;
Geom g{};
for (const char* bad : {"1e300", "1e-300", "0", "-2", "nan", "inf"}) {
vals[1] = bad;
g.rope_scale = 3.0f;
CHECK_EQ(yarn_from(g, &m, "", 64), RAD_E_INVAL);
CHECK_EQ(g.rope_scale, 3.0f);
}
vals[1] = "0.5";
CHECK_OK(yarn_from(g, &m, "", 64));
CHECK_EQ(g.rope_scale, 0.5f);
}
TEST(yarn_legacy_explicit_magnitude_and_fractional_bounds) {
const char* keys[] = {"rope_scaling.type", "rope_scaling.factor",
"rope_scaling.original_max_position_embeddings", "rope_scaling.attention_factor",
"rope_scaling.truncate", "rope_scaling.beta_fast", "rope_scaling.beta_slow"};
const char* vals[] = {"yarn", "2", "262144", "1.25", "0", "32", "1"};
RadModelMeta m{}; m.n_kv = 7; m.kv_key = keys; m.kv_val = vals;
Geom g{}; g.theta = 1e7f;
CHECK_OK(yarn_from(g, &m, "", 64));
CHECK_EQ(g.yarn.magnitude, 1.25f);
CHECK(g.yarn.low > 14.0f && g.yarn.low < 15.0f);
CHECK(g.yarn.high > 21.0f && g.yarn.high < 22.0f);
vals[4] = "2"; CHECK(yarn_from(g, &m, "", 64) != RAD_OK);
vals[4] = "0"; vals[2] = "262144.5";
CHECK(yarn_from(g, &m, "", 64) != RAD_OK);
vals[2] = "262144"; vals[5] = "0.5";
CHECK(yarn_from(g, &m, "", 64) != RAD_OK);
}
/* --rope-scaling (core/format/rope_override.h) rewrites a container's keys at load; yarn_from then
* reads the result as it reads a converted container. These hold the two together. */
namespace {
struct Meta {
std::vector<std::string> k, v;
std::vector<const char*> kp, vp;
RadModelMeta m{};
Meta(std::initializer_list<std::pair<const char*, const char*>> kvs) {
for (const auto& p : kvs) { k.push_back(p.first); v.push_back(p.second); }
}
const RadModelMeta* meta() {
kp.clear(); vp.clear();
for (size_t i = 0; i < k.size(); ++i) { kp.push_back(k[i].c_str()); vp.push_back(v[i].c_str()); }
m = RadModelMeta{};
m.n_kv = (int)k.size(); m.kv_key = kp.data(); m.kv_val = vp.data();
return &m;
}
const std::string* get(const std::string& key) const {
for (size_t i = 0; i < k.size(); ++i) if (k[i] == key) return &v[i];
return nullptr;
}
};
/* What a Qwen3.8-Flash-Next container says about its rotary (rad-info --meta). */
Meta qfn_container() {
return Meta{ { "max_position_embeddings", "262144" },
{ "rope_parameters.mrope_section", "11 11 10" },
{ "rope_parameters.partial_rotary_factor", "0.25" },
{ "rope_parameters.rope_theta", "10000000" },
{ "rope_parameters.rope_type", "default" },
{ "text_config.max_position_embeddings", "262144" },
{ "text_config.rope_parameters.mrope_section", "11 11 10" },
{ "text_config.rope_parameters.partial_rotary_factor", "0.25" },
{ "text_config.rope_parameters.rope_theta", "10000000" },
{ "text_config.rope_parameters.rope_type", "default" } };
}
rad::RopeSpec spec(const char* s) {
rad::RopeSpec r;
CHECK(rad::rope_spec_parse(s, &r));
return r;
}
} /* namespace */
TEST(rope_spec_parse_takes_yarn_with_a_factor_above_one_or_none) {
rad::RopeSpec r;
CHECK(rad::rope_spec_parse("yarn:2", &r));
CHECK(r.kind == rad::RopeSpec::Yarn); CHECK_EQ(r.factor, 2.0); CHECK_EQ(r.orig, (int64_t)0);
CHECK(rad::rope_spec_parse("yarn:4:131072", &r));
CHECK_EQ(r.factor, 4.0); CHECK_EQ(r.orig, (int64_t)131072);
CHECK(rad::rope_spec_parse("none", &r)); CHECK(r.kind == rad::RopeSpec::None);
CHECK(rad::rope_spec_parse("", &r)); CHECK(r.kind == rad::RopeSpec::Keep);
for (const char* bad : { "yarn:1", "yarn:0.5", "yarn:4x", "yarn:", "yarn:4:", "yarn:4:0",
"yarn:4:12k", "linear:2", "yarn", "yarn:nan", "yarn:inf" })
CHECK(!rad::rope_spec_parse(bad, &r));
}
/* THE TRAP THE OVERRIDE EXISTS TO AVOID: the container names its rotary under text_config., and
* the reader takes the first object that names one -- so YaRN written beside it is never read. */
TEST(rope_override_writes_where_the_reader_looks_on_a_qwen38_container) {
{
Meta naive = qfn_container();
naive.v[4] = "yarn";
naive.k.push_back("rope_parameters.factor"); naive.v.push_back("2");
naive.k.push_back("rope_parameters.original_max_position_embeddings");
naive.v.push_back("262144");
Geom g{}; g.theta = 1e7f;
CHECK_OK(yarn_from(g, naive.meta(), "", 64));
CHECK_EQ(g.yarn.factor, 0.0f); /* text_config's "default" won */
}
Meta m = qfn_container();
std::string why;
CHECK(rad::rope_override_group(m.k, m.v, spec("yarn:2"), "", 262144, &why));
CHECK_EQ(*m.get("text_config.rope_parameters.rope_type"), std::string("yarn"));
CHECK_EQ(*m.get("rope_parameters.rope_type"), std::string("default")); /* untouched */
Geom g{}; g.theta = 1e7f;
CHECK_OK(yarn_from(g, m.meta(), "", 64));
CHECK_EQ(g.yarn.factor, 2.0f);
CHECK_EQ(g.yarn.low, 14.0f); CHECK_EQ(g.yarn.high, 22.0f);
CHECK_NEAR(g.yarn.magnitude, 1.0 + 0.1 * std::log(2.0), 1e-6);
CHECK_EQ(g.rope_scale, 1.0f);
const rad::RopeResolved r = rad::rope_resolve(m.k, m.v, "");
CHECK_EQ(r.type, std::string("yarn")); CHECK_EQ(r.factor, 2.0); CHECK_EQ(r.orig, 262144.0);
/* An explicit ORIG is the one used. */
Meta m2 = qfn_container();
CHECK(rad::rope_override_group(m2.k, m2.v, spec("yarn:4:131072"), "", 262144, &why));
Geom g2{}; g2.theta = 1e7f;
CHECK_OK(yarn_from(g2, m2.meta(), "", 64));
CHECK_EQ(g2.yarn.factor, 4.0f);
CHECK(g2.yarn.low < 14.0f); /* a shorter trained length moves the ramp down */
}
/* A checkpoint's own YaRN: the override's factor replaces it, its trained length stays, and what
* belonged to the old factor (an explicit attention_factor) goes so the reader derives it anew.
* `none` takes it off. */
TEST(rope_override_over_a_checkpoints_own_yarn_and_none_takes_it_off) {
auto legacy = [] {
return Meta{ { "rope_scaling.type", "yarn" }, { "rope_scaling.factor", "4" },
{ "rope_scaling.original_max_position_embeddings", "32768" },
{ "rope_scaling.attention_factor", "1.25" } };
};
Meta m = legacy();
std::string why;
CHECK(rad::rope_override_group(m.k, m.v, spec("yarn:2"), "", 131072, &why));
CHECK_EQ(*m.get("rope_scaling.original_max_position_embeddings"), std::string("32768"));
CHECK(!m.get("rope_scaling.attention_factor"));
Geom g{}; g.theta = 1e6f;
CHECK_OK(yarn_from(g, m.meta(), "", 128));
CHECK_EQ(g.yarn.factor, 2.0f);
CHECK_NEAR(g.yarn.magnitude, 1.0 + 0.1 * std::log(2.0), 1e-6);
Meta off = legacy();
CHECK(rad::rope_override_group(off.k, off.v, spec("none"), "", 131072, &why));
Geom g3{}; g3.theta = 1e6f; g3.rope_scale = 1.0f;
CHECK_OK(yarn_from(g3, off.meta(), "", 128));
CHECK_EQ(g3.yarn.factor, 0.0f);
CHECK_EQ(g3.rope_scale, 1.0f);
/* none on a model without YaRN changes nothing. */
Meta q = qfn_container();
const std::vector<std::string> before = q.v;
CHECK(rad::rope_override_group(q.k, q.v, spec("none"), "", 262144, &why));
CHECK(q.v == before);
}
/* Not stacked over another rotary scheme, and not without a trained length to scale from. The
* drafter is its own group, over its own trained length. */
TEST(rope_override_refuses_linear_and_scales_a_drafter_on_its_own) {
Meta lin{ { "rope_parameters.rope_type", "linear" }, { "rope_parameters.factor", "2" } };
std::string why;
CHECK(!rad::rope_override_group(lin.k, lin.v, spec("yarn:2"), "", 262144, &why));
CHECK(why.find("linear") != std::string::npos);
Meta bare{ { "rope_theta", "1000000" } };
CHECK(!rad::rope_override_group(bare.k, bare.v, spec("yarn:2"), "", 0, &why));
CHECK(rad::rope_override_group(bare.k, bare.v, spec("yarn:2:65536"), "", 0, &why));
CHECK_EQ(*bare.get("rope_parameters.rope_type"), std::string("yarn"));
/* The legacy `mrope` type is default with sections, so YaRN goes over it. */
Meta vl{ { "rope_scaling.type", "mrope" }, { "rope_scaling.mrope_section", "16 24 24" } };
CHECK(rad::rope_override_group(vl.k, vl.v, spec("yarn:2"), "", 32768, &why));
Geom gv{}; gv.theta = 1e6f;
CHECK_OK(yarn_from(gv, vl.meta(), "", 128));
CHECK_EQ(gv.yarn.factor, 2.0f);
Meta d = qfn_container();
d.k.push_back("draft.rope_parameters.rope_type"); d.v.push_back("default");
d.k.push_back("draft.max_position_embeddings"); d.v.push_back("262144");
CHECK(rad::rope_override_group(d.k, d.v, spec("yarn:2"), "", 262144, &why));
CHECK(rad::rope_override_group(d.k, d.v, spec("yarn:2"), "draft.", 262144, &why));
Geom t{}, dr{}; t.theta = dr.theta = 1e7f;
CHECK_OK(yarn_from(t, d.meta(), "", 64));
CHECK_OK(yarn_from(dr, d.meta(), "draft.", 128));
CHECK_EQ(t.yarn.factor, 2.0f); CHECK_EQ(dr.yarn.factor, 2.0f);
CHECK_EQ(dr.yarn.low, 28.0f); CHECK_EQ(dr.yarn.high, 43.0f);
}
/* A persisted prefix store is fingerprinted with rope_identity (Engine::configure_kv). The stock
* container, the same container under --rope-scaling, one converted with YaRN and the same model
* whose drafter alone is scaled must all differ; key order and unrelated keys must not matter. */
TEST(the_rotary_identity_tells_every_resolved_rotary_apart) {
std::string why;
Meta stock = qfn_container();
const std::string base = rad::rope_identity(stock.k, stock.v);
CHECK(!base.empty());
CHECK(base.find("text_config.rope_parameters.rope_type=default") != std::string::npos);
Meta flag = qfn_container();
CHECK(rad::rope_override_group(flag.k, flag.v, spec("yarn:2"), "", 262144, &why));
const std::string scaled = rad::rope_identity(flag.k, flag.v);
CHECK(scaled != base);
Meta flag4 = qfn_container();
CHECK(rad::rope_override_group(flag4.k, flag4.v, spec("yarn:4"), "", 262144, &why));
CHECK(rad::rope_identity(flag4.k, flag4.v) != scaled);
/* Converted with YaRN: the same keys written by the converter, not by the flag. */
Meta conv = qfn_container();
conv.v[9] = "yarn";
conv.k.push_back("text_config.rope_parameters.factor"); conv.v.push_back("2");
conv.k.push_back("text_config.rope_parameters.original_max_position_embeddings");
conv.v.push_back("262144");
CHECK(rad::rope_identity(conv.k, conv.v) != base);
conv.k.push_back("text_config.rope_parameters.beta_fast"); conv.v.push_back("16");
CHECK(rad::rope_identity(conv.k, conv.v) != rad::rope_identity(flag.k, flag.v));
Meta draft = qfn_container();
draft.k.push_back("draft.rope_theta"); draft.v.push_back("10000000");
const std::string d0 = rad::rope_identity(draft.k, draft.v);
draft.k.push_back("draft.rope_parameters.rope_type"); draft.v.push_back("yarn");
CHECK(rad::rope_identity(draft.k, draft.v) != d0);
Meta shuffled = qfn_container();
std::reverse(shuffled.k.begin(), shuffled.k.end());
std::reverse(shuffled.v.begin(), shuffled.v.end());
shuffled.k.push_back("eos_token_id"); shuffled.v.push_back("248044");
shuffled.k.push_back("max_position_embeddings"); shuffled.v.push_back("1");
CHECK_EQ(rad::rope_identity(shuffled.k, shuffled.v), base);
Meta gguf{ { "qwen35.rope.dimension_count", "64" }, { "qwen35.rope.freq_base", "1e7" },
{ "partial_rotary_factor", "0.25" }, { "qwen35.block_count", "64" } };
CHECK_EQ(rad::rope_identity(gguf.k, gguf.v),
std::string("partial_rotary_factor=0.25;qwen35.rope.dimension_count=64;"
"qwen35.rope.freq_base=1e7;"));
}
RAD_TEST_MAIN()
-1
View File
@@ -747,7 +747,6 @@ int main(int argc, char** argv) {
w.meta_i("n_expert_shared",meta.m.n_expert_shared);
w.meta_f("rms_eps", meta.m.rms_eps);
w.meta_f("rope_theta", meta.m.rope_theta);
w.meta_f("rope_scale", meta.m.rope_scale);
for (int i = 0; i < meta.m.n_kv; ++i) w.meta_s(meta.m.kv_key[i], meta.m.kv_val[i]);
/* THE CONTAINER CARRIES AN ENCODER'S WEIGHTS: what `--mm-max-patches auto` keys on. */
if (prog.encoder.modalities != 0) w.meta_s("radiance.encoder", prog.encoder_name.c_str());
+1 -1
View File
@@ -1707,7 +1707,7 @@ int main(int argc, char** argv) {
meta.n_expert = mi("n_expert", 0); meta.n_expert_used = mi("n_expert_used", 0);
meta.n_expert_shared = mi("n_expert_shared", 0);
meta.rms_eps = mf("rms_eps", 1e-6); meta.rope_theta = mf("rope_theta", 10000.f);
meta.rope_scale = mf("rope_scale", 1.f);
meta.rope_scale = 1.f; /* the rotary's scaling is the free-form rope keys (rad_builder.h) */
/* The gated-delta-net head counts. No op names them -- the kernels read them off the operands
* -- so a recipe sizing a GDN case would otherwise have to invent them, and a GDN check at an
+1 -1
View File
@@ -333,7 +333,7 @@ int main(int argc, char** argv) {
meta.n_expert = mi("n_expert", 0); meta.n_expert_used = mi("n_expert_used", 0);
meta.n_expert_shared = mi("n_expert_shared", 0);
meta.rms_eps = mf("rms_eps", 1e-6); meta.rope_theta = mf("rope_theta", 10000.f);
meta.rope_scale = mf("rope_scale", 1.f);
meta.rope_scale = 1.f; /* the rotary's scaling is the free-form rope keys (rad_builder.h) */
std::vector<std::string> kk, kv;
std::vector<const char*> kp, vp;