Skip to content

Support bf16 in dotProduct and optimize the implementation slightly - #106569

Merged
nickitat merged 13 commits into
masterfrom
arraydotproduct-bf16
Jun 25, 2026
Merged

nickitat merged 13 commits into
masterfrom
arraydotproduct-bf16

Conversation

@nickitat

@nickitat nickitat commented Jun 5, 2026 •

Copy link
Copy Markdown
Member

Changelog category (leave one):

  • Improvement

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

Added support for BFloat16 in dotProduct and improved dot product performance by batching the SIMD path.


Unfortunately, CI won't show perf improvements from enabling bf16, because on master, all such queries will just throw an exception. Here are the custom measurements:

● Complete dotProduct review on CI's actual ThinLTO binaries (branch e38355c9714 vs master f1cc925e, flto=thin), all three boxes:

  Batching effect — master (per-row) vs branch (batched)

  ┌─────────────────┬───────────┬──────────┬───────────┬──────────┐
  │                 │ F32 const │ F32 self │ F64 const │ F64 self │
  ├─────────────────┼───────────┼──────────┼───────────┼──────────┤
  │ AMD Zen5        │ 1.37×     │ 1.08×    │ 1.21×     │ 1.06×    │
  ├─────────────────┼───────────┼──────────┼───────────┼──────────┤
  │ Intel GNR       │ 1.17×     │ 1.03×    │ 1.06×     │ 0.93×    │
  ├─────────────────┼───────────┼──────────┼───────────┼──────────┤
  │ m7i (CI runner) │ 1.03×     │ 0.99×    │ 1.00×     │ 1.00×    │
  └─────────────────┴───────────┴──────────┴───────────┴──────────┘

  BFloat16 (branch only; master throws)

  ┌───────────┬───────────────────┬──────────────────┐
  │           │ BF16 vs F32 const │ BF16 vs F32 self │
  ├───────────┼───────────────────┼──────────────────┤
  │ AMD Zen5  │ 1.40×             │ 1.60×            │
  ├───────────┼───────────────────┼──────────────────┤
  │ Intel GNR │ 1.79×             │ 1.17×            │
  ├───────────┼───────────────────┼──────────────────┤
  │ m7i       │ 1.43×             │ 1.46×            │
  └───────────┴───────────────────┴──────────────────┘

Version info

  • Merged into: 26.7.1.66

nickitat and others added 4 commits June 5, 2026 13:22
`arrayDotProduct` rejected `BFloat16` arrays with an exception, even though
`arrayNorm`/`arrayDistance` already support them and `BFloat16` is the common
storage format for embedding vectors.

Template the existing auto-vectorized `dotProductImpl` kernel on `ArgumentType`
and widen each element to `ResultType` with a `static_cast` inside the loop
(the arrayNorm "widen in the kernel" approach). `BFloat16 x BFloat16` now
accumulates in `Float32` (matching `arrayNorm`/`arrayDistance`); the widening
is the identity when `ArgumentType == ResultType`, so the `Float32`/`Float64`
and integer paths are byte-for-byte unchanged (verified at runtime). Because
the kernel is a generic `MULTITARGET_FUNCTION`, the widened `BFloat16` path
auto-vectorizes on every target - AVX-512 on x86 (`vpmovzxwd`+`vpslld`+FMA),
NEON on ARM - rather than only x86.

Measured `arrayDotProduct` `BFloat16` vs `Float32` (5M x 150, one thread):
AMD Zen5 0.053s vs 0.094s (1.8x faster, half the bytes), Intel GNR 0.170s vs
0.230s. No native AVX512-BF16 (`dpbf16`) path yet - left as a follow-up.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
`arrayDotProduct` previously rejected `BFloat16`, so the new widened path had
no coverage. Add `04312_array_dot_product_bfloat16`: the SIMD const-argument
path over length-80 vectors checked against an independent `Float64`
computation within a tolerance (stable across architectures), the `Float32`
result type, and exact small-integer cases.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
`dotProduct.xml` covered only `Float32`/`Float64`. Split it into
`dotProduct_bfloat16.xml`, `dotProduct_float32.xml` and
`dotProduct_float64.xml`, one element type each (2 queries per file), and add
the `BFloat16` case now that `arrayDotProduct` supports it. Splitting keeps
each file well under the performance runner per-test query limit, the same
issue that was hiding the tail of the combined `norm_distance` test, and
leaves room to re-enable the integer cases without exceeding it.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The dispatch called the `NO_INLINE` `dotProductImpl` kernel once per row. For
the float/BFloat16 fast path that call boundary stalls the hardware prefetcher
between rows, leaving the memory-bound kernel waiting on loads - the same issue
that regressed `Float64` array distances on Zen5.

Move the per-row loop inside the kernel: add `dotProductBatchImpl` (both
columns advance, sizes taken from the offsets) and `dotProductConstBatchImpl`
(left vector fixed, right column advances) and call each once per column in
the non-const and const-left-argument paths. The scalar fall-back path for
mixed/integer types keeps its per-row loop. Results are unchanged (verified
byte-for-byte against the per-row version on deterministic data; the official
`02011_tuple_vector_functions` / `03269_bf16` tests still pass).

Measured on AMD Zen5 (5M x 150, one thread) vs the per-row version:
`Float32` const-arg 1.33x and self 1.28x, `Float64` const-arg 1.17x,
`BFloat16` ~1.05-1.08x; no query regresses.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@nickitat nickitat added the ci-performance performance only label Jun 5, 2026
@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

Workflow [PR], commit [38ad78b]

Summary: ✅


AI Review

Summary

This PR adds BFloat16 support for the array-backed dotProduct / arrayDotProduct path and batches the same-type floating dot-product kernels. I did not find unresolved correctness, safety, documentation, or test-evidence issues in the current diff; the earlier bot concerns about BFloat16 path coverage and generated function documentation are addressed.

Final Verdict

Status: ✅ Approve

@clickhouse-gh clickhouse-gh Bot added the pr-performance Pull request with some performance improvements label Jun 5, 2026
@nickitat nickitat removed the ci-performance performance only label Jun 5, 2026
Comment thread src/Functions/array/arrayDotProduct.cpp Resolved
@clickhouse-gh

clickhouse-gh Bot commented Jun 5, 2026 •

Copy link
Copy Markdown
Contributor

📊 Cloud Performance Report

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

This PR is scoped entirely to the arrayDotProduct/dotProduct vector functions: it adds BFloat16 support and restructures the SIMD kernel into batched per-column calls. Neither ClickBench nor TPC-H queries call dotProduct, so none of the flagged deltas can plausibly come from this change. The eight ClickBench "improvements" (about 5-18%) and the single TPC-H Q4 "regression" (+15.5%, with noisy underlying measurements) are off-path run-to-run variance and have been downgraded. No actionable performance impact from this change on these benchmarks.

clickbench

⚠️ 8 inconclusive

Flagged queries (8 of 43)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 264 220 -16.7% <0.0001 PR only touches arrayDotProduct/dotProduct SIMD kernel; ClickBench Q4 never calls it. Off-path, variance.
⚠️ 15 not_sure 251 205 -18.3% <0.0001 arrayDotProduct change cannot affect this aggregation query; no dot-product code on its path. Variance.
⚠️ 18 not_sure 1342 1258 -6.3% <0.0001 Off-path: PR scope is arrayDotProduct/BFloat16; Q18 doesn't exercise it. Run-to-run variance.
⚠️ 20 not_sure 239 213 -10.9% <0.0001 PR only edits vector dot-product kernel; unrelated to this query. Treat as variance.
⚠️ 28 not_sure 7046 6500 -7.7% <0.0001 arrayDotProduct kernel restructure cannot touch Q28's hot path. Off-path improvement, variance.
⚠️ 32 not_sure 1351 1278 -5.4% <0.0001 Already not_sure; PR (arrayDotProduct only) does not exercise this query anyway.
⚠️ 33 not_sure 1478 1387 -6.2% <0.0001 Off-path: dotProduct change unrelated to Q33. Variance, not a PR effect.
⚠️ 34 not_sure 1482 1396 -5.8% <0.0001 Off-path: dotProduct change unrelated to Q34. Variance, not a PR effect.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

tpch_adapted_1_official

⚠️ 1 inconclusive

Flagged queries (1 of 22)
Query Verdict Baseline median (ms) PR median (ms) Change q-value Hint
⚠️ 4 not_sure 2230 2575 +15.5% 0.0015 TPC-H Q4 (order-priority EXISTS) never calls dotProduct; PR cannot cause this 15% delta. High CV, variance.

q-value = BH-FDR adjusted p; smaller is stronger evidence. MIRAI flags a query when q < fdr_q (default 0.10) — the value the verdict is based on.

Debug info
  • StressHouse run: 6d19d7cb-f2e3-48be-bac9-332b3f2e6126
  • MIRAI run: 11bfdcf5-4701-4b60-8dfb-6663bcad2269
  • PR check IDs:
    • clickbench_24834_1782251428
    • clickbench_24848_1782251428
    • clickbench_24854_1782251428
    • tpch_adapted_1_official_24860_1782251428
    • tpch_adapted_1_official_24867_1782251428
    • tpch_adapted_1_official_24877_1782251428

nickitat and others added 3 commits June 9, 2026 11:24
The registered `FunctionDocumentation` for `arrayDotProduct` and the public
`dotProduct` did not describe `BFloat16` inputs or the same-type `BFloat16` ->
`Float32` result rule, so the generated structured docs were stale. List
`BFloat16` as a supported array element type and document that two `BFloat16`
arrays accumulate in and return `Float32` (the same rule as two `Float32`
arrays).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The test used `range(80)`, but 80 is a multiple of the kernel unroll width (16),
so `dotProductConstBatchImpl` exited after the unrolled loop and never ran the
scalar tail. It also only exercised the constant-left batch path, never the
separate non-const kernel (`dotProductBatchImpl`) used by `arrayDotProduct(v, v)`.

Use `range(150)` (not a multiple of 16, so the tail runs) and add a
column-vs-column `arrayDotProduct(v, v)` assertion checked against an
independent `Float64` computation, so both batch kernels and their tails are
covered.

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@nickitat nickitat changed the title Support bf16 in dotProduct Support bf16 in dotProduct and optimize the implementation slightly Jun 9, 2026
@nickitat
nickitat marked this pull request as ready for review June 9, 2026 16:31
@nickitat
nickitat requested a review from rienath June 16, 2026 14:24
@rienath rienath self-assigned this Jun 16, 2026

@rienath rienath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Looks good. I left a few comments. On a side-note: could we move the PR to Improvement category and add label pr-performance manually as the OR includes both new capability and perf improvement? That'd make the life of release engineer easier down the line.

Also, I noticed that both arm and x86 machines in CI do not have performance difference on F32/F64. Do you have any hypotheses why on Zen5 and Intel GNR the performance changes?

Comment thread src/Functions/vectorFunctions.cpp Resolved
Comment thread src/Functions/array/arrayDotProduct.cpp Resolved
nickitat and others added 5 commits June 23, 2026 14:23
The split into `dotProduct_{bfloat16,float32,float64}.xml` was done to stay under
the perf runner's per-test query limit, but that limit was removed (all tests run
now), so the split just produced three near-identical files that land in
different CI jobs and are harder to find. Fold them back into a single
`dotProduct.xml` with `element_type` ranging over `BFloat16`, `Float32`,
`Float64` (6 queries total).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
The dot-product SIMD kernel only fires for same-type BFloat16 x BFloat16; a
BFloat16 array against any other type falls to the scalar accumulator, which was
untested. Add a distinct Float32 column and assert both orderings (BF16 x T and
T x BF16) match each other and an independent Float64 reference, for both the
column-vs-column path and the const-argument path, plus the mixed result type
(BFloat16 x Float32 -> Float64).

Co-Authored-By: Claude Opus 4.8 <[email protected]>
@clickhouse-gh clickhouse-gh Bot added the pr-improvement Pull request with some product improvements label Jun 23, 2026
@nickitat

Copy link
Copy Markdown
Member Author

Also, I noticed that both arm and x86 machines in CI do not have performance difference on F32/F64. Do you have any hypotheses why on Zen5 and Intel GNR the performance changes?

The X86_V4 code path changes won't affect arm. For x86, the reason seems to be that on older 7i, we were and remain to be memory bound for these queries, so the better compute part had no effect on the execution time. In newer instances, we don't saturate the memory bandwidth, so the compute efficiency matters more.

@clickhouse-gh

clickhouse-gh Bot commented Jun 23, 2026

Copy link
Copy Markdown
Contributor

LLVM Coverage Report

Metric Baseline Current Δ
Lines 85.30% 85.40% +0.10%
Functions 92.50% 92.60% +0.10%
Branches 77.50% 77.60% +0.10%

Changed lines: Changed C/C++ lines covered by tests: 73/93 (78.49%) | Lost baseline coverage (was covered on master, now uncovered in this PR): 3 line(s) · Uncovered code

Full report · Diff report

@nickitat
nickitat requested a review from rienath June 24, 2026 10:14

@rienath rienath left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I've left a small nit, but otherwise looks good

Comment on lines +75 to +80
/// Manual unrolling with independent accumulators to break FP dependency chains.
/// With FMA latency ~4 cycles and throughput 1/cycle, we need >= 4 independent
/// chains to saturate the pipeline. 16 accumulators is enough to do that while
/// keeping the per-row reduction and scalar remainder small: a wider unroll
/// (e.g. 128/sizeof = 32 for Float32) only pays off for very long arrays and
/// noticeably regresses the short (~150-element) arrays typical of vector search.

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

Maybe don't need this block second time (it's very close to the first one and repeats same information)

@nickitat
nickitat added this pull request to the merge queue Jun 25, 2026
Merged via the queue into master with commit 1aa2794 Jun 25, 2026
328 of 330 checks passed
@nickitat
nickitat deleted the arraydotproduct-bf16 branch June 25, 2026 13:54
@robot-ch-test-poll4 robot-ch-test-poll4 added the pr-synced-to-cloud The PR is synced to the cloud repo label Jun 25, 2026
zeekay pushed a commit to hanzoai/datastore that referenced this pull request Sep 11, 2026
…bf16

Support bf16 in `dotProduct` and optimize the implementation slightly
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

pr-improvement Pull request with some product improvements 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