13 CHAPTERS · EVIDENCE FIRST
THE INVESTIGATION

Make the work
disappear.

A field masterclass in factorization, cached sweeps, Rust, SIMD, and handwritten assembly. Follow one real investigation from an honest reference to a billion-row experiment.

The fastest instruction is the one
your architecture no longer needs.

We began with a small Rust repository that already knew a powerful trick: an experiment row is not an indivisible unit of computation. We ended with an integrated pipeline, a preserved reference, a complete scaling study, and a Git-backed evidence trail.

This is the whole journey, including the misleading comparisons, the underfilled vector lanes, the hardware changes, and the final handoff. The achievement is not one multiplier. It is learning which work to remove, which work to accelerate, and which claims the measurements can support.

RECORDED RUN · AMD EPYC 9V74
$ TERASWEEP_LEVEL=assembly
… 1000000000 summary.json
98.29s

One billion sampled rows. Complete process.
One measured run. Not one billion independent fits.

Valid rows727,869,685
Cached failed-fit rows272,130,315
Native large-run timingsProjected, not executed
01 / THE LEARNING CONTRACT
UNDERSTAND

Factor the dependency graph.

Separate fixed-data work, model work, signal-path work, and cost work. Share results only when the inputs that determine them are identical.

EXPERIMENT

Choose the right SIMD axis.

Pack independent score jobs into lanes, preserve time order, and see why wider vectors initially failed to improve throughput.

DEFEND

Make the denominator visible.

Distinguish a kernel gain, a complete-process gain, and a native-reference projection. Do not manufacture a cumulative ratio across experiments.

What was inherited, and what was added?

The original Terasweep already contained shared ridge statistics, fitted-prediction reuse, score caching, factored cost arithmetic, and winner-only detail reporting. This investigation added the minimal native Limen Ridge SFD, controlled comparisons, profiling, the constant-signal shortcut, compact cache/scheduling, Rust AVX-512 intrinsics, an authored assembly kernel, validation, scaling experiments, and the evidence handoff.

The route through the investigation

BEFORE THE SESSION

A factorized Rust runner already exists.

The preserved baseline becomes the control, not a blank slate. Other model modules exist, but the measured story here is ridge.

REFERENCE FIRST

Native Limen must stay native.

A fresh sklearn Ridge estimator for each call. No Terasweep cache transplanted into Limen. The small matched run exposes both a speed difference and backtest-semantic differences.

PROFILE → REMOVE → VECTORIZE

The scorer, not Cholesky, dominates.

93.1% of first-million score misses yield constant signals. Eliminating those scans changes the problem before any new SIMD is written.

INTEGRATE → SCALE → PRESERVE

From standalone kernels to a real pipeline.

Rust intrinsics and assembly share one runner. The 100k–1b study reveals cache saturation. The original and optimized implementations, raw outputs, and replay instructions are committed together.

MEASURED Recorded experiment PROJECTED Conditional reference-cost model TEACHING LAB Browser illustration, never benchmark evidence

All calculations and charts in the lesson are offline. No benchmark executes when you move a slider. Learning progress and notes stay in this browser when local storage is available. Evidence buttons open the retained reports or source snapshots; older reports keep their original limitations and deployment status.

01 / PROTECT THE CONTROL

A reference you
can trust.

Before optimizing anything, establish what is actually being compared. A native SFD is not a disguised cached implementation.

Fresh estimator. Every time.

The merged Limen Ridge SFD delegates fitting and prediction to sklearn.linear_model.Ridge. Its train method constructs a new estimator and calls fit. In the native UEL path, preparation and the model execute again for every experiment row.

Changing only a fee does not cause the native reference to reuse the previous fit. That redundancy is precisely what the Terasweep sweep architecture can eliminate.

LIMEN · PINNED REFERENCE BEHAVIOR
self.model = _ridge(params)
self.model.fit(data['x_train'], data['y_train'])

# _ridge constructs sklearn.linear_model.Ridge.
# No cross-trial fit or prediction cache.

Limen merge commit 44eff3b2, PR #826. The wrapper is minimal; native preparation, metrics, Trainer and Sensor remain Limen responsibilities.

1,014native fit calls in the matched grid
6unique model configurations
169fee × slippage combinations per model

Same parameters do not mean the same work boundary.

Native CLI / UELraw input → prepare → fresh sklearn fit → predict → native metrics → full round artifacts
Terasweepprepared matrices → shared statistics → cached fits → cached/factored scores → winner summary

A native-relative application comparison is useful, but it is not a pure Python-versus-Rust, solver-versus-solver, or equal-output benchmark. The original Rust internal timer includes statistics, fit/predict precomputation, the sampled loop and winner details; it excludes input loading and price-statistics preparation. Whole-process timings avoid dividing those unlike sub-timers.

Economic equivalence was not established.

Terasweep uses entry-bar open-to-close returns and its existing multiplicative cost factors. Current native Limen uses its own entry and fees-on-notional convention. Rounded MAE and aggregate signal rates can match while return accounting differs. We preserved the original Rust contract instead of silently rewriting the reference.

Three workloads. Keep them separate.

EXPERIMENT MAPRECORDED INPUTS

Different hosts also appear at different stages: M1 Max for the early local work; an AMD EPYC guest for the first AVX-512 prototype; an Intel 8573C guest for the handwritten-kernel experiment; an Intel 8370C guest for integration; and an AMD EPYC 9V74 guest for scaling. Each report identifies its host. None of those host-to-host changes is an optimization gain.

CHECK YOUR MODEL

What does “six unique model configurations” tell you about native Limen’s 1,014-row grid?

02 / FACTOR THE MODEL

Shrink the repeated
mathematics.

Start with the ridge objective, not the estimator API. Identify the terms that do not change when the model parameters change.

minw,b ‖y − Xw − b1‖² + α‖w‖²

Let n be training rows, d features, and m test rows. Without an intercept, the normal equations are (XᵀX + αI)w = Xᵀy. The dependence on the full training data is concentrated in two objects:

GRAM MATRIXG = XᵀXd × d values
RIGHT-HAND SIDEh = Xᵀyd values

For a new regularization strength, solve (G + αI)w = h. Neither G nor h changes with α. Terasweep computes them once, not once per logical sweep row. This was already present in the inherited implementation.

Derive the intercept path

Center the data: Xc = X − 1x̄ᵀ and yc = y − ȳ1. Form Gc = XcᵀXc and hc = Xcᵀyc. Solve (Gc + αI)w = hc, then recover b = ȳ − x̄ᵀw. The original code retains both raw and centered statistics and accumulates only the lower triangle before mirroring it for the solve.

The intercept is not penalized in this formulation. Changing the intercept setting chooses the relevant statistics; it does not require re-reading the training data for every trial.

A 55-feature problem remains a 55-feature problem.

The original training matrix is 4,136 × 55. Its repeated solve is a 55 × 55 system. One FP64 Gram matrix contains 24,200 bytes, calculated as 55 × 55 × 8. No feature is discarded.

Cholesky produces A = LLᵀ; forward and backward substitution solve the system. The code does not explicitly invert the matrix. It still performs a distinct Cholesky solve for each training key—there is no shared eigendecomposition across all α values in this implementation.

THE REUSE BOUNDARY

Fixed X and y.

A different feature set, scaler, split, window, target or dataset changes the statistics. Reuse is justified by dependencies, not resemblance.

The code’s solver_eps tests a Cholesky pivot. It is not sklearn’s iterative-solver tol. A failed solve is cached as a failed configuration, not converted to a successful model.

LAB / REGULARIZATION WITHOUT REBUILDING GTEACHING FIXTURE

Eight illustrative (x, y) pairs; one feature. This browser calculation is not market data or a performance measurement.

Predictions are another reusable intermediate.

Once a fit succeeds, the original code computes predictions and MAE in a single pass, storing them under (alpha.to_bits(), fit_intercept, solver_eps.to_bits()). A fee or threshold change cannot change those predictions.

O(nd²) + O(Ud³) + O(Umd)

Leading-order structural work for statistics, U distinct solves, and their test predictions. This is a complexity explanation, not a fitted timing model. It omits parsing, allocations, failure branches, scoring and reporting.

CHECK YOUR MODEL

You double the number of fee settings, keeping data and model parameters fixed. Which mathematical work must be repeated?

03 / FACTOR THE SWEEP

An experiment row
is not a job.

One requested row can share almost all its expensive work with thousands of other rows. Factor at the intermediate-result boundary, not only at the final-output boundary.

LAB / WHAT DOES THIS PARAMETER INVALIDATE?DEPENDENCY MODEL

Choose a change. The highlighted stages must be reconsidered; upstream unaffected stages remain reusable.

The original keys describe the actual dependencies.

IntermediateIdentity, with data fixedReused across
Training statisticsPrepared X and yAll model and score settings
Fit, predictions, MAEα, intercept, pivot cutoffRules, thresholds, fees, slippage
Base scoreTraining key, rule, thresholdFees and slippage
Cost-adjusted rowBase score plus fee and slippageNot globally memoized by the original runner

The full original scoring key deliberately excludes costs. That is not accidental omission: the inherited base-score statistics are designed so costs can be applied later. A complete-experiment cache would miss this sharing between different experiments.

384 × 2 × 32,304 configured training keys
627failed under the original pivot contract
1,677successful configured training keys

What a million rows really means.

The canonical million-row sample contained 728,102 valid rows and 271,898 failed-fit rows. There were 648,130 unique valid base-score keys. Training reuse was extensive, but only 79,972 valid rows reused a base score—about 11% of valid rows in that first million.

Do not let “cached sweep” suggest every row is cheap from the start. First encounters still cost work. Later chapters show what happens as the key space fills.

The sampler is deterministic, not unique.

SplitMix64 is seeded from the configured seed and a mixed row ID. An ID determines its parameters, which also lets the summary reconstruct a winner later. Sampling is with replacement. One billion requested rows is not one billion distinct configurations; the original configured Cartesian space contains 781,088,256 logical combinations, including failures.

Count failures honestly.

Once a training key fails, downstream requests reuse that failure. They remain part of the requested-row total and failure count. Throughput expressed as sampled rows per second therefore includes these cheaper failed requests. Calling it models trained per second would change the meaning of the benchmark.

CHECK YOUR MODEL

Which key is sufficient for a base score under the inherited contract?

04 / FACTOR THE SCORER

Price the path.
Don’t replay the path.

The original implementation does more than memoize. It derives compact statistics that support repeated fee/slippage evaluation without rescanning the bars.

Separate the trading path from its costs.

Predictions, a rule, and a threshold determine the shifted position path. The original scorer uses the previous bar’s prediction for the current position, subject to tradability. Entry, continuation and exit flags determine the gross return and cost category.

aₜ = 1 + rₜgross   ·   Egross = ∏ₜ aₜ

Under Terasweep’s own cost convention, with fee f and slippage s expressed as fractions:

ENTRY MULTIPLIERu = (1 − f) / (1 + s)
EXIT MULTIPLIERv = (1 − f)(1 − s)
Enet = Egross · uentries · vexits

A new cost pair changes a few arithmetic operations, not the whole time-series traversal. These equations are not a claim about current Limen’s different accounting.

Sharpe needs moments, not only compounded return.

For each of four entry/exit categories, retain a count n꜀, a sum S꜀ = Σaₜ, and a squared sum Q꜀ = Σaₜ². Their cost multipliers are 1, u, v, uv. Since the net bar return is k꜀aₜ − 1:

Σrnet = Σ꜀ (k꜀S꜀ − n꜀)
Σ(rnet)² = Σ꜀ (k꜀²Q꜀ − 2k꜀S꜀ + n꜀)

Those two moments and the eligible-bar count give the mean and sample variance. The cost-adjustment stage operates over four categories. It does not require rebuilding the returns array for each fee setting.

LAB / ONE PATH, MANY COSTS12-BAR TEACHING FIXTURE

Illustrative prices and signals; original Terasweep formulas. Not a benchmark or a trading recommendation. The active position is shifted by one bar.

CategoryBarsΣaΣa²Cost factor

Not every diagnostic belongs in every trial.

These moments do not preserve an arbitrary drawdown path, rolling-return distribution, or trade-level quantile. Terasweep selects winners using the compact per-row metrics, then recomputes rich backtest details for the best return, best Sharpe and best MAE rows.

Three report slots need not mean three distinct winners. Selecting on rounded metrics also means ties must retain the original ordering. This is a summary-producing runner, not a replacement for full native per-trial artifact production.

CHECK YOUR MODEL

Can four category moments reconstruct arbitrary drawdown episodes?

05 / FOLLOW THE PROFILE

The bottleneck
was not the solver.

Before writing instructions, measure where the existing program spends its time. The first major new optimization removed work rather than vectorizing it.

A diagnostic, not a new denominator.

Sampling the original M1 executable pointed to score_cached. A diagnostic copy gave the inlined scorer a name and added phase timers. The resulting times are not an exact decomposition of the production binary, but they decisively identify the first target.

The source and historical executable remained unchanged. The diagnostic summary still matched the golden result.

M1 MAX · DIAGNOSTIC BUILD
Training statistics0.010 s
Fit and prediction0.098 s
Sampled loop4.179 s
Winner details0.00078 s

Phase timings are specific to this instrumented run. They are not pooled with later Intel/AMD process timings.

93.1% of score misses had one of two answers.

ALL OFF
ALL ON
394,015all-off logical keys
209,555all-on logical keys
44,560mixed logical keys

For a finite prediction vector, retain its minimum and maximum, plus those of its absolute values. For p > t, max(p) ≤ t proves all-off; min(p) > t proves all-on. Strict and inclusive inequalities matter at the exact boundary.

LAB / PROVE THE CONSTANT PATTERNILLUSTRATIVE PREDICTIONS

The first actual occurrence of each constant pattern is passed through the original scorer. Later constant keys reuse its exact payload. Non-finite prediction vectors fall back to the scalar path. For this million-row sample, full base-score scans fall from 648,130 to 44,562: 44,560 mixed paths and the two initial constant paths.

ISOLATED M1 PROTOTYPE
4.01 sOriginal median
→
0.77 sBounds-shortcut median
5.21×

Three alternating pairs. All 603,570 shortcuts were separately checked against the original scorer, field-for-field and float-bit-for-float-bit. The golden comparisons passed. This gain did not require new SIMD.

The new profile is a new problem.

After the shortcut, sampling showed meaningful hash lookup, insertion and rehash overhead. The first prototype still stored a full base-score payload under every logical key, even when hundreds of thousands of keys shared one of two values. Faster arithmetic was no longer the only opportunity.

CHECK YOUR MODEL

Why not start with handwritten Cholesky assembly?

06 / REDESIGN THE CACHE

Same logical result.
Smaller physical state.

A cache is an algorithm and a memory layout. Preserving every logical key does not require storing a complete payload for every key.

Three kinds of slot.

The inherited BaseScore is 128 bytes; its key is 24 bytes in the measured build. The compact path uses a logical key to select either the shared all-off result, the shared all-on result, or an individually stored mixed result.

The reported cache cardinality remains the number of logical keys. Compression changes physical representation, not what counts as an evaluated configuration.

LOGICAL ID → PHYSICAL PAYLOAD
0       → shared all-off BaseScore
1       → shared all-on BaseScore
2 + j   → mixed BaseScore[j]

row     → { train: u32, slot: u32 }

Actual allocation includes metadata, optional values, capacity slack, indexing and buffers. A payload-only calculation is not process RSS.

Use categorical identities when the configuration gives them to you.

The sampler already chooses positions in finite parameter arrays. Carry those ordinals forward rather than hashing float bit patterns on every normal generated row. Duplicate configured values still need their original deduplication semantics. Explicit CSV plans use lookup paths that retain the value-based contract.

A dense index is allowed only while its address space fits the 64 MiB cap; larger configured spaces use a sparse map with bounded initial reservation. “Use an array” is not a license to allocate the full theoretical grid without checking its size.

LAB / WHY A BILLION ROWS NEED NOT FILL MEMORYROW-REFERENCE STORAGE CALCULATION

Two u32 values per row reference: 8 bytes. The scheduler keeps at most 1,048,576 requested row references at a time. These values exclude all other storage; they are not measured RSS.

Cache state survives across blocks. Pending mixed jobs are grouped by model inside each block; rows are reduced in their original sequence afterward. Physical execution order may change, but rounded ties still favor the original earliest row.

939.1 MiBOriginal Rust peak RSS at 1b, AMD scaling run
77.8 MiBAssembly pipeline peak RSS at 1b, same study
224,178mixed states at full key-space coverage

The measured reduction reflects the complete implementation, not merely the row buffer. At full coverage the compact cache still retains state for distinct keys. “Bounded row scheduling” does not mean constant total memory for every possible configuration space.

A subtle cost remains.

The compact implementation samples each logical row during planning and again during original-order reduction. It applies costs and updates winners for every row. These operations become dominant after the score cache saturates; they are not erased by the SIMD kernel.

CHECK YOUR MODEL

Why is “only 44,560 mixed payloads” not the same as “only 44,560 logical score keys”?

07 / CHOOSE THE SIMD AXIS

Eight jobs.
One timeline.

AVX-512 gives eight FP64 lanes. The engineering question is what a lane should represent—not merely whether wide registers exist.

TEMPTING AXIS

Eight consecutive bars.

Comparisons vectorize naturally. But the equity product and category sums reduce across time. Reordering those floating-point reductions can change results. Vector width does not remove the temporal dependency.

CHOSEN AXIS

Eight independent score jobs.

Each lane carries its own threshold and rule, for the same fitted model. Broadcast one prediction and price row to all lanes. Advance through bars sequentially inside every lane.

This shares input loads while preserving each job’s chronological arithmetic. Category updates target separate lane-owned accumulators, avoiding several lanes scattering into the same four scalar sums. It creates useful parallel work without a horizontal reduction across time.

LAB / STEP THROUGH THE VECTOR12-BAR TEACHING FIXTURE

Each column is an independent score job. Signal uses the current prediction; position uses the previous signal and the current bar’s tradability. Active lanes retain separate state.

Why the first AVX-512 kernel tied AVX2.

Batching required both the same model and the same rule. Many groups did not fill eight lanes. With only 52.7% useful AVX-512 lanes, the first wide kernel’s median was 83.4 ms, essentially the same as the 83.6 ms AVX2 version.

Historical C prototype groupingAVX2 useful lanesAVX-512 useful lanesAVX-512 median
Same model, same rule73.9%52.7%83.4 ms
Same model, mixed rules94.5%88.3%60.3 ms

Allowing different rules within the same-model batch increased lane utilization. A per-lane sign transform handles less-than rules; an absolute-value mask handles absolute rules; an inclusive mask adds equality cases. The final Rust kernel carries the same idea.

The prototype language is not the final language.

The early x86 environment had C compilers but no Rust toolchain. A C reference enabled an exploratory SIMD experiment; it was separately checked against the original Rust scorer on the Mac. That experiment measured kernels, not the full Rust runner. The integrated pipeline later replaced that bridge with Rust std::arch::x86_64 intrinsics. There is no C scoring implementation in the final runtime.

Build for the verified instruction set.

The original Mac is ARM64; it cannot natively execute this x86 AVX-512 code. The integrated AVX-512 build targets x86-64 Linux with Rust 1.89 or newer. Runtime dispatch checks AVX-512F, and also BMI1 for the authored assembly. Unsupported levels fail rather than silently falling back. The Linux assembly ABI was not ported to x86 macOS or Windows.

CHECK YOUR MODEL

Why allow different rules within a same-model SIMD batch?

08 / WRITE THE LAST INSTRUCTIONS

Make the incremental
claim real.

“AVX-512” does not mean “handwritten assembly.” The final claim requires an authored kernel and an A/B that changes only that kernel.

Do not compare against a convenient weak baseline.

The first handwritten variant looked faster than the early intrinsics implementation. Further intrinsics tuning recovered much of that gap. The standalone study compared multiple intrinsics formulations under GCC and Clang before selecting the strongest tested candidate.

“Strongest tested” is deliberately narrower than “the best intrinsics implementation possible.” The evidence does not prove assembly is inherently faster or that a compiler could never generate an equivalent schedule.

CODE WALK / THE AUTHORED KERNELACTUAL COMMITTED SOURCE

The actual integration boundary.

RUST LINKS BOTH KERNELS INTO ONE EXECUTABLE
core::arch::global_asm!(
    include_str!("score8_gpr.S"), options(raw)
);

let kernel: Kernel = if assembly {
    score8_asm_gpr
} else {
    score8_rust_intrinsics
};

Both functions receive the same packed thresholds, sign/absolute-value masks and price view. They write the same output layout. Grouping, packing, caching, cost adjustment and summary reduction stay in the same Rust pipeline. The extern "C" notation specifies a calling convention; it does not introduce a C implementation.

Three numbers that must not be confused.

STANDALONE · INTEL 8573C

1.070×

54.547 → 50.997 ms. Approx. 7% more scoring throughput, or 6.51% less time. The C-wrapper kernel experiment; not yet Rust end-to-end.

INTEGRATED · INTEL 8370C

1.0406×

770.530 → 740.476 ms. Ratio of medians for 16 full-process pairs. Assembly wins 12/16. The interval reaches effectively no whole-process gain.

1B SCALE · AMD 9V74

≈0.60%

98.8745 → 98.2869 s in one pair of full runs. Too little replication to establish a durable assembly-specific gain at this scale.

These are separate experiments, on different guests and scopes. They are not three factors to multiply. Their common lesson is that the end-to-end benefit depends on how much time still belongs to the optimized kernel.

What the assembly controls.

It explicitly assigns vector accumulators, keeps position-state masks in 32-bit general-purpose registers, transfers masks into AVX-512 mask registers, and schedules Boolean work alongside floating-point accumulation. It preserves separate multiplies and adds and chronological reduction within each lane. No FMA substitution, reduced precision or fast-math explains the gain.

CHECK YOUR MODEL

A kernel goes from 54.55 ms to 51.00 ms. What does “7% faster” mean here?

09 / PROVE THE CLAIM

A faster wrong answer
is still wrong.

Correctness is a hierarchy of claims. A golden summary, bitwise agreement, and economic equivalence are different tests.

01

Same input identity

Hash the frozen matrices, configuration, source and executable. A filename alone is not a reproducibility contract.

02

Prediction and signal checks

Matching a rounded MAE or positive-signal count does not prove equal prediction arrays or equal signal positions. The integrated matched grid exported predictions: maximum observed difference 4.156 × 10⁻¹³, with all six complete sign vectors equal.

03

Complete intermediate results

A BaseScore contains eight integer fields and nine floating-point fields. Compare integer values and FP64 bit patterns, not only the final winners.

04

Full output and boundary behavior

Validate stable JSON, failure counts, rounded ties, strict/inclusive thresholds, signed zero, tail lanes, prefixes and tradability masks. Cross the 1,048,576-row block boundary.

05

Know the claim that still fails

Original-versus-optimized Rust equivalence does not establish current Limen backtest equivalence. Different economic conventions remain different even when model predictions agree.

3,364,062complete BaseScores checked per SIMD path at scale
17fields compared exactly per result
138,240Rust boundary comparisons on the scaling host

The large validation runs deliberately recompute scalar scores. They happened after the timed scaling runs and are excluded from the timing table. Exhausting this retained finite score-key universe is strong evidence for that workload, not a proof for every future input.

Measurement is also part of correctness.

Keep a ledger of boundaries.

Whole-process: launch, imports or input reading, computation, writes, exit. Internal timer: only the explicitly delimited stages. Kernel experiment: its stated grouping/packing/scoring scope. Never silently divide one by another.

Keep inconvenient observations.

Short-run stage times are not monotonic. Shared-VM outliers remain. An early timeout-wait pilot biased process timing and was excluded as a whole protocol for every variant, not cherry-picked per winner.

Claim clinic

Classify each sentence. “Unsupported” does not mean the code is bad; it means the sentence asks the evidence to establish something it did not test.

The benchmark is not a trading-quality result.

The optimization studies measure execution and agreement with a retained computational contract. They do not establish profitability, predictive generalization, data quality across markets, or live trading performance.

10 / EXPLORE THE REVERSE FUNNEL

Every level needs
its own denominator.

Inspect the actual ablations. One study isolates the reuse levels; another measures the complete million-row pipeline. Neither needs a manufactured monotonic story.

EXPLORER / INTEGRATED RUST EXPERIMENTINTEL XEON 8370C

The clean factorization comparison is within Rust.

On the 1,014-row grid, turning statistics, prediction and score reuse on reduces the internal timer from 511.384 ms to 4.440 ms: 115.18×. The prepared input and Rust scoring/output contract stay the same.

The full native CLI median of 31.280 s divided by the original cached Rust process median of 28.887 ms gives about 1,083×. That ratio includes differences in preparation, orchestration, metrics and artifacts. It is not a 1,083× solver gain.

WHY THE LAST STAGES PLATEAU

Six models. Six paths.

All 1,014 rows collapse to six fits and six scoring paths. Each model supplies only one scoring job, leaving most SIMD lanes unused. Only six path evaluations remain after caching. Startup and scheduling dominate the final differences.

The input also has 1,430 positive predictions out of 1,431 for each native model. That observed property limits how well this grid represents a varied scoring workload.

The million-row study tests the later optimizations.

On the original 55-feature workload, the integrated pipeline’s five-stage process median falls from 6.942 s to 0.758 s—9.16× versus original Rust on that host. The dedicated assembly A/B uses separate paired runs and reports its own median, not a substituted value from the five-stage table.

That distinction explains why you will see 0.758 s in the multi-stage study and 0.740 s in the paired assembly study. They are measurements from different protocols, not interchangeable cells.

CHECK YOUR MODEL

Can you multiply the 1,083× native-grid ratio by the 9.16× million-row Rust ratio?

11 / SCALE THE EXPERIMENT

Watch the multiplier
grow—and flatten.

Twenty-five actual Rust processes, 100k through 1b sampled rows. Only the large native-reference runtimes are inferred.

EXPLORER / 5,555,500,000 ACTUAL RUST ROW EVALUATIONSAMD EPYC 9V74

Every plotted Rust point is a fresh-process measurement with empty computational caches. One run per stage/size; no outliers removed. Lines connect observations for readability, not to invent measurements between them. OS file caches were not flushed.

The growth is real. The denominator is modeled.

The same-matrix native Ridge reference was calibrated with 256 and 2,048 evaluations, twice each, using a fresh sklearn fit and native metrics every time. Its fitted reference-cost model is:

TLimen prepared(N) = 0.120492 + 0.006253191N seconds

That intercept belongs to the prepared-loop calibration, not Python/import startup. Those overheads are excluded from the prepared reference’s loop timing, while every plotted Rust denominator includes its whole process. The full native CLI reference includes its entire process but uses a separate 13-feature workflow, not the original 55-feature matrices.

At 1b, the measured assembly process is 98.286879 s. The projected same-matrix native Ridge cost is about 72.37 days, giving about 63,622×. This is explicitly a projected reference-cost multiplier; native signal rules and solver-failure contracts are not replaced with the Rust scorer.

The large native jobs were not run.

Linearity is an assumption requested for this study. Short-run calibration variability and long-run memory, artifact I/O and scheduler effects are not resolved by a straight line. The two prepared-native repetitions imply slopes of about 5.897 and 6.609 ms/row. The chart uses the recorded central model, not a confidence guarantee.

Cache saturation explains the shape.

The 1,677 successful training keys each have 2,006 rule/threshold possibilities: 4 × 401 + 2 × 201. The valid base-score-key ceiling is therefore 3,364,062. It is already reached at 100m rows in this sample. At 1b, about 99.54% of valid rows reuse a base score.

TRust(N) ≈ fixed training + c · unique scores(N) + dN

This is an explanatory structural model, not a substitute for the actual Rust timings. Once unique scores stop increasing, the remaining per-row term still grows. The multiplier approaches a ceiling; it does not become infinite.

The last bottleneck has moved again.

Planning, sampling and cache lookup at 1b53.805 s
Costs and summary reduction44.016 s
Mixed scoring, grouping and packing0.336 s

The scoring kernel’s phase is now only 0.342% of whole-process time. The native-relative multiplier can grow while the intrinsics and handwritten curves converge. Assembly has little opportunity to help after its work is mostly reused.

LAB / WHERE CAN THE NEXT SPEEDUP COME FROM?AMDAHL CALCULATION
Swhole = 1 / [(1 − p) + p / s]

This is a calculation using a chosen target share and speedup, not a new measurement. It assumes all other work remains unchanged. At p = 100%, the infinite-kernel limit is unbounded in the mathematical model.

CHECK YOUR MODEL

Why can original Rust catch up to the optimized scorer as N becomes huge?

12 / CLOSE THE LOOP

From a result
to a reproducible record.

The investigation is not complete when a chart exists. The code, data, environment, validation, limits and replay path must survive outside the working session.

The Git handoff is the durable boundary.

The original source is preserved as baseline-2026-05. The integrated runtime is commit 70525ba. The verified experiment snapshot is benchmark-handoff-2026-09-24 at 2e549d4, including reports, raw records, archives and integrity checks. This course is an additive teaching layer; it does not revise those measurements.

Open the evidence, then replay deliberately.

The repository keeps readable reports in benchmarks/reports/, original experiment bundles in benchmarks/archives/, earlier prototypes and the C oracle in benchmarks/mac-history/, and handoff checks in benchmarks/handoff/. Compiler installers, Python environments and duplicate clean worktrees are rebuildable dependencies, not the unique research record.

VERIFY THE PRESERVED EVIDENCE
git clone https://github.com/mikkokotila/Terasweep.git
cd Terasweep
python3 scripts/verify_evidence.py

# Use a separate clean checkout for the original snapshot:
git worktree add ../Terasweep-baseline baseline-2026-05

The repository is private; access uses your existing GitHub authorization. Nothing in this lesson bypasses that requirement.

RUN THE INTEGRATED LEVELS · DISTINCT OUTPUT DIRECTORIES
make build
make run LEVEL=compact RUNS=1000000 OUT=runs/lesson-compact

# On supported x86-64 Linux with Rust 1.89+:
make run LEVEL=intrinsics RUNS=1000000 OUT=runs/lesson-intrinsics
make run LEVEL=assembly RUNS=1000000 OUT=runs/lesson-assembly
make test
TERASWEEP_CHECK_BASE=1 make verify LEVEL=assembly

Do not include TERASWEEP_CHECK_BASE=1 in performance measurements: it recomputes the oracle. make verify creates a fresh output directory. make run writes to the selected output path, so choose a new path when retaining observations. The bare executable defaults to score; the Makefile defaults to compact. Unsupported SIMD selections fail rather than posing as assembly runs.

The end-to-end method

Freeze the contract→Factor dependencies→Profile→Remove redundant work→Compact the state→Choose SIMD lanes→Schedule instructions→Validate and scale→Commit the evidence

That order matters. Handwritten assembly is a final, specific intervention—not the explanation for the huge native-relative multiplier. The large ratio largely reflects avoiding repeated work. The instruction-level increment is real only to the extent that an appropriately controlled A/B measures it.

CAPSTONE / WRITE THE CLAIM YOU WOULD SIGNSYNTHESIS

Write a short results paragraph that includes the actual billion-row time, its sampled-row meaning, the native projection boundary, the assembly-specific limit, and one reproducibility detail.

Compare with a defensible synthesis

On a single pinned CPU in the recorded AMD EPYC 9V74 VM, the integrated Rust/handwritten-assembly pipeline processed one billion sampled rows in 98.286879 seconds. This includes cached failed-fit rows and is not one billion independent model fits. A short-run linear native Ridge cost model on the same matrices implies approximately 63,622× relative throughput; that native large run was not executed, and the scoring contracts differ. The one-pair intrinsics/assembly difference at this scale is not an established assembly-specific gain. Earlier paired integration measurements support a small, noisy whole-pipeline increment. Source, frozen inputs, validation records and replay scripts are preserved in the benchmark handoff snapshot.

What remains open—not what was silently solved.

The record does not establish complete current-Limen/Terasweep economic equivalence, a universal assembly advantage, linear native billion-row feasibility, live trading quality, or unlimited scaling. At saturation, sampling, lookups, costs and reduction are the obvious measured targets to investigate next; accelerating them is future work, not part of these results.

First change how much work exists.
Then change how fast you execute what remains.
Open the verified Git snapshot ↗

The evidence room

RETAINED REPORT / CODE SNAPSHOT

Pinned Git source ↗

The working vocabulary

Definitions as used in this investigation. Technical contracts live in the source and evidence room.

Find a concept