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.
This commit is contained in:
Deadcode committed 2026-10-07 12:37:53 +02:00
1 parent 6fa7707dff
commit ac79f4dc8a
63 files changed
+2744 -8759

No files matched your search

+54
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>
@@ -578,6 +580,58 @@ TEST(qwen35_bf16_yarn_reaches_every_text_rotary_op) {
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();
+27 -2
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,8 +849,6 @@ TEST(usage_names_every_flag_it_documents) {
CHECK(text.size() > 1000);
}
RAD_TEST_MAIN()
/* --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) {
@@ -843,3 +866,5 @@ TEST(rope_scaling_takes_yarn_with_a_factor_above_one_or_none) {
CHECK_EQ(parse({}, &d), RAD_OK);
CHECK(d.rope_scaling.empty());
}
RAD_TEST_MAIN()
-27
View File
@@ -1,27 +0,0 @@
"""Generate independent YaRN vectors using vLLM (Apache-2.0).
Run in the reference environment, redirect stdout to yarn_reference.json (CPU)
or pass cuda and redirect to yarn_reference_rocm.json (ROCm/gfx1201).
This script is not a runtime dependency and does not load model weights.
"""
import json
import sys
from types import SimpleNamespace
import torch
from vllm.model_executor.layers.rotary_embedding.yarn_scaling_rope import YaRNScalingRotaryEmbedding
positions = [0, 1, 4096, 262143, 262144, 500000, 524287]
cases = []
device = sys.argv[1] if len(sys.argv) > 1 else 'cpu'
with torch.device(device):
for rot in (64, 128, 256):
cfg = SimpleNamespace(base=10000000.0, rotary_dim=rot, max_position_embeddings=262144,
beta_fast=32, beta_slow=1, truncate=True)
inv = YaRNScalingRotaryEmbedding._compute_inv_freq(cfg, 2.0)
phase = torch.tensor(positions, dtype=torch.float32)[:, None] * inv[None, :]
magnitude = 1.0 + 0.1 * __import__('math').log(2.0)
cases.append(dict(rot=rot, theta=cfg.base, factor=2.0, original=262144,
magnitude=magnitude, inv_freq=inv.tolist(),
cos=(phase.cos()*magnitude).tolist(), sin=(phase.sin()*magnitude).tolist()))
print(json.dumps({'reference': f'vLLM YaRNScalingRotaryEmbedding; torch {device} FP32; static factor=2',
'positions': positions, 'cases': cases}, indent=2))
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+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));
+95
View File
@@ -621,6 +621,101 @@ TEST(kv_pool_mib_for_tokens_is_the_inverse_of_paged_tokens) {
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. */
+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
+141 -20
View File
@@ -22,8 +22,6 @@
#include "rad_abi.h"
#include "../libref/ref_common.h"
#include "rad_sample.h"
#include "../vendor/nlohmann/json.hpp"
#include <fstream>
#include <deque>
#include <string>
@@ -270,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",
@@ -1781,16 +1779,33 @@ TEST(op_rope) {
CHECK_EQ(qkv.at(5), 9.0f);
}
TEST(yarn_rotary_matches_independent_vllm_vectors) {
const std::string here = __FILE__;
std::ifstream input(here.substr(0, here.find_last_of('/')) + "/data/yarn_reference.json");
REQUIRE(input.good());
const auto fixture = nlohmann::json::parse(input);
const auto positions = fixture["positions"].get<std::vector<int64_t>>();
for (const auto& c : fixture["cases"]) {
const int rot = c["rot"], half = rot / 2, hd = rot + 16;
const double low = rot == 64 ? 14 : (rot == 128 ? 28 : 56);
const double high = rot == 64 ? 22 : (rot == 128 ? 43 : 85);
/* 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);
@@ -1800,20 +1815,19 @@ TEST(yarn_rotary_matches_independent_vllm_vectors) {
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", low).d("yarn_high", high).d("yarn_magnitude", c["magnitude"]);
.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", low).d("yarn_high", high).d("yarn_magnitude", c["magnitude"]);
.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 float cosine = c["cos"][m][i], sine = c["sin"][m][i];
/* FP32 libm/pow versus torch; at long positions an inverse-frequency ULP
* is amplified into the phase. Bound the actual absolute cosine error. */
CHECK_NEAR(qkv.at(m * hd * 3 + i), cosine, 0.004);
CHECK_NEAR(qkv.at(m * hd * 3 + half + i), sine, 0.004);
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));
@@ -1824,6 +1838,113 @@ TEST(yarn_rotary_matches_independent_vllm_vectors) {
}
}
/* 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});
+416 -291
View File
@@ -16,6 +16,9 @@
#include <cstdlib>
#include <cstring>
#include <new>
#include <string>
#include <unistd.h>
using namespace rad;
@@ -1605,12 +1608,12 @@ TEST(the_draft_depth_is_the_configured_one_whatever_the_acceptance_trace) {
}
/* ------------------------------------------------------------------ the adaptive window
* RADIANCE_DRAFT_ADAPT (draft.h). The switch is read from the environment once per process, so
* these cases turn the policy on through Params instead -- the controller cannot tell the two
* apart, and the tests do not depend on what the suite was started with. */
* --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. */
/* A small deterministic coin, the one the static case above uses. */
namespace {
/* A small deterministic coin, the one the static case above uses. */
struct Coin {
uint64_t s = 12345;
bool operator()(double pr) {
@@ -1618,96 +1621,131 @@ struct Coin {
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;
DraftController::Params p;
p.max_depth = 6;
p.adapt = true;
CHECK_OK(c.configure(p));
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 on the default cost wants it all. */
/* Nothing measured yet: both start from the prior, which drafts the whole window. */
DraftAdapt code, summary;
CHECK_EQ(c.depth_for(code), 6);
CHECK_EQ(c.depth_for(summary), 6);
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 window follows its own text. */
* 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.depth_for(code), a = 0;
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.depth_for(summary);
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.depth_for(code), 6);
CHECK(c.depth_for(summary) >= 1);
CHECK(c.depth_for(summary) <= 2);
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);
/* The estimate is the conditional rate, and the global hazard is still counted. */
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);
/* The windows the verifies carried are counted while the policy is on: 6 throughout for one,
* and 6 until the other moved off it. */
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 window that went shallow comes back when the text changes: the positions it stopped
/* 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.depth_for(summary);
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.depth_for(summary), 6);
CHECK_EQ(c.window_for(summary), 6);
}
/* A MOVE IS RATE-LIMITED: not within `hold` verifies of the last one, and only for a window worth
* `hyst` more than the one it leaves. A window that followed every flicker of its estimate would
* re-record its passes for nothing (runtime/ctx.h). */
TEST(the_adaptive_window_moves_only_past_its_hold_and_its_hysteresis) {
DraftController c;
DraftController::Params p;
p.max_depth = 6;
p.adapt = true;
p.hold = 50;
CHECK_OK(c.configure(p));
/* 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.depth_for(s), 6);
for (int t = 0; t < 49; ++t) CHECK_EQ(c.adapt_observe(s, 6, 0), 6); /* held */
CHECK(c.adapt_observe(s, 6, 0) < 6); /* the 50th moves */
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 */
/* The same trace with a hysteresis no estimate can clear never moves at all. */
DraftController h;
p.hold = 0;
p.hyst = 1000.0f;
CHECK_OK(h.configure(p));
DraftAdapt u;
CHECK_EQ(h.depth_for(u), 6);
for (int t = 0; t < 200; ++t) h.adapt_observe(u, 6, 0);
CHECK_EQ(u.depth, 6);
/* The floor holds whatever the estimate says. */
DraftController m;
p.hyst = 0.0f;
p.min_depth = 2;
CHECK_OK(m.configure(p));
DraftAdapt v;
for (int t = 0; t < 200; ++t) m.adapt_observe(v, m.depth_for(v), 0);
CHECK_EQ(m.depth_for(v), 2);
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;
@@ -1716,151 +1754,199 @@ TEST(the_adaptive_window_moves_only_past_its_hold_and_its_hysteresis) {
CHECK_OK(off.configure(q));
CHECK(!off.adaptive());
DraftAdapt w;
CHECK_EQ(off.depth_for(w), 5);
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);
/* Nonsense knobs are refused rather than run. */
DraftController bad;
DraftController::Params r;
r.max_depth = 4;
r.adapt = true;
r.half_life = 0.0f;
CHECK(bad.configure(r) < 0);
/* Adaptive with no speculation is no policy at all. */
DraftController zero = adaptive_controller(0);
CHECK(!zero.adaptive());
}
/* THE COST TABLE: measured points as they are, lines between them, the nearest two past the ends;
* and with fewer than two points, the default 1 + 0.06 d. A dear depth is a shallower window at
* the same estimate. */
TEST(the_adaptive_window_prices_a_step_from_the_cost_table) {
DraftController c;
DraftController::Params p;
p.max_depth = 6;
p.adapt = true;
p.cost[2] = 11.3f;
p.cost[3] = 12.0f;
CHECK_OK(c.configure(p));
CHECK_NEAR(c.cost(2), 11.3, 1e-4);
CHECK_NEAR(c.cost(3), 12.0, 1e-4);
CHECK_NEAR(c.cost(1), 10.6, 1e-4); /* extrapolated below */
CHECK_NEAR(c.cost(6), 14.1, 1e-4); /* and above */
/* 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);
DraftController d;
DraftController::Params q;
q.max_depth = 6;
q.adapt = true;
q.cost[1] = 1.0f;
q.cost[2] = 10.0f; /* a second draft costs nine times the first */
CHECK_OK(d.configure(q));
DraftAdapt s;
CHECK_EQ(d.depth_for(s), 1);
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 */
DraftController e;
DraftController::Params r;
r.max_depth = 4;
r.adapt = true;
r.cost[3] = 5.0f; /* one point is no table */
CHECK_OK(e.configure(r));
CHECK_NEAR(e.cost(1), 1.06, 1e-9);
CHECK_NEAR(e.cost(4), 1.24, 1e-9);
/* 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);
/* A table whose line runs below zero is the wrong sign, and the default is used. */
DraftController g;
DraftController::Params t;
t.max_depth = 6;
t.adapt = true;
t.cost[1] = 10.0f;
t.cost[2] = 4.0f;
CHECK_OK(g.configure(t));
CHECK_NEAR(g.cost(6), 1.36, 1e-9);
/* 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 SCHEDULER'S HALF: the cap on a proposal, and the rounds the head runs. One sequence whose
* prior pays for two drafts of a ceiling of four verifies two, and the head runs two rounds. */
TEST(the_adaptive_window_caps_the_proposal_and_the_rounds) {
Fixture f;
f.build(/*blocks=*/4096, /*states=*/64);
f.cfg.n_spec = 4;
CHECK_OK(f.start());
DraftController::Params p;
p.max_depth = 4;
p.adapt = true;
p.prior = 0.3f; /* on the default cost: two */
CHECK_OK(f.sch.draft().configure(p));
/* 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 */
const uint64_t a = f.submit(160, 64);
CHECK(f.sch.step() != nullptr);
f.commit_plain(11);
/* 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);
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, 2);
const RadBatch* b = f.sch.step();
REQUIRE(b != nullptr);
CHECK_EQ(b->n_spec, 2);
CHECK_EQ(b->n_tok, 3);
CHECK_EQ(f.sch.plan().e[0].n_spec, 2);
/* 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);
int rounds = 4;
Scheduler::SerialRow rows[4];
CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 1);
CHECK_EQ(rounds, 2);
const RadBatch* hb = f.sch.serial_batch(0, 1);
REQUIRE(hb != nullptr);
CHECK_EQ(hb->n_tok, 3); /* every verified position, as ever */
CHECK(f.sch.serial_batch(2, 1) != nullptr);
f.sch.serial_end(2);
/* 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);
const SchedMetrics m = f.sch.metrics();
CHECK(m.draft_adaptive);
CHECK_NEAR(m.draft_depth_adaptive, 2.0, 1e-6);
CHECK_EQ(m.draft_depth, 4); /* the ceiling, as before */
/* 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);
}
/* A BLOCK DRAFTER KEEPS ITS DEPTH. The engine turns the policy off before the first step when the
* drafter proposes its block in one pass; the proposal then reaches the step uncut, as without the
* switch. */
TEST(the_adaptive_window_turns_off_for_a_block_drafter) {
Fixture f;
f.build(/*blocks=*/4096, /*states=*/64);
f.cfg.n_spec = 4;
CHECK_OK(f.start());
DraftController::Params p;
p.max_depth = 4;
p.adapt = true;
p.prior = 0.3f; /* on the default cost: two */
CHECK_OK(f.sch.draft().configure(p));
f.sch.draft_adapt_off("a block drafter");
CHECK(!f.sch.draft().adaptive());
/* 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);
const SchedMetrics m = f.sch.metrics();
CHECK(!m.draft_adaptive);
f.sch.draft_adapt_off("again"); /* a second call is a no-op */
CHECK(!f.sch.draft().adaptive());
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 WINDOW, 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. */
/* 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;
f.build(/*blocks=*/4096, /*states=*/64);
f.cfg.n_spec = 4;
adaptive_fixture(f, 4);
CHECK_OK(f.start());
DraftController::Params p;
p.max_depth = 4;
p.adapt = true;
p.hold = 0;
p.hyst = 0.0f;
CHECK_OK(f.sch.draft().configure(p));
REQUIRE(f.sch.draft().adaptive());
const uint64_t a = f.submit(160, 2000);
const uint64_t b = f.submit(160, 2000);
@@ -1892,6 +1978,7 @@ TEST(the_adaptive_window_is_per_sequence_and_the_rounds_follow_the_deepest) {
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);
@@ -1929,27 +2016,141 @@ TEST(the_adaptive_window_is_per_sequence_and_the_rounds_follow_the_deepest) {
CHECK(f.sch.metrics().draft_verify_depth[4] > 0);
}
/* THE LOAD CAP (RADIANCE_DRAFT_ADAPT_BUSY) IS COUNTED ONCE A CYCLE AND HELD FOR IT. The load moves
* between cycles -- a sequence admitted, a client hanging up -- and the cap follows it from the
* next cycle on; within one, the plan, the rounds, the step issued ahead and the proposal
* published after the commit all see the same cap, so a count that changes mid-cycle is never a
* mismatch. The estimates learn on underneath: the windows come back with the load. */
TEST(the_busy_cap_is_counted_once_a_cycle_and_follows_the_load_between_cycles) {
Fixture f;
f.build(/*blocks=*/4096, /*states=*/64);
f.cfg.n_spec = 4;
CHECK_OK(f.start());
DraftController::Params p;
p.max_depth = 4;
p.adapt = true;
p.busy = 2; /* more than two running is busy */
p.busy_depth = 2;
CHECK_OK(f.sch.draft().configure(p));
CHECK_EQ(f.sch.draft().busy_cap(2), 0);
CHECK_EQ(f.sch.draft().busy_cap(3), 2);
/* 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 };
/* Every draft taken, so every estimate stays at the whole window. */
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);
@@ -1962,116 +2163,40 @@ TEST(the_busy_cap_is_counted_once_a_cycle_and_follows_the_load_between_cycles) {
r.eos = eos.data();
CHECK_OK(f.sch.commit(r));
};
auto spec_of = [&](uint64_t id) {
for (const StepEntry& e : f.sch.plan().e) if (e.seq == id) return (int)e.n_spec;
return -1;
};
const uint64_t a = f.submit(160, 2000);
const uint64_t b = f.submit(160, 2000);
REQUIRE(f.sch.step() != nullptr); /* both prompts */
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);
/* Two running is not busy: each takes its own window. */
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(spec_of(a), 4);
CHECK_EQ(spec_of(b), 4);
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);
/* A third arrives. The plan that admits it counted two when its cycle opened, so that cycle
* is not busy yet... */
const uint64_t c = f.submit(160, 2000);
/* 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);
CHECK_EQ(spec_of(a), 4);
CHECK_EQ(spec_of(c), 0); /* its prompt */
commit_all();
/* ...and the next one is: three running, every window capped, no estimate moved. The
* proposals were published under the last cycle, four long; this plan cuts them. */
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(spec_of(a), 2);
CHECK_EQ(spec_of(b), 2);
CHECK(spec_of(c) <= 2);
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 2.0, 1e-6);
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), 3);
CHECK_EQ(rounds, 2);
REQUIRE(f.sch.serial_batch(0, 1) != nullptr);
REQUIRE(f.sch.serial_batch(2, 1) != nullptr);
/* The step issued ahead verifies the cycle's count... */
for (uint64_t id : { a, b, c }) f.sch.find(id)->speculation_fixed = true;
for (uint64_t id : { a, b, c }) f.sch.expect_draft(id, rounds);
const RadBatch* nb = f.sch.step_next();
REQUIRE(nb != nullptr);
CHECK_EQ(nb->n_spec, 2);
/* ...and a client hangs up before the commit. Two running would not be busy, and the cycle
* keeps its cap anyway: the proposal published after the commit matches the step that is
* already on the card, so set_draft has nothing to refuse. */
CHECK_OK(f.sch.cancel(c));
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 2.0, 1e-6);
commit_all();
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, 2);
/* The next cycle opens on the load as it now is: two running, the cap lifted, and the
* windows are the whole window again at once -- the estimates never stopped learning. */
f.sch.promote_next();
CHECK_EQ(spec_of(a), 2); /* planned last cycle */
rounds = 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);
commit_all();
f.sch.serial_end(rounds);
CHECK_OK(f.sch.set_draft(a, draft, rounds));
CHECK_OK(f.sch.set_draft(b, draft, rounds));
REQUIRE(f.sch.step() != nullptr);
CHECK_EQ(spec_of(a), 4);
CHECK_EQ(spec_of(b), 4);
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 4.0, 1e-6);
commit_all();
/* THE SAME HANG-UP WITH NO STEP ISSUED AHEAD, where the held cap is what the proposal gets: a
* busy cycle stays busy to its end, and the next plan is the first to see the load fall. */
const uint64_t e = f.submit(160, 2000);
CHECK_OK(f.sch.set_draft(a, draft, 4));
CHECK_OK(f.sch.set_draft(b, draft, 4));
REQUIRE(f.sch.step() != nullptr); /* admits it; counted two */
commit_all();
CHECK_OK(f.sch.set_draft(a, draft, 4));
CHECK_OK(f.sch.set_draft(b, draft, 4));
REQUIRE(f.sch.step() != nullptr); /* counted three: busy */
CHECK_EQ(spec_of(a), 2);
CHECK_OK(f.sch.cancel(e));
commit_all();
CHECK_OK(f.sch.set_draft(a, draft, 4));
CHECK_EQ(f.sch.find(a)->n_draft, 2); /* the cycle's cap, not the live count's */
REQUIRE(f.sch.step() != nullptr); /* counted two: lifted */
CHECK_EQ(spec_of(a), 2); /* drafted under the busy cycle */
rounds = 4;
CHECK_EQ(f.sch.serial_begin(&rounds, rows, 4), 2);
CHECK_EQ(rounds, 4);
CHECK_EQ(rounds, 1);
f.sch.serial_end(0);
/* No threshold set: no cap, whatever the load. */
DraftController::Params q;
q.max_depth = 4;
q.adapt = true;
DraftController d;
CHECK_OK(d.configure(q));
CHECK_EQ(d.busy_cap(1000), 0);
CHECK_NEAR(f.sch.metrics().draft_depth_adaptive, 1.0, 1e-6);
}
/* ================================================================== the step path */
+3 -3
View File
@@ -2473,9 +2473,9 @@ TEST(each_draft_position_counts_its_acceptances) {
5.0 / 7.0, 1e-9);
}
/* THE ADAPTIVE DRAFT WINDOW (RADIANCE_DRAFT_ADAPT) 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. */
/* 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;
+120
View File
@@ -2,6 +2,7 @@
#include "../arch/common/rad_arch.h"
#include "format/rope_override.h"
#include <algorithm>
#include <cmath>
#include <string>
#include <vector>
@@ -30,6 +31,72 @@ TEST(yarn_metadata_is_independent_of_deployment_context) {
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"};
@@ -217,6 +284,12 @@ TEST(rope_override_refuses_linear_and_scales_a_drafter_on_its_own) {
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");
@@ -230,4 +303,51 @@ TEST(rope_override_refuses_linear_and_scales_a_drafter_on_its_own) {
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()