Add Spark rotated-int8 inference and calibration

Serve the Spark X2.6 trunk on IQ8R's rotated int8 grid. Six projection types a layer carry
fwht128-rotated int8 weights with a bf16 scale per 128 columns; activations are quantised into
the same 128-column groups and feed the `i8a8h` rows, exact GELU runs before the down
projection's own Hadamard quantiser, and the embedding, the two norms a layer, the head's norm
and the 16-row attention gate stay as they are. The descriptor is `w8a8_fwht128`, and the
container says `quantization_config.quant_method=w8a8`, `fmt=fwht128`.

`data/recipes/spark-x26-4b-iq8r.recipe` fits those weights by GPTQ against the model's own
calibration Hessians, which the BF16 plugin writes as RADGRAM2 files under `RADIANCE_CALIB_DIR`;
each layer's f32 [K,K] accumulators are 533 MB, so `RADIANCE_SPARK_CALIB_LAYERS=lo:hi` calibrates
a slice at a time into one directory. The output head is RTN. Column-sharded inputs and their
offsets must land on whole scale groups, so a rank with an unaligned span is refused rather than
served with misaligned scales: TP 1, 2, 4 and 8 align for these shapes, TP 3 does not for the
FFN-down shard. Calibration asks for TP=1, because the off-diagonal cross-rank terms only exist
on one card.

`tests/spark25_iq8r.py` compares a deterministic quantised fixture against the Transformers
reference, top-10 probabilities included, across cached decoding; `--tp 2` checks two fake host
ranks and `--wide-tp --tp N` the group-aligned attention and FFN shards for N from 1 to 8. Run it
under a GPU-denying device cgroup, as with the BF16 fixture.

Against this checkpoint's own BF16 container, 32 held-out chat, math, code and tool-call samples
and 31,391 positions, greedy with prefix caching off: 98.60% of positions keep their top token,
mean KL 0.00408, median 6.5e-5, p99 0.0496, p99.9 0.348, worst 11.88. The tail is the honest
part -- 13 positions above one nat -- and leaving the first twelve layers in BF16 takes the worst
to 0.247 with nothing above one nat, for about 12% of prefill and 17% of decode. One R9700, zero
cached prompt tokens: 11.8k, 11.8k and 11.3k tok/s of prefill at 1.1k, 4.4k and 9.9k-token
prompts, 93.7 tok/s of decode from a short prompt and 88.9 with a 4.4k-token context. 8.29 GiB of
BF16 weights become 4.52 GiB.

That comparison is distribution agreement against BF16, not a task benchmark, and the corpus the
Grams came from is public text held disjoint from the holdout by hash; no MMLU or GSM8K-class
number is claimed here. The numbers need the prefill softmax scaling per row rather than per
wave: while a row's rounding depended on its wave-mates, the quantised container was worse off
against BF16 than its own error explains.
This commit is contained in:
Constantin committed 2026-11-03 13:53:26 -05:00
1 parent 5d6de60318
commit cb97b1c886
9 files changed
+974 -44

No files matched your search

+51 -1
View File
@@ -11,6 +11,7 @@
* and writes bf16 for the linear projections. * and writes bf16 for the linear projections.
*/ */
#include <arch/rad_arch.h> #include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include "chat.h" #include "chat.h"
#include "spark25_prefill_pass_key.h" #include "spark25_prefill_pass_key.h"
@@ -29,6 +30,7 @@ struct Layer {
rad_op anorm = 0, qp = 0, kp = 0, vp = 0, gp = 0, rq = 0, rk = 0, store = 0, attn = 0; rad_op anorm = 0, qp = 0, kp = 0, vp = 0, gp = 0, rq = 0, rk = 0, store = 0, attn = 0;
rad_op sigmoid = 0, gate_heads = 0, op = 0, widen_attn = 0, reduce_attn = 0, add_attn = 0; rad_op sigmoid = 0, gate_heads = 0, op = 0, widen_attn = 0, reduce_attn = 0, add_attn = 0;
rad_op fnorm = 0, gup = 0, act = 0, dp = 0, widen_ffn = 0, reduce_ffn = 0, add_ffn = 0; rad_op fnorm = 0, gup = 0, act = 0, dp = 0, widen_ffn = 0, reduce_ffn = 0, add_ffn = 0;
CalibTap tap_in{}, tap_o{}, tap_gu{}, tap_down{};
}; };
struct Model { struct Model {
@@ -40,6 +42,9 @@ struct Model {
rad_weight tok = 0, norm = 0, head = 0; rad_weight tok = 0, norm = 0, head = 0;
rad_op embed = 0, widen = 0, reduce_embed = 0, final_norm = 0, gather = 0, logits_op = 0; rad_op embed = 0, widen = 0, reduce_embed = 0, final_norm = 0, gather = 0, logits_op = 0;
std::vector<Layer> layers; std::vector<Layer> layers;
bool tap_live = false;
long long calib_rows = 0;
int64_t calib_lo = 0, calib_hi = 0;
}; };
static Model models[MAX_RANKS]; static Model models[MAX_RANKS];
@@ -163,6 +168,16 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
} }
std::vector<bool> local; std::vector<bool> local;
RAD_ARCH_TRY(schedule(meta, g.n_layer, local)); RAD_ARCH_TRY(schedule(meta, g.n_layer, local));
if (calib_dir()) {
if (g.world != 1) {
fprintf(stderr, "radiance: spark25 calibration requires one rank so column-split "
"Grams retain their cross terms\n");
return RAD_E_UNSUPPORTED;
}
RAD_ARCH_TRY(calib_layers("spark25", "RADIANCE_SPARK_CALIB_LAYERS", g.n_layer,
&m.calib_lo, &m.calib_hi));
m.tap_live = true;
}
const int64_t window = rad_meta_geti(meta, "sliding_window", 0); const int64_t window = rad_meta_geti(meta, "sliding_window", 0);
if (window <= 0) { if (window <= 0) {
fprintf(stderr, "radiance: spark25: a positive sliding_window is required\n"); fprintf(stderr, "radiance: spark25: a positive sliding_window is required\n");
@@ -366,6 +381,12 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
} }
a.widen_ffn = widen(m.delta); a.widen_ffn = widen(m.delta);
a.add_ffn = add(); a.add_ffn = add();
if (m.tap_live && l >= m.calib_lo && l < m.calib_hi) {
RAD_ARCH_TRY(a.tap_in.declare(b, nm, T, nm.f("blk.%d.attn_in", l), m.h, E));
RAD_ARCH_TRY(a.tap_o.declare(b, nm, T, nm.f("blk.%d.attn_o", l), m.attn, Q));
RAD_ARCH_TRY(a.tap_gu.declare(b, nm, T, nm.f("blk.%d.ffn_in", l), m.h, E));
RAD_ARCH_TRY(a.tap_down.declare(b, nm, T, nm.f("blk.%d.ffn_down_in", l), m.ff, F));
}
} }
m.final_norm = norm(m.norm, m.x, m.h); m.final_norm = norm(m.norm, m.x, m.h);
m.gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows), m.gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
@@ -382,7 +403,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
} }
static void step(RadCtx* c, const RadBatch* batch) { static void step(RadCtx* c, const RadBatch* batch) {
const Model& m = models[rad_rank(c)]; Model& m = models[rad_rank(c)];
const Geom& g = m.g; const Geom& g = m.g;
const int64_t T = batch->n_tok; const int64_t T = batch->n_tok;
const RadOperand pos = praw(batch->positions, RAD_I32, T); const RadOperand pos = praw(batch->positions, RAD_I32, T);
@@ -400,6 +421,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
RAD_ISSUE(c, a.kp, brows(m.h, T), RAD_W(a.k), brows(m.k, T)); RAD_ISSUE(c, a.kp, brows(m.h, T), RAD_W(a.k), brows(m.k, T));
RAD_ISSUE(c, a.vp, brows(m.h, T), RAD_W(a.v), brows(m.v, T)); RAD_ISSUE(c, a.vp, brows(m.h, T), RAD_W(a.v), brows(m.v, T));
RAD_ISSUE(c, a.gp, brows(m.h, T), RAD_W(a.gate), brows(m.gate, T)); RAD_ISSUE(c, a.gp, brows(m.h, T), RAD_W(a.gate), brows(m.gate, T));
a.tap_in.step(c, m.h, T, m.tap_live);
RAD_ISSUE(c, a.rq, brows(m.q, T), pos); RAD_ISSUE(c, a.rq, brows(m.q, T), pos);
RAD_ISSUE(c, a.rk, brows(m.k, T), pos); RAD_ISSUE(c, a.rk, brows(m.k, T), pos);
RAD_ISSUE(c, a.store, brows(m.k, T), brows(m.v, T), praw(slot, RAD_I32, T), RAD_ISSUE(c, a.store, brows(m.k, T), brows(m.v, T), praw(slot, RAD_I32, T),
@@ -412,13 +434,16 @@ static void step(RadCtx* c, const RadBatch* batch) {
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, m.attn), RAD_BF16, T * g.n_head, g.head_dim); const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, m.attn), RAD_BF16, T * g.n_head, g.head_dim);
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, m.gate), RAD_BF16, T * g.n_head, 1); const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, m.gate), RAD_BF16, T * g.n_head, 1);
RAD_ISSUE_N(c, a.gate_heads, T * g.n_head, heads, gates, RAD_NONE, heads); RAD_ISSUE_N(c, a.gate_heads, T * g.n_head, heads, gates, RAD_NONE, heads);
a.tap_o.step(c, m.attn, T, m.tap_live);
RAD_ISSUE(c, a.op, brows(m.attn, T), RAD_W(a.o), brows(m.h, T)); RAD_ISSUE(c, a.op, brows(m.attn, T), RAD_W(a.o), brows(m.h, T));
if (a.reduce_attn) RAD_ISSUE_N(c, a.reduce_attn, T * g.n_embd, brows(m.h, T), RAD_NONE); if (a.reduce_attn) RAD_ISSUE_N(c, a.reduce_attn, T * g.n_embd, brows(m.h, T), RAD_NONE);
RAD_ISSUE(c, a.widen_attn, brows(m.h, T), brows(m.delta, T)); RAD_ISSUE(c, a.widen_attn, brows(m.h, T), brows(m.delta, T));
RAD_ISSUE(c, a.add_attn, brows(m.x, T), brows(m.delta, T), brows(m.x, T)); RAD_ISSUE(c, a.add_attn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
RAD_ISSUE(c, a.fnorm, brows(m.x, T), RAD_W(a.fn), brows(m.h, T)); RAD_ISSUE(c, a.fnorm, brows(m.x, T), RAD_W(a.fn), brows(m.h, T));
RAD_ISSUE(c, a.gup, brows(m.h, T), RAD_W(a.gu), brows(m.gu, T)); RAD_ISSUE(c, a.gup, brows(m.h, T), RAD_W(a.gu), brows(m.gu, T));
a.tap_gu.step(c, m.h, T, m.tap_live);
RAD_ISSUE(c, a.act, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, g.n_ff, g.n_ff, T), brows(m.ff, T)); RAD_ISSUE(c, a.act, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, g.n_ff, g.n_ff, T), brows(m.ff, T));
a.tap_down.step(c, m.ff, T, m.tap_live);
RAD_ISSUE(c, a.dp, brows(m.ff, T), RAD_W(a.down), brows(m.h, T)); RAD_ISSUE(c, a.dp, brows(m.ff, T), RAD_W(a.down), brows(m.h, T));
if (a.reduce_ffn) RAD_ISSUE_N(c, a.reduce_ffn, T * g.n_embd, brows(m.h, T), RAD_NONE); if (a.reduce_ffn) RAD_ISSUE_N(c, a.reduce_ffn, T * g.n_embd, brows(m.h, T), RAD_NONE);
RAD_ISSUE(c, a.widen_ffn, brows(m.h, T), brows(m.delta, T)); RAD_ISSUE(c, a.widen_ffn, brows(m.h, T), brows(m.delta, T));
@@ -431,6 +456,31 @@ static void step(RadCtx* c, const RadBatch* batch) {
RAD_ISSUE_N(c, m.logits_op, batch->n_out, brows(m.hout, batch->n_out), RAD_W(m.head), RAD_ISSUE_N(c, m.logits_op, batch->n_out, brows(m.hout, batch->n_out), RAD_W(m.head),
brows(m.logits, batch->n_out)); brows(m.logits, batch->n_out));
} }
if (m.tap_live) {
m.calib_rows += T;
if (m.calib_rows >= calib_target()) {
bool ok = true;
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
const Layer& a = m.layers[(size_t)l];
char stem[96];
for (const char* proj : {"attn_q", "attn_k", "attn_v"}) {
std::snprintf(stem, sizeof stem, "blk.%lld.%s", (long long)l, proj);
ok = calib_write(c, a.tap_in.h, a.tap_in.K, m.calib_rows, stem, 0) && ok;
}
std::snprintf(stem, sizeof stem, "blk.%lld.attn_output", (long long)l);
ok = calib_write(c, a.tap_o.h, a.tap_o.K, m.calib_rows, stem, 0) && ok;
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_gate_up", (long long)l);
ok = calib_write(c, a.tap_gu.h, a.tap_gu.K, m.calib_rows, stem, 0) && ok;
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_down", (long long)l);
ok = calib_write(c, a.tap_down.h, a.tap_down.K, m.calib_rows, stem, 0) && ok;
}
m.tap_live = false;
std::fprintf(stderr, "radiance: spark25 rank %d wrote calibration Grams for layers "
"%lld:%lld after %lld tokens to %s%s\n", rad_rank(c),
(long long)m.calib_lo, (long long)m.calib_hi, m.calib_rows, calib_dir(),
ok ? "" : ", with errors");
}
}
} }
#ifdef SPARK25_HAVE_PREFILL_SPLIT #ifdef SPARK25_HAVE_PREFILL_SPLIT
+9
View File
@@ -0,0 +1,9 @@
# Built in tree or against an installed radiance.
if(NOT COMMAND rad_add_plugin)
cmake_minimum_required(VERSION 3.21)
project(spark25_w8a8 LANGUAGES CXX)
find_package(radiance REQUIRED)
rad_plugin_defaults()
endif()
rad_add_plugin(spark25_w8a8 architectures SOURCES ${CMAKE_CURRENT_SOURCE_DIR}/spark25_w8a8.cpp)
+546
View File
@@ -0,0 +1,546 @@
/* Spark X2.6 (Spark2_5ForCausalLM), rotated int8 weights and activations.
*
* The checkpoint has one [q | k | v] projection per layer. Conversion splits its rows into
* contiguous matrices because paged attention needs a contiguous query. The MLP's two matrices
* are concatenated as [gate | up]; act_mul with exact erf GELU matches the reference, unlike
* gelu_mul (which is the tanh approximation). The attention gate is one sigmoid per head, not
* per channel. Local and full layers have different NeoX rotary dimensions and theta values.
*
* Tensor parallelism splits attention by whole KV groups, replicating KV heads when ranks
* outnumber them. As in the HF reference, residuals accumulate in f32; rmsnorm reads that stream
* and writes bf16 for the linear projections.
*/
#include <arch/rad_arch.h>
#include <arch/rad_fp8.h>
#include "../spark25_bf16/chat.h"
#include <algorithm>
#include <cmath>
#include <sstream>
#include <string>
#include <vector>
namespace spark25_w8a8 {
using namespace rad::arch;
struct Layer {
rad_kvgroup kv = 0;
rad_weight an = 0, gate = 0, fn = 0;
LinearFP8 q{}, k{}, v{}, o{}, gu{}, down{};
rad_op anorm = 0, gp = 0, rq = 0, rk = 0, store = 0, attn = 0;
rad_op sigmoid = 0, gate_heads = 0, widen_attn = 0, reduce_attn = 0, add_attn = 0;
rad_op fnorm = 0, act = 0, widen_ffn = 0, reduce_ffn = 0, add_ffn = 0;
CalibTap tap_in{}, tap_o{}, tap_gu{}, tap_down{};
};
struct Model {
Names nm{""};
Geom g{};
rad_kvgroup kv = 0;
rad_buf x = 0, delta = 0, h = 0, q = 0, k = 0, v = 0, gate = 0, attn = 0, gu = 0, ff = 0;
rad_buf hout = 0, logits = 0;
ActFP8 a_h{}, a_attn{}, a_ff{};
rad_weight tok = 0, norm = 0, head = 0;
rad_op embed = 0, widen = 0, reduce_embed = 0, had = 0, final_norm = 0, gather = 0, logits_op = 0;
std::vector<Layer> layers;
bool tap_live = false;
long long calib_rows = 0;
int64_t calib_lo = 0, calib_hi = 0;
};
static Model models[MAX_RANKS];
/* The HF config names every layer. Do not infer a periodic schedule: it changes the mask and
* rotary of a layer and would silently produce a different model. */
static int schedule(const RadModelMeta* meta, int64_t n, std::vector<bool>& local) {
const char* s = rad_meta_gets(meta, "layer_types", nullptr);
if (!s) {
fprintf(stderr, "radiance: spark25: layer_types is required\n");
return RAD_E_INVAL;
}
std::istringstream in(s);
std::string word;
while (in >> word) {
if (word != "sliding_attention" && word != "full_attention") {
fprintf(stderr, "radiance: spark25: unknown layer type '%s'\n", word.c_str());
return RAD_E_UNSUPPORTED;
}
local.push_back(word == "sliding_attention");
}
if ((int64_t)local.size() != n) {
fprintf(stderr, "radiance: spark25: layer_types has %zu entries for %lld layers\n",
local.size(), (long long)n);
return RAD_E_INVAL;
}
return RAD_OK;
}
struct Span {
int64_t first = 0, count = 0;
};
/* Remainder-first contiguous slices, in whole units. */
static Span split(int64_t n, int parts, int rank) {
const int64_t base = n / parts, rem = n % parts;
return {base * rank + std::min<int64_t>(rank, rem), base + (rank < rem ? 1 : 0)};
}
struct Shards {
Span q, kv, ff; /* q and kv in heads; ff in channels */
};
/* A rank's attention heads must describe whole GQA groups, or a slice of a single group with
* that group's KV head replicated. This also covers non-divisible worlds such as 3 ranks over
* the checkpoint's 4 KV heads. Projection and FFN spans below give the loader those exact cuts. */
static int shard_geometry(Geom& g, const RadBuildCtx* ctx, Shards& s) {
g.world = ctx->world_size > 0 ? ctx->world_size : 1;
g.rank = ctx->rank;
if (g.rank >= g.world || g.world > g.n_head_all || g.n_head_kv_all <= 0 ||
g.n_head_all % g.n_head_kv_all || g.world > g.n_ff_all) {
fprintf(stderr, "radiance: spark25: cannot shard %lld query heads, %lld KV heads and "
"%lld FFN channels over %d ranks\n", (long long)g.n_head_all,
(long long)g.n_head_kv_all, (long long)g.n_ff_all, g.world);
return RAD_E_INVAL;
}
const int64_t group = g.n_head_all / g.n_head_kv_all;
if (g.world <= g.n_head_kv_all) {
s.kv = split(g.n_head_kv_all, g.world, g.rank);
s.q = {s.kv.first * group, s.kv.count * group};
} else {
int first_rank = 0;
for (int64_t k = 0; k < g.n_head_kv_all; ++k) {
const int n = (int)split(g.world, (int)g.n_head_kv_all, (int)k).count;
if (g.rank < first_rank + n) {
const Span q = split(group, n, g.rank - first_rank);
s.kv = {k, 1};
s.q = {k * group + q.first, q.count};
break;
}
first_rank += n;
}
}
/* Prefer whole 128-channel blocks for a ragged split, keeping device GEMMs aligned. */
const int64_t unit = g.n_ff_all % 128 == 0 && g.n_ff_all / 128 >= g.world ? 128 : 1;
s.ff = split(g.n_ff_all / unit, g.world, g.rank);
s.ff.first *= unit;
s.ff.count *= unit;
g.n_head = s.q.count;
g.n_head_kv = s.kv.count;
g.n_ff = s.ff.count;
g.n_vocab = shard_extent(g.n_vocab_all, g.world, g.rank);
g.vocab_off = shard_begin(g.n_vocab_all, g.world, g.rank);
return g.n_head > 0 && g.n_head_kv > 0 && g.n_ff > 0 && g.n_vocab > 0 ? RAD_OK : RAD_E_INVAL;
}
static bool needs_span(const Span& s, int64_t total, const Geom& g) {
return total % g.world != 0 || s.first != g.rank * (total / g.world) ||
s.count != total / g.world;
}
static int check_format(const RadModelMeta* meta) {
const char* method = rad_meta_gets(meta, "quantization_config.quant_method", nullptr);
const char* fmt = rad_meta_gets(meta, "quantization_config.fmt", nullptr);
if (!method || std::strcmp(method, "w8a8") != 0 || !fmt || std::strcmp(fmt, "fwht128") != 0) {
fprintf(stderr, "radiance: spark25_w8a8 serves a rotated int8 trunk (quant_method "
"'w8a8', fmt 'fwht128'); this container says '%s' / '%s'\n",
method ? method : "(none)", fmt ? fmt : "(none)");
return RAD_E_UNSUPPORTED;
}
return RAD_OK;
}
static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
RAD_ARCH_TRY(check_format(meta));
Model& m = models[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
/* geom_from's even-only split cannot express a ragged GQA/FFN world. Read the whole geometry,
* then give each rank a group-preserving shard and state its spans on the weights. */
RadBuildCtx whole = *ctx;
whole.rank = 0;
whole.world_size = 1;
RAD_ARCH_TRY(geom_from(m.g, meta, &whole, "bf16", RAD_BF16));
Geom& g = m.g;
Shards shards;
RAD_ARCH_TRY(shard_geometry(g, ctx, shards));
/* A column-sharded int8 linear slices its input's scale groups, so every rank's
* feed-forward span must be whole 128-column groups. shard_geometry prefers whole blocks
* even for ragged worlds such as TP=3; refuse a geometry that cannot be split that way. */
if (g.world > 1 && shards.ff.count % RAD_FP8_BLOCK) {
fprintf(stderr, "radiance: spark25_w8a8 cannot shard %lld FFN channels over %d ranks: a "
"rank's %lld are not whole %d-column scale groups. An int8 down projection "
"sliced inside a group would read its scale plane at the wrong width\n",
(long long)g.n_ff_all, g.world, (long long)shards.ff.count, RAD_FP8_BLOCK);
return RAD_E_UNSUPPORTED;
}
Names& nm = m.nm;
if (g.n_head_kv <= 0 || g.n_head % g.n_head_kv || g.head_dim % 2 || meta->n_expert ||
rad_meta_geti(meta, "attention_bias", 0) || rad_meta_geti(meta, "mlp_bias", 0) ||
!rad_meta_geti(meta, "tie_word_embeddings", 0) ||
!rad_meta_geti(meta, "headwise_attn_output_gate", 0) ||
std::strcmp(rad_meta_gets(meta, "gate_attn_act_mode", "sigmoid"), "sigmoid") ||
std::strcmp(rad_meta_gets(meta, "hidden_act", "gelu"), "gelu")) {
fprintf(stderr, "radiance: spark25: requires a dense, bias-free, tied model with headwise "
"sigmoid gates, exact GELU and divisible attention heads\n");
return RAD_E_UNSUPPORTED;
}
/* A single global override cannot describe this model's two rotary ladders. */
RAD_ARCH_TRY(yarn_from(g, meta, "", g.head_dim));
if (g.yarn.factor != 0.0f || g.rope_scale != 1.0f || g.rope_mc) {
fprintf(stderr, "radiance: spark25: rotary scaling overrides are not supported\n");
return RAD_E_UNSUPPORTED;
}
std::vector<bool> local;
RAD_ARCH_TRY(schedule(meta, g.n_layer, local));
if (calib_dir()) {
if (g.world != 1) {
fprintf(stderr, "radiance: spark25 calibration requires one rank so column-split "
"Grams retain their cross terms\n");
return RAD_E_UNSUPPORTED;
}
RAD_ARCH_TRY(calib_layers("spark25", "RADIANCE_SPARK_CALIB_LAYERS", g.n_layer,
&m.calib_lo, &m.calib_hi));
m.tap_live = true;
}
const int64_t window = rad_meta_geti(meta, "sliding_window", 0);
if (window <= 0) {
fprintf(stderr, "radiance: spark25: a positive sliding_window is required\n");
return RAD_E_INVAL;
}
double theta[2]{};
int64_t rot[2]{};
const char* kinds[] = {"full_attention", "sliding_attention"};
for (int j = 0; j < 2; ++j) {
theta[j] = rad_meta_getf(meta, nm.f("rope_parameters.%s.rope_theta", kinds[j]), 10000.0);
const double factor = rad_meta_getf(meta,
nm.f("rope_parameters.%s.partial_rotary_factor", kinds[j]), 1.0);
const char* type = rad_meta_gets(meta, nm.f("rope_parameters.%s.rope_type", kinds[j]), "default");
if (std::strcmp(type, "default")) {
fprintf(stderr, "radiance: spark25: %s rotary type '%s' is not supported\n", kinds[j], type);
return RAD_E_UNSUPPORTED;
}
const double r = g.head_dim * factor;
if (!std::isfinite(theta[j]) || !(theta[j] > 0) || !(factor > 0 && factor <= 1) || !std::isfinite(r) ||
std::floor(r) != r || (int64_t)r % 2) {
fprintf(stderr, "radiance: spark25: invalid %s rotary theta %g or factor %g\n",
kinds[j], theta[j], factor);
return RAD_E_INVAL;
}
rot[j] = (int64_t)r;
}
/* A full cache for both kinds keeps prefix caching valid. The local attention op enforces
* its own window (q - k < window); the full layers read all past positions. */
RadKVGroupDecl kd{};
kd.kind = RAD_KV_FULL;
kd.dtype = rad_kv_cache_dtype(ctx, RAD_BF16);
kd.n_head_kv = g.n_head_kv;
kd.head_dim = g.head_dim;
m.kv = rad_decl_kv_group(b, nm.f("kv_attn"), &kd);
if (!m.kv) return RAD_E_INVAL;
g.kv_dtype = rad_dtype_name(kd.dtype);
const int64_t T = g.max_tok, E = g.n_embd, Q = g.q_dim(), K = g.kv_dim(), F = g.n_ff;
m.x = decl_b(b, nm.f("x"), RAD_F32, {T, E});
m.delta = decl_b(b, nm.f("delta"), RAD_F32, {T, E});
m.h = decl_b(b, nm.f("h"), RAD_BF16, {T, E});
m.q = decl_b(b, nm.f("q"), RAD_BF16, {T, Q});
m.k = decl_b(b, nm.f("k"), RAD_BF16, {T, K});
m.v = decl_b(b, nm.f("v"), RAD_BF16, {T, K});
m.gate = decl_b(b, nm.f("gate"), RAD_BF16, {T, g.n_head});
m.attn = decl_b(b, nm.f("attn"), RAD_BF16, {T, Q});
m.gu = decl_b(b, nm.f("gate_up"), RAD_BF16, {T, 2 * F});
m.ff = decl_b(b, nm.f("ff"), RAD_BF16, {T, F});
m.hout = decl_b(b, nm.f("h_out"), RAD_BF16, {g.max_logit_rows, E});
m.logits = decl_b(b, nm.f("logits"), RAD_F32, {g.max_logit_rows, g.n_vocab});
if (!m.x || !m.delta || !m.h || !m.q || !m.k || !m.v || !m.gate || !m.attn || !m.gu || !m.ff ||
!m.hout || !m.logits) return RAD_E_INVAL;
m.a_h.x = m.h;
RAD_ARCH_TRY(m.a_h.declare_qs(b, nm, g, "h", E, 0, true, false));
m.a_h.q8_fed = true;
m.a_h.q8_rot = true;
m.a_attn.x = m.attn;
RAD_ARCH_TRY(m.a_attn.declare_qs(b, nm, g, "attn_out", Q, 0, true, false));
m.a_ff.x = m.ff;
RAD_ARCH_TRY(m.a_ff.declare_qs(b, nm, g, "ff", F, 0, true, false));
m.had = rw(b, RAD_OP(b, "had_quant_act_i8g",
RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E), RAD_INT("group", RAD_FP8_BLOCK),
RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS),
{m.h}, {m.a_h.q8, m.a_h.s8});
if (!m.had) return RAD_E_INVAL;
RAD_ARCH_TRY(rad_declare_logits(b, m.logits));
auto weight = [&](const char* name, const char* src, uint32_t dt,
std::initializer_list<int64_t> shape, RadWeightGroup group,
int access = RAD_ACCESS_PER_TOKEN, int shard = RAD_SHARD_NONE) {
if (map_copy(b, name, src) != RAD_OK) return (rad_weight)0;
return decl_w(b, name, dt, shape, access, shard, group);
};
m.tok = weight(nm.f("token_embd.weight"), nm.ckpt("model.embedding.weight"), RAD_BF16,
{g.n_vocab, E}, grp_model(), RAD_ACCESS_VOCAB, RAD_SHARD_ROW);
/* The head is the tied table again, at whatever the container holds it: bf16 as shipped, or
* the int8 grid where the recipe quantised it, which is the widest GEMM a decode step runs. */
if (map_copy(b, nm.f("output.weight"), nm.ckpt("model.embedding.weight")) != RAD_OK)
return RAD_E_INVAL;
m.head = decl_w(b, nm.f("output.weight"),
weight_codes_dtype(b, nm.f("output.weight"), RAD_BF16),
{g.n_vocab, E}, RAD_ACCESS_VOCAB, RAD_SHARD_ROW, grp_model());
m.norm = weight(nm.f("output_norm.weight"), nm.ckpt("model.norm.weight"), RAD_F32,
{E}, grp_model());
if (!m.tok || !m.head || !m.norm) return RAD_E_INVAL;
if (g.world > 1 && g.n_vocab_all % g.world) {
RAD_ARCH_TRY(rad_weight_shard_span(b, m.tok, g.vocab_off, g.vocab_off + g.n_vocab));
RAD_ARCH_TRY(rad_weight_shard_span(b, m.head, g.vocab_off, g.vocab_off + g.n_vocab));
}
auto norm = [&](rad_weight w, rad_buf x, rad_buf y) {
return rw(b, RAD_OP(b, "rmsnorm", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_F64("eps", g.eps), RAD_F64("wadd", 0.0), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(w)), {x}, {y});
};
auto gemm = [&](int64_t n, int64_t k, rad_weight w, rad_buf x, rad_buf y) {
return rw(b, RAD_OP(b, "gemm_nt", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("N", n),
RAD_INT("K", k), RAD_STR("dtype", "bf16")), RAD_WEIGHTS(w)), {x}, {y});
};
auto add = [&]() {
return rw(b, RAD_OP(b, "add", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_STR("dtype", "f32")), RAD_NOWEIGHTS), {m.x, m.delta}, {m.x});
};
m.embed = rw(b, RAD_OP(b, "embed_lookup", RAD_PARAMS(RAD_RANGE("M", 1, T),
RAD_INT("n_embd", E), RAD_INT("n_vocab", g.n_vocab), RAD_STR("dtype", "bf16"),
RAD_INT("vocab_offset", g.vocab_off)), RAD_WEIGHTS(m.tok)), {}, {m.h});
auto widen = [&](rad_buf output) {
return rw(b, RAD_OP(b, "cast", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", E),
RAD_STR("from", "bf16"), RAD_STR("to", "f32")), RAD_NOWEIGHTS), {m.h}, {output});
};
m.widen = widen(m.x);
/* Embedding shards contribute disjoint rows, so their widened sum is exact. Projection
* shards must instead reduce in bf16, rounding the merged output before it is widened and
* added to the f32 residual, as in the reference's BF16 linear layers. */
auto reduce = [&](rad_buf x, const char* dtype) {
if (g.world <= 1) return (rad_op)0;
return rw(b, RAD_OP(b, "all_reduce", RAD_PARAMS(RAD_INT("world_size", g.world),
RAD_RANGE("numel", E, T * E), RAD_STR("dtype", dtype), RAD_INT("exact", 1)),
RAD_NOWEIGHTS), {x}, {x});
};
m.reduce_embed = reduce(m.x, "fp32");
if (g.world > 1 && !m.reduce_embed) {
fprintf(stderr, "radiance: spark25_w8a8 requires an exact fp32 all-reduce for TP=%d\n", g.world);
return RAD_E_UNSUPPORTED;
}
m.layers.resize((size_t)g.n_layer);
for (int l = 0; l < g.n_layer; ++l) {
Layer& a = m.layers[(size_t)l];
auto src = [&](const char* suffix) { return nm.ckpt("model.layers.%d.%s", l, suffix); };
auto w = [&](const char* suffix, const char* s, uint32_t dt,
std::initializer_list<int64_t> shape, int shard = RAD_SHARD_NONE) {
return weight(nm.f("blk.%d.%s", l, suffix), src(s), dt, shape, grp_layer(l),
RAD_ACCESS_PER_TOKEN, shard);
};
a.an = w("attn_norm.weight", "input_layernorm.weight", RAD_F32, {E});
a.gate = w("attn_gate.weight", "self_attn.g_proj.weight", RAD_BF16, {g.n_head, E}, RAD_SHARD_ROW);
a.fn = w("ffn_norm.weight", "post_attention_layernorm.weight", RAD_F32, {E});
const char* qkv = src("self_attn.q_k_v_proj.weight");
const int64_t qall = g.n_head_all * g.head_dim, kall = g.n_head_kv_all * g.head_dim;
const int64_t qlo = needs_span(shards.q, g.n_head_all, g) ? shards.q.first * g.head_dim : 0;
const int64_t qhi = needs_span(shards.q, g.n_head_all, g)
? (shards.q.first + shards.q.count) * g.head_dim : 0;
const int64_t kvlo = needs_span(shards.kv, g.n_head_kv_all, g)
? shards.kv.first * g.head_dim : 0;
const int64_t kvhi = needs_span(shards.kv, g.n_head_kv_all, g)
? (shards.kv.first + shards.kv.count) * g.head_dim : 0;
auto map_part = [&](const char* name, int64_t first, int64_t rows) {
const char* target = nm.f("blk.%d.attn_%s.weight", l, name);
return map_rows(b, target, {{qkv, (int)first, rows}});
};
const char* qb = nm.f("blk.%d.attn_q", l);
const char* kb = nm.f("blk.%d.attn_k", l);
const char* vb = nm.f("blk.%d.attn_v", l);
RAD_ARCH_TRY(map_part("q", 0, qall));
RAD_ARCH_TRY(map_part("k", qall, kall));
RAD_ARCH_TRY(map_part("v", qall + kall, kall));
a.q.mapped = a.k.mapped = a.v.mapped = true;
RAD_ARCH_TRY(a.q.declare(b, nm, g, qb, Q, E, RAD_SHARD_ROW, grp_layer(l), {qkv},
m.a_h, m.q, 0, {}, qlo, qhi));
RAD_ARCH_TRY(a.k.declare(b, nm, g, kb, K, E, RAD_SHARD_ROW, grp_layer(l), {qkv},
m.a_h, m.k, 0, {}, kvlo, kvhi));
RAD_ARCH_TRY(a.v.declare(b, nm, g, vb, K, E, RAD_SHARD_ROW, grp_layer(l), {qkv},
m.a_h, m.v, 0, {}, kvlo, kvhi));
const int64_t olo = qlo, ohi = qhi;
RAD_ARCH_TRY(a.o.declare(b, nm, g, nm.f("blk.%d.attn_output", l), E, Q,
RAD_SHARD_COL, grp_layer(l), {src("self_attn.out_proj.weight")},
m.a_attn, m.h, 0, {}, olo, ohi));
RAD_ARCH_TRY(a.gu.declare(b, nm, g, nm.f("blk.%d.ffn_gate_up", l), 2 * F, E,
RAD_SHARD_ROW, grp_layer(l),
{src("mlp.gate_proj.weight"), src("mlp.up_proj.weight")},
m.a_h, m.gu, 0, {F, F}));
const int64_t flo = needs_span(shards.ff, g.n_ff_all, g) ? shards.ff.first : 0;
const int64_t fhi = needs_span(shards.ff, g.n_ff_all, g)
? shards.ff.first + shards.ff.count : 0;
if (needs_span(shards.ff, g.n_ff_all, g)) {
const int64_t lo[2] = {shards.ff.first, shards.ff.first};
const int64_t hi[2] = {shards.ff.first + shards.ff.count,
shards.ff.first + shards.ff.count};
const int64_t total[2] = {g.n_ff_all, g.n_ff_all};
RAD_ARCH_TRY(a.gu.span_parts(b, lo, hi, total, 2));
}
RAD_ARCH_TRY(a.down.declare(b, nm, g, nm.f("blk.%d.ffn_down", l), E, F,
RAD_SHARD_COL, grp_layer(l), {src("mlp.down_proj.weight")},
m.a_ff, m.h, 0, {}, flo, fhi));
if (!a.an || !a.gate || !a.fn || !a.q.w || !a.k.w || !a.v.w || !a.o.w ||
!a.gu.w || !a.down.w) return RAD_E_INVAL;
if (g.world > 1 && needs_span(shards.q, g.n_head_all, g))
RAD_ARCH_TRY(rad_weight_shard_span(b, a.gate, shards.q.first,
shards.q.first + shards.q.count));
a.kv = m.kv;
RAD_ARCH_TRY(rad_bind_layer_kv(b, l, a.kv));
a.anorm = norm(a.an, m.x, m.h);
a.gp = gemm(g.n_head, E, a.gate, m.h, m.gate);
Geom rope = g;
const int kind = local[(size_t)l] ? 1 : 0;
rope.theta = (float)theta[kind];
a.rq = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head, 0, rot[kind], "neox"), {m.q}, {m.q});
a.rk = rw(b, decl_rope(b, rope, T, g.head_dim, g.n_head_kv, 0, rot[kind], "neox"), {m.k}, {m.k});
a.attn = rw(b, decl_attn(b, g, "attn_paged",
RAD_PARAMS(RAD_RANGE("q_len", 1, T), RAD_INT("head_dim", g.head_dim),
RAD_INT("gqa", g.gqa()), RAD_INT("causal", 1), RAD_INT("window", kind ? window : 0),
RAD_INT("n_head", g.n_head), RAD_INT("block_size", RAD_KV_BLOCK),
RAD_INT("max_seqs", g.max_seqs), RAD_INT("max_ctx", g.max_ctx),
RAD_STR("q_dtype", "bf16"), RAD_STR("kv_dtype", g.kv_dtype)), RAD_NOWEIGHTS),
{m.q}, {m.attn});
a.store = rw(b, RAD_OP(b, "kv_store", RAD_PARAMS(RAD_RANGE("M", 1, T),
RAD_INT("head_dim", g.head_dim), RAD_INT("n_head_kv", g.n_head_kv),
RAD_INT("block_size", rad_kv_block_size(b, a.kv)), RAD_STR("kv_dtype", g.kv_dtype)),
RAD_NOWEIGHTS), {m.k, m.v}, {});
a.sigmoid = rw(b, RAD_OP(b, "sigmoid", RAD_PARAMS(RAD_RANGE("M", 1, T),
RAD_INT("n", g.n_head), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gate}, {m.gate});
/* View dense [tokens, heads * dim] and [tokens, heads] as one row per head. */
a.gate_heads = rw(b, RAD_OP(b, "scale_rows", RAD_PARAMS(RAD_RANGE("M", 1, T * g.n_head),
RAD_INT("n", g.head_dim), RAD_STR("act", "none"), RAD_STR("dtype", "bf16")),
RAD_NOWEIGHTS), {m.attn, m.gate}, {m.attn});
a.reduce_attn = reduce(m.h, "bf16");
a.widen_attn = widen(m.delta);
a.add_attn = add();
a.fnorm = norm(a.fn, m.x, m.h);
a.act = rw(b, RAD_OP(b, "act_mul", RAD_PARAMS(RAD_RANGE("M", 1, T), RAD_INT("n", F),
RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gu}, {m.ff});
a.reduce_ffn = reduce(m.h, "bf16");
if (g.world > 1 && (!a.reduce_attn || !a.reduce_ffn)) {
fprintf(stderr, "radiance: spark25_w8a8 requires exact bf16 all-reduces for TP=%d\n", g.world);
return RAD_E_UNSUPPORTED;
}
a.widen_ffn = widen(m.delta);
a.add_ffn = add();
if (m.tap_live && l >= m.calib_lo && l < m.calib_hi) {
RAD_ARCH_TRY(a.tap_in.declare(b, nm, T, nm.f("blk.%d.attn_in", l), m.h, E));
RAD_ARCH_TRY(a.tap_o.declare(b, nm, T, nm.f("blk.%d.attn_o", l), m.attn, Q));
RAD_ARCH_TRY(a.tap_gu.declare(b, nm, T, nm.f("blk.%d.ffn_in", l), m.h, E));
RAD_ARCH_TRY(a.tap_down.declare(b, nm, T, nm.f("blk.%d.ffn_down_in", l), m.ff, F));
}
}
m.final_norm = norm(m.norm, m.x, m.h);
m.gather = rw(b, RAD_OP(b, "gather_rows", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n", E), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.h}, {m.hout});
m.logits_op = rw(b, RAD_OP(b, "logits_gemm", RAD_PARAMS(RAD_RANGE("M", 1, g.max_logit_rows),
RAD_INT("n_vocab", g.n_vocab), RAD_INT("n_embd", E), RAD_STR("dtype", "bf16")),
RAD_WEIGHTS(m.head)), {m.hout}, {m.logits});
rad_note(b, "spark25 rank %d/%d: %lld layers, %lld query / %lld KV heads x %lld, "
"FFN %lld, vocab [%lld, %lld), local window %lld", g.rank, g.world,
(long long)g.n_layer, (long long)g.n_head, (long long)g.n_head_kv,
(long long)g.head_dim, (long long)g.n_ff, (long long)g.vocab_off,
(long long)(g.vocab_off + g.n_vocab), (long long)window);
return RAD_OK;
}
static void step(RadCtx* c, const RadBatch* batch) {
Model& m = models[rad_rank(c)];
const Geom& g = m.g;
const int64_t T = batch->n_tok;
const RadOperand pos = praw(batch->positions, RAD_I32, T);
RAD_ISSUE(c, m.embed, praw(batch->token_ids, RAD_I32, T), RAD_W(m.tok), brows(m.h, T));
RAD_ISSUE(c, m.widen, brows(m.h, T), brows(m.x, T));
if (m.reduce_embed) RAD_ISSUE_N(c, m.reduce_embed, T * g.n_embd, brows(m.x, T), RAD_NONE);
for (size_t i = 0; i < m.layers.size(); ++i) {
const Layer& a = m.layers[i];
const RadKVGroupBatch* kvb = kv_batch(batch, a.kv);
const int32_t* slot = kvb ? kvb->slot_mapping : nullptr;
const int32_t* table = kvb ? kvb->block_table : nullptr;
const int32_t* used = kvb ? kvb->seqused : nullptr;
RAD_ISSUE(c, a.anorm, brows(m.x, T), RAD_W(a.an), brows(m.h, T));
a.tap_in.step(c, m.h, T, m.tap_live);
RAD_ISSUE(c, m.had, brows(m.h, T), brows(m.a_h.q8, T), brows(m.a_h.s8, T));
a.q.step(c, m.a_h, m.q, T);
a.k.step(c, m.a_h, m.k, T);
a.v.step(c, m.a_h, m.v, T);
RAD_ISSUE(c, a.gp, brows(m.h, T), RAD_W(a.gate), brows(m.gate, T));
RAD_ISSUE(c, a.rq, brows(m.q, T), pos);
RAD_ISSUE(c, a.rk, brows(m.k, T), pos);
RAD_ISSUE(c, a.store, brows(m.k, T), brows(m.v, T), praw(slot, RAD_I32, T),
kv_cache(a.kv, (int)i));
RAD_ISSUE_N(c, a.attn, batch->max_q_len, brows(m.q, T), kv_cache(a.kv, (int)i),
praw2(table, RAD_I32, batch->n_seq, kvb ? kvb->block_table_pitch : 0),
praw(used, RAD_I32, batch->n_seq), RAD_NONE, RAD_NONE,
praw(batch->cu_seqlens, RAD_I32, batch->n_seq + 1), brows(m.attn, T));
RAD_ISSUE(c, a.sigmoid, brows(m.gate, T), brows(m.gate, T));
const RadOperand heads = RAD_P_T2(rad_buf_ptr(c, m.attn), RAD_BF16, T * g.n_head, g.head_dim);
const RadOperand gates = RAD_P_T2(rad_buf_ptr(c, m.gate), RAD_BF16, T * g.n_head, 1);
RAD_ISSUE_N(c, a.gate_heads, T * g.n_head, heads, gates, RAD_NONE, heads);
a.tap_o.step(c, m.attn, T, m.tap_live);
a.o.step(c, m.a_attn, m.h, T);
if (a.reduce_attn) RAD_ISSUE_N(c, a.reduce_attn, T * g.n_embd, brows(m.h, T), RAD_NONE);
RAD_ISSUE(c, a.widen_attn, brows(m.h, T), brows(m.delta, T));
RAD_ISSUE(c, a.add_attn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
RAD_ISSUE(c, a.fnorm, brows(m.x, T), RAD_W(a.fn), brows(m.h, T));
a.tap_gu.step(c, m.h, T, m.tap_live);
RAD_ISSUE(c, m.had, brows(m.h, T), brows(m.a_h.q8, T), brows(m.a_h.s8, T));
a.gu.step(c, m.a_h, m.gu, T);
RAD_ISSUE(c, a.act, bcol(m.gu, 0, g.n_ff, T), bcol(m.gu, g.n_ff, g.n_ff, T), brows(m.ff, T));
a.tap_down.step(c, m.ff, T, m.tap_live);
a.down.step(c, m.a_ff, m.h, T);
if (a.reduce_ffn) RAD_ISSUE_N(c, a.reduce_ffn, T * g.n_embd, brows(m.h, T), RAD_NONE);
RAD_ISSUE(c, a.widen_ffn, brows(m.h, T), brows(m.delta, T));
RAD_ISSUE(c, a.add_ffn, brows(m.x, T), brows(m.delta, T), brows(m.x, T));
}
RAD_ISSUE(c, m.final_norm, brows(m.x, T), RAD_W(m.norm), brows(m.h, T));
if (batch->n_out > 0) {
RAD_ISSUE_N(c, m.gather, batch->n_out, brows(m.h, T),
praw(batch->out_ids, RAD_I32, batch->n_out), brows(m.hout, batch->n_out));
RAD_ISSUE_N(c, m.logits_op, batch->n_out, brows(m.hout, batch->n_out), RAD_W(m.head),
brows(m.logits, batch->n_out));
}
if (m.tap_live) {
m.calib_rows += T;
if (m.calib_rows >= calib_target()) {
bool ok = true;
for (int64_t l = m.calib_lo; l < m.calib_hi; ++l) {
const Layer& a = m.layers[(size_t)l];
char stem[96];
for (const char* proj : {"attn_q", "attn_k", "attn_v"}) {
std::snprintf(stem, sizeof stem, "blk.%lld.%s", (long long)l, proj);
ok = calib_write(c, a.tap_in.h, a.tap_in.K, m.calib_rows, stem, 0) && ok;
}
std::snprintf(stem, sizeof stem, "blk.%lld.attn_output", (long long)l);
ok = calib_write(c, a.tap_o.h, a.tap_o.K, m.calib_rows, stem, 0) && ok;
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_gate_up", (long long)l);
ok = calib_write(c, a.tap_gu.h, a.tap_gu.K, m.calib_rows, stem, 0) && ok;
std::snprintf(stem, sizeof stem, "blk.%lld.ffn_down", (long long)l);
ok = calib_write(c, a.tap_down.h, a.tap_down.K, m.calib_rows, stem, 0) && ok;
}
m.tap_live = false;
std::fprintf(stderr, "radiance: spark25 rank %d wrote calibration Grams for layers "
"%lld:%lld after %lld tokens to %s%s\n", rad_rank(c),
(long long)m.calib_lo, (long long)m.calib_hi, m.calib_rows, calib_dir(),
ok ? "" : ", with errors");
}
}
}
static const RadChatFormat* chat_format(const RadModelMeta*) { return spark25_bf16::spark_chat_format(); }
}
#ifndef RAD_ARCH_NO_EXPORTS
RAD_ARCH_PLUGIN(spark25_w8a8, "spark25", "w8a8_fwht128", "0.1.0",
"Spark X2.6 with an int8 trunk: i8 weights with a bf16 scale a 128 of K, rotated "
"by a 128-wide Hadamard, against int8 activations the same rotation quantises")
RAD_ARCH_CHAT_FORMAT(spark25_w8a8)
#endif
+27
View File
@@ -0,0 +1,27 @@
# spark-x26-4b-iq8r.recipe -- Spark X2.6 4B (Spark2_5ForCausalLM) on IQ8R's rotated int8 grid.
# Every trunk linear rotated by fwht128 and fitted by GPTQ against the container's own calibration
# Hessians (RADGRAM2), an int8 code with a bf16 scale per [1 x 128] (docs/IQR.md). Served by
# arch/spark25_w8a8 at gemm_nt_q dtype i8a8h behind had_quant_act_i8g.
#
# The tap is arch/spark25_bf16's: serve the BF16 container with RADIANCE_CALIB_DIR set and push a
# corpus through prefill. The f32 [K,K] accumulators are 533 MB a layer, so calibrate a slice at a
# time -- RADIANCE_SPARK_CALIB_LAYERS=lo:hi, once per slice, same directory:
#
# RADIANCE_CALIB_DIR=$CALIB RADIANCE_CALIB_TOKENS=65536 RADIANCE_SPARK_CALIB_LAYERS=0:12 \
# radiance --model spark-x2.6-4b-radiance-bf16.rad ... # and drive prompts at max_tokens=1
#
# CALIB=$CALIB rad-convert <XHToken-Spark-X2.6-4B> --recipe data/recipes/spark-x26-4b-iq8r.recipe \
# --set quantization_config.quant_method=w8a8 --set quantization_config.fmt=fwht128 \
# -o spark-x2.6-4b-radiance-iq8r.rad
#
# Left unquantised, as arch/spark25_w8a8 declares them: the two norms a layer, the head's norm, the
# embedding (which `blk.*.attn_gate.weight`-sized bf16 aside, the tied table the gather reads) and
# the 16-row attention gate projection, which is 41k parameters and serves a sigmoid per head.
blk.*.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.*.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.*.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.*.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.*.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.*.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym rule=search
+29 -5
View File
@@ -112,11 +112,35 @@ otherwise it fails with `RAD_E_UNSUPPORTED` rather than running rank-local parti
serves these collectives at 2, 3, 4 and 8 ranks; other widths resolve only on a library with a serves these collectives at 2, 3, 4 and 8 ranks; other widths resolve only on a library with a
general `all_reduce` (libref), so a card deployment is limited to those worlds. general `all_reduce` (libref), so a card deployment is limited to those worlds.
The initial implementation serves BF16 with tied embeddings, headwise sigmoid gates and the Both plugins reject multi-rank declarations if a required exact collective cannot be resolved;
checkpoint's own rotary parameters. It does not implement DSpark, quantisation recipes, other gate otherwise a missing reduction would silently leave rank-local projections in the residual.
activations or rotary-scaling overrides. The tokenizer and its template come from the checkpoint;
the architecture declares the `<think>`/`</think>` reasoning markers and the The tokenizer and its template come from the checkpoint; the architecture declares the
`<tool_call>name<arg_key>...` tool-call format. `<think>`/`</think>` reasoning markers and the `<tool_call>name<arg_key>...` tool-call format.
DSpark, other gate activations and rotary-scaling overrides are not implemented.
## Rotated int8 (IQ8R)
`arch/spark25_w8a8` serves a trunk whose linears use the fwht128-rotated int8 grid: per-128 int8
activation codes feed `i8a8h` GEMMs, while the embedding and small per-head gate remain BF16 and
normalisation gains remain FP32. Exact GELU runs before the down projection's separate Hadamard quantiser. The output head
may be BF16 or a separately quantised int8 table. The descriptor is `w8a8_fwht128`; the container
must set `quantization_config.quant_method=w8a8` and `quantization_config.fmt=fwht128`.
Column-sharded inputs and their offsets must be whole 128-column scale groups. A rank with an
unaligned span is refused, not served with misaligned scales.
`data/recipes/spark-x26-4b-iq8r.recipe` fits the six trunk projection types against BF16
calibration Grams, and quantises the output head with RTN. The BF16 plugin records them with
`RADIANCE_CALIB_DIR`, `RADIANCE_CALIB_TOKENS`, and `RADIANCE_SPARK_CALIB_LAYERS=lo:hi`; calibration
requires TP=1 to retain off-diagonal cross-rank terms. Drive a representative corpus through
prefill with `--no-prefix-cache` and no speculative decoding. Each slice writes six RADGRAM2 files
per layer. Calibration completeness is not a measure of quality: compare the resulting container
against BF16 on disjoint data, including the tail of the per-position KL distribution.
`tests/spark25_iq8r.py` compares a deterministic quantised fixture with the Transformers reference,
including top-10 probabilities across cached decoding. `--tp 2` checks two fake host ranks, and
`--wide-tp --tp N` exercises group-aligned attention and FFN shards for N from 1 to 8. As with the
BF16 fixture, run it under a GPU-denying device cgroup on a shared machine.
For a CPU differential against the reference implementation's `configuration_spark.py` and For a CPU differential against the reference implementation's `configuration_spark.py` and
`modeling_spark.py`, with Python's torch, transformers and safetensors installed: `modeling_spark.py`, with Python's torch, transformers and safetensors installed:
+1 -1
View File
@@ -101,7 +101,7 @@ TEST(the_shipped_architectures_load_with_distinct_selection_keys) {
{ "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" }, { "qwen35", "fp8_e4m3" }, { "qwen35", "w8a8_fwht128" }, { "qwen35moe", "fp8_e4m3" },
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" }, { "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
{ "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" }, { "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" },
{ "spark25", "" }, { "sdxl", "" }, { "spark25", "" }, { "spark25", "w8a8_fwht128" }, { "sdxl", "" },
{ "unlimitedocr", "" } }; { "unlimitedocr", "" } };
std::set<std::pair<std::string, std::string>> got; std::set<std::pair<std::string, std::string>> got;
for (const auto& [k, name] : keys) got.insert(k); for (const auto& [k, name] : keys) got.insert(k);
+76
View File
@@ -3,6 +3,7 @@
#include "arch_fakes.h" #include "arch_fakes.h"
#include "rad_plugin.h" #include "rad_plugin.h"
#include "../arch/spark25_bf16/spark25_bf16.cpp" #include "../arch/spark25_bf16/spark25_bf16.cpp"
#include "../arch/spark25_w8a8/spark25_w8a8.cpp"
using namespace rad_fake; using namespace rad_fake;
@@ -152,6 +153,81 @@ TEST(tensor_parallel_covers_heads_and_ffn_without_changing_gqa) {
} }
} }
static void spark_iq8r_encodings(RadBuilder& b, bool rotated = true) {
RadEncoding e = rad_enc_affine(RAD_I8, RAD_BF16, 1, 128);
if (rotated) rad_enc_copy_str(e.transform, "fwht128");
for (const char* name : {"attn_q.weight", "attn_k.weight", "attn_v.weight",
"attn_output.weight", "ffn_gate_up.weight", "ffn_down.weight"})
b.encs.emplace_back(name, e);
b.encs.emplace_back("output.weight", rad_enc_affine(RAD_I8, RAD_BF16, 1, 128));
}
TEST(iq8r_graph_uses_rotated_codes_and_is_liveness_safe) {
for (int world = 1; world <= 8; ++world) {
for (int rank = 0; rank < world; ++rank) {
MetaKV k = spark_meta();
k.m.quant = "w8a8_fwht128";
k.set("quantization_config.quant_method", "w8a8")
.set("quantization_config.fmt", "fwht128");
RadBuilder b;
spark_iq8r_encodings(b);
RadBuildCtx ctx = build_ctx();
ctx.world_size = world;
ctx.rank = rank;
REQUIRE_EQ(spark25_w8a8::declare(&b, k.meta(), &ctx), RAD_OK);
int quantized = 0;
for (const auto& op : b.ops) if (op.op == "gemm_nt_q") {
CHECK_EQ(pstr(&op, "dtype"), std::string("i8a8h"));
++quantized;
}
CHECK_EQ(quantized, 24); /* six linears x four layers */
CHECK_EQ(count_op(b, "all_reduce"), world == 1 ? 0 : 9);
for (int n : {1, 8}) {
RadBatch batch = decode_batch();
batch.n_tok = batch.max_q_len = n;
RadCtx c{.b = &b, .batch = &batch, .rank = rank, .world = world};
spark25_w8a8::step(&c, &batch);
CHECK_LINT(b, &c);
CHECK(c.step_fail.empty());
}
}
}
}
TEST(iq8r_rejects_unrotated_weights_and_missing_collectives) {
MetaKV k = spark_meta();
k.m.quant = "w8a8_fwht128";
k.set("quantization_config.quant_method", "w8a8")
.set("quantization_config.fmt", "fwht128");
RadBuildCtx ctx = build_ctx();
RadBuilder unrotated;
spark_iq8r_encodings(unrotated, false);
CHECK_EQ(stderr_of_rc([&] { return spark25_w8a8::declare(&unrotated, k.meta(), &ctx); }),
RAD_E_DTYPE);
RadBuilder missing;
spark_iq8r_encodings(missing);
missing.refuse.insert("all_reduce");
ctx.world_size = 2;
CHECK_EQ(stderr_of_rc([&] { return spark25_w8a8::declare(&missing, k.meta(), &ctx); }),
RAD_E_UNSUPPORTED);
}
TEST(tp_rejects_missing_all_reduce_instead_of_skipping_it) {
MetaKV k = spark_meta();
RadBuilder b;
b.refuse.insert("all_reduce");
RadBuildCtx ctx = build_ctx();
ctx.world_size = 2;
CHECK_EQ(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }),
RAD_E_UNSUPPORTED);
/* No collective is required for single-device inference. */
RadBuilder single;
single.refuse.insert("all_reduce");
ctx.world_size = 1;
CHECK_EQ(spark25_bf16::declare(&single, k.meta(), &ctx), RAD_OK);
}
TEST(tp_projection_rounds_to_bf16_before_the_fp32_residual_add) { TEST(tp_projection_rounds_to_bf16_before_the_fp32_residual_add) {
MetaKV k = spark_meta(); MetaKV k = spark_meta();
RadBuilder b; RadBuilder b;
+180
View File
@@ -0,0 +1,180 @@
#!/usr/bin/env python3
"""IQ8R differential for Spark X2.6 on the host kernels.
Builds the deterministic two-layer fixture (tests/spark25_reference.py's, at a geometry the
group-128 rotated int8 grid takes), converts it twice -- as it stands, and on IQ8R's grid -- and
serves both through the CPU kernels. The quantised model must stay close to its bf16 self and to
the Transformers reference: activations fed unrotated into rotated weights, or a scale plane read
at the wrong width, yields a model that runs, generates fluently and is wrong.
Requires torch, transformers and safetensors. GPUs are hidden from both processes; on a shared
machine run it in a GPU-denying device cgroup (ROCm may open device nodes while probing).
tests/spark25_iq8r.py --reference <XHToken-Spark-X2.6-4B> --build <build dir>
"""
import argparse
import json
import os
from pathlib import Path
import socket
import subprocess
import sys
import tempfile
import urllib.request
sys.path.insert(0, str(Path(__file__).resolve().parent))
from spark25_reference import (PROMPTS, generate, load_reference, serve, write_tokenizer) # noqa: E402
# Rows a token and widths the group-128 grid takes: hidden and every contraction in whole 128s,
# output rows in whole 16s. head_dim 32 x 8 heads keeps q and the o_proj contraction at 256.
GEOM = dict(vocab_size=3584, hidden_size=256, intermediate_size=256, num_hidden_layers=2,
num_attention_heads=8, num_key_value_heads=4, head_dim=32)
TRUNK = ("attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up", "ffn_down")
def main():
ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--reference", required=True, type=Path, help="directory with modeling_spark.py")
ap.add_argument("--build", required=True, type=Path, help="Radiance build directory")
ap.add_argument("--keep", type=Path, help="write the fixture and both containers here")
ap.add_argument("--tp", type=int, choices=range(1, 9), default=1,
help="number of fake host ranks (up to 8)")
ap.add_argument("--wide-tp", action="store_true",
help="use 128-wide heads and a 1024-wide FFN to exercise TP up to 8")
args = ap.parse_args()
if args.tp > 2 and not args.wide_tp:
ap.error("--tp above 2 needs --wide-tp so every rank owns a whole scale group")
import torch
import transformers
from safetensors.torch import save_file
torch.set_num_threads(2)
cfgmod, modelmod = load_reference(args.reference.resolve())
if int(transformers.__version__.split(".")[0]) >= 5:
modelmod.Spark2_5ForCausalLM._tied_weights_keys = {"lm_head.weight": "model.embedding.weight"}
geom = dict(GEOM)
if args.wide_tp:
geom.update(intermediate_size=1024, head_dim=128)
config = cfgmod.Spark2_5Config(
**geom, hidden_act="gelu", max_position_embeddings=128, rms_norm_eps=1e-6,
tie_word_embeddings=True, headwise_attn_output_gate=True, gate_attn_act_mode="sigmoid",
sliding_window=8, layer_types=["sliding_attention", "full_attention"],
rope_parameters={"sliding_attention": {"rope_theta": 10000.0, "partial_rotary_factor": 1.0},
"full_attention": {"rope_theta": 5000000.0, "partial_rotary_factor": 0.5}},
bos_token_id=256, eos_token_id=256, pad_token_id=256)
torch.manual_seed(19)
model = modelmod.Spark2_5ForCausalLM(config).eval().to(torch.bfloat16)
with torch.no_grad():
for name, w in model.named_parameters():
if name.endswith("layernorm.weight") or name == "model.norm.weight":
w.copy_((1 + 0.08 * torch.randn(w.shape)).to(w.dtype))
# Scale the measured 4B weight standard deviations by sqrt(2560 / 256), so
# this narrower random fixture has comparable projection and head logit magnitudes.
elif name == "model.embedding.weight":
w.copy_((0.09 * torch.randn(w.shape)).to(w.dtype))
elif name.endswith("g_proj.weight"):
w.copy_((0.055 * torch.randn(w.shape)).to(w.dtype))
else:
w.copy_((0.085 * torch.randn(w.shape)).to(w.dtype))
def reference(ids):
n = len(ids)
q, k = torch.arange(n)[:, None], torch.arange(n)[None, :]
full = torch.where(k <= q, 0.0, float("-inf"))[None, None, :, :]
local = torch.where((k <= q) & (k > q - config.sliding_window), 0.0,
float("-inf"))[None, None, :, :]
with torch.inference_mode():
logits = model(torch.tensor([ids]), attention_mask={"full_attention": full,
"sliding_attention": local}, use_cache=False).logits[0, -1].float()
return torch.log_softmax(logits, dim=-1)
build = args.build.resolve()
env = os.environ.copy()
env.update(RADIANCE_HOME=str(build / "radiance_home"), RADIANCE_HOST_VRAM_MIB="2048",
RADIANCE_HOST_DEVICES=str(args.tp))
keep = args.keep.resolve() if args.keep else None
root = keep or Path(tempfile.mkdtemp(prefix="spark25-iq8r-"))
root.mkdir(parents=True, exist_ok=True)
ckpt = root / "checkpoint"
ckpt.mkdir(exist_ok=True)
config_json = config.to_dict()
config_json.update(model_type="spark2_5", architectures=["Spark2_5ForCausalLM"])
(ckpt / "config.json").write_text(json.dumps(config_json, indent=2))
state = {k: v.contiguous().clone() for k, v in model.state_dict().items()
if k != "lm_head.weight"}
save_file(state, ckpt / "model.safetensors")
write_tokenizer(ckpt)
bf16, trunk, full = root / "model-bf16.rad", root / "model-trunk.rad", root / "model-iq8r.rad"
trunk_recipe = root / "iq8r-trunk.recipe"
trunk_recipe.write_text("".join(f"blk.*.{w}.weight gptq codes=i8 group=128 scale=bf16 "
f"transform=fwht128 clamp=sym rule=search\n" for w in TRUNK))
full_recipe = root / "iq8r.recipe"
full_recipe.write_text(trunk_recipe.read_text() +
"output.weight rtn codes=i8 group=128 scale=bf16 clamp=sym "
"rule=search\n")
sets = ["--set", "quantization_config.quant_method=w8a8", "--set",
"quantization_config.fmt=fwht128"]
for out, extra in ((bf16, []), (trunk, ["--recipe", str(trunk_recipe)] + sets),
(full, ["--recipe", str(full_recipe)] + sets)):
subprocess.run([str(build / "bin/rad-convert"), str(ckpt), "-o", str(out),
"--max-ctx", "64", "--max-tok", "32"] + extra, env=env, check=True,
stdout=subprocess.DEVNULL)
got = {}
with (root / "server.log").open("w+") as log:
for tag, container in (("bf16", bf16), ("trunk", trunk), ("iq8r", full)):
with socket.socket() as s:
s.bind(("127.0.0.1", 0))
port = s.getsockname()[1]
proc, url = serve(build, container, port, env, log, tp=args.tp)
try:
for prompt in PROMPTS:
got.setdefault(tag, {})[prompt] = generate(url, prompt)
except Exception:
log.flush()
log.seek(0)
print(log.read(), file=sys.stderr)
raise
finally:
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
# What a step's token costs against the Transformers reference: the same rule
# tests/spark25_reference.py holds the bf16 model to, with the margin the int8 grid buys. This
# fixture is a random model, so its candidates sit close together and a quantised run can flip
# a greedy token; what it may not do is drift far, which is what a connection fed unrotated
# codes or a scale plane read at the wrong width produces.
# Bounds cover BF16/TP reduction rounding and 8-bit grid error at this geometry, while
# rejecting a wrong rotation or scale plane. Compare probabilities as well as the sampled id:
# an apparently correct argmax alone can hide a badly corrupted distribution.
bounds = {"bf16": (0.1, 0.15), "trunk": (0.35, 0.4), "iq8r": (0.35, 0.4)}
for prompt in PROMPTS:
for tag, (bound, logp_bound) in bounds.items():
ids, exact, gap, max_error = list(prompt.encode()), 0, 0.0, 0.0
for row in got[tag][prompt]:
expected = reference(ids)
gap = max(gap, float(expected.max() - expected[row["id"]]))
for candidate in row["top_logprobs"]:
max_error = max(max_error, abs(candidate["logprob"] - float(expected[candidate["id"]])))
if row["id"] == int(expected.argmax()):
exact += 1
ids.append(row["id"])
print(f"{tag:5s} {prompt!r}: {exact}/5 greedy tokens match the reference, worst step "
f"{gap:.5f} nats behind the reference's best candidate, max top-10 logp error "
f"{max_error:.5f}")
if gap > bound:
raise AssertionError(f"{tag} {prompt!r}: a step is {gap:.5f} nats behind the "
f"reference's best candidate (bound {bound})")
if max_error > logp_bound:
raise AssertionError(f"{tag} {prompt!r}: top-10 logp error {max_error:.5f} "
f"exceeds {logp_bound}")
print(f"TP={args.tp}: iq8r stays within the test's configured reference bounds")
if __name__ == "__main__":
main()
+55 -37
View File
@@ -52,9 +52,8 @@ def write_tokenizer(path):
vocab[s] = 256 + i vocab[s] = 256 + i
added.append(dict(id=256 + i, content=s, single_word=False, lstrip=False, added.append(dict(id=256 + i, content=s, single_word=False, lstrip=False,
rstrip=False, normalized=False, special=True)) rstrip=False, normalized=False, special=True))
# A 1024-token vocabulary leaves every rank a nonempty shard even at a ragged TP=3. # Vocabulary shards are rounded to 128-row blocks; 3584 rows give worlds 1 to 8 a nonempty
# The vocabulary shard is rounded up to a 128-row block, so a small vocab leaves a rank with # shard, including ragged worlds such as TP=3.
# nothing at some widths. 3584 rows give every world from 1 to 8 a nonempty shard.
for i in range(259, 3584): for i in range(259, 3584):
s = f"<extra_{i}>" s = f"<extra_{i}>"
vocab[s] = i vocab[s] = i
@@ -68,6 +67,52 @@ def write_tokenizer(path):
(path / "tokenizer.json").write_text(json.dumps(tok, ensure_ascii=False)) (path / "tokenizer.json").write_text(json.dumps(tok, ensure_ascii=False))
# The last prompt crosses the 32-token prefill chunk boundary; the third leaves the local window.
PROMPTS = ("a", "hello", "longer prompt", "the quick brown fox jumps over the lazy dog twice")
def serve(build, rad, port, env, log, tp=1):
"""Start Radiance on the host kernels over `rad` and wait for /health. The caller stops it."""
proc = subprocess.Popen(
[str(build / "bin/radiance"), "--model", str(rad), "--host", "127.0.0.1", "--port",
str(port), "--kernels", "libref", "--debug-accept-reference-kernels", "--max-model-len",
"64", "--max-num-batched-tokens", "32", "--max-num-seqs", "1", "--tp", str(tp)],
env=env, stdout=log, stderr=subprocess.STDOUT)
url = f"http://127.0.0.1:{port}"
for _ in range(300):
if proc.poll() is not None:
proc.wait()
raise RuntimeError("Radiance exited before listening")
try:
urllib.request.urlopen(url + "/health", timeout=1).close()
return proc, url
except (OSError, urllib.error.URLError):
time.sleep(0.1)
stop(proc)
raise RuntimeError("Radiance did not start")
def stop(proc):
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
def generate(url, prompt, steps=5, logprobs=10):
"""Greedy decode of `steps` tokens with the top candidates at each step."""
data = json.dumps(dict(prompt=prompt, max_tokens=steps, temperature=0, logprobs=logprobs,
ignore_eos=True)).encode()
req = urllib.request.Request(url + "/v1/completions", data,
{"Content-Type": "application/json"})
rows = json.load(urllib.request.urlopen(req, timeout=30))["choices"][0]["logprobs"]["content"]
if len(rows) != steps:
raise AssertionError(f"{prompt!r}: expected {steps} decode rows, got {len(rows)}")
return rows
def main(): def main():
ap = argparse.ArgumentParser(description=__doc__) ap = argparse.ArgumentParser(description=__doc__)
ap.add_argument("--reference", required=True, type=Path, help="directory with modeling_spark.py") ap.add_argument("--reference", required=True, type=Path, help="directory with modeling_spark.py")
@@ -140,35 +185,12 @@ def main():
sock.bind(("127.0.0.1", 0)) sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1] port = sock.getsockname()[1]
with (root / "server.log").open("w+") as log: with (root / "server.log").open("w+") as log:
proc = subprocess.Popen([build / "bin/radiance", "--model", rad, "--host", "127.0.0.1", proc = None
"--port", str(port), "--kernels", "libref", "--debug-accept-reference-kernels",
"--max-model-len", "64", "--max-num-batched-tokens", "32", "--max-num-seqs", "1",
"--tp", str(args.tp)],
env=env, stdout=log, stderr=subprocess.STDOUT)
try: try:
url = f"http://127.0.0.1:{port}" proc, url = serve(build, rad, port, env, log, tp=args.tp)
for _ in range(200): # Compare cached decode with the same HF continuation.
if proc.poll() is not None: for prompt in PROMPTS:
raise RuntimeError("Radiance exited before listening") rows = generate(url, prompt)
try:
urllib.request.urlopen(url + "/health", timeout=1).close()
break
except (OSError, urllib.error.URLError):
time.sleep(0.1)
else:
raise RuntimeError("Radiance did not start")
# The longer prompts exceed the local window, and the last also crosses the
# 32-token prefill chunk boundary. Compare cached decode to the same HF continuation.
for prompt in ("a", "hello", "longer prompt", "the quick brown fox jumps over the lazy dog twice"):
request = dict(prompt=prompt, max_tokens=5, temperature=0, logprobs=10,
ignore_eos=True)
data = json.dumps(request).encode()
req = urllib.request.Request(url + "/v1/completions", data,
{"Content-Type": "application/json"})
result = json.load(urllib.request.urlopen(req, timeout=30))
rows = result["choices"][0]["logprobs"]["content"]
if len(rows) != 5:
raise AssertionError(f"{prompt!r}: expected 5 decode rows, got {len(rows)}")
ids = list(prompt.encode()) ids = list(prompt.encode())
max_error = 0.0 max_error = 0.0
matches = 0 matches = 0
@@ -197,12 +219,8 @@ def main():
print(log.read(), file=sys.stderr) print(log.read(), file=sys.stderr)
raise raise
finally: finally:
proc.terminate() if proc is not None:
try: stop(proc)
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
if __name__ == "__main__": if __name__ == "__main__":