← Back to Pull requests

Keep PQ encoding on SIMD on JDK 21 when C2 compiles the stream frame first #839

Closed
unknown closed this pull request without merging on Dec 01, 2026 01:22 UTC
View on GitHub
unknown unknown commented on Nov 25, 2026 10:23 UTC
Author

Fixes #801.

Summary

On JDK 21, ProductQuantization.encodeAll can run the Vector API's Java fallback instead of SIMD, depending on which method C2 compiles first in a fresh JVM. This PR makes both changes proposed in #801, one commit each.

1. Point-access VectorAccess scans loop over claimed chunks. Before, forEach called the consumer once per vector from IntStream.forEach. That made the JDK frame shared by every IntStream.forEach the hot compile root, and C2 hit its inlining limit inside FloatVector.lanewiseTemplate:

 ForEachOps$ForEachOp$OfInt.accept       (JDK, shared by every IntStream.forEach)
-  VectorAccess.lambda$forEach           one call per vector: this JDK frame gets hot, C2 compiles it as the root
+  VectorAccess.lambda$forEachPoint      one call per worker: never hot through this frame
+    while (claim next 16-position chunk)
+      for i in chunk
       PQVectors.lambda$encodeAndBuild    now compiled as its own root
         ProductQuantization.encodeTo → encodeUnweighted → closestCentroidIndex
           VectorUtil.squareL2Distance → PanamaVectorUtilSupport.squareDistance64 → …
             FloatVector.sub → … → lanewiseTemplate
-              VectorSupport.binaryOp     depth 16 under the JDK root: "failed to inline (intrinsic)", Java fallback
+              VectorSupport.binaryOp     (intrinsic)

Claiming small chunks from a shared counter also does three other things:

  • It keeps each counted loop short. Under Parallel and Serial GC, C2 drops the safepoint poll from such a loop.

  • It rebalances uneven per-vector cost or a busy pool worker.

  • It lets the other workers stop claiming once a consumer fails.
  • Batched sources are unchanged.

    2. The Panama provider scans 1–3-float subspaces with scalar code. PanamaVectorUtilSupport.tryClosestCentroid now handles subspaces of up to 3 floats, which before only the native provider (JDK 22+) did. Every caller of closestCentroidIndex and of the k-means assignment then skips the Vector API for these shapes, whatever the call shape above it. That includes callers outside VectorAccess.forEach, such as single-vector encode() and MutablePQVectors.

    Each distance sums its terms in the order squareDistance does, so the codes don't change. Wider subspaces return -1 and keep the SIMD scan, and so do vectors the provider didn't create. With -ea, the selected distance is checked by VectorUtil as of #834, so the scan needs no assertions of its own.

    Evidence

    All numbers are from Apple M5 Pro (arm64), JDK 21.0.13, PanamaVectorizationProvider, 4 encode threads (-Djvector.physical_core_count=4). Both builds are on main at 7d04508e. The harness is the one from #801, with two additions:

  • a subspace-width argument;

  • a checksum of the codes, made with codebooks saved to disk so codes can be compared across builds.
  • Each JVM trains its own PQ, then times 6 encodeAll rounds over 20,000 random 768-d vectors with 256 centroids. Every JVM run is reported; none were dropped or rerun.

    Nanoseconds per centroid distance, one fresh JVM per run

    | Subspace | Build | JVMs that fell back | Steady state (rounds 2–6, median) | Round 1 |
    |---|---|--:|--:|--:|
    | 2 floats | main | 2 / 10 | 0.158 with SIMD, 4.75 after a fallback (30×) | 0.15–2.49; over 1 in 7 of 10 |
    | 2 floats | this PR | 0 / 10 | 0.166 | 0.16–0.21 |
    | 4 floats | main | 0 / 5 | 0.175 | 0.18–0.20 |
    | 4 floats | this PR | 0 / 5 | 0.177 | 0.18–0.19 |
    | 8 floats | main | 0 / 5 | 0.473 | 0.43–0.47 |
    | 8 floats | this PR | 0 / 5 | 0.445 | 0.44–0.49 |
    | 2 floats, -ea | main | 1 / 6 | 0.189 with SIMD, 4.91 after a fallback | 2.08–2.47 in all 6 |
    | 2 floats, -ea | this PR | 0 / 6 | 0.167 | 0.16–0.20 |

    On main, even JVMs that recovered often ran their first encodeAll 7–15× slower, about 4 s instead of 0.3 s for 20,000 vectors. Codes were identical in every run of every build: one checksum per width.

    CPU profiles

    These are JFR CPU samples (-XX:StartFlightRecording=settings=profile), filtered to stacks under PQVectors.encodeAndBuild so training is left out. Red frames are jdk.incubator.vector.

    main, a JVM that fell back (round 2–6: 4.7–4.9 ns/distance). The samples sit in the Vector API's Java fallback, which computes one lane at a time, under FloatVector.sub:

  • 57% in FloatVector.lanewiseTemplate;

  • 22% in a FloatVector lambda;

  • 11% in fromArray0Template;

  • 3% in bOpTemplate.
  • <img width="1600" height="798" alt="flame-before-fallback" src="https://github.com/user-attachments/assets/e8e2f32d-d928-4d6c-8e28-7aa5694382b5" />

    main, a JVM that kept SIMD (same build, same command, a different JVM):

    <img width="1600" height="577" alt="flame-before-simd" src="https://github.com/user-attachments/assets/fecb1671-3ec1-4ecf-ae92-cc4ed1ca534b" />

    This PR. 80% of samples are in closestCentroid2, and no Vector API frames appear in the encode:

    <img width="1600" height="577" alt="flame-after" src="https://github.com/user-attachments/assets/17d64b8c-d9ac-4d87-baa2-3d3826b5f73b" />

    Top methods from jfr view hot-methods:

    main, JVM that fell back                                                         samples
    jdk.incubator.vector.FloatVector.lanewiseTemplate(...)                            10,072  57.10%
    jdk.incubator.vector.FloatVector$$Lambda.apply(...)                                3,945  22.37%
    jdk.incubator.vector.FloatVector.fromArray0Template(...)                           1,938  10.99%
    jdk.incubator.vector.FloatVector.bOpTemplate(...)                                    508   2.88%
    
    this PR
    io.github.jbellis.jvector.vector.PanamaVectorUtilSupport.closestCentroid2(...)     1,349  80.44%
    io.github.jbellis.jvector.quantization.KMeansPlusPlusClusterer.chooseInitialCentroids(...)  177  10.55%
    

    The fallback allocates a vector object per operation. Young GCs during the whole run, for 5 recorded JVMs per build:

    | Build | Per JVM | Outcome |
    |---|---|---|
    | main | 1,608, 121, 7, 112, 1,712 | fell back throughout, round 1 fell back, kept SIMD, round 1 fell back, fell back throughout |
    | this PR | 7, 7, 7, 7, 7 | kept SIMD |

    C2 inlining (-XX:+PrintCompilation -XX:+PrintInlining)

    These two excerpts were recorded on the previous base, 764a2d8b. VectorAccess and the encode chain are the same on 7d04508e.

    On main, in a JVM that fell back, the tier-4 compile of java.util.stream.ForEachOps$ForEachOp$OfInt::accept inlines the encode and fails sub's intrinsic, as described in #801:

    6931 1024  4  java.util.stream.ForEachOps$ForEachOp$OfInt::accept (11 bytes)
      @ 5   VectorAccess$$Lambda::accept   inline (hot)   TypeProfile (11270/11270 counts)
       @ 13  VectorAccess::lambda$forEach$6   inline (hot)
        …  PQVectors::lambda$encodeAndBuild$1 → ProductQuantization::encodeTo → encodeUnweighted → closestCentroidIndex
         …  VectorUtil::squareL2Distance → PanamaVectorUtilSupport::squareDistance → squareDistance64 → squareDistance64
          @ 27  FloatVector::sub → Float64Vector::lanewise → Float64Vector::lanewise → FloatVector::lanewiseTemplate
            @ 2   AbstractVector::sameSpecies   force inline by annotation
            @ 96  jdk.internal.vm.vector.VectorSupport::binaryOp (38 bytes)   failed to inline (intrinsic)
    

    With this PR, using 8-float subspaces so the Vector API path is still in use, the stream frame never gets a tier-4 compile. C2 compiles the chunk loop on its own, and the encode is a separate root:

    2963 1072 % !   4       io.github.jbellis.jvector.graph.VectorAccess::lambda$forEachPoint$8 @ 47 (102 bytes)
                                  @ 74   io.github.jbellis.jvector.quantization.PQVectors$$Lambda::accept (18 bytes)   already compiled into a big method
    

    Across that whole run: 50 C2 binaryOp intrinsics, 0 unbox failed. The one binaryOp marked "failed to inline (intrinsic)" is in a tier-3 (C1) compile, which never intrinsifies.

    Time to reach a safepoint, Parallel GC

    -XX:+UseParallelGC, a thread dump every 20 ms during 10 encode rounds, -Xlog:safepoint, 3 JVMs per build:

    | Build | Worst wait for the encode threads to reach a safepoint |
    |---|---|
    | main | 2.27, 0.17, 1.51 ms (all 3 fell back; the Java fallback keeps its safepoint polls) |
    | this PR | 1.01, 0.98, 1.02 ms |

    A first version of this change ran one contiguous partition per worker. On the previous base it made that wait 305–369 ms, because C2 had dropped the poll from the whole partition's loop. The 16-position chunks bound the wait to one chunk.

    Tests

  • TestClosestCentroid (new) checks the Panama tryClosestCentroid against the per-centroid squareDistance scan it replaces:

  • - Inputs cover dimensions 0–16, 1–256 centroids, many exact ties, NaN, infinities, ±0, and invalid regions.
    - Centroids that permute one difference vector differ only in summation order, so this case catches a kernel that adds the terms in another order.
    - With the Panama provider, dimensions ≤ 3 must be handled. On main this fails with dim 0. Actual: -1.
  • TestVectorAccess adds two tests (new):

  • - The first checks a point-access mapped scan: every output position is visited once with its mapped vector, each worker reads only the copy it made, and it looks the copy up once rather than once per vector. Against main's per-vector forEach it fails with count 64 lookups 64.
    - The second checks that a consumer failure propagates.
  • The full jvector-tests suite on JDK 21 with -Pjdk20 -DTest_RequireSpecificVectorizationProvider=PanamaVectorizationProvider: 714 run, 0 failures.

  • jvector-native compiles on JDK 27, and jvector-base passes mvn javadoc:jar.
  • Merge Danger

    Door: two-way

    There is no API, format or on-disk change, and codes are bit-for-bit identical, so a revert is free.

    Blast Radius: throughput

  • 2- and 3-float subspaces when SIMD would have worked: the scalar scan is about 5% slower than working SIMD on this arm64 machine (0.166 against 0.158 ns/distance). In return the encode never falls back, which cost 30×, and loses the slow first encode most fresh JVMs paid. Under -ea it's about 12% faster than main's SIMD path.

  • 8-float subspaces: about 6% faster. 4-float subspaces are unchanged.

  • VectorAccess.forEach on point-access sources now takes one atomic increment per 16 positions.

  • The native provider (JDK 22+) overrides tryClosestCentroid, so change 2 doesn't affect it.

  • Not fixed: JDK 21's C2 can still drop a Vector API intrinsic when some other compile happens to inline the encode past its limit. That's the HotSpot bug behind #801 (JDK-8302459). This PR removes the call shape that set it off.

  • No CI guard: CI doesn't run JDK 21, and benchmarks-jmh compiles with --release 22, so neither can catch a return of #801. The harness above, run on several fresh JVMs, is the reproducer.

  • Not measured: x86-64. #801 reports the same mechanism there, a 17× penalty with AVX-512.
  • Checklist notes

  • Release note: docs/release notes/4.1.0-rc.2/839.bugfix.md.

  • Rebase: rebased on main at 7d04508e, which includes #834's -ea change.

  • Run Bench Main: not triggered; this needs a maintainer.

  • Raw data: JFR recordings, collapsed stacks, PrintInlining excerpts, safepoint logs and per-run tables are available on request.
  • Diff: 650 lines (+487 / -163) across 8 files Reviewer: tlwillke Review duration: 8098m
    All Vouch review confidence checks passed
    Residual risk 0.21 = Change Risk (0.52) × (1 − Review Confidence (0.60)). Review depth and reviewer attention state are adequate.
    Model 1 · Change Risk (XGBoost)
    Score: 0.52 · 650 lines diff across 8 files
    0.52
    Model 2 · Review Depth (DistilBERT)
    Depth Score: 0.17 · 1 substantive comment(s)
    0.17
    Model 3 · Review Timing & Attention
    Session adequacy: 100% · Reviewer familiarity: 35%
    60%
    Bedrock Claude 3 · Risk Narration
    (disconnected)
    Groq
    Groq Risk Narration
    AWS Bedrock is currently disconnected. Generate high-confidence PR triage narration on-demand using Groq.
    Model 1 · Change Risk Attribution
    SHAP Weights
    Diff Size diff_size
    0.388
    Shallow Review Depth shallow_review_depth
    0.289
    Real PR Conversation Timeline
    1 comments
    "Review active on #839"
    general weight: 0.35
    Reviewers
    Assignees
    Unassigned
    Labels
    risk: low confidence: 60.5% reviewed
    Vouch Risk Breakdown
    AI-powered review risk analysis
    Change Risk
    Change Risk · Model 1 (XGBoost)
    Predicted defect probability (0.00–1.00) based on diff churn, modified sensitive files, and author risk history.
    Score: 52% (MEDIUM) · Higher = larger blast radius
    52%
    Review Confidence
    Review Confidence · Models 2 & 3
    Scrutiny score (0.00–1.00) combining DistilBERT semantic review depth with reviewer familiarity and session dwell time.
    Score: 60.5% · Lower = rushed or shallow review
    60.5%
    Residual Risk
    Residual Risk · Core Equation
    Residual = Change × (1 − Confidence)
    Unmitigated risk surviving review. ≥ 0.65 triggers an automated re-queue to protect production.
    Score: 20.5% · Safe to merge
    20.5%