Repository navigation
Description
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:
- Cache the error vector so the fallback scans stop recomputing
Eper candidate. - Skip candidates whose
etais non-negative before calling_smo_step, since a degenerate step is predictable from the kernel diagonal without attempting it. - Second-order working set selection, matching libsvm.
Constraints
svm.flowis 76KB and the known victim of compiler bug Config comparator flags identical settings expressed in different vocabularies #469: LinearSVC accuracy collapsed 0.833 to 0.033 purely from surrounding code growing. Verify printed accuracies withtests/test_multiclass_svm.flowandtests/test_multiclass_kernel_svm.flow, diffing numbers rather than checking exit codes.- PR perf: evaluate the SVC prediction kernel once per call instead of once per class #346 is open against
svm.flowand rewrote the predict path. Keep any diff orthogonal. - Changing working-set selection changes which support vectors are found and therefore the fitted model. Close the Digits KernelSVC quality gap and isolate the libsvm performance deficit #206 tracks a
score_abs_diffof 0.002777767; any change here must report its effect on that number rather than assume it is unchanged.
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
godofecht commentedon Aug 18, 2026
Correcting my own recommendation: the
etaguard is the wrong fix, and for RBF it essentially never firesI listed "skip candidates whose
etais 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.etacannot be degenerate for an RBF kernelsvm.flow:790buildsQas:So
Q[i][j] = y_i * y_j * K(i,j), and thereforeQ[i][i] = y_i^2 * K(i,i) = K(i,i). For RBF,K(x,x) = exp(-gamma * 0) = 1._smo_stepcomputeseta = q11 + q22 - 2*q12 = 2 - 2 * y1 * y2 * K(i1,i2). Two cases:y1 != y2:q12 = -K(i1,i2), soeta = 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 whenK(i1,i2) ~ 1, meaning the two points are near-identical in feature space.The guard at
_smo_stepline 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_stephas a second false-return, after clipping:This fires when the clipped update leaves
alpha2where it already was: the multiplier is already pinned atLorHand 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_stepcalls do the full setup, computeeta, 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
i1is in the up-set andi2in the low-set:iis inI_upif (y_i > 0andalpha_i < C) or (y_i < 0andalpha_i > 0)iis inI_lowif (y_i > 0andalpha_i > 0) or (y_i < 0andalpha_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_lowsets 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
etaargument above is arithmetic, not conjecture: withQ[i][i] = 1,eta >= 2whenever the labels differ.godofecht commentedon Aug 18, 2026
Narrowing further: the third fallback loop is essentially all of the futile calls
Reading
_smo_examineloop by loop against the measured counters localises this to one loop, which changes where the fix belongs.The three candidate loops
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:
_smo_stepcalls_smo_stepcallsTotal ~16.6M against the measured 17.0M. Loop 3 is essentially the entire futile population.
Why loop 3's calls fail, mechanically
i2is fixed for the whole of_smo_examineand has already passed the KKT violation test at the top, soi2itself can move. The calls still fail because the clip bounds depend onalpha1 = alphas[j]:y1 == y2:L = alpha1 + alpha2 - C,H = alpha1 + alpha2y1 != y2:L = alpha2 - alpha1,H = alpha2 - alpha1 + CTake
alpha1 = 0withy1 == y2. ThenH = alpha2, soa2_newis clipped to at mostalpha2. If the unclipped update wants to increasealpha2, it clips exactly back toalpha2,d2is 0, and the call returns false having done the full setup, theetacomputation, 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:
There is also a small provably-safe redundancy. If loop 2 runs to completion, every non-bound
jhas just returned false, and_smo_stepmutates nothing on its false paths (both returns precedealphas[i1] = a1_new). State is therefore unchanged, so loop 3 re-testing those same non-boundjis 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.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/mainbefore 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.
godofecht commentedon Aug 18, 2026
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
LandHexactly as_smo_stepdoes, 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 threeQlookups. For a fixedi2those areQ[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
_smo_stepcalls.etacorrection stands: for RBF,Q[i][i] = 1soeta >= 2whenever labels differ, and the guard essentially never fires.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:
ncandidates computing(E1-E2)^2per outer examine. That is the 92.6M figure.nentries of twoQcolumns. 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.
godofecht commentedon Aug 20, 2026
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. Branchperf/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 formW = sum a - 1/2 a^T Q a, computed inside the solver as0.5 * sum_i a_i * (1 - G_i).The libsvm anchor is my own measurement, not a relayed one: 45 binary
SVCfits on the same pairs,Wcomputed fromdual_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:score_abs_diffgoes from 0.011111093 to 0.000000012, which is just the f32 representation of 342/360. The gap is closed.Note the local
mainbaseline 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|irisis 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:
19.6x on the median. Corroborated by
bench_flow_v2under the same conditions:KernelSVC_RBF|digitsfit 742.5 ms to 37.2 ms,KernelSVC_RBF|iris2.195 ms to 0.339 ms.LinearSVC|digitsis 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
etacomputed in_smo_stepwas wrong whenever the pair's labels differ.Q[i][j] = y_i y_j K(i,j), so this evaluates toK11 + K22 - 2 y1 y2 K12. The curvature along the feasible direction isK11 + K22 - 2 K12. Fory1 != y2the code therefore used2 + 2*K12where the correct value is2 - 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 argueetacould never be degenerate.eta >= 2for 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_ijhas to be correct for the selection rule to rank pairs at all.Two smaller things in the same diff
Qwith striden.Qis symmetric, so it now walks two rows. Same arithmetic, row-major._smo_examineand_smo_stepare deleted.svm.flowloses 18 lines net, which is the right direction given Config comparator flags identical settings expressed in different vocabularies #469.tests/test_multiclass_svm.flowprints LinearSVC accuracy 0.9778 and decision function0.2858 -1.8328 -0.7503both 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.
godofecht commentedon Aug 20, 2026
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_RBFdigits 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. Localpython tools/run_all.pyis 104/104.