Skip to content

shader_library: 9-bit canonical Huffman LUT and 64-bit BitReader refill (PERF-ZLIB-HUFFMAN-LUT) - #9566

Closed
iliassgm wants to merge 2 commits into
ProjectLeonida:mainfrom
iliassgm:perf/zlib-huffman-lut
Closed

iliassgm wants to merge 2 commits into
ProjectLeonida:mainfrom
iliassgm:perf/zlib-huffman-lut

Conversation

@iliassgm

Copy link
Copy Markdown
Contributor

Claimed in the coordination issue as: PERF-ZLIB-HUFFMAN-LUT.

What and why

leonida::zlib_inflate (runtime/src/shader_library.h) runs on every FSSM shader container extraction (50k+ CreatePipelineState calls at boot) and on DirectStorage zlib streaming (#7180). Previously, detail::decode pulled one bit at a time through BitReader::bits(1) (up to 15 iterations per literal/length/distance symbol), and BitReader refilled one byte at a time.

This PR speeds up Huffman decoding without changing the public API, output bytes, error rejection, or overlapping #8682 (Adler-32 batching) or #8942 (stored/match bulk copies):

  • 64-bit fast refill in detail::BitReader: fill() loads up to 56..63 bits in one little-endian 8-byte memcpy (with a portable byte-loop tail near EOF and on big-endian hosts), keeping bits >= count_ zero so peek()/drop() work directly from the bit buffer. position() returns pos_ - count_ / 8 and align() rewinds pos_ -= count_ / 8 before clearing the buffer, preserving exact trailer and stored-block offsets.
  • Dynamic-width canonical Huffman lookup table (<= 9 bits) in detail::Huffman / build_huffman: sizes fast_bits = min(max_len, 9) (so 5-bit distance and small code-length tables touch only 32..128 entries instead of 512) and fills LSB-first reversed slots using a static constexpr 4-bit nibble reversal table (zero function-local dynamic static / TLS-0 guards).
  • Fast lookup + register slow path in detail::decode: 1..9-bit canonical codes resolve in one lookup and drop (checking len <= available() at EOF). Codes of length 10..15 and unassigned/empty tables fall through to a register-based canonical scan over peek() that produces identical symbols and failure states.

Benchmarks (Windows 11 x64, Intel Core i5-10400F, MSVC 19.44 /O2, synthetic inputs only)

Benchmark Before (upstream/main) After Speedup
Pure detail::decode (21.48M syms, 2..11-bit codes) 248.37 ms (86.5 Msym/s) 97.23 ms (220.9 Msym/s) 2.55×
zlib_inflate Z_HUFFMAN_ONLY 512 KiB (incl. unbatched Adler-32) 12.590 ms (39.71 MiB/s) 5.169 ms (96.73 MiB/s) 2.44×
zlib_inflate 4 KiB dynamic (shader-like, 2000 reps) 0.052 ms (75.56 MiB/s) 0.039 ms (99.99 MiB/s) 1.32×
zlib_inflate 16 KiB dynamic (500 reps) 0.192 ms (81.52 MiB/s) 0.143 ms (109.52 MiB/s) 1.34×
zlib_inflate 1 MiB fixed (20 reps, incl. 3.17 ms unbatched Adler-32) 11.424 ms (87.54 MiB/s) 8.360 ms (119.61 MiB/s) 1.37× (1.59× excl. Adler-32)
zlib_inflate 256 KiB deep 10..15-bit dynamic (50 reps) 3.114 ms (80.28 MiB/s) 2.320 ms (107.75 MiB/s) 1.34×

(When combined with #8682's Adler-32 batching and #8942's bulk match copy, the deflate speedup dominates end-to-end throughput.)

Verification

  • Built with MSVC 19.44 (/std:c++20 /W4 /permissive-, Windows SDK 10.0.26100, Vulkan SDK 1.4.363.0): 0 warnings in modified files.
  • runtime/build/shader_library_test.exe: PASS (exit 0), including new huffman_lut_checks() covering:
    • BitReader::fill() / bits() / position() / align() / byte() across 1..64 bits, all 8 mod-8 alignments, and < 8-byte short buffers;
    • 1..15-bit canonical Huffman table across all 8 starting bit offsets, 0-trailing-byte EOF boundaries, truncations, empty, single-symbol incomplete, 5-bit fixed-distance, and over-subscribed/reused tables;
    • Multi-block fixed -> stored -> fixed zlib streams hitting all 8 mod-8 bit offsets before align() and Adler-32, with every prefix truncation rejected;
    • Full zlib_inflate dynamic block spanning 1..15-bit codes with every prefix truncation and corrupted Adler-32 rejected.
  • Negative control: compiling runtime/test/shader_library_test.cpp against upstream/main's runtime/src/shader_library.h fails (error C2039: 'fast_bits' / 'kFastBits' / 'fast_mask' / 'fast', exit 2).
  • Differential fuzz check (outside repo): 1,000 / 1,000 synthetic zlib streams (levels 0..9, all 5 strategies, multi-block Z_SYNC_FLUSH/Z_FULL_FLUSH, sizes 0..16 KiB) matched Python zlib.decompress bit-for-bit, including exact-limit, limit-1, 1-byte truncation, and corrupted Adler-32 checks.
  • GPU/runtime smoke on NVIDIA GeForce RTX 3060 12 GB (Windows 11): d3d12_draw_test.exe and d3d12_compute_test.exe both pass (exit 0).
  • python -I tests/test_ci_registration.py: 14/14 OK; python -I scripts/check_no_game_data.py: clean; 0 CRLF bytes.

AI-assisted: yes

Checklist

  • No game data, keys or decryption (CONTRIBUTING.md), including in logs or reports quoted here.
  • A new translator rule is in the contract table of docs/design.md, with how it was confirmed. (Not applicable: no translator change.)

@DaviTostes

Copy link
Copy Markdown

Tested bcb1f888a (as pushed, based on main 5d74c2723) on Arch Linux, CMake/Ninja, GCC: pass.

  • Built shader_library_test from this head and ran it: rc 0, SHA-256, inflate (stored/fixed/dynamic), JSON, FSSM extraction, FSPX programs and index lookup OK.
  • ctest --test-dir runtime/build/linux -R '^shader_library$': 1/1 passed.

(shader_library_corpus is listed by CTest but reports Not Run here because it needs the package's shaders.rpf, which this machine does not have; that is the existing corpus-gated test, not part of this change.)

Counts and pass/fail only; no game files. AI-assisted (DeepSeek V4.1 Flash coding agent).

@SweatierKey

Copy link
Copy Markdown
Contributor

checked: #9566@bcb1f888a | base: origin/main@5d74c2723 | with: clean merge + git diff --check + scripts/check_no_game_data.py + cmake/ctest -R '^shader_library$' + g++ -std=c++20 -O2 -Wall -Wextra -Wconversion -Werror -fsanitize=address,undefined runtime/test/shader_library_test.cpp | on: Linux x86-64 (GCC 14.2.0, CPU only) | result: pass (shader_library CTest 1/1 + ASan/UBSan 0 warnings / 0 findings; retail shader corpus inflate timing not run)

Reviewed runtime/src/shader_library.h line by line:

  • BitReader::fill() keeps next_count = count_ | 56 in [56, 63] (never shifting by 64), masks upper bits so buffer_ >> count_ == 0 stays an invariant across fill() / bits() / drop(), and align() / position() properly rewind pos_ by count_ / 8 before byte() reads.
  • build_huffman() 9-bit reversal (kRev4[v & 15] << 5) | (kRev4[(v >> 4) & 15] << 1) | (v >> 8) with shift = kFastBits - len and packed = (sym << 4) | len (len >= 1, sym <= 287) is non-zero for all assigned entries, clears fast_bits/fast_mask/fast[0] on empty or over-subscribed tables, and decode() checks len > in.available() before dropping bits on EOF tails.

One tiny defensive note (non-blocking): BitReader::fill() does not early-return if failed_ is already set, which is harmless for all current zlib_inflate() paths (every error sets failed_ only at EOF or immediately returns false), though guarding if (failed_) return; would make BitReader strictly sticky if reused directly later.

@shdann

shdann commented Nov 23, 2026

Copy link
Copy Markdown
Contributor

The new 1..15-bit dynamic-block fixture in huffman_lut_checks() has an incomplete code-length tree. It assigns 17 symbols a length of 5. That fills only 17 of 32 slots. The Windows shader_library test passes, but CPython 3.14.7 zlib rejects the 95-byte fixture with "invalid code lengths set". Both this head (bcb1f88) and parent 6312c05 accept it. The issue is in the new positive test fixture.

To reproduce, write w.bytes to fixture.bin immediately before auto bad_adler = w.bytes in section 4, then run:

python -I -c "import pathlib,zlib; print(zlib.decompress(pathlib.Path('fixture.bin').read_bytes()))"

I tested a complete tree. Give symbols 0 through 14 length 4, and symbols 15 and 18 length 5. Emit canonical codes 0 through 14 in four bits, 30 for symbol 15, and 31 for symbol 18 in five bits. Keep the literal/EOB tree and payload unchanged. The revised fixture is 92 bytes. Python decodes it to b'abcdefghijklmno' * 4, and the PR's C++ checks still pass, including the prefix-truncation checks.

AI-assisted.

@katherinebytes katherinebytes left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Independent CPU review of bcb1f888aa36a6b86a3c61c7e5b9952dfa5c4420 against 5d74c272363f2703265d44e6aaab1a1df8ddfaf3. I inspected the refill/bit-position bookkeeping, canonical lookup and EOF/slow-path checks, and the added synthetic cases. No blocking finding in this focused review; I recommend merge subject to the project's normal checks.

macOS 27.2.1, Apple Silicon, Apple clang++, synthetic inputs, no GPU or game data:

  • Compiled runtime/test/shader_library_test.cpp directly with C++20, -O2 -Wall -Wextra; the test passed.
  • Recompiled and ran it with AddressSanitizer and UndefinedBehaviorSanitizer; it passed without a sanitizer report.
  • Changed-file no-game-data check and git diff --check passed.

CMake is unavailable here, so this is a direct test build, not a full runtime build. I did not independently benchmark or run the Windows/GPU smoke tests. AI-assisted (Codex). Review claim: #9522 (comment)

@matheusfermiano-source

Copy link
Copy Markdown

I checked how the three inflate optimizations compose, starting at main 5d74c2723 and #9566 bcb1f888a. The production hunk from #8682 9c3ba87a applies directly. The production hunks from #8942 d3c46a5c apply after refreshing the context around position() to retain #9566's prefetched-byte accounting. The only manual adjustment was to that context line.

All four builds produced byte-identical output to Python zlib-ng 1.3.1 on 171 independently encoded, valid synthetic streams, with the output limit set to the exact decoded length. Each nonempty stream also returned false with the limit set one byte below that length. This includes 96 mixed streams covering all six permutations of stored, fixed-Huffman, and dynamic-Huffman data. I assembled them from raw DEFLATE segments using Z_SYNC_FLUSH between segments and checked the wrapped stream with Python before passing it to the C++ harness. The stream sizes exercise the 5,552-byte Adler batch boundary and 65,535-byte stored-block boundary.

Focused full-inflate timings (Linux x86-64, Ryzen 7 5825U, GCC 16.2.1 -O3, pinned to one logical CPU). Each entry summarizes forward and reverse build order, with five 60-decode rounds per invocation and reused output capacity. Inputs decode to about 512 KiB. Values are ms per stream.

Build Dynamic literals only Stored blocks Repetitive long matches
main 13.86 4.32 3.80
#9566 5.25 4.05 3.79
#9566 + #8682 2.88 1.67 1.42
#9566 + #8682 + #8942 2.93 0.290 0.468

This supports integrating the checksum batching after the Huffman change and retaining the byte-position adjustment when rebasing the bulk-copy patch. It also gives the bulk-copy patch separate coverage for the stored path after Huffman lookahead. These timings characterize the synthetic workloads. The independent corpus does not rely on the code-length fixture discussed above.

AI-assisted (Codex). Synthetic inputs only.

@iliassgm

Copy link
Copy Markdown
Contributor Author

Thanks @shdann for catching the incomplete code-length tree in section 4 of huffman_lut_checks() — fixed in 72ab1220d (symbols 0..14 length 4, symbols 15 and 18 length 5, Kraft sum = 1; 92-byte fixture now decodes to b'abcdefghijklmno' * 4 in Python zlib.decompress as well as passing all C++ checks and prefix-truncation checks, so it stays clean once #7734 lands). runtime/src/shader_library.h is unchanged from bcb1f888a.

And thank you @katherinebytes, @DaviTostes, @SweatierKey, and @matheusfermiano-source for the thorough macOS/Linux/ASan/UBSan reviews and the #8682 + #8942 composition benchmarks!

AI-assisted: yes

@DaviTostes

Copy link
Copy Markdown

Re-checked the new head 72ab1220d on Arch Linux, CMake/Ninja, GCC: pass.

  • Built shader_library_test from this head and ran it: rc 0, SHA-256, inflate (stored/fixed/dynamic), JSON, FSSM extraction, FSPX programs and index lookup OK.

The new head only makes the section-4 dynamic code-length tree complete for standard zlib; no behavior change for the other paths. (shader_library_corpus still reports Not Run here because it needs the package's shaders.rpf.)

Counts and pass/fail only; no game files. AI-assisted (DeepSeek V4.1 Flash coding agent).

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.

7 participants