Skip to content

perf(vector): SIMD min/max and word-at-a-time NULLs (#33463) - #33464

Merged
XuPeng-SH merged 11 commits into
matrixorigin:mainfrom
fengttt:minmax-simd-33463
Nov 30, 2026
Merged

XuPeng-SH merged 11 commits into
matrixorigin:mainfrom
fengttt:minmax-simd-33463

Conversation

@fengttt

@fengttt fengttt commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

What type of PR is this?

  • API-change
  • BUG
  • Improvement
  • Documentation
  • Feature
  • Test and CI
  • Code Refactoring

Which issue(s) this PR fixes:

issue #33463

What this PR does / why we need it:

SIMD min/max. New package pkg/common/minmax replaces the hand-unrolled min/max loops in vector.

  • Kernels are generated (mkminmax.go) with archsimd for NEON and AVX2, and are used when the build sets GOEXPERIMENT=simd, as make build does. AVX2 is assumed on amd64. Other builds, and columns under 32 rows, use scalar loops.
  • archsimd rather than portable simd: the latter falls back to 128-bit vectors on x86 CPUs without VPCLMULQDQ, and measured 1.4-2x slower on arm64.
  • Float lanes are selected by comparison, which skips NaN. Go marks Min/Max commutative, so their NaN result is not defined by operand order.

NULLs. Columns with NULLs use the null bitmap a word at a time instead of testing each row. The kernels skip all-NULL words, scan NULL-free words, visit the rows of mostly-NULL words one by one, and in other words replace NULL lanes by a value that widens nothing (a valid value for integers, NaN for floats).

Bug fix. GetMinMaxValue panicked (index out of range) on a const integer vector of more than one row.

CI. make ut does not set GOEXPERIMENT, so it tests only the scalar code. The new package needs no cgo, and simd-kernels.yml tests its scalar and SIMD builds on amd64 and arm64.

Cleanup. Removes the race-build ascending check (assertAscendingSels, raceBuild) from ShrinkByRows, and folds vector/minmax.go into utils.go.

Results (arm64, M2 Max)

Kernel, 8192 rows:

type scalar NEON
int8 3.2 µs 0.13 µs 25x
int16 3.3 µs 0.23 µs 14x
int32 3.0 µs 0.45 µs 6.6x
int64 3.0 µs 1.6 µs 1.8x
float32 5.5 µs 0.82 µs 6.7x
float64 5.5 µs 1.6 µs 3.3x

GetMinMaxValue on 8192 rows with randomly placed NULLs, main vs this PR's SIMD build:

NULLs int64 float64
one row 24.3 -> 2.1 µs 11x 14.6 -> 2.1 µs 6.9x
1% 27.5 -> 2.5 µs 11x 14.5 -> 2.5 µs 5.8x
10% 32.6 -> 2.8 µs 11x 13.6 -> 2.9 µs 4.8x
50% 50.1 -> 2.8 µs 18x 19.9 -> 2.8 µs 7.0x
90% 27.2 -> 0.9 µs 31x 6.8 -> 1.7 µs 4.0x
99% 20.4 -> 0.5 µs 38x 6.7 -> 0.6 µs 12x

Validation

  • minmax, vector, tae/index and colexec/order pass in the scalar build, and in the arm64 SIMD build with -race.
  • The AVX2 kernels pass their tests under Rosetta. AVX2 performance has not been measured yet; it will be on a real amd64 machine.
GOEXPERIMENT=simd GOAMD64=v3 go test -run xxx -bench . -count 5 ./pkg/common/minmax

🤖 Generated with Claude Code

fengttt and others added 2 commits November 29, 2026 18:03
Only a test reads raceBuild. Moving it out also puts the doc comments of
assertAscendingSels back on assertAscendingSels.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Add pkg/common/minmax: generated archsimd kernels for NEON and AVX2, used
by builds with GOEXPERIMENT=simd, and scalar loops for the rest. AVX2 is
assumed on amd64. The package has no cgo, and a workflow tests the scalar
and SIMD builds on both architectures, since make ut sets no experiment.

Columns with NULLs walk the null bitmap a word at a time instead of testing
each row, so spans without NULLs use the kernels.

GetMinMaxValue no longer panics on a const integer vector of more than one
row.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@fengttt
fengttt requested a review from XuPeng-SH as a code owner November 30, 2026 02:03
@qodo-code-review

Copy link
Copy Markdown

Qodo reviews are paused for this user.

Troubleshooting steps vary by plan Learn more →

On a Teams plan?
Reviews resume once this user has a paid seat and their Git account is linked in Qodo.
Link Git account →

Using GitHub Enterprise Server, GitLab Self-Managed, or Bitbucket Data Center?
These require an Enterprise plan - Contact us
Contact us →

@mergify

mergify Bot commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

This pull request is merged.

Remove assertAscendingSels from ShrinkByRows with its test and raceBuild.
The min/max functions left in vector/minmax.go move to utils.go.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
license-eye wants the header first in a file. molint allows unsafe only
through pkg/common/util; CI lints without GOEXPERIMENT and did not see it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
fengttt and others added 3 commits November 29, 2026 20:10
Go compiles min and max of int8 and uint8 to branches, as amd64 has no
8-bit conditional move; on random bytes they mispredict. Without
GOEXPERIMENT=simd, GetMinMaxValue on 65536 random TINYINT rows took
100.8 us against main's 18.6 us. The scalar loops, with and without
NULLs, now compare int32 copies, which compile to CMOV and keep the
order: 15.4 us (2048 rows: 868 -> 502 ns). The SIMD build is unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
govet rejects shifting a possibly 8-bit value by 8. Truncating 256 to T
tells the same thing and still folds to a constant per type.

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

XuPeng-SH commented Nov 30, 2026 •

Copy link
Copy Markdown
Contributor

mo-bot review · mo-bot-local · done

Commit: c7e5c83f510ecae5bd523d2a4f33614be273f333

Review completed. Read the assessment.

@XuPeng-SH XuPeng-SH left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

mo-bot review · mo-bot-local · review

Commit: c7e5c83f510ecae5bd523d2a4f33614be273f333

Assessment: approve

No actionable defects were found. The change reuses the vector min/max boundary and generates architecture-specific kernels where the SIMD API requires concrete types. The scalar and SIMD paths preserved the tested bounds and NULL behavior, and the representative comparison showed gains for larger nullable vectors.

Model: gpt-6.1-terra / max

Session: 01a22868-9ecc-7250-9120-16606b40e9e2 · slot 0 · generation 44

Validation:

  • Scalar and AVX2 min/max suites passed. Selected vector, zonemap, and scan-cutoff tests passed in both modes; selected SIMD tests also passed under the race detector.

  • An embedded MySQL probe passed for flushed nullable bigint and double data, block-filter plans, aggregate bounds, and a repeated-constant insert.

  • A base-owner overlay reproduced the preexisting constant-vector panic. A separate probe passed across the 8,192-row NULL-mask boundary with aligned and unaligned windows.

  • Both generated kernel files matched the checked-in generator. The ARM64 SIMD test binary cross-compiled, and the supplied CI snapshot reports successful ARM64 and AMD64 scalar and SIMD kernel jobs.

  • Representative base-versus-head vector benchmarks and their receipts are retained in the diagnostic directory. The receipt and discussion audit passed.

Limitations:

  • ARM64 execution was not repeated locally; the available host is AMD64.

  • The race-only ascending-selection assertion was removed. The examined current producers validate or construct ordered selections, but the guard no longer detects future violations.

  • The full test suite and mo-tester BVT were not independently run.

@XuPeng-SH
XuPeng-SH merged commit 90068fd into matrixorigin:main Nov 30, 2026
9 checks passed
fengttt added a commit that referenced this pull request Nov 30, 2026
…3463) (#33502)

## What type of PR is this?

- [ ] API-change
- [ ] BUG
- [x] Improvement
- [ ] Documentation
- [ ] Feature
- [ ] Test and CI
- [ ] Code Refactoring

## Which issue(s) this PR fixes:

issue #33463

## What this PR does / why we need it:

Follow-up to #33464. On amd64, its SIMD float valid kernels
(`FloatValid`, used by `GetMinMaxValue` on columns with NULLs) were
slower than the scalar loop at high NULL density: float32 at 90% NULLs
took 2.3 µs per 8192 rows against 0.49 µs scalar.

**Cause.** A kernel visits words with few valid rows row by row (the
visit path) and masks the others with 256-bit vectors. In the float
kernels the visit path ran scalar float code, which Go encodes as legacy
SSE even with `GOAMD64=v3`. Each switch between that code and the
256-bit loops costs about 300 cycles. The evidence:

- A strict alternation of visit and masked words, which branch
prediction gets right every time, was the slowest pattern: 6.6 µs,
against 0.43 µs for visit words alone and 1.0 µs for masked words alone.
So the cost is the switch itself, not mispredicts.
- The int kernels, whose visit path stays in integer registers, run the
same patterns at the mean of the two paths.
- In the disassembly, the only legacy-SSE code inside the 256-bit region
was the float visit path. Any change that left a legacy-SSE instruction
there kept paying the penalty, including XMM loads hidden in
`math.Float64bits(rows[i])` and register spills in the setup code.

**Fix (AVX2 only, in `mkminmax.go`):**
- The float kernels now visit in integer registers. They read the
values' bits through an integer view of the column and map them to
integer keys that order like the floats: a negative value's other bits
flip. NaN is skipped with an integer test, and the bounds are converted
back after the loop.
- The keys are set up before any vector instruction. Between the first
256-bit instruction and the `vzeroupper`, the kernels now contain no
legacy-SSE instruction (checked with binutils `objdump`).
- With the switch cost gone, float32 visits up to 12 valid rows per word
(was 8); float64 stays at 16, which a sweep found best.
- **Mostly NULL columns go to the scalar loop (amd64).** At high NULL
density the plain scalar loop beats every kernel variant, because it
runs no 256-bit code. `FloatValid` now counts the valid rows, stopping
as soon as there are enough, and takes the scalar loop below a
per-architecture threshold. On AVX2 that is 25% valid rows for float32
and 40% for float64, the measured crossovers (float64 vectors hold half
as many lanes, so the scalar loop wins sooner).
- arm64 keeps its kernels. Its generated file only gains the two
thresholds, both 0 (never take the scalar loop). NEON scalar and vector
code share registers with no such penalty, and this PR has no arm64
measurements. See "arm64 thresholds" below.

### Benchmarks

Intel Core Ultra 9 275HX (AVX2), `GOEXPERIMENT=simd GOAMD64=v3`, pinned
to one performance core, median of 8 interleaved runs, main → this PR.

`BenchmarkSwitch` (new), 128 words, each with 4 valid rows (visit) or 32
(masked), ns:

| kernel | visit only | masked only | alternate | random 50/50 |
| --- | --- | --- | --- | --- |
| float32 | 433 → 395 | 1006 → 1022 | 6593 → 557 | 4133 → 611 |
| float64 | 405 → 406 | 2002 → 2018 | 7120 → 1062 | 4627 → 1079 |
| int32 (unchanged) | 252 → 252 | 471 → 469 | 336 → 337 | 340 → 336 |

`BenchmarkValid`, 8192 rows with random NULLs, ns. "scalar" is the plain
scalar loop:

| NULLs | float32 scalar | float32 main → PR | float64 scalar | float64
main → PR |
| --- | --- | --- | --- | --- |
| 0% | 3928 | 936 → 961 | 3906 | 1865 → 1883 |
| 10% | 3948 | 1012 → 1040 | 4431 | 2019 → 2040 |
| 50% | 2508 | 1010 → 1046 | 2838 | 2024 → 2046 |
| 80% | 799 | 1634 → 829 | 931 | 2469 → 955 |
| 90% | 489 | 2295 → 519 | 512 | 586 → 542 |
| 95% | 314 | 404 → 334 | 316 | 402 → 338 |
| 99% | 155 | 249 → 181 | 155 | 244 → 181 |

`BenchmarkGetMinMaxValueNulls` (8192 rows, main → PR): DOUBLE at 90%
NULLs 754 → 721 ns (−4%), at 99% 409 → 370 ns (−9%), and at 0–50% +0.6%
to +2.2%. BIGINT and every `BenchmarkGetMinMaxValueByType` case are
within ±1%.

**Costs:** counting the valid rows adds about 20 ns per 8192 rows on
float32 columns that have some NULLs but are mostly valid (+1.7% to
+3.6%); float64 pays about 1%. It stops after a quarter (float32) or two
fifths (float64) of the words of a dense column. Columns without NULLs
never reach it. At 80–99% NULLs the PR stays 10–30 ns above the scalar
loop: that's the count plus the call.

### arm64 thresholds

arm64 has not been measured, so its thresholds are 0. To set them, run
the crossover on an arm64 machine:

```
GOEXPERIMENT=simd go test -run xxx -bench 'Valid$/float' -count 5 ./pkg/common/minmax
```

For each type, find the NULL percentage where the `scalar` row starts
beating `default`. Then set `scalarBelow["NEON"]` in `mkminmax.go` to
100 minus that percentage, run `go generate ./pkg/common/minmax`, and
check `TestSIMDKernelsRun`.

### Tests

- **Direct kernel test (new):** `TestValidKernelsDifferential` calls the
float valid kernels directly, past the density threshold, so they stay
tested at every NULL density. `TestSIMDKernelsRun` checks that a mostly
NULL column takes the scalar loop where the threshold is set, and the
kernel where it isn't.
- **Differential tests (new):** `TestIntegerDifferential` and
`TestFloatDifferential` compare `Integer`, `Float`, `IntegerValid` and
`FloatValid` (whichever kernels the build has) with plain loops. They
cover every element type and a named type, with random lengths up to 700
rows.
- Masks have an exact random number of valid rows per word, or whole
valid and NULL runs.
- Values come from random bits (every NaN, subnormal and sign pattern),
mixed with extremes, -0, and signaling and negative NaNs.
- **Fuzz target (new):** `FuzzMinMax` runs the same comparisons on
fuzzer input. 3 minutes of fuzzing in the SIMD build (26.8M executions)
found nothing.
- **Mutations:** four mutations of the generated kernels each fail the
new tests: no NaN test, no negative-value key flip, a wrong lane-select
table, and an off-by-one tail reload in the int64 kernel.
- `TestFloatValid` and `TestIntegerValid` gain a "sparse words" mask,
about 13 valid rows per word, which lands on both sides of the visit
thresholds.
- `pkg/common/minmax` passes in the scalar build and in the SIMD build
with `-race`; arm64 SIMD vets.
- `make static-check-changed` reports 0 issues.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

---------

Co-authored-by: Claude Opus 5.5 <[email protected]>
Co-authored-by: mergify[bot] <37929162+mergify[bot]@users.noreply.github.com>

This branch was successfully deployed

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

Labels

kind/bug Something isn't working kind/enhancement kind/refactor Code refactor kind/test-ci size/XXL Denotes a PR that changes 2000+ lines

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants