Skip to content

Optimize splitByNonAlpha and splitByString tokenizers - #119434

Merged
CurtizJ merged 17 commits into
ClickHouse:masterfrom
CurtizJ:tokenizers-byte-set
Sep 14, 2026
Merged

CurtizJ merged 17 commits into
ClickHouse:masterfrom
CurtizJ:tokenizers-byte-set

Conversation

@CurtizJ

@CurtizJ CurtizJ commented Sep 11, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Performance Improvement

Changelog entry (a user-readable short description of the changes that goes into CHANGELOG.md):

Improved performance of splitByNonAlpha and splitByString tokenizers.


Workflow [PR]
Sync PR [sync-upstream/pr/119434]

…ass scanner

`ByteSet` (`src/Common/ByteSet.h`) is a set of bytes with a 256-entry membership
table and a vectorized search for the first byte that is (or is not) in the set.
Sixteen bytes are classified at once with two nibble lookups (`pshufb` on x86,
`tbl` on AArch64), written with GCC/Clang vector extensions so that both
platforms share one implementation. `matchBlock` returns the classification of a
16-byte block as a bitmask.

`SplitByStringTokenizer` previously compared every separator with `memcmp` at
every position and copied the matched separator into a string. It now jumps to
the next byte that can start a separator and compares only there. Single-threaded
throughput of `tokens(s, 'splitByString', ...)` is 1.7-4x higher on short-token
data and 6-17x higher on data with long tokens.

`SplitByNonAlphaTokenizer` takes its "is token byte" mask from `ByteSet` as
well, which replaces the hand-written SSE4.2 and SSE2 code and gives AArch64 a
vectorized path where it had a byte-by-byte loop. On x86 the throughput is
unchanged.

The output of both tokenizers is byte-identical to the previous implementation on
random inputs including all 256 byte values, and in text index build and search.
A performance test with log lines, prose, long tokens and UTF-8 text is added.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [9515b88]

Summary: ✅


AI Review

Summary

This PR rewrites the splitByNonAlpha and splitByString hot paths around a shared ByteSetLookup scanner and adds focused tokenizer correctness and performance coverage. I did not find a remaining contract or correctness issue in the current code: the separator semantics are preserved across both nextInString and the new forEachToken fast paths, the adjacent-row / FixedString overread boundary is explicitly covered by the new tests, and the PR has supporting performance evidence for the claimed speedups.

Final Verdict
  • Status: ✅ Approve

LLVM Coverage Report

Measured on commit 9515b88.

Metric Baseline Current Δ
Lines 89.00% 89.10% +0.10%
Functions 91.80% 91.80% +0.00%
Branches 81.50% 81.50% +0.00%

Changed lines: Changed C/C++ lines covered: 161/166 (96.99%) · Uncovered code

Full report · Diff report

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Sep 11, 2026
Comment thread src/Interpreters/ITokenizer.h Resolved
@clickhouse-gh clickhouse-gh Bot added the comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... label Sep 11, 2026
@clickhouse-gh

clickhouse-gh Bot commented Sep 11, 2026 •

Copy link
Copy Markdown
Contributor

Build profile diff (arm_release)

Comparing 9515b88e5 with master d7262251a (stripped binary size, per-symbol sizes and ThinLTO time; compile times per translation unit against the most recent warmup build that recompiled it).

✅ No significant changes.

Binary sizes

programs/clickhouse-stripped: smaller than the master baseline by the known offset between the two builds, so the difference is not shown. A delta that differs from the offset by more than 50% of it is shown, in either direction.

The official master build is compiled with -g and a pull request build is not, and XRay counts debug instructions towards its instrumentation threshold, so master instruments thousands of functions more and its binary is ~0.4% larger no matter what the pull request does.

Object file sizes

38 object files changed (+146.94 KiB total), 0 added.

Object file Master PR Δ
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/hasAnyAllTokens.cpp.o 940.24 KiB 1020.57 KiB +80.33 KiB (+8.54%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/hasPhrase.cpp.o 470.86 KiB 488.60 KiB +17.74 KiB (+3.77%)
src/Functions/CMakeFiles/clickhouse_functions_obj.dir/tokens.cpp.o 564.68 KiB 580.71 KiB +16.03 KiB (+2.84%)

716 more object files are built by the master warmup baseline only (it builds every object-file target, a pull request build only clickhouse-bundle) and not compared.

Compile time of recompiled translation units

3062 translation units recompiled, 16499 s compile time in total, 3061 of them have a recent master baseline.

Job report

@CurtizJ

This comment was marked as outdated.

@CurtizJ CurtizJ changed the title Try a few optimizations for tokenizers Optimize splitByNonAlpha and splitByString tokenizers. Sep 11, 2026
CurtizJ and others added 9 commits September 11, 2026 17:34
When every separator is one byte long, the set of separator first bytes is
exactly the set of separators, so both loops of `nextInString` can be
delimited by `ByteSet::find` alone: `find<false>` skips the run of
separators and `find<true>` finds the end of the token. This removes the
per-byte `matchSeparator` call and its loop over all separators with
`memcmp`. Multi-byte separator sets keep the previous code, because there
the bytes after the first one are not in the first-byte set.

Net of data generation, tokenizing with `[' ']` and `[' ', '=', ',', '"']`
is 1.4-1.7x faster on log lines and prose, 1.3x on UTF-8 prose and 1.1x on
long tokens. The output is byte-identical to the previous implementation.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…sets on x86

`pshufb` reads only the low 4 bits of an index and zeroes the lane if bit 7
is set, so a set without members >= 0x80 does not need `bytes & 0x0F` before
the low-nibble lookup. NEON `tbl` zeroes every index >= 16 instead, so the
mask stays there.

`ByteSet::add` now tracks `ascii_only`, and `classify` / `findVectorized`
are instantiated for both cases with a single dispatch in `find` and
`matchBlock`. `SplitByNonAlphaTokenizer::separator_chars` becomes
`static constexpr` (the ASCII class helpers in `StringUtils.h` are
`constexpr` now), so the `vectorized` and `ascii_only` dispatch folds away
and `matchBlock` compiles to 12 branch-free instructions with the tables
as constants.

Also add the missing `<cstddef>` include for `ptrdiff_t`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The scalar prefix loop had a data-dependent trip count, so the compiler
never unrolled it and every byte cost a load, a table compare, an exit
branch, an increment, a bound compare and a loop branch. Scanning the
first `SCALAR_PREFIX` bytes only when at least that many remain gives the
loop a constant trip count, which clang unrolls into a straight sequence
of table lookups (3-4 instructions and one branch per byte). The semantics
of `find` are unchanged.

`find` is marked `ALWAYS_INLINE` because the unrolled version was not
inlined into `nextInString` on its own, and out of line it was 3-5% slower
on `splitByString` queries. Inlined, the single-byte `splitByString` path
in `tests/performance/tokenizers.xml` gets up to 7% faster; the other
queries are unchanged within noise.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The class is a byte-class lookup table used for scanning, not a general
set container, and the new name says so at the use site.

Co-Authored-By: Claude Opus 5 <[email protected]>
The hot path went through `detail::forEachTokenImpl`, which called the
out-of-line `nextInString` once per token, and the multi-byte separator
branch re-scanned the same bytes several times per token.

Single-byte separators now run a fused loop of two `ByteSetLookup::find`
calls. Multi-byte separators classify each 16-byte block once over the
first bytes of the separators and call `matchSeparator` only at the
candidate positions. The tail block is classified with the new
`ByteSetLookup::matchBytes`, so the kernel reads exactly `length` bytes
and needs no padding.

`tokens(s, 'splitByString', ...)` in `tests/performance/tokenizers.xml`,
two-server comparison with 15 runs: log lines -17%, prose with a single
separator -20%, prose with multi-byte separators -51%, long tokens -4%.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
The data passed to `forEachToken` is always padded from the right, as
`SplitByNonAlphaTokenizer` already relies on, so the tail block can be
classified with `matchBlock` too and the bits of the padding bytes
masked out. This removes `ByteSetLookup::matchBytes`.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…splitByString`

`SplitByNonAlphaTokenizer::forEachTokenImpl` extracted token runs from
the block mask with two `countr_zero` and two data-dependent shifts per
token, and the single-byte path of `SplitByStringTokenizer` restarted
`ByteSetLookup::find` at every token boundary. Both now share
`detail::forEachTokenSplitByBytes`, which classifies each 16-byte block
once and emits a token before every separator bit, the same shape as
the multi-byte kernel. The padding note, the MSan fallback and the tail
mask live in `detail::separatorBits`, shared by all three paths.

`tests/performance/tokenizers.xml`, two-server comparison with 15 runs
against the state before this series: `tokens(s)` -3.5% log lines,
-5.7% prose, -23% long tokens; `splitByString` -33% log lines, -39%
prose with a single separator, -52% with multi-byte separators, -9%
long tokens.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
For a full block `(1u << 16) - 1` is `0xFFFF`, so the branch on the block
length was redundant.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
…okup`

The low-nibble lookup now always masks with `0x0F`, so `classify`,
`findVectorized` and `lookupByLowNibble` lose their `ascii_only`
template parameter and the member that tracked it. Every tokenizer
kernel classifies a block once per 16 bytes, so the saved `pand` is not
measurable: `tests/performance/tokenizers.xml` is unchanged within 1.5%
on all queries.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@CurtizJ CurtizJ changed the title Optimize splitByNonAlpha and splitByString tokenizers. Optimize splitByNonAlpha and splitByString tokenizers Sep 12, 2026
CurtizJ and others added 3 commits September 12, 2026 13:48
…tokenizers

Inserts log lines into tables with a `text` index using `splitByNonAlpha`
and `splitByString` with single-byte and multi-byte separators, with
merges stopped so that only the INSERT builds the index. Against master
the `splitByString` builds take half the time (2.7 s to 1.4 s), on par
with `splitByNonAlpha`, which is unchanged because tokenizing is a small
share of its index build.

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@CurtizJ

CurtizJ commented Sep 12, 2026

Copy link
Copy Markdown
Member Author

amd:

Screenshot 2026-09-12 at 22 03 05

arm:

Screenshot 2026-09-12 at 22 02 13

@CurtizJ

CurtizJ commented Sep 12, 2026

Copy link
Copy Markdown
Member Author

On real index build, improvement is almost not noticeable for the splitByNonAlpha tokenizer, but significant for the splitByString.

Screenshot 2026-09-12 at 22 04 40 Screenshot 2026-09-12 at 22 04 55

@CurtizJ

CurtizJ commented Sep 12, 2026

Copy link
Copy Markdown
Member Author

Performance of brufe-force tokens search has also improved:

Screenshot 2026-09-12 at 22 09 16

@CurtizJ
CurtizJ marked this pull request as ready for review September 12, 2026 20:12
@clickhouse-gh

clickhouse-gh Bot commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

✅ AI verdict: no_change — no significant changes across 39 queries analysed

no significant changes detected. K_source=6 K_base=30 flagged=0/65

clickbench

🟢 No significant changes

tpch_adapted_1_official

🟢 No significant changes

Debug info
  • StressHouse run: 736e0e38-9944-43ed-8ec0-3d1a1c1ee1a5
  • MIRAI run: 2fc3e950-140f-4f78-b61c-dd36b61999c9
  • PR check IDs:
    • clickbench_137789_1789386978
    • clickbench_137795_1789386978
    • clickbench_137801_1789386978
    • tpch_adapted_1_official_137812_1789386978
    • tpch_adapted_1_official_137825_1789386978
    • tpch_adapted_1_official_137859_1789386978

…izers

Cover byte classification, block boundaries, overlapping and long separators,
binary strings, search needles, and text-index results compared with scans.
Verify identical results on the pre-refactor binary and the PR CI binary.

Related: ClickHouse#119434
@CurtizJ
CurtizJ force-pushed the tokenizers-byte-set branch from af77666 to 785e225 Compare September 14, 2026 00:34
@rschu1ze rschu1ze self-assigned this Sep 14, 2026
Comment thread src/Common/ByteSetLookup.h Resolved
Comment thread src/Common/ByteSetLookup.h Resolved
Comment thread src/Common/ByteSetLookup.h Resolved
Comment thread src/Common/ByteSetLookup.h Resolved
Comment thread src/Common/ByteSetLookup.h Resolved
Comment thread src/Common/ByteSetLookup.h Resolved
Comment thread src/Common/ByteSetLookup.h Resolved
Comment thread src/Common/ByteSetLookup.h Resolved
Comment thread src/Common/ByteSetLookup.h Resolved
Comment thread src/Common/ByteSetLookup.h Resolved
Clarify the comments in `ByteSetLookup`: describe the set as at most 256 elements
with two operations, explain the row/column bit encoding of the nibble tables,
rename `classify` to `containsVector`, and do not refer to tokens in a generic
byte-set class.

Pass the tokenizer explicitly in the forced-index queries of test 05178. Without
the third argument `hasAnyTokens` and `hasAllTokens` tokenize with `splitByNonAlpha`
on the scan path, so the forced-index queries of the `splitByString` columns
evaluated a different predicate than the queries with `use_skip_indexes = 0`.

Addresses review comments in ClickHouse#119434

Co-Authored-By: Claude Fable 5.1 <[email protected]>
@CurtizJ
CurtizJ added this pull request to the merge queue Sep 14, 2026
Merged via the queue into ClickHouse:master with commit 8b57af1 Sep 14, 2026
176 checks passed
@CurtizJ
CurtizJ deleted the tokenizers-byte-set branch September 14, 2026 17:30
@robot-clickhouse-ci-1 robot-clickhouse-ci-1 added the pr-synced-to-cloud The PR is synced to the cloud repo label Sep 14, 2026
pull Bot pushed a commit to sonvt1710/ClickHouse that referenced this pull request Sep 29, 2026
The Ngrams arm of forEachToken was the last frequently used tokenizer
still going through the generic pull loop over NgramsTokenizer::nextInString.
Each call re-counts n code points from its own start position and then
advances by one more, so a token costs n + 1 UTF8::seqLength steps, in an
out-of-line function, although consecutive n-grams share n - 1 of them.

NgramsTokenizer::forEachTokenImpl keeps two cursors on the one chain of
code point starts c_0 = 0, c_{k+1} = c_k + seqLength(data[c_k]): begin is
the start of the current n-gram and last the start of its n-th code point.
Each token advances both by one step, so it costs two steps, and the
callback is visible at the call site like the four sibling
forEachTokenImpl in this header (ClickHouse#119434).

The emitted sequence is the one nextInString produces: both emit
[c_j, min(c_{j+n}, length)) iff c_{j+n-1} < length, in order of j, and
stop at the first callback returning true. seqLength is at least 1, so
both loops terminate, and the new one reads data[begin] and data[last]
only below length. n = 0 would differ but cannot reach this code
(MIN_NGRAM_SIZE = 1 in TokenizerFactory.cpp).

Measured on x86_64 with the amd_release ThinLTO configuration, both
binaries from one build directory, alternating pairs, geometric mean of
per-pair query_duration_ms ratios with a 95% interval:

  tokens(URL, 'ngrams', 3), 10M ClickBench URLs     -35.7% [-36.4, -35.1]
  tokens(URL, 'ngrams', 5)                          -39.9% [-40.7, -39.1]
  tokens(s, 'ngrams', 3), 10M Cyrillic/CJK strings  -29.8% [-31.4, -28.2]
  INSERT into a text(tokenizer = ngrams(3)) index    -7.8% [-10.3, -5.3]
  INSERT into an ngrambf_v1(3, 4096, 3, 0) index     -6.3% [-7.5, -5.1]
  tokens(URL) and splitByString controls             -0.8% and +1.2%

The token streams are identical to master over an adversarial byte
corpus (tokens and ngrams, n up to 64), 1M synthetic rows and 10M
ClickBench URLs, and the text and ngrambf_v1 index files are
byte-identical. The new test pins the UTF-8 boundary cases; its reference
was generated with the unpatched binary.

Reported and measured on aarch64 by snelheidai in ClickHouse#122227.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

comp-text-index Full-text search: inverted/text index in MergeTree (tokenizers, posting lists, GIN-style index bu... pr-performance Pull request with some performance improvements pr-synced-to-cloud The PR is synced to the cloud repo

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants