Skip to content

Quantize in u32 so exact reciprocals cannot overflow - #1

Merged
telecos merged 6 commits into
telecos:feat/exact-quantizationfrom
sunsided:feature/exact-quantization-u32
Nov 23, 2026
Merged

telecos merged 6 commits into
telecos:feat/exact-quantizationfrom
sunsided:feature/exact-quantization-u32

Conversation

@sunsided

Copy link
Copy Markdown

Stacked on vstroebel#44, so it can be folded into that PR.

With the variable shift from compute_reciprocal_exact, the reciprocal keeps 16 significant bits, so (|v| + correction) * reciprocal in QuantizationTable::quantize can exceed i32::MAX. For divisor 1032 and |v| = 32768 the product is about 2.16e9. In i32 this panics in debug builds ("attempt to multiply with overflow") and wraps in release builds: -32768 / 1032 quantizes to +32 instead of -32.

Real FDCT output stays well below |v| = 32768, so this is unlikely to show up in images. But quantize takes any i16, and the debug panic is easy to reach from a test.

Change

  • Store reciprocals / corrections as u32 and do the multiply and shift in u32. The product stays below ~2^31.3 for every divisor Custom can produce (up to 2048 << 3 on main).
  • The default 15-bit path produces the same results as before.

Test

test_quantize_exact_all_divisors_all_values: for every Custom divisor (t << 3, t in 1..=2048) and every i16, exact quantization equals round-half-up division with the sign restored. On a9ad83f it fails in debug (overflow panic) and in release (divisor=1032, val=-32768: left 32, right -32). With this commit it passes.

cargo fmt --check and cargo test pass with --features simd, with --features use_wide, with --no-default-features --tests, and in --release, also on 1.89.

With the variable shift from `compute_reciprocal_exact`, the reciprocal
keeps 16 significant bits, so `(|v| + correction) * reciprocal` can
exceed i32::MAX: for divisor 1032 and |v| = 32768 it is ~2.16e9. In i32
that panics in debug builds and wraps in release, where -32768 / 1032
quantized to +32 instead of -32.

Store reciprocals and corrections as u32 and do the multiply and shift
in u32; the product stays below ~2^31.3 for every divisor `Custom` can
produce. The 15-bit default path gives the same results as before.

Adds an exhaustive test: for every `Custom` divisor (t << 3, t in
1..=2048) and every i16, exact quantization equals round-half-up
division with the sign restored.
The benchmark feature re-exports fdct and fdct_avx2, but both take
&mut AlignedBlock, which was pub(crate). Nothing outside the crate could
call them, and criterion/benches/fdct.rs did not compile because it
passed a plain [i16; 64].

Make AlignedBlock pub and re-export it only with `benchmark`; the
encoder module stays private, so the normal public API is unchanged.
The fdct bench now wraps its input in AlignedBlock::new.
avx2_matches_scalar asserts that fdct_avx2 and RgbImageAVX2 produce
exactly the same output as fdct and RgbImage. FDCT input is
level-shifted bytes (-128..=127), the range the encoder feeds it; the
RGB part is a single row of arbitrary width so both the vector body and
the remainder are hit. The target returns early without AVX2, since the
AVX2 entry points do not check for it themselves.

With the AVX2 FDCT from before ffbfcdb restored, the target reports an
fdct mismatch within 60 seconds. The fuzz crate now enables the
benchmark feature to reach these internals.
`a as u16 + (b as u16) << 8` parses as `(a + b) << 8`, so every fuzzed
table entry was a multiple of 256 and small divisors were never tried.
Decode entries with u16::from_le_bytes instead.

Byte 128 of the input now toggles set_exact_quantization, so the u32
exact-reciprocal path gets fuzzed with arbitrary Custom tables. Pixels
start at byte 129; existing corpora are still valid input, just
reinterpreted.
The fuzz targets were never built in CI, so they could rot unnoticed.
A new fuzz job installs nightly and cargo-fuzz, builds every target, and
runs avx2_matches_scalar for 60 seconds to catch AVX2/scalar mismatches
on GitHub's AVX2-capable runners.
encode_roundtrip lets the fuzzer pick every encoder setting from an
8-byte header: color type, quality, sampling factor, optimized Huffman
tables, exact quantization, average subsampling, progressive mode with
2..=64 scans, restart interval and width. When encoding succeeds, the
output must decode with jpeg-decoder to the same dimensions, pixel
format and buffer length. Pixel values are not compared, since
arbitrary input has no meaningful error bound.

On main it currently finds two known bugs within minutes: progressive
scan counts of 34..=64 write an empty AC range (fixed by vstroebel#47), and
optimized Huffman tables with a restart interval miss the DC prediction
reset (fixed by vstroebel#42). With both applied, 589k runs pass. CI builds the
target but does not run it until those land.

@telecos telecos left a comment

Copy link
Copy Markdown
Owner

Choose a reason for hiding this comment

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

LGTM. Thanks!

@telecos
telecos merged commit 4355804 into telecos:feat/exact-quantization Nov 23, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants