Repository navigation
PRF Speed up k-means++ initialization - #35140
Conversation
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]>
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]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
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 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
MachineApple Silicon (arm64), 10 cores ( DatasetsAll synthetic and generated once. "Blobs" means
Method
ResultsSpeedup = main time ÷ PR time; above 1 means the PR is faster.
Toolchain versionsBuild toolchain, from the 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()}") |
|
@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]>
All the CPUs (or 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). |
big +1 for usefulness but I propose to collectively take the habit of putting this kind of long reports inside |
|
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 |
|
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. |
|
It seems like it changed nothing :-/ Main sweep: main vs PR
|
| 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.Twith sparse candidates.
ConvertingX.Tto 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 onsparse_f64and 17M onsparse_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]>
|
@betatim Thanks for re-running! Your AI analysis is right: main multiplies the sparse candidates with I pushed a76e618, which uses the sparsity of the candidates like main does. X is converted to CSC once per Could you re-run the sparse cases on your Mac? 🙏
I'd rather avoid two code paths, and with this change it shouldn't be needed. With many threads and a small 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 😜 |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
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]>
…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]>
|
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 |
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
ogrisel
left a comment
There was a problem hiding this comment.
This is already much easier to read. Here are some more suggestions to use more consistent/explicit variable names.
| 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` |
There was a problem hiding this comment.
I think j should be renamed to trial_idx and i to sample_idx, both in the docstring and in the code.
There was a problem hiding this comment.
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.|
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...). |
…gorithm Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Re-run of the benchmarks on my macbook using the commit 0ca7554. Looks like you fixed it!
Full results table
20 newsgroups TF-IDF
Builds compared
|
Co-authored-by: Olivier Grisel <[email protected]>
|
Let's merge then ? 😄 |
|
Oh but naive Arthur, there can always be more review :D :D Thanks for this fix! Also say thank you to your agent |
Reference Issues/PRs
I found this while looking at why scikit-learn-intelex is much faster than scikit-learn on
KMeansin scikit-learn-benchmarks: on an Intel Xeon 6787P (2 x 86 cores), the k-means++ init takes 75-97% of the time ofKMeans.fit.Related to #17334.
What does this implement/fix? Explain your changes.
Current implementation is slow for two reasons:
_euclidean_distancesgoes 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.This PR evaluates the candidates of a step in a single OpenMP kernel (
_kmeans_plusplus_trials_dense). It introduces two units of work:blocks: each thread processes exactly one blockchunks: it's the parallel reduction unit, and it also allows a trick in the candidates sampling which avoidsnp.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_originfails 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.Tat every step, inX[candidate_ids] @ X.T).Some notes:
random_state, the selected centers are not the same as on main, because the cumulative sums used for sampling are different.kmeans_plusplusnow 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).AI usage disclosure
I used AI assistance for:
The main things I trust:
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.