Repository navigation
Description
Follow-up from #265 (PR #383). Measured, then deliberately NOT shipped. Same shape as #361, with one extra wrinkle that #361 did not hit.
The measurement
dictionary_learning_transform is exactly X @ D^T followed by a soft threshold against alpha. PR #383 shipped the safe half of the optimization, direct row-major indexing in place of matrix_at/matrix_set, worth about 2.1x with bit-identical output.
A prototype that instead packs the dictionary into a d x k buffer and does the whole projection in one cblas_sgemm was built purely to measure it, then reverted. Interleaved before/after runs, min of 5, macOS/Accelerate:
| shape (n x features -> components) | origin/main | PR #383 (scalar) | sgemm prototype |
|---|---|---|---|
| 4000 x 64 -> 32 | 28.150 ms | 13.9 ms | 0.689 ms |
| 2000 x 100 -> 20 | 14.161 ms | 6.5 ms | 0.232 ms |
| 512 x 16 -> 8 | 0.2515 ms | 0.12 ms | 0.0238 ms |
So a further 20-28x on top of what #383 banks, and 41-61x against origin/main. That is the largest single win measured anywhere in decomposition.flow.
Why it was not taken
It is bit-identical under Accelerate and not under OpenBLAS. On macOS, every element of every shape matched the scalar dot products exactly. exact_mismatches=0, maxabsdiff=0.000000000000 on five shapes. That made the prototype look safe.
CI caught it. Run all tests and examples failed on Linux with FAIL: parity mismatch on realistic workload (600 x 16 -> 8), from the element-wise != check in tests/test_opt_dictionarylearning_transform.flow. OpenBLAS blocks and accumulates differently, so the dot products differ in the last ulp.
The soft threshold turns that ulp into a discrete change. The output is
if fabs(dot) > alpha { dot -/+ alpha } else { 0.0 }
A coefficient whose dot product sits within one ulp of alpha flips between exactly zero and a value of order 1e-7 depending on which BLAS is linked. Sparsity is the property this estimator exists to produce, so that is not a drift you can absorb inside a tolerance the way #361's explained_variance drift arguably could be.
What is different from #361
#361 is a single-platform ulp question: does the drift fit inside the declared contract. This one is a cross-platform reproducibility question. benchmarks/parity_contract.json has no DictionaryLearning row, so nothing fails today, but the same estimator would return different sparsity patterns on macOS and Linux from the same input and the same fitted model. Any future contract row for DictionaryLearning would be unpinnable while that is true.
The same hazard applies to every other gemm substitution in the repo whose result feeds a hard comparison, including PR #342's pca_transform if a downstream consumer ever thresholds it. PR #342's own parity check would not have caught this, because it was verified on macOS.
What a follow-up needs to establish
- whether the repo wants bit-identical-across-BLAS as a standing rule, or is willing to declare DictionaryLearning.transform approximate and give the test a tolerance instead of
!= - if the latter, what tolerance, and how the sparsity pattern (not just the coefficient values) is asserted, since that is the part that actually changes
- whether the equivalent risk exists in already-merged or already-open gemm work, notably perf: route PCA.transform through cblas gemm and hoist mean centring #342
- a small-input work threshold if it is taken. The prototype used
n * n_components * n_features >= 65536, the analogue of the KMeans product from perf: KMeans.transform via squared-euclidean expansion and one sgemm #332/perf: KMeans.predict argmin from one sgemm with an exact-tie fallback #341/perf: cut KMeans Lloyd iteration cost without touching its trajectory #345, and measured no regression below it: the scalar path still ran 1.9-2.1x faster thanorigin/main
If the answer is that bit-identity across BLAS implementations is required, this should be closed as won't-do and recorded, so nobody derives the prototype a third time.
Activity
godofecht commentedon Aug 19, 2026
The premise this was rejected on has changed
#397 records a measured gemm for
dictionary_learning_transformworth 20-28x, reverted because it was not bit-identical under OpenBLAS on Linux while matching exactly under macOS Accelerate.PR #377 settled that question the other way. From commit
686e0f4:#377 kept its 14.7x BLAS optimization and changed its test to assert tight numerical equivalence (absolute 1e-5, relative 1e-4) instead of exact equality. That is the precedent, and I have reopened #361 on the same basis.
Why this issue is NOT simply unblocked by that
#361 and #397 look like the same situation and are not. The difference is what the drift feeds into.
PCA's outputs are continuous: a few float32 ulps on an eigenvalue stay a few ulps, and a tolerance-based contract captures that honestly.
DictionaryLearning applies a soft threshold against
alpha. A last-ulp difference flips a coefficient between exactly zero and about 1e-7, which changes the sparsity pattern, not just the digits. That is a discontinuity: the estimator's entire purpose is which coefficients are zero, andn_zero_coefsis a reported quantity. A tolerance on coefficient values would pass while the sparsity structure differs, so the tolerance contract would be measuring the wrong thing here.What would actually settle it
Someone should determine, on Linux with OpenBLAS:
n_zero_coefsand the sparsity pattern are stable, or vary run to run.If (3) holds the optimization is probably shippable with a sparsity-pattern assertion rather than a value tolerance. If flips are widespread, it is not, and 20-28x is not worth an estimator whose output structure depends on the BLAS vendor.
Leaving this open rather than reopening it as ready. The contract change removes the original objection but does not answer the sparsity question, and that question is the real one.
godofecht commentedon Aug 19, 2026
Measured: the sparsity question, with counts
I measured the three things the previous comment asked for. Short version: the sparsity pattern is stable, the flips that are possible at all are confined to coefficients sitting inside the dot product's own rounding error of
alpha, and the rate is about 1 flip per 14 million coefficients. The CI failure that killed the prototype was value drift, not a sparsity change.The limitation, stated first
This is macOS with Accelerate. Under Accelerate
cblas_sgemmis bit-identical to the scalar dot products, exactly as #397 originally reported, so a direct gemm-vs-scalar comparison here measures nothing. I confirmed that first (0 differing values out of 366,096 coefficients across 11 shape/data combinations) and then perturbed the accumulation order deliberately to stand in for what a different BLAS does:decomposition.flowshipscblas_sgemm, AccelerateC and D are simulations of reassociation, not OpenBLAS. E is useful as a bound: any sane BLAS result lies between A and E, so A-vs-E brackets what reassociation can do. The harness is posted in full in the next comment so anyone with a Linux box can run the same measurement against the real thing, unchanged.
1. How many coefficients flip
Zero. On every shape, under every perturbation.
Read the two middle columns together. On 600 x 16 -> 8, the shape whose element-wise
!=check failed on Linux, 3,500 of 4,800 coefficient values move when the accumulation order changes, and 0 coefficients change zero/non-zero status. Between 73% and 91% of values differ on every shape, with 0 flips throughout.That is the answer to what CI actually caught.
FAIL: parity mismatch on realistic workloadwas the!=reporting a last-ulp value difference. It was not reporting a sparsity change, and the old test could not have told the two apart.2. Is
n_zero_coefsstableYes, on three axes.
Run to run inside one process: the gemm was run twice per shape on the same inputs and compared bit for bit. 0 differences, all 11 shapes.
Run to run across processes: the whole harness binary was run twice. Output byte-identical.
Between the scalar path and the gemm, end to end on actually fitted models:
3. Are the flips threshold-adjacent
This is the question that matters, and the answer is yes, structurally and then empirically.
Structurally: a coefficient flips at threshold
alphaexactly whenalphalies between|dot_A|and|dot_X|. So every flip that can happen is confined to a coefficient whose distance from the threshold is at most the drift itself. It is not possible for a reassociating BLAS to flip a coefficient that is comfortably clear ofalpha. The only way that happens is if the drift is not reassociation, and the drift here is 2.4e-7 to 1.5e-6 absolute, which is the accumulated f32 rounding error of a length 16 to 100 dot product.One correction to the framing in the issue: the flip window is not one ulp.
ulp(0.1)is 7.45e-9, and the measured drift reaches 1.5e-6, so the window is about 200 ulps ofalpha. Wider than the issue assumed, still 1.5e-6 wide in absolute terms.Empirically, how populated is that window:
Nothing lands within 1e-6 of the threshold on any shape. The drift is 1.5e-6 at worst. That is why the flip count is 0 rather than lucky.
A stronger version of the same check: count coefficients whose distance from
alphais smaller than the scalar path's own distance from the correctly rounded (f64) value, meaning positions where f32 arithmetic cannot determine the zero/non-zero answer at all, whatever BLAS you use. That count is 0 on every shape, and still 0 at 4x and 16x the scalar path's own error.The flip rate, measured rather than inferred
0 observed flips is a weak statement on its own, so I swept the threshold instead of fixing it. On the 4000 x 64 -> 32 pseudorandom set, 20,000 values of
alphaacross (0, 1.0] against 128,000 coefficients, comparing forward against reverse accumulation. That is 2.56e9 coefficient-threshold pairs.And on 2000 x 32 -> 16:
So flips are real and they are rare: about 0.07 per million coefficients, roughly 1 in 14 million. At a randomly chosen
alphaon a 128,000 coefficient transform you expect 0.0095 flipped coefficients, and the worst threshold placement found anywhere in 40,000 tried flipped 2. Every one of those 190 flips was, necessarily, a coefficient within 1.5e-6 of the threshold, where the scalar path's own answer was already arbitrary.Recommendation: ship it, with a sparsity-pattern assertion
The condition set out in the last comment holds. Flips are confined to threshold-adjacent coefficients, the pattern is stable run to run and path to path, and
n_zero_coefsdid not move on any fitted model. A tolerance on values alone would indeed have been the wrong contract, so the test does not use one alone.PR #442 does three things.
dictionary_learning_transformgets the gemm behind a work threshold ofn * n_components * n_features >= 65536, the KMeans product form from #332/#341/#345. Below it the original scalar kernel runs unchanged and stays bit-identical, and skips the OpenBLAS thread dispatch that would otherwise cost more than the loop it replaced.The test asserts the sparsity pattern element for element with no tolerance, on both paths. Values get the 1e-5 absolute / 1e-4 relative tolerance from #377, but only after the pattern check has passed.
The test also asserts that no fixture parks a coefficient within 1e-5 of
alpha. That third check is what makes the first one safe on a BLAS this machine cannot run: the pattern assertion is only meaningful because the fixtures keep at least a 7x margin over the largest drift measured. It is not decoration. One candidate fixture I added (1000 x 32 -> 16 at alpha 0.1) failed it with a coefficient 9.76e-6 from the threshold, which is inside the margin even though it did not flip, so I moved that fixture to alpha 0.08 where the margin is 3.2e-4. If a future edit drifts a fixture onto the threshold, the test says so instead of turning into a coin flip on the BLAS vendor.Timings on this machine, min of 7, interleaved,
FLOW_OPT_LEVEL=0, load average 5.06 so treat these as indicative:n*k*pThe three rows below the threshold are the same code on both sides, so 1.00x is the expected reading and confirms the gate.
What this does not settle
I could not run OpenBLAS. Everything above says a reassociating BLAS cannot move the sparsity pattern on these fixtures because nothing sits close enough to the threshold, and the margin check enforces that property rather than assuming it. Linux CI is the thing that actually tests it, and if it fails there the margin check will say whether the cause was a fixture sitting on the threshold or a drift far larger than reassociation explains, which would be a genuinely different bug.
The wider point from the original issue still stands and is worth recording: the hazard is specific to a BLAS result feeding a hard comparison, and the defence is a margin between the compared quantity and the threshold, not bit identity.
pca_transform(#342) has no threshold downstream today. If one is ever added, the same margin check belongs with it.godofecht commentedon Aug 19, 2026
The measurement harness, in full, so the same run can be done against OpenBLAS without reconstructing anything. It is self-contained apart from
import "lib/scikit/scikit.flow". Drop it at the repo root and run it:On Linux the interesting column is
path 1, the realcblas_sgemmagainst the scalar loop. On macOSpath 1reports zero differences and paths 2, 3 and 4 are the perturbations that stand in for it.FLIPSis the number of coefficients that changed zero/non-zero status.valuediffsis the number whose value changed at all. Those two columns are the whole point: they are expected to be far apart.godofecht commentedon Aug 20, 2026
The OpenBLAS result
The measurement above was macOS with Accelerate and said so. Linux CI has now run the real thing on PR #442, and it answers the question directly.
Run all tests and examplespassed on Linux with-lm -lopenblas, 42m30s, includingtests/test_opt_dictionarylearning_transform.flowwith the new checks. That means, under OpenBLAS:n_zero_coefson the fitted case matches exactly,alpha.The same file with the old element-wise
!=check is what failed on Linux and caused the original revert. Both statements are now on the record together: the values differ under OpenBLAS, and the sparsity pattern does not.All eight checks on #442 are green.
Scaled benchmark reportfailed once on('KernelSVC_RBF', 100, 32) fit_ms: 11.58 ms > allowed 9.21 ms, a row this PR does not touch, and passed on rerun in 1m54s, so it was runner noise on a 100 row fit.That closes the question the issue was left open on. Cross-BLAS bit identity is not the property this estimator needs. The property it needs is a margin between the projection and the threshold, and the test now asserts that margin rather than assuming it.