From 130ea623fa6001f8b2c453b7b3d3ed72103a8895 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 20:36:03 +0100 Subject: [PATCH 1/8] tests: add a test-only BCPack lane encoder with a round-trip check 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 --- CMakeLists.txt | 9 ++ tests/bcpack_encoder.h | 214 +++++++++++++++++++++++++++++++++ tests/bcpack_encoder_check.cpp | 61 ++++++++++ 3 files changed, 284 insertions(+) create mode 100644 tests/bcpack_encoder.h create mode 100644 tests/bcpack_encoder_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 94084d41e9..585d5536e9 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -611,6 +611,15 @@ add_test(NAME startup_storage_consumer_pair_accept_refused_control set_tests_properties(startup_storage_consumer_pair startup_storage_consumer_pair_accept_refused_control PROPERTIES TIMEOUT 60) set_tests_properties(startup_storage_consumer_pair_accept_refused_control PROPERTIES PASS_REGULAR_EXPRESSION "FAIL: after both fences: R destination taken as data differs from the stream prefix in 4096 byte\\(s\\), first at 0xf000") +# Test-only BCPack encoder (tests/bcpack_encoder.h): random synthetic streams must decode back to their +# symbols. Interleaving with a 7-byte cycle budget is the negative control. +add_executable(bcpack_encoder_check tests/bcpack_encoder_check.cpp) +target_compile_features(bcpack_encoder_check PRIVATE cxx_std_17) +target_include_directories(bcpack_encoder_check PRIVATE src) +add_test(NAME bcpack_encoder_roundtrip COMMAND bcpack_encoder_check) +add_test(NAME bcpack_encoder_window_control COMMAND bcpack_encoder_check --mutate window) +set_tests_properties(bcpack_encoder_roundtrip bcpack_encoder_window_control PROPERTIES TIMEOUT 120) +set_tests_properties(bcpack_encoder_window_control PROPERTIES WILL_FAIL TRUE) # A queue whose worker cannot start (both CreateThread attempts fail, or the construction of its work # throws std::bad_alloc) completes status entries and fences at Submit, never inside Enqueue (#1199). # The test compiles the stand-in's source into itself so it can redirect CreateThread and operator new. diff --git a/tests/bcpack_encoder.h b/tests/bcpack_encoder.h new file mode 100644 index 0000000000..62f33c9b62 --- /dev/null +++ b/tests/bcpack_encoder.h @@ -0,0 +1,214 @@ +// Test-only BCPack lane encoder: the exact inverse of x2w_bcpack::decode_lanes. +// Reverse rANS fragment equation adapted from bcpack-rs by Ahmet Dedeler +// (https://github.com/Ahmet-Dedeler/bcpack-rs, src/encode.rs), as in tests/bcpack_symbols_check.py. +// SPDX-License-Identifier: MIT OR Apache-2.0 +// Each lane is encoded on its own as flushed fragments. The shared-stream order is then learnt by +// running the reference cycle loop with every lane fed from its own byte queue. +#pragma once + +#include "startup_stubs/bcpack_decoder.h" + +#include +#include + +namespace bcpack_test { + +struct Rng { + uint64_t s; + uint32_t next() { + s += 0x9E3779B97F4A7C15ull; + uint64_t z = s; + z = (z ^ (z >> 30)) * 0xBF58476D1CE4E5B9ull; + z = (z ^ (z >> 27)) * 0x94D049BB133111EBull; + return static_cast((z ^ (z >> 31)) >> 32); + } + uint32_t below(uint32_t n) { return next() % n; } +}; + +// The decoder's interval for a symbol, or f == 0 when the symbol cannot be coded. +inline bool interval(uint8_t eab, uint8_t q, uint16_t sym, uint32_t& f, uint32_t& cf) { + if (sym >= (1u << (eab + 1))) return false; + x2w_bcpack::model_forward(eab, q, sym, f, cf); + return f != 0 && x2w_bcpack::model_inverse_fast(eab, q, static_cast(cf)) == sym && + x2w_bcpack::model_inverse_fast(eab, q, static_cast(cf + f - 1)) == sym; +} + +// One flushed fragment (header + payload); false when a symbol has no interval or the payload is too long. +inline bool encode_fragment(uint8_t ab, uint8_t narrow, uint8_t q, const uint16_t* values, size_t count, + bool trim, std::vector& out) { + const uint8_t eab = static_cast(ab - narrow); + uint64_t state = 1u << 24; + std::vector emitted; + size_t last_emitted = 0; + for (size_t k = 0; k < count; ++k) { + uint32_t f, start; + if (!interval(eab, q, values[count - 1 - k], f, start)) return false; + while (state >= (uint64_t(f) << 16)) { + emitted.push_back(static_cast(state)); + state >>= 8; + } + if (k == 0) last_emitted = emitted.size(); + state = ((state / f) << 16) + state % f + start; + } + size_t omit = 0; + if (trim) { + while (omit < 2 && omit < last_emitted && emitted[omit] == 0) ++omit; + } + const size_t payload = 4 + emitted.size() - omit; + if (payload > 65792) return false; + const uint8_t header = static_cast((narrow << 6) | 0x10 | q); + if (payload <= 256) { + out.push_back(header); + out.push_back(static_cast(payload - 1)); + } else { + out.push_back(header | 0x20); + out.push_back(static_cast(payload - 257)); + out.push_back(static_cast((payload - 257) >> 8)); + } + for (int b = 3; b >= 0; --b) out.push_back(static_cast(state >> (8 * b))); + for (size_t k = emitted.size(); k > omit; --k) out.push_back(emitted[k - 1]); + return true; +} + +// The reference cycle loop with each lane reading its own queue; records the shared-stream order. +inline bool interleave(const std::vector>& lane_bytes, const uint8_t* ab, size_t n, + size_t target, std::vector& stream, size_t window = 8) { + using namespace x2w_bcpack; + std::vector lanes(n); + std::vector next(n, 0); + for (size_t i = 0; i < n; ++i) { + lanes[i].ab = ab[i]; + lanes[i].target = static_cast(target); + } + uint32_t slots = 0; + for (uint64_t cycle = 0; cycle < 64ull * n * target + 1000; ++cycle) { + size_t served = 0; + for (size_t i = 0; i < n; ++i) { + Lane& ln = lanes[i]; + const uint32_t bit = 1u << i; + const bool blocked_out = ln.sym_full && (slots & bit); + const bool need = !ln.ib_full && ((ln.state >= LANE_HDR0 && ln.state <= LANE_HDR2) || + (ln.state == LANE_PROC && ln.in_rem > 0)); + const bool valid = need && !blocked_out && served < window; + if (valid && next[i] >= lane_bytes[i].size()) return false; // the encoder is wrong + ln.stall = (need && !valid) || blocked_out; + if (ln.stall) continue; + if (ln.state == LANE_PROC || ln.state == LANE_DRAIN) { + ln.p0 = ln.sym_full ? model_advance(ln.eab, ln.q, ln.p1, ln.sym) : ln.p1; + } + if (valid) { + ln.ib = lane_bytes[i][next[i]++]; + ln.ib_full = true; + stream.push_back(ln.ib); + served++; + } + if (ln.sym_full) { + slots |= bit; + ln.sym_full = false; + } + } + uint32_t active = 0; + bool finished = true; + for (size_t i = 0; i < n; ++i) { + Lane& ln = lanes[i]; + if (!ln.stall && !phase1(ln)) return false; + if (!(ln.done && !ln.sym_full && (slots & (1u << i)) == 0)) active |= 1u << i; + finished &= ln.done && !ln.sym_full; + } + if (slots != 0 && (slots & active) == active) slots = 0; + if (finished) { + for (size_t i = 0; i < n; ++i) { + if (next[i] != lane_bytes[i].size()) return false; + } + return true; + } + } + return false; +} + +// Codes of BC7_CONTROL_TABLE whose two lane-15 symbols (code & 31, code >> 5) both have an interval. +inline std::vector bc7_codes(uint8_t eab, uint8_t q) { + std::vector codes; + uint32_t f, cf; + for (uint16_t c = 0; c < 512; ++c) { + if (x2w_bcpack::BC7_CONTROL_TABLE[c].valid && interval(eab, q, c & 31, f, cf) && + interval(eab, q, c >> 5, f, cf)) { + codes.push_back(c); + } + } + return codes; +} + +struct Options { + uint32_t max_fragment = 150; // symbols per fragment, at most + bool uniform = false; // uniform symbols instead of the fragment model's distribution + bool narrow = true; // random alphabet narrowing in the headers + bool trim = true; // randomly omit the trailing zero bytes of a fragment + int bc7_lane = -1; // lane whose symbol pairs must form a valid BC7 control code + size_t padding = 0; // trailing zero bytes + size_t window = 8; // bytes served per cycle; only the negative control changes it +}; + +// A random stream and its symbols (lane-major, target per lane). False only on an encoder bug. +inline bool make_stream(const uint8_t* ab, size_t n, size_t target, Rng& rng, const Options& o, + std::vector& stream, std::vector& symbols) { + symbols.assign(n * target, 0); + std::vector> lane_bytes(n); + for (size_t l = 0; l < n; ++l) { + size_t at = 0; + while (at < target) { + const bool control = static_cast(l) == o.bc7_lane; + size_t count = 1 + rng.below(o.max_fragment); + if (control) count = 2 * ((count + 1) / 2); // keep code pairs inside one fragment + if (count > target - at) count = target - at; + uint8_t narrow = (o.narrow && !control) ? static_cast(rng.below(ab[l] < 3 ? ab[l] + 1 : 4)) : 0; + const uint8_t eab = static_cast(ab[l] - narrow); + uint8_t q = 0; + std::vector codes; + for (int tries = 0;; ++tries) { + q = static_cast(rng.below(16)); + if (!control) break; + codes = bc7_codes(eab, q); + if (!codes.empty()) break; + if (tries > 64) return false; + } + uint16_t* v = &symbols[l * target + at]; + for (size_t k = 0; k < count; ++k) { + if (control) { + const uint16_t c = codes[rng.below(static_cast(codes.size()))]; + v[k] = c & 31; + if (k + 1 < count) v[++k] = c >> 5; + continue; + } + for (int tries = 0;; ++tries) { + uint16_t s; + if (o.uniform) { + s = static_cast(rng.below(1u << (eab + 1))); + } else { + s = x2w_bcpack::model_inverse_fast(eab, q, static_cast(1 + rng.below(65535))); + } + uint32_t f, cf; + if (interval(eab, q, s, f, cf)) { + v[k] = s; + break; + } + if (tries > 100000) return false; + } + } + const bool trim = o.trim && (rng.next() & 1); + if (!encode_fragment(ab[l], narrow, q, v, count, trim, lane_bytes[l])) { + if (count == 1) return false; + // payload over the long-header limit: retry with fewer symbols + for (size_t k = 0; k < count; ++k) v[k] = 0; + continue; + } + at += count; + } + } + stream.clear(); + if (!interleave(lane_bytes, ab, n, target, stream, o.window)) return false; + stream.insert(stream.end(), o.padding, 0); + return true; +} + +} // namespace bcpack_test diff --git a/tests/bcpack_encoder_check.cpp b/tests/bcpack_encoder_check.cpp new file mode 100644 index 0000000000..0e3466a763 --- /dev/null +++ b/tests/bcpack_encoder_check.cpp @@ -0,0 +1,61 @@ +// Round trip of the test-only BCPack encoder (tests/bcpack_encoder.h) through decode_lanes and +// decode_bcpack: random BC1- and BC7-shaped streams with short and long fragment headers, narrowed +// alphabets, trimmed flushed fragments, uniform and model-distributed symbols and zero padding. +// --mutate window interleaves with a 7-byte instead of an 8-byte cycle budget; the decoder must then +// disagree, which shows the check depends on the shared-stream arbitration (negative control). +#include "bcpack_encoder.h" + +#include +#include + +namespace { + +const uint8_t AB1[12] = { 7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7 }; +const uint8_t AB7[16] = { 3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4 }; + +} // namespace + +int main(int argc, char** argv) { + const bool mutate = argc == 3 && std::strcmp(argv[1], "--mutate") == 0 && std::strcmp(argv[2], "window") == 0; + if (argc != 1 && !mutate) { + std::fprintf(stderr, "usage: bcpack_encoder_check [--mutate window]\n"); + return 64; + } + bcpack_test::Rng rng{ 2026 }; + int failures = 0; + size_t bytes = 0, symbols_total = 0; + for (int t = 0; t < 240; ++t) { + const bool bc7 = (t & 1) != 0; + const uint8_t* ab = bc7 ? AB7 : AB1; + const size_t n = bc7 ? 16 : 12; + const size_t blocks = 1 + rng.below(t < 230 ? 96 : 3000); + const size_t target = bc7 ? 2 * blocks : blocks; + bcpack_test::Options o; + o.max_fragment = 1 + rng.below(t % 3 == 0 ? 600 : 150); // long fragments need three-byte headers + o.uniform = t % 5 == 0; + o.bc7_lane = bc7 ? 15 : -1; + o.padding = rng.below(3); + if (mutate) o.window = 7; + std::vector stream; + std::vector expected, got; + if (!bcpack_test::make_stream(ab, n, target, rng, o, stream, expected)) { + std::fprintf(stderr, "case %d: the encoder failed\n", t); + return 1; + } + bytes += stream.size(); + symbols_total += expected.size(); + const bool lanes_ok = x2w_bcpack::decode_lanes(stream.data(), stream.size(), ab, n, target, got); + std::vector out(blocks * (bc7 ? 16 : 8)); + size_t produced = 0; + const bool bcpack_ok = x2w_bcpack::decode_bcpack(stream.data(), stream.size(), bc7 ? 7 : 1, out.data(), + out.size(), &produced); + if (!lanes_ok || got != expected || !bcpack_ok || produced != out.size()) { + if (failures++ < 5) { + std::fprintf(stderr, "case %d (BC%d, %zu blocks, %zu bytes): lanes=%d symbols-equal=%d bcpack=%d\n", t, + bc7 ? 7 : 1, blocks, stream.size(), lanes_ok, got == expected, bcpack_ok); + } + } + } + std::printf("bcpack_encoder_check: 240 streams, %zu bytes, %zu symbols, %d failed\n", bytes, symbols_total, failures); + return failures == 0 ? 0 : 1; +} From 15c536bac8f7833be4c08274af89eed9527bb654 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 20:45:40 +0100 Subject: [PATCH 2/8] bcpack: fuse the two lane phases of each decode cycle 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 --- CMakeLists.txt | 18 ++ src/startup_stubs/bcpack_decoder.h | 218 +++++++++++++++++++- tests/bcpack_lanes_check.cpp | 307 +++++++++++++++++++++++++++++ 3 files changed, 539 insertions(+), 4 deletions(-) create mode 100644 tests/bcpack_lanes_check.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 585d5536e9..8041194eb5 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -620,6 +620,24 @@ add_test(NAME bcpack_encoder_roundtrip COMMAND bcpack_encoder_check) add_test(NAME bcpack_encoder_window_control COMMAND bcpack_encoder_check --mutate window) set_tests_properties(bcpack_encoder_roundtrip bcpack_encoder_window_control PROPERTIES TIMEOUT 120) set_tests_properties(bcpack_encoder_window_control PROPERTIES WILL_FAIL TRUE) +# Each decode_lanes path against the original cycle loop on whole, truncated and bit-flipped streams +# (tests/bcpack_lanes_check.cpp), one test per path; 77 means this CPU lacks that path. The control +# build takes a wrong short DRAIN step at the home state and must fail on every path. +foreach(variant IN ITEMS check control) + add_executable(bcpack_lanes_${variant} tests/bcpack_lanes_check.cpp) + target_compile_features(bcpack_lanes_${variant} PRIVATE cxx_std_17) + target_include_directories(bcpack_lanes_${variant} PRIVATE src) + target_compile_definitions(bcpack_lanes_${variant} PRIVATE X2W_BCPACK_LANE_TESTS) +endforeach() +target_compile_definitions(bcpack_lanes_control PRIVATE X2W_BCPACK_LANES_CONTROL) +set(bcpack_lane_paths scalar) +foreach(path IN LISTS bcpack_lane_paths) + add_test(NAME bcpack_lanes_${path} COMMAND bcpack_lanes_check "${CMAKE_SOURCE_DIR}/tools/_bcpack_rans/vectors" --path ${path}) + add_test(NAME bcpack_lanes_${path}_drain_control + COMMAND bcpack_lanes_control "${CMAKE_SOURCE_DIR}/tools/_bcpack_rans/vectors" --path ${path}) + set_tests_properties(bcpack_lanes_${path} bcpack_lanes_${path}_drain_control PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + set_tests_properties(bcpack_lanes_${path}_drain_control PROPERTIES WILL_FAIL TRUE) +endforeach() # A queue whose worker cannot start (both CreateThread attempts fail, or the construction of its work # throws std::bad_alloc) completes status entries and fences at Submit, never inside Enqueue (#1199). # The test compiles the stand-in's source into itself so it can redirect CreateThread and operator new. diff --git a/src/startup_stubs/bcpack_decoder.h b/src/startup_stubs/bcpack_decoder.h index eb022bba35..8d11bb957f 100644 --- a/src/startup_stubs/bcpack_decoder.h +++ b/src/startup_stubs/bcpack_decoder.h @@ -242,10 +242,11 @@ inline bool phase1(Lane& ln) { return true; } -inline bool decode_lanes(const uint8_t* input, size_t input_size, - const uint8_t* alphabet_bits, size_t num_lanes, - size_t target_symbols_per_lane, - std::vector& symbols) { +// The original cycle loop. decode_lanes no longer calls it; tests compare every path with it. +inline bool decode_lanes_reference(const uint8_t* input, size_t input_size, + const uint8_t* alphabet_bits, size_t num_lanes, + size_t target_symbols_per_lane, + std::vector& symbols) { if (num_lanes == 0 || num_lanes > 16 || target_symbols_per_lane == 0) return false; for (size_t i = 0; i < num_lanes; ++i) { if (alphabet_bits[i] > 8) return false; @@ -353,6 +354,215 @@ inline bool decode_lanes(const uint8_t* input, size_t input_size, return false; } +// model_inverse_fast followed by model_forward of its result. The enabled BASE entries of a row +// never decrease, so the comparator chain is a count, and the reciprocal divide never leaves the +// segment it starts in. bcpack_lanes_check compares all 9 x 16 x 65536 inputs with the originals. +inline uint16_t model_inverse_interval(uint8_t eab, uint8_t q, uint32_t c, uint32_t& f, uint32_t& cf) { + const uint16_t* base = BASE_TABLE[eab][q]; + uint32_t seg = 0; + for (uint32_t k = 1; k < 10; ++k) { + seg += (k <= eab + 1u) & (c >= base[k]); + } + uint32_t dist = (c - base[seg] + RN_TABLE[eab][q][seg]) & 0xFFFF; + uint32_t steps = (((dist * RF_TABLE[eab][q][seg]) >> 15) >> RS_TABLE[eab][q][seg]) & 0x1FF; + uint32_t fa = FREQ_TABLE[eab][q][seg]; + uint32_t cfa = (base[seg] + fa * steps) & 0xFFFF; + f = cfa ? fa : ((fa - 1) & 0xFFFF); + cf = cfa ? cfa : 1; + return static_cast((((1u << seg) >> 1) + steps) & 0x1FF); +} + +// Lowest DRAIN state that decodes without a state change. bcpack_lanes_check builds a negative control +// with X2W_BCPACK_LANES_CONTROL, which also sends the home state L down the short path. Define it only +// for a whole test executable: two translation units of one binary that disagree on it would break the +// one-definition rule for every inline function below. +#ifdef X2W_BCPACK_LANES_CONTROL +inline constexpr uint32_t LANE_DRAIN_SHORT_MIN = 0x1000000; +#else +inline constexpr uint32_t LANE_DRAIN_SHORT_MIN = 0x1000001; +#endif + +// decode_lanes_reference with both phases in one pass over the lanes. Exact because a lane's +// phase 1 reads and writes only that lane, and a later lane's phase 0 reads only its own state and +// the shared cursor. Steps without a header, fragment end or flush go through a short path; all +// others use phase1. A lane's f and cf are kept from the step that decoded its symbol. +inline bool decode_lanes_scalar(const uint8_t* input, size_t input_size, + const uint8_t* alphabet_bits, size_t num_lanes, + size_t target_symbols_per_lane, + std::vector& symbols) { + if (num_lanes == 0 || num_lanes > 16 || target_symbols_per_lane == 0) return false; + for (size_t i = 0; i < num_lanes; ++i) { + if (alphabet_bits[i] > 8) return false; + } + symbols.assign(num_lanes * target_symbols_per_lane, 0); + + Lane lanes[16]; + uint32_t lane_f[16] = {}; + uint32_t lane_cf[16] = {}; + for (size_t i = 0; i < num_lanes; ++i) { + lanes[i].ab = alphabet_bits[i]; + lanes[i].target = static_cast(target_symbols_per_lane); + } + + uint32_t slots = 0; + size_t pos = 0; + uint64_t cycle = 0; + uint64_t max_cycles = 64ull * (num_lanes * target_symbols_per_lane + input_size) + 1000; + uint64_t total_syms = 0; + size_t last_pos = SIZE_MAX; + uint64_t last_total_syms = UINT64_MAX; + uint32_t last_state_sum = UINT32_MAX; + uint64_t last_change = 0; + + while (cycle < max_cycles) { + size_t served = 0; + uint32_t active = 0; + bool finished = true; + bool failed = false; + uint32_t state_sum = 0; + for (size_t i = 0; i < num_lanes; ++i) { + Lane& ln = lanes[i]; + uint32_t bit = 1u << i; + bool blocked_out = ln.sym_full && ((slots & bit) != 0); + bool need = !ln.ib_full && ((ln.state >= LANE_HDR0 && ln.state <= LANE_HDR2) || + (ln.state == LANE_PROC && ln.in_rem > 0)); + // The reference's exhausted mask is implied: pos never moves back from input_size. + bool valid = need && !blocked_out && served < 8 && pos < input_size; + bool stall = (need && !valid) || blocked_out; + if (!stall) { + if (ln.state == LANE_PROC || ln.state == LANE_DRAIN) { + ln.p0 = ln.sym_full ? lane_f[i] * (ln.p1 >> 16) + (ln.p1 & 0xFFFF) - lane_cf[i] : ln.p1; + } + if (valid) { + ln.ib = input[pos]; + ln.ib_full = true; + pos++; + served++; + } + if (ln.sym_full) { + slots |= bit; + symbols[i * target_symbols_per_lane + ln.nsyms] = ln.sym; + ln.nsyms++; + total_syms++; + ln.sym_full = false; + } + } + // After a failed phase 1 the reference still ran phase 0 for every lane, but no phase 1. + bool skip = stall || failed; + bool short_step = skip; + if (!skip && ln.state == LANE_PROC) { + bool will = ln.p0 < 0x1000000 && ln.ib_full; + if (ln.in_rem > static_cast(will)) { + short_step = true; + uint32_t x = will ? ((ln.p0 << 8) | ln.ib) : ln.p0; + bool nsf = (x > 0x1000000) && (ln.out_rem > 0); + if (nsf) { + ln.out_rem--; + ln.sym = model_inverse_interval(ln.eab, ln.q, x & 0xFFFF, lane_f[i], lane_cf[i]); + } + ln.p1 = x; + ln.sym_full = nsf; + if (will) { + ln.in_rem--; + ln.ib_full = false; + } + } + } else if (!skip && ln.state == LANE_DRAIN && ln.p0 >= LANE_DRAIN_SHORT_MIN) { + short_step = true; + bool nsf = ln.out_rem > 0; + if (nsf) { + ln.out_rem--; + ln.sym = model_inverse_interval(ln.eab, ln.q, ln.p0 & 0xFFFF, lane_f[i], lane_cf[i]); + } + ln.p1 = ln.p0; + ln.sym_full = nsf; + } + if (!short_step) { + if (!phase1(ln)) { + failed = true; + } else if (ln.sym_full) { + model_forward(ln.eab, ln.q, ln.sym, lane_f[i], lane_cf[i]); + } + } + if (!(ln.done && !ln.sym_full && (slots & bit) == 0)) { + active |= bit; + } + finished &= (ln.done && !ln.sym_full); + state_sum += ln.state; + } + if (failed) return false; + + if (slots != 0 && (slots & active) == active) { + slots = 0; + } + cycle++; + if (finished) { + for (size_t i = 0; i < num_lanes; ++i) { + uint32_t f = lanes[i].final_state; + if (f != 0x1000000 && f != 0x10000 && f != 0x100) { + return false; + } + } + for (size_t p = pos; p < input_size; ++p) { + if (input[p] != 0) return false; + } + return true; + } + + if (pos != last_pos || total_syms != last_total_syms || state_sum != last_state_sum) { + last_pos = pos; + last_total_syms = total_syms; + last_state_sum = state_sum; + last_change = cycle; + } else if (cycle - last_change > 64) { + return false; + } + } + return false; +} + +enum LanePath : int { LANE_PATH_REFERENCE, LANE_PATH_SCALAR, LANE_PATH_COUNT }; + +inline bool lane_path_supported(int path) { + return path == LANE_PATH_REFERENCE || path == LANE_PATH_SCALAR; +} + +inline int best_lane_path() { + return LANE_PATH_SCALAR; +} + +#ifdef X2W_BCPACK_LANE_TESTS +// Test-only switch, compiled only into tests that define X2W_BCPACK_LANE_TESTS for the whole binary: +// when set to a supported LanePath, decode_lanes uses it. +inline int lane_path_override = -1; +#endif + +inline bool decode_lanes_on(int path, const uint8_t* input, size_t input_size, + const uint8_t* alphabet_bits, size_t num_lanes, + size_t target_symbols_per_lane, + std::vector& symbols) { + switch (path) { + case LANE_PATH_REFERENCE: + return decode_lanes_reference(input, input_size, alphabet_bits, num_lanes, target_symbols_per_lane, symbols); + case LANE_PATH_SCALAR: + return decode_lanes_scalar(input, input_size, alphabet_bits, num_lanes, target_symbols_per_lane, symbols); + default: + return false; + } +} + +inline bool decode_lanes(const uint8_t* input, size_t input_size, + const uint8_t* alphabet_bits, size_t num_lanes, + size_t target_symbols_per_lane, + std::vector& symbols) { +#ifdef X2W_BCPACK_LANE_TESTS + int path = lane_path_supported(lane_path_override) ? lane_path_override : best_lane_path(); +#else + int path = best_lane_path(); +#endif + return decode_lanes_on(path, input, input_size, alphabet_bits, num_lanes, target_symbols_per_lane, symbols); +} + inline constexpr uint8_t SUBSETS[8] = { 3, 2, 3, 2, 1, 1, 1, 2 }; inline constexpr uint8_t CHANNEL_BITS[8][4] = { { 4, 4, 4, 0 }, diff --git a/tests/bcpack_lanes_check.cpp b/tests/bcpack_lanes_check.cpp new file mode 100644 index 0000000000..3a38200415 --- /dev/null +++ b/tests/bcpack_lanes_check.cpp @@ -0,0 +1,307 @@ +// Differential check of every decode_lanes path (src/startup_stubs/bcpack_decoder.h) against +// decode_lanes_reference, the original cycle loop: the two repository BC1 vectors, the 16-lane +// mode-6 vector of tests/bcpack_mode6_vector.py and synthetic BC1/BC7 streams from +// tests/bcpack_encoder.h, each whole, truncated and with single bits flipped. Every path must give +// the reference's accept or reject decision and the same symbols (on rejection too), and +// decode_bcpack must leave the same destination bytes, including streams that the reference +// accepts although they are damaged. Inputs end at a no-access page and the destination sits +// between a canary and a no-access page. The model shortcut is compared on all inputs. +// +// bcpack_lanes_check VECTOR_DIR [--path NAME] [--full] check (--full: every truncation and bit flip) +// bcpack_lanes_check VECTOR_DIR --bench [--large] +// +// With --path, only that path is compared with the reference, and the exit code is 77 (capability +// skip) when this CPU does not support it. Without --path, every supported path is compared. +#include "bcpack_encoder.h" + +#include + +#include +#include +#include +#include +#include +#include + +namespace { + +using namespace x2w_bcpack; + +const uint8_t AB1[12] = { 7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7 }; +const uint8_t AB7[16] = { 3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4 }; +const char* const PATH_NAMES[LANE_PATH_COUNT] = { "reference", "scalar" }; +int only_path = -1; // --path: the one path compared with the reference + +// tests/bcpack_mode6_vector.py (issue #442): one BC7 block. +const char MODE6_HEX[] = + "101010101010101004040303030304040101010101010140" + "000000000000024002027546281800000101df5f4b7c0341" + "020202411010101004040403101010104004100103030304" + "4001080001010104000000080000000041020994e4db27a4" + "410511fe6b020005"; + +struct Stream { + std::string name; + unsigned format; // 1 or 7 + size_t blocks; + std::vector bytes; +}; + +std::vector from_hex(const std::string& hex) { + std::vector out; + for (size_t i = 0; i + 1 < hex.size(); i += 2) out.push_back(static_cast(std::stoi(hex.substr(i, 2), nullptr, 16))); + return out; +} + +bool load_vector(const std::string& path, Stream& s) { + std::ifstream f(path, std::ios::binary); + std::stringstream ss; + ss << f.rdbuf(); + const std::string text = ss.str(); + const size_t hex = text.find("\"chunk_hex\":\""); + const size_t blocks = text.find("\"blocks\":"); + if (hex == std::string::npos || blocks == std::string::npos) return false; + const size_t start = hex + 13; + s.bytes = from_hex(text.substr(start, text.find('"', start) - start)); + s.blocks = std::stoul(text.substr(blocks + 9)); + s.format = 1; + return !s.bytes.empty(); +} + +// A region whose last byte is followed by a no-access page. +struct Guarded { + uint8_t* base = nullptr; + size_t span = 0; + explicit Guarded(size_t size) { + span = (size + 0xFFFF) & ~size_t(0xFFFF); + base = static_cast(VirtualAlloc(nullptr, span + 0x1000, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE)); + DWORD old; + if (!base || !VirtualProtect(base + span, 0x1000, PAGE_NOACCESS, &old)) std::abort(); + } + ~Guarded() { VirtualFree(base, 0, MEM_RELEASE); } + uint8_t* tail(size_t size) const { return base + span - size; } +}; + +struct Checker { + Guarded in{ 8u << 20 }; + Guarded out{ (4u << 20) + 64 }; + int failures = 0; + size_t compared = 0, accepted = 0, rejected = 0, damaged_accepted = 0; + + struct Result { + bool ok = false; + std::vector symbols; + bool bc_ok = false; + size_t produced = 0; + std::vector dest; + }; + + void run(int path, const Stream& s, const uint8_t* data, size_t size, Result& r) { + const uint8_t* ab = s.format == 7 ? AB7 : AB1; + const size_t n = s.format == 7 ? 16 : 12, target = s.format == 7 ? 2 * s.blocks : s.blocks; + r.ok = decode_lanes_on(path, data, size, ab, n, target, r.symbols); + const size_t dest_size = s.blocks * (s.format == 7 ? 16 : 8); + uint8_t* dest = out.tail(dest_size); + std::memset(dest - 64, 0x5A, 64); + std::memset(dest, 0xA5, dest_size); + r.produced = 0x12345; + lane_path_override = path; + r.bc_ok = decode_bcpack(data, size, s.format, dest, dest_size, &r.produced); + lane_path_override = -1; + for (int k = 0; k < 64; ++k) { + if (dest[k - 64] != 0x5A) fail(s, "canary before the destination overwritten", path, size); + } + r.dest.assign(dest, dest + dest_size); + } + + void fail(const Stream& s, const char* what, int path, size_t size) { + if (failures++ < 12) std::fprintf(stderr, "%s, %zu bytes, %s path: %s\n", s.name.c_str(), size, PATH_NAMES[path], what); + } + + // data: the stream as given (whole, truncated or with a flipped bit); intact: true for the encoder's output. + void compare(const Stream& s, const std::vector& data, bool intact) { + uint8_t* p = in.tail(data.size()); + if (!data.empty()) std::memcpy(p, data.data(), data.size()); + Result ref; + run(LANE_PATH_REFERENCE, s, p, data.size(), ref); + ++compared; + ref.ok ? ++accepted : ++rejected; + if (ref.ok && !intact) ++damaged_accepted; + if (intact && (!ref.ok || !ref.bc_ok)) fail(s, "the reference rejects an intact stream", LANE_PATH_REFERENCE, data.size()); + for (int path = LANE_PATH_REFERENCE + 1; path < LANE_PATH_COUNT; ++path) { + if (!lane_path_supported(path) || (only_path >= 0 && path != only_path)) continue; + Result r; + run(path, s, p, data.size(), r); + if (r.ok != ref.ok) fail(s, "accept/reject differs from the reference", path, data.size()); + if (r.symbols != ref.symbols) fail(s, "symbols differ from the reference", path, data.size()); + if (r.bc_ok != ref.bc_ok || r.produced != ref.produced) fail(s, "decode_bcpack result differs", path, data.size()); + if (r.dest != ref.dest) fail(s, "destination bytes differ", path, data.size()); + } + } + + void sweep(const Stream& s, bool full) { + compare(s, s.bytes, true); + const size_t size = s.bytes.size(); + const size_t cut_step = full ? 1 : (size / 48 + 1), bit_step = full ? 1 : (size * 8 / 160 + 1); + for (size_t len = 0; len < size; len += cut_step) compare(s, std::vector(s.bytes.begin(), s.bytes.begin() + len), false); + for (size_t len = size > 16 ? size - 16 : 0; len < size; ++len) compare(s, std::vector(s.bytes.begin(), s.bytes.begin() + len), false); + for (size_t bit = 0; bit < size * 8; bit += bit_step) { + std::vector flipped = s.bytes; + flipped[bit / 8] ^= static_cast(1u << (bit % 8)); + compare(s, flipped, false); + } + } +}; + +std::vector streams(const std::string& dir, bool bench, bool large) { + std::vector list; + for (const char* v : { "synthetic_11", "synthetic_12" }) { + Stream s; + s.name = v; + if (!load_vector(dir + "/" + v + ".json", s)) { + std::fprintf(stderr, "cannot read %s/%s.json\n", dir.c_str(), v); + std::exit(1); + } + list.push_back(s); + } + if (!bench) list.push_back({ "mode6", 7, 1, from_hex(MODE6_HEX) }); + bcpack_test::Rng rng{ bench ? 7u : 1139u }; + auto add = [&](unsigned format, size_t blocks, uint32_t fragment, bool uniform, size_t padding) { + bcpack_test::Options o; + o.max_fragment = fragment; + o.uniform = uniform; + o.padding = padding; + o.bc7_lane = format == 7 ? 15 : -1; + Stream s{ "", format, blocks, {} }; + std::vector symbols; + const size_t n = format == 7 ? 16 : 12, target = format == 7 ? 2 * blocks : blocks; + if (!bcpack_test::make_stream(format == 7 ? AB7 : AB1, n, target, rng, o, s.bytes, symbols)) std::abort(); + char name[96]; + std::snprintf(name, sizeof name, "BC%u %zu blocks, fragments <= %u%s", format, blocks, fragment, uniform ? ", uniform" : ""); + s.name = name; + list.push_back(s); + }; + if (bench) { + for (unsigned format : { 1u, 7u }) { + const size_t blocks = large ? (4u << 20) / (format == 7 ? 16 : 8) : (512u << 10) / (format == 7 ? 16 : 8); + add(format, blocks, 150, false, 0); + add(format, blocks, 4096, false, 0); + } + } else { + for (unsigned format : { 1u, 7u }) { + add(format, 1, 8, false, 0); + add(format, 40, 8, false, 2); + add(format, 300, 150, false, 0); + add(format, 300, 150, true, 1); + add(format, 300, 4096, false, 0); + } + } + return list; +} + +uint64_t fnv(const void* data, size_t size, uint64_t h = 1469598103934665603ull) { + for (size_t i = 0; i < size; ++i) h = (h ^ static_cast(data)[i]) * 1099511628211ull; + return h; +} + +int bench(const std::vector& list) { + using clock = std::chrono::steady_clock; + for (const Stream& s : list) { + const uint8_t* ab = s.format == 7 ? AB7 : AB1; + const size_t n = s.format == 7 ? 16 : 12, target = s.format == 7 ? 2 * s.blocks : s.blocks; + const size_t syms = n * target, dest_size = s.blocks * (s.format == 7 ? 16 : 8); + const int reps = static_cast(syms > 1000000 ? 1 : 2000000 / syms); + double lanes_best[LANE_PATH_COUNT], total_best[LANE_PATH_COUNT]; + uint64_t sums[LANE_PATH_COUNT] = {}; + std::vector dest(dest_size); + std::vector symbols; + for (int p = 0; p < LANE_PATH_COUNT; ++p) lanes_best[p] = total_best[p] = 1e30; + for (int round = 0; round < 8; ++round) { // round 0 is a warm-up + for (int p = 0; p < LANE_PATH_COUNT; ++p) { // paths interleaved within each round + if (!lane_path_supported(p)) continue; + auto t0 = clock::now(); + for (int k = 0; k < reps; ++k) { + if (!decode_lanes_on(p, s.bytes.data(), s.bytes.size(), ab, n, target, symbols)) return 1; + } + auto t1 = clock::now(); + lane_path_override = p; + size_t produced = 0; + for (int k = 0; k < reps; ++k) { + if (!decode_bcpack(s.bytes.data(), s.bytes.size(), s.format, dest.data(), dest.size(), &produced)) return 1; + } + lane_path_override = -1; + auto t2 = clock::now(); + if (round == 0) continue; + lanes_best[p] = (std::min)(lanes_best[p], std::chrono::duration(t1 - t0).count() / reps); + total_best[p] = (std::min)(total_best[p], std::chrono::duration(t2 - t1).count() / reps); + sums[p] = fnv(dest.data(), dest.size(), fnv(symbols.data(), symbols.size() * 2)); + } + } + std::printf("%s: %zu stream bytes, %zu symbols, %.2f MiB out\n", s.name.c_str(), s.bytes.size(), syms, dest_size / 1048576.0); + for (int p = 0; p < LANE_PATH_COUNT; ++p) { + if (!lane_path_supported(p)) continue; + std::printf(" %-9s lanes %6.2f ns/symbol decode_bcpack %7.2f ms %7.1f MiB/s x%.2f checksum %016llx\n", PATH_NAMES[p], + lanes_best[p] * 1e9 / syms, total_best[p] * 1e3, dest_size / 1048576.0 / total_best[p], + total_best[LANE_PATH_REFERENCE] / total_best[p], static_cast(sums[p])); + if (sums[p] != sums[LANE_PATH_REFERENCE]) return 1; + } + } + return 0; +} + +// model_inverse_interval against model_inverse_fast + model_forward for every model and low state. +int check_interval() { + for (uint8_t eab = 0; eab < 9; ++eab) { + for (uint8_t q = 0; q < 16; ++q) { + for (uint32_t c = 0; c < 65536; ++c) { + uint32_t f, cf, rf, rcf; + const uint16_t s = model_inverse_interval(eab, q, c, f, cf); + const uint16_t rs = model_inverse_fast(eab, q, static_cast(c)); + model_forward(eab, q, rs, rf, rcf); + if (s != rs || f != rf || cf != rcf) { + std::fprintf(stderr, "model_inverse_interval differs: eab %u q %u cf %u\n", eab, q, c); + return 1; + } + } + } + } + return 0; +} + +} // namespace + +int main(int argc, char** argv) { + bool full = false, do_bench = false, large = false, usage = argc < 2; + for (int k = 2; k < argc; ++k) { + if (std::strcmp(argv[k], "--full") == 0) full = true; + else if (std::strcmp(argv[k], "--bench") == 0) do_bench = true; + else if (std::strcmp(argv[k], "--large") == 0) large = true; + else if (std::strcmp(argv[k], "--path") == 0 && k + 1 < argc) { + ++k; + for (int p = LANE_PATH_REFERENCE + 1; p < LANE_PATH_COUNT; ++p) { + if (std::strcmp(argv[k], PATH_NAMES[p]) == 0) only_path = p; + } + usage |= only_path < 0; + } else usage = true; + } + if (usage) { + std::fprintf(stderr, "usage: bcpack_lanes_check VECTOR_DIR [--path NAME] [--full | --bench [--large]]\n"); + return 64; + } + std::printf("lane paths:"); + for (int p = 0; p < LANE_PATH_COUNT; ++p) std::printf(" %s%s", PATH_NAMES[p], lane_path_supported(p) ? "" : " (not supported)"); + std::printf("; decode_lanes uses %s\n", PATH_NAMES[best_lane_path()]); + if (only_path >= 0 && !lane_path_supported(only_path)) { + std::printf("capability skip: the %s path is not supported here\n", PATH_NAMES[only_path]); + return 77; + } + const std::vector list = streams(argv[1], do_bench, large); + if (do_bench) return bench(list); + + if (check_interval() != 0) return 1; + Checker checker; + for (const Stream& s : list) checker.sweep(s, full); + std::printf("%zu streams compared (%zu accepted, %zu rejected by the reference; %zu damaged streams accepted), %d mismatches\n", + checker.compared, checker.accepted, checker.rejected, checker.damaged_accepted, checker.failures); + return checker.failures == 0 ? 0 : 1; +} From ad98d001e07108e3a40c18d5996f88c5248aad82 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 23:49:15 +0100 Subject: [PATCH 3/8] bcpack: decode the lanes of a cycle side by side with AVX2 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 --- CMakeLists.txt | 2 +- src/startup_stubs/bcpack_decoder.h | 299 ++++++++++++++++++++++++++++- tests/bcpack_lanes_check.cpp | 2 +- 3 files changed, 298 insertions(+), 5 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 8041194eb5..90e9a48285 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -630,7 +630,7 @@ foreach(variant IN ITEMS check control) target_compile_definitions(bcpack_lanes_${variant} PRIVATE X2W_BCPACK_LANE_TESTS) endforeach() target_compile_definitions(bcpack_lanes_control PRIVATE X2W_BCPACK_LANES_CONTROL) -set(bcpack_lane_paths scalar) +set(bcpack_lane_paths scalar avx2) foreach(path IN LISTS bcpack_lane_paths) add_test(NAME bcpack_lanes_${path} COMMAND bcpack_lanes_check "${CMAKE_SOURCE_DIR}/tools/_bcpack_rans/vectors" --path ${path}) add_test(NAME bcpack_lanes_${path}_drain_control diff --git a/src/startup_stubs/bcpack_decoder.h b/src/startup_stubs/bcpack_decoder.h index 8d11bb957f..8d92424d0f 100644 --- a/src/startup_stubs/bcpack_decoder.h +++ b/src/startup_stubs/bcpack_decoder.h @@ -11,6 +11,9 @@ #include #include #include +#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_X64) +#include +#endif #include "bcpack_tables.h" @@ -521,14 +524,300 @@ inline bool decode_lanes_scalar(const uint8_t* input, size_t input_size, return false; } -enum LanePath : int { LANE_PATH_REFERENCE, LANE_PATH_SCALAR, LANE_PATH_COUNT }; +#if defined(_MSC_VER) && !defined(__clang__) && defined(_M_X64) +#define X2W_BCPACK_LANE_SIMD 1 + +// AVX, AVX2 and POPCNT, and an OS that saves the YMM state. +inline bool lane_avx2_supported() { + static const bool supported = [] { + int r[4]; + __cpuid(r, 0); + if (r[0] < 7) return false; + __cpuid(r, 1); + const int popcnt_osxsave_avx = (1 << 23) | (1 << 27) | (1 << 28); + if ((r[2] & popcnt_osxsave_avx) != popcnt_osxsave_avx) return false; + if ((_xgetbv(0) & 0x6) != 0x6) return false; // XMM and YMM state + __cpuidex(r, 7, 0); + return (r[1] & (1 << 5)) != 0; // AVX2 + }(); + return supported; +} + +// The lowest count set bits of mask. Not pdep, which is microcoded on AMD cores before Zen 3. +inline uint32_t lowest_bits(uint32_t mask, uint32_t count) { + uint32_t kept = 0; + for (uint32_t k = 0; k < count; ++k, mask &= mask - 1) kept |= mask & (0u - mask); + return kept; +} + +// For each 8-bit lane mask, the source byte of every lane when the set lanes take consecutive bytes. +struct LaneExpandTable { + uint8_t index[256][8]; + constexpr LaneExpandTable() : index() { + for (int m = 0; m < 256; ++m) { + int next = 0; + for (int lane = 0; lane < 8; ++lane) index[m][lane] = static_cast((m >> lane) & 1 ? next++ : 0); + } + } +}; +inline constexpr LaneExpandTable LANE_EXPAND{}; + +// decode_lanes_scalar with each per-lane field of up to 16 lanes held as two 8-lane AVX2 halves. The +// byte arbitration is a mask computation: the first min(8, bytes left) requesting lanes, in lane order, +// receive the next stream bytes (lowest_bits picks them; LANE_EXPAND with vpermd places them). Lanes +// whose step is a header, an idle start, a fragment end or a flush run the existing phase1 one by one, +// in lane order, after the vector step. Phase 0 of every lane precedes every phase 1, as in the +// reference, so a rejection leaves the same symbols. Within a segment the symbol's interval follows +// from the inverse (model_inverse_interval). Lane masks are kept as bits; vector masks are rebuilt from +// them, and unsigned compares use a sign flip. +inline bool decode_lanes_avx2_body(const uint8_t* input, size_t input_size, + const uint8_t* alphabet_bits, size_t num_lanes, + size_t target_symbols_per_lane, + std::vector& symbols) { + if (num_lanes == 0 || num_lanes > 16 || target_symbols_per_lane == 0) return false; + for (size_t i = 0; i < num_lanes; ++i) { + if (alphabet_bits[i] > 8) return false; + } + symbols.assign(num_lanes * target_symbols_per_lane, 0); + const size_t target = target_symbols_per_lane; + const uint32_t lane_mask = (1u << num_lanes) - 1; + + Lane lanes[16]; + alignas(32) uint32_t p0[16] = {}, p1[16] = {}, in_rem[16] = {}, out_rem[16] = {}; + alignas(32) uint32_t sym[16] = {}, lane_f[16] = {}, lane_cf[16] = {}, ib[16] = {}; + alignas(32) uint32_t bound[9][16], base_rn[10][16], freq_rs[10][16], rf[10][16]; + uint32_t nsyms[16] = {}; + uint8_t row_eab[16], row_q[16]; + auto load_rows = [&](size_t i) { + const uint8_t e = lanes[i].eab, q = lanes[i].q; + row_eab[i] = e; + row_q[i] = q; + for (uint32_t k = 1; k < 10; ++k) bound[k - 1][i] = (k <= e + 1u) ? BASE_TABLE[e][q][k] : 0x10000u; + for (uint32_t k = 0; k < 10; ++k) { + base_rn[k][i] = BASE_TABLE[e][q][k] | (uint32_t(RN_TABLE[e][q][k]) << 16); + freq_rs[k][i] = FREQ_TABLE[e][q][k] | (uint32_t(RS_TABLE[e][q][k]) << 16); + rf[k][i] = RF_TABLE[e][q][k]; + } + }; + for (size_t i = 0; i < 16; ++i) { + if (i < num_lanes) { + lanes[i].ab = alphabet_bits[i]; + lanes[i].target = static_cast(target); + } + load_rows(i); + } + uint32_t ib_full = 0, sym_full = 0, proc = 0, drain = 0, header = 0, quiet = 0, done = 0; + auto set_bit = [](uint32_t& m, uint32_t bit, bool on) { m = on ? (m | bit) : (m & ~bit); }; + + const __m256i one = _mm256_set1_epi32(1), low16 = _mm256_set1_epi32(0xFFFF), sign = _mm256_set1_epi32(INT32_MIN); + const __m256i home_s = _mm256_set1_epi32(static_cast(0x1000000u ^ 0x80000000u)); + const __m256i drain_min_s = _mm256_set1_epi32(static_cast(LANE_DRAIN_SHORT_MIN ^ 0x80000000u)); + const __m256i lane_bits = _mm256_set_epi32(128, 64, 32, 16, 8, 4, 2, 1); + const __m256i lane_index = _mm256_set_epi32(7, 6, 5, 4, 3, 2, 1, 0); + auto bits_of = [](__m256i lo, __m256i hi) { + return static_cast(_mm256_movemask_ps(_mm256_castsi256_ps(lo))) | + (static_cast(_mm256_movemask_ps(_mm256_castsi256_ps(hi))) << 8); + }; + auto mask_of = [&](uint32_t m, int h) { + return _mm256_cmpeq_epi32(_mm256_and_si256(_mm256_set1_epi32(static_cast((m >> (8 * h)) & 0xFF)), lane_bits), lane_bits); + }; + auto load = [](const uint32_t* a, int h) { return _mm256_load_si256(reinterpret_cast(a + 8 * h)); }; + auto store = [](uint32_t* a, int h, __m256i v) { _mm256_store_si256(reinterpret_cast<__m256i*>(a + 8 * h), v); }; + + uint32_t slots = 0; + size_t pos = 0; + uint64_t cycle = 0; + uint64_t max_cycles = 64ull * (num_lanes * target_symbols_per_lane + input_size) + 1000; + uint64_t total_syms = 0; + size_t last_pos = SIZE_MAX; + uint64_t last_total_syms = UINT64_MAX; + uint32_t last_state_sum = UINT32_MAX; + uint64_t last_change = 0; + uint32_t state_sum = 0; + + while (cycle < max_cycles) { + __m256i v_in_rem[2], v_ib[2], v_p0[2], v_p1[2], v_x[2], v_out[2]; + for (int h = 0; h < 2; ++h) v_in_rem[h] = load(in_rem, h); + const uint32_t in_left = ~bits_of(_mm256_cmpeq_epi32(v_in_rem[0], _mm256_setzero_si256()), + _mm256_cmpeq_epi32(v_in_rem[1], _mm256_setzero_si256())) & 0xFFFF; + const uint32_t blocked = sym_full & slots; + const uint32_t need = ~ib_full & (header | (proc & in_left)) & lane_mask; + const uint32_t request = need & ~blocked; + const size_t left = input_size - pos; + const uint32_t avail = left < 8 ? static_cast(left) : 8u; + uint32_t valid = request; + if (static_cast(_mm_popcnt_u32(request)) > avail) valid = lowest_bits(request, avail); + const uint32_t run = lane_mask & ~((need & ~valid) | blocked); + uint64_t raw = 0; + if (avail != 0) std::memcpy(&raw, input + pos, avail); + const uint32_t low_taken = static_cast(_mm_popcnt_u32(valid & 0xFF)); + const uint64_t raw_half[2] = { raw, low_taken < 8 ? raw >> (8 * low_taken) : 0 }; + ib_full |= valid; + pos += _mm_popcnt_u32(valid); + + const uint32_t pd = proc | drain; + const uint32_t emit = run & sym_full; + for (int h = 0; h < 2; ++h) { + const uint32_t vh = (valid >> (8 * h)) & 0xFF; + const __m256i bytes = _mm256_permutevar8x32_epi32( + _mm256_cvtepu8_epi32(_mm_cvtsi64_si128(static_cast(raw_half[h]))), + _mm256_cvtepu8_epi32(_mm_loadl_epi64(reinterpret_cast(LANE_EXPAND.index[vh])))); + v_ib[h] = _mm256_blendv_epi8(load(ib, h), bytes, mask_of(valid, h)); + v_p1[h] = load(p1, h); + const __m256i adv = _mm256_sub_epi32( + _mm256_add_epi32(_mm256_mullo_epi32(load(lane_f, h), _mm256_srli_epi32(v_p1[h], 16)), _mm256_and_si256(v_p1[h], low16)), + load(lane_cf, h)); + v_p0[h] = _mm256_blendv_epi8(load(p0, h), _mm256_blendv_epi8(v_p1[h], adv, mask_of(sym_full, h)), mask_of(run & pd, h)); + } + for (uint32_t m = emit; m != 0; m &= m - 1) { + unsigned long i; + _BitScanForward(&i, m); + symbols[i * target + nsyms[i]++] = static_cast(sym[i]); + } + slots |= emit; + total_syms += _mm_popcnt_u32(emit); + sym_full &= ~run; + + __m256i below_home[2], in_is_will[2], below_drain_min[2], above_home[2], out_left[2]; + for (int h = 0; h < 2; ++h) { + below_home[h] = _mm256_cmpgt_epi32(home_s, _mm256_xor_si256(v_p0[h], sign)); + } + const uint32_t will = proc & run & in_left & ib_full & bits_of(below_home[0], below_home[1]); + for (int h = 0; h < 2; ++h) { + const __m256i wm = mask_of(will, h); + v_x[h] = _mm256_blendv_epi8(v_p0[h], _mm256_or_si256(_mm256_slli_epi32(v_p0[h], 8), v_ib[h]), wm); + in_is_will[h] = _mm256_cmpeq_epi32(v_in_rem[h], _mm256_and_si256(wm, one)); + const __m256i xs = _mm256_xor_si256(v_x[h], sign); + below_drain_min[h] = _mm256_cmpgt_epi32(drain_min_s, xs); + above_home[h] = _mm256_cmpgt_epi32(xs, home_s); + v_out[h] = load(out_rem, h); + out_left[h] = _mm256_cmpeq_epi32(v_out[h], _mm256_setzero_si256()); + } + const uint32_t edge = (proc & bits_of(in_is_will[0], in_is_will[1])) | (drain & bits_of(below_drain_min[0], below_drain_min[1])); + const uint32_t simple = run & pd & ~edge; + const uint32_t generic = run & ((~pd & ~quiet) | (pd & edge)); + const uint32_t nsf = simple & bits_of(above_home[0], above_home[1]) & ~bits_of(out_left[0], out_left[1]); + const uint32_t consumed = simple & will; + for (int h = 0; h < 2; ++h) { + if (((nsf >> (8 * h)) & 0xFF) != 0) { + const __m256i c = _mm256_and_si256(v_x[h], low16); + __m256i seg = _mm256_set1_epi32(9); + for (int k = 0; k < 9; ++k) seg = _mm256_add_epi32(seg, _mm256_cmpgt_epi32(load(bound[k], h), c)); + const __m256i idx = _mm256_add_epi32(_mm256_slli_epi32(seg, 4), lane_index); + const __m256i v_base_rn = _mm256_i32gather_epi32(reinterpret_cast(&base_rn[0][8 * h]), idx, 4); + const __m256i v_freq_rs = _mm256_i32gather_epi32(reinterpret_cast(&freq_rs[0][8 * h]), idx, 4); + const __m256i v_rf = _mm256_i32gather_epi32(reinterpret_cast(&rf[0][8 * h]), idx, 4); + const __m256i base = _mm256_and_si256(v_base_rn, low16); + const __m256i freq = _mm256_and_si256(v_freq_rs, low16); + const __m256i dist = _mm256_and_si256(_mm256_add_epi32(_mm256_sub_epi32(c, base), _mm256_srli_epi32(v_base_rn, 16)), low16); + const __m256i steps = _mm256_and_si256( + _mm256_srlv_epi32(_mm256_srli_epi32(_mm256_mullo_epi32(dist, v_rf), 15), _mm256_srli_epi32(v_freq_rs, 16)), + _mm256_set1_epi32(0x1FF)); + const __m256i s = _mm256_and_si256(_mm256_add_epi32(_mm256_srli_epi32(_mm256_sllv_epi32(one, seg), 1), steps), + _mm256_set1_epi32(0x1FF)); + const __m256i cfa = _mm256_and_si256(_mm256_add_epi32(base, _mm256_mullo_epi32(freq, steps)), low16); + const __m256i zero = _mm256_cmpeq_epi32(cfa, _mm256_setzero_si256()); + const __m256i k = mask_of(nsf, h); + store(sym, h, _mm256_blendv_epi8(load(sym, h), s, k)); + store(lane_f, h, _mm256_blendv_epi8(load(lane_f, h), + _mm256_blendv_epi8(freq, _mm256_and_si256(_mm256_sub_epi32(freq, one), low16), zero), k)); + store(lane_cf, h, _mm256_blendv_epi8(load(lane_cf, h), _mm256_blendv_epi8(cfa, one, zero), k)); + v_out[h] = _mm256_add_epi32(v_out[h], k); // k is -1 where a symbol was decoded + } + store(p0, h, v_p0[h]); + store(p1, h, _mm256_blendv_epi8(v_p1[h], v_x[h], mask_of(simple, h))); + store(in_rem, h, _mm256_add_epi32(v_in_rem[h], mask_of(consumed, h))); + store(out_rem, h, v_out[h]); + store(ib, h, v_ib[h]); + } + sym_full |= nsf; + ib_full &= ~consumed; + + for (uint32_t m = generic; m != 0; m &= m - 1) { + unsigned long i; + _BitScanForward(&i, m); + const uint32_t bit = 1u << i; + Lane& ln = lanes[i]; + ln.p0 = p0[i]; + ln.p1 = p1[i]; + ln.in_rem = in_rem[i]; + ln.out_rem = out_rem[i]; + ln.sym = static_cast(sym[i]); + ln.ib = static_cast(ib[i]); + ln.ib_full = (ib_full & bit) != 0; + ln.sym_full = (sym_full & bit) != 0; + const uint32_t old_state = ln.state; + if (!phase1(ln)) return false; + p0[i] = ln.p0; + p1[i] = ln.p1; + in_rem[i] = ln.in_rem; + out_rem[i] = ln.out_rem; + sym[i] = ln.sym; + set_bit(ib_full, bit, ln.ib_full); + set_bit(sym_full, bit, ln.sym_full); + if (ln.sym_full) model_forward(ln.eab, ln.q, ln.sym, lane_f[i], lane_cf[i]); + state_sum += static_cast(ln.state) - old_state; + set_bit(proc, bit, ln.state == LANE_PROC); + set_bit(drain, bit, ln.state == LANE_DRAIN); + set_bit(header, bit, ln.state >= LANE_HDR0 && ln.state <= LANE_HDR2); + set_bit(quiet, bit, ln.state == LANE_IDLE && !ln.go); + set_bit(done, bit, ln.done); + if (ln.eab != row_eab[i] || ln.q != row_q[i]) load_rows(i); + } + + const uint32_t settled = done & ~sym_full; + const uint32_t active = lane_mask & ~(settled & ~slots); + if (slots != 0 && (slots & active) == active) { + slots = 0; + } + cycle++; + if ((settled & lane_mask) == lane_mask) { + for (size_t i = 0; i < num_lanes; ++i) { + uint32_t f = lanes[i].final_state; + if (f != 0x1000000 && f != 0x10000 && f != 0x100) { + return false; + } + } + for (size_t p = pos; p < input_size; ++p) { + if (input[p] != 0) return false; + } + return true; + } + + if (pos != last_pos || total_syms != last_total_syms || state_sum != last_state_sum) { + last_pos = pos; + last_total_syms = total_syms; + last_state_sum = state_sum; + last_change = cycle; + } else if (cycle - last_change > 64) { + return false; + } + } + return false; +} + +inline bool decode_lanes_avx2(const uint8_t* input, size_t input_size, + const uint8_t* alphabet_bits, size_t num_lanes, + size_t target_symbols_per_lane, + std::vector& symbols) { + bool ok = decode_lanes_avx2_body(input, input_size, alphabet_bits, num_lanes, target_symbols_per_lane, symbols); + _mm256_zeroupper(); + return ok; +} +#endif + +enum LanePath : int { LANE_PATH_REFERENCE, LANE_PATH_SCALAR, LANE_PATH_AVX2, LANE_PATH_COUNT }; inline bool lane_path_supported(int path) { - return path == LANE_PATH_REFERENCE || path == LANE_PATH_SCALAR; + if (path == LANE_PATH_REFERENCE || path == LANE_PATH_SCALAR) return true; +#ifdef X2W_BCPACK_LANE_SIMD + if (path == LANE_PATH_AVX2) return lane_avx2_supported(); +#endif + return false; } inline int best_lane_path() { - return LANE_PATH_SCALAR; + return lane_path_supported(LANE_PATH_AVX2) ? LANE_PATH_AVX2 : LANE_PATH_SCALAR; } #ifdef X2W_BCPACK_LANE_TESTS @@ -546,6 +835,10 @@ inline bool decode_lanes_on(int path, const uint8_t* input, size_t input_size, return decode_lanes_reference(input, input_size, alphabet_bits, num_lanes, target_symbols_per_lane, symbols); case LANE_PATH_SCALAR: return decode_lanes_scalar(input, input_size, alphabet_bits, num_lanes, target_symbols_per_lane, symbols); +#ifdef X2W_BCPACK_LANE_SIMD + case LANE_PATH_AVX2: + return decode_lanes_avx2(input, input_size, alphabet_bits, num_lanes, target_symbols_per_lane, symbols); +#endif default: return false; } diff --git a/tests/bcpack_lanes_check.cpp b/tests/bcpack_lanes_check.cpp index 3a38200415..4bd10bd608 100644 --- a/tests/bcpack_lanes_check.cpp +++ b/tests/bcpack_lanes_check.cpp @@ -29,7 +29,7 @@ using namespace x2w_bcpack; const uint8_t AB1[12] = { 7, 7, 4, 5, 4, 4, 5, 4, 7, 7, 7, 7 }; const uint8_t AB7[16] = { 3, 3, 7, 7, 7, 7, 7, 6, 6, 4, 5, 7, 7, 7, 7, 4 }; -const char* const PATH_NAMES[LANE_PATH_COUNT] = { "reference", "scalar" }; +const char* const PATH_NAMES[LANE_PATH_COUNT] = { "reference", "scalar", "avx2" }; int only_path = -1; // --path: the one path compared with the reference // tests/bcpack_mode6_vector.py (issue #442): one BC7 block. From 8bfe99cffb283a101f7517bafbc5ff7db5ce28c7 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 23:51:07 +0100 Subject: [PATCH 4/8] tests: cover other lane tables and symbol counts in the lane check 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 --- tests/bcpack_lanes_check.cpp | 50 ++++++++++++++++++++++++++++++++---- 1 file changed, 45 insertions(+), 5 deletions(-) diff --git a/tests/bcpack_lanes_check.cpp b/tests/bcpack_lanes_check.cpp index 4bd10bd608..29727c0c8a 100644 --- a/tests/bcpack_lanes_check.cpp +++ b/tests/bcpack_lanes_check.cpp @@ -42,9 +42,12 @@ const char MODE6_HEX[] = struct Stream { std::string name; - unsigned format; // 1 or 7 + unsigned format; // 1 or 7; with lane widths below, decode_lanes only size_t blocks; std::vector bytes; + std::vector ab; // lane widths of a lanes-only stream + size_t target = 0; // symbols per lane of a lanes-only stream + bool whole_only = false; // compared whole only (a stream decoded with the wrong table or count) }; std::vector from_hex(const std::string& hex) { @@ -97,6 +100,10 @@ struct Checker { }; void run(int path, const Stream& s, const uint8_t* data, size_t size, Result& r) { + if (!s.ab.empty()) { + r.ok = decode_lanes_on(path, data, size, s.ab.data(), s.ab.size(), s.target, r.symbols); + return; + } const uint8_t* ab = s.format == 7 ? AB7 : AB1; const size_t n = s.format == 7 ? 16 : 12, target = s.format == 7 ? 2 * s.blocks : s.blocks; r.ok = decode_lanes_on(path, data, size, ab, n, target, r.symbols); @@ -127,7 +134,7 @@ struct Checker { ++compared; ref.ok ? ++accepted : ++rejected; if (ref.ok && !intact) ++damaged_accepted; - if (intact && (!ref.ok || !ref.bc_ok)) fail(s, "the reference rejects an intact stream", LANE_PATH_REFERENCE, data.size()); + if (intact && (!ref.ok || (s.ab.empty() && !ref.bc_ok))) fail(s, "the reference rejects an intact stream", LANE_PATH_REFERENCE, data.size()); for (int path = LANE_PATH_REFERENCE + 1; path < LANE_PATH_COUNT; ++path) { if (!lane_path_supported(path) || (only_path >= 0 && path != only_path)) continue; Result r; @@ -140,7 +147,8 @@ struct Checker { } void sweep(const Stream& s, bool full) { - compare(s, s.bytes, true); + compare(s, s.bytes, !s.whole_only); + if (s.whole_only) return; const size_t size = s.bytes.size(); const size_t cut_step = full ? 1 : (size / 48 + 1), bit_step = full ? 1 : (size * 8 / 160 + 1); for (size_t len = 0; len < size; len += cut_step) compare(s, std::vector(s.bytes.begin(), s.bytes.begin() + len), false); @@ -164,7 +172,7 @@ std::vector streams(const std::string& dir, bool bench, bool large) { } list.push_back(s); } - if (!bench) list.push_back({ "mode6", 7, 1, from_hex(MODE6_HEX) }); + if (!bench) list.push_back({ "mode6", 7, 1, from_hex(MODE6_HEX), {}, 0, false }); bcpack_test::Rng rng{ bench ? 7u : 1139u }; auto add = [&](unsigned format, size_t blocks, uint32_t fragment, bool uniform, size_t padding) { bcpack_test::Options o; @@ -172,7 +180,7 @@ std::vector streams(const std::string& dir, bool bench, bool large) { o.uniform = uniform; o.padding = padding; o.bc7_lane = format == 7 ? 15 : -1; - Stream s{ "", format, blocks, {} }; + Stream s{ "", format, blocks, {}, {}, 0, false }; std::vector symbols; const size_t n = format == 7 ? 16 : 12, target = format == 7 ? 2 * blocks : blocks; if (!bcpack_test::make_stream(format == 7 ? AB7 : AB1, n, target, rng, o, s.bytes, symbols)) std::abort(); @@ -195,6 +203,38 @@ std::vector streams(const std::string& dir, bool bench, bool large) { add(format, 300, 150, true, 1); add(format, 300, 4096, false, 0); } + // Each stream with one block more or fewer, and with the other format's lane table. + const size_t base_count = list.size(); + for (size_t k = 0; k < base_count; ++k) { + const Stream b = list[k]; + const size_t own = b.format == 7 ? 2 * b.blocks : b.blocks; + const std::vector t1(AB1, AB1 + 12), t7(AB7, AB7 + 16); + for (size_t count : { own + 1, own - 1 }) { + if (count > 0) list.push_back({ b.name + ", wrong symbol count", 0, 0, b.bytes, b.format == 7 ? t7 : t1, count, true }); + } + list.push_back({ b.name + ", other lane table", 0, 0, b.bytes, b.format == 7 ? t1 : t7, own, true }); + } + // Lane counts and widths beyond the BC1 and BC7 tables, including PR 1390's BC3/BC4/BC5 tables. + std::vector> tables = { + { 8 }, std::vector(16, 8), std::vector(3, 0), { 0, 1, 2 }, + { 7, 7, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5 }, { 3, 3, 7, 7, 5, 5, 5, 5, 5, 5, 5, 5 }, + { 3, 3, 7, 5, 5, 5, 5, 4, 5, 4, 7, 7 }, + }; + for (size_t n : { 7, 9, 13 }) { + std::vector ab(n); + for (auto& w : ab) w = static_cast(rng.below(9)); + tables.push_back(ab); + } + for (const auto& ab : tables) { + bcpack_test::Options o; + o.max_fragment = 1 + rng.below(200); + o.padding = rng.below(2); + Stream s{ "", 0, 0, {}, ab, 1 + rng.below(160), false }; + std::vector symbols; + if (!bcpack_test::make_stream(ab.data(), ab.size(), s.target, rng, o, s.bytes, symbols)) std::abort(); + s.name = std::to_string(ab.size()) + " lanes, widths " + std::to_string(ab.front()) + ".." + std::to_string(ab.back()); + list.push_back(s); + } } return list; } From ea0aba4c10576c0917e0c69601c75dc6b60cc3fc Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 23:51:08 +0100 Subject: [PATCH 5/8] tests: add unflushed fragments to the BCPack lane encoder 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 --- tests/bcpack_encoder.h | 37 ++++++++++++++++++++++++++++++---- tests/bcpack_encoder_check.cpp | 4 +++- tests/bcpack_lanes_check.cpp | 6 +++++- 3 files changed, 41 insertions(+), 6 deletions(-) diff --git a/tests/bcpack_encoder.h b/tests/bcpack_encoder.h index 62f33c9b62..58d3ce2d8a 100644 --- a/tests/bcpack_encoder.h +++ b/tests/bcpack_encoder.h @@ -34,8 +34,10 @@ inline bool interval(uint8_t eab, uint8_t q, uint16_t sym, uint32_t& f, uint32_t } // One flushed fragment (header + payload); false when a symbol has no interval or the payload is too long. +// With split, the same rANS stream is written as unflushed fragments of random lengths instead: the lane +// state then carries across fragment headers. inline bool encode_fragment(uint8_t ab, uint8_t narrow, uint8_t q, const uint16_t* values, size_t count, - bool trim, std::vector& out) { + bool trim, std::vector& out, Rng* split = nullptr) { const uint8_t eab = static_cast(ab - narrow); uint64_t state = 1u << 24; std::vector emitted; @@ -51,10 +53,35 @@ inline bool encode_fragment(uint8_t ab, uint8_t narrow, uint8_t q, const uint16_ state = ((state / f) << 16) + state % f + start; } size_t omit = 0; - if (trim) { + if (trim && !split) { while (omit < 2 && omit < last_emitted && emitted[omit] == 0) ++omit; } const size_t payload = 4 + emitted.size() - omit; + if (split) { + std::vector bytes; + for (int b = 3; b >= 0; --b) bytes.push_back(static_cast(state >> (8 * b))); + for (size_t k = emitted.size(); k > 0; --k) bytes.push_back(emitted[k - 1]); + // The last fragment must start at or before the last byte that precedes the final zero bytes: + // a lane that decodes its last symbol after its budget ran out finishes in DRAIN and never + // reads a later fragment (the decoder then sees those bytes as trailing data). + const size_t last_start = bytes.size() - last_emitted - 1; + for (size_t at = 0; at < bytes.size();) { + size_t len = 1 + split->below(300); + if (at + len > last_start) len = bytes.size() - at; + const uint8_t header = static_cast((narrow << 6) | q); + if (len <= 256) { + out.push_back(header); + out.push_back(static_cast(len - 1)); + } else { + out.push_back(header | 0x20); + out.push_back(static_cast(len - 257)); + out.push_back(static_cast((len - 257) >> 8)); + } + out.insert(out.end(), bytes.begin() + at, bytes.begin() + at + len); + at += len; + } + return true; + } if (payload > 65792) return false; const uint8_t header = static_cast((narrow << 6) | 0x10 | q); if (payload <= 256) { @@ -144,6 +171,7 @@ struct Options { bool uniform = false; // uniform symbols instead of the fragment model's distribution bool narrow = true; // random alphabet narrowing in the headers bool trim = true; // randomly omit the trailing zero bytes of a fragment + bool unflushed = false; // code about half of the lanes as one stream cut into unflushed fragments int bc7_lane = -1; // lane whose symbol pairs must form a valid BC7 control code size_t padding = 0; // trailing zero bytes size_t window = 8; // bytes served per cycle; only the negative control changes it @@ -158,7 +186,8 @@ inline bool make_stream(const uint8_t* ab, size_t n, size_t target, Rng& rng, co size_t at = 0; while (at < target) { const bool control = static_cast(l) == o.bc7_lane; - size_t count = 1 + rng.below(o.max_fragment); + const bool whole = o.unflushed && !control && at == 0 && (rng.next() & 1); + size_t count = whole ? target : 1 + rng.below(o.max_fragment); if (control) count = 2 * ((count + 1) / 2); // keep code pairs inside one fragment if (count > target - at) count = target - at; uint8_t narrow = (o.narrow && !control) ? static_cast(rng.below(ab[l] < 3 ? ab[l] + 1 : 4)) : 0; @@ -196,7 +225,7 @@ inline bool make_stream(const uint8_t* ab, size_t n, size_t target, Rng& rng, co } } const bool trim = o.trim && (rng.next() & 1); - if (!encode_fragment(ab[l], narrow, q, v, count, trim, lane_bytes[l])) { + if (!encode_fragment(ab[l], narrow, q, v, count, trim, lane_bytes[l], whole ? &rng : nullptr)) { if (count == 1) return false; // payload over the long-header limit: retry with fewer symbols for (size_t k = 0; k < count; ++k) v[k] = 0; diff --git a/tests/bcpack_encoder_check.cpp b/tests/bcpack_encoder_check.cpp index 0e3466a763..e4dbd045f2 100644 --- a/tests/bcpack_encoder_check.cpp +++ b/tests/bcpack_encoder_check.cpp @@ -1,6 +1,7 @@ // Round trip of the test-only BCPack encoder (tests/bcpack_encoder.h) through decode_lanes and // decode_bcpack: random BC1- and BC7-shaped streams with short and long fragment headers, narrowed -// alphabets, trimmed flushed fragments, uniform and model-distributed symbols and zero padding. +// alphabets, trimmed flushed fragments, unflushed fragments, uniform and model-distributed symbols and +// zero padding. // --mutate window interleaves with a 7-byte instead of an 8-byte cycle budget; the decoder must then // disagree, which shows the check depends on the shared-stream arbitration (negative control). #include "bcpack_encoder.h" @@ -33,6 +34,7 @@ int main(int argc, char** argv) { bcpack_test::Options o; o.max_fragment = 1 + rng.below(t % 3 == 0 ? 600 : 150); // long fragments need three-byte headers o.uniform = t % 5 == 0; + o.unflushed = t % 4 >= 2; o.bc7_lane = bc7 ? 15 : -1; o.padding = rng.below(3); if (mutate) o.window = 7; diff --git a/tests/bcpack_lanes_check.cpp b/tests/bcpack_lanes_check.cpp index 29727c0c8a..051e07070c 100644 --- a/tests/bcpack_lanes_check.cpp +++ b/tests/bcpack_lanes_check.cpp @@ -174,11 +174,12 @@ std::vector streams(const std::string& dir, bool bench, bool large) { } if (!bench) list.push_back({ "mode6", 7, 1, from_hex(MODE6_HEX), {}, 0, false }); bcpack_test::Rng rng{ bench ? 7u : 1139u }; - auto add = [&](unsigned format, size_t blocks, uint32_t fragment, bool uniform, size_t padding) { + auto add = [&](unsigned format, size_t blocks, uint32_t fragment, bool uniform, size_t padding, bool unflushed = false) { bcpack_test::Options o; o.max_fragment = fragment; o.uniform = uniform; o.padding = padding; + o.unflushed = unflushed; o.bc7_lane = format == 7 ? 15 : -1; Stream s{ "", format, blocks, {}, {}, 0, false }; std::vector symbols; @@ -186,6 +187,7 @@ std::vector streams(const std::string& dir, bool bench, bool large) { if (!bcpack_test::make_stream(format == 7 ? AB7 : AB1, n, target, rng, o, s.bytes, symbols)) std::abort(); char name[96]; std::snprintf(name, sizeof name, "BC%u %zu blocks, fragments <= %u%s", format, blocks, fragment, uniform ? ", uniform" : ""); + if (unflushed) std::strcat(name, ", unflushed lanes"); s.name = name; list.push_back(s); }; @@ -202,6 +204,7 @@ std::vector streams(const std::string& dir, bool bench, bool large) { add(format, 300, 150, false, 0); add(format, 300, 150, true, 1); add(format, 300, 4096, false, 0); + add(format, 200, 150, false, 0, true); } // Each stream with one block more or fewer, and with the other format's lane table. const size_t base_count = list.size(); @@ -229,6 +232,7 @@ std::vector streams(const std::string& dir, bool bench, bool large) { bcpack_test::Options o; o.max_fragment = 1 + rng.below(200); o.padding = rng.below(2); + o.unflushed = (rng.next() & 1) != 0; Stream s{ "", 0, 0, {}, ab, 1 + rng.below(160), false }; std::vector symbols; if (!bcpack_test::make_stream(ab.data(), ab.size(), s.target, rng, o, s.bytes, symbols)) std::abort(); From 93dcba48c4905f99626d628463f82f2b0f1777f3 Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Tue, 24 Nov 2026 23:59:48 +0100 Subject: [PATCH 6/8] tests: anchor every BCPack lane path to outside expectations 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_ runs it per path (77 when the CPU lacks the path). bcpack_lanes_python__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 --- CMakeLists.txt | 21 ++++- tests/bcpack_lanes_check.cpp | 147 ++++++++++++++++++++++++++++- tests/bcpack_lanes_python_check.py | 70 ++++++++++++++ 3 files changed, 233 insertions(+), 5 deletions(-) create mode 100644 tests/bcpack_lanes_python_check.py diff --git a/CMakeLists.txt b/CMakeLists.txt index 90e9a48285..785e59fbcd 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -631,11 +631,28 @@ foreach(variant IN ITEMS check control) endforeach() target_compile_definitions(bcpack_lanes_control PRIVATE X2W_BCPACK_LANES_CONTROL) set(bcpack_lane_paths scalar avx2) +# Each path is also checked against outside anchors: the symbols stored in the repository vectors, the +# expected bytes in tests/bcpack_mode6_vector.py and tests/startup_stub_consumer.cpp, and the vendored +# Python decoder on a sample of streams (tests/bcpack_lanes_python_check.py). foreach(path IN LISTS bcpack_lane_paths) - add_test(NAME bcpack_lanes_${path} COMMAND bcpack_lanes_check "${CMAKE_SOURCE_DIR}/tools/_bcpack_rans/vectors" --path ${path}) + add_test(NAME bcpack_lanes_${path} COMMAND bcpack_lanes_check "${CMAKE_SOURCE_DIR}/tools/_bcpack_rans/vectors" + --path ${path} --consumer "${CMAKE_SOURCE_DIR}/tests/startup_stub_consumer.cpp") add_test(NAME bcpack_lanes_${path}_drain_control COMMAND bcpack_lanes_control "${CMAKE_SOURCE_DIR}/tools/_bcpack_rans/vectors" --path ${path}) - set_tests_properties(bcpack_lanes_${path} bcpack_lanes_${path}_drain_control PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) + set(bcpack_lane_tests bcpack_lanes_${path} bcpack_lanes_${path}_drain_control) + if(EXISTS "${INTAKE_PYTHON}") + foreach(variant IN ITEMS check control) + set(name bcpack_lanes_python_${path}) + if(variant STREQUAL control) + set(name bcpack_lanes_python_${path}_drain_control) + endif() + add_test(NAME ${name} COMMAND "${INTAKE_PYTHON}" -B "${CMAKE_SOURCE_DIR}/tests/bcpack_lanes_python_check.py" + "$" "${CMAKE_SOURCE_DIR}/tools/_bcpack_rans/vectors" --path ${path}) + list(APPEND bcpack_lane_tests ${name}) + endforeach() + set_tests_properties(bcpack_lanes_python_${path}_drain_control PROPERTIES WILL_FAIL TRUE) + endif() + set_tests_properties(${bcpack_lane_tests} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) set_tests_properties(bcpack_lanes_${path}_drain_control PROPERTIES WILL_FAIL TRUE) endforeach() # A queue whose worker cannot start (both CreateThread attempts fail, or the construction of its work diff --git a/tests/bcpack_lanes_check.cpp b/tests/bcpack_lanes_check.cpp index 051e07070c..64a77c3d82 100644 --- a/tests/bcpack_lanes_check.cpp +++ b/tests/bcpack_lanes_check.cpp @@ -7,7 +7,8 @@ // accepts although they are damaged. Inputs end at a no-access page and the destination sits // between a canary and a no-access page. The model shortcut is compared on all inputs. // -// bcpack_lanes_check VECTOR_DIR [--path NAME] [--full] check (--full: every truncation and bit flip) +// bcpack_lanes_check VECTOR_DIR [--path NAME] [--consumer FILE] [--full] check (--full: every truncation and bit flip) +// bcpack_lanes_check VECTOR_DIR [--path NAME] --emit FILE sample for tests/bcpack_lanes_python_check.py // bcpack_lanes_check VECTOR_DIR --bench [--large] // // With --path, only that path is compared with the reference, and the exit code is 77 (capability @@ -293,6 +294,141 @@ int bench(const std::vector& list) { return 0; } +// Outside anchors, checked on every path: the lane symbols stored in the repository vectors (written by +// the upstream Rust encoder), and the expected decode_bcpack bytes of tests/bcpack_mode6_vector.py and +// tests/startup_stub_consumer.cpp (read from that file, so the expected bytes have a single source). +std::vector> json_symbols(const std::string& path) { + std::ifstream f(path, std::ios::binary); + std::stringstream ss; + ss << f.rdbuf(); + const std::string text = ss.str(); + std::vector> lanes; + size_t at = text.find("\"symbols\":["); + if (at == std::string::npos) return lanes; + at += 11; + while (at < text.size() && text[at] == '[') { + const size_t end = text.find(']', at); + std::vector lane; + std::stringstream values(text.substr(at + 1, end - at - 1)); + std::string item; + while (std::getline(values, item, ',')) lane.push_back(static_cast(std::stoul(item))); + lanes.push_back(lane); + at = end + 1; + if (at < text.size() && text[at] == ',') ++at; + } + return lanes; +} + +std::vector c_array(const std::string& source, const std::string& name) { + const size_t at = source.find("const unsigned char " + name + "["); + if (at == std::string::npos) return {}; + const size_t open = source.find('{', at), close = source.find('}', at); + std::vector out; + for (size_t p = source.find("0x", open); p != std::string::npos && p < close; p = source.find("0x", p + 2)) { + out.push_back(static_cast(std::stoul(source.substr(p + 2, 2), nullptr, 16))); + } + return out; +} + +int check_anchors(const std::string& dir, const std::string& consumer_path) { + int failures = 0; + size_t checks = 0; + auto bcpack_on = [](int path, const std::vector& in, unsigned format, size_t size) { + std::vector out(size, 0xA5); + size_t produced = 0; + lane_path_override = path; + const bool ok = decode_bcpack(in.data(), in.size(), format, out.data(), out.size(), &produced); + lane_path_override = -1; + if (!ok || produced != size) out.clear(); + return out; + }; + for (int path = 0; path < LANE_PATH_COUNT; ++path) { + if (!lane_path_supported(path) || (only_path >= 0 && path != only_path && path != LANE_PATH_REFERENCE)) continue; + for (const char* v : { "synthetic_11", "synthetic_12" }) { + Stream s; + const std::vector> expected = json_symbols(dir + "/" + v + ".json"); + if (!load_vector(dir + "/" + v + ".json", s) || expected.size() != 12) return 1; + std::vector got; + const bool ok = decode_lanes_on(path, s.bytes.data(), s.bytes.size(), AB1, 12, s.blocks, got); + for (size_t l = 0; l < 12; ++l) { + ++checks; + if (!ok || expected[l].size() != s.blocks || + !std::equal(expected[l].begin(), expected[l].end(), got.begin() + l * s.blocks)) { + std::fprintf(stderr, "%s path: %s lane %zu differs from the vector's symbols\n", PATH_NAMES[path], v, l); + ++failures; + break; + } + } + } + ++checks; + if (bcpack_on(path, from_hex(MODE6_HEX), 7, 16) != from_hex("40317204a56819be023456789abcdef0")) { + std::fprintf(stderr, "%s path: tests/bcpack_mode6_vector.py block differs\n", PATH_NAMES[path]); + ++failures; + } + if (consumer_path.empty()) continue; + std::ifstream f(consumer_path, std::ios::binary); + std::stringstream ss; + ss << f.rdbuf(); + const std::string source = ss.str(); + const struct { const char* packed; const char* expected; unsigned format; } pairs[] = { + { "bc1_packed", "bc1_expected", 1 }, + { "bc7_mode6_packed", "bc7_mode6_expected", 7 }, + { "bc7_mode1_packed", "bc7_mode1_expected", 7 }, + }; + for (const auto& p : pairs) { + const std::vector in = c_array(source, p.packed), expected = c_array(source, p.expected); + ++checks; + if (in.empty() || expected.empty() || bcpack_on(path, in, p.format, expected.size()) != expected) { + std::fprintf(stderr, "%s path: %s does not decode to %s\n", PATH_NAMES[path], p.packed, p.expected); + ++failures; + } + } + } + std::printf("outside anchors: %zu checks, %d failed\n", checks, failures); + return failures == 0 ? 0 : 1; +} + +// For tests/bcpack_lanes_python_check.py: a sample of streams with every compared path's result, one +// JSON object per line. +int emit(const std::vector& list, const char* file) { + std::FILE* out = std::fopen(file, "w"); + if (!out) return 1; + auto write = [&](const Stream& s, const std::vector& data) { + const std::vector ab = !s.ab.empty() ? s.ab + : (s.format == 7 ? std::vector(AB7, AB7 + 16) : std::vector(AB1, AB1 + 12)); + const size_t target = !s.ab.empty() ? s.target : (s.format == 7 ? 2 * s.blocks : s.blocks); + std::fprintf(out, "{\"ab\":["); + for (size_t i = 0; i < ab.size(); ++i) std::fprintf(out, "%s%u", i ? "," : "", ab[i]); + std::fprintf(out, "],\"target\":%zu,\"hex\":\"", target); + for (uint8_t b : data) std::fprintf(out, "%02x", b); + std::fprintf(out, "\",\"paths\":{"); + bool first = true; + for (int path = 0; path < LANE_PATH_COUNT; ++path) { + if (!lane_path_supported(path) || (only_path >= 0 && path != only_path && path != LANE_PATH_REFERENCE)) continue; + std::vector symbols; + const bool ok = decode_lanes_on(path, data.data(), data.size(), ab.data(), ab.size(), target, symbols); + std::fprintf(out, "%s\"%s\":{\"ok\":%s,\"symbols\":[", first ? "" : ",", PATH_NAMES[path], ok ? "true" : "false"); + for (size_t i = 0; ok && i < symbols.size(); ++i) std::fprintf(out, "%s%u", i ? "," : "", symbols[i]); + std::fprintf(out, "]}"); + first = false; + } + std::fprintf(out, "}}\n"); + }; + for (const Stream& s : list) { + if (s.whole_only) continue; + const size_t size = s.bytes.size(); + write(s, s.bytes); + for (size_t len : { size / 4, size / 2, size - 1 }) write(s, std::vector(s.bytes.begin(), s.bytes.begin() + len)); + for (size_t k = 1; k <= 5; ++k) { + std::vector flipped = s.bytes; + const size_t bit = (k * 2654435761u) % (size * 8); + flipped[bit / 8] ^= static_cast(1u << (bit % 8)); + write(s, flipped); + } + } + return std::fclose(out) == 0 ? 0 : 1; +} + // model_inverse_interval against model_inverse_fast + model_forward for every model and low state. int check_interval() { for (uint8_t eab = 0; eab < 9; ++eab) { @@ -316,8 +452,12 @@ int check_interval() { int main(int argc, char** argv) { bool full = false, do_bench = false, large = false, usage = argc < 2; + const char* emit_file = nullptr; + std::string consumer; for (int k = 2; k < argc; ++k) { if (std::strcmp(argv[k], "--full") == 0) full = true; + else if (std::strcmp(argv[k], "--emit") == 0 && k + 1 < argc) emit_file = argv[++k]; + else if (std::strcmp(argv[k], "--consumer") == 0 && k + 1 < argc) consumer = argv[++k]; else if (std::strcmp(argv[k], "--bench") == 0) do_bench = true; else if (std::strcmp(argv[k], "--large") == 0) large = true; else if (std::strcmp(argv[k], "--path") == 0 && k + 1 < argc) { @@ -329,7 +469,7 @@ int main(int argc, char** argv) { } else usage = true; } if (usage) { - std::fprintf(stderr, "usage: bcpack_lanes_check VECTOR_DIR [--path NAME] [--full | --bench [--large]]\n"); + std::fprintf(stderr, "usage: bcpack_lanes_check VECTOR_DIR [--path NAME] [--consumer FILE] [--full | --emit FILE | --bench [--large]]\n"); return 64; } std::printf("lane paths:"); @@ -341,8 +481,9 @@ int main(int argc, char** argv) { } const std::vector list = streams(argv[1], do_bench, large); if (do_bench) return bench(list); + if (emit_file) return emit(list, emit_file); - if (check_interval() != 0) return 1; + if (check_interval() != 0 || check_anchors(argv[1], consumer) != 0) return 1; Checker checker; for (const Stream& s : list) checker.sweep(s, full); std::printf("%zu streams compared (%zu accepted, %zu rejected by the reference; %zu damaged streams accepted), %d mismatches\n", diff --git a/tests/bcpack_lanes_python_check.py b/tests/bcpack_lanes_python_check.py new file mode 100644 index 0000000000..d742ae6843 --- /dev/null +++ b/tests/bcpack_lanes_python_check.py @@ -0,0 +1,70 @@ +"""Compare the C++ decode_lanes paths with the vendored Python decoder (tools/_bcpack_rans). + +The lane check executable writes a sample of streams with each compared path's result: the +repository vectors, the mode-6 vector and synthetic streams from tests/bcpack_encoder.h, each whole, +truncated and with bits flipped. The C++ paths and the C++ encoder share the decoder's lane code; the +Python decoder is a separate implementation, so it anchors the accept/reject decision and the symbols. + +usage: bcpack_lanes_python_check.py LANES_CHECK_EXE VECTOR_DIR [--path NAME] +Exit 77 when the executable reports that this CPU lacks the path. +""" +import json +from pathlib import Path +import subprocess +import sys +import tempfile + +sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tools")) +from _bcpack_rans import BCPackError, decode_lanes # noqa: E402 + + +def python_decode(data, ab, target): + """The vendored reference with the C++ decoder's trailing-byte rule; None when it rejects.""" + try: + result = decode_lanes(data, list(ab), [target] * len(ab)) + except BCPackError: + return None + if any(data[result["consumed"]:]): + return None + return [value for lane in result["syms"] for value in lane] + + +def main(): + if len(sys.argv) not in (3, 5) or (len(sys.argv) == 5 and sys.argv[3] != "--path"): + print(__doc__, file=sys.stderr) + return 64 + with tempfile.TemporaryDirectory() as directory: + sample = Path(directory) / "sample.jsonl" + run = subprocess.run([sys.argv[1], sys.argv[2], *sys.argv[3:], "--emit", str(sample)], + capture_output=True, text=True) + if run.returncode == 77: + print(run.stdout.strip()) + return 77 + if run.returncode != 0: + print(run.stdout, run.stderr, file=sys.stderr) + return 1 + lines = sample.read_text().splitlines() + mismatches = accepted = 0 + for line in lines: + case = json.loads(line) + data = bytes.fromhex(case["hex"]) + expected = python_decode(data, case["ab"], case["target"]) + accepted += expected is not None + for path, result in case["paths"].items(): + got = result["symbols"] if result["ok"] else None + if got != expected: + mismatches += 1 + if mismatches <= 10: + print(f"{path} path, {len(data)} bytes, widths {case['ab']}, {case['target']} symbols: " + f"Python {'accepts' if expected is not None else 'rejects'}, " + f"C++ {'accepts' if result['ok'] else 'rejects'}" + f"{' with other symbols' if expected is not None and result['ok'] else ''}", + file=sys.stderr) + paths = sorted(json.loads(lines[0])["paths"]) if lines else [] + print(f"{len(lines)} streams ({accepted} accepted by the Python decoder), paths {', '.join(paths)}: " + f"{mismatches} mismatches") + return 0 if lines and mismatches == 0 else 1 + + +if __name__ == "__main__": + sys.exit(main()) From 4b37eb9124eeff85903bf9b40f91334dd894a80e Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 00:09:19 +0100 Subject: [PATCH 7/8] docs: describe the BCPack lane decoder paths and their checks 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 --- docs/experiments.md | 66 +++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) diff --git a/docs/experiments.md b/docs/experiments.md index 85af08e39b..2315cf710c 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9454,6 +9454,72 @@ mapping, archive stream discovery and rendered pixels remain separate work. The existing prefix probe keeps its diagnostic behavior. No local archive or texture payload is used by these checks. +### BCPack lane decoder paths + +The startup storage stand-in decodes BCPack streams with `decode_lanes` in +`src/startup_stubs/bcpack_decoder.h`. All lanes of one stream share one byte cursor. Each cycle, the +first eight lanes that request a byte receive consecutive stream bytes, in lane order. When a lane asks +for a byte depends on its rANS state, and so on every symbol it has decoded. One stream therefore cannot +be split between threads. Within a single cycle the lanes are independent apart from that prefix +count, so the decoder runs them side by side. + +`decode_lanes` uses an AVX2 path (16 lanes as two 8-lane halves) when `cpuid` reports AVX, AVX2 and +POPCNT and the OS saves the YMM state. Otherwise it uses a scalar loop that runs both phases of a cycle +in one pass. On every path, header bytes, fragment ends and flushes go through the original per-lane +step. The original loop is kept as `decode_lanes_reference` for tests. + +Each path has its own tests: `bcpack_lanes_scalar`, `bcpack_lanes_avx2` and their +`bcpack_lanes_python_*` counterparts. A path test compares only that path with the reference and +returns 77 (capability skip) when the CPU lacks the path. A CPU without AVX2 therefore passes the +scalar tests and reports the AVX2 tests as skipped. + +The comparison uses the two repository vectors, the mode-6 vector and synthetic streams from the +test-only encoder in `tests/bcpack_encoder.h`. The synthetic streams cover BC1, BC7 and other lane +tables, flushed and unflushed fragments, and wrong symbol counts. Each stream is tested whole, +truncated and with single bits flipped. The check requires the same accept or reject decision and the +same symbols, also on rejection. It also compares every `decode_bcpack` destination byte, including +for damaged streams that the reference accepts. Inputs end at a no-access page. + +The encoder learns the stream order from the decoder's own lane code. So each path is also checked +against data it did not produce: +- the lane symbols stored in the repository vectors; +- the expected bytes in `tests/bcpack_mode6_vector.py` and `tests/startup_stub_consumer.cpp`; +- the vendored Python decoder (`tests/bcpack_lanes_python_check.py`), on 225 sampled streams. + +The `*_drain_control` builds take a wrong DRAIN step and must fail; `bcpack_encoder_window_control` +must fail as well. + +Real fragment lengths are unknown. The repository vectors used at most 150 symbols per fragment; v12 +averages about 72. The benchmark runs at most 150 and at most 4096 symbols per fragment. Each round runs +every path in turn, the first round is a warm-up and the best of seven is reported. Every path must +give the same checksum of symbols and destination. + +```powershell +cmake --preset release +cmake --build --preset release --target bcpack_lanes_check +.\out\build\release\bcpack_lanes_check.exe tools\_bcpack_rans\vectors --full +.\out\build\release\bcpack_lanes_check.exe tools\_bcpack_rans\vectors --bench --large +ctest --preset dev --no-tests=error -R '^bcpack_(lanes|encoder)_' -V +``` + +Observed on a Ryzen 7 9800X3D with Windows 11 build 26300 and MSVC Release (`/O2`): +- `--full` compared 423,874 streams with 0 mismatches on every path. The reference accepted 48,004 + damaged streams, and every path matched it on each one. +- `--bench --large` gave the `decode_bcpack` times below for 4 MiB destinations (524,288 BC1 or + 262,144 BC7 blocks), with the lane-decode rate in parentheses. + +| Stream | Reference | Scalar | AVX2 | +|---|---|---|---| +| BC1, at most 150 symbols per fragment | 161 ms (24.5 ns/symbol) | 127 ms (18.9) | 46 ms (5.9) | +| BC1, at most 4096 | 119 ms (17.4) | 91 ms (13.0) | 31 ms (3.7) | +| BC7, at most 150 | 283 ms (27.0) | 232 ms (20.8) | 107 ms (6.0) | +| BC7, at most 4096 | 227 ms (20.2) | 181 ms (15.0) | 89 ms (4.0) | + +End to end, the scalar loop is 1.2-1.3x faster than the reference; the lane step alone is +1.3-1.4x faster here and up to 2x on the 700-block vector. AVX2 is 3.5-3.8x faster for BC1 and +2.6x for BC7. BC7 block reconstruction, unchanged, now takes about half of the BC7 time. The AVX2 +gain was measured on Zen 5, which has fast gathers; CPUs with slow gathers are unmeasured. + ### Reading logical ranges and probing structured resources `tools/paged_resource.py` reads a logical byte range from an open archive and a supplied segment map. Each segment gives a physical offset, stored byte count excluding padding, decoded byte count, and codec. Raw and zlib segments may be mixed. The reader verifies the complete compressed stream and decoded size before returning bytes from it. Reads that touch an unknown codec fail. Segments after it remain independently addressable. From a0ff8ead6003cbf8b3ea744e8484b6231588277b Mon Sep 17 00:00:00 2001 From: NiiRoZz Date: Wed, 25 Nov 2026 01:22:43 +0100 Subject: [PATCH 8/8] tests: pin the BCPack lane controls to the failures they must show 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 --- CMakeLists.txt | 7 +++++-- docs/experiments.md | 4 +++- tests/bcpack_lanes_check.cpp | 13 ++++++++++--- 3 files changed, 18 insertions(+), 6 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index 785e59fbcd..1d75a0099b 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -650,10 +650,13 @@ foreach(path IN LISTS bcpack_lane_paths) "$" "${CMAKE_SOURCE_DIR}/tools/_bcpack_rans/vectors" --path ${path}) list(APPEND bcpack_lane_tests ${name}) endforeach() - set_tests_properties(bcpack_lanes_python_${path}_drain_control PROPERTIES WILL_FAIL TRUE) + set_tests_properties(bcpack_lanes_python_${path}_drain_control PROPERTIES + PASS_REGULAR_EXPRESSION "${path} path, [0-9]+ bytes, widths .*: Python accepts, C\\+\\+ rejects") endif() set_tests_properties(${bcpack_lane_tests} PROPERTIES TIMEOUT 300 SKIP_RETURN_CODE 77) - set_tests_properties(bcpack_lanes_${path}_drain_control PROPERTIES WILL_FAIL TRUE) + # Both the vector symbols and the reference sweep must catch the control build. + set_tests_properties(bcpack_lanes_${path}_drain_control PROPERTIES PASS_REGULAR_EXPRESSION + "${path} path: synthetic_11 lane [0-9]+ differs from the vector's symbols.*result: anchors failed, [1-9][0-9]* mismatches") endforeach() # A queue whose worker cannot start (both CreateThread attempts fail, or the construction of its work # throws std::bad_alloc) completes status entries and fences at Submit, never inside Enqueue (#1199). diff --git a/docs/experiments.md b/docs/experiments.md index 2315cf710c..89f70def45 100644 --- a/docs/experiments.md +++ b/docs/experiments.md @@ -9466,7 +9466,9 @@ count, so the decoder runs them side by side. `decode_lanes` uses an AVX2 path (16 lanes as two 8-lane halves) when `cpuid` reports AVX, AVX2 and POPCNT and the OS saves the YMM state. Otherwise it uses a scalar loop that runs both phases of a cycle in one pass. On every path, header bytes, fragment ends and flushes go through the original per-lane -step. The original loop is kept as `decode_lanes_reference` for tests. +step. The original loop is kept as `decode_lanes_reference` for tests. The SIMD code is compiled only by +MSVC for x64; a clang-cl build has only the scalar path, and its AVX2 tests report 77 with that reason +rather than a CPU limit. Each path has its own tests: `bcpack_lanes_scalar`, `bcpack_lanes_avx2` and their `bcpack_lanes_python_*` counterparts. A path test compares only that path with the reference and diff --git a/tests/bcpack_lanes_check.cpp b/tests/bcpack_lanes_check.cpp index 64a77c3d82..414a3776bd 100644 --- a/tests/bcpack_lanes_check.cpp +++ b/tests/bcpack_lanes_check.cpp @@ -476,17 +476,24 @@ int main(int argc, char** argv) { for (int p = 0; p < LANE_PATH_COUNT; ++p) std::printf(" %s%s", PATH_NAMES[p], lane_path_supported(p) ? "" : " (not supported)"); std::printf("; decode_lanes uses %s\n", PATH_NAMES[best_lane_path()]); if (only_path >= 0 && !lane_path_supported(only_path)) { - std::printf("capability skip: the %s path is not supported here\n", PATH_NAMES[only_path]); +#ifdef X2W_BCPACK_LANE_SIMD + std::printf("capability skip: this CPU or OS lacks the %s path\n", PATH_NAMES[only_path]); +#else + std::printf("capability skip: the %s path is not compiled (it needs MSVC for x64, not clang-cl)\n", + PATH_NAMES[only_path]); +#endif return 77; } const std::vector list = streams(argv[1], do_bench, large); if (do_bench) return bench(list); if (emit_file) return emit(list, emit_file); - if (check_interval() != 0 || check_anchors(argv[1], consumer) != 0) return 1; + // The sweep runs even when an anchor fails, so a control build shows that both catch it. + const bool anchors_ok = check_interval() == 0 && check_anchors(argv[1], consumer) == 0; Checker checker; for (const Stream& s : list) checker.sweep(s, full); std::printf("%zu streams compared (%zu accepted, %zu rejected by the reference; %zu damaged streams accepted), %d mismatches\n", checker.compared, checker.accepted, checker.rejected, checker.damaged_accepted, checker.failures); - return checker.failures == 0 ? 0 : 1; + std::printf("result: anchors %s, %d mismatches\n", anchors_ok ? "passed" : "failed", checker.failures); + return anchors_ok && checker.failures == 0 ? 0 : 1; }