Skip to content

SMO working-set selection: 98.4% of _smo_step calls make no progress, and the solver is 96% of KernelSVC fit #412

Closed

Description

@godofecht

Measured while working the attribution half of #206. Full numbers in that comment.

Where Digits KernelSVC fit time goes

Standalone harness copying the solver out of lib/scikit/svm.flow under b206_ prefixes with timers added, so the library is untouched and no canonical RESULT| line moves. 1437 train / 360 test / 64 features, gamma 0.001, C 1.0, max_iter 1000.

Phase ms Share
SMO solver loop 608.714 96.2%
Full RBF kernel build (sgemm + exp) 9.447 1.5%
Per-pair Q gather 9.442 1.5%
Per-pair training subset extraction 4.445 0.7%
Everything else 0.747 0.1%

Kernel evaluation is already done well: the full 1437x1437 kernel is built once via cblas_sgemm plus a vectorised exp, 2.06M entries in 9.4 ms, then sliced per pair. Orchestration, allocation and setup together are 2.3%. Deleting all of it would move the local fit ratio from 0.0433 to only 0.0443.

The actual waste

Counter Value
_smo_examine calls 332,245
_smo_step calls 17,001,738
_smo_step calls that made progress 266,823
best-j scan element visits 92,639,427
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 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, calling _smo_step on each until one succeeds.

Direction

This is Platt's original SMO fallback. libsvm does not do this; it uses second-order working set selection, choosing the pair that maximises the objective decrease directly rather than guessing by |E1 - E2| and scanning on failure. That removes most degenerate steps rather than recovering from them.

Options, cheapest first:

  1. Cache the error vector so the fallback scans stop recomputing E per candidate.
  2. Skip candidates whose eta is non-negative before calling _smo_step, since a degenerate step is predictable from the kernel diagonal without attempting it.
  3. Second-order working set selection, matching libsvm.

Constraints

Note on a refuted hypothesis

The earlier reading that 80-95% of support pinned at C indicates a truncated solver does not hold. sklearn is fully converged and still puts 87.3% of its support at the bound (4201 of 4810), against Flow's 93.0% (4151 of 4461). 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. The iteration count is the tell, not the bounded fraction.

Activity

  1. godofecht commented on Aug 18, 2026

    @godofecht
    OwnerAuthor

    Correcting my own recommendation: the eta guard is the wrong fix, and for RBF it essentially never fires

    I listed "skip candidates whose eta is non-negative" as option 1, the cheapest and safest win. That was wrong. Anyone picking this up would implement it first and measure nothing. Here is why, and what the actual dominant path is.

    eta cannot be degenerate for an RBF kernel

    svm.flow:790 builds Q as:

    Q[i * n + j] = yi * y_d[j] * kernel_full[gi * n_total + gj]
    

    So Q[i][j] = y_i * y_j * K(i,j), and therefore Q[i][i] = y_i^2 * K(i,i) = K(i,i). For RBF, K(x,x) = exp(-gamma * 0) = 1.

    _smo_step computes eta = q11 + q22 - 2*q12 = 2 - 2 * y1 * y2 * K(i1,i2). Two cases:

    • y1 != y2: q12 = -K(i1,i2), so eta = 2 + 2*K(i1,i2) >= 2. RBF K is strictly positive, so this is never degenerate.
    • y1 == y2: eta = 2 - 2*K(i1,i2), degenerate only when K(i1,i2) ~ 1, meaning the two points are near-identical in feature space.

    The guard at _smo_step line 29 (if eta > 0.0000000001) therefore fires only on duplicate or near-duplicate training points. On standardised digits that is rare, so it cannot account for 16.7M futile calls.

    The dominant path is the clip test, not eta

    _smo_step has a second false-return, after clipping:

    if a2_new < L { a2_new = L }
    if a2_new > H { a2_new = H }
    ...
    let d2: f64 = a2_new - alpha2
    if abs_d2 < 0.0000000001 { return false }
    

    This fires when the clipped update leaves alpha2 where it already was: the multiplier is already pinned at L or H and the unclipped step pushes further out of bounds. That is the futile case.

    This fits the measured data. 93.0% of Flow's nonzero duals sit at the box bound (4151 of 4461, from the earlier comment on #206). If most multipliers are pinned, most candidate pairs cannot move, so most _smo_step calls do the full setup, compute eta, compute the update, clip it, discover nothing moved, and return false. 98.4% futile is exactly what a heavily bounded solution looks like under a selection rule that does not check feasibility before attempting the step.

    The correct cheap fix

    libsvm's feasibility test, which is O(1) per candidate and needs no kernel lookup. A pair can only move if i1 is in the up-set and i2 in the low-set:

    • i is in I_up if (y_i > 0 and alpha_i < C) or (y_i < 0 and alpha_i > 0)
    • i is in I_low if (y_i > 0 and alpha_i > 0) or (y_i < 0 and alpha_i < C)

    Screen candidates on that membership in the caller's scan loops before invoking _smo_step. It is a pure speed change: the same pairs get selected in the same order and the same steps get taken, only the calls that provably could not move are skipped. The fitted model should stay bit-identical, and that must be verified rather than assumed.

    This replaces option 1. Options 2 (cache the error vector) and 3 (second-order working set selection) stand as written, and note that the I_up/I_low sets are also exactly what second-order selection needs, so doing this first is a step toward option 3 rather than a detour.

    Status of this analysis

    This is derived from reading the code and from the already-measured bound fractions, not from instrumenting which return path dominates. That instrumentation is still worth doing and would take one counter per return path in a harness copy. But the RBF eta argument above is arithmetic, not conjecture: with Q[i][i] = 1, eta >= 2 whenever the labels differ.

  2. godofecht commented on Aug 18, 2026

    @godofecht
    OwnerAuthor

    Narrowing further: the third fallback loop is essentially all of the futile calls

    Reading _smo_examine loop by loop against the measured counters localises this to one loop, which changes where the fix belongs.

    The three candidate loops

    # 1. best-j scan
    for j in 0 to n {
        if alphas[j] > 0.0 && alphas[j] < C { ... pick max (E1-E2)^2 ... }
    }
    if best_j >= 0 { if _smo_step(best_j, i2, ...) { return true } }
    
    # 2. fallback over non-bound examples
    while k < n {
        if alphas[j] > 0.0 && alphas[j] < C {
            if _smo_step(j, i2, ...) { return true }
        }
    }
    
    # 3. fallback over ALL examples, no filter
    while k2 < n {
        if _smo_step(j, i2, ...) { return true }
    }
    

    Loops 1 and 2 filter to non-bound j. Loop 3 does not filter at all.

    Reconciling that with the counters

    Per one-vs-one pair on digits: 1437 training samples over 10 classes gives roughly 287 samples per pair. Across all 45 pairs there are 4461 nonzero duals of which 4151 sit at the bound, so about 99 nonzero and about 7 genuinely free per pair. Alphas at exactly 0 are also bounded. So non-bound is roughly 2.4% of candidates.

    Against the measured 26.7M non-bound scan visits and 16.0M full scan visits:

    • loop 2: 26.7M visits x ~2.4% non-bound = ~0.6M _smo_step calls
    • loop 3: 16.0M visits, unfiltered = ~16.0M _smo_step calls

    Total ~16.6M against the measured 17.0M. Loop 3 is essentially the entire futile population.

    Why loop 3's calls fail, mechanically

    i2 is fixed for the whole of _smo_examine and has already passed the KKT violation test at the top, so i2 itself can move. The calls still fail because the clip bounds depend on alpha1 = alphas[j]:

    • y1 == y2: L = alpha1 + alpha2 - C, H = alpha1 + alpha2
    • y1 != y2: L = alpha2 - alpha1, H = alpha2 - alpha1 + C

    Take alpha1 = 0 with y1 == y2. Then H = alpha2, so a2_new is clipped to at most alpha2. If the unclipped update wants to increase alpha2, it clips exactly back to alpha2, d2 is 0, and the call returns false having done the full setup, the eta computation, the update and the clip.

    So for a bounded alpha1, roughly half of all desired directions are structurally unreachable, and loop 3 walks ~280 bounded candidates per invocation attempting them.

    What this means for the fix

    The feasibility screen should go in loop 3, and it only needs to answer one question per candidate: given alphas[j]'s bound state, y[j], y[i2], and the sign of the desired step (y1*y2*G[j] - G[i2]), is the required direction inside [L, H] at all? That is O(1), needs no kernel lookup, and skips a call that provably cannot move.

    Two notes for whoever implements it:

    1. There is also a small provably-safe redundancy. If loop 2 runs to completion, every non-bound j has just returned false, and _smo_step mutates nothing on its false paths (both returns precede alphas[i1] = a1_new). State is therefore unchanged, so loop 3 re-testing those same non-bound j is guaranteed-redundant work. Skipping them in loop 3 is unconditionally safe. It is only worth about 2.4%, so it is a correctness-free freebie rather than the win.

    2. The screen must be direction-exact. Getting the inequality backwards would skip pairs that could have moved, which changes the fitted model silently rather than failing loudly. Verify bit-identical duals, support indices, intercepts and accuracy against origin/main before claiming it is pure speed.

    Derived from the code and the existing counters; the per-loop call split above is arithmetic from the measured visit counts, not separately instrumented.

  3. godofecht commented on Aug 18, 2026

    @godofecht
    OwnerAuthor

    Option 1 was tried and measured. It is a 28% regression. Do not retry it.

    PR #416 implemented the feasibility screen exactly as specified in the previous comment. It is correct (all 19 canonical score fields bit-identical, both SVM tests byte-identical) and it is slower. Closed.

    Five interleaved A/B pairs on a quiet machine, digits KernelSVC fit_ms: baseline median 615 ms, screened median 785 ms. Baseline spread 611-672 (9%); screened spread 600-992 (65%).

    Why

    The screen recomputes L and H exactly as _smo_step does, then every candidate that passes has them computed a second time inside _smo_step. Most bounded candidates pass, so the common path does the work twice.

    The premise underneath was wrong: I assumed _smo_step's futile path was expensive because of its three Q lookups. For a fixed i2 those are Q[i1*n+i1], Q[i1*n+i2], Q[i2*n+i2], which are cache-friendly, so the early exit was already cheap. There was little to reclaim, and the screen's own branch-heavy setup costs more than it saves.

    What survives

    • The per-loop attribution stands: the third fallback really is about 16.0M of the 17.0M _smo_step calls.
    • The eta correction stands: for RBF, Q[i][i] = 1 so eta >= 2 whenever labels differ, and the guard essentially never fires.
    • The conclusion that counting futile calls does not identify where the time goes is the actual lesson. 98.4% of calls being futile is true and turns out not to matter, because each futile call is cheap.

    What to do instead

    Any further work here should start by measuring time per call, not call counts. The 96.2% of fit time spent in the solver is real, but it is evidently spread across the gradient update (76.7M element visits) and the best-j scan (92.6M element visits) rather than concentrated in the futile-call setup. Those two loops touch far more memory than the futile calls do, and are the better targets:

    • The best-j scan walks all n candidates computing (E1-E2)^2 per outer examine. That is the 92.6M figure.
    • The gradient update after a successful step touches all n entries of two Q columns. That is the 76.7M figure, and it is the one libsvm optimises with a kernel cache.

    Option 2 (cache the error vector) targets the first. Option 3 (second-order working set selection) reduces the number of successful steps needed and therefore the second. Both remain plausible; option 1 is now closed off with evidence.

  4. godofecht commented on Aug 20, 2026

    @godofecht
    OwnerAuthor

    Option 3 implemented and measured: Flow now reaches libsvm's dual objective exactly, and the digits accuracy gap closes

    Second-order working set selection (libsvm WSS3, Fan/Chen/Lin 2005) replaces the max |E1 - E2| heuristic and its two scan-on-failure fallbacks in _kernel_svc_smo_precomputed. Branch perf/412-second-order-working-set.

    Dual objective

    Summed over all 45 one-vs-one pairs, digits, gamma 0.001, C 1.0, standardised, canonical split_digits.bin. Maximisation form W = sum a - 1/2 a^T Q a, computed inside the solver as 0.5 * sum_i a_i * (1 - G_i).

    dual objective pairwise SVs
    Flow, `max E1 - E2 `
    Flow, second-order WSS 2813.4047 4807
    libsvm (sklearn) 2813.4047 4811

    The libsvm anchor is my own measurement, not a relayed one: 45 binary SVC fits on the same pairs, W computed from dual_coef_ and an f64 RBF gram. It agrees with the new Flow solver to all four printed decimals.

    This is a different scale from the 636.8965 / 627.3047 pair relayed earlier on #206, so those two numbers were on some other basis. The direction is the same and the conclusion recorded there holds: the old rule was strictly short of the optimum, and the shortfall was 4.8% of the objective.

    Accuracy

    Local bench_flow_v2.flow, canonical fixture:

    KernelSVC_RBF digits accuracy
    sklearn 0.950000000
    Flow before 0.938888907
    Flow after 0.949999988

    score_abs_diff goes from 0.011111093 to 0.000000012, which is just the f32 representation of 342/360. The gap is closed.

    Note the local main baseline reads 0.938888907, not the 0.947222233 in the committed CI evidence, so the local starting gap is 4x the CI one. Either way it lands on sklearn's value after the change.

    KernelSVC_RBF|iris is unchanged at 0.966666639, equal to sklearn.

    Fit time

    Interleaved A/B in one process, both solvers compiled into the same binary sharing identical kernel build, Q gather and bias code, 5 alternating repeats, digits:

    fit ms, per repeat
    old 669.4, 693.0, 661.7, 741.9, 736.9 (median 693.0)
    new 34.9, 34.9, 35.3, 39.0, 37.3 (median 35.3)

    19.6x on the median. Corroborated by bench_flow_v2 under the same conditions: KernelSVC_RBF|digits fit 742.5 ms to 37.2 ms, KernelSVC_RBF|iris 2.195 ms to 0.339 ms. LinearSVC|digits is 724.8 ms before and 726.2 ms after, so nothing outside the solver moved.

    Total SMO steps over the 45 pairs: 44,408 before, 3,816 after.

    Why the old rule stopped short

    The eta computed in _smo_step was wrong whenever the pair's labels differ.

    let q12: f64 = Q[i1 * n + i2]
    let eta: f64 = q11 + q22 - 2.0 * q12
    

    Q[i][j] = y_i y_j K(i,j), so this evaluates to K11 + K22 - 2 y1 y2 K12. The curvature along the feasible direction is K11 + K22 - 2 K12. For y1 != y2 the code therefore used 2 + 2*K12 where the correct value is 2 - 2*K12, so the step was divided by a number up to twice too large and every mixed-label step undershot the line minimum. That is the mechanism behind the objective shortfall, and it is the same arithmetic I used earlier on this issue to argue eta could never be degenerate. eta >= 2 for mixed labels was true, and it was true because the expression was wrong.

    Second-order selection fixes it as a side effect, because a_ij = QD_i + QD_j - 2 y_i y_j Q_ij has to be correct for the selection rule to rank pairs at all.

    Two smaller things in the same diff

    • The gradient update walked two columns of Q with stride n. Q is symmetric, so it now walks two rows. Same arithmetic, row-major.
    • _smo_examine and _smo_step are deleted. svm.flow loses 18 lines net, which is the right direction given Config comparator flags identical settings expressed in different vocabularies #469. tests/test_multiclass_svm.flow prints LinearSVC accuracy 0.9778 and decision function 0.2858 -1.8328 -0.7503 both before and after, unchanged.

    On PR #416

    The lesson recorded when the feasibility screen was closed was that counting futile calls does not locate time. That still holds. The 16.0M futile calls in the third fallback loop were a symptom of a selection rule that had to scan because its first choice kept failing, and of a step that was too small to satisfy KKT quickly. Removing the cause removed 91.4% of the steps, not just the futile calls around them.

    PR to follow, referencing this issue and #206.

  5. godofecht commented on Aug 20, 2026

    @godofecht
    OwnerAuthor

    PR #447 is open and green on all eight CI checks. On the committed evidence's own basis, from run 32346735364's headline-benchmark artifact: KernelSVC_RBF digits accuracy 0.947222233 -> 0.949999988 against sklearn's 0.950000000, and fit_ms 1037.72986 -> 114.200417 against sklearn's 55.824051. The iris row goes 7.90797901 -> 1.07990003 ms with accuracy unchanged at sklearn's own value. Local python tools/run_all.py is 104/104.

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