Skip to content

lazy: inline the hash-chain search for inputs of 16 KB or less (builds on #5007) - #5008

Open
hieu-lee wants to merge 15 commits into
meta:devfrom
hieu-lee:l5-lazy-hc-inline
Open

hieu-lee wants to merge 15 commits into
meta:devfrom
hieu-lee:l5-lazy-hc-inline

Conversation

@hieu-lee

@hieu-lee hieu-lee commented Nov 20, 2026 •

Copy link
Copy Markdown

Problem

At level 5, inputs of 16 KB and less use the lazy parser with the hash-chain match finder; the row match finder needs windowLog > 14. That path is common for small payloads such as messages and records. #4841 and #5007 do not speed it up: on Graviton2 it is about 70% ZSTD_HcFindBestMatch and 15% ZSTD_compressBlock_lazy.

The search is a separate function called at every searched position. Inside it, the hash and chain table stores (U32) may alias *ms as far as the compiler can tell, so the match-state fields are reloaded in every search.

Solution

This PR builds on #5007, which builds on #4841, and includes their commits. Please review only the last 3 commits, 8270643bf..6de3d7196. Each of them keeps the compressed output byte-for-byte identical.

  1. Inline the hash-chain search into the lazy parser for mls 4, which is level 5's setting for these inputs. ZSTD_compressBlock_lazy() sends mls 4 to ZSTD_compressBlock_lazy_4(), which builds ZSTD_HcFindBestMatch() into the parser loop. The inline flag that lazy: inline the row search into level 5's greedy parsers and trim it (builds on #4841) #5007 added to ZSTD_compressBlock_lazy_specialized() now covers both the row search and the hash-chain search.
  2. Run that parser on a local copy of the match state. gcc keeps the copy's fields in registers. The parser modifies only nextToUpdate and lazySkipping, and those two fields are written back afterwards. A comment states this rule, so that a future write to another field is not lost.
  3. Prefetch the hash-chain bucket while catching up. ZSTD_insertAndFindFirstIndex_internal() now hashes ip first and prefetches its bucket, so the load overlaps the catch-up inserts.

Verification. A harness compared the XXH64 digests of the compressed output against dev (1658a42), and round-trip decoded every frame. It covered the same matrices as #5007, on every commit state:

  • 2028 configs: level 5 whole, chunked, streaming, LDM, MT, dictionaries, parameter variants; levels -5..19.
  • 4160 configs: levels -3..19 at 1 KB to 200 KB chunks, with raw-content and trained dictionaries.
  • 1047 edge configs: tight dst capacities with an overrun canary, and offsets of 2^26 and above.

These ran on release builds, on a -DZSTD_NO_INTRINSICS build of commit 3 and on a DEBUGLEVEL=1 build of the final state. tests/fuzzer and tests/zstreamtest pass, and there are no new warnings and no new stack frames over 1 KiB. Merging this branch into dev gives exactly the verified tree.

Benchmarks.

  • Setup: AWS Graviton2 (Neoverse-N1); gcc 11.4; default -O3; level 5; one-shot ZSTD_compress2() with a reused CCtx.
  • Data: the 12 Silesia files, split into independent chunks.
  • Method: one thread pinned to one core, measuring thread CPU time. Binaries ran in interleaved rounds; the best and median of 6 to 8 passes are reported.
  • Noise: the machine was shared, so expect about ±0.5%.
level 5 vs #5007: CPU time, best (median) cycles instructions with #4841 and #5007, vs dev
16 KB chunks -14.3% (-14.3%) -14.5% -17.2% -15.2%
4 KB chunks -15.2% (-15.2%) -16.2%
whole files, 64 KB chunks unaffected identical

Per commit at 16 KB chunks, against the previous commit:

commit CPU time instructions
1 -7.2% -11.6%
2 -5.5% -6.6%
3 -2.4% +0.3%

Not measured: x86-64 (the changes are plain C), clang, MSVC, data other than Silesia. The local match-state copy relies on the compiler eliding the struct copy, as gcc 11 does. Another compiler might copy about 300 bytes per block instead, which should be negligible but is not measured.

TLDR

zstd_lazyhc.mp4

Checklist

Tools used

Claude Code (Anthropic Claude Opus) profiled level-5 compression, wrote these changes, built the byte-identity harness, and ran the benchmarks, using several parallel agents. OpenAI Codex agents reviewed the patches over several rounds. I directed the work and reviewed the results.

🤖 Generated with Claude Code

rluvaton and others added 15 commits October 13, 2026 20:03
Slot 0 of each row in the tag table holds the row's head, not an entry,
so the candidate loops tested `matchPos == 0` on every tag hit. Clear
that slot's bit group from the match mask once instead. `continue` did
not consume an attempt nor store a candidate, so the candidates (and
the compressed output) are unchanged.
Row offsets and slot positions were U32, so every tagTable / hashTable
access in the insertion loop needed a zero-extension, and on AArch64
the uxtw-extended addressing modes cost an extra uop each. Use size_t,
read hashSalt once (BYTE stores into the tag table may alias *ms, which
forced a reload per position), and reuse the head byte already loaded
for the match mask when inserting the current position.

llvm-mca (Neoverse-N1 model) on the generated insertion loop:
33 -> 30 uops per position. Output is unchanged.
In the row matchfinder, 57% of candidate match lengths are 4-7 bytes and
~85% are below 16, so ZSTD_count()'s "first 8 bytes equal?" branch and
its loop exit are close to unpredictable (~24% of level 6 cycles are
lost to bad speculation on Sapphire Rapids). Add ZSTD_countShort(),
which compares the first two words and picks the first differing one
with selects; its only branch (>= 16 equal bytes) is taken ~15% of the
time. Bit 63 is OR-ed in so the trailing-zero count is defined for a
zero word without changing the result for a non-zero one.

Only the row matchfinder uses it: applied to ZSTD_count() itself it
slowed down the strategies with longer matches (dfast, btlazy2, btopt)
by 2-6%. The returned length is identical, so output is unchanged.
Convert 8 sequences per iteration: vld4q_u16 de-interleaves offBase
(low/high halves), litLength and mlBase into 16-bit lanes; codes for
small lengths are computed by counting the LL_Code / ML_Code thresholds
reached, and large ones / offsets from vclzq_u16. All selects are
branchless; one narrowed 8-byte store per code table.

Only enabled on little-endian 64-bit NEON targets. An SSE2 version was
measured slower than the scalar loop on x86-64 (4 lanes, no vector
lzcnt), so x86 keeps the scalar loop. Verified equal to the scalar loop
for every 16-bit litLength / mlBase and all offBase bit widths.
On x86-64, the out-of-line row search costs callee-saved register
spills, the mls/rowLog dispatch and re-deriving constants from ms on
every call; perf attributed ~10% of level 6 cycles to that overhead.
Inline only the noDict row search there. It was measured neutral on
aarch64, so other targets, and the other dict modes, stay outlined to
limit code size (+98 KB of .text on x86-64 with gcc 11).
Outside x86-64, every greedy search calls the outlined
ZSTD_RowFindBestMatch_noDict_<mls>_<rowLog>(), 34 M calls per Silesia
pass at level 5. Each call pays for the call itself, saving and
restoring registers, a stack protector check, the (mls, rowLog)
dispatch, and a round trip of the offset through memory.

On those targets, ZSTD_compressBlock_greedy_row() now picks a variant
with the search inlined, once per block, for the (mls, rowLog) pairs of
the default parameters:
- (5,4) for level 5 above 256 KB;
- (5,5) for 128-256 KB;
- (4,4) for 128 KB and below.
Other pairs keep the outlined searches.

x86-64 already inlines the noDict row searches into every lazy parser,
so the variants are not built there and its code is unchanged.
ZSTD_ROW_SEARCH_INLINE_NODICT now names that choice for both uses. On
Neoverse-N1 at level 5, inlining every noDict row search (the x86-64
scheme) measured -2.4% CPU for +88 KB of code, these variants -6.3% for
+13 KB, and both together -6.6%.

ZSTD_compressBlock_lazy_generic() becomes a wrapper around
ZSTD_compressBlock_lazy_specialized(), which takes mls, rowLog and the
inline flag as template parameters. The variants run the same search
code on the same (mls, rowLog) as ms->cParams (asserted), so the output
is unchanged.

Level 5, vs the previous patch: -6.1% CPU on full Silesia (-9.6%
instructions), -8.9% with 64 KB chunks (-12.4% instructions). Inputs
of 16 KB and less (hash chain parser) are not affected.

The compressed output is byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The row match finder inserts every position covered by a match: 166 M
positions per Silesia pass at level 5. The loop stored the tag through
tagTable + relRow and the position through hashTable + relRow, so the
compiler formed both row addresses and added the slot to each.

Both stores now index their table with the same relRow + slot. This
removes one add per position: 27 -> 26 instructions per position in
the level 5 greedy parser on aarch64 with gcc 11.

The same positions are inserted in the same slots, in the same order,
with the same values, so the output is unchanged.

Level 5, vs the previous patch: -0.6% CPU on full Silesia (-1.1%
instructions), -0.7% with 64 KB chunks (-1.0% instructions). Applied
directly on meta#4841, where the search is still outlined, it measured
-0.4..-0.6% on full Silesia but +0.8..+1.0% with 64 KB chunks although
instructions also fell by 1.1%, hence its place after the inlining.

The compressed output is byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Candidates after the first one are compared at offset ml, and matches
are often longer than the rest of the first cache line, so the second
line is prefetched too.

The second address can lie past the end of the buffer, so
ZSTD_row_prefetchMatch() computes it as an integer instead of forming
an out-of-bounds pointer. A prefetch never faults and changes no value,
so the output is unchanged.

Level 5, vs the previous patch: -2.5% CPU on full Silesia, 0.0% with
64 KB chunks (+0.5% and +0.4% instructions: one more prefetch per
candidate).

The compressed output is byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
59% of level 5 searches find no matching tag. lowLimit and the prefetch
loop are now only set up when the match mask is not empty. Without a
candidate, the compare loop already does nothing.

The compare loop's assert that each buffered candidate is >= lowLimit
goes away with lowLimit's scope: the prefetch loop only buffers
candidates that pass that test.

The same candidates are buffered and compared, in the same order, and
the current position is inserted as before, so the output is unchanged.

Level 5, vs the previous patch: -2.1% CPU on full Silesia (-3.2%
instructions), -2.6% with 64 KB chunks (-4.1% instructions).

The compressed output is byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
For 16-entry rows, the tag row and the hash row of a hash share their
cache lines with hash >> 4 and hash >> 2. The prefetch addresses then
take one shift each instead of a shift, a mask and a scale.

The hash table is 64-byte aligned, and the prefetches touch the same
lines as before. Prefetches change no value, so the output is
unchanged.

Level 5, vs the previous patch: -0.9% CPU on full Silesia (-1.2%
instructions), -0.6% with 64 KB chunks (-0.8% instructions).

The compressed output is byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
(offset_1 > 0) & (read == read) becomes &&. The predictable branch on
offset_1 skips the load when no repcode is active.

When offset_1 is 0, the skipped comparison could not change the result
of the &, so the parser takes the same decisions and the output is
unchanged.

Level 5, vs the previous patch: -0.9% CPU on full Silesia (-1.2%
instructions), -1.5% with 64 KB chunks (-1.7% instructions), -0.2%
instructions with 16 KB chunks.

The compressed output is byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ZSTD_row_update_internal() no longer stores ms->nextToUpdate. Its
callers do:
- the row search sets it past ip after inserting ip;
- ZSTD_row_update() sets it after loading a dictionary.

ZSTD_row_nextCachedHash() takes the position pointer, so the search
hashes ip + 8 directly instead of recomputing base + curr.

ms->nextToUpdate was equal to curr whenever the search inserted ip, in
both the normal and the lazy skipping modes, so ip is inserted with the
same index, and every later reader sees the same value. The output is
unchanged.

Level 5, vs the previous patch: -0.3% CPU on full Silesia (-1.0%
instructions), -1.0% with 64 KB chunks (-1.3% instructions).

The compressed output is byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Level 5 compresses inputs of 16 KB and less with the lazy parser and
the hash chain match finder: the row match finder needs windowLog > 14.

ZSTD_compressBlock_lazy() now dispatches mls 4 to
ZSTD_compressBlock_lazy_4(), which inlines ZSTD_HcFindBestMatch()
instead of calling it for every search. The inline flag of
ZSTD_compressBlock_lazy_specialized() is generalised from the row
search to both searches.

The inlined search is the same function with the same arguments, so
the output is unchanged.

Level 5 with 16 KB chunks, vs the previous patch: -7.2% CPU (-11.6%
instructions). Larger inputs are not affected.

The compressed output is byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The compiler cannot tell that the U32 stores into the hash and chain
tables don't alias *ms. It therefore reloaded the window, cParams,
table pointers and nextToUpdate in every search.

ZSTD_compressBlock_lazy_4() now runs the parser on a local copy, which
gcc keeps in registers. It then writes back the only two fields the
parser modifies, nextToUpdate and lazySkipping.

The tables are reached through the same pointers, and *ms ends with the
same field values, so the output is unchanged.

Level 5 with 16 KB chunks, vs the previous patch: -5.5% CPU (-6.6%
instructions).

The compressed output is byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
ZSTD_insertAndFindFirstIndex_internal() now hashes ip first and
prefetches its bucket, so the load overlaps the catch-up inserts.

The hash of ip is the same value as before and the bucket is still read
after the catch-up inserts, so it returns the same index and the output
is unchanged.

Level 5 with 16 KB chunks, vs the previous patch: -2.4% CPU (+0.3%
instructions).

The compressed output is byte-identical to the previous commit.

Co-Authored-By: Claude Opus 5.5 <[email protected]>

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants