Skip to content

DictionaryLearning.transform: gemm offers a further 20-28x but is not bit-identical across BLAS implementations #397

Closed

Description

@godofecht

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

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

  1. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    The premise this was rejected on has changed

    #397 records a measured gemm for dictionary_learning_transform worth 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:

    BLAS implementations are allowed to reassociate floating-point operations internally, so cross-backend bit identity is not a valid contract.

    #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, and n_zero_coefs is 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:

    1. How many coefficients flip zero/non-zero across representative shapes, not just the magnitude of the drift.
    2. Whether n_zero_coefs and the sparsity pattern are stable, or vary run to run.
    3. Whether the flips are confined to coefficients already within an ulp of the threshold, in which case the sparsity was arbitrary at that point anyway and the drift is arguably harmless.

    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.

  2. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    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_sgemm is 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:

    path what it is
    A scalar forward, exactly what decomposition.flow ships
    B cblas_sgemm, Accelerate
    C scalar reverse accumulation
    D four interleaved SIMD lanes, tree-combined, the shape of a real gemm micro-kernel k-loop
    E f64 accumulation rounded once to f32, near correctly rounded

    C 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.

    shape (n x p -> k) alpha data coefficients value diffs (C) max abs drift FLIPS (B/C/D/E)
    600 x 16 -> 8 0.1 structured 4,800 3,500 3.58e-7 0 / 0 / 0 / 0
    600 x 16 -> 8 0.1 pseudorandom 4,800 3,509 2.38e-7 0 / 0 / 0 / 0
    4000 x 64 -> 32 0.1 structured 128,000 116,271 5.07e-7 0 / 0 / 0 / 0
    4000 x 64 -> 32 0.1 pseudorandom 128,000 110,712 1.07e-6 0 / 0 / 0 / 0
    2000 x 100 -> 20 0.1 structured 40,000 36,004 4.17e-7 0 / 0 / 0 / 0
    2000 x 100 -> 20 0.1 pseudorandom 40,000 35,591 1.55e-6 0 / 0 / 0 / 0
    512 x 16 -> 8 0.1 pseudorandom 4,096 3,002 3.58e-7 0 / 0 / 0 / 0
    500 x 64 -> 10 0.05 structured 5,000 4,530 3.58e-7 0 / 0 / 0 / 0
    500 x 64 -> 10 0.05 pseudorandom 5,000 4,331 7.15e-7 0 / 0 / 0 / 0
    400 x 16 -> 8 0.9 structured 3,200 2,335 3.58e-7 0 / 0 / 0 / 0
    400 x 16 -> 8 0.9 pseudorandom 3,200 2,347 2.98e-7 0 / 0 / 0 / 0

    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 workload was 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_coefs stable

    Yes, 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:

    fitted model coefficients n_zero scalar n_zero gemm n_zero reverse pattern flips
    300 x 12 -> 6, alpha 0.1 1,800 230 230 230 0
    600 x 16 -> 8, alpha 0.1 4,800 584 584 584 0
    2000 x 32 -> 16, alpha 0.05 32,000 1,946 1,946 1,946 0

    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 alpha exactly when alpha lies 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 of alpha. 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 of alpha. Wider than the issue assumed, still 1.5e-6 wide in absolute terms.

    Empirically, how populated is that window:

    shape coefficients within 1e-6 of alpha within 1e-5 within 1e-4 within 1e-3
    600 x 16 -> 8 (structured) 4,800 0 0 0 26
    4000 x 64 -> 32 (structured) 128,000 0 0 57 701
    4000 x 64 -> 32 (pseudorandom) 128,000 0 3 33 346
    2000 x 100 -> 20 (structured) 40,000 0 0 19 116
    500 x 64 -> 10 (structured) 5,000 0 0 2 22
    400 x 16 -> 8 (structured) 3,200 0 0 0 2

    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 alpha is 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 alpha across (0, 1.0] against 128,000 coefficients, comparing forward against reverse accumulation. That is 2.56e9 coefficient-threshold pairs.

    coefficients per alpha: 128000 | alphas with at least one flip: 146 of 20000
    total flips across the sweep: 190 | worst single alpha: 2 flips at alpha 0.047800
    mean flips per alpha: 0.009500 = 0.0742 per million coefficients
    

    And on 2000 x 32 -> 16:

    coefficients per alpha: 32000 | alphas with at least one flip: 15 of 20000
    total flips across the sweep: 28 | worst single alpha: 2 flips at alpha 0.013950
    mean flips per alpha: 0.001400 = 0.0437 per million coefficients
    

    So flips are real and they are rare: about 0.07 per million coefficients, roughly 1 in 14 million. At a randomly chosen alpha on 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_coefs did 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_transform gets the gemm behind a work threshold of n * 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:

    shape work n*k*p scalar gemm speedup
    4000 x 64 -> 32 8,192,000 10.800 ms 0.292 ms 37.0x
    2000 x 100 -> 20 4,000,000 5.143 ms 0.105 ms 49.0x
    1000 x 32 -> 16 512,000 0.749 ms 0.042 ms 17.8x
    600 x 16 -> 8 76,800 0.117 ms 0.015 ms 7.8x
    512 x 16 -> 8 65,536 0.101 ms 0.013 ms 7.8x
    400 x 16 -> 8 51,200 0.079 ms 0.078 ms 1.01x
    100 x 8 -> 8 6,400 0.010 ms 0.010 ms 1.00x
    100 x 8 -> 4 3,200 0.005 ms 0.005 ms 1.00x

    The 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.

  3. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    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:

    export FLOW_HOST=python
    export FLOW_OPT_LEVEL=0
    export FLOW_LDFLAGS="-lm -lopenblas"
    flow run dl397_flip_harness.flow
    

    On Linux the interesting column is path 1, the real cblas_sgemm against the scalar loop. On macOS path 1 reports zero differences and paths 2, 3 and 4 are the perturbations that stand in for it. FLIPS is the number of coefficients that changed zero/non-zero status. valuediffs is the number whose value changed at all. Those two columns are the whole point: they are expected to be far apart.

    # Issue #397 measurement harness: does a gemm-substituted
    # dictionary_learning_transform change the SPARSITY PATTERN, and if so are the
    # flips confined to coefficients already within an ulp of alpha?
    #
    # Five dot-product paths per (sample, atom):
    #   A  scalar forward   (exactly what lib/scikit/decomposition.flow does today)
    #   B  cblas_sgemm      (the proposed optimization, Accelerate on this host)
    #   C  scalar reverse   (accumulation-order perturbation)
    #   D  four SIMD lanes  (accumulation-order perturbation, gemm-kernel shaped)
    #   E  f64 accumulate then round to f32 (near correctly rounded; any sane BLAS
    #      result lies between A and E, so A-vs-E bounds what a BLAS can do)
    #
    # Reported per shape: zero counts, zero/non-zero FLIP counts, drift magnitude,
    # and for every flip the gap fabs(fabs(dot) - alpha) in ulps of alpha.
    
    import "lib/scikit/scikit.flow"
    
    function dl397_ulp(x: f32) -> f32 {
        let mut a: f32 = x
        if a < 0.0 { a = -a }
        if a < 0.00000000000000000000000000000000000001 {
            return 0.00000000000000000000000000000000000001
        }
        let mut m: f32 = 1.0
        while m * 2.0 <= a { m = m * 2.0 }
        while m > a { m = m / 2.0 }
        return m / 8388608.0
    }
    
    function dl397_absf(x: f32) -> f32 {
        if x < 0.0 { return -x }
        return x
    }
    
    function dl397_iszero(dot: f32, alpha: f32) -> bool {
        let mut a: f32 = dot
        if a < 0.0 { a = -a }
        if a > alpha { return false }
        return true
    }
    
    # Compare path A against path X. Prints flips, drift, and flip-gap statistics.
    function dl397_compare(dotA: ptr<f32>, dotX: ptr<f32>, total: i32, alpha: f32, tag: i32) -> void {
        let ua: f32 = dl397_ulp(alpha)
        let mut flips: i32 = 0
        let mut z_a: i32 = 0
        let mut z_x: i32 = 0
        let mut maxdiff: f32 = 0.0
        let mut maxulp: f32 = 0.0
        let mut maxrel: f32 = 0.0
        let mut flip_maxgap: f32 = 0.0
        let mut flip_gt1: i32 = 0
        let mut flip_gt8: i32 = 0
        let mut flip_gt64: i32 = 0
        let mut flip_gt1024: i32 = 0
        let mut ndiff: i32 = 0
        let mut interval_sum: f64 = 0.0
        let mut maxmag: f32 = 0.0
        let mut t: i32 = 0
        while t < total {
            let a: f32 = dotA[t]
            let x: f32 = dotX[t]
            if dl397_iszero(a, alpha) { z_a = z_a + 1 }
            if dl397_iszero(x, alpha) { z_x = z_x + 1 }
            if a != x { ndiff = ndiff + 1 }
            let d: f32 = dl397_absf(a - x)
            if d > maxdiff { maxdiff = d }
            # A threshold at alpha flips this coefficient exactly when alpha lies
            # between the two magnitudes. Summing those interval widths gives the
            # expected flip count for a threshold placed uniformly at random.
            let iw: f32 = dl397_absf(dl397_absf(a) - dl397_absf(x))
            interval_sum = interval_sum + (iw as f64)
            if dl397_absf(a) > maxmag { maxmag = dl397_absf(a) }
            let mag: f32 = dl397_absf(a)
            if mag > 0.0 {
                let r: f32 = d / mag
                if r > maxrel { maxrel = r }
                let u: f32 = d / dl397_ulp(a)
                if u > maxulp { maxulp = u }
            }
            if dl397_iszero(a, alpha) != dl397_iszero(x, alpha) {
                flips = flips + 1
                let gap: f32 = dl397_absf(mag - alpha)
                if gap > flip_maxgap { flip_maxgap = gap }
                if gap > ua { flip_gt1 = flip_gt1 + 1 }
                if gap > ua * 8.0 { flip_gt8 = flip_gt8 + 1 }
                if gap > ua * 64.0 { flip_gt64 = flip_gt64 + 1 }
                if gap > ua * 1024.0 { flip_gt1024 = flip_gt1024 + 1 }
            }
            t = t + 1
        }
        print("    path ")
        print(tag)
        print(" | zeros_A ")
        print(z_a)
        print(" zeros_X ")
        print(z_x)
        print(" | FLIPS ")
        print(flips)
        print(" | valuediffs ")
        print(ndiff)
        print(" | maxabsdiff ")
        printf("%.12f", maxdiff)
        print(" maxulps ")
        printf("%.2f", maxulp)
        print(" maxrel ")
        printf("%.12f", maxrel)
        println("")
        if maxmag > 0.0 {
            let exp_flips: f64 = interval_sum / (maxmag as f64)
            print("       expected flips for a uniformly random alpha in [0, ")
            printf("%.4f", maxmag)
            print("]: ")
            printf("%.6f", exp_flips)
            print(" of ")
            print(total)
            print(" = ")
            printf("%.4f", exp_flips * 1000000.0 / (total as f64))
            println(" per million coefficients")
        }
        if flips > 0 {
            print("       flip gap max ")
            printf("%.12f", flip_maxgap)
            print(" = ")
            printf("%.2f", flip_maxgap / ua)
            print(" ulp(alpha) | flips beyond 1/8/64/1024 ulp: ")
            print(flip_gt1)
            print(" ")
            print(flip_gt8)
            print(" ")
            print(flip_gt64)
            print(" ")
            print(flip_gt1024)
            println("")
        }
    }
    
    # How many coefficients sit close to the threshold at all. Reported both in
    # ulps of alpha (the flip-risk window) and at wide absolute half-widths, so the
    # local density of coefficients near alpha can be read off and the expected
    # flip count extrapolated to the observed drift.
    function dl397_band(dotA: ptr<f32>, total: i32, alpha: f32) -> void {
        let ua: f32 = dl397_ulp(alpha)
        let mut b1: i32 = 0
        let mut b8: i32 = 0
        let mut b64: i32 = 0
        let mut b1024: i32 = 0
        let mut w6: i32 = 0
        let mut w5: i32 = 0
        let mut w4: i32 = 0
        let mut w3: i32 = 0
        let mut w2: i32 = 0
        let mut t: i32 = 0
        while t < total {
            let gap: f32 = dl397_absf(dl397_absf(dotA[t]) - alpha)
            if gap <= ua { b1 = b1 + 1 }
            if gap <= ua * 8.0 { b8 = b8 + 1 }
            if gap <= ua * 64.0 { b64 = b64 + 1 }
            if gap <= ua * 1024.0 { b1024 = b1024 + 1 }
            if gap <= 0.000001 { w6 = w6 + 1 }
            if gap <= 0.00001 { w5 = w5 + 1 }
            if gap <= 0.0001 { w4 = w4 + 1 }
            if gap <= 0.001 { w3 = w3 + 1 }
            if gap <= 0.01 { w2 = w2 + 1 }
            t = t + 1
        }
        print("    band in ulp(alpha) (<=1/8/64/1024): ")
        print(b1)
        print(" ")
        print(b8)
        print(" ")
        print(b64)
        print(" ")
        print(b1024)
        print(" of ")
        print(total)
        println("")
        print("    band in absolute half-width (1e-6/1e-5/1e-4/1e-3/1e-2): ")
        print(w6)
        print(" ")
        print(w5)
        print(" ")
        print(w4)
        print(" ")
        print(w3)
        print(" ")
        print(w2)
        println("")
        # Local density of coefficients per unit of |dot| around alpha, from the
        # widest window, and the flip count that density predicts for a drift of
        # 0.0000015 (the largest drift any perturbation produced here).
        let dens: f32 = (w2 as f32) / 0.02
        print("    density near alpha ")
        printf("%.1f", dens)
        print(" coeffs per unit |dot| -> predicted flips at drift 0.0000015: ")
        printf("%.4f", dens * 0.0000015)
        println("")
    }
    
    # Coefficients whose zero/non-zero status f32 accumulation cannot resolve:
    # the scalar path's own distance from the correctly rounded value is at least
    # as large as its distance from the threshold. At those positions the shipped
    # scalar answer is already arbitrary.
    function dl397_undetermined(dotA: ptr<f32>, dotE: ptr<f32>, total: i32, alpha: f32) -> void {
        let mut u1: i32 = 0
        let mut u4: i32 = 0
        let mut uq16: i32 = 0
        let mut t: i32 = 0
        while t < total {
            let err: f32 = dl397_absf(dotA[t] - dotE[t])
            let gap: f32 = dl397_absf(dl397_absf(dotA[t]) - alpha)
            if gap <= err { u1 = u1 + 1 }
            if gap <= err * 4.0 { u4 = u4 + 1 }
            if gap <= err * 16.0 { uq16 = uq16 + 1 }
            t = t + 1
        }
        print("    zero/non-zero undetermined in f32 (gap <= 1x/4x/16x own rounding error): ")
        print(u1)
        print(" ")
        print(u4)
        print(" ")
        print(uq16)
        print(" of ")
        print(total)
        println("")
    }
    
    function dl397_run(n: i32, p: i32, k: i32, alpha: f32, seed: i32, mode: i32) -> i32 {
        print("shape n=")
        print(n)
        print(" p=")
        print(p)
        print(" k=")
        print(k)
        print(" alpha=")
        printf("%.4f", alpha)
        print(" mode=")
        print(mode)
        print(" ulp(alpha)=")
        printf("%.12f", dl397_ulp(alpha))
        println("")
    
        let X: Matrix = matrix_new(n, p)
        let xd: ptr<f32> = X.data
        if mode == 0 {
            for i in 0 to n {
                for j in 0 to p {
                    let s: i32 = (i * 37 + j * 17 + seed) % 211
                    let v: f32 = ((s as f32) / 105.0) - 1.0
                    xd[i * p + j] = v
                }
            }
        } else {
            let mut st: i32 = seed * 7919 + 13
            for i in 0 to n {
                for j in 0 to p {
                    st = st * 1103515 + 12345
                    if st < 0 { st = -st }
                    let r: i32 = (st / 7) % 32768
                    let v: f32 = ((r as f32) / 16384.0) - 1.0
                    xd[i * p + j] = v
                }
            }
        }
    
        let dict: ptr<ptr<f32> > = malloc((k as i64) * 8) as ptr<ptr<f32> >
        let mut st2: i32 = seed * 104729 + 7
        for c in 0 to k {
            dict[c] = array_new_f32(p)
            let mut norm: f32 = 0.0
            for j in 0 to p {
                let mut v: f32 = 0.0
                if mode == 0 {
                    let s: i32 = (c * 53 + j * 29 + 7) % 197
                    v = ((s as f32) / 98.0) - 1.0
                } else {
                    st2 = st2 * 1103515 + 12345
                    if st2 < 0 { st2 = -st2 }
                    let r: i32 = (st2 / 11) % 32768
                    v = ((r as f32) / 16384.0) - 1.0
                }
                dict[c][j] = v
                norm = norm + v * v
            }
            norm = sqrt((norm as f64)) as f32
            if norm > 0.0000000001 {
                for j in 0 to p { dict[c][j] = dict[c][j] / norm }
            }
        }
    
        let total: i32 = n * k
        let dotA: ptr<f32> = array_new_f32(total)
        let dotB: ptr<f32> = array_new_f32(total)
        let dotB2: ptr<f32> = array_new_f32(total)
        let dotC: ptr<f32> = array_new_f32(total)
        let dotD: ptr<f32> = array_new_f32(total)
        let dotE: ptr<f32> = array_new_f32(total)
    
        # A: scalar forward, the shipped accumulation order.
        for i in 0 to n {
            let xb: i32 = i * p
            for c in 0 to k {
                let atom: ptr<f32> = dict[c]
                let mut s: f32 = 0.0
                for j in 0 to p {
                    s = s + xd[xb + j] * atom[j]
                }
                dotA[i * k + c] = s
            }
        }
    
        # B: one cblas_sgemm on a packed p x k dictionary.
        let W: Matrix = matrix_new(p, k)
        let wd: ptr<f32> = W.data
        for c in 0 to k {
            let atom: ptr<f32> = dict[c]
            for j in 0 to p {
                wd[j * k + c] = atom[j]
            }
        }
        blas_matmat(xd, wd, dotB, n, k, p, 1.0, 0.0)
        blas_matmat(xd, wd, dotB2, n, k, p, 1.0, 0.0)
    
        # C: scalar reverse accumulation.
        for i in 0 to n {
            let xb: i32 = i * p
            for c in 0 to k {
                let atom: ptr<f32> = dict[c]
                let mut s: f32 = 0.0
                let mut j: i32 = p - 1
                while j >= 0 {
                    s = s + xd[xb + j] * atom[j]
                    j = j - 1
                }
                dotC[i * k + c] = s
            }
        }
    
        # D: four interleaved SIMD lanes, tree-combined. This is the shape of a
        # real gemm micro-kernel k-loop.
        for i in 0 to n {
            let xb: i32 = i * p
            for c in 0 to k {
                let atom: ptr<f32> = dict[c]
                let mut a0: f32 = 0.0
                let mut a1: f32 = 0.0
                let mut a2: f32 = 0.0
                let mut a3: f32 = 0.0
                let mut j: i32 = 0
                while j + 3 < p {
                    a0 = a0 + xd[xb + j] * atom[j]
                    a1 = a1 + xd[xb + j + 1] * atom[j + 1]
                    a2 = a2 + xd[xb + j + 2] * atom[j + 2]
                    a3 = a3 + xd[xb + j + 3] * atom[j + 3]
                    j = j + 4
                }
                while j < p {
                    a0 = a0 + xd[xb + j] * atom[j]
                    j = j + 1
                }
                dotD[i * k + c] = (a0 + a1) + (a2 + a3)
            }
        }
    
        # E: f64 accumulation rounded once to f32.
        for i in 0 to n {
            let xb: i32 = i * p
            for c in 0 to k {
                let atom: ptr<f32> = dict[c]
                let mut s: f64 = 0.0
                for j in 0 to p {
                    s = s + (xd[xb + j] as f64) * (atom[j] as f64)
                }
                dotE[i * k + c] = s as f32
            }
        }
    
        dl397_band(dotA, total, alpha)
        dl397_undetermined(dotA, dotE, total, alpha)
        dl397_compare(dotA, dotB, total, alpha, 1)
        dl397_compare(dotA, dotC, total, alpha, 2)
        dl397_compare(dotA, dotD, total, alpha, 3)
        dl397_compare(dotA, dotE, total, alpha, 4)
    
        # gemm run-to-run reproducibility inside one process.
        let mut bb: i32 = 0
        let mut t: i32 = 0
        while t < total {
            if dotB[t] != dotB2[t] { bb = bb + 1 }
            t = t + 1
        }
        print("    gemm rerun differences in-process: ")
        print(bb)
        println("")
        println("")
    
        array_free_f32(dotA)
        array_free_f32(dotB)
        array_free_f32(dotB2)
        array_free_f32(dotC)
        array_free_f32(dotD)
        array_free_f32(dotE)
        matrix_free(W)
        for c in 0 to k { array_free_f32(dict[c]) }
        free(dict as ptr<void>)
        matrix_free(X)
        return 0
    }
    
    # Empirical flip census: sweep the threshold across the bulk of the coefficient
    # distribution and count, at every alpha, how many coefficients change
    # zero/non-zero status under an accumulation-order perturbation. This measures
    # the flip rate directly instead of predicting it.
    function dl397_sweep(n: i32, p: i32, k: i32, seed: i32, nsweep: i32, amax: f32) -> i32 {
        print("threshold sweep n=")
        print(n)
        print(" p=")
        print(p)
        print(" k=")
        print(k)
        print(" alphas=")
        print(nsweep)
        print(" over (0, ")
        printf("%.2f", amax)
        print("]")
        println("")
    
        let X: Matrix = matrix_new(n, p)
        let xd: ptr<f32> = X.data
        let mut st: i32 = seed * 7919 + 13
        for i in 0 to n {
            for j in 0 to p {
                st = st * 1103515 + 12345
                if st < 0 { st = -st }
                let r: i32 = (st / 7) % 32768
                xd[i * p + j] = ((r as f32) / 16384.0) - 1.0
            }
        }
        let dict: ptr<ptr<f32> > = malloc((k as i64) * 8) as ptr<ptr<f32> >
        let mut st2: i32 = seed * 104729 + 7
        for c in 0 to k {
            dict[c] = array_new_f32(p)
            let mut norm: f32 = 0.0
            for j in 0 to p {
                st2 = st2 * 1103515 + 12345
                if st2 < 0 { st2 = -st2 }
                let r: i32 = (st2 / 11) % 32768
                let v: f32 = ((r as f32) / 16384.0) - 1.0
                dict[c][j] = v
                norm = norm + v * v
            }
            norm = sqrt((norm as f64)) as f32
            if norm > 0.0000000001 {
                for j in 0 to p { dict[c][j] = dict[c][j] / norm }
            }
        }
    
        let total: i32 = n * k
        let magA: ptr<f32> = array_new_f32(total)
        let magC: ptr<f32> = array_new_f32(total)
        for i in 0 to n {
            let xb: i32 = i * p
            for c in 0 to k {
                let atom: ptr<f32> = dict[c]
                let mut s: f32 = 0.0
                for j in 0 to p {
                    s = s + xd[xb + j] * atom[j]
                }
                magA[i * k + c] = dl397_absf(s)
                let mut r2: f32 = 0.0
                let mut j2: i32 = p - 1
                while j2 >= 0 {
                    r2 = r2 + xd[xb + j2] * atom[j2]
                    j2 = j2 - 1
                }
                magC[i * k + c] = dl397_absf(r2)
            }
        }
    
        let step: f32 = amax / (nsweep as f32)
        let mut total_flips: i32 = 0
        let mut alphas_with_flips: i32 = 0
        let mut worst: i32 = 0
        let mut worst_alpha: f32 = 0.0
        let mut m: i32 = 1
        while m <= nsweep {
            let alpha: f32 = (m as f32) * step
            let mut f: i32 = 0
            let mut t: i32 = 0
            while t < total {
                let za: bool = magA[t] <= alpha
                let zc: bool = magC[t] <= alpha
                if za != zc { f = f + 1 }
                t = t + 1
            }
            if f > 0 {
                alphas_with_flips = alphas_with_flips + 1
                total_flips = total_flips + f
                if f > worst {
                    worst = f
                    worst_alpha = alpha
                }
            }
            m = m + 1
        }
    
        print("    coefficients per alpha: ")
        print(total)
        print(" | alphas with at least one flip: ")
        print(alphas_with_flips)
        print(" of ")
        print(nsweep)
        println("")
        print("    total flips across the sweep: ")
        print(total_flips)
        print(" | worst single alpha: ")
        print(worst)
        print(" flips at alpha ")
        printf("%.6f", worst_alpha)
        println("")
        print("    mean flips per alpha: ")
        printf("%.6f", (total_flips as f64) / (nsweep as f64))
        print(" = ")
        printf("%.4f", (total_flips as f64) * 1000000.0 / ((nsweep as f64) * (total as f64)))
        println(" per million coefficients")
        println("")
    
        array_free_f32(magA)
        array_free_f32(magC)
        for c in 0 to k { array_free_f32(dict[c]) }
        free(dict as ptr<void>)
        matrix_free(X)
        return 0
    }
    
    # End-to-end on a real fitted model: compare n_zero_coefs and the sparsity
    # pattern of the shipped dictionary_learning_transform against a gemm
    # projection and against two accumulation-order perturbations of it.
    function dl397_fitted(n: i32, p: i32, k: i32, alpha: f32, seed: i32) -> i32 {
        print("fitted model n=")
        print(n)
        print(" p=")
        print(p)
        print(" k=")
        print(k)
        print(" alpha=")
        printf("%.4f", alpha)
        println("")
    
        let X: Matrix = matrix_new(n, p)
        let xd: ptr<f32> = X.data
        let mut st: i32 = seed * 7919 + 13
        for i in 0 to n {
            for j in 0 to p {
                st = st * 1103515 + 12345
                if st < 0 { st = -st }
                let r: i32 = (st / 7) % 32768
                xd[i * p + j] = ((r as f32) / 16384.0) - 1.0
            }
        }
    
        let model: DictionaryLearning = dictionary_learning_fit(X, k, alpha, 5, 0.0001, 42)
        let T: Matrix = dictionary_learning_transform(model, X)
        let td: ptr<f32> = T.data
        let total: i32 = n * k
    
        let W: Matrix = matrix_new(p, k)
        let wd: ptr<f32> = W.data
        for c in 0 to k {
            let atom: ptr<f32> = model.dictionary[c]
            for j in 0 to p {
                wd[j * k + c] = atom[j]
            }
        }
        let gdot: ptr<f32> = array_new_f32(total)
        blas_matmat(xd, wd, gdot, n, k, p, 1.0, 0.0)
    
        let rdot: ptr<f32> = array_new_f32(total)
        for i in 0 to n {
            let xb: i32 = i * p
            for c in 0 to k {
                let atom: ptr<f32> = model.dictionary[c]
                let mut s: f32 = 0.0
                let mut j: i32 = p - 1
                while j >= 0 {
                    s = s + xd[xb + j] * atom[j]
                    j = j - 1
                }
                rdot[i * k + c] = s
            }
        }
    
        let mut nz_scalar: i32 = 0
        let mut nz_gemm: i32 = 0
        let mut nz_rev: i32 = 0
        let mut flips_gemm: i32 = 0
        let mut flips_rev: i32 = 0
        let mut t: i32 = 0
        while t < total {
            let sz: bool = td[t] == 0.0
            let gz: bool = dl397_iszero(gdot[t], alpha)
            let rz: bool = dl397_iszero(rdot[t], alpha)
            if sz { nz_scalar = nz_scalar + 1 }
            if gz { nz_gemm = nz_gemm + 1 }
            if rz { nz_rev = nz_rev + 1 }
            if sz != gz { flips_gemm = flips_gemm + 1 }
            if sz != rz { flips_rev = flips_rev + 1 }
            t = t + 1
        }
        print("    n_zero_coefs scalar ")
        print(nz_scalar)
        print(" gemm ")
        print(nz_gemm)
        print(" reverse ")
        print(nz_rev)
        print(" of ")
        print(total)
        print(" | pattern flips gemm ")
        print(flips_gemm)
        print(" reverse ")
        print(flips_rev)
        println("")
    
        dl397_band(rdot, total, alpha)
        println("")
    
        array_free_f32(gdot)
        array_free_f32(rdot)
        matrix_free(W)
        matrix_free(T)
        dictionary_learning_free(model)
        matrix_free(X)
        return 0
    }
    
    function main() -> i32 {
        println("=== issue 397 sparsity-flip measurement ===")
        println("path 1 = cblas_sgemm, 2 = reverse sum, 3 = 4-lane SIMD sum, 4 = f64 sum")
        println("")
    
        # Shapes from the issue table and from the existing regression test.
        dl397_run(600, 16, 8, 0.1, 11, 0)
        dl397_run(600, 16, 8, 0.1, 11, 1)
        dl397_run(4000, 64, 32, 0.1, 3, 0)
        dl397_run(4000, 64, 32, 0.1, 3, 1)
        dl397_run(2000, 100, 20, 0.1, 7, 0)
        dl397_run(2000, 100, 20, 0.1, 7, 1)
        dl397_run(512, 16, 8, 0.1, 5, 1)
        dl397_run(500, 64, 10, 0.05, 29, 0)
        dl397_run(500, 64, 10, 0.05, 29, 1)
        dl397_run(400, 16, 8, 0.9, 5, 0)
        dl397_run(400, 16, 8, 0.9, 5, 1)
    
        println("--- threshold sweep ---")
        dl397_sweep(4000, 64, 32, 3, 20000, 1.0)
        dl397_sweep(2000, 32, 16, 23, 20000, 1.0)
    
        println("--- end to end on fitted models ---")
        dl397_fitted(300, 12, 6, 0.1, 17)
        dl397_fitted(600, 16, 8, 0.1, 11)
        dl397_fitted(2000, 32, 16, 0.05, 23)
        println("=== done ===")
        return 0
    }
    
    
  4. godofecht commented on Aug 20, 2026

    @godofecht
    OwnerAuthor

    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 examples passed on Linux with -lm -lopenblas, 42m30s, including tests/test_opt_dictionarylearning_transform.flow with the new checks. That means, under OpenBLAS:

    • the sparsity pattern of the gemm output matches the scalar reference element for element, with no tolerance, on all three above-threshold fixtures (600 x 16 -> 8, 500 x 64 -> 10, 1000 x 32 -> 16) and on the fitted end-to-end case (800 x 20 -> 10),
    • n_zero_coefs on the fitted case matches exactly,
    • coefficient values agree to 1e-5 absolute and 1e-4 relative,
    • no fixture sits within 1e-5 of 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 report failed 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.

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