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

@@ -0,0 +1,158 @@
# Quality-preferred tested allocation for Spark X2.6 4B.
# Keep layers 0..11 in source BF16; fit the six projections in layers 12..35 to IQ8R.
# The ordered recipe glob syntax has no exclusions, so the 144 layer/projection rules below
# explicitly begin at layer 12. Unmatched weights keep their checkpoint encoding.
# The tied output head remains RTN-quantized; the small attention gate and other non-target
# tensors remain BF16/FP32 as described in docs/ARCHITECTURES.md.
#
# Reproduce from the BF16 checkpoint with the published RADGRAM2 calibration directory:
# CALIB=/path/to/grams rad-convert /path/to/XHToken-Spark-X2.6-4B \
# --recipe data/recipes/spark-x26-4b-iq8r-keep12.recipe \
# --set quantization_config.quant_method=w8a8 \
# --set quantization_config.fmt=fwht128 -o spark-x2.6-4b-iq8r-keep12.rad
# This is a tested allocation, not a universal task-quality guarantee.
blk.12.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.12.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.12.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.12.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.12.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.12.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.13.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.13.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.13.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.13.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.13.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.13.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.14.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.14.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.14.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.14.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.14.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.14.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.15.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.15.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.15.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.15.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.15.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.15.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.16.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.16.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.16.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.16.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.16.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.16.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.17.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.17.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.17.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.17.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.17.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.17.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.18.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.18.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.18.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.18.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.18.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.18.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.19.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.19.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.19.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.19.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.19.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.19.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.20.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.20.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.20.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.20.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.20.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.20.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.21.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.21.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.21.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.21.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.21.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.21.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.22.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.22.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.22.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.22.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.22.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.22.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.23.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.23.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.23.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.23.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.23.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.23.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.24.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.24.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.24.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.24.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.24.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.24.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.25.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.25.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.25.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.25.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.25.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.25.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.26.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.26.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.26.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.26.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.26.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.26.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.27.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.27.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.27.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.27.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.27.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.27.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.28.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.28.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.28.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.28.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.28.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.28.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.29.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.29.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.29.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.29.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.29.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.29.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.30.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.30.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.30.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.30.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.30.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.30.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.31.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.31.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.31.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.31.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.31.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.31.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.32.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.32.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.32.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.32.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.32.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.32.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.33.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.33.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.33.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.33.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.33.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.33.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.34.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.34.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.34.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.34.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.34.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.34.ffn_down.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.35.attn_q.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.35.attn_k.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.35.attn_v.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.35.attn_output.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.35.ffn_gate_up.weight gptq codes=i8 group=128 scale=bf16 transform=fwht128 clamp=sym rule=search calib=$CALIB
blk.35.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
+4 -2
View File
@@ -1,5 +1,7 @@
# 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
# Full, opt-in speed/size variant for Spark X2.6 4B (Spark2_5ForCausalLM) on IQ8R's rotated int8 grid.
# For the tested quality-preferred allocation retaining layers 0..11 in BF16, use
# spark-x26-4b-iq8r-keep12.recipe instead. Neither allocation guarantees task quality for every use.
# Every trunk linear rotated by fwht128 and fitted by GPTQ against 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.
#
+29 -16
View File
@@ -123,24 +123,37 @@ DSpark, other gate activations and rotary-scaling overrides are not implemented.
`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.
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`.
`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.
The full recipe, `data/recipes/spark-x26-4b-iq8r.recipe`, is an explicit speed/size tradeoff, not a
quality-preferred default. `data/recipes/spark-x26-4b-iq8r-keep12.recipe` leaves layers 0–11 in
BF16 and is the tested quality-preferred allocation (6.09 GB / 5.67 GiB). The full IQ8R container
is 4.52 GiB; BF16 is 8.29 GiB. The measured comparison used top-128-plus-tail KL, with the full
variant's maximum 11.883 and keep12's maximum 0.247 over 31,391 held-out positions. These are
coarsened distribution-parity measurements, not full-vocabulary KL or task-benchmark scores. The
source revision and replay commands, tail details, hashes, calibration/evaluation provenance, and
limits are in [`SPARK25-IQ8R.md`](SPARK25-IQ8R.md). The cited numbers require the shared prefill
softmax fix #362 (`7480da3d46b0475d9d77966e31284cc19072759`); they are not evidence for standalone
#363 without that prerequisite.
`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.
The BF16 plugin records the calibration Grams with `RADIANCE_CALIB_DIR`, `RADIANCE_CALIB_TOKENS`,
and `RADIANCE_SPARK_CALIB_LAYERS=lo:hi`; use TP=1 to retain off-diagonal cross-rank terms. Drive
a representative corpus through prefill with prefix caching and speculation disabled. Each layer
slice writes six RADGRAM2 files. The published calibration manifest and dataset revision are
recorded in [`SPARK25-IQ8R.md`](SPARK25-IQ8R.md); calibration completeness is not a measure of
quality.
A column-sharded input must have a 128-column-aligned offset and width. When possible, FFN sharding
partitions whole 128-channel groups with a ragged remainder-first split. Spark's 10,240-channel FFN
has 80 groups, so TP=3 gets 27/27/26 groups and is aligned; TP=3 is not inherently refused. The
architecture rejects a particular computed span only if it is not group-aligned. Actual serving
also requires the selected kernels and collectives to support the world size. `tests/spark25_iq8r.py`
compares a deterministic quantised fixture with the Transformers reference, including top-10
probabilities across cached decoding; `--wide-tp --tp N` checks aligned attention/FFN shards for
N=1..8. Use a GPU-denying device cgroup for this CPU fixture on shared machines.
For a CPU differential against the reference implementation's `configuration_spark.py` and
`modeling_spark.py`, with Python's torch, transformers and safetensors installed:
+152
View File
@@ -0,0 +1,152 @@
# Spark X2.6 4B IQ8R: recipes, provenance, and validation
`arch/spark25_w8a8` serves Spark X2.6's six dense projections per layer on the `fwht128` rotated
int8 grid. It requires `quantization_config.quant_method=w8a8` and
`quantization_config.fmt=fwht128`; activations use `had_quant_act_i8g` and weights use `gemm_nt_q`
with `dtype=i8a8h`. The embedding and small per-head attention gate stay BF16; norm gains stay
FP32. Calibration is TP=1 so the Gram matrices retain cross-rank terms.
## Recipe choice
The container format does not choose a recipe or change a launcher default. Select one explicitly
when converting a BF16 source checkpoint:
| Allocation | Recipe | Published container size | Measured distribution parity | Performance note |
|---|---|---:|---|---|
| Quality-preferred tested hybrid | `data/recipes/spark-x26-4b-iq8r-keep12.recipe` | 5.67 GiB (6,092,100,608 bytes) | 99.111% top-1 agreement; top-128-plus-tail KL mean 0.000677, p99 0.00923, p99.9 0.04013, max 0.24712 | About 12% less prefill and 17% less decode throughput than full IQ8R in the reported single-card comparison |
| Full IQ8R, explicit speed/size tradeoff | `data/recipes/spark-x26-4b-iq8r.recipe` | 4.52 GiB (4,853,470,208 bytes) | 98.595% top-1 agreement; top-128-plus-tail KL mean 0.004077, p99 0.04960, p99.9 0.34814, max 11.8832; 13 positions exceed 1 nat | Prefill 11.8k / 11.8k / 11.3k tok/s at 1.1k / 4.4k / 9.9k-token prompts; decode 93.7 tok/s at short context and 88.9 tok/s at 4.4k context |
| Source BF16 | no recipe | 8.29 GiB | reference | Baseline |
For the keep12 allocation, six explicit rules cover each projection in layers 12–35. Layers 0–11
have no matching rule and retain their BF16 checkpoint encoding. The output head remains RTN in both
IQ8R recipes; unmatched tensors (including the embedding and attention gate) retain their source
encoding. The full recipe is not quality-preferred and is not applied implicitly. Neither measured
allocation establishes task accuracy or universal quality for all prompts and uses.
The reported KLD values above are **not exact full-vocabulary KL**. They use Radiance's sparse
`--kld-top 128` form: the reference's top 128 token probabilities plus one bucket for all remaining
probability mass, compared with the candidate on the same coarsened support. The 31,391 positions
are from a 32-document held-out evaluation; the keep12 maximum is below one nat on this set, not a
claim about all inputs. Perplexity ratios were 1.00178 (keep12) and 1.00409 (full IQ8R).
## Calibration and evaluation provenance
The published calibration dataset is
[`gostar77/spark-x2.6-4b-iq8r-calibration`](https://huggingface.co/datasets/gostar77/spark-x2.6-4b-iq8r-calibration),
revision `4b622fa2ecca376a02a83ef23ec6dfb3b7cdc52b`. Its `CALIBRATION-MANIFEST.json` records
Spark X2.6 4B, `RADGRAM2`, TP=1, all 36 layers and six projection types. It contains 216 validated
Gram files (21,290,294,016 bytes; about 19.83 GiB) accumulated over 65,660 tokens. The prompts
were 100 selected document beginnings from `swift15-public-corpus`, with selection seed `20261031`
and every fourth candidate wrapped in the Spark chat format. The published dataset is CC BY-SA 4.0;
its `SHA256SUMS` covers the Gram files. The local manifest used for this record is
`/mnt/gostar_data/radiance-builds/hf-publish/spark-x2.6-4b-iq8r-calibration/CALIBRATION-MANIFEST.json`
(SHA-256 `f2225de42cfc885dca2720128143487296a5ba8c33cc797de0bac2b2bcebf007`); its local
`SHA256SUMS` has SHA-256 `f8d14fc575875e33045c2231013e87da52da8db4e21f692c363464d858dbbb18`.
The evaluation manifest is
`/mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/independent-chat-eval.manifest.json`
(SHA-256 `a8528f193986b7267b7ec5b5a447c0d1f5271d5c2f7f004ceb8ba543e5168f4d`). It identifies a
separate held-out source file, `/mnt/gostar_data/radiance-calib/qwen3.8-flash-next-base-w5dn64/corpus/heldout.jsonl`
(source SHA-256 `2c3935512dbf0b09c8fea88be19f7d31447a540de57133a54f97e6e172f15532`), selection seed
`7132026`, and 8 examples each from tools, math, prose, and code. Two high-overlap candidates were
excluded; the manifest describes a sampled 20-gram overlap check against the 100 diverse calibration
documents and the original nine. That check is not proof of zero semantic overlap. Math/tool rows
score assistant continuations; prose/code rows score text after 32 tokens. The resulting local KLD
corpus is `/mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/independent-chat-eval.jsonl`
(SHA-256 `468d9c6037a17475688ba432d804618c10d15288b4d5fe538b7ac4c0ab725ace`).
The recorded matched-reference artifacts are local and were not copied into this repository:
- BF16 sparse reference: `/mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/rowfix-bf16-ref128/`
(`kld.json` SHA-256 `b722b8a956b747dd932413204d9ae0775bd2bd50377f0466134cc922ad83b026`).
- Full IQ8R report and per-row file: `rowfix-diverse-kld.json` and
`rowfix-diverse-kld.json.rows` (report SHA-256
`0f7368c83a3c9a896aa42bcbdf8022db526517f7fc4a9e680747ccd2b66bdee9`).
- Keep12 report and per-row file: `rowfix-keep12-kld.json` and
`rowfix-keep12-kld.json.rows` (report SHA-256
`d6b577c1e6f7fc5c40814744bea22079998562229eaa2b2a892274544a149dbf`).
- Reference KLD metadata records 31,391 positions and corpus FNV-1a `17d9069a2711c745`; candidate
`.rows` files contain one row per scored position (KL, candidate NLL, reference NLL, top-1 match).
The measured rowfix comparison used Radiance source commit `54f2602367eb96ca08674095f7e32506fd7d752b`
(the build tree points to `/mnt/gostar_data/radiance-worktrees/spark-x2-6`), `libr4d@0.5.0`, TP=1,
BF16 KV, `--max-model-len 4096`, `--max-num-seqs 1`, `--max-num-batched-tokens 128`, no speculation,
and prefix cache disabled. The prerequisite shared prefill correction is #362,
`7480da3d46b0475d9d77966e31284cc19072759`. **Those parity figures are for the tree with #362**;
#363's original `5024aea` ancestry did not contain it. Do not attribute these numbers to standalone
#363 or to a build without #362. A fresh GPU TP2 validation is separate and remains outstanding.
Published container checksums from `/mnt/gostar_data/radiance-builds/hf-publish/SHA256SUMS`
(SHA-256 `3c14ea79cb8b7b3aba8807dd43101aa84110636e914eb2008eb2ba3a387e3d1b`):
| Container | SHA-256 |
|---|---|
| `spark-x2.6-4b-radiance-bf16.rad` | `39694f258a3bb1e8367690a5d26762061226f3166125e929c6e33a4981583b6c` |
| `spark-x2.6-4b-radiance-iq8r-diverse.rad` | `2f6982f12b43d1e7621326c5c05a3764ef62defbbd4f59c708f9db698a14b0e5` |
| `spark-x2.6-4b-radiance-iq8r-keep12.rad` | `5a12f1f4c6cb1b2a545344bcb800cd829dc53de6cefa7a6bd9d4e2ed9fee2740` |
## Sharding alignment
A shard must own whole 128-column scale groups for a column-sharded IQ8R input; the architecture
rejects any computed span whose count is not group-aligned. It splits the FFN in whole 128-channel
units when the model width permits, using a ragged remainder-first partition. For Spark's
10,240-channel FFN there are 80 such units: TP=3 gets 27, 27, and 26 groups (3,456, 3,456, and
3,328 channels), all aligned. TP=3 is **not** categorically unaligned or unsupported. The synthetic
wide fixture checks TP=1..8; actual device support still depends on the selected kernel library and
required collectives. Calibration itself remains TP=1.
## Reproduce matched KLD and tail replays
Use a private output directory; the reference is immutable once `kld.json` is written. The harness
hashes the checkpoint, executable, corpus, evaluation manifest, loaded kernel shared objects, and
optional source revision into `run.json`. It replays the same corpus against BF16 once and scores
each candidate against that reference, with fixed chunking/cache/TP flags:
```sh
python3 tests/spark25_quality.py \\
--radiance "$BUILD/bin/radiance" --home "$BUILD/radiance_home" \\
--reference "$BF16" \\
--corpus /mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/independent-chat-eval.jsonl \\
--provenance /mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/independent-chat-eval.manifest.json \\
--calibration-manifest /mnt/gostar_data/radiance-builds/hf-publish/spark-x2.6-4b-iq8r-calibration/CALIBRATION-MANIFEST.json \\
--source-root "$PWD" --out "$RUN" \\
--candidate "full=$FULL_IQ8R" --candidate "keep12=$KEEP12"
```
Run that process inside the host's exclusive GPU/device scope for `libr4d`. For one of the candidate
reports, start that same model as a server with TP=1, BF16 KV, `--max-model-len 4096`,
`--max-num-seqs 1`, `--max-num-batched-tokens 128`, `--num-speculative-tokens 0`, and
`--no-prefix-cache`. Then replay the highest-KL rows with their exact token prefixes from the BF16
reference (the tool checks the server consumed every prefix token):
```sh
python3 tests/spark25_kld_tail.py \\
--reference "$RUN/bf16-top128-ref" --report "$RUN/full-kld.json" \\
--url http://127.0.0.1:5914 --model spark --out "$RUN/full-tail-replay.json"
```
The replay compares candidate top-20 log-probabilities with the stored reference top-20 for the
selected rows. The full corpus KLD report remains the top-128-plus-tail metric; top-20 replay is a
focused diagnostic, not a replacement for the full evaluation.
## Reproducible serving QoS smoke
Run this separately for each model, one process/container at a time and under an exclusive device
scope. It reuses the same evaluation prompts, disables prefix caching and speculation, and stores
per-request latency plus p50/p95/max and aggregate generated-token throughput at each concurrency.
These are end-to-end request measurements (prefill plus decode and service overhead), not decode-only
throughput or task scores:
```sh
python3 tests/spark25_qos.py \\
--radiance "$BUILD/bin/radiance" --home "$BUILD/radiance_home" \\
--model "$KEEP12" \\
--prompts /mnt/gostar_data/radiance-builds/spark-x2-6-iq8r/independent-chat-eval.jsonl \\
--source-root "$PWD" --out "$RUN/keep12-qos" \\
--concurrency 1,4,8 --requests 16 --repeats 3 --max-tokens 32
```
Use identical flags, prompt file and `RADIANCE_HOME` for BF16 and full IQ8R; run them sequentially
on the same device allocation. This smoke is a reproducible validation command, not a completed
concurrent/long-context QoS certification. The held-out distribution comparison is not an external
benchmark and does not establish universal model quality.
+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()