Skip to content

PRF Speed up k-means++ initialization - #35140

Merged
ogrisel merged 21 commits into
scikit-learn:mainfrom
cakedev0:kmeans/fast_kmeans_plusplus
Oct 28, 2026
Merged

ogrisel merged 21 commits into
scikit-learn:mainfrom
cakedev0:kmeans/fast_kmeans_plusplus

Conversation

@cakedev0

@cakedev0 cakedev0 commented Oct 13, 2026 •

Copy link
Copy Markdown
Member

Reference Issues/PRs

I found this while looking at why scikit-learn-intelex is much faster than scikit-learn on KMeans in scikit-learn-benchmarks: on an Intel Xeon 6787P (2 x 86 cores), the k-means++ init takes 75-97% of the time of KMeans.fit.

Related to #17334.

What does this implement/fix? Explain your changes.

Current implementation is slow for two reasons:

  • for float32 data, _euclidean_distances goes through the upcast path: many float64 BLAS calls on small chunks. On sift (1M x 128) with 64 threads, it takes 365 ms vs 2.7 ms for the raw gemm, and it gets slower with more threads.
  • for low-dimensional data, the single-threaded numpy passes dominate (~10 ms per step for 350k x 3 samples, while the gemm takes 0.2 ms).

This PR evaluates the candidates of a step in a single OpenMP kernel (_kmeans_plusplus_trials_dense). It introduces two units of work:

  • the blocks: each thread processes exactly one block
  • the chunks: it's the parallel reduction unit, and it also allows a trick in the candidates sampling which avoids np.searchsorted(np.cumsum(w * d), r) which is single-threaded and can dominate when the rest is parallelized.

Each thread does one BLAS call for its block of samples, then adds the squared norms, takes the min with the current closest distances and sums the weighted distances per chunk of 256 samples. The next candidates are sampled from these per-chunk sums (first a chunk, then a sample in that chunk), so there is no cumulative sum over all the samples anymore.

Distances smaller than 1% of ||x||² + ||c||² (1e-8 in float64) are recomputed directly, to avoid catastrophic cancellation in float32 (this is what the upcast was protecting against: it was added in #13554 to fix #9354). In particular, a sample identical to a chosen center gets a zero distance and can't be sampled again: test_kmeans_plusplus_far_from_origin fails without this.

Sparse input uses the same sampling and the same recomputation of small distances, so dense and sparse inputs still give the same centers. The candidates are rows of X, so they are sparse too: their dot products with the samples only read the columns of X where they have non-zeros. X is converted to CSC once per call for that (main converts X.T at every step, in X[candidate_ids] @ X.T).

Some notes:

  • For a given random_state, the selected centers are not the same as on main, because the cumulative sums used for sampling are different.
  • kmeans_plusplus now converts X to a C-contiguous float array, so integer input gives float centers (see the docstring example). It also rejects sparse input with 64-bit indices, like the estimators already do (the kernels use 32-bit indices).
  • I do one BLAS call per thread rather than one per chunk of samples because many small concurrent BLAS calls scale badly with OpenBLAS (see also PRF Use bigger chunks of samples in dense Lloyd with many threads cakedev0/scikit-learn#24 for Lloyd).

AI usage disclosure

I used AI assistance for:

  • Code & Algorithm generation, A/B testing several approaches/variants: I've dug deeply into this final version but not in all the things the AI tested.
  • Test generation
  • Research and understanding (profiling)

The main things I trust:

  • existing tests
  • my benchmarks
  • from the code / the algorithm, it's easy to believe this is a good improvement

Benchmarks

See the init columns in probabl-ai/scikit-learn-benchmarks#144

Init speed-up ranges from ~1x to 100x depending on the cases. Typical speed-up is 3x-15x I'd say.

cakedev0 and others added 8 commits October 8, 2026 17:14
Evaluate the candidates of each k-means++ step in a single OpenMP kernel
(one BLAS call per thread, then the min with the closest distances and
the potential per chunk of samples), instead of `_euclidean_distances`
followed by several single-threaded numpy passes. The per-chunk potentials
are used to sample the next candidates without a cumulative sum over all
the samples.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Each k-means++ step is a parallel region: for small datasets, starting
and synchronizing many threads costs more than the work itself.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Recompute small distances in the sparse kernel too, as in the dense one: a
  sample identical to a chosen center could be chosen again in float32 far
  from the origin.
- Don't slice memoryviews per (sample, candidate) in the sparse kernel, it
  made it much slower than main with many threads.
- Accept read-only sparse input, reject sparse input with 64-bit indices in
  kmeans_plusplus as in the estimators.
- Use a lower recompute threshold in float64, recomputing is costly on data far
  from the origin.
- Only sample candidates with a positive potential when rounding errors
  overshoot the potential of a chunk.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
- Pick the best candidate with np.argmin instead of a Cython function.
- Sum the duplicate entries of sparse X in KMeans, MiniBatchKMeans and
  kmeans_plusplus: row_norms and the Cython kernels assume there are none.
  The sparse kernel can then copy the values of a sample instead of adding
  them.
- Explain why the direct recomputation of small distances is accurate.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
It fixes a bug that is already on main, out of scope for this PR.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
@cakedev0
cakedev0 requested a review from jeremiedbb October 14, 2026 04:56
@cakedev0 cakedev0 moved this to PR waiting for reviews in Labs Oct 14, 2026
@cakedev0 cakedev0 added this to Labs Oct 14, 2026
@betatim

betatim commented Oct 15, 2026

Copy link
Copy Markdown
Member

I've not had time to read (and then understand) the diff, but I thought it would be useful to ask AI if the information in the PR is enough to figure out a useful set of benchmarks to run on my MacBook. It said yes and compared the performance of this PR to main on a few different datasets and different number of threads.

One thing I was wondering about was what the downsides of this PR are (ever the optimist I am ;))

Below are the results. It seems like this PR is always faster, except for sparse data with one thread. What is the default number of threads? Maybe we can do something to make the sparse case not slow down?

Below I've posted excerpts from the (long) report the AI wrote. Maybe it is useful?


Naming

Label Commit What
main 14e0baec6d3db2b197c6f966e4580ee17c90ed64 merge-base of the PR with main
PR 7e26a5c37e PR head, branch kmeans/fast_kmeans_plusplus

Machine

Apple Silicon (arm64), 10 cores (os.cpu_count()), macOS 26.7.1.
OpenBLAS 0.3.33 (OpenMP threading layer, target VORTEX) and LLVM
libomp from conda-forge.

Datasets

All synthetic and generated once. "Blobs" means
make_blobs(n, d, centers=50, random_state=0).

Case Data Why it's included
sift_f32 blobs 1M × 128, float32 The PR's headline case: float32 hit main's slow float64 upcast path. Shape of sift, not the real data.
lowdim_f64, lowdim_f32 blobs 350k × 3 The PR's other case: few features, where main's single-threaded numpy passes dominate
mid_f64, mid_f32 blobs 100k × 50 Middle-of-the-road shape; isolates the dtype effect
far_f64, far_f32 blobs 200k × 10, shifted by +1e3 Data far from the origin, where most distances fall below the recompute threshold
sparse_f64 scipy.sparse.random 100k × 10k CSR, 1% density (10M non-zeros) The new sparse kernel vs main's sparse _euclidean_distances
small_f64 blobs 5k × 50 Small input; covers the PR's rule of one thread per 2¹⁶ elements, and is near the #17334 shape
bisect_f64 blobs 50k × 20, BisectingKMeans(n_clusters=100).fit Many small init calls, each of which now enters a BLAS thread limit

Method

  • Each (build, case, k, threads) runs in a fresh subprocess with
    OMP_NUM_THREADS and OPENBLAS_NUM_THREADS set to 1, 4 or 10.
    main and PR runs alternate to reduce drift.
  • After one warm-up call, the reported time is the median of 3–7 calls
    (seeds 1–7), stopping once 3 calls are done and 10 s have passed.
  • Potential is the mean, over 3 seeds, of the sum of squared distances
    from each sample to its nearest initial center. It is reported as the
    ratio PR/main.
  • Peak MB is tracemalloc peak for one call. This counts numpy
    allocations only, not BLAS or Cython calloc buffers.
  • Only kmeans_plusplus is timed; bisect_f64 times the full fit.

Results

Speedup = main time ÷ PR time; above 1 means the PR is faster.

case k threads main (ms) PR (ms) speedup potential PR/main peak MB main peak MB PR
sift_f32 8 1 2054.0 323.7 6.35x 0.998 45 57
sift_f32 8 4 2196.6 136.8 16.05x 0.998 45 57
sift_f32 8 10 2492.3 122.4 20.36x 0.998 45 57
sift_f32 100 1 26179.0 5005.5 5.23x 1.000 61 73
sift_f32 100 4 27940.2 1447.9 19.30x 1.000 61 73
sift_f32 100 10 37009.5 1240.2 29.84x 1.000 61 73
lowdim_f64 8 1 43.2 25.3 1.71x 1.000 37 32
lowdim_f64 8 4 43.3 14.4 3.01x 1.000 37 32
lowdim_f64 8 10 42.6 12.4 3.42x 1.000 37 32
lowdim_f64 100 1 811.1 366.6 2.21x 1.000 53 43
lowdim_f64 100 4 724.5 148.8 4.87x 1.000 53 43
lowdim_f64 100 10 733.7 110.5 6.64x 1.000 53 43
lowdim_f64 1000 1 9626.7 4753.1 2.03x 1.000 69 54
lowdim_f64 1000 4 8441.7 1715.1 4.92x 1.000 69 54
lowdim_f64 1000 10 8303.9 1329.3 6.25x 1.000 69 54
lowdim_f32 8 1 82.4 22.7 3.63x 0.928 14 20
lowdim_f32 8 4 95.0 11.3 8.38x 0.928 14 20
lowdim_f32 8 10 94.7 10.1 9.39x 0.928 14 20
lowdim_f32 100 1 1288.7 297.5 4.33x 1.037 19 26
lowdim_f32 100 4 1288.8 104.0 12.39x 1.037 19 26
lowdim_f32 100 10 1370.5 80.5 17.03x 1.037 19 26
mid_f32 8 1 50.0 14.8 3.37x 0.990 5 6
mid_f32 8 4 48.6 8.4 5.80x 0.990 5 6
mid_f32 8 10 52.7 7.5 7.04x 0.990 5 6
mid_f32 100 1 718.9 217.0 3.31x 0.994 6 7
mid_f32 100 4 789.6 78.3 10.09x 0.994 6 7
mid_f32 100 10 777.8 66.4 11.72x 0.994 6 7
mid_f32 1000 1 8583.0 2408.9 3.56x 1.001 8 9
mid_f32 1000 4 8908.1 837.0 10.64x 1.001 8 9
mid_f32 1000 10 8942.5 687.0 13.02x 1.001 8 9
mid_f64 8 1 30.1 22.0 1.37x 1.000 11 9
mid_f64 8 4 25.6 12.4 2.06x 1.000 11 9
mid_f64 8 10 22.6 10.7 2.10x 1.000 11 9
mid_f64 100 1 501.7 334.6 1.50x 1.000 15 12
mid_f64 100 4 400.7 115.7 3.46x 1.000 15 12
mid_f64 100 10 347.1 98.7 3.52x 1.000 15 12
mid_f64 1000 1 5885.3 3773.8 1.56x 1.000 20 15
mid_f64 1000 4 4860.0 1303.7 3.73x 1.000 20 15
mid_f64 1000 10 4513.5 1049.0 4.30x 1.000 20 15
far_f32 100 1 773.1 510.1 1.52x 1.007 11 15
far_f32 100 4 778.8 153.6 5.07x 1.007 11 15
far_f32 100 10 834.7 117.0 7.13x 1.007 11 15
far_f64 100 1 418.7 264.3 1.58x 1.000 31 24
far_f64 100 4 380.6 109.6 3.47x 1.000 31 24
far_f64 100 10 385.6 83.6 4.62x 1.000 31 24
sparse_f64 8 1 361.3 490.2 0.74x 1.000 123 9
sparse_f64 8 4 358.4 139.2 2.57x 1.000 123 9
sparse_f64 8 10 362.4 95.0 3.82x 1.000 123 9
sparse_f64 100 1 4940.3 9872.8 0.50x 1.000 133 18
sparse_f64 100 4 5112.3 2618.9 1.95x 1.000 133 18
sparse_f64 100 10 5151.6 1725.7 2.99x 1.000 133 18
small_f64 8 1 1.6 1.3 1.23x 1.000 1 0
small_f64 8 4 1.9 1.2 1.61x 1.000 1 0
small_f64 8 10 2.0 1.3 1.61x 1.000 1 0
small_f64 100 1 20.8 16.8 1.23x 1.000 1 1
small_f64 100 4 22.1 11.3 1.96x 1.000 1 1
small_f64 100 10 24.8 11.5 2.17x 1.000 1 1
bisect_f64 100 1 100.0 103.7 0.96x – 18 18
bisect_f64 100 4 145.7 147.0 0.99x – 18 18
bisect_f64 100 10 209.2 211.0 0.99x – 18 18

Toolchain versions

System:
    python: 3.14.6 | packaged by conda-forge | (main, Jun 12 2026, 08:47:56) [Clang 20.1.8 ]
executable: /Users/thead/miniconda/envs/sklearn-py3.14/bin/python
   machine: macOS-26.7.1-arm64-arm-64bit-Mach-O

Python dependencies:
      sklearn: 1.10.dev0
          pip: 26.1.2
   setuptools: 81.0.0
        numpy: 2.5.0
        scipy: 1.18.0
       Cython: 3.2.5
       pandas: 3.0.6
   matplotlib: None
       joblib: 1.5.3
threadpoolctl: 3.6.0
     narwhals: 2.23.0

Built with OpenMP: True

threadpoolctl info:
       user_api: blas
   internal_api: openblas
    num_threads: 10
         prefix: libopenblas
       filepath: /Users/thead/miniconda/envs/sklearn-py3.14/lib/libopenblas.0.dylib
        version: 0.3.33
threading_layer: openmp
   architecture: VORTEX

       user_api: openmp
   internal_api: openmp
    num_threads: 10
         prefix: libomp
       filepath: /Users/thead/miniconda/envs/sklearn-py3.14/lib/libomp.dylib
        version: None

Build toolchain, from the sklearn-py3.14 env: conda-forge compilers
2.0.0 (clang 21.1.8), meson 1.11.1, meson-python 0.20.0, Cython 3.2.5,
llvm-openmp 22.1.8.

Benchmark script

bench_kpp.py
"""Benchmark k-means++ init: main (merge-base) vs PR #35140.

Usage:
  python bench_kpp.py gen                      # write datasets to DATA_DIR
  python bench_kpp.py run BUILD CASE K         # one measurement, prints a JSON line
  python bench_kpp.py drive OUT.jsonl          # loop over everything
  python bench_kpp.py report OUT.jsonl
  python bench_kpp.py versions BUILD           # sklearn.show_versions() for a build
"""

import json
import os
import statistics
import subprocess
import sys
import time

HERE = os.path.dirname(os.path.abspath(__file__))
S = os.path.dirname(HERE)
DATA_DIR = os.path.join(S, "data")
SITES = {"main": os.path.join(S, "site-main"), "pr": os.path.join(S, "site-pr"),
         "prsparse": os.path.join(S, "site-prsparse")}
THREADS = [1, 4, 10]

# name -> (description, n_clusters list)
CASES = {
    "sift_f32": ("1M x 128 float32 (sift-like blobs)", [8, 100]),
    "lowdim_f64": ("350k x 3 float64", [8, 100, 1000]),
    "lowdim_f32": ("350k x 3 float32", [8, 100]),
    "mid_f32": ("100k x 50 float32", [8, 100, 1000]),
    "mid_f64": ("100k x 50 float64", [8, 100, 1000]),
    "far_f32": ("200k x 10 float32, offset 1e3", [100]),
    "far_f64": ("200k x 10 float64, offset 1e3", [100]),
    "sparse_f64": ("CSR 100k x 10k, density 1%", [8, 100]),
    "small_f64": ("5k x 50 float64", [8, 100]),
    "bisect_f64": ("BisectingKMeans 50k x 20, n_clusters=100 (full fit)", [100]),
}


def gen():
    import numpy as np
    import scipy.sparse as sp
    from sklearn.datasets import make_blobs

    os.makedirs(DATA_DIR, exist_ok=True)

    def blobs(n, d, seed=0):
        return make_blobs(n_samples=n, n_features=d, centers=50, random_state=seed)[0]

    np.save(f"{DATA_DIR}/sift_f32.npy", blobs(1_000_000, 128).astype(np.float32))
    low = blobs(350_000, 3)
    np.save(f"{DATA_DIR}/lowdim_f64.npy", low)
    np.save(f"{DATA_DIR}/lowdim_f32.npy", low.astype(np.float32))
    mid = blobs(100_000, 50)
    np.save(f"{DATA_DIR}/mid_f64.npy", mid)
    np.save(f"{DATA_DIR}/mid_f32.npy", mid.astype(np.float32))
    far = blobs(200_000, 10) + 1e3
    np.save(f"{DATA_DIR}/far_f64.npy", far)
    np.save(f"{DATA_DIR}/far_f32.npy", far.astype(np.float32))
    Xs = sp.random(100_000, 10_000, density=0.01, format="csr", random_state=0)
    sp.save_npz(f"{DATA_DIR}/sparse_f64.npz", Xs)
    np.save(f"{DATA_DIR}/small_f64.npy", blobs(5_000, 50))
    np.save(f"{DATA_DIR}/bisect_f64.npy", blobs(50_000, 20))


def use_build(build):
    # Drop the editable-install finder so the unpacked wheel wins.
    sys.meta_path[:] = [
        f for f in sys.meta_path
        if not type(f).__module__.startswith("_scikit_learn_editable_loader")
    ]
    sys.path.insert(0, SITES[build])
    import sklearn
    import sklearn.cluster._k_means_common as kmc

    assert sklearn.__file__.startswith(SITES[build]), sklearn.__file__
    assert hasattr(kmc, "_kmeans_plusplus_trials_dense") == (build != "main")


def potential(X, centers):
    import numpy as np
    from sklearn.metrics import pairwise_distances_argmin_min

    _, d = pairwise_distances_argmin_min(X, centers.astype(X.dtype))
    return float(np.sum(d.astype(np.float64) ** 2))


def run(build, case, k):
    use_build(build)
    import numpy as np
    import scipy.sparse as sp
    import tracemalloc
    from sklearn.cluster import BisectingKMeans, kmeans_plusplus

    if case.startswith("sparse"):
        X = sp.load_npz(f"{DATA_DIR}/{case}.npz")
    else:
        X = np.load(f"{DATA_DIR}/{case}.npy")

    if case.startswith("bisect"):
        def call(seed):
            BisectingKMeans(n_clusters=k, random_state=seed).fit(X)
            return None
    else:
        def call(seed):
            return kmeans_plusplus(X, k, random_state=seed)[0]

    call(0)  # warm-up
    times, pots = [], []
    t_budget = time.perf_counter()
    for seed in range(1, 8):
        t0 = time.perf_counter()
        centers = call(seed)
        times.append(time.perf_counter() - t0)
        if centers is not None and len(pots) < 3:
            pots.append(potential(X, centers))
        if len(times) >= 3 and time.perf_counter() - t_budget > 10:
            break

    # Peak traced (numpy) memory of a single call, single thread count is fine.
    tracemalloc.start()
    call(1)
    _, peak = tracemalloc.get_traced_memory()
    tracemalloc.stop()

    return {
        "build": build, "case": case, "k": k,
        "threads": int(os.environ["OMP_NUM_THREADS"]),
        "median_s": statistics.median(times), "min_s": min(times),
        "n_reps": len(times),
        "potential": statistics.mean(pots) if pots else None,
        "peak_mb": peak / 2**20,
    }


def drive(out):
    done = set()
    if os.path.exists(out):
        for line in open(out):
            r = json.loads(line)
            done.add((r["build"], r["case"], r["k"], r["threads"]))
    for case, (_, ks) in CASES.items():
        for k in ks:
            for t in THREADS:
                for build in ("main", "pr"):
                    if (build, case, k, t) in done:
                        continue
                    env = dict(os.environ, OMP_NUM_THREADS=str(t),
                               OPENBLAS_NUM_THREADS=str(t))
                    t0 = time.time()
                    p = subprocess.run(
                        [sys.executable, __file__, "run", build, case, str(k)],
                        env=env, capture_output=True, text=True, cwd=HERE,
                    )
                    if p.returncode:
                        print(f"FAIL {build} {case} k={k} t={t}\n{p.stderr[-2000:]}",
                              flush=True)
                        continue
                    line = p.stdout.strip().splitlines()[-1]
                    with open(out, "a") as f:
                        f.write(line + "\n")
                    r = json.loads(line)
                    print(f"{case:11s} k={k:<5d} t={t:<3d} {build:5s} "
                          f"{r['median_s']*1e3:10.1f} ms  ({time.time()-t0:.0f}s wall)",
                          flush=True)


def report(out):
    rows = [json.loads(l) for l in open(out)]
    by = {(r["case"], r["k"], r["threads"], r["build"]): r for r in rows}
    print("| case | k | threads | main (ms) | PR (ms) | speedup | potential PR/main "
          "| peak MB main | peak MB PR |")
    print("|---|---:|---:|---:|---:|---:|---:|---:|---:|")
    for case, (desc, ks) in CASES.items():
        for k in ks:
            for t in THREADS:
                m, p = by.get((case, k, t, "main")), by.get((case, k, t, "pr"))
                if not (m and p):
                    continue
                ratio = (f"{p['potential']/m['potential']:.3f}"
                         if m["potential"] else "–")
                print(f"| {case} | {k} | {t} | {m['median_s']*1e3:.1f} "
                      f"| {p['median_s']*1e3:.1f} "
                      f"| {m['median_s']/p['median_s']:.2f}x | {ratio} "
                      f"| {m['peak_mb']:.0f} | {p['peak_mb']:.0f} |")


if __name__ == "__main__":
    cmd = sys.argv[1]
    if cmd == "gen":
        gen()
    elif cmd == "run":
        print(json.dumps(run(sys.argv[2], sys.argv[3], int(sys.argv[4]))))
    elif cmd == "drive":
        drive(sys.argv[2])
    elif cmd == "report":
        report(sys.argv[2])
    elif cmd == "versions":
        use_build(sys.argv[2])
        import sklearn
        from sklearn.utils._openmp_helpers import _openmp_parallelism_enabled

        sklearn.show_versions()
        print(f"\nsklearn loaded from: {sklearn.__file__}")
        print(f"OpenMP parallelism enabled: {_openmp_parallelism_enabled()}")

@cakedev0

Copy link
Copy Markdown
Member Author

@betatim I can't really reproduce a clear slowdown on an intel laptop and on an intel server (Xeon 6), can you try to re-run just the cases with a slowdown? With interlaced runs between main and branch.

Thermal & Power management of laptops makes benchmarks mixing multi-threaded and single-threaded regions quite unstable.

One sum over the non-zeros per candidate is a chain of dependent additions,
which made the sparse kernel slower than main on one thread on some CPUs.

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

cakedev0 commented Oct 16, 2026 •

Copy link
Copy Markdown
Member Author

@betatim

What is the default number of threads?

All the CPUs (or OMP_NUM_THREADS if set), but at most one thread per 2**16 elements of X (non-zeros for sparse X), because each k-means++ step is a short parallel region. Note that on main the sparse path is single-threaded whatever the number of threads: it's scipy's sparse x dense product.

So I think the one-threaded sparse case is a bit artificial, I would not have tried to make it better. Still AI wanted to make it faster and it did it. It's more complex now, I find it a bit hard to understand compared to the previous implementation. But I kept it as it makes things around 2x faster in many (sparse) cases and at all threads counts.

Explanation of the improvement form AI:

The sparse kernel did one sum over the non-zeros per candidate, which is a chain of dependent additions, so its speed depends a lot on the CPU (which could explain a real slowdown on MacOS/AMD). 6b86d54 sums the dot products of a sample with all the candidates together, with the candidates in the inner loop (that's also what scipy's sparse x dense product does on main).

@cakedev0

Copy link
Copy Markdown
Member Author

Below I've posted excerpts from the (long) report the AI wrote. Maybe it is useful?

big +1 for usefulness but I propose to collectively take the habit of putting this kind of long reports inside <details> tags to spare our scrolling muscles 😉

@betatim

betatim commented Oct 16, 2026

Copy link
Copy Markdown
Member

I only copied the bits I thought would be useful and the script went in a details. Which additional parts would you remove/hide in details? On reflection I would keep the (massive) table of results and the datasets table. Hide the details on my machine and the versions used?

I haven't tried to re-run the sparse cases. Do you still want to see the results for the version without the latest improvement? I will re-run with the improvements to see what it does. I assume we will see a speed up :D

@cakedev0

Copy link
Copy Markdown
Member Author

Personally, I would put all the AI report under a details tag. I would only keep it on the initial write-up of a PR or an issue.

I'd be happy to results for both 👍 🙏 improving my intuition of how noisy benchmarks can get is very useful for me.

@betatim

betatim commented Oct 16, 2026

Copy link
Copy Markdown
Member

It seems like it changed nothing :-/

Main sweep: main vs PR 6b86d54b16

case k threads main (ms) PR (ms) speedup potential PR/main peak MB main peak MB PR
sparse_f64 8 1 373.4 557.2 0.67x 1.000 123 9
sparse_f64 8 4 381.0 159.9 2.38x 1.000 123 9
sparse_f64 8 10 375.5 111.8 3.36x 1.000 123 9
sparse_f64 100 1 5155.9 9449.9 0.55x 1.000 133 18
sparse_f64 100 4 5245.3 2557.8 2.05x 1.000 133 18
sparse_f64 100 10 5249.6 1605.2 3.27x 1.000 133 18
Full results table

Main sweep: main vs PR 6b86d54b16

case k threads main (ms) PR (ms) speedup potential PR/main peak MB main peak MB PR
sift_f32 8 1 1894.1 316.3 5.99x 0.998 45 57
sift_f32 8 4 2255.9 137.7 16.38x 0.998 45 57
sift_f32 8 10 2474.7 131.9 18.77x 0.998 45 57
sift_f32 100 1 25333.3 4926.1 5.14x 1.000 61 73
sift_f32 100 4 27816.1 1635.3 17.01x 1.000 61 73
sift_f32 100 10 35577.1 1209.0 29.43x 1.000 61 73
lowdim_f64 8 1 44.7 25.0 1.79x 1.000 37 32
lowdim_f64 8 4 41.5 14.3 2.91x 1.000 37 32
lowdim_f64 8 10 43.8 12.3 3.56x 1.000 37 32
lowdim_f64 100 1 771.9 364.6 2.12x 1.000 53 43
lowdim_f64 100 4 657.3 139.1 4.73x 1.000 53 43
lowdim_f64 100 10 670.9 104.8 6.40x 1.000 53 43
lowdim_f64 1000 1 9767.5 4712.1 2.07x 1.000 69 54
lowdim_f64 1000 4 8563.9 1844.5 4.64x 1.000 69 54
lowdim_f64 1000 10 8172.8 1308.5 6.25x 1.000 69 54
lowdim_f32 8 1 86.4 21.1 4.10x 0.928 14 20
lowdim_f32 8 4 80.6 11.7 6.89x 0.928 14 20
lowdim_f32 8 10 87.3 10.2 8.54x 0.928 14 20
lowdim_f32 100 1 1216.6 294.5 4.13x 1.037 19 26
lowdim_f32 100 4 1385.5 104.7 13.23x 1.037 19 26
lowdim_f32 100 10 1344.5 83.5 16.11x 1.037 19 26
mid_f32 8 1 53.3 15.9 3.34x 0.990 5 6
mid_f32 8 4 55.1 8.7 6.31x 0.990 5 6
mid_f32 8 10 53.3 8.2 6.47x 0.990 5 6
mid_f32 100 1 826.3 226.6 3.65x 0.994 6 7
mid_f32 100 4 822.1 80.9 10.16x 0.994 6 7
mid_f32 100 10 810.8 70.4 11.52x 0.994 6 7
mid_f32 1000 1 9369.8 2482.1 3.77x 1.001 8 9
mid_f32 1000 4 9289.0 857.7 10.83x 1.001 8 9
mid_f32 1000 10 9109.4 723.1 12.60x 1.001 8 9
mid_f64 8 1 32.2 22.9 1.40x 1.000 11 9
mid_f64 8 4 25.0 12.6 1.98x 1.000 11 9
mid_f64 8 10 26.1 11.0 2.39x 1.000 11 9
mid_f64 100 1 538.3 343.8 1.57x 1.000 15 12
mid_f64 100 4 399.0 125.1 3.19x 1.000 15 12
mid_f64 100 10 413.3 104.1 3.97x 1.000 15 12
mid_f64 1000 1 6465.5 3900.2 1.66x 1.000 20 15
mid_f64 1000 4 5103.2 1394.4 3.66x 1.000 20 15
mid_f64 1000 10 4663.7 1130.1 4.13x 1.000 20 15
far_f32 100 1 896.1 520.5 1.72x 1.007 11 15
far_f32 100 4 881.8 155.6 5.67x 1.007 11 15
far_f32 100 10 911.4 123.4 7.39x 1.007 11 15
far_f64 100 1 441.6 260.7 1.69x 1.000 31 24
far_f64 100 4 404.8 106.0 3.82x 1.000 31 24
far_f64 100 10 399.4 86.8 4.60x 1.000 31 24
sparse_f64 8 1 373.4 557.2 0.67x 1.000 123 9
sparse_f64 8 4 381.0 159.9 2.38x 1.000 123 9
sparse_f64 8 10 375.5 111.8 3.36x 1.000 123 9
sparse_f64 100 1 5155.9 9449.9 0.55x 1.000 133 18
sparse_f64 100 4 5245.3 2557.8 2.05x 1.000 133 18
sparse_f64 100 10 5249.6 1605.2 3.27x 1.000 133 18
small_f64 8 1 1.9 1.3 1.49x 1.000 1 0
small_f64 8 4 1.9 1.1 1.70x 1.000 1 0
small_f64 8 10 1.9 1.3 1.50x 1.000 1 0
small_f64 100 1 22.6 17.6 1.29x 1.000 1 1
small_f64 100 4 20.6 10.8 1.91x 1.000 1 1
small_f64 100 10 21.7 13.9 1.56x 1.000 1 1
bisect_f64 100 1 103.4 104.4 0.99x – 18 18
bisect_f64 100 4 137.5 159.2 0.86x – 18 18
bisect_f64 100 10 199.3 204.0 0.98x – 18 18

And in the next detail an analysis from the AI that it gave me "for free" when I asked it to re-run the benchmarks. Maybe this suggests that for 1 thread we should use main and for >1 thread use this PR for sparse data?

AI analysis

What each side does per step

I timed one k-means++ step with 6 candidates (k=100) on one thread:

Data main: _euclidean_distances main: X.T.tocsr() alone PR old: trials kernel PR new: trials kernel
sparse_f64 51.1 ms 48.5 ms 100.8 ms 94.1 ms
sparse_news20 13.5 ms 10.9 ms 37.8 ms 30.6 ms
  • Main computes X[candidate_ids] @ X.T with sparse candidates.
    Converting X.T to CSR on its own takes almost the whole step time. This
    suggests scipy converts the CSC operand on every call, and the multiply
    itself is cheap because the candidates are sparse. I inferred this from
    the timings and didn't profile scipy to confirm it. Either way, main's
    per-step cost is roughly one memory-bound pass over the non-zeros of X.
  • The PR densifies the candidates and does n_trials × nnz(X)
    multiply-adds: 60M per step on sparse_f64 and 17M on sparse_news20.
    It runs at only 0.46–0.64 G multiply-adds/s on one thread.
  • The new commit speeds up the kernel by 7% (uniform) and 19% (20
    newsgroups). That's not enough, because the PR does about n_trials times
    as much work per non-zero as main, at a lower rate per element.

So the single-threaded gap comes from the algorithm, not from how the
inner loop is written. Closing it on one thread would probably mean using
the sparsity of the candidates, as main does, rather than tuning the dense
inner loop. I haven't checked why the kernel only reaches 0.5–0.6 G/s.

The candidates are rows of X, so their dot products with the samples only
need the columns of their non-zeros. X is converted to CSC once per call.

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

Copy link
Copy Markdown
Member Author

@betatim Thanks for re-running! Your AI analysis is right: main multiplies the sparse candidates with X.T, which is cheap, and most of main's time per step is scipy converting X.T to CSR.

I pushed a76e618, which uses the sparsity of the candidates like main does. X is converted to CSC once per kmeans_plusplus call (main converts X.T at every step), then applies a Cython kernel that now ressembles a lot with the dense one (which is a really nice perk IMO, as it makes the overall code quite easier to understand I think).

Could you re-run the sparse cases on your Mac? 🙏

Maybe this suggests that for 1 thread we should use main and for >1 thread use this PR for sparse data?

I'd rather avoid two code paths, and with this change it shouldn't be needed.

With many threads and a small n_clusters, the single-threaded X.tocsc() is now a good part of the time.

I already had in mind to implement parallel conversions (CSR/CSC, C/F order) in scikit-learn. I think it would be useful here and even more in other places. But I keep that as as separate idea/PR #staytuned 😜

cakedev0 and others added 2 commits October 16, 2026 14:15
With threadpoolctl 3.7 and OpenBLAS's OpenMP threading layer, limiting BLAS
to 1 thread also sets the default number of OpenMP threads of the current
thread to 1, so k-means++ ran on a single thread.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
cakedev0 added a commit to probabl-ai/scikit-learn-benchmarks that referenced this pull request Oct 19, 2026
…teration

For scikit-learn/scikit-learn#35140. The workloads move to configs/_kmeans.py,
to share them with a Lloyd-only config.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Clearer names (potentials, dist_sq, center_indices), shapes in the
argument comments, docstrings and NumPy equivalents of each kernel call.
The random values are now drawn in _kmeans_plusplus_sample_candidates,
in the same order as before, so the results don't change.

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

Copy link
Copy Markdown

This PR exceeds the recommended size of 500 lines changed. Consider splitting it into smaller PRs to ease the review process. Please make sure you read our Contributing guide and in particular our Pull Request guidelines

@ogrisel ogrisel 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.

This is already much easier to read. Here are some more suggestions to use more consistent/explicit variable names.

Comment thread sklearn/cluster/_k_means_common.pyx Outdated
The potential of a sample is its squared distance to the closest center,
weighted by `sample_weight`.

Each candidate is evaluated as a possible new center: with candidate `j`

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 think j should be renamed to trial_idx and i to sample_idx, both in the docstring and in the code.

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

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

Did that.

I just kept i & j in comments like that because I find the sentence easier to ready/more fluent this way

# trials_dist_sq[:, j, i] is the squared distance from sample i to its
# closest center, with candidate j added to the centers.

Comment thread sklearn/cluster/_kmeans.py Resolved
Comment thread sklearn/cluster/_kmeans.py Resolved
Comment thread sklearn/cluster/tests/test_k_means.py Resolved
Comment thread sklearn/cluster/_k_means_common.pyx Resolved
@cakedev0

cakedev0 commented Oct 22, 2026 •

Copy link
Copy Markdown
Member Author

Thanks for the review, I've spent some time addressing them half-manually, I think it should be better now in terms of readability.

I find the chunk trick to be inherently hard to read/understand, as it's a pure performance artifact, I had already asked Claude to make some documentation effort on it because I simply couldn't understand it at first. Once I understood that, the rest felt relatively easy to grasp (but I had already spent quite some time in that code at that point...).

@betatim

betatim commented Oct 23, 2026 •

Copy link
Copy Markdown
Member

Re-run of the benchmarks on my macbook using the commit 0ca7554. Looks like you fixed it!

case k threads main (ms) PR (ms) speedup potential PR/main peak MB main peak MB PR
sparse_f64 8 1 377.7 73.7 5.12x 1.000 123 124
sparse_f64 8 4 382.3 67.8 5.64x 1.000 123 124
sparse_f64 8 10 382.9 66.9 5.73x 1.000 123 124
sparse_f64 100 1 5133.3 277.4 18.50x 1.000 133 133
sparse_f64 100 4 5130.0 164.9 31.10x 1.000 133 133
sparse_f64 100 10 5175.4 173.3 29.87x 1.000 133 133
Full results table

case k threads main (ms) PR (ms) speedup potential PR/main peak MB main peak MB PR
sift_f32 8 1 1797.1 321.2 5.59x 0.998 45 57
sift_f32 8 4 1940.2 136.4 14.23x 0.998 45 57
sift_f32 8 10 2371.7 125.6 18.88x 0.998 45 57
sift_f32 100 1 24286.1 5129.4 4.73x 1.000 61 73
sift_f32 100 4 27802.2 1456.4 19.09x 1.000 61 73
sift_f32 100 10 37429.4 1215.3 30.80x 1.000 61 73
lowdim_f64 8 1 46.3 26.0 1.78x 1.000 37 32
lowdim_f64 8 4 43.9 14.0 3.14x 1.000 37 32
lowdim_f64 8 10 43.2 12.3 3.51x 1.000 37 32
lowdim_f64 100 1 836.3 379.0 2.21x 1.000 53 43
lowdim_f64 100 4 721.5 136.2 5.30x 1.000 53 43
lowdim_f64 100 10 688.3 108.9 6.32x 1.000 53 43
lowdim_f64 1000 1 9781.2 4854.3 2.01x 1.000 69 54
lowdim_f64 1000 4 8352.3 1736.1 4.81x 1.000 69 54
lowdim_f64 1000 10 8267.2 1290.3 6.41x 1.000 69 54
lowdim_f32 8 1 86.4 22.5 3.84x 0.928 14 20
lowdim_f32 8 4 87.0 11.5 7.54x 0.928 14 20
lowdim_f32 8 10 82.1 10.8 7.62x 0.928 14 20
lowdim_f32 100 1 1260.9 311.5 4.05x 1.037 19 26
lowdim_f32 100 4 1279.7 107.8 11.87x 1.037 19 26
lowdim_f32 100 10 1308.8 81.3 16.09x 1.037 19 26
mid_f32 8 1 52.1 15.3 3.41x 0.990 5 6
mid_f32 8 4 55.3 8.5 6.47x 0.990 5 6
mid_f32 8 10 52.4 7.7 6.78x 0.990 5 6
mid_f32 100 1 794.0 228.5 3.47x 0.994 6 7
mid_f32 100 4 790.3 78.8 10.03x 0.994 6 7
mid_f32 100 10 816.5 68.2 11.98x 0.994 6 7
mid_f32 1000 1 8990.7 2536.3 3.54x 1.001 8 9
mid_f32 1000 4 9162.3 831.6 11.02x 1.001 8 9
mid_f32 1000 10 9214.5 700.5 13.16x 1.001 8 9
mid_f64 8 1 33.1 23.3 1.42x 1.000 11 9
mid_f64 8 4 25.8 12.4 2.08x 1.000 11 9
mid_f64 8 10 23.8 10.7 2.23x 1.000 11 9
mid_f64 100 1 548.5 349.8 1.57x 1.000 15 12
mid_f64 100 4 378.3 124.0 3.05x 1.000 15 12
mid_f64 100 10 357.2 100.7 3.55x 1.000 15 12
mid_f64 1000 1 6338.3 3957.4 1.60x 1.000 20 15
mid_f64 1000 4 4880.1 1392.2 3.51x 1.000 20 15
mid_f64 1000 10 4421.1 1082.8 4.08x 1.000 20 15
far_f32 100 1 862.7 537.6 1.60x 1.007 11 15
far_f32 100 4 867.6 156.3 5.55x 1.007 11 15
far_f32 100 10 860.1 118.6 7.25x 1.007 11 15
far_f64 100 1 426.4 263.9 1.62x 1.000 31 24
far_f64 100 4 388.4 103.1 3.77x 1.000 31 24
far_f64 100 10 382.1 84.2 4.54x 1.000 31 24
sparse_f64 8 1 377.7 73.7 5.12x 1.000 123 124
sparse_f64 8 4 382.3 67.8 5.64x 1.000 123 124
sparse_f64 8 10 382.9 66.9 5.73x 1.000 123 124
sparse_f64 100 1 5133.3 277.4 18.50x 1.000 133 133
sparse_f64 100 4 5130.0 164.9 31.10x 1.000 133 133
sparse_f64 100 10 5175.4 173.3 29.87x 1.000 133 133
small_f64 8 1 1.7 1.5 1.11x 1.000 1 0
small_f64 8 4 1.9 1.4 1.38x 1.000 1 0
small_f64 8 10 2.1 1.4 1.45x 1.000 1 0
small_f64 100 1 22.9 18.5 1.24x 1.000 1 1
small_f64 100 4 23.8 13.7 1.74x 1.000 1 1
small_f64 100 10 23.0 13.1 1.75x 1.000 1 1
bisect_f64 100 1 111.7 118.1 0.95x – 18 18
bisect_f64 100 4 185.5 180.1 1.03x – 18 18
bisect_f64 100 10 234.2 240.8 0.97x – 18 18

20 newsgroups TF-IDF

k threads main (ms) PR (ms) speedup potential PR/main peak MB main peak MB PR
8 1 99.6 33.5 2.98x 1.000 43 43
8 4 98.5 27.8 3.55x 1.000 43 43
8 10 98.6 28.2 3.50x 1.000 43 43
100 1 1283.3 338.3 3.79x 1.000 135 135
100 4 1262.9 215.2 5.87x 1.000 135 135
100 10 1314.7 212.6 6.18x 1.000 135 135

Builds compared

Label Commit What
main 718eedb7af8678255de080d4748d9f67e321ba41 the main commit merged into the PR (b628a8a18f), also its merge-base
PR 0ca7554cb891b7d08f98d84438ba86333e5b4171 PR head, branch kmeans/fast_kmeans_plusplus

@ogrisel ogrisel 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.

LGTM. I think that the performance/readability tradeoff is strongly favorable now. Thanks for the great performance fix.

Comment thread sklearn/cluster/_kmeans.py Resolved
Comment thread sklearn/cluster/_kmeans.py Resolved
@cakedev0

Copy link
Copy Markdown
Member Author

Let's merge then ? 😄

@cakedev0
cakedev0 removed the request for review from jeremiedbb October 28, 2026 11:01
@ogrisel
ogrisel merged commit d685424 into scikit-learn:main Oct 28, 2026
38 checks passed
@github-project-automation github-project-automation Bot moved this from PR waiting for reviews to Done in Labs Oct 28, 2026
@betatim

betatim commented Oct 28, 2026

Copy link
Copy Markdown
Member

Oh but naive Arthur, there can always be more review :D :D

Thanks for this fix! Also say thank you to your agent

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.

Numerical precision of euclidean_distances with float32

4 participants