Skip to content

Make KMeans trajectory semantics sklearn-compatible and retire the equivalence exception #203

Closed

Description

@godofecht

Parent: #202

Problem

Digits KMeans is currently headline-eligible only through a dedicated approximate-equivalence contract. The strict diagnostic still records a substantial ARI disparity because Flow and sklearn diverge before Lloyd iteration begins.

The semantic audit already identifies concrete differences:

  • sklearn uses NumPy RandomState/MT19937 plus greedy k-means++ local trials
  • Flow uses xorshift32 plus one weighted candidate per center
  • sklearn convergence uses total squared center shift against its effective tolerance
  • Flow uses maximum absolute coordinate shift

Eligibility must not make those differences disappear.

Work

Implement sklearn-compatible seeded initialization for the canonical path, including greedy k-means++ local trials and matching random-state consumption order.

Align convergence-statistic and effective-tolerance semantics.

Audit empty-cluster relocation, final reassignment and n_init behavior under identical seeds.

Persist initial centers, per-iteration inertia/center movement and final centers modulo permutation for both implementations.

Acceptance criteria

The first-divergence audit moves beyond initialization or disappears entirely.

Digits KMeans passes the normal strict clustering parity contract without finalize_kmeans_parity.py promoting a failed strict diagnostic.

The special equivalence exception can be removed or reduced to a documented intentional API difference.

Pages continues to show any residual ARI/inertia/model-state disparity even after strict parity succeeds.

Activity

  1. godofecht commented on Aug 18, 2026

    @godofecht
    OwnerAuthor

    Triage: still open, no implementation work has landed

    Verified against the frozen canonical evidence on main (c1e01df).

    The equivalence exception is still in place and still load-bearing:

    • benchmarks/kmeans_equivalence_contract.json still exists with ari_absolute_tolerance: 0.07 and inertia_relative_tolerance: 0.10, and its stated rationale is unchanged: sklearn consumes NumPy RandomState/MT19937 with greedy local trials while Flow uses xorshift32 with one candidate per center.
    • benchmarks/finalize_kmeans_parity.py still promotes the row, and it still hard-requires audit.get("first_divergence_stage") == "initialization", raising SystemExit otherwise. The gate is built on the divergence persisting.
    • benchmarks/kmeans_semantics_audit.json still records "first_divergence_stage": "initialization" with first_divergent_center: 0. sklearn picks initial indices [538, 223, 1234, 1174, 267, 878, 549, 740, 112, 1363]; Flow picks [258, 473, 325, 993, 1078, 949, 1043, 191, ...]. They diverge at the very first center.
    • benchmarks/disparity_report.json still shows digits KMeans with strict_diagnostic_status: "not parity verified" against final_parity_status: "approximately equivalent", ARI absolute difference 0.06368012500000003. It is the only row in the report producing strict_final_status_disagreements: 1.
    • .github/workflows/remaining-issues.yml still runs audit_kmeans_semantics.py then finalize_kmeans_parity.py and asserts strict_final_status_disagreements >= 1, so CI currently requires the exception to remain.

    Partial credit on the persistence half of the acceptance criteria: PR #331 made the KMeans inertia and iteration-count deltas survive the failed strict gate, so digits KMeans now carries inertia_relative_diff (about 0.1044%) and n_iter_abs_diff (22 sklearn vs 19 Flow) in model_state_diagnostics.

    Remaining work: implement sklearn-compatible seeded k-means++ in the canonical Flow path (MT19937-equivalent random-state consumption order, greedy local trials with 2 + log(k) candidates and the best-inertia pick), switch the convergence statistic from maximum absolute coordinate shift to total squared center shift against sklearn's effective tolerance, audit empty-cluster relocation and n_init under identical seeds, then remove kmeans_equivalence_contract.json and finalize_kmeans_parity.py from the CI path along with the strict_final_status_disagreements >= 1 assertion.

  2. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    Diagnosis: it is the initialization, and only the initialization

    I built two numpy models: one that reproduces Flow's kmeans_fit_plus_plus exactly, and one that reproduces sklearn 1.9's KMeans exactly. Both check out against the committed evidence before any ablation:

    model digits ARI digits inertia n_iter iris ARI iris inertia
    Flow model 0.464646089 55293.914 19 0.548888889 110.19525
    flow_results_v2.txt 0.464646101 55293.898 19 0.548888862 110.195274
    sklearn model 0.528326226 55236.1953 22 0.548888889 110.19525
    sklearn_results_v2.txt 0.528326226 55236.1836 22 0.548888889 110.195267

    The sklearn model also reproduces the audit's recorded first-init indices [538, 223, 1234, 1174, 267, 878, 549, 740, 112, 1363] and produces train labels identical to sklearn.cluster.KMeans up to permutation.

    Ablation over the four candidate causes

    Each row changes exactly one thing against the Flow baseline, digits, random_state=42, n_init=10:

    configuration digits ARI digits inertia n_iter winning init
    Flow baseline 0.464646089 55293.914 19 9
    + sklearn init only 0.528326226 55236.195 22 7
    + sklearn convergence statistic only 0.464646089 55293.914 19 9
    + sklearn n_init selection rule only 0.464646089 55293.914 19 9
    + sklearn mean-centering of X only 0.464646089 55293.914 19 9
    full sklearn 0.528326226 55236.195 22 7

    Swapping the initializer alone, while keeping Flow's max-absolute-coordinate-shift convergence test, Flow's pre-update inertia and Flow's plain best-inertia n_init selection, lands on sklearn's answer to the last printed digit. The convergence criterion, the selection rule and the mean-centering each change nothing on either dataset.

    So of the four leads:

    1. k-means++ initialization: this is the whole gap.

    2. RNG draw order: part of the same cause, and it is not separable from the greedy trials. Neither ingredient alone reaches sklearn's result:

      initializer digits ARI inertia
      xorshift32 + 1 candidate (current Flow) 0.464646089 55293.914
      xorshift32 + greedy 2 + log(k) trials 0.476867539 55418.656
      MT19937 + 1 candidate 0.550946889 55433.906
      MT19937 + greedy trials 0.528326226 55236.195

      Note the third row: MT19937 with a single candidate scores a higher ARI than sklearn, on a worse objective. That is the trap this issue warns about. The goal is sklearn's trajectory, not the best ARI.

    3. Empty-cluster relocation: not implicated. Instrumented across all 20 canonical runs (10 inits x 2 datasets, both implementations), the empty-cluster branch never fires. The policies do differ (sklearn moves the n_empty distinct farthest points and debits them from their old cluster; Flow re-picks the single farthest point per empty cluster and leaves it in its old cluster), but on the canonical fixtures it is dead code.

    4. Convergence criterion: not implicated on these fixtures. Flow compares max |coordinate shift| against the raw tol=0.001; sklearn compares the summed squared centre shift against mean(var(X)) * tol (0.0009531 on digits), plus a strict label-equality short circuit and a final E-step. Substituting sklearn's version changes neither dataset. Related: Flow reports the inertia of the assignment made before the last centroid update, whereas sklearn reports the inertia of the final centres against final labels. On digits that distinction is worth 0.000 in f32 for all 10 inits, measured; it is not the source of the 0.104% inertia gap either. That gap is simply a different local minimum.

    The singleton cluster is explained

    X_train row 191 is a genuine outlier with L2 norm 46.971, the largest in the standardized training set (next largest 41.68, then 38.66). It is extreme because StandardScaler amplifies three near-constant pixel columns: features 48, 40 and 31 are nonzero in only 3, 7 and 4 of the 1437 training rows, and row 191 is nonzero in all three, giving standardized values 35.24, 21.01 and 18.93.

    sklearn's winning run (init 7) seeds a centre on row 191 as its 10th centre. Lloyd keeps that cluster a singleton, so it contributes 0 to the inertia; absorbing row 191 into any other cluster would cost roughly 46.97^2 = 2206. sklearn's center_l2_norms_sorted therefore ends [..., 11.670, 46.971] with sizes [349, 222, 151, 147, 144, 142, 130, 123, 28, 1].

    Flow's current initializer does pick row 191 sometimes: inits 0, 1 and 4 contain it and all end with maxnorm = 46.971 and a singleton. They just lose the n_init contest, at 56561, 57755 and 57014 against the winner's 55293.9. So the singleton is not something Flow structurally cannot produce. Flow's ten k-means++ draws are simply worse as a set, because a single D^2 sample per centre has much higher variance than the best of 2 + log(k) = 4 samples.

    The port is numerically safe

    The worry with matching an RNG-driven searchsorted is that a draw lands next to a cumulative-weight boundary and a different rounding picks a different candidate. The tightest of the 360 digits draws has a relative margin of 3.9e-7, below the 1.7e-4 error scale of a 1437-term float32 sequential cumsum, so it is a fair worry.

    Measured instead of assumed. All 12 combinations of {potential in f32, f64} x {cumsum in f32, f64} x {distances direct-f32, direct-f64, expanded ||x||^2 + ||c||^2 - 2x.c} land on ARI 0.528326226, inertia 55236.1953, n_iter 22, winning init 7. Injecting relative noise into the cumulative weights, the answer is stable to 1e-5 and only breaks at 1e-4. A Flow port in float32 has plenty of headroom.

    Plan

    Implement MT19937 plus sklearn's _kmeans_plusplus (one random_sample() for the first centre through the p-weighted choice path, then 2 + int(log(k)) uniform() draws per subsequent centre with the best-potential pick), consuming one RandomState(42) stream across all n_init restarts as sklearn does. Convergence, empty-cluster policy and selection stay as they are, since they are measurably not the cause; I will note the remaining divergences in the audit rather than pretend they are gone.

    Expected canonical movement: digits ARI 0.464646101 -> 0.528326226 (sklearn 0.528326226, so the row passes the normal 0.05 gate with a diff near 0), digits inertia 55293.90 -> 55236.20, n_iter 19 -> 22. Iris ARI and inertia unchanged at 0.548888862 / 110.195274; iris n_iter moves 7 -> 4, matching sklearn's 4.

    Numbers to follow once it is running in Flow.

  3. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    Implemented in #428.

    Digits ARI 0.464646101 -> 0.528326213 against sklearn's 0.528326226, inertia 55293.902344 -> 55236.183594 against 55236.1836, n_iter 19 -> 22 against 22. The largest centre norm moves from 11.837 to 46.971 with a singleton cluster, matching sklearn's model state. Held-out label agreement with sklearn after optimal cluster matching goes from 0.791667 to 1.000000 on digits and stays at 1.000000 on iris. Iris ARI and inertia are unchanged; its n_iter moves 7 -> 4, matching sklearn.

    kmeans_equivalence_contract.json and finalize_kmeans_parity.py are deleted, the equivalence-gate step is out of remaining-issues.yml, and the strict_final_status_disagreements >= 1 assertion is now == 0 with a new rows_with_semantic_difference > 0 check so the residual differences still have to be on the record. The audit's first_divergence_stage is none and it now verifies all ten restarts rather than one.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions