Repository navigation
bcpack: decode the lanes of one stream side by side (fused scalar loop and AVX2) - #2112
Conversation
The repository has two small BCPack vectors (64 and 700 BC1 blocks), so a decoder change cannot be checked on BC7-shaped or multi-megabyte streams. tests/bcpack_encoder.h is the exact inverse of decode_lanes: - each lane is encoded on its own as flushed fragments with the reverse rANS equation already used by tests/bcpack_symbols_check.py (short and long headers, alphabet narrowing, optional trimming of the trailing zero bytes that the decoder restores); - the shared-stream order is learnt by running the decoder's cycle loop (Lane, phase1, model_advance) with every lane fed from its own queue. Symbols are drawn from each fragment's model or uniformly; a BC7 lane-15 pair is always a valid control code. Fragment lengths are random up to a caller-set maximum, because real fragment lengths are unknown; the repository vectors were generated with a maximum of 150. bcpack_encoder_roundtrip decodes 240 random streams with decode_lanes and decode_bcpack. bcpack_encoder_window_control interleaves with a 7-byte cycle budget instead of 8 and must fail (it fails all 240 streams). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
decode_lanes now dispatches to decode_lanes_scalar. The original loop is kept unchanged as decode_lanes_reference and is called only by tests. The new loop runs both phases of each cycle in one pass over the lanes and gives the reference's result for every input, valid or not. Invariants the fast path relies on: - A lane's phase 1 reads and writes only that lane. A later lane's phase 0 reads only its own state, its own slot bit, the per-cycle byte count and the cursor. So phase 0 and phase 1 of lane i can run before phase 0 of lane i+1. After a failed phase 1 the loop still runs phase 0 (including symbol stores) for the remaining lanes and no further phase 1, as the reference did, so the symbols match even on rejection. - The reference's exhausted mask is redundant: a lane is marked only at pos == input_size, and pos never decreases. - A step goes through the short path only when the reference's phase1 would change nothing but p1, the symbol, out_rem, in_rem and ib_full: PROC with in_rem > will (so no fragment end or flush padding), or DRAIN with p0 > L. Every other step calls phase1 itself. - model_inverse_interval returns model_inverse_fast's symbol and model_forward's f and cf for that symbol. It relies on two table facts: BASE rows are non-decreasing over the enabled segments, and the reciprocal divide never leaves its segment. bcpack_lanes_differential checks all 9 x 16 x 65536 inputs. The f and cf of the step that decoded a symbol are kept for the next advance; eab and q cannot change in between, because the advance comes first in the lane's next unstalled cycle. - The watchdog inputs (pos, symbols emitted, state sum) and max_cycles are computed exactly as before. tests/bcpack_lanes_check.cpp compares every supported path with the reference on the two vectors, the mode-6 vector and 10 synthetic BC1/BC7 streams, each whole, truncated at sampled lengths and with sampled single-bit flips. It compares the accept/reject decision and the symbols, and runs decode_bcpack on a sentinel-filled destination between a canary and a no-access page; inputs end at a no-access page. lane_path_override is a test-only switch that makes decode_lanes use one path; it exists only when the whole test binary defines X2W_BCPACK_LANE_TESTS, so the stand-ins cannot reach it. One test per path (bcpack_lanes_scalar here) compares only that path and returns 77 when the CPU lacks it. The control build (X2W_BCPACK_LANES_CONTROL) also sends the DRAIN home state down the short path and must fail on every path. Release, --full (every truncation and bit flip): 328,163 streams, 0 mismatches. The reference accepts 42,733 damaged streams and the new path matches it on every one, destination bytes included. bcpack_lanes_check VECTOR_DIR --bench, decode_bcpack, reference -> scalar: 1.26-1.59x (BC1 0.5 MiB, at most 150 symbols per fragment: 32.4 -> 23.0 ms; BC7 0.5 MiB: 58.4 -> 40.7 ms). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
When cpuid reports AVX, AVX2 and POPCNT and the OS saves the YMM state (XCR0 & 0x6), decode_lanes uses decode_lanes_avx2; otherwise it keeps the fused scalar loop. One stream still cannot be split between threads: when a lane requests a byte depends on its rANS state, so the byte schedule depends on every symbol decoded. Within a cycle the lanes are independent apart from the prefix count of byte requests, so each per-lane field of all 16 lanes is held in two 8-lane registers. Invariants the vector path relies on, in addition to those of the fused scalar loop: - Byte arbitration: the reference serves requesting, unblocked lanes in lane order while fewer than 8 bytes were served and pos < input_size. That equals the lowest min(8, input_size - pos) set bits of the request mask (lowest_bits, a clear-lowest-bit loop that runs only when more lanes ask; not pdep, which is microcoded on AMD before Zen 3 and measured the same here). The bytes input[pos..] land in those lanes in order: LANE_EXPAND gives each set lane its rank for vpermd, and the upper half starts after the lower half's bytes. Only those avail bytes are read (memcpy of avail <= 8 bytes, skipped at 0), never past the input. - Every lane's phase 0 runs before any lane's phase 1, as in the reference. Symbols are stored during phase 0, so a phase1 failure leaves the same symbols. - The vector phase 1 handles only steps that change nothing but p1, the symbol, f/cf, out_rem, in_rem and ib_full: PROC with in_rem != will (no fragment end, so no flush padding) and DRAIN with x >= L+1. Every other running lane (IDLE with go, header states, fragment ends, flushes) calls the original phase1 with the vector state copied into its Lane, one lane at a time in lane order, and the result is copied back. An IDLE lane without go is skipped, because phase1 does nothing for it. - Lane state bits (PROC, DRAIN, header, idle without go, done) and the state sum change only in phase1 and are updated right after it. The model rows used by the vector inverse are reloaded whenever phase1 leaves a different eab or q. Rows for disabled segments use the bound 0x10000, which no 16-bit value reaches, so the segment is the same count as in model_inverse_interval (9 plus the -1 results of bound > c; both operands are below 2^31). - Unsigned 32-bit compares flip the sign bit on both operands before the signed compare. Vector masks are rebuilt from the lane bits (broadcast, AND with the lane bit, compare) and read back with movemask. - The watchdog inputs, max_cycles and the final checks are computed as in the reference. Upper vector state is cleared (vzeroupper) before returning; the loop body is VEX-encoded throughout (checked with dumpbin). bcpack_lanes_avx2 compares this path with the reference; on a CPU without AVX2 it reports a capability skip (77). The control build is caught on both the scalar and the AVX2 path. Release, Ryzen 7 9800X3D, Windows 11 26300, MSVC /O2, bcpack_lanes_check VECTOR_DIR --bench --large (4 MiB destinations, interleaved, warm-up dropped, best of 7), decode_bcpack reference / scalar / avx2, lane ns per symbol for reference and avx2: BC1, fragments <= 150: 168 / 126 / 46 ms (25.2 / 5.9) BC1, fragments <= 4096: 120 / 90 / 32 ms (17.8 / 3.7) BC7, fragments <= 150: 296 / 229 / 109 ms (27.5 / 6.0) BC7, fragments <= 4096: 229 / 182 / 90 ms (20.7 / 4.0) This was measured on Zen 5, which has fast gathers. On CPUs with slow gathers the AVX2 gain is unmeasured. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
bcpack_lanes_check used only the BC1 (12-lane) and BC7 (16-lane) tables, so no lane had alphabet index 8 (9-bit symbols, segment 9 of the vector inverse) or below 3 (headers that select an undefined alphabet), and every stream was decoded with its own symbol count. The check now also compares, with decode_lanes only: - every stream with one symbol more and one fewer per lane, and with the other format's lane table (whole stream only); - synthetic streams for 1 lane at index 8, 16 lanes at index 8, three lanes at index 0, indices 0-2, the three 12-lane tables of the BC3/BC4/BC5 decoders proposed in PR 1390, and random tables of 7, 9 and 13 lanes, each whole, truncated and with single bits flipped. Release --full (every truncation and bit flip): 0 mismatches on every path (counts are in docs/experiments.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The encoder wrote only flushed fragments, so a lane state that carries across a fragment header (flush bit clear: DRAIN to HDR0 without a reset, partial renormalisation across the boundary) was covered only by bit flips. Options::unflushed now codes about half of the lanes as one rANS stream cut into unflushed fragments of 1 to 300 bytes. The last fragment must start at or before the last byte that precedes the final zero bytes. Otherwise the lane decodes its last symbol in DRAIN, finishes with state L >> 8 or L >> 16 (both legal) and never reads the later fragment, which the decoder then treats as trailing data. The round-trip check found this on its first run: 3 of about 1,700 single-lane streams failed before the rule, and 0 of 30,000 failed after it. bcpack_encoder_roundtrip uses unflushed lanes in half of its cases. bcpack_lanes_check adds a BC1 and a BC7 stream with unflushed lanes and uses them at random in its lanes-only tables. Release --full (every truncation and bit flip): 0 mismatches on every path (counts are in docs/experiments.md). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The test-only encoder learns the stream order from the decoder's own lane code, so the encoder round trip and the path comparison only show that the paths agree with each other and with that code. Each per-path test now also checks the path against data it did not produce: - the lane symbols stored in synthetic_11.json and synthetic_12.json, written by the upstream Rust encoder (24 lane arrays); - the 16-byte block of tests/bcpack_mode6_vector.py; - the three expected decode_bcpack outputs of tests/startup_stub_consumer.cpp (64 BC1 blocks, two mode-6 BC7 blocks, one mode-1 BC7 block), read from that file so the expected bytes keep a single source. The consumer fixture itself runs them only on the path its CPU picks. tests/bcpack_lanes_python_check.py runs the lane check with --emit, which writes 225 streams (the vectors, the mode-6 vector and the synthetic streams, each whole, truncated three ways and with five bits flipped) with each path's result. It decodes each stream with the vendored Python decoder (tools/_bcpack_rans, the separate upstream implementation) plus the C++ trailing-byte rule, and requires the same accept or reject decision and the same symbols from the reference and the tested path. bcpack_lanes_python_<path> runs it per path (77 when the CPU lacks the path). bcpack_lanes_python_<path>_drain_control runs it on the control build and must fail; it reports 42 mismatches on the scalar path. Results here: outside anchors 56 checks per path, 0 failed; Python comparison 225 streams (45 accepted), 0 mismatches for the reference, scalar and AVX2 paths. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The new section in docs/experiments.md explains why one stream cannot be split between threads, which path decode_lanes picks, the per-path tests and their capability skips, the outside anchors, the fragment-length assumption, and the benchmark command with its results on a Ryzen 7 9800X3D (bcpack_lanes_check --full: 423,874 streams, 0 mismatches; --bench --large: decode_bcpack for a 4 MiB BC1 destination 161 -> 127 (scalar) -> 46 ms (AVX2), BC7 283 -> 232 -> 107 ms, at most 150 symbols per fragment). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
The drain controls used WILL_FAIL, so any nonzero exit passed them: a missing vector directory, a crash or a Python traceback. Each control now passes only on its expected output. The C++ control must name a synthetic_11 lane that differs from the vector's symbols and must end with 'result: anchors failed, N mismatches' where N > 0. To make that possible, the check now runs the reference sweep even after an anchor fails, and prints that result line. The Python control must report 'Python accepts, C++ rejects' for its path. Also, when a SIMD path is not compiled (clang-cl, non-x64), the capability skip says so instead of blaming the CPU, and docs/experiments.md notes it. bcpack_lanes_* on this machine: 8 of 8 passed (controls pinned). Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
tedin7
left a comment
There was a problem hiding this comment.
Review of head a0ff8ead6003cbf8b3ea744e8484b6231588277b (comment only, no approval).
Scope: decode_lanes fused scalar loop + AVX2 path, kept decode_lanes_reference, test-only encoder, lane/python checks, CMake wiring, docs/experiments.md. Diff: 7 files, +1497/-4.
Run locally (Linux):
git diff --check origin/main...HEAD: clean.python3 tests/docs_links_check.py: pass (18 files, 393 links).python3 tests/bidi_controls_check.py: pass (1417 files, no bidi controls).bcpack_encoder_checkbuilt with g++ -std=c++17 -O2 plus a localintrin.hshim (only_BitScanReverse/_BitScanForward):240 streams, 419030 bytes, 535960 symbols, 0 failed.--mutate windowcontrol exits non-zero as the CMake test expects.- Mutation 1 in
decode_lanes_scalar(served < 8->served < 7): encoder round-trip fails 240/240. Killed. - Mutation 2 in
decode_lanes_scalar(will = p0 < 0x1000000->p0 <= 0x1000000): encoder round-trip still0 failed. It survives this check. It is probably only caught by the reference-vs-path sweep inbcpack_lanes_check, or it is an equivalent mutant. I could not tell on Linux (see below). - All edits reverted (
git checkout -- .).
Not runnable on Linux: bcpack_lanes_check.cpp includes windows.h, and the AVX2 path is gated on _MSC_VER && _M_X64, so the scalar-vs-reference sweep, the python anchor check and the AVX2 path were not run here. CI shows Build and test on Windows pass, Assemble and translate gfx1013 fixtures pass, Run platform-independent Python checks on Linux pass. Build and test on Windows at /O2 was skipped. No separate Windows run was done by me.
Findings:
- P1: none.
- P2: none.
- nit (tests): please confirm that
bcpack_lanes_scalarkills ap0 <= 0x1000000change in thewillcondition (bcpack_decoder.hindecode_lanes_scalar). If it does not, add a stream that hitsp0 == 0x1000000exactly, or say why it cannot occur. - nit (CI): the
/O2Windows job was skipped. The fast paths depend on invariants that optimization can expose, so a /O2 run on the final head would be useful. - Title and body are neutral, mergeable state shows UNKNOWN at review time.
AI-assisted; commands listed were executed locally.
|
I kept the storage reuse and all BCPack test registrations. Local Windows Release passed all ten focused BCPack CTests, including the scalar and AVX2 comparisons against the reference and Python, and the short-drain controls. No capability skips. |
tedin7
left a comment
There was a problem hiding this comment.
Re-review of head 20f9814328e6f49b89f4eece8a620b675c341adc (comment only, no approval). Previous review was on a0ff8ead6003cbf8b3ea744e8484b6231588277b.
What changed since the last review: only merges of main. git diff a0ff8ead HEAD on the PR's own files shows no change to src/startup_stubs/bcpack_decoder.h, tests/bcpack_encoder.h, tests/bcpack_encoder_check.cpp, tests/bcpack_lanes_check.cpp or tests/bcpack_lanes_python_check.py. The CMakeLists.txt and docs/experiments.md differences come from main (BCPack registrations are preserved). Author comment: local Windows Release passed all ten focused BCPack CTests (scalar and AVX2 vs reference and Python, short-drain controls).
Run locally (Linux, on this head):
git diff --check origin/main...HEAD: clean.python3 tests/docs_links_check.py: pass (18 files, 401 links).python3 tests/bidi_controls_check.py: pass (1457 files, no bidi controls).- CI:
Build and test on Windowspass,Assemble and translate gfx1013 fixturespass,Run platform-independent Python checks on Linuxpass.Build and test on Windows at /O2is still skipped. Mergeable: yes. - No new mutation run: the decoder and test code are byte-identical to the previous review, so the earlier results still hold (mutation 1
served < 8killed 240/240; mutation 2p0 <= 0x1000000survived the encoder round-trip).
Status of previous findings:
- P1/P2: none before, none now.
- nit (tests,
willboundaryp0 == 0x1000000indecode_lanes_scalar,bcpack_decoder.h:188): NOT addressed. No new test and no explanation. The author's Windows run does not say whether the lanes sweep kills this mutant. Please either add a stream hittingp0 == 0x1000000within_rem > 0andib_full, or say why it is unreachable or equivalent. - nit (CI, /O2 job skipped): NOT addressed. Still skipped on this head. A /O2 run on the final head is still wanted, since the fast paths depend on invariants optimization can expose.
No new findings. Neither open item blocks the change.
AI-assisted; commands listed were executed locally.
Change
The startup storage stand-in decodes BCPack DirectStorage streams with
decode_lanes(
src/startup_stubs/bcpack_decoder.h). This PR makes that decode faster without changing a singleoutput byte or accept/reject decision.
for a byte depends on its rANS state, so on every symbol decoded so far. A first pass that only finds
the byte positions costs as much as a full decode. Within one cycle the lanes are independent apart
from the prefix count of byte requests, so this PR runs them side by side.
decode_lanes_scalarruns both phases of each cycle in one pass over the lanes, keeps f and cf fromthe decoding step, and counts the model segment without branches. It is used when AVX2 is missing.
decode_lanes_avx2holds each per-lane field of all 16 lanes in two 8-lane registers. The bytearbitration is a mask computation: a clear-lowest-bit loop rather than pdep, which is microcoded on
AMD before Zen 3, plus a vpermd rank table. Header bytes, fragment ends and flushes go through the
original
phase1for that lane.decode_lanes_referenceand is used only by tests. Thedecode_lanessignature is unchanged.tests/bcpack_encoder.his a test-only encoder: per-lane reverse rANS plus the reference cycle loop tolearn the stream order. It makes synthetic BC1, BC7 and other lane layouts of any size: short and long
headers, narrowing, trimmed flushed fragments and unflushed fragments.
Overlapping work:
decode_lanesand edits its body. Thisbranch renames that body to
decode_lanes_reference, so the two conflict inbcpack_decoder.h. Toreconcile: put the report on
decode_lanes_reference, and haveinspect_bcpackcall the referenceloop. It is a diagnostic path, so it does not need the fast path, and the reports stay exact. The fast
paths give the same decision on every input tested.
12-lane tables are among the lane tables this branch tests.
Verification
Build and machine: commit a0ff8ea, Windows 11 26300, Ryzen 7 9800X3D (Zen 5), MSVC, Ninja.
Result: 34 passed, 1 skipped, 0 failed out of 35. The bcpack tests among them:
bcpack_encoder_roundtrip,bcpack_encoder_window_control,bcpack_lanes_{scalar,avx2},bcpack_lanes_python_{scalar,avx2}, their*_drain_controlcontrols,bcpack_prefix_and_mip_tail,bcpack_rans_symbolsandbcpack_tables.Capability skips:
bc7_mode6_multiblock_warpskips becauseBCPACK_REFERENCE_TOOLSis not set. It is unrelated tothis change.
_hardwaretests were not run.bcpack_lanes_avx2and its variants return 77 on a CPU or OS withoutAVX2, and in a clang-cl build, where the SIMD code is not compiled; the skip message names which. A
machine without AVX2 therefore passes the scalar tests and reports the AVX2 tests as skipped.
--fullruns every truncation and every single-bit flip of each stream: 423,874 streams, 0mismatches. The reference accepts 48,004 of the damaged streams, and both fast paths match it on each
one, destination bytes included.
--bench --largedecodes 4 MiB destinations (524,288 BC1 or 262,144 BC7 blocks). The paths areinterleaved, the warm-up round is dropped, the best of 7 is kept and the output checksums must match.
Times are
decode_bcpackms, with lane-decode ns per symbol in parentheses:Measured on one CPU (Zen 5); CPUs with slow gathers are unmeasured.
Evidence and follow-up
repository), plus synthetic streams generated at test time by
tests/bcpack_encoder.h. Its reverserANS equation comes from the vendored bcpack-rs code (MIT OR Apache-2.0); the credit is kept.
streams. The check covers the decision, the symbols (also on rejection) and every
decode_bcpackdestination byte. Inputs end at a no-access page and the destination sits between a canary and a
no-access page.
data it did not produce:
synthetic_11.jsonandsynthetic_12.json;tests/bcpack_mode6_vector.pyandtests/startup_stub_consumer.cpp;tests/bcpack_lanes_python_check.py).bcpack_encoder_window_controlinterleaves with a 7-byte cycle budget.*_drain_controlbuilds take a wrong DRAIN step at the home state. Each control passes only onits expected output: the C++ control must fail on both the vector symbols and the reference sweep,
and the Python control must report that Python accepts what C++ rejects.
fragment (v12 averages about 72), so the benchmark uses at most 150 and at most 4096.
docs/experiments.md, section "BCPack lane decoder paths", has the reproduction commandsand results.
prtest preset does not run the new tests; the full dev and release CTest jobs do.decode_bc7_blocks) is unchanged and now takes about half of the BC7time.
Checklist
This change was AI-assisted (Claude Code). An independent review agent checked it before this PR.
🤖 Generated with Claude Code