Skip to content

quant: refuse non-finite values in Q8 quantizers - #597

Merged
juliankang4 merged 3 commits into
midagedev:mainfrom
juliankang4:fix-q8-nan-blocks
Oct 21, 2026
Merged

juliankang4 merged 3 commits into
midagedev:mainfrom
juliankang4:fix-q8-nan-blocks

Conversation

@juliankang4

Copy link
Copy Markdown
Collaborator

Q8_0, Q8_K, Q8_2_X4 양자화기와 MLA 활성값 양자화기가 NaN이나 무한대가 든 블록을 정상 블록처럼 만들어 내던 결함을, 최댓값 스캔과 곱수, 반올림 규칙의 공통 소유자로 모아 이름 있는 실패로 바꾸는 작업입니다.

Fixes #541.

What and why

quantize_q8_0 checked only the block length. f32::max ignores NaN, so a block of 32 NaNs had a maximum absolute value of 0 and came out as scale 0 with 32 zero codes. An infinity gave an inverse scale of 0 and the same zero codes. A model built from dequantized GGUF values (deepseek2::derived::build_block) would take that block as real data.

The same pattern sat in sibling encoders. The Q8_K and Q8_2_X4 roundtrips in gguf had no check at all, and the MLA activation quantizer quantize_act turned a block that mixed NaN with finite values into a normal scale and integer codes.

This PR gives the scan to one owner, gguf::quant::activation_max. IEEE 754 bits without the sign sort as finite, infinity, NaN, so the scan keeps a NaN as the maximum instead of dropping it. The strict > stays, so the first of several equal extremes keeps its sign. The finiteness check runs once per block after the scan. A failing block is read again to name the first non-finite value, its offset in the block and the block size. The qdot diagnostic that did this already moved to gguf, so the scalar and SIMD paths report the same way.

The scale rules had the same copy problem, so they have one owner in gguf::quant too. q80_inverse is the Q8_0 inverse scale (127 over the maximum), q82_inverse is the Q8_2 inverse scale (one over the bf16 scale), and fp32_to_bf16_bits and bf16_bits_to_f32 are the bf16 conversions. Both inverse scales become 0 when they overflow. qdot, the roundtrips and the MLA quantizer call them, and the private bf16 helper in the MLA code is gone. The roundtrips also use nearest_int and the same i8 saturation as the engine encoders.

A finite block of ordinary size gives the same output as before: the x86 rounding rule, the stored scale format, the code clamp and the Q8_K signed-maximum rule are unchanged.

Release notes: Fixed: Q8_0, Q8_K and Q8_2_X4 activation quantization and the DeepSeek MLA activation quantizer refuse NaN and infinite input with a named error instead of writing a zero or normal-looking block. The Q8_K and Q8_2 roundtrips and the MLA quantizer no longer return wrong values for blocks whose maximum is near the smallest normal float.

Code shape

  • No second copy. I searched crates/ for every place that turns floats into a Q8 block (table below). The seven scalar max scans in qdot now call the one owner, and the scale and bf16 rules each have one definition. The two GPU gates and a qdot test fixture call those owners too, for the plane packing, the bf16 conversion and the Q8_0 byte layout.
  • Model code holds only architecture facts. model::quant keeps its module comment and the re-export of the Q8_0 function. The MLA quantizer calls the owners.
  • Dead code is gone. The duplicate f16 conversion and rounding helpers and the local word packing in gate_p3.rs are removed, and so are the bf16 rounding copy in gate_dspark_hc.rs, the Q8_0 byte writer in a qdot test fixture and a model::quant test module that only retested the re-export. A dated PIN names the owner that now carries that test.
  • No silent failure. A non-finite value is a named panic, the same policy as the existing qdot activation quantizer. No return type changed, so no caller can receive a substitute block.
  • Comments state what is true now. The nearest_int documentation lives on its gguf definition only.
  • No relaxed gate. No band, tolerance or lint moved. The rounding mutant under tools/mutants/quant_host_qdot now targets nearest_int in gguf.
  • Hot path. A normal block gets no extra scan, allocation, log or lock.
  • cargo fmt, git diff --check and tools/dup-scan.py ran on this code.

Every path that makes a Q8 block from floats

Function Non-finite input before this PR What this PR does
gguf/src/quant.rs quantize_row_q8_k_roundtrip no check, all NaN gave a zero block refuses through the owner, rounds with nearest_int
gguf/src/quant.rs quantize_row_q8_2_x4_roundtrip no check, NaN lost in the maximum refuses through the owner, uses q82_inverse, the shared bf16 conversion and i8 saturation
gguf/src/quant.rs quantize_q8_0 and quantize_row_q8_0_roundtrip NaN became a zero block refuses through the owner, uses q80_inverse
gguf/src/quant.rs quantize_activations dispatches to the three above all three paths are covered, the F32 and F16 copies make no scale
gguf/src/quant.rs Q8Block::quantize_ref already returns None kept, it is the weight-file rule with its own scale and rounding
model/src/arch/deepseek2/attn.rs quantize_act no check, NaN became integer 0 refuses through the owner for both callers, q_nope2_absorbed and quantize_q_nope, and uses q82_inverse
model/src/quant.rs re-export of Q8_0 unchanged
qdot/src/lib.rs quantize_q8k_block, quantize_q82x4_col (groups and tail), quantize_q8f0_col named panic per value one scan per block from the owner, scale rules from gguf
qdot/src/lib.rs AVX2 Q8_K and 32-value blocks NaN mask and maximum check judgment kept, diagnostic from the owner
qdot/src/lib.rs AVX2 Q8_2 and Q8_0 columns call the block owners above unchanged
qdot/src/generic.rs Entry::quantize calls the scalar and SIMD owners covered by the same change
qdot/src/lib.rs card_q8_1_fill_scalar and card_q8_1_fill_avx2 refused flag, NaN scale, zero codes kept, a separate fault contract that never returns a normal block
gpu-gates/src/bin/gate_p3.rs quant_q8_0_row copy of the old Q8_0 code and its own word packing uses the shared block encoder and bloomery_gpu::weights::q8_0_planes for the word and scale layout
gpu-gates/src/bin/gate_dspark_hc.rs q8_0_rows NaN became zero codes uses the owner and the existing q8_0_planes
gpu-gates/src/bin/gate_dspark_hc.rs bf16_round local bf16 bit rounding calls the two gguf bf16 conversions
qdot/tests/qdot.rs q8f0_block local Q8_0 byte writer calls Q8Block::to_bytes
gpu/src/rope_neox.rs q8_block_warp already faults through FaultSite::KvQuant unchanged

ik_q8_2::quantize and act_rule::quantize_q8_k already call refuse_non_finite. The float comparison oracles (q8_1_dequant, gate_p2::q8_hat, exact_ref::Act::round) keep NaN in their float output on purpose. This survey covers the CPU activation encoders. It is not an audit of every CUDA format.

Two kinds of finite input change. A block whose inverse scale overflows becomes a zero block, which is what the qdot activation quantizer already did. A roundtrip code of integer 0 comes back as an unsigned 0.

The third change fixes the small-block defect in the roundtrips and the MLA quantizer. For a block whose maximum is below about 2^-121, the Q8_K roundtrip returned NaN, the Q8_2 roundtrip returned nonzero values where the engine encoder gives 0, a bf16 scale that rounded down gave code 128 where the engine saturates to 127, and the MLA quantizer gave codes of -127 whatever the sign. These blocks now give 0 or 127 times the scale, as the engine encoders do.

What I ran

The head of this PR is 206e207e0 on upstream e04ed9683. The GPU and owner checks below ran on 67392618e on upstream 74240f50, and the three commits of the two heads are the same changes (git range-diff shows each pair equal, through 407550f2e on 3b1236e8), so those results carry over. The CPU test results are from cc7bcdf9b.

Before the fix, the new tests were added on the unfixed code. The gguf test activation_roundtrips_refuse_non_finite_blocks and the model test activation_blocks_refuse_non_finite_values both exit with rc 101. The gguf test collects the non-finite inputs that Q8_K and Q8_2_X4 accepted. The MLA test gets a normal scale and integer codes back for a block that mixes NaN with finite values. On the unfixed Q8_0 function, 32 NaNs give d=0 and 32 zero codes, and a block with one infinity gives d=31744 and zero codes. A normal block of 127.0 gives d=15360 and codes of 127.

After the fix, on an x86 Linux machine at cc7bcdf9b:

cargo test -p bloomery-gguf --lib activation_roundtrips_refuse_non_finite_blocks
cargo test -p bloomery-model --lib activation_blocks_refuse_non_finite_values
cargo test -p bloomery-qdot --test qdot

Both targeted tests pass (1 passed, 0 failed). The whole qdot test target passes with 33 passed and 61 ignored, and the ignored hw_q82_codes_at_bf16_round_down test passes on AVX2. bloomery-gguf --lib passes with 43 tests and the deepseek2 tests of bloomery-model with 6.

I then reverted six boundaries one at a time to the rule they had before this PR: the Q8_K roundtrip rounding, the Q8_2 roundtrip multiplier, the Q8_2 roundtrip saturation, the q82_inverse overflow check, the q80_inverse overflow check and the MLA multiplier. All 6 made the tests fail with rc 101, and the source was restored afterwards.

The moved rounding mutant ran through tools/mutant-run.sh with --crate bloomery-gguf and the qdot and generic test targets. It reports mut-01-rounding rc=101 killed, the clean run is green, and the summary is 1 mutant, 1 killed, PASS.

I did not run the full model or gpu-gates suites on this head. The arithmetic for finite blocks of ordinary size did not change in the last commit, and I do not claim a full-suite result for it.

The two gate_* binaries are in a device crate, so I ran them on DGX Spark machines with GB10 cards. The checks below ran at 67392618e. A debug build of the GPU crates stopped in codegen on an atomic ordering in mamba2, so these runs use the release profile.

GPU evidence

Raw nvidia-smi lines from the cards that ran the checks:

| NVIDIA-SMI 595.84                 Driver Version: 595.84         CUDA Version: 13.2     |
|   0  NVIDIA GB10                    On  |   0000000F:01:00.0 Off |                  N/A |
  • BLOOMERY_REF_MODEL=<path to DeepSeek-V2-Lite-Chat-Q3_K_M.gguf> BLOOMERY_BOX_LOCAL=1 BLOOMERY_ARCH=sm_121 just gate-gpu-p3 on a DGX Spark exited with rc 0. The host fixture test reports 1 passed; 0 failed. All 8 F32 rows and all 8 Q8_0 rows are inside the 1e-5 band, the four Q8_0 graph replays are bit-identical with nodes=1, and the gate ends with PASSED: f32 and q8_0 gemv within 1e-5 of the f64 reference; eager == graph replay.
  • The gate reads the F32 router of DeepSeek-V2-Lite-Chat-Q3_K_M.gguf from second-state/DeepSeek-V2-Lite-Chat-GGUF at revision fbba16c9ee1ba016b0ab083938acb7be061f970f, SHA256 17c1b1c347222101f5bfce551c5ec6807cd81bcf0303b7c183948621dc4aa7d4.
  • BLOOMERY_BOX_LOCAL=1 BLOOMERY_ARCH=sm_121 bash tools/gate.sh --oxide -p bloomery-gpu-gates --release --features deepseek41 --bin gate_dspark_hc on a DGX Spark, the host test step of the gate-gpu-dspark-hc recipe, exited with rc 0 and q8_0_fixture_refuses_non_finite_blocks ... ok, 1 passed; 0 failed.
  • just gate-gpu-dspark-hc not run: the real DSpark draft and its reference sets are not available on this machine.
  • BLOOMERY_BOX_LOCAL=1 BLOOMERY_ARCH=sm_86 just canon-check 74240f50954cd96882407c99b44bcd9a33694750 on a DGX Spark exited with rc 0: 3 bins, 964 entries: 964 identical, 0 reordered-only, 0 differs, 0 only-on-one-side. The tool compares sm_86 builds, so this build targets sm_86 on the GB10. It shows that the device code of the two gates' kernels is unchanged.
  • On a Linux CPU host, replacing the owners that the P3 gate, the HC gate, the qdot fixture and the bf16 helper now call with a byte-swapping or truncating variant made each of their tests exit with rc 101, and the clean source exited with rc 0 in all four checks. The old local copies passed the same variants with rc 0.

What I ran into

This does not block the PR. Two existing CCD placement tests in the model lib need at least 8 threads and a particular lane layout, so a full model lib run needs BLOOMERY_THREADS=8.

Hardware

One x86 Linux machine for the unit tests and mutants. DGX Spark machines (GB10, driver 595.84, CUDA 13.2) for the CUDA builds and host tests.

AI help

AI 코딩 에이전트가 코드를 작성한 후 설명을 썼고, 테스트를 마쳤습니다. diff 리뷰와 PR 초안 리뷰는 제가 직접 했습니다.

…rounding

The q8_0 and q8_2 code multipliers (q80_inverse, q82_inverse) and the bf16
scale conversions move from qdot to gguf::quant beside nearest_int, so the
f32 round trips, the MLA activation quantizer and qdot's scalar and AVX2
encoders read one rule. The Q8_K and Q8_2 round trips code through
nearest_int with the encoders' i8 wrap and saturation: a block whose
multiplier overflows now restores to zero instead of infinity or NaN, and a
subnormal bf16 scale saturates its code at 127 as the encoders do.

The rounding mutant targets nearest_int at its new home.
@github-actions github-actions Bot added gpu The card engine: crates/gpu*, crates/app host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja needs-gpu Changes code a card must check, and carries no gate run on a card tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo labels Oct 21, 2026

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Verdict: CLEAN: The shared quantizers reject non-finite blocks, and no must-fix defect was found.

Checked

Duplicates: 8 introduced or relocated production definitions and 4 new tests checked. The diff removes local copies of scanning, scale, rounding, bf16 conversion and packing rules.
Complexity: the shared maximum scan has one loop, one update branch and one refusal branch.
Silent failure: the changed Q8 roundtrips, scalar qdot encoders and MLA quantizer reject non-finite blocks through the shared owner. Finite multiplier overflow follows the existing qdot encoder rules.
Tests: static mutation reasoning covers all 6 added or changed tests. Removing rejection at crates/gguf/src/quant.rs:1528 would fail the gguf and scalar qdot refusal assertions. Bypassing the scan at crates/model/src/arch/deepseek2/attn.rs:509 would fail the MLA assertion. Reversing packing at crates/gpu/src/weights.rs:1685 would fail both gate fixtures. Swapping scale bytes at crates/gguf/src/quant.rs:1790 would fail the qdot test against its fixed mainline byte fixture.
Gates: no thresholds or lint levels moved. The PR reports FAIL-first rejection tests and a killed rounding mutant.
Escape catalog: no C1–C4 pattern matched. The added recipe commands propagate failures through &&.
Adversarial checks: the magnitude-bit scan retains NaN and infinity among finite values and preserves the first signed maximum on ties. Added assertions cover tiny scales and incomplete GPU fixture blocks.
Performance: decode/prefill activation encoding adds no allocation, lock, device launch or transfer. New fixture allocations run outside the engine hot path.

Notes

Rust tests and GPU gates were not run during this read-only review. The PR reports P3 GPU and HC fixture results on GB10. The full HC gate was not run because its draft and reference sets were unavailable.

Card check: gpu-evidence. This pull request changes crates/gpu-gates/src/bin/gate_dspark_hc.rs, crates/gpu-gates/src/bin/gate_p3.rs and carries a gate run on the author's card, which counts as verified.

🔨 Shingler, bloomery's review bot: approves a clean pull request and requests changes on a must-fix (how it works)

@github-actions github-actions Bot added gpu-evidence Verified on the author's card: the pull request carries the gate run and its output and removed needs-gpu Changes code a card must check, and carries no gate run on a card labels Oct 21, 2026
@juliankang4

Copy link
Copy Markdown
Collaborator Author

The review is done and the contribution check passed, so I'm merging this.

@juliankang4
juliankang4 merged commit f956b65 into midagedev:main Oct 21, 2026
6 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

gpu The card engine: crates/gpu*, crates/app gpu-evidence Verified on the author's card: the pull request carries the gate run and its output host Host crates: qdot, threads, engram, engram-lab, runtime, sampler, levers, decision, vision, refset model The CPU engine and model files: crates/model, models, hf, gguf, tokenizer, jinja tools Tools, recipes, CI and the toolchain: tools/, justfile, .github/, Cargo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

model/quant: NaN inputs become valid Q8_0 blocks

1 participant