Shard Spark across ranks and reduce the f32 residual

Attention takes whole GQA groups, so a world that does not divide the KV head count still gets a
clean cut; above it the KV heads are replicated and a group splits between the ranks sharing its
KV head. Gate/up, down and the tied vocabulary take matching spans, and every query head, FFN
channel and vocabulary row belongs to exactly one rank at every world from 1 to 8.

The projection outputs are partial sums, so each block widens to f32 and issues an exact f32
all_reduce before the residual add, which keeps the single-card accumulation order.

tests/spark25_reference.py --tp N holds the sharded graph against the HF reference on N fake host
devices; the tiny fixture has 8 heads over 4 KV heads and 3584 vocabulary rows so worlds 1-8 all
get a nonempty shard.
This commit is contained in:
Constantin authored and StillDeadcode committed 2026-11-03 19:08:58 +01:00
1 parent 48407fb52d
commit 1c96558970
5 files changed
+264 -47

No files matched your search

+4 -3
View File
@@ -34,7 +34,7 @@ To support the development of radiance: [Patreon](https://patreon.com/StillDeadC
| Sage-A1.5 FP8, DFlash2 drafter, vision | `sage-a1.5-fp8-df2.rad` (34 GiB) | [download](https://huggingface.co/Aijuus/sage-a1.5-fp8-df2) | `sage-a1.5-df2.yaml` |
| MiniCPM5-2B FP8, DSpark drafter | `minicpm5-2b-fp8.rad` (3 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-fp8) | `minicpm5-2b.yaml` |
| MiniCPM5-2B bf16, DSpark drafter | `minicpm5-2b-bf16.rad` (5 GiB) | [download](https://huggingface.co/StillDeadcode/minicpm5-2b-bf16) | `minicpm5-2b-bf16.yaml` |
| Spark X2.6 4B bf16: thinking and tool calls, one card | `spark-x2.6-4b-bf16.rad` (8.3 GiB) | [convert](#convert-a-checkpoint) | — |
| Spark X2.6 4B bf16: thinking and tool calls, one to four cards | `spark-x2.6-4b-bf16.rad` (8.3 GiB) | [convert](#convert-a-checkpoint) | — |
| Gemma 4 31B: GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w4a8) | `gemma4-31b-w4a8.yaml` |
| Gemma 4 31B w5: GPTQ int5 trunk (a scale and a zero point per 128 weights), MTP, vision | `gemma4-31b-w5.rad` (23 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-w5) | `gemma4-31b-w5.yaml` |
| Gemma 4 31B heretic-ara (refusals removed): GPTQ int4 trunk, int8 activations, MTP, vision | `gemma4-31b-heretic-ara-w4a8.rad` (20 GiB) | [download](https://huggingface.co/keptn/gemma4-31b-heretic-ara-w4a8) | `gemma4-31b-heretic-ara-w4a8.yaml` |
@@ -323,8 +323,9 @@ reads it: NVFP4 (compressed-tensors' and NVIDIA ModelOpt's) to the MXFP4 kernels
Flash-Next's int4 block projections to int8. [docs/GUIDE.md](docs/GUIDE.md) names the recipes of record
with their `rad-convert` commands.
Spark X2.6 currently runs at `--tp 1` without a drafter or quantisation recipe. Its checkpoint's
chat template enables thinking by default; replies return reasoning in `reasoning_content`. Set
Spark X2.6 runs BF16 at `--tp 1`, `2`, `3` or `4` -- and `8`, the worlds libr4d has an exact
all-reduce for -- without a drafter or quantisation recipe. Its checkpoint's chat template enables
thinking by default; replies return reasoning in `reasoning_content`. Set
`chat_template_kwargs.enable_thinking` to `false` for a non-thinking request. Tool calls use the
checkpoint's tagged format and are returned as OpenAI `tool_calls`.
+137 -30
View File
@@ -6,12 +6,14 @@
* 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.
*
* This first implementation is deliberately single-card. As in the HF reference, residuals
* accumulate in f32; rmsnorm reads that stream and writes bf16 for the linear projections.
* 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 "chat.h"
#include <algorithm>
#include <cmath>
#include <sstream>
#include <string>
@@ -24,8 +26,8 @@ struct Layer {
rad_kvgroup kv = 0;
rad_weight an = 0, q = 0, k = 0, v = 0, gate = 0, o = 0, fn = 0, gu = 0, down = 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, add_attn = 0;
rad_op fnorm = 0, gup = 0, act = 0, dp = 0, widen_ffn = 0, add_ffn = 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;
};
struct Model {
@@ -35,7 +37,7 @@ struct Model {
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;
rad_weight tok = 0, norm = 0, head = 0;
rad_op embed = 0, widen = 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;
};
static Model models[MAX_RANKS];
@@ -65,17 +67,82 @@ static int schedule(const RadModelMeta* meta, int64_t n, std::vector<bool>& loca
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 declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* ctx) {
if (!b || !meta || !ctx || ctx->rank < 0 || ctx->rank >= MAX_RANKS) return RAD_E_INVAL;
if (ctx->world_size > 1) {
fprintf(stderr, "radiance: spark25: this BF16 implementation needs --tp 1\n");
return RAD_E_UNSUPPORTED;
}
Model& m = models[ctx->rank];
m = Model{};
m.nm = Names(ctx->scope);
RAD_ARCH_TRY(geom_from(m.g, meta, ctx, "bf16", RAD_BF16));
/* 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));
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) ||
@@ -152,17 +219,21 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
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 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, RAD_SHARD_NONE, group);
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);
{g.n_vocab, E}, grp_model(), RAD_ACCESS_VOCAB, RAD_SHARD_ROW);
m.head = weight(nm.f("output.weight"), nm.ckpt("model.embedding.weight"), RAD_BF16,
{g.n_vocab, E}, grp_model(), RAD_ACCESS_VOCAB);
{g.n_vocab, E}, grp_model(), RAD_ACCESS_VOCAB, RAD_SHARD_ROW);
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),
@@ -179,42 +250,71 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
};
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", 0)), RAD_WEIGHTS(m.tok)), {}, {m.h});
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);
/* Reducing the widened projection outputs retains the f32 residual stream. The exact f32
* wire is also needed for the embedding, where only one vocabulary shard contributes. */
auto reduce = [&](rad_buf x) {
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", "fp32"), RAD_INT("exact", 1)),
RAD_NOWEIGHTS), {x}, {x});
};
m.reduce_embed = reduce(m.x);
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) {
return weight(nm.f("blk.%d.%s", l, suffix), src(s), dt, shape, grp_layer(l));
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});
a.o = w("attn_output.weight", "self_attn.out_proj.weight", RAD_BF16, {E, Q});
a.gate = w("attn_gate.weight", "self_attn.g_proj.weight", RAD_BF16, {g.n_head, E}, RAD_SHARD_ROW);
a.o = w("attn_output.weight", "self_attn.out_proj.weight", RAD_BF16, {E, Q}, RAD_SHARD_COL);
a.fn = w("ffn_norm.weight", "post_attention_layernorm.weight", RAD_F32, {E});
a.down = w("ffn_down.weight", "mlp.down_proj.weight", RAD_BF16, {E, F});
a.down = w("ffn_down.weight", "mlp.down_proj.weight", RAD_BF16, {E, F}, RAD_SHARD_COL);
const char* qkv = src("self_attn.q_k_v_proj.weight");
auto part = [&](const char* name, int first, int64_t rows) {
auto part = [&](const char* name, int first, int64_t all_rows, int64_t rows) {
const char* target = nm.f("blk.%d.attn_%s.weight", l, name);
if (map_rows(b, target, {{qkv, first, rows}}) != RAD_OK) return (rad_weight)0;
return decl_w(b, target, RAD_BF16, {rows, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
if (map_rows(b, target, {{qkv, first, all_rows}}) != RAD_OK) return (rad_weight)0;
return decl_w(b, target, RAD_BF16, {rows, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
grp_layer(l));
};
a.q = part("q", 0, Q);
a.k = part("k", (int)Q, K);
a.v = part("v", (int)(Q + K), K);
const int64_t qall = g.n_head_all * g.head_dim, kall = g.n_head_kv_all * g.head_dim;
a.q = part("q", 0, qall, Q);
a.k = part("k", (int)qall, kall, K);
a.v = part("v", (int)(qall + kall), kall, K);
const char* gu = nm.f("blk.%d.ffn_gate_up.weight", l);
RAD_ARCH_TRY(map_concat(b, gu, {src("mlp.gate_proj.weight"), src("mlp.up_proj.weight")}));
a.gu = decl_w(b, gu, RAD_BF16, {2 * F, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_NONE,
grp_layer(l));
a.gu = decl_w(b, gu, RAD_BF16, {2 * F, E}, RAD_ACCESS_PER_TOKEN, RAD_SHARD_ROW,
grp_layer(l), 0, {F, F});
if (!a.an || !a.q || !a.k || !a.v || !a.gate || !a.o || !a.fn || !a.gu || !a.down)
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.q, shards.q.first * g.head_dim,
(shards.q.first + shards.q.count) * g.head_dim));
RAD_ARCH_TRY(rad_weight_shard_span(b, a.gate, shards.q.first,
shards.q.first + shards.q.count));
RAD_ARCH_TRY(rad_weight_shard_span(b, a.o, shards.q.first * g.head_dim,
(shards.q.first + shards.q.count) * g.head_dim));
}
if (g.world > 1 && needs_span(shards.kv, g.n_head_kv_all, g)) {
for (rad_weight h : {a.k, a.v})
RAD_ARCH_TRY(rad_weight_shard_span(b, h, shards.kv.first * g.head_dim,
(shards.kv.first + shards.kv.count) * g.head_dim));
}
if (g.world > 1 && needs_span(shards.ff, g.n_ff_all, g)) {
for (rad_weight h : {a.gu, a.down})
RAD_ARCH_TRY(rad_weight_shard_span(b, h, shards.ff.first,
shards.ff.first + shards.ff.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);
@@ -246,6 +346,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_NOWEIGHTS), {m.attn, m.gate}, {m.attn});
a.op = gemm(E, Q, a.o, m.attn, m.h);
a.widen_attn = widen(m.delta);
a.reduce_attn = reduce(m.delta);
a.add_attn = add();
a.fnorm = norm(a.fn, m.x, m.h);
a.gup = gemm(2 * F, E, a.gu, m.h, m.gu);
@@ -253,6 +354,7 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
RAD_STR("act", "gelu"), RAD_STR("dtype", "bf16")), RAD_NOWEIGHTS), {m.gu}, {m.ff});
a.dp = gemm(E, F, a.down, m.ff, m.h);
a.widen_ffn = widen(m.delta);
a.reduce_ffn = reduce(m.delta);
a.add_ffn = add();
}
m.final_norm = norm(m.norm, m.x, m.h);
@@ -261,9 +363,11 @@ static int declare(RadBuilder* b, const RadModelMeta* meta, const RadBuildCtx* c
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: %lld layers, %lld query / %lld KV heads x %lld, local window %lld",
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)window);
(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;
}
@@ -274,6 +378,7 @@ static void step(RadCtx* c, const RadBatch* batch) {
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);
@@ -299,12 +404,14 @@ static void step(RadCtx* c, const RadBatch* batch) {
RAD_ISSUE_N(c, a.gate_heads, T * g.n_head, heads, gates, RAD_NONE, heads);
RAD_ISSUE(c, a.op, brows(m.attn, T), RAD_W(a.o), brows(m.h, T));
RAD_ISSUE(c, a.widen_attn, brows(m.h, T), brows(m.delta, T));
if (a.reduce_attn) RAD_ISSUE_N(c, a.reduce_attn, T * g.n_embd, brows(m.delta, T), RAD_NONE);
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.gup, brows(m.h, T), RAD_W(a.gu), brows(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));
RAD_ISSUE(c, a.dp, brows(m.ff, T), RAD_W(a.down), brows(m.h, T));
RAD_ISSUE(c, a.widen_ffn, brows(m.h, T), brows(m.delta, T));
if (a.reduce_ffn) RAD_ISSUE_N(c, a.reduce_ffn, T * g.n_embd, brows(m.delta, T), RAD_NONE);
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));
+30 -5
View File
@@ -85,7 +85,30 @@ attention head's output is multiplied by its own sigmoid gate before the output
10000; full layers use 64 rotary dimensions at theta 5000000. Both use the full KV group, with the
window applied by the local attention op, so prefix caching remains valid.
The initial implementation serves BF16 at TP1, tied embeddings, headwise sigmoid gates and the
## Tensor parallelism
A rank's attention slice is whole GQA groups, so a world that does not divide 4 KV heads still
shards cleanly: the three ranks of a 3-rank world take 2, 1 and 1 KV heads with the query heads
that belong to them. Above the KV-head count the KV heads are replicated and one group's query
heads are split between the ranks sharing its KV head, so every query head still attends the KV
head the checkpoint gave it -- a rank's own `gqa` can then be smaller than the checkpoint's, while
the KV cache it stores is a replica of its peer's. The gate and output projections take the
matching row and column spans, and the tied embedding and lm_head take the contiguous vocabulary
shard `rad_arch.h`'s `shard_begin` describes, because that is the split the sampler's candidate
merge assumes.
The FFN splits by channels, whole 128-column blocks where the width has them, and a rank's
`[gate | up]` keeps both parts the same width. Every split dimension is covered exactly once at
every world from 1 to 8, asserted in `spark25_arch_test`.
Column-sharded outputs are partial sums, and the residual stream is f32, so the plugin reduces the
*f32* delta rather than the bf16 projection output: one exact `all_reduce` over the widened rows
after the embedding (whose ranks hold disjoint token rows) and two per layer, all issued on the
residual's own buffer. The accumulation order then matches the single-card graph. libr4d serves
that row 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.
The initial implementation serves BF16 with tied embeddings, headwise sigmoid gates and the
checkpoint's own rotary parameters. It does not implement DSpark, quantisation recipes, other gate
activations or rotary-scaling overrides. The tokenizer and its template come from the checkpoint;
the architecture declares the `<think>`/`</think>` reasoning markers and the
@@ -96,15 +119,17 @@ For a CPU differential against the reference implementation's `configuration_spa
```sh
python3 tests/spark25_reference.py --reference /path/to/XHToken-Spark-X2.6-4B --build build
python3 tests/spark25_reference.py --reference /path/to/XHToken-Spark-X2.6-4B --build build --tp 3
SPARK25_REFERENCE_TEMPLATE=/path/to/XHToken-Spark-X2.6-4B/chat_template.jinja \
build/tests/spark25_chat_test
```
The first builds a small deterministic checkpoint and compares prefill, chunked prefill and cached
decode against the reference with GPUs hidden. ROCm may still open GPU device nodes while probing
even with visibility masks; on a shared machine run the CPU comparison in a device cgroup that
denies access to `/dev/kfd` and the GPU render nodes. The second also exercises the checkpoint's
actual chat template, which is not redistributed in this tree.
decode against the reference with GPUs hidden; `--tp` runs the same fixture over that many fake host
ranks, which is how the sharding and the collectives are checked without cards. ROCm may still open
GPU device nodes while probing even with visibility masks; on a shared machine run the CPU
comparison in a device cgroup that denies access to `/dev/kfd` and the GPU render nodes. The last
also exercises the checkpoint's actual chat template, which is not redistributed in this tree.
---
+63 -2
View File
@@ -89,6 +89,67 @@ TEST(prefill_and_decode_issue_a_liveness_safe_graph) {
}
}
TEST(tensor_parallel_covers_heads_and_ffn_without_changing_gqa) {
for (int world = 1; world <= 8; ++world) {
std::vector<int> query_owners(16, 0), ffn_owners(10240, 0), vocab_owners(131072, 0);
for (int rank = 0; rank < world; ++rank) {
MetaKV k = spark_meta();
RadBuilder b;
RadBuildCtx ctx = build_ctx();
ctx.world_size = world;
ctx.rank = rank;
REQUIRE_EQ(spark25_bf16::declare(&b, k.meta(), &ctx), RAD_OK);
const auto& g = spark25_bf16::models[rank].g;
const RecWeight* q = find_w(b, "blk.0.attn_q.weight");
const RecWeight* key = find_w(b, "blk.0.attn_k.weight");
const RecWeight* gate = find_w(b, "blk.0.attn_gate.weight");
const RecWeight* out = find_w(b, "blk.0.attn_output.weight");
const RecWeight* gu = find_w(b, "blk.0.ffn_gate_up.weight");
const RecWeight* down = find_w(b, "blk.0.ffn_down.weight");
const RecWeight* tok = find_w(b, "token_embd.weight");
REQUIRE(q && key && gate && out && gu && down && tok);
CHECK_EQ(q->d.shard, RAD_SHARD_ROW);
CHECK_EQ(gate->d.shard, RAD_SHARD_ROW);
CHECK_EQ(out->d.shard, RAD_SHARD_COL);
CHECK_EQ(gu->d.shard, RAD_SHARD_ROW);
CHECK_EQ(down->d.shard, RAD_SHARD_COL);
CHECK_EQ(gu->d.n_row_parts, 2);
CHECK_EQ(gu->d.row_parts[0], g.n_ff);
CHECK_EQ(gu->d.row_parts[1], g.n_ff);
const int64_t q0 = q->span_set ? q->span_lo / g.head_dim : rank * g.n_head;
const int64_t k0 = key->span_set ? key->span_lo / g.head_dim : rank * g.n_head_kv;
const int64_t f0 = gu->span_set ? gu->span_lo : rank * g.n_ff;
const int64_t v0 = tok->span_set ? tok->span_lo : rank * g.n_vocab;
CHECK_EQ(gate->span_set ? gate->span_lo : rank * g.n_head, q0);
CHECK_EQ(out->span_set ? out->span_lo : rank * g.q_dim(), q0 * g.head_dim);
CHECK_EQ(down->span_set ? down->span_lo : rank * g.n_ff, f0);
CHECK_EQ(v0, g.vocab_off);
for (int64_t h = 0; h < g.n_head; ++h) {
REQUIRE(q0 + h < (int64_t)query_owners.size());
++query_owners[(size_t)(q0 + h)];
CHECK_EQ(k0 + h / g.gqa(), (q0 + h) / 4);
}
for (int64_t i = 0; i < g.n_ff; ++i) ++ffn_owners[(size_t)(f0 + i)];
for (int64_t i = 0; i < g.n_vocab; ++i) ++vocab_owners[(size_t)(v0 + i)];
CHECK_EQ(count_op(b, "all_reduce"), world == 1 ? 0 : 9);
for (const auto& op : b.ops) if (op.op == "all_reduce") {
CHECK_EQ(pstr(&op, "dtype"), std::string("fp32"));
CHECK_EQ(pint(&op, "exact"), 1);
CHECK_EQ(pint(&op, "world_size"), world);
}
RadBatch batch = decode_batch();
batch.n_tok = batch.max_q_len = 8;
RadCtx c{.b = &b, .batch = &batch, .rank = rank, .world = world};
spark25_bf16::step(&c, &batch);
CHECK_LINT(b, &c);
CHECK(c.step_fail.empty());
}
CHECK(std::all_of(query_owners.begin(), query_owners.end(), [](int n) { return n == 1; }));
CHECK(std::all_of(ffn_owners.begin(), ffn_owners.end(), [](int n) { return n == 1; }));
CHECK(std::all_of(vocab_owners.begin(), vocab_owners.end(), [](int n) { return n == 1; }));
}
}
TEST(refuses_unimplemented_variants) {
RadBuildCtx ctx = build_ctx();
for (const auto& change : {std::pair{"tie_word_embeddings", "0"},
@@ -111,8 +172,8 @@ TEST(refuses_unimplemented_variants) {
CHECK(stderr_of_rc([&] { return spark25_bf16::declare(&scaled, k.meta(), &ctx); }) == RAD_E_UNSUPPORTED);
k = spark_meta();
RadBuilder b;
ctx.world_size = 2;
CHECK(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }) == RAD_E_UNSUPPORTED);
ctx.world_size = 17; /* more ranks than query heads */
CHECK(stderr_of_rc([&] { return spark25_bf16::declare(&b, k.meta(), &ctx); }) == RAD_E_INVAL);
}
RAD_TEST_MAIN()
+30 -7
View File
@@ -3,6 +3,8 @@
Requires torch, transformers and safetensors. It creates a tiny two-layer random checkpoint,
converts and serves it on the host, then compares prefill and cached decode with the HF reference.
--tp N runs the same fixture over N fake host devices (RADIANCE_HOST_DEVICES), which is how the
tensor-parallel sharding and collectives are held to the reference without cards.
No model weights are copied from the reference checkpoint, and GPUs are hidden from both processes.
ROCm may still open device nodes when probing; use a GPU-denying device cgroup on shared machines.
"""
@@ -50,6 +52,14 @@ def write_tokenizer(path):
vocab[s] = 256 + i
added.append(dict(id=256 + i, content=s, single_word=False, lstrip=False,
rstrip=False, normalized=False, special=True))
# A 1024-token vocabulary leaves every rank a nonempty shard even at a ragged TP=3.
# The vocabulary shard is rounded up to a 128-row block, so a small vocab leaves a rank with
# nothing at some widths. 3584 rows give every world from 1 to 8 a nonempty shard.
for i in range(259, 3584):
s = f"<extra_{i}>"
vocab[s] = i
added.append(dict(id=i, content=s, single_word=False, lstrip=False,
rstrip=False, normalized=False, special=False))
bytelevel = dict(type="ByteLevel", add_prefix_space=False, trim_offsets=False, use_regex=True)
tok = dict(version="1.0", added_tokens=added, normalizer=None, pre_tokenizer=bytelevel,
post_processor=None, decoder=bytelevel,
@@ -62,7 +72,10 @@ 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("--tp", type=int, default=1, help="number of fake host ranks (up to 8)")
args = ap.parse_args()
if args.tp < 1 or args.tp > 8:
ap.error("--tp must be between 1 and 8")
import torch
import transformers
from safetensors.torch import save_file
@@ -73,8 +86,8 @@ def main():
if int(transformers.__version__.split(".")[0]) >= 5:
modelmod.Spark2_5ForCausalLM._tied_weights_keys = {"lm_head.weight": "model.embedding.weight"}
config = cfgmod.Spark2_5Config(
vocab_size=259, hidden_size=32, intermediate_size=64, num_hidden_layers=2,
num_attention_heads=4, num_key_value_heads=2, head_dim=8, hidden_act="gelu",
vocab_size=3584, hidden_size=32, intermediate_size=64, num_hidden_layers=2,
num_attention_heads=8, num_key_value_heads=4, head_dim=4, 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=4,
layer_types=["sliding_attention", "full_attention"],
@@ -108,7 +121,8 @@ def main():
build = args.build.resolve()
env = os.environ.copy()
env.update(RADIANCE_HOME=str(build / "radiance_home"), RADIANCE_HOST_VRAM_MIB="512")
env.update(RADIANCE_HOME=str(build / "radiance_home"), RADIANCE_HOST_VRAM_MIB="512",
RADIANCE_HOST_DEVICES=str(args.tp))
with tempfile.TemporaryDirectory(prefix="spark25-reference-") as tmp:
root = Path(tmp)
ckpt = root / "checkpoint"
@@ -128,7 +142,8 @@ def main():
with (root / "server.log").open("w+") as log:
proc = subprocess.Popen([build / "bin/radiance", "--model", 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"],
"--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:
url = f"http://127.0.0.1:{port}"
@@ -156,10 +171,17 @@ def main():
raise AssertionError(f"{prompt!r}: expected 5 decode rows, got {len(rows)}")
ids = list(prompt.encode())
max_error = 0.0
matches = 0
for row in rows:
expected = reference(ids)
if row["id"] != int(expected.argmax()):
raise AssertionError(f"{prompt!r}: token {row['id']} != reference {int(expected.argmax())}")
if row["id"] == int(expected.argmax()):
matches += 1
# A shard changes the order of a bf16 reduction, which can swap two
# candidates closer than this. A wider gap is a wrong model, not rounding.
elif float(expected.max() - expected[row["id"]]) > 0.1:
raise AssertionError(
f"{prompt!r}: token {row['id']} != reference "
f"{int(expected.argmax())}, {float(expected.max() - expected[row['id']]):.5f} nats behind")
for candidate in row["top_logprobs"]:
max_error = max(max_error,
abs(candidate["logprob"] - float(expected[candidate["id"]])))
@@ -167,7 +189,8 @@ def main():
# BF16 logits / attention reduction order differ slightly from CPU torch.
if max_error >= 0.15:
raise AssertionError(f"{prompt!r}: max top-10 log-prob error {max_error:.5f}")
print(f"{prompt!r}: 5/5 top-1, max top-10 log-prob error {max_error:.5f}")
print(f"TP={args.tp} {prompt!r}: {matches}/5 exact top-1, "
f"max top-10 log-prob error {max_error:.5f}")
except Exception:
log.flush()
log.seek(0)