Bet 3: schedules: speed without touching meaning
Claim. You can write a numeric kernel once, as plain math, and make it fast in a separate file that cannot change what the program computes. (This is Halide's idea, applied to a general-purpose language.)
Kill criterion (CHARTER.md). Matmul demo: a layout change plus vectorization gives byte-identical output and a measured speedup. Result: passed.
What the programmer writes
# kernels.tr: meaning only
fn matmul(a, b):
let n = len(a)
let k = len(b)
let m = len(b[0])
grid(n, m, fn(i, j) => sum(k, 0.0, fn(t) => a[i][t] * b[t][j]))
# kernels.sched: speed only (picked up automatically by `trine build`)
matmul:
layout b: transposed # rows | flat | transposed
order i t j # any permutation of the loop variables
tile i 32, j 128
vectorize j 4 # widths 2, 4, 8
grid and sum are ordinary pure builtins. They run unchanged in the interpreter and the VM. The schedule only affects native builds.
Why results cannot change
- Only pure, total kernels are accepted. The body must be Float arithmetic plus indexing by loop variables, with no calls, no effects and nothing that can fail midway. Any other body gets the reference code, and the reason is printed.
- Guarded specialization. The compiled kernel first checks shapes at run time: the matrices must be rectangular, the extents must agree, and every index must be in range. If any check fails, the call falls back to the generic
rt_grid. Wrong-shaped input therefore fails with the interpreter's exact error message and location. - The reduction order is fixed. Each output element still sums
t = 0, 1, …, k-1frominit, in that order. Floating-point addition is not associative, so a schedule may reorder which element is computed when, but never the order of additions inside an element. Vectorization runs acrossj, which means separate elements, never acrosst. The C compiler is run with-ffp-contract=off, so it cannot fuse multiply-adds either. - Invalid schedules are rejected, not guessed. Examples: an order that isn't a permutation of the loop variables, a vector width other than 2/4/8, vectorizing
t, or a layout for a name that isn't a matrix the kernel indexes. Each is reported withschedule f: NOT applied (reason), and the reference code runs instead.
Evidence
- Schedule fuzzer (
tools/sched_fuzz.py). It draws random matrix shapes, including empty and wrong ones, and random schedules (layouts, orders, tiles, widths), then compares each native build with the interpreter byte for byte. Over 1,500 trials all matched, including the bad-shape cases, which fell back and failed identically. - It caught one real bug: whentwas innermost, the emitter generated the reduction loop twice. That did k-fold redundant work and gave wrong output fork = 0. Fixed, and the 40-trial run is now part ofcargo test(bet3_schedules_never_change_results). - Rejection test (
bet3_invalid_schedules_are_rejected_safely). Bad schedules are reported and the program output is unchanged. - Golden test.
examples/kernels.schedis applied by the native golden test: identical output, 0 leaked objects.
Speed (matmul, Float, this machine; all outputs byte-identical)
n = 512:
| variant | time | vs reference |
|---|---|---|
reference grid/sum (closure per element) | 3.753 s | 1× |
| same algorithm as imperative loops | 0.740 s | 5.1× |
| compiled kernel, empty schedule | 0.164 s | 23× |
order i t j + vectorize j 4 | 0.079 s | 48× |
layout b: transposed | 0.100 s | 38× |
tiled + flat + vectorize j 8 | 0.097 s | 39× |
tiled + -march=native | 0.056 s | 67× |
naive Rust (triple loop, Vec<Vec<f64>>) | 0.180 s |
n = 1024:
| variant | time |
|---|---|
| compiled kernel, empty schedule | 1.469 s |
order i t j + vectorize j 4 | 0.639 s |
| tiled | 1.123 s |
order i t j + -march=native | 0.454 s |
tiled + -march=native | 0.648 s |
| naive Rust | 1.950 s |
A one-line schedule beats a naive Rust triple loop by 2.3–3×, from the same source that runs in the interpreter.
Honest notes
- Tiling hasn't paid off yet. With the default SSE2 target and these sizes, the
i t jorder already streams rows ofbandoutthrough the cache well. The tiled loop nest then costs more than the locality it adds. Tiling should matter once register blocking exists (severalirows per pass) or for sizes far beyond L2. That is future work, not a claim. - Coverage is narrow on purpose. The schedule applies to the first
gridin a function, whose body is a Float expression over 1-D and 2-D indexing, optionally with onesum. This is enough to test the bet. Widening it (stencils, multiple stages,compute_at) is roadmap work. - The reference path is slow because of closures, not refcounting. Bet 3 also motivated two general improvements that apply to all code: - element reads from borrowed parameters now borrow; - closures handed straight to
grid/sumborrow their environment ("lent closures").
On bench/matmul_kernel.tr, Perceus now removes 99.5% of refcount overhead, and the small kernels.tr goes from 50% to 100%.