Skip to content

Close the Digits KernelSVC quality gap and isolate the libsvm performance deficit #206

Closed

Description

@godofecht

Parent: #202

Problem

The canonical Digits KernelSVC row remains approximately equivalent rather than tightly matched, with an accuracy disparity of roughly 0.00278. It is also one of the clearest performance losses because sklearn delegates to mature libsvm while Flow currently uses a different native implementation path.

Work

Audit and align the canonical configuration and learned state:

  • gamma calculation and kernel parameterization
  • shrinking behavior
  • stopping tolerance / max-iteration semantics
  • class ordering and decision-function shape
  • support-vector indices and counts
  • dual coefficients and intercepts
  • prediction tie-breaking

Profile kernel construction, training loop/solver, and prediction separately.

Add an optional comparison path that calls the same libsvm backend from Flow or otherwise isolates orchestration overhead from solver quality.

Acceptance criteria

The predictive disparity is reduced from the current ~0.00278 without widening the parity contract.

Model-state diagnostics explain any remaining support-vector/dual-coefficient differences.

The benchmark report distinguishes solver/kernel cost from Flow orchestration cost, so the external-native gap is actionable rather than a single end-to-end number.

Activity

  1. godofecht commented on Aug 18, 2026

    @godofecht
    OwnerAuthor

    Triage: still open, nothing has landed

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

    • benchmarks/disparity_report.json, digits KernelSVC_RBF accuracy: score_abs_diff is 0.0027777669999999866, unchanged from the ~0.00278 figure this issue was filed against. Both statuses are "approximately equivalent".
    • The performance deficit is the worst on the classification side of the canonical set. runtime_ratio_sklearn_over_flow is 0.0638, so Flow is roughly 15.7x slower than sklearn's libsvm path on this row. Iris KernelSVC_RBF is 0.1391, about 7.2x slower.
    • model_state_diagnostics for both KernelSVC rows is empty {}. No support-vector indices or counts, dual coefficients, intercepts, gamma value or decision-function shape are persisted by either implementation. benchmarks/bench_flow_v2.flow emits DETAIL| records only for KMeans and PCA.
    • benchmarks/sklearn_execution_inventory.csv already classifies SVC.fit as external-native-bound:libsvm for canonical-headline:digits,iris, so the architectural attribution exists. The benchmark still reports a single end-to-end number, with no split between kernel construction, solver loop and prediction.
    • The only related merged work is the local commit 45cb65c "perf: SMO solver for KernelSVC, 25x faster on digits", which predates this issue and is already reflected in the current 0.0638 ratio.

    Remaining work: emit gamma, class ordering, support-vector indices and counts, dual coefficients and intercepts as DETAIL| records from both implementations and compare them under the required index alignment; audit shrinking, stopping tolerance and max-iteration semantics against libsvm; add per-phase timing (kernel construction, training loop, prediction) so the report separates solver cost from Flow orchestration cost; optionally add a comparison path that drives libsvm from Flow to isolate solver quality from orchestration overhead.

  2. godofecht commented on Aug 18, 2026

    @godofecht
    OwnerAuthor

    #207 is partly done for this row. PR #402 adds SVM learned-state emission on both
    sides. It does not add per-phase timing; see below.

    What you can now read straight out of disparity_report.json

    Both implementations are one-vs-one, so the 45 Digits pairs line up. #402 sorts
    Flow's pairs by class label, since Flow discovers classes in the order they
    appear in y while libsvm sorts them. pair_class_a, pair_class_b and
    pair_train_sizes all match exactly, which confirms the alignment.

    Digits KernelSVC_RBF, score_abs_diff 0.0027777669999999866 on the run below:

    Field Flow sklearn delta
    gamma 0.00100000005 0.001 5e-08 relative
    C 1 1 0
    n_pairs 45 45 0
    n_support_total 4431 4810 379 absolute, 7.88% relative
    n_support_per_pair max 20 absolute, 20.2% relative
    n_bounded_support_per_pair max 11 absolute
    dual_coef_abs_sum_per_pair max 14.38 absolute, 15.9% relative
    intercept_per_pair max 1.456 absolute

    Iris is much closer: n_support_total 54 against 58, intercept_per_pair max
    absolute difference 0.00828, dual_coef_abs_sum_per_pair max relative difference
    1.4%.

    The interesting one is n_bounded_support_per_pair, the count of duals sitting
    at the box bound C. On Digits, most pairs have 80 to 95% of their support vectors
    pinned at C on both sides. That is what a solver looks like when it stops at its
    iteration cap rather than at its KKT tolerance, and Flow's max_iter is 1000 for
    this row. If the Digits gap turns out to be a truncation artifact rather than a
    formulation difference, that field is where it will show.

    What is still missing for this issue

    • Per-phase timing. Separating kernel-matrix construction from SMO iteration
      needs timers inside svm.flow. That file is the known victim of compiler bug
      Config comparator flags identical settings expressed in different vocabularies #469 ("large programs produce incorrect code for certain functions;
      LinearSVC accuracy drops from 0.833 to 0.033 when surrounding code grows"), and
      the canonical RESULT| timings must not move. feat: learned-state diagnostics for every canonical benchmark row (3/19 -> 19/19) #402 deliberately touches
      nothing under lib/scikit/, so this was not attempted. It probably wants a
      standalone harness outside the canonical benchmark rather than instrumentation
      inside the timed path.
    • Individual support vectors. Only per-pair counts are emitted, not which
      training rows became support vectors. Flow's KernelSVCMulti stores each pair's
      own X_train subset rather than indices into the shared training matrix, so
      recovering global indices needs either a struct change or a row match.
    • Individual dual coefficients. Emitted as a per-pair absolute sum. The full
      set would be ~4400 values per side for Digits.
    • Support-vector overlap between the two implementations. With 4431 against
      4810 support vectors, the useful question is how many are the same rows.
      Nothing emitted answers that yet; it needs the point above first.
    • The gap itself. feat: learned-state diagnostics for every canonical benchmark row (3/19 -> 19/19) #402 is instrumentation only and changes no fitted numeric.

    Note that the Digits KernelSVC score differs between environments: the frozen CI
    evidence has Flow at 0.947222233 against sklearn 0.95, while a local macOS
    Accelerate build gives Flow 0.938888907. Worth pinning down which BLAS the
    committed number came from before drawing conclusions from the absolute gap.

    Reproducing

    FLOW_HEADLINE_COMMAND="flow run benchmarks/bench_flow_v2.flow" \
      python benchmarks/run_headline.py --repeats 3
    cp benchmarks/headline_summary.json benchmarks/headline_result_v2.json
    python benchmarks/generate_disparity_report.py
  3. godofecht commented on Aug 18, 2026

    @godofecht
    OwnerAuthor

    Per-phase attribution of the Digits KernelSVC fit, and the iteration cap

    Partial post, real numbers. Measured with a standalone harness that copies the
    solver out of lib/scikit/svm.flow under b206_ prefixes and adds timers, so
    lib/scikit/svm.flow is untouched and no canonical RESULT| line moves. This
    sidesteps compiler bug #469 as recommended in the previous comment.

    Machine: macOS arm64, FLOW_HOST=python FLOW_OPT_LEVEL=0 FLOW_LDFLAGS="-framework Accelerate".
    Workload: benchmarks/split_digits.bin, StandardScaler, 1437 train / 360 test / 64 features,
    gamma 0.001, C 1.0, max_iter 1000. Identical to the canonical row.

    Sanity check on the copy: library kernel_svc_multi_fit best of 3 is 608.455 ms
    at accuracy 0.938888907; the instrumented copy is 632.903 ms at the same
    accuracy 0.938888907. Instrumentation costs 4.0%.

    Where the fit time goes

    Phase ms Share
    SMO solver loop 608.714 96.2%
    Full RBF kernel build (sgemm + exp, 1437x1437 in f64) 9.447 1.5%
    Per-pair Q gather from the full kernel 9.442 1.5%
    Per-pair training subset extraction 4.445 0.7%
    Bias from free SVs 0.294 0.05%
    Model tail (alpha f64->f32, matrix_copy) 0.383 0.06%
    Solver setup allocations 0.023 <0.01%
    Class discovery 0.031 <0.01%
    Frees 0.016 <0.01%

    Is the deficit kernel math or Flow orchestration?

    Neither.

    Kernel evaluation is 1.5% of the fit. The existing code already does the right
    thing: it builds the full 1437x1437 kernel once via cblas_sgemm plus a vectorised
    exp, then slices it per pair. 2.06M kernel entries in 9.4 ms.

    Orchestration, allocation and setup together are 2.3% (subset extraction, Q
    gather, model tail, frees, class discovery). There is nothing worth reclaiming there.
    Even deleting all of it entirely would move the row from 0.0433 to 0.0443 on the
    local fit ratio.

    The deficit is 96% solver iteration, and it is not solver math that libsvm also
    has to do. It is redundant work inside Flow's working-set selection:

    Counter Value
    _smo_examine calls 332,245
    _smo_examine calls that found a KKT violation 322,336
    best-j scan element visits 92,639,427
    _smo_step calls 17,001,738
    _smo_step calls that made progress 266,823
    gradient-update element visits 76,682,555
    fallback non-bound scan visits 26,702,793
    fallback full scan visits 15,976,688

    98.4% of the 17.0M _smo_step calls do nothing. When the max |E1 - E2|
    heuristic in _smo_examine picks a best_j whose step is degenerate,
    the function falls through to a full O(n) scan over non-bound examples and then a
    second full O(n) scan over all examples, invoking _smo_step on each until one
    returns true. At 608.7 ms over 17.0M step calls that is ~36 ns per call, and the
    step body does three strided f64 loads from a 287x287 Q before it can decide to
    bail.

    Flow is stopping on its iteration cap. libsvm is not.

    This is the part that reframes the issue.

    Flow's cap for this row is max_iter = 1000 and its tolerance is tol = 0.001,
    hardcoded in _kernel_svc_smo_precomputed. 44 of the 45 pairs exhaust it. Only
    pair 14 stops earlier, at 408.

    libsvm on the identical split, sklearn 1.9.0:

    n_iter_ per OvO pair: [52, 52, 63, 88, 74, 57, 53, 91, 108, 89, 87, 90, 82, 72, 80,
                           103, 98, 99, 91, 84, 72, 89, 116, 103, 66, 95, 65, 77, 106,
                           116, 71, 87, 79, 106, 72, 63, 89, 107, 108, 51, 96, 65, 85,
                           70, 108]
    

    51 to 116 iterations, median 87. max_iter=1000 and max_iter=-1 produce an
    identical model, identical n_support_, identical accuracy 0.95, and zero
    ConvergenceWarning. libsvm converges on its KKT tolerance with ~9x headroom.

    Note that the two max_iter=1000 values in the canonical benchmark do not mean the
    same thing. Flow counts full passes over the pair's training set. libsvm counts
    individual two-variable SMO steps. Flow performs 266,823 productive steps against
    libsvm's ~3,900 total, so it takes roughly 68x as many productive steps and still
    does not reach its stopping criterion.

    The bounded-at-C observation does not indicate truncation

    The previous comment flagged that 80 to 95% of Flow's support is pinned at C and
    suggested that is what a truncated solver looks like. Measured on both sides, that
    reading does not hold:

    duals at the box bound total nonzero duals share
    Flow 4151 4461 93.0%
    sklearn 4201 4810 87.3%

    sklearn is fully converged and still puts 87% of its support at the bound. With
    C = 1 and gamma = 0.001 on standardised digits the problem is heavily regularised,
    so a large bounded set is the correct solution shape rather than a truncation
    artifact. That field is not the tell. The iteration count is.

    (Flow totals here are 4461 / 4151 from this harness against the 4431 reported in
    #402; the difference is the counting predicate for a support vector, and it does
    not change the conclusion.)

    Local vs committed numbers

    Local sklearn SVC.fit best of 5 is 26.3 ms against Flow's 608.5 ms, so the local
    fit ratio is 0.0433. The committed CI evidence has 54.587 ms against 1092.493 ms,
    ratio 0.0500. Same story, different absolute speed. With PR #346's predict rewrite
    landing, essentially the entire remaining Digits KernelSVC deficit is fit, and
    essentially all of the fit is this solver loop.

    Still to determine

    Whether running Flow's solver to actual convergence closes the 0.002777767 accuracy
    gap. Posting this now rather than holding it.

  4. godofecht commented on Aug 18, 2026

    @godofecht
    OwnerAuthor

    Flow is not truncating. It converges on tolerance, so the accuracy gap is not a convergence artifact.

    Answering the open question from the previous comment. This is inference from the code plus the counters already measured, not a fresh instrumented run, and I mark it as such. It should be confirmed with a direct iteration-count print, but the conclusion is well supported.

    Same tolerance, same criterion

    lib/scikit/svm.flow:800:

    let tol: f64 = 0.001
    

    That is sklearn's tol=1e-3, the same value on the same quantity (the KKT violation), so these are the same stopping criterion and not merely similarly named.

    The loop has a real convergence exit

    svm.flow:805-832:

    while iter < max_iter {
        ...
        if examine_all { examine_all = false }
        elif n_changed == 0 { examine_all = true }
        iter = iter + 1
        if n_changed == 0 && examine_all { break }
    }
    

    This is Platt's alternation between a full sweep and a non-bound-only sweep, breaking when a full sweep changes nothing. The cap is a backstop, not the expected exit.

    Critically, iter counts OUTER passes, not individual steps. The canonical digits row passes max_iter=1000 (bench_flow_v2.flow:276), meaning 1000 full sweeps, which is enormously generous.

    The arithmetic says it exits far short of the cap

    From the measured counters: 332,245 _smo_examine calls in total, across 45 one-vs-one pairs. Digits has 1437 training samples over 10 classes, so each pair holds roughly 287 samples. A full examine_all sweep over all 45 pairs therefore costs about 45 x 287 = 12,915 examine calls.

    332,245 / 12,915 is about 26 outer passes per pair on average, and non-bound sweeps examine fewer than a full sweep so the true pass count is somewhat higher than that. Either way it is on the order of tens, against a cap of 1000.

    What this means for this issue

    The score_abs_diff of 0.002777767 is not explained by early stopping. Both implementations reach their KKT tolerance. So there is a genuine difference in the fitted model, and the most likely source is the one already documented in #412: Flow's max |E1 - E2| working-set heuristic with scan-on-failure explores pairs in a different order from libsvm's second-order selection, converges to a different point in the (large, flat, heavily bounded) optimal set, and therefore selects a different support vector set. Flow finds 4461 nonzero duals against sklearn's 4810.

    That reframes #206 cleanly into two separable problems:

    1. Performance is SMO working-set selection: 98.4% of _smo_step calls make no progress, and the solver is 96% of KernelSVC fit #412: 98.4% of _smo_step calls do nothing. That is the 96% of fit time and it is worth fixing on its own terms.
    2. Accuracy is a working-set-selection difference, not a truncation. Fixing it means matching libsvm's selection rule, which is option 3 in SMO working-set selection: 98.4% of _smo_step calls make no progress, and the solver is 96% of KernelSVC fit #412. Note that options 1 and 2 in SMO working-set selection: 98.4% of _smo_step calls make no progress, and the solver is 96% of KernelSVC fit #412 (skip non-negative eta, cache the error vector) are pure speed and should leave the fitted model identical; only option 3 changes which support vectors are found, and it is the one that could move the disparity in either direction.

    Still worth measuring directly

    A print of the per-pair exit iter and whether the loop broke or hit the cap would turn the arithmetic above into a fact. Given #469 makes editing svm.flow risky, that belongs in the harness-copy approach described in the previous comment.

  5. godofecht commented on Aug 19, 2026

    @godofecht
    OwnerAuthor

    The accuracy gap is a genuine convergence defect, not a different-but-equal optimum

    Measured by a Jules agent which could not reach gh to post directly; relaying its findings here. These numbers are its measurements and I have not independently reproduced them, but they are internally consistent and they refute the hypothesis I recorded earlier on this issue.

    1. Dual objective, the decisive measurement

    Summed over all 45 one-vs-one pairs:

    dual objective
    libsvm (sklearn) 636.8965
    Flow 627.3047

    For a single pair, class 0 vs class 1, Flow reaches 6.942 against libsvm's 6.971.

    This is a maximisation problem, so a lower objective means Flow is stopping short of the optimum, not finding an alternative point of equal quality.

    2. Support vector sets differ substantially

    Flow libsvm
    pairwise SV count 3226 3494
    bounded SVs 268 236
    sum of |alpha| 1222.6 1230.0

    Consistent with early stopping rather than swapping a few vectors within a flat region.

    3. Not tie-order noise

    Sweeping random_state and shuffling the training data over 50 iterations in sklearn yielded zero variance in test accuracy. So the 0.002777767 is structural, not the kind of tie-break noise that explained the DecisionTree and RandomForest gaps in #204 and #205.

    What this changes

    My earlier comment on this issue proposed that Flow converges to a different point in a large flat heavily-bounded optimal set. That was wrong. Flow's objective is strictly worse, so the first-order max-absolute-error heuristic in the working-set selection is genuinely terminating early relative to libsvm's second-order selection.

    It also reframes #412. Second-order working set selection was listed there as option 3, a performance change with a fitted-model side effect to be reported as a tradeoff. On this evidence it is the correctness fix for this issue, and closing the accuracy gap is a reason to do it rather than a risk of doing it.

    Note this does not contradict the earlier finding that the solver reaches its KKT tolerance in about 26 outer sweeps: reaching a tolerance on the KKT violation and reaching the optimum are different things when the working-set rule keeps proposing pairs that make little progress.

    Recommend keeping #206 open and blocked on #412 rather than closing it as diagnosed, since unlike #204 and #205 there is a real defect here.

  6. godofecht commented on Aug 20, 2026

    @godofecht
    OwnerAuthor

    The gap is closed. PR #447 implements second-order working set selection.

    Following the reframing above, option 3 on #412 is done. Full measurement is on #412; the part that belongs here:

    KernelSVC_RBF digits accuracy
    sklearn 0.950000000
    Flow before 0.938888907
    Flow after 0.949999988

    score_abs_diff goes to 0.000000012, which is the f32 representation of 342/360.

    Note the local main baseline is 0.938888907, not the 0.947222233 in the committed CI evidence, so the local starting gap was 0.011111 rather than 0.002777767. Both land on sklearn's value after the change.

    The dual objective confirms this is the optimum rather than a lucky point. Summed over all 45 pairs, W = sum a - 1/2 a^T Q a: Flow before 2678.7339, Flow after 2813.4047, libsvm 2813.4047. The libsvm figure is measured here from 45 binary SVC fits on the same pairs rather than relayed, so it is on the same basis as the Flow numbers; it is a different scale from the 636.8965 / 627.3047 pair reported earlier, though the direction and the conclusion are the same.

    The root cause was narrower than "the heuristic explores pairs in a different order". _smo_step computed eta = q11 + q22 - 2*q12 where Q[i][j] = y_i y_j K(i,j), which is K11 + K22 - 2 y1 y2 K12. The correct curvature is K11 + K22 - 2 K12. Every pair with differing labels was divided by up to twice the right denominator and undershot the line minimum, which is why the solver satisfied its KKT tolerance while sitting 4.8% below the optimal objective.

    Fit time went from 693 ms to 35 ms on the same measurement, so the performance half of this issue moves too.

  7. godofecht commented on Aug 20, 2026

    @godofecht
    OwnerAuthor

    CI numbers, on the committed evidence's own basis

    PR #447 is green on all eight checks. From run 32346735364's headline-benchmark artifact, so this is directly comparable to the committed headline_result_v2.json:

    field main (committed) PR #447 (CI) sklearn (CI)
    KernelSVC_RBF digits accuracy 0.947222233 0.949999988 0.950000000
    KernelSVC_RBF digits fit_ms 1037.72986 114.200417 55.824051
    KernelSVC_RBF iris accuracy 0.966666639 0.966666639 0.966666667
    KernelSVC_RBF iris fit_ms 7.90797901 1.07990003 1.05668884

    score_abs_diff on the digits row: 0.002777767 -> 1.2e-8, the residual being the f32 representation of 342/360.

    Fit ratio on that row moves from 20.0x slower than sklearn to 2.05x. The iris row lands at 1.02x.

  8. godofecht commented on Aug 20, 2026

    @godofecht
    OwnerAuthor

    Closing. Both halves are now resolved, and the cause was a sign error rather than a working-set heuristic difference.

    The performance half

    PR #346 rewrote the predict path: it had been building 45 separate kernel blocks for 45 one-vs-one pairs, expanding 1437 training rows into 12933 kernel rows and calling exp 4.66M times where 517k suffice. Digits predict went 43.5 ms to 4.1 ms, and on the CI runner Flow went from 149.4 ms to 17.5 ms against sklearn 25.7 ms in the same job.

    PR #447 then fixed fit. The canonical row goes 1037.73 ms to 114.20 ms against sklearn 55.82, so the fit ratio moves from 20.0x slower to 2.05x slower. Interleaved locally: 693.0 ms to 35.3 ms, 19.6x.

    The accuracy half

    Closed. KernelSVC_RBF digits accuracy 0.947222233 to 0.949999988 against sklearn 0.950000000. score_abs_diff goes 0.002777767 to 1.2e-8, which is the f32 representation of 342/360.

    The actual cause

    _smo_step computed the subproblem curvature as eta = q11 + q22 - 2*q12 from Q[i][j] = y_i y_j K(i,j), which evaluates to K11 + K22 - 2 y_1 y_2 K12. The correct curvature is K11 + K22 - 2 K12. For differing labels the code divided by 2 + 2 K12 instead of 2 - 2 K12, so every mixed-label step undershot the line minimum by up to a factor of two.

    The dual objective, summed over all 45 pairs on digits, measured against libsvm recomputed from dual_coef_ on an f64 gram:

    dual objective pairwise SVs SMO steps
    Flow before 2678.7339 4461 44,408
    Flow after 2813.4047 4807 3,816
    libsvm 2813.4047 4811 —

    Flow now matches libsvm to four decimals.

    Correcting the record on this issue

    Two earlier conclusions here were wrong and are worth marking so nobody builds on them.

    I wrote that the bounded-at-C fraction and the KKT tolerance showed Flow was converging normally and the gap must be a different-but-equal optimum in a flat region. It was not; Flow was reaching a KKT tolerance while systematically taking half-length steps.

    Worse, my analysis on #412 observed that eta >= 2 whenever labels differ, and used that to argue the degenerate-step guard never fires. That observation was arithmetically correct and it was the bug in plain sight. I read it as a property of the RBF kernel rather than as evidence the expression was wrong.

    The relayed figures of 636.8965 and 627.3047 in an earlier comment could not be reproduced on any basis; the measurement above was taken independently. Same direction, different scale, so treat those two numbers as unreliable.

    Second-order working set selection fixed this necessarily rather than incidentally: a_ij = QD_i + QD_j - 2 y_i y_j Q_ij has to be correct for the ranking to work at all, so implementing it forced the expression to be right.

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