Document Spark IQ8R quality allocation and replay

This commit is contained in:
Constantin committed 2026-11-03 13:53:26 -05:00
1 parent cb97b1c886
commit 08c3e752f7
10 files changed
+952 -18

No files matched your search

+5
View File
@@ -313,6 +313,11 @@ if(TARGET spechub)
add_dependencies(sample_test spechub)
endif()
if(TARGET spark25_recipe_test)
target_compile_definitions(spark25_recipe_test PRIVATE
RAD_SPARK25_RECIPE_DIR="${CMAKE_SOURCE_DIR}/data/recipes")
endif()
# ================================================================== whole models on the CPU
#
# engine_e2e_test runs the radiance binary on tiny synthetic checkpoints (tests/tiny_model.h) on
+15
View File
@@ -212,6 +212,21 @@ TEST(iq8r_rejects_unrotated_weights_and_missing_collectives) {
RAD_E_UNSUPPORTED);
}
TEST(iq8r_refuses_containers_with_a_different_format) {
for (const auto& [method, fmt] : {std::pair{"w8a8", "fwht64"},
std::pair{"fp8", "fwht128"}}) {
MetaKV k = spark_meta();
k.m.quant = "w8a8_fwht128";
k.set("quantization_config.quant_method", method)
.set("quantization_config.fmt", fmt);
RadBuilder b;
spark_iq8r_encodings(b);
RadBuildCtx ctx = build_ctx();
CHECK_EQ(stderr_of_rc([&] { return spark25_w8a8::declare(&b, k.meta(), &ctx); }),
RAD_E_UNSUPPORTED);
}
}
TEST(tp_rejects_missing_all_reduce_instead_of_skipping_it) {
MetaKV k = spark_meta();
RadBuilder b;
+130
View File
@@ -0,0 +1,130 @@
#!/usr/bin/env python3
"""Replay the largest matched-reference IQ8R KLD rows as one-token requests.
Uses the exact token prefixes recorded with --kld-record and verifies the server consumed each
entire prefix. Run against one candidate server configured with the same TP, BF16 KV, chunk limit,
no speculation, and no prefix cache as the KLD scoring run. The report stores only row metadata and
top candidates, not the prompt token sequence.
"""
import argparse
import json
from pathlib import Path
import struct
import sys
import urllib.error
import urllib.request
def post(url, body, timeout):
req = urllib.request.Request(url.rstrip("/") + "/v1/completions",
json.dumps(body).encode(),
{"Content-Type": "application/json"})
with urllib.request.urlopen(req, timeout=timeout) as response:
return json.load(response)
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--reference", required=True, type=Path,
help="directory from --kld-record (top-128 + tail)")
p.add_argument("--report", required=True, type=Path,
help="candidate --kld-out JSON; matching .rows file must be present")
p.add_argument("--url", required=True, help="candidate Radiance base URL, e.g. http://127.0.0.1:5914")
p.add_argument("--model", default="spark", help="served model name")
p.add_argument("--out", required=True, type=Path)
p.add_argument("--limit", type=int, default=20, help="replay this many largest-KL rows")
p.add_argument("--threshold", type=float, default=1.0,
help="also include every row above this coarsened KL threshold")
p.add_argument("--timeout", type=float, default=120)
args = p.parse_args()
ref_dir, report_path, out = args.reference.resolve(), args.report.resolve(), args.out.resolve()
ref = json.loads((ref_dir / "kld.json").read_text())
report = json.loads(report_path.read_text())
if ref.get("format") != "radiance-kld-top-1" or ref.get("top") != 128:
p.error("reference must be radiance-kld-top-1 with top=128")
if report.get("ref_form") != "top-128 + tail":
p.error("candidate report was not scored against the top-128-plus-tail reference")
n = int(ref["rows"])
if report.get("all", {}).get("positions") != n:
p.error("candidate report position count differs from the reference")
raw_rows = Path(str(report_path) + ".rows").read_bytes()
if len(raw_rows) != n * 4 * 4:
p.error("candidate .rows file has an unexpected size")
values = struct.unpack("<" + "f" * (n * 4), raw_rows)
kls = [values[4 * i] for i in range(n)]
above = [i for i, kl in enumerate(kls) if kl > args.threshold]
selected = set(sorted(range(n), key=kls.__getitem__, reverse=True)[:args.limit])
selected.update(above)
selected = sorted(selected, key=kls.__getitem__, reverse=True)
docs = ref["docs"]
tokens_raw = (ref_dir / "tokens.i32").read_bytes()
if len(tokens_raw) % 4:
p.error("tokens.i32 has an unexpected size")
tokens = struct.unpack("<" + "i" * (len(tokens_raw) // 4), tokens_raw)
token_starts = []
total = 0
for doc in docs:
token_starts.append(total)
total += int(doc["tokens"])
if total != len(tokens):
p.error("tokens.i32 length does not match the reference manifest")
spans = [(int(d["row0"]), int(d["row0"]) + int(d["tokens"]) - int(d["score_from"]) - 1)
for d in docs]
top_count = int(ref["top"])
top_raw = (ref_dir / "top.bin").read_bytes()
if len(top_raw) != n * top_count * 8:
p.error("top.bin has an unexpected size")
results = []
for row in selected:
doc_index = next((i for i, (lo, hi) in enumerate(spans) if lo <= row < hi), None)
if doc_index is None:
p.error(f"row {row} is outside every reference document")
doc = docs[doc_index]
token_pos = int(doc["score_from"]) + row - int(doc["row0"])
begin = token_starts[doc_index]
prompt = list(tokens[begin:begin + token_pos + 1])
if not prompt:
p.error(f"row {row} produced an empty replay prompt")
ref_entries = [struct.unpack_from("<if", top_raw, (row * top_count + i) * 8)
for i in range(top_count)]
ref_top = sorted(ref_entries, key=lambda item: (-item[1], item[0]))[:20]
response = post(args.url, {"model": args.model, "prompt": prompt, "max_tokens": 1,
"temperature": 0, "ignore_eos": True, "logprobs": 20},
args.timeout)
if int(response.get("usage", {}).get("prompt_tokens", -1)) != len(prompt):
p.error(f"row {row}: server did not consume the full {len(prompt)}-token replay prefix")
choice = response["choices"][0]
content = choice["logprobs"]["content"]
if len(content) != 1:
p.error(f"row {row}: expected one scored output token, got {len(content)}")
got = content[0]["top_logprobs"]
got_top = [{"token_id": int(item["id"]), "logprob": float(item["logprob"])}
for item in got]
result = {
"row": row, "source": doc.get("source", ""), "document_index": doc_index,
"token_position": token_pos, "prompt_tokens": len(prompt), "coarsened_kl": kls[row],
"top1_agreement_from_kld": bool(values[4 * row + 3]),
"reference_top20": [{"token_id": int(i), "logprob": float(lp)} for i, lp in ref_top],
"candidate_top20": got_top,
}
results.append(result)
print(f"row={row} source={result['source']} token={token_pos} prompt={len(prompt)} "
f"top128+tail-KL={kls[row]:.6g} top1-agree={result['top1_agreement_from_kld']}")
out.parent.mkdir(parents=True, exist_ok=True)
out.write_text(json.dumps({"reference": str(ref_dir), "candidate_report": str(report_path),
"ref_form": report["ref_form"], "threshold": args.threshold,
"rows_above_threshold": len(above), "replayed": results}, indent=2) + "\n")
print(f"Replay receipt: {out}")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except (KeyError, OSError, ValueError, struct.error, urllib.error.URLError) as exc:
print(f"spark25_kld_tail: {exc}", file=sys.stderr)
sys.exit(1)
+199
View File
@@ -0,0 +1,199 @@
#!/usr/bin/env python3
"""Repeatable real-container Spark latency/throughput smoke (end-to-end, not decode-only).
Run this separately for BF16, full IQ8R, and keep12 under an exclusive device scope. Each run
starts one server, disables speculation and prefix caching, and replays the same held-out prompt
strings at the requested concurrency levels. It records artifact hashes, p50/p95/max request
latency, and aggregate generated-token throughput; it does not claim task quality.
"""
import argparse
from concurrent.futures import ThreadPoolExecutor
import hashlib
import json
import os
from pathlib import Path
import socket
import subprocess
import sys
import time
import urllib.error
import urllib.request
def sha256(path):
h = hashlib.sha256()
with Path(path).open("rb") as f:
for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
h.update(block)
return h.hexdigest()
def quantile(values, q):
values = sorted(values)
if not values:
return 0.0
at = q * (len(values) - 1)
lo = int(at)
return values[lo] if lo + 1 == len(values) else values[lo] + (at - lo) * (values[lo + 1] - values[lo])
def prompts_from(path):
prompts = []
for line_no, line in enumerate(Path(path).read_text().splitlines(), 1):
if not line:
continue
row = json.loads(line)
if not isinstance(row.get("prompt"), str):
raise ValueError(f"{path}:{line_no}: expected a string prompt")
prompts.append({"source": row.get("source", ""), "prompt": row["prompt"]})
if not prompts:
raise ValueError(f"{path}: no prompts")
return prompts
def request(url, model, prompt, max_tokens, timeout):
body = {"model": model, "prompt": prompt, "max_tokens": max_tokens,
"temperature": 0, "ignore_eos": True}
req = urllib.request.Request(url + "/v1/completions", json.dumps(body).encode(),
{"Content-Type": "application/json"})
start = time.perf_counter()
with urllib.request.urlopen(req, timeout=timeout) as response:
data = json.load(response)
elapsed = time.perf_counter() - start
usage = data.get("usage", {})
return {"seconds": elapsed, "prompt_tokens": int(usage.get("prompt_tokens", 0)),
"completion_tokens": int(usage.get("completion_tokens", 0)),
"finish_reason": data["choices"][0].get("finish_reason")}
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--radiance", required=True, type=Path)
p.add_argument("--home", required=True, type=Path)
p.add_argument("--model", required=True, type=Path)
p.add_argument("--prompts", required=True, type=Path, help="JSONL with prompt and optional source")
p.add_argument("--out", required=True, type=Path)
p.add_argument("--source-root", type=Path)
p.add_argument("--kernels", default="libr4d")
p.add_argument("--tp", type=int, default=1)
p.add_argument("--concurrency", default="1,4,8", help="comma-separated sequence counts")
p.add_argument("--requests", type=int, default=16, help="requests per concurrency/repetition")
p.add_argument("--repeats", type=int, default=3)
p.add_argument("--max-tokens", type=int, default=32)
p.add_argument("--max-model-len", type=int, default=16384)
p.add_argument("--max-num-batched-tokens", type=int, default=4096)
p.add_argument("--gpu-headroom-mib", type=int, default=1024)
p.add_argument("--timeout", type=float, default=600)
args = p.parse_args()
radiance, home, model = args.radiance.resolve(), args.home.resolve(), args.model.resolve()
prompt_path, out = args.prompts.resolve(), args.out.resolve()
prompts = prompts_from(prompt_path)
concurrencies = [int(x) for x in args.concurrency.split(",")]
if not concurrencies or any(x < 1 for x in concurrencies):
p.error("--concurrency must be comma-separated positive integers")
if args.requests < 1 or args.repeats < 1 or args.max_tokens < 1:
p.error("requests, repeats, and max-tokens must be positive")
for path in (radiance, model):
if not path.is_file():
p.error(f"not a file: {path}")
out.mkdir(parents=True, exist_ok=True)
with socket.socket() as sock:
sock.bind(("127.0.0.1", 0))
port = sock.getsockname()[1]
served = "spark-qos"
command = [str(radiance), "--model", str(model), "--radiance-home", str(home),
"--kernels", args.kernels, "--host", "127.0.0.1", "--port", str(port),
"--served-model-name", served, "--tp", str(args.tp), "--kv-cache-dtype", "bf16",
"--max-num-seqs", str(max(concurrencies)), "--max-model-len", str(args.max_model_len),
"--max-num-batched-tokens", str(args.max_num_batched_tokens),
"--gpu-headroom-mib", str(args.gpu_headroom_mib),
"--num-speculative-tokens", "0", "--no-prefix-cache"]
receipt = {"model": str(model), "model_sha256": sha256(model),
"radiance": str(radiance), "radiance_sha256": sha256(radiance),
"radiance_home": str(home), "prompt_file": str(prompt_path),
"prompt_file_sha256": sha256(prompt_path), "kernels": args.kernels,
"tp": args.tp, "kv_cache_dtype": "bf16", "prefix_cache": False,
"speculation": 0, "max_num_seqs": max(concurrencies),
"max_model_len": args.max_model_len,
"max_num_batched_tokens": args.max_num_batched_tokens,
"gpu_headroom_mib": args.gpu_headroom_mib,
"requests_per_repeat": args.requests, "repeats": args.repeats,
"max_tokens": args.max_tokens, "command": command, "results": {}}
kernel_dir = home / "kernels"
if kernel_dir.is_dir():
receipt["kernel_shared_objects"] = {
str(f.relative_to(home)): sha256(f) for f in sorted(kernel_dir.rglob("*.so"))}
if args.source_root:
root = args.source_root.resolve()
receipt["source"] = {
"root": str(root),
"revision": subprocess.run(["git", "-C", str(root), "rev-parse", "HEAD"],
check=True, capture_output=True, text=True).stdout.strip(),
"status_porcelain": subprocess.run(["git", "-C", str(root), "status", "--porcelain"],
check=True, capture_output=True, text=True).stdout.strip(),
}
env = os.environ.copy()
env.pop("HF_TOKEN", None)
server_log = (out / "server.log").open("w+")
proc = subprocess.Popen(command, env=env, stdout=server_log, stderr=subprocess.STDOUT)
url = f"http://127.0.0.1:{port}"
try:
deadline = time.monotonic() + 240
while time.monotonic() < deadline:
if proc.poll() is not None:
raise RuntimeError(f"Radiance exited before readiness; see {out / 'server.log'}")
try:
with urllib.request.urlopen(url + "/health", timeout=1):
break
except (OSError, urllib.error.URLError):
time.sleep(0.2)
else:
raise TimeoutError(f"Radiance did not become ready; see {out / 'server.log'}")
for concurrency in concurrencies:
samples = []
started = time.perf_counter()
with ThreadPoolExecutor(max_workers=concurrency) as pool:
for repeat in range(args.repeats):
for base in range(0, args.requests, concurrency):
prompts_for_batch = [prompts[(repeat * args.requests + base + i) % len(prompts)]
for i in range(min(concurrency, args.requests - base))]
futures = [pool.submit(request, url, served, item["prompt"],
args.max_tokens, args.timeout)
for item in prompts_for_batch]
samples.extend(f.result() for f in futures)
wall = time.perf_counter() - started
latencies = [x["seconds"] for x in samples]
generated = sum(x["completion_tokens"] for x in samples)
summary = {"requests": len(samples), "wall_seconds": wall,
"latency_seconds": {"p50": quantile(latencies, 0.50),
"p95": quantile(latencies, 0.95),
"max": max(latencies, default=0.0)},
"generated_tokens": generated,
"aggregate_completion_tokens_per_second": generated / wall if wall else 0.0,
"samples": samples}
receipt["results"][str(concurrency)] = summary
print(f"concurrency={concurrency} requests={len(samples)} p50={summary['latency_seconds']['p50']:.3f}s "
f"p95={summary['latency_seconds']['p95']:.3f}s max={summary['latency_seconds']['max']:.3f}s "
f"aggregate={summary['aggregate_completion_tokens_per_second']:.2f} tok/s")
finally:
proc.terminate()
try:
proc.wait(timeout=30)
except subprocess.TimeoutExpired:
proc.kill()
proc.wait()
server_log.close()
report = out / "qos.json"
report.write_text(json.dumps(receipt, indent=2) + "\n")
print(f"QoS receipt: {report}")
return 0
if __name__ == "__main__":
try:
sys.exit(main())
except (KeyError, OSError, ValueError, urllib.error.URLError, TimeoutError, RuntimeError) as exc:
print(f"spark25_qos: {exc}", file=sys.stderr)
sys.exit(1)
+189
View File
@@ -0,0 +1,189 @@
#!/usr/bin/env python3
"""Matched BF16-vs-IQ8R KLD run for real Spark containers (no conversion is done).
The KLD reference uses the exact same tokenized corpus for every candidate and records top-128
reference tokens plus the remaining probability mass as one tail bucket. Per-position candidate
rows are kept so severe cases can be replayed with spark25_kld_tail.py.
Example (run inside an externally managed GPU scope when using libr4d):
python3 tests/spark25_quality.py --radiance build/bin/radiance \\
--home build/radiance_home --reference /models/spark-bf16.rad \\
--corpus /eval/independent-chat-eval.jsonl --provenance /eval/independent-chat-eval.manifest.json \\
--out /tmp/spark-quality --candidate full=/models/spark-iq8r.rad \\
--candidate keep12=/models/spark-iq8r-keep12.rad
"""
import argparse
import hashlib
import json
import os
from pathlib import Path
import struct
import subprocess
import sys
def sha256(path):
h = hashlib.sha256()
with Path(path).open("rb") as f:
for block in iter(lambda: f.read(8 * 1024 * 1024), b""):
h.update(block)
return h.hexdigest()
def fnv1a64(path):
# Match core/kld.cpp: getline hashes each line without its terminating LF.
h = 1469598103934665603
with Path(path).open("rb") as f:
for line in f:
if line.endswith(b"\n"):
line = line[:-1]
for b in line:
h = ((h ^ b) * 1099511628211) & 0xffffffffffffffff
return f"{h:016x}"
def parse_candidate(spec):
name, sep, path = spec.partition("=")
if not sep or not name or not path:
raise argparse.ArgumentTypeError("candidate must be NAME=/path/to/model.rad")
return name, Path(path).resolve()
def main():
p = argparse.ArgumentParser(description=__doc__)
p.add_argument("--radiance", required=True, type=Path)
p.add_argument("--home", required=True, type=Path, help="RADIANCE_HOME / plugin tree")
p.add_argument("--reference", required=True, type=Path, help="BF16 .rad reference")
p.add_argument("--corpus", required=True, type=Path, help="held-out KLD corpus JSONL")
p.add_argument("--provenance", type=Path, help="evaluation manifest to hash into the run receipt")
p.add_argument("--calibration-manifest", type=Path,
help="calibration dataset manifest to hash into the run receipt")
p.add_argument("--source-root", type=Path, help="git checkout to record the exact source revision")
p.add_argument("--out", required=True, type=Path)
p.add_argument("--candidate", required=True, action="append", type=parse_candidate,
metavar="NAME=RAD", help="repeat for each candidate container")
p.add_argument("--kernels", default="libr4d")
p.add_argument("--tp", type=int, default=1)
p.add_argument("--max-model-len", type=int, default=4096)
p.add_argument("--max-num-batched-tokens", type=int, default=128,
help="match the rowfix Spark quality replay (default: 128)")
p.add_argument("--gpu-headroom-mib", type=int, default=1024)
p.add_argument("--reuse-reference", action="store_true",
help="reuse an existing compatible top-128 reference instead of recording it")
p.add_argument("--dry-run", action="store_true")
args = p.parse_args()
radiance, home, reference = args.radiance.resolve(), args.home.resolve(), args.reference.resolve()
corpus, out = args.corpus.resolve(), args.out.resolve()
candidates = args.candidate
if len({name for name, _ in candidates}) != len(candidates):
p.error("candidate names must be unique")
for path in (radiance, reference, corpus, *(model for _, model in candidates)):
if not path.is_file():
p.error(f"not a file: {path}")
ref_dir = out / "bf16-top128-ref"
common = ["--radiance-home", str(home), "--kernels", args.kernels, "--tp", str(args.tp),
"--kv-cache-dtype", "bf16", "--max-num-seqs", "1", "--max-model-len",
str(args.max_model_len), "--max-num-batched-tokens", str(args.max_num_batched_tokens),
"--gpu-headroom-mib", str(args.gpu_headroom_mib),
"--num-speculative-tokens", "0", "--no-prefix-cache"]
record = [str(radiance), "--model", str(reference), *common, "--kld-record", str(ref_dir),
"--kld-corpus", str(corpus), "--kld-top", "128"]
if args.dry_run:
print(" ".join(record))
for name, model in candidates:
print(" ".join([str(radiance), "--model", str(model), *common, "--kld-ref",
str(ref_dir), "--kld-out", str(out / f"{name}-kld.json")]))
return 0
out.mkdir(parents=True, exist_ok=True)
ref_meta_path = ref_dir / "kld.json"
if args.reuse_reference:
if not ref_meta_path.is_file():
p.error(f"--reuse-reference requested but {ref_meta_path} is missing")
ref_meta = json.loads(ref_meta_path.read_text())
if (ref_meta.get("format") != "radiance-kld-top-1" or ref_meta.get("top") != 128 or
ref_meta.get("corpus_fnv1a64") != fnv1a64(corpus)):
p.error("existing reference is not the same top-128 reference for this corpus")
else:
if ref_dir.exists():
p.error(f"reference directory already exists: {ref_dir}; choose another --out or use --reuse-reference")
ref_dir.mkdir(parents=True)
env = os.environ.copy()
subprocess.run(record, env=env, check=True)
ref_meta = json.loads(ref_meta_path.read_text())
if ref_meta.get("format") != "radiance-kld-top-1" or ref_meta.get("top") != 128:
p.error("reference is not radiance-kld-top-1 with top=128")
if ref_meta.get("corpus_fnv1a64") != fnv1a64(corpus):
p.error("KLD reference corpus hash does not match --corpus")
run = {
"reference_model": str(reference), "reference_sha256": sha256(reference),
"reference_dir": str(ref_dir), "reference_form": "top-128 + tail",
"corpus": str(corpus), "corpus_sha256": sha256(corpus),
"corpus_fnv1a64": fnv1a64(corpus), "evaluation_manifest": None,
"radiance": str(radiance), "radiance_sha256": sha256(radiance),
"radiance_home": str(home), "kernel_selector": args.kernels,
"tp": args.tp, "kv_cache_dtype": "bf16", "max_num_seqs": 1,
"max_model_len": args.max_model_len,
"max_num_batched_tokens": args.max_num_batched_tokens,
"gpu_headroom_mib": args.gpu_headroom_mib,
"speculation": 0, "prefix_cache": False,
"reference_manifest": ref_meta,
"candidates": {},
}
if args.provenance:
prov = args.provenance.resolve()
run["evaluation_manifest"] = {"path": str(prov), "sha256": sha256(prov),
"contents": json.loads(prov.read_text())}
if args.calibration_manifest:
calib = args.calibration_manifest.resolve()
run["calibration_manifest"] = {"path": str(calib), "sha256": sha256(calib),
"contents": json.loads(calib.read_text())}
if args.source_root:
root = args.source_root.resolve()
def git(*cmd):
return subprocess.run(["git", "-C", str(root), *cmd], check=True,
stdout=subprocess.PIPE, text=True).stdout.strip()
run["source"] = {"root": str(root), "revision": git("rev-parse", "HEAD"),
"status_porcelain": git("status", "--porcelain")}
kernel_dir = home / "kernels"
if kernel_dir.is_dir():
run["kernel_shared_objects"] = {str(f.relative_to(home)): sha256(f)
for f in sorted(kernel_dir.rglob("*.so"))}
expected_rows = ref_meta.get("rows")
for name, model in candidates:
report = out / f"{name}-kld.json"
command = [str(radiance), "--model", str(model), *common, "--kld-ref", str(ref_dir),
"--kld-out", str(report)]
subprocess.run(command, env=os.environ.copy(), check=True)
scored = json.loads(report.read_text())
if scored.get("ref_form") != "top-128 + tail" or scored.get("all", {}).get("positions") != expected_rows:
p.error(f"{name}: candidate report is not matched to the top-128 reference rows")
values = scored["all"]["kld"]
row_path = Path(str(report) + ".rows")
raw = row_path.read_bytes()
if len(raw) != expected_rows * 16:
p.error(f"{name}: unexpected per-position rows size {len(raw)}")
row_values = struct.unpack("<" + "f" * (expected_rows * 4), raw)
kl = [row_values[i * 4] for i in range(expected_rows)]
run["candidates"][name] = {"model": str(model), "sha256": sha256(model),
"report": str(report), "rows": str(row_path),
"metrics": scored["all"],
"positions_over_1_nat": sum(x > 1.0 for x in kl)}
print(f"{name}: {expected_rows} positions; ref_form={scored['ref_form']}; "
f"mean={values['mean']:.6g}, p99={values['p99']:.6g}, "
f"p99.9={values['p99_9']:.6g}, max={values['max']:.6g}, "
f">1 nat={run['candidates'][name]['positions_over_1_nat']}")
(out / "run.json").write_text(json.dumps(run, indent=2) + "\n")
print(f"Run receipt: {out / 'run.json'}")
print("Per-position rows are available as <name>-kld.json.rows; replay severe positions with "
"tests/spark25_kld_tail.py. These are top-128-plus-tail KL values, not full-vocabulary KL.")
return 0
if __name__ == "__main__":
sys.exit(main())
+71
View File
@@ -0,0 +1,71 @@
/* Regression tests for the shipped Spark IQ8R recipe allocations. */
#include "rad_test.h"
#include "format/recipe.h"
#include <cstdlib>
#include <fstream>
#include <map>
#include <sstream>
using namespace rad;
static bool load_recipe(const char* name, Recipe* recipe) {
const std::string path = std::string(RAD_SPARK25_RECIPE_DIR) + "/" + name;
std::ifstream in(path);
if (!in) return false;
std::ostringstream text;
text << in.rdbuf();
std::string why;
return recipe->add_text(text.str(), path, &why) == RAD_OK;
}
static std::string option(const RecipeRule& rule, const std::string& key) {
for (const auto& [k, v] : rule.options)
if (k == key) return v;
return {};
}
static void check_iq8r_rule(const RecipeRule* rule, const char* quantizer, bool calibrated) {
REQUIRE(rule != nullptr);
CHECK_EQ(rule->quantizer, std::string(quantizer));
CHECK_EQ(option(*rule, "codes"), std::string("i8"));
CHECK_EQ(option(*rule, "group"), std::string("128"));
CHECK_EQ(option(*rule, "scale"), std::string("bf16"));
CHECK_EQ(option(*rule, "clamp"), std::string("sym"));
CHECK_EQ(option(*rule, "rule"), std::string("search"));
if (calibrated) {
CHECK_EQ(option(*rule, "transform"), std::string("fwht128"));
CHECK_EQ(option(*rule, "calib"), std::string("/test/spark-grams"));
} else {
CHECK(option(*rule, "transform").empty());
CHECK(option(*rule, "calib").empty());
}
}
TEST(spark_iq8r_recipes_allocate_the_quality_and_full_variants_explicitly) {
REQUIRE_EQ(::setenv("CALIB", "/test/spark-grams", 1), 0);
const char* projections[] = {"attn_q", "attn_k", "attn_v", "attn_output", "ffn_gate_up", "ffn_down"};
Recipe keep12, full;
REQUIRE(load_recipe("spark-x26-4b-iq8r-keep12.recipe", &keep12));
REQUIRE(load_recipe("spark-x26-4b-iq8r.recipe", &full));
for (int layer = 0; layer < 36; ++layer) {
for (const char* projection : projections) {
const std::string name = "blk." + std::to_string(layer) + "." + projection + ".weight";
const RecipeRule* hybrid = keep12.match(name);
if (layer < 12) {
CHECK(hybrid == nullptr); // unmatched tensors retain source BF16
} else {
check_iq8r_rule(hybrid, "gptq", true);
}
check_iq8r_rule(full.match(name), "gptq", true);
}
}
check_iq8r_rule(keep12.match("output.weight"), "rtn", false);
check_iq8r_rule(full.match("output.weight"), "rtn", false);
CHECK(keep12.match("blk.0.attn_gate.weight") == nullptr);
CHECK(keep12.match("token_embd.weight") == nullptr);
CHECK(full.match("blk.35.input_norm.weight") == nullptr);
}
RAD_TEST_MAIN()