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

+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" },
{ "qwen3asr", "" }, { "krea2", "" }, { "ltx2", "" }, { "minimaxh3", "" },
{ "minimaxmusic3", "" }, { "qwen4exp", "" }, { "qwenimage21", "" },
{ "spark25", "" }, { "sdxl", "" },
{ "spark25", "" }, { "spark25", "w8a8_fwht128" }, { "sdxl", "" },
{ "unlimitedocr", "" } };
std::set<std::pair<std::string, std::string>> got;
for (const auto& [k, name] : keys) got.insert(k);
+76
View File
@@ -3,6 +3,7 @@
#include "arch_fakes.h"
#include "rad_plugin.h"
#include "../arch/spark25_bf16/spark25_bf16.cpp"
#include "../arch/spark25_w8a8/spark25_w8a8.cpp"
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) {
MetaKV k = spark_meta();
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
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.
# Vocabulary shards are rounded to 128-row blocks; 3584 rows give worlds 1 to 8 a nonempty
# shard, including ragged worlds such as TP=3.
for i in range(259, 3584):
s = f"<extra_{i}>"
vocab[s] = i
@@ -68,6 +67,52 @@ def write_tokenizer(path):
(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():
ap = argparse.ArgumentParser(description=__doc__)
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))
port = sock.getsockname()[1]
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",
"--tp", str(args.tp)],
env=env, stdout=log, stderr=subprocess.STDOUT)
proc = None
try:
url = f"http://127.0.0.1:{port}"
for _ in range(200):
if proc.poll() is not None:
raise RuntimeError("Radiance exited before listening")
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)}")
proc, url = serve(build, rad, port, env, log, tp=args.tp)
# Compare cached decode with the same HF continuation.
for prompt in PROMPTS:
rows = generate(url, prompt)
ids = list(prompt.encode())
max_error = 0.0
matches = 0
@@ -197,12 +219,8 @@ def main():
print(log.read(), file=sys.stderr)
raise
finally:
proc.terminate()
try:
proc.wait(timeout=10)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
if proc is not None:
stop(proc)
if __name__ == "__main__":