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

+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__":