Mapal

A language exposition

Describe how data flows. Mapal places it where it runs best.

A Mapal program states each value and what it is made from — never threads, kernels or where data lives. The compiler matches that flow to the machine in front of it and places every step where it runs best: on CPUs and NVIDIA GPUs today, and on any hardware by design.

On the right: a dense layer. Below it, what it became. Every number on this page was produced by the real compiler when the page was built.

// A dense layer: a matrix product, a bias and a ReLU. What to compute, not how.
64 -> n;

fn main() {
    "dense-a.bin" -> read -> a: [f32; n * n];
    "dense-b.bin" -> read -> b: [f32; n * n];
    n -> iota -> along;
    n * n -> iota -> map {
        c ->
        c / n -> row;
        c % n -> column;
        (0.0, along) -> fold {
            sum, k -> sum + a[row * n + k] * b[k * n + column]
        } -> dot;
        (dot + 1.0 > 0.0) -> {
            -true-> dot + 1.0;
            -false-> 0.0;
        }
    } -> out;
    out[0] -> println;
    out[n * n - 1] -> println;
}
A dense layer — docs/exposition/dense.mapal, 22 lines

What it becomes

1

It runs and prints two numbers: the first and the last cell of the result, a matrix product of two matrices read from files, plus one, with negatives set to zero.

Output mapal run --target=zen3 dense.mapal (native CPU run)
3136
0
2

The flow you wrote, as the compiler's own graph holds it, drawn in the two standard notations for it:

Steps are boxes and values are wires: a product is just several wires entering one box, and a value read twice splits at a Δ.

The default form mapal dump-ir --mermaid dense.mapal

map over cells (uses a, b, along)

cell: i32

cell: i32

① a: [f32; 4096]

② b: [f32; 4096]

③ along: [i32; 64]

out: [f32; 4096]

out

out

ret: f32

④ row: i32

⑤ column: i32

dot: f32

read "dense-a.bin"

read "dense-b.bin"

iota

out[0] · println

out[n * n - 1] · println

Δ out

+ · guard

÷

in

mod

in

a[row * n + k] ; b[k * n + column] ; fold

ret

map over cells (uses a, b, along)

cell: i32

cell: i32

① a: [f32; 4096]

② b: [f32; 4096]

③ along: [i32; 64]

out: [f32; 4096]

out

out

ret: f32

④ row: i32

⑤ column: i32

dot: f32

read "dense-a.bin"

read "dense-b.bin"

iota

out[0] · println

out[n * n - 1] · println

Δ out

+ · guard

÷

in

mod

in

a[row * n + k] ; b[k * n + column] ; fold

ret

Open in mermaid.live

3

At the full size the compiler turned the whole computation into one GPU kernel, computing the product in 8 × 16 tiles (compile only, for an RTX 5080). The same source also runs on the CPU, as the output above.

Show the compiler output

For readers who want the facts behind those two lines: the graph the compiler built (operation counts, before and after its rewrites), the kernel it chose for an RTX 5080 at 2048 by 2048, and the instructions it emitted.

The graph mapal dump-ir --stage=lowered|rewritten dense.mapal
values (objects)   lowered   85   rewritten   82
Map                lowered    1   rewritten    1
Fold               lowered    1   rewritten    1
Index              lowered    4   rewritten    4
Phi                lowered    1   rewritten    1
all operations     lowered   94   rewritten   90
What the compiler derived mapal build --emit-only --target=rtx-5080, sizes scaled: n=2048
compile-time evaluation: 0 values embedded as constants, 2 left to compute at run time
rewriting: 2 rounds, 2 ConstFold, 1 Dce
1 device kernel(s):
kind=tile rows=2048 c=2048 k=2048 grid=16x16 block=128 tile=8x16 bk=16 stages=1 smem=16640
Generated code the emitted PTX for rtx-5080
  2048  fused multiply-adds            e.g. fma.rn.f32
    16  global loads                   e.g. ld.global.nc.v2.b64
    32  global stores                  e.g. st.global.v4.b32
    96  shared-memory loads            e.g. ld.shared.v4.b32
    20  shared-memory stores           e.g. st.shared.b32
     2  barriers                       e.g. bar.sync
  2671  instructions in the module

the first fused multiply-adds, as emitted:
    fma.rn.f32 	%r65, %r41, %r49, %r2733;
    fma.rn.f32 	%r66, %r41, %r50, %r2732;
    fma.rn.f32 	%r67, %r41, %r51, %r2731;
    fma.rn.f32 	%r68, %r41, %r52, %r2730;
    fma.rn.f32 	%r69, %r41, %r53, %r2729;
    fma.rn.f32 	%r70, %r41, %r54, %r2728;

1Programs, and what the compiler makes of them

Eight small programs and a piece of a language model. Each shows the code, its real output, and what the compiler derived. Their inputs are small files read at run time (docs/exposition/data/), so the compiler cannot just compute the answer; two keep constants on purpose. Outputs come from the reference interpreter (the oracle) and carry the bound the language proves for each float.

Three steps over every sample

Scale, shift, clip. Each map says its cells are independent; nothing says "loop".

// Three steps over every sample: scale, shift, clip below zero. Each `map` says its cells are independent.
1024 -> samples;

fn main() {
    "signal.bin" -> read -> signal: [f32; samples];
    signal -> map {
        v -> v * 0.25
    } -> scaled;
    scaled -> map {
        v -> v - 100.0
    } -> shifted;
    shifted -> map {
        v -> (v > 0.0) -> {
            -true-> v;
            -false-> 0.0;
        }
    } -> clipped;
    (0.0, clipped) -> fold {
        sum, v -> sum + v
    } -> total;
    clipped[samples - 1] -> println;
    total -> println;
}
pipeline — docs/exposition/pipeline.mapal, 23 lines
Output mapal run --interp pipeline.mapal; ± is the composed bound, --bound
155.75   ± 4.91e-05
48594   ± 21.2
What the compiler derived mapal build --emit-only --target=rtx-5080
compile-time evaluation: 0 values embedded as constants, 0 left to compute at run time
rewriting: 3 rounds, 4 MapFusion
no device kernel: nothing here is placed on the device

The signal comes from a file, so nothing is known before the run and nothing is folded (the report counts zero embedded values). It is also one pass over data that arrives in host memory: copying it to a GPU would cost more than computing it where it is, so no device kernel is made. The attention demo below does far more work per byte and does get one.

A fold says how values combine, not in what order

The length of a vector. A fold is a reduction the compiler may split into lanes and a tree.

// The length of a vector: a fold says how values combine, not in which order.
4096 -> length;

fn main() {
    "vector.bin" -> read -> v: [f32; length];
    (0.0, v) -> fold {
        sum, x -> sum + x * x
    } -> squares;
    squares -> sqrt -> norm;
    norm -> println;
}
norm — docs/exposition/norm.mapal, 11 lines
Output mapal run --interp norm.mapal; ± is the composed bound, --bound
186.60118   ± 0.0457
What the compiler derived mapal build --emit-only --target=rtx-5080
compile-time evaluation: 0 values embedded as constants, 0 left to compute at run time
rewriting: 1 rounds, nothing to change
no device kernel: nothing here is placed on the device

The vector is read from a file, so the sum is computed at run time; like the signal above it is a single pass over host data and stays on the CPU. Correctness is the flow plus a stated bound, not bit-identity: the result carries a proven error bound (the ±), and inside it the compiler orders the sum however is fastest for the target.

Softmax, in the order you would explain it

A maximum, exponentials, a total, a division. This is the program from the README, unchanged.

// softmax: turn scores into probabilities that add up to 1.
fn softmax<n>(scores: [f32; n]) -> [f32; n] {
    n -> iota -> positions;
    (scores[0], positions) -> fold {
        top, i -> (scores[i] > top) -> {
            -true-> scores[i];
            -false-> top;
        }
    } -> largest;
    positions -> map {
        i -> scores[i] - largest -> exp
    } -> weights;
    (0.0, positions) -> fold {
        sum, i -> sum + weights[i]
    } -> total;
    positions -> map {
        i -> weights[i] / total
    } -> ret;
}

fn main() {
    [1.0, 2.0, 3.0, 4.0] -> softmax -> probabilities;
    probabilities[0] -> println;
    probabilities[1] -> println;
    probabilities[2] -> println;
    probabilities[3] -> println;
}
softmax — examples/softmax.mapal, 27 lines
Output mapal run --interp softmax.mapal; ± is the composed bound, --bound
0.032058604   ± 7.83e-08
0.08714432   ± 2.04e-07
0.23688284   ± 4.86e-07
0.6439143   ± 8.21e-07
What the compiler derived mapal build --emit-only --target=rtx-5080
compile-time evaluation: 6 values embedded as constants, 1 left to compute at run time
rewriting: 1 rounds, nothing to change
no device kernel: nothing here is placed on the device

softmax<n> works for any length: the size n is inferred at the call and stays in the type, so every fact sees the exact extent. This demo keeps its four numbers written in the source on purpose: with no run-time input the compiler computes the whole answer itself and embeds it as constants, as the report shows. The other demos read their inputs from files in docs/exposition/data/, so their reports show real work.

Attention for one head: five steps, one kernel

Scores, a row maximum, exponentials, a row total, a weighted sum. Written as five separate steps.

// Attention for one head: scores, a softmax over each row, a weighted sum of the values.
16 -> tokens;
8 -> width;

fn main() {
    tokens * width -> iota -> cells;
    "query.bin" -> read -> query: [f32; tokens * width];
    "key.bin" -> read -> key: [f32; tokens * width];
    "value.bin" -> read -> value: [f32; tokens * width];
    width -> iota -> dims;
    tokens -> iota -> positions;
    width -> widen<f32> -> sqrt -> scale;
    tokens * tokens -> iota -> map {
        cell ->
        cell / tokens -> i;
        cell % tokens -> j;
        (0.0, dims) -> fold {
            sum, d -> sum + query[i * width + d] * key[j * width + d]
        } -> dot;
        dot / scale
    } -> scores;
    positions -> map {
        i -> (-1000000000.0, positions) -> fold {
            best, j -> scores[i * tokens + j] -> s;
            (s > best) -> {
                -true-> s;
                -false-> best;
            }
        }
    } -> maximum;
    tokens * tokens -> iota -> map {
        cell -> scores[cell] - maximum[cell / tokens] -> exp
    } -> weights;
    positions -> map {
        i -> (0.0, positions) -> fold {
            sum, j -> sum + weights[i * tokens + j]
        }
    } -> total;
    cells -> map {
        cell ->
        cell / width -> i;
        cell % width -> d;
        (0.0, positions) -> fold {
            sum, j -> sum + weights[i * tokens + j] * value[j * width + d]
        } -> mixed;
        mixed / total[i]
    } -> out;
    (0.0, out) -> fold {
        sum, v -> sum + v
    } -> checksum;
    out[0] -> println;
    checksum -> println;
}
attention — docs/exposition/attention.mapal, 53 lines
Output mapal run --interp attention.mapal; ± is the composed bound, --bound
1.9652196   ± 3.81e-05
5.6616716   ± 0.00292
What the compiler derived mapal build --emit-only --target=rtx-5080, sizes scaled: tokens=4096,width=64
compile-time evaluation: 1 values embedded as constants, 5 left to compute at run time
rewriting: 2 rounds, 8 ConstFold, 4 Dce
1 device kernel(s):
kind=flow rows=4096 steps=5 grid=1024 block=128 smem=43552 windows=128

At 4096 tokens the kind=flow kernel carries all five steps. There is no "fusion" pass: each row block's footprint fits on chip, so the scores and weights never reach memory and the kernel streams the keys and values in windows. The output above is the same program at 16 tokens, where the interpreter finishes.

State carried through a loop

Heat spreading along a rod. u is a new array each step; the old one dies when the new one is made.

// Heat spreading along a rod: state carried through a loop, one new array per step.
64 -> points;
100 -> steps;

fn main() {
    "rod.bin" -> read -> start: [f32; points];
    mut u: [f32; points] <- start;
    mut step: i32 <- 0;
    loop {
        (step < steps) -> {
            -true-> {
                points -> iota -> map {
                    i -> (i > 0 && i < points - 1) -> {
                        -true-> u[i] + 0.25 * (u[i - 1] - 2.0 * u[i] + u[i + 1]);
                        -false-> 0.0;
                    }
                } -> u;
                step + 1 -> step;
                -> loop;
            }
            -false-> u -> final;
        }
    }
    final[points / 2] -> println;
    final[points / 2 + 8] -> println;
}
heat — docs/exposition/loop.mapal, 26 lines
Output mapal run --interp loop.mapal; ± is the composed bound, --bound
5.6348486   ± 0.000121
2.9786952   ± 6.22e-05
What the compiler derived mapal build --emit-only --target=rtx-5080, sizes scaled: points=4194304
compile-time evaluation: 2 values embedded as constants, 1 left to compute at run time
rewriting: 2 rounds, 1 Cse
1 device kernel(s):
kind=cell work=1

The loop is the only cycle in the graph. Its body, one map over the rod, becomes one cell kernel; the start state is a generator kernel. Death points (last_use_plan) say when each step's array dies.

One function for every length

mean<n> is generic in a size, not in a type; each call fixes n.

// One function for every length: the size is inferred at each call.
fn mean<n>(x: [f32; n]) -> f32 {
    (0.0, x) -> fold {
        sum, v -> sum + v
    } -> total;
    n -> widen<f32> -> count;
    total / count -> ret;
}

fn main() {
    [1.0, 2.0, 3.0, 4.0] -> small: [f32; 4];
    1000 -> iota -> map {
        i -> i -> widen<f32>
    } -> large;
    small -> mean -> println;
    large -> mean -> println;
}
generic — docs/exposition/generic.mapal, 17 lines
Output mapal run --interp generic.mapal; ± is the composed bound, --bound
2.5   ± 1.49e-06
499.5   ± 0.0596
What the compiler derived mapal build --emit-only --target=rtx-5080
compile-time evaluation: 2 values embedded as constants, 2 left to compute at run time
rewriting: 2 rounds, 2 ConstFold
no device kernel: nothing here is placed on the device

Each call is instantiated with its own extent, 4 and 1000; the compiler checks the sizes, not a type. Its inputs are constants here, so the report shows them computed at compile time.

Data from a file

Raw little-endian values, typed by the binding: "readings.bin" -> read -> hourly: [f32; 24].

// Data comes from a file: raw little-endian values, typed by the binding.
fn main() {
    "readings.bin" -> read -> hourly: [f32; 24];
    (0.0, hourly) -> fold {
        sum, t -> sum + t
    } -> total;
    (-1000.0, hourly) -> fold {
        best, t -> (t > best) -> {
            -true-> t;
            -false-> best;
        }
    } -> warmest;
    "mean " -> print;
    total / 24.0 -> println;
    "max  " -> print;
    warmest -> println;
}
read — docs/exposition/read.mapal, 17 lines
Output mapal run --interp read.mapal; ± is the composed bound, --bound
mean 13.999999   ± 4.17e-05
max  22   ± 0
What the compiler derived mapal build --emit-only --target=rtx-5080
compile-time evaluation: 0 values embedded as constants, 0 left to compute at run time
rewriting: 1 rounds, nothing to change
no device kernel: nothing here is placed on the device

Here the compiler folds nothing: the values come from a file, so the dataflow has a run-time input and the work stays at run time. Compile-time evaluation is inferred from the graph, never annotated (const does not exist).

One source, three machines

A linear layer with bf16 weights, fold: bf16 | f32: the products may run in bf16 with f32 accumulation. Compiled for three GPU profiles, never run here.

// A linear layer with bf16 weights: out[t][row] = sum over columns of weight[row][column] * x[t][column].
4 -> tokens;
8 -> rows;
16 -> columns;

fn main() {
    "weight.bin" -> read -> weight: [bf16; rows * columns];
    "activations.bin" -> read -> x: [f32; tokens * columns];
    columns -> iota -> along;
    tokens * rows -> iota -> map {
        cell ->
        cell / rows -> t;
        cell % rows -> row;
        (0.0, along) -> fold: bf16 | f32 {
            sum, column -> weight[row * columns + column] -> widen<f32> -> w;
            sum + w * x[t * columns + column]
        }
    } -> out;
    (0.0, out) -> fold {
        sum, v -> sum + v
    } -> checksum;
    out[0] -> println;
    checksum -> println;
}
projection — docs/exposition/projection.mapal, 24 lines
Output mapal run --interp projection.mapal; ± is the composed bound, --bound
1.9277344   ± 7.81e-06
-46.90625   ± 0.00187
One source, three machines mapal build --emit-only --target=<profile>, sizes scaled: tokens=128,rows=4096,columns=4096
profilekindopgridblockbkstagessmemblocks per sm
rtx-5080mmam16n8k16.bf1664x2256323460802
rtx-3090mmam16n8k16.bf1664x2256323460802
h100wgmmam64n32k16.bf16128x225625621638881

The source is identical. The matrix instruction, tile, pipeline depth and shared memory differ because the machines' physical properties differ, not because of a branch on the chip's name. Where a rule loses on some part, the project treats it as a missing hardware property to add.

A piece of Llama-3.2-1B

RMSNorm, as it is in the model: the whole of examples/llama.mapal is 403 lines, weights read from a file.

// RMSNorm of each vector: x / sqrt(mean(x^2) + epsilon), times a learned gain per feature.
fn rms_norm<tokens>(x: [f32; tokens * hidden_size], gain: [bf16; hidden_size]) -> [f32; tokens * hidden_size] {
    hidden_size -> iota -> features;
    hidden_size -> widen<f32> -> width;
    tokens -> iota -> map {
        t -> (0.0, features) -> fold {
            sum, i -> sum + x[t * hidden_size + i] * x[t * hidden_size + i]
        }
    } -> sum_of_squares;
    tokens * hidden_size -> iota -> map {
        cell ->
        sum_of_squares[cell / hidden_size] / width + rms_epsilon -> sqrt -> root;
        gain[cell % hidden_size] -> widen<f32> -> g;
        x[cell] * (1.0 / root) * g
    } -> ret;
}
Whole model, compile only mapal build --emit-only --target=rtx-5080 examples/llama.mapal
compile-time evaluation: 9 values embedded as constants, 58 left to compute at run time
rewriting: 17 rounds, 54 Inline, 2 Unroll, 1888 ConstFold, 394 Cse, 829 Dce
64 device kernels:
  33  flow
  17  cell
   6  mma
   4  hz
   2  reduce
   2  tile
the 33 flow kernels each carry several steps (130 steps in all)

The model compiles to a few dozen kernels, about half of them flow kernels carrying several steps each, with the weights kept in bf16. The full source is in In depth and in examples/llama.mapal; a run needs the weights file and a GPU, so no output is shown here.

2Performance

Where Mapal is faster and where it is slower, by kind of problem, each against the best library or compiler at the same precision. Blue is Mapal faster, red slower. Every chart is drawn from the repository's measurement files when the page is built.

On GPUs: six kinds of problem

Five NVIDIA GPUs, 119 programs timed on every one. Against cuBLAS, cuBLASLt, CUTLASS, PyTorch eager and torch.compile, FlashAttention, Triton and hand-written CUDA.

Mapal against the best library or compiler, by kind of problem Geomean of Mapal time divided by the fastest same-precision competitor's time, per problem class and GPU, with the number of programs faster, even and slower. Mapal against the best library or compiler, by kind of problem Each cell: the geomean of Mapal's time ÷ the fastest competitor's, and below it the programs faster · even · slower (119 programs timed on every GPU). RTX 5080 RTX 3090 A100 RTX 4090 H100 Attention and softmax 14 programs 0.64 9 · 5 · 0 0.52 9 · 0 · 5 0.63 12 · 0 · 2 0.65 12 · 2 · 0 0.79 5 · 1 · 8 Convolution and FIR 7 programs 0.49 6 · 0 · 1 0.70 5 · 0 · 2 0.94 4 · 1 · 2 0.65 5 · 0 · 2 0.80 4 · 0 · 3 Fan-in / fan-out chains 9 programs 0.98 1 · 8 · 0 1.03 0 · 7 · 2 0.98 6 · 0 · 3 0.96 5 · 2 · 2 1.11 0 · 1 · 8 Matrix products 46 programs 0.92 13 · 18 · 15 1.05 7 · 17 · 22 1.16 14 · 8 · 24 0.93 13 · 14 · 19 1.38 2 · 5 · 39 LLM layers 37 programs 0.99 16 · 7 · 14 0.97 18 · 5 · 14 1.01 18 · 2 · 17 1.05 10 · 6 · 21 0.98 19 · 1 · 17 MLP chains 6 programs 0.97 1 · 5 · 0 1.09 0 · 1 · 5 1.08 3 · 0 · 3 0.95 4 · 0 · 2 1.28 0 · 0 · 6 0.5 0.67 0.8 1 1.25 1.5 2 Mapal faster ← → slower Even: within 5% or the run-to-run variation. Data: benches/results/evidence/matrix.json.
Mapal against the best library or compiler, by kind of problem Geomean of Mapal time divided by the fastest same-precision competitor's time, per problem class and GPU, with the number of programs faster, even and slower. Mapal against the best library or compiler, by kind of problem Each cell: the geomean of Mapal's time ÷ the fastest competitor's, and below it the programs faster · even · slower (119 programs timed on every GPU). RTX 5080 RTX 3090 A100 RTX 4090 H100 Attention and softmax 14 programs 0.64 9 · 5 · 0 0.52 9 · 0 · 5 0.63 12 · 0 · 2 0.65 12 · 2 · 0 0.79 5 · 1 · 8 Convolution and FIR 7 programs 0.49 6 · 0 · 1 0.70 5 · 0 · 2 0.94 4 · 1 · 2 0.65 5 · 0 · 2 0.80 4 · 0 · 3 Fan-in / fan-out chains 9 programs 0.98 1 · 8 · 0 1.03 0 · 7 · 2 0.98 6 · 0 · 3 0.96 5 · 2 · 2 1.11 0 · 1 · 8 Matrix products 46 programs 0.92 13 · 18 · 15 1.05 7 · 17 · 22 1.16 14 · 8 · 24 0.93 13 · 14 · 19 1.38 2 · 5 · 39 LLM layers 37 programs 0.99 16 · 7 · 14 0.97 18 · 5 · 14 1.01 18 · 2 · 17 1.05 10 · 6 · 21 0.98 19 · 1 · 17 MLP chains 6 programs 0.97 1 · 5 · 0 1.09 0 · 1 · 5 1.08 3 · 0 · 3 0.95 4 · 0 · 2 1.28 0 · 0 · 6 0.5 0.67 0.8 1 1.25 1.5 2 Mapal faster ← → slower Even: within 5% or the run-to-run variation. Data: benches/results/evidence/matrix.json.
Six named programs, five GPUs Mapal time divided by the fastest competitor's time for six programs, one mark per GPU. Six named programs, five GPUs Mapal ÷ the fastest competitor, one dot per GPU (large: RTX 5080); left of 1: Mapal faster. Causal attention causal_1024_256 0.30 on the RTX 5080 vs torch.compile + CUDA graphs FIR filter, 4M samples fir_4194304_16 0.42 on the RTX 5080 vs PyTorch eager MLP chain, 2048 mlp_2048 0.95 on the RTX 5080 vs cuBLASLt chain Matrix product, 2048 rows pj_m2048_n4096_k4096 1.02 on the RTX 5080 vs cuBLASLt Matrix-vector product pj_m1_n4096_k4096 1.26 on the RTX 5080 vs cuBLASLt LLM decode layer, batch 32, bf16 weights llm_dec_b32_l2048_bf16w 1.64 on the RTX 5080 vs torch.compile (bf16) 0.1 0.2 0.5 1 2 Blue: faster; grey: even; red: slower. Each against the fastest library or compiler at the same precision, on that GPU. Data: matrix.json.
Six named programs, five GPUs Mapal time divided by the fastest competitor's time for six programs, one mark per GPU. Six named programs, five GPUs Mapal ÷ the fastest competitor, one dot per GPU (large: RTX 5080); left of 1: Mapal faster. Causal attention causal_1024_256 0.30 on the RTX 5080 vs torch.compile + CUDA graphs FIR filter, 4M samples fir_4194304_16 0.42 on the RTX 5080 vs PyTorch eager MLP chain, 2048 mlp_2048 0.95 on the RTX 5080 vs cuBLASLt chain Matrix product, 2048 rows pj_m2048_n4096_k4096 1.02 on the RTX 5080 vs cuBLASLt Matrix-vector product pj_m1_n4096_k4096 1.26 on the RTX 5080 vs cuBLASLt LLM decode layer, batch 32, bf16 weights llm_dec_b32_l2048_bf16w 1.64 on the RTX 5080 vs torch.compile (bf16) 0.1 0.2 0.5 1 2 Blue: faster; grey: even; red: slower. Each against the fastest library or compiler at the same precision, on that GPU. Data: matrix.json.
Attention and softmax

Leads: a chain of steps runs together and saves the launches between them. Trails a memory-efficient attention kernel on long f32 prefill, which skips masked blocks.

Convolution and FIR

Leads on every GPU. The one loss is the TF32 multi-channel convolution, against a tensor-core library.

Fan-in / fan-out chains

About even. Merging launches only pays where the phases are short.

Matrix products

The weak class. Matrix-vector shapes are limited by how many bytes the kernel keeps in flight, and the H100’s TF32 products trail cuBLAS by 1.3–3×; why is still open (cuBLAS’s own kernels were not captured).

LLM layers

Ahead in f32. Behind in bf16 where torch.compile with CUDA graphs replays many small kernels without launch gaps.

MLP chains

About even with the best chain of library calls: the time is in the matrix products.

Kernel and layer suite: Mapal against the fastest same-precision competitor Geometric mean of Mapal time divided by the fastest competitor's time, per GPU: RTX 5080 0.876; RTX 3090 0.920; A100 1.006; RTX 4090 0.911; H100 1.101 Kernel and layer suite: Mapal against the fastest same-precision competitor Geomean of Mapal time ÷ the fastest competitor's time over the 119 programs timed on every GPU, at the program boundary. Below 1: Mapal faster. Each program against competitors of its own precision: cuBLAS(Lt), CUTLASS, PyTorch eager / compiled, Triton, FlashAttention, FlashInfer, Liger. Mapal faster within 5% Mapal slower programs faster / even / slower RTX 5080 0.876 46 / 44 / 30 RTX 3090 0.920 39 / 30 / 51 A100 1.006 57 / 11 / 51 RTX 4090 0.911 49 / 25 / 46 H100 1.101 30 / 8 / 82 0.8 0.9 1 1.1 1.25 ← Mapal faster Mapal slower → Builds: RTX 5080 81a89c02, 9abeb446, d450014d, d945c641; RTX 3090 b8429388; A100 b8429388; RTX 4090 b8429388; H100 b8429388. Data: benches/results/evidence/matrix.json (2026-11-26); even = within 5% or the row's own noise; counts over every row the GPU timed (120 / 120 / 119 / 120 / 120).
Kernel and layer suite: Mapal against the fastest same-precision competitor Geometric mean of Mapal time divided by the fastest competitor's time, per GPU: RTX 5080 0.876; RTX 3090 0.920; A100 1.006; RTX 4090 0.911; H100 1.101 Kernel and layer suite: Mapal against the fastest same-precision competitor Geomean of Mapal time ÷ the fastest competitor's time over the 119 programs timed on every GPU, at the program boundary. Below 1: Mapal faster. Each program against competitors of its own precision: cuBLAS(Lt), CUTLASS, PyTorch eager / compiled, Triton, FlashAttention, FlashInfer, Liger. Mapal faster within 5% Mapal slower programs faster / even / slower RTX 5080 0.876 46 / 44 / 30 RTX 3090 0.920 39 / 30 / 51 A100 1.006 57 / 11 / 51 RTX 4090 0.911 49 / 25 / 46 H100 1.101 30 / 8 / 82 0.8 0.9 1 1.1 1.25 ← Mapal faster Mapal slower → Builds: RTX 5080 81a89c02, 9abeb446, d450014d, d945c641; RTX 3090 b8429388; A100 b8429388; RTX 4090 b8429388; H100 b8429388. Data: benches/results/evidence/matrix.json (2026-11-26); even = within 5% or the row's own noise; counts over every row the GPU timed (120 / 120 / 119 / 120 / 120).

The same suite, all programs: faster than the best on average on three of the five GPUs.

On CPUs: against C++ and NumPy

One thread against one thread, Mapal is faster than NumPy on all six programs and faster than plain C++ on four, level on saxpy and the gather. The large gaps on the FIR filter and the sum come from Mapal being allowed to reorder a sum within its stated error, so it vectorizes it; C++ and NumPy keep strict order. With the whole machine, Mapal is ahead of C++ on every program.

CPU: Mapal against C++ and NumPy Mapal time divided by C++'s and NumPy's time on one AMD Threadripper 9970X, per workload: one thread against one thread, and the whole machine against the whole machine. CPU: Mapal against C++ and NumPy Mapal's time ÷ the other's, log scale; left of 1: Mapal faster. AMD Ryzen Threadripper 9970X, 32 cores / 64 threads, 2026-11-27. One thread against one thread FIR filter, 1M vs C++: 20.8× faster 1.00 vs 20.8 ms vs NumPy: 22.9× faster 1.00 vs 22.9 ms conv2d 3x3, 1024² vs C++: 1.6× faster 0.0990 vs 0.159 ms vs NumPy: 19.6× faster 0.0990 vs 1.94 ms saxpy, 1M vs C++: level 0.110 vs 0.113 ms vs NumPy: 2.18× faster 0.110 vs 0.239 ms sum reduction, 1M vs C++: 14× faster 0.0337 vs 0.472 ms vs NumPy: 4.67× faster 0.0337 vs 0.157 ms transpose, 1024² vs C++: 2.44× faster 1.16 vs 2.82 ms vs NumPy: 3.32× faster 1.16 vs 3.85 ms gather x[idx[i]], 1M vs C++: level 0.533 vs 0.518 ms vs NumPy: 1.57× faster 0.533 vs 0.835 ms 0.05 0.1 0.25 0.5 1 Whole machine against whole machine (64 threads) FIR filter, 1M vs C++: 9.92× faster 0.172 vs 1.71 ms conv2d 3x3, 1024² vs C++: 1.52× faster 0.104 vs 0.159 ms saxpy, 1M vs C++: 1.5× faster 0.0750 vs 0.113 ms sum reduction, 1M vs C++: 10.8× faster 0.0438 vs 0.472 ms transpose, 1024² vs C++: 5.14× faster 0.262 vs 1.35 ms gather x[idx[i]], 1M vs C++: 2.34× faster 0.221 vs 0.518 ms 0.05 0.1 0.25 0.5 1 C++ whole machine: the faster of its one-thread and its threaded build (the threaded one starts its threads on every call, which costs more than it saves at 1M elements). Times: best of 25 for one thread, median of 25 for the whole machine. NumPy runs these on one thread. Data: benches/results/evidence/local-rtx-5080/cpu/shapes-fair.json.
CPU: Mapal against C++ and NumPy Mapal time divided by C++'s and NumPy's time on one AMD Threadripper 9970X, per workload: one thread against one thread, and the whole machine against the whole machine. CPU: Mapal against C++ and NumPy Mapal's time ÷ the other's, log scale; left of 1: Mapal faster. AMD Ryzen Threadripper 9970X, 32 cores / 64 threads, 2026-11-27. One thread against one thread FIR filter, 1M vs C++: 20.8× faster 1.00 vs 20.8 ms vs NumPy: 22.9× faster 1.00 vs 22.9 ms conv2d 3x3, 1024² vs C++: 1.6× faster 0.0990 vs 0.159 ms vs NumPy: 19.6× faster 0.0990 vs 1.94 ms saxpy, 1M vs C++: level 0.110 vs 0.113 ms vs NumPy: 2.18× faster 0.110 vs 0.239 ms sum reduction, 1M vs C++: 14× faster 0.0337 vs 0.472 ms vs NumPy: 4.67× faster 0.0337 vs 0.157 ms transpose, 1024² vs C++: 2.44× faster 1.16 vs 2.82 ms vs NumPy: 3.32× faster 1.16 vs 3.85 ms gather x[idx[i]], 1M vs C++: level 0.533 vs 0.518 ms vs NumPy: 1.57× faster 0.533 vs 0.835 ms 0.05 0.1 0.25 0.5 1 Whole machine against whole machine (64 threads) FIR filter, 1M vs C++: 9.92× faster 0.172 vs 1.71 ms conv2d 3x3, 1024² vs C++: 1.52× faster 0.104 vs 0.159 ms saxpy, 1M vs C++: 1.5× faster 0.0750 vs 0.113 ms sum reduction, 1M vs C++: 10.8× faster 0.0438 vs 0.472 ms transpose, 1024² vs C++: 5.14× faster 0.262 vs 1.35 ms gather x[idx[i]], 1M vs C++: 2.34× faster 0.221 vs 0.518 ms 0.05 0.1 0.25 0.5 1 C++ whole machine: the faster of its one-thread and its threaded build (the threaded one starts its threads on every call, which costs more than it saves at 1M elements). Times: best of 25 for one thread, median of 25 for the whole machine. NumPy runs these on one thread. Data: benches/results/evidence/local-rtx-5080/cpu/shapes-fair.json.

One whole model: Llama-3.2-1B

The readable source above against the fastest of gpt-fast, vLLM, SGLang, TensorRT-LLM, llama.cpp and Hugging Face on five GPUs, each at the same precision. A bar below 1.0 means Mapal is faster.

Llama-3.2-1B, f32 class: Mapal against the fastest f32 engine Mapal as written (f32 activations on the bf16 weights, within the default face's bound) against the f32-compute engines, TF32 off. Time to first token, 512-token prompt: RTX 5080 0.62 (25.4 vs 41.0 ms, vLLM f32); RTX 3090 0.95 (56.0 vs 58.8 ms, llama.cpp f32); A100 0.52 (40.0 vs 76.8 ms, vLLM f32); RTX 4090 0.64 (20.1 vs 31.6 ms, vLLM f32); H100 0.74 (21.8 vs 29.6 ms, HF eager f32). Decode, per generated token, 512-token prompt: RTX 5080 0.58 (3.29 vs 5.72 ms, gpt-fast f32); RTX 3090 0.66 (4.04 vs 6.15 ms, gpt-fast f32); A100 0.91 (3.82 vs 4.21 ms, gpt-fast f32); RTX 4090 0.63 (3.47 vs 5.54 ms, gpt-fast f32); H100 0.95 (2.06 vs 2.16 ms, gpt-fast f32). Llama-3.2-1B, f32 class: Mapal against the fastest f32 engine Mapal as written (f32 activations on the bf16 weights, within the default face's bound) against the f32-compute engines, TF32 off. Mapal time ÷ the fastest engine's time, per GPU. Batch 1, greedy, 128 generated tokens, medians of 5. Below 1: Mapal faster. Mapal faster within 5% Mapal slower Time to first token, 512-token prompt Mapal vs the fastest engine RTX 5080 0.62 25.4 vs 41.0 ms · vLLM f32 RTX 3090 0.95 56.0 vs 58.8 ms · llama.cpp f32 A100 0.52 40.0 vs 76.8 ms · vLLM f32 RTX 4090 0.64 20.1 vs 31.6 ms · vLLM f32 H100 0.74 21.8 vs 29.6 ms · HF eager f32 0.5 0.67 0.8 1 1.25 1.5 2 Decode, per generated token, 512-token prompt Mapal vs the fastest engine RTX 5080 0.58 3.29 vs 5.72 ms · gpt-fast f32 RTX 3090 0.66 4.04 vs 6.15 ms · gpt-fast f32 A100 0.91 3.82 vs 4.21 ms · gpt-fast f32 RTX 4090 0.63 3.47 vs 5.54 ms · gpt-fast f32 H100 0.95 2.06 vs 2.16 ms · gpt-fast f32 0.5 0.67 0.8 1 1.25 1.5 2 ← Mapal faster Mapal slower → Engines of the class: gpt-fast f32, vLLM f32, llama.cpp f32, HF eager f32, HF static + compile f32. Not compared: SGLang: no f32 path; TensorRT-LLM: its f32 build runs but its output is wrong (0 of 128 tokens equal HF f32). Builds b8429388 / 9be9886d. Data: benches/results/evidence/full-model.json (every engine, prompts 128 / 512 / 2048).
Llama-3.2-1B, f32 class: Mapal against the fastest f32 engine Mapal as written (f32 activations on the bf16 weights, within the default face's bound) against the f32-compute engines, TF32 off. Time to first token, 512-token prompt: RTX 5080 0.62 (25.4 vs 41.0 ms, vLLM f32); RTX 3090 0.95 (56.0 vs 58.8 ms, llama.cpp f32); A100 0.52 (40.0 vs 76.8 ms, vLLM f32); RTX 4090 0.64 (20.1 vs 31.6 ms, vLLM f32); H100 0.74 (21.8 vs 29.6 ms, HF eager f32). Decode, per generated token, 512-token prompt: RTX 5080 0.58 (3.29 vs 5.72 ms, gpt-fast f32); RTX 3090 0.66 (4.04 vs 6.15 ms, gpt-fast f32); A100 0.91 (3.82 vs 4.21 ms, gpt-fast f32); RTX 4090 0.63 (3.47 vs 5.54 ms, gpt-fast f32); H100 0.95 (2.06 vs 2.16 ms, gpt-fast f32). Llama-3.2-1B, f32 class: Mapal against the fastest f32 engine Mapal as written (f32 activations on the bf16 weights, within the default face's bound) against the f32-compute engines, TF32 off. Mapal time ÷ the fastest engine's time, per GPU. Batch 1, greedy, 128 generated tokens, medians of 5. Below 1: Mapal faster. Mapal faster within 5% Mapal slower Time to first token, 512-token prompt Mapal vs the fastest engine RTX 5080 0.62 25.4 vs 41.0 ms · vLLM f32 RTX 3090 0.95 56.0 vs 58.8 ms · llama.cpp f32 A100 0.52 40.0 vs 76.8 ms · vLLM f32 RTX 4090 0.64 20.1 vs 31.6 ms · vLLM f32 H100 0.74 21.8 vs 29.6 ms · HF eager f32 0.5 0.67 0.8 1 1.25 1.5 2 Decode, per generated token, 512-token prompt Mapal vs the fastest engine RTX 5080 0.58 3.29 vs 5.72 ms · gpt-fast f32 RTX 3090 0.66 4.04 vs 6.15 ms · gpt-fast f32 A100 0.91 3.82 vs 4.21 ms · gpt-fast f32 RTX 4090 0.63 3.47 vs 5.54 ms · gpt-fast f32 H100 0.95 2.06 vs 2.16 ms · gpt-fast f32 0.5 0.67 0.8 1 1.25 1.5 2 ← Mapal faster Mapal slower → Engines of the class: gpt-fast f32, vLLM f32, llama.cpp f32, HF eager f32, HF static + compile f32. Not compared: SGLang: no f32 path; TensorRT-LLM: its f32 build runs but its output is wrong (0 of 128 tokens equal HF f32). Builds b8429388 / 9be9886d. Data: benches/results/evidence/full-model.json (every engine, prompts 128 / 512 / 2048).
Llama-3.2-1B, bf16 class: Mapal against the fastest bf16 engine Mapal with bf16 operands and f32 accumulation on the sums of products and a bf16 KV cache, against the bf16 engines. Time to first token, 512-token prompt: RTX 5080 1.05 (14.1 vs 13.5 ms, llama.cpp bf16); RTX 3090 1.17 (23.8 vs 20.4 ms, SGLang); A100 1.44 (16.1 vs 11.1 ms, SGLang); RTX 4090 1.16 (11.9 vs 10.3 ms, gpt-fast); H100 1.88 (7.60 vs 4.04 ms, gpt-fast). Decode, per generated token, 512-token prompt: RTX 5080 1.10 (3.29 vs 2.98 ms, gpt-fast); RTX 3090 1.23 (4.01 vs 3.27 ms, gpt-fast); A100 1.55 (3.69 vs 2.38 ms, gpt-fast); RTX 4090 1.19 (3.47 vs 2.93 ms, gpt-fast); H100 1.56 (2.06 vs 1.32 ms, gpt-fast). Llama-3.2-1B, bf16 class: Mapal against the fastest bf16 engine Mapal with bf16 operands and f32 accumulation on the sums of products and a bf16 KV cache, against the bf16 engines. Mapal time ÷ the fastest engine's time, per GPU. Batch 1, greedy, 128 generated tokens, medians of 5. Below 1: Mapal faster. Mapal faster within 5% Mapal slower Time to first token, 512-token prompt Mapal vs the fastest engine RTX 5080 1.05 14.1 vs 13.5 ms · llama.cpp bf16 RTX 3090 1.17 23.8 vs 20.4 ms · SGLang A100 1.44 16.1 vs 11.1 ms · SGLang RTX 4090 1.16 11.9 vs 10.3 ms · gpt-fast H100 1.88 7.60 vs 4.04 ms · gpt-fast 0.5 0.67 0.8 1 1.25 1.5 2 Decode, per generated token, 512-token prompt Mapal vs the fastest engine RTX 5080 1.10 3.29 vs 2.98 ms · gpt-fast RTX 3090 1.23 4.01 vs 3.27 ms · gpt-fast A100 1.55 3.69 vs 2.38 ms · gpt-fast RTX 4090 1.19 3.47 vs 2.93 ms · gpt-fast H100 1.56 2.06 vs 1.32 ms · gpt-fast 0.5 0.67 0.8 1 1.25 1.5 2 ← Mapal faster Mapal slower → Engines of the class: gpt-fast, SGLang, TensorRT-LLM, vLLM, llama.cpp bf16, HF eager, HF static + compile. Not compared: llama.cpp f16: f16 is another 16-bit format (recorded under other_types). Builds b8429388 / 9be9886d. Data: benches/results/evidence/full-model.json (every engine, prompts 128 / 512 / 2048).
Llama-3.2-1B, bf16 class: Mapal against the fastest bf16 engine Mapal with bf16 operands and f32 accumulation on the sums of products and a bf16 KV cache, against the bf16 engines. Time to first token, 512-token prompt: RTX 5080 1.05 (14.1 vs 13.5 ms, llama.cpp bf16); RTX 3090 1.17 (23.8 vs 20.4 ms, SGLang); A100 1.44 (16.1 vs 11.1 ms, SGLang); RTX 4090 1.16 (11.9 vs 10.3 ms, gpt-fast); H100 1.88 (7.60 vs 4.04 ms, gpt-fast). Decode, per generated token, 512-token prompt: RTX 5080 1.10 (3.29 vs 2.98 ms, gpt-fast); RTX 3090 1.23 (4.01 vs 3.27 ms, gpt-fast); A100 1.55 (3.69 vs 2.38 ms, gpt-fast); RTX 4090 1.19 (3.47 vs 2.93 ms, gpt-fast); H100 1.56 (2.06 vs 1.32 ms, gpt-fast). Llama-3.2-1B, bf16 class: Mapal against the fastest bf16 engine Mapal with bf16 operands and f32 accumulation on the sums of products and a bf16 KV cache, against the bf16 engines. Mapal time ÷ the fastest engine's time, per GPU. Batch 1, greedy, 128 generated tokens, medians of 5. Below 1: Mapal faster. Mapal faster within 5% Mapal slower Time to first token, 512-token prompt Mapal vs the fastest engine RTX 5080 1.05 14.1 vs 13.5 ms · llama.cpp bf16 RTX 3090 1.17 23.8 vs 20.4 ms · SGLang A100 1.44 16.1 vs 11.1 ms · SGLang RTX 4090 1.16 11.9 vs 10.3 ms · gpt-fast H100 1.88 7.60 vs 4.04 ms · gpt-fast 0.5 0.67 0.8 1 1.25 1.5 2 Decode, per generated token, 512-token prompt Mapal vs the fastest engine RTX 5080 1.10 3.29 vs 2.98 ms · gpt-fast RTX 3090 1.23 4.01 vs 3.27 ms · gpt-fast A100 1.55 3.69 vs 2.38 ms · gpt-fast RTX 4090 1.19 3.47 vs 2.93 ms · gpt-fast H100 1.56 2.06 vs 1.32 ms · gpt-fast 0.5 0.67 0.8 1 1.25 1.5 2 ← Mapal faster Mapal slower → Engines of the class: gpt-fast, SGLang, TensorRT-LLM, vLLM, llama.cpp bf16, HF eager, HF static + compile. Not compared: llama.cpp f16: f16 is another 16-bit format (recorded under other_types). Builds b8429388 / 9be9886d. Data: benches/results/evidence/full-model.json (every engine, prompts 128 / 512 / 2048).

After the 16-bit warpgroup tiles (wgmma), on another H100 against gpt-fast on the same box, the bf16 time to first token at 128 / 512 / 2048 tokens is 0.75 / 1.25 / 1.58 of gpt-fast's (2.7 / 5.6 / 18.11 ms against 3.58 / 4.47 / 11.45 ms): ahead for short prompts, behind for long ones. Source: full-model.json, H100 reruns.

Full precision (f32)

The fastest on all five GPUs at generating text, and for prompts of 512 tokens or more.

Half precision (bf16)

Mostly still behind the fastest engine: within 5–15% on the RTX 5080, further behind on the others. On the H100 it is faster for short prompts. Work is in progress.

Memory

2.7–3.5 GB of GPU memory, level with the leanest engines and far below the serving engines.

All numbers, how they were measured, and every engine: docs/performance/results.md.

3Philosophy

Six ideas. Each one is something you have already seen above.

The language is the flow

A program states data and how it flows, data -> transform -> result;, not the control that moves it. A map says cells are independent; a fold says how they combine.

See three steps over every sample.

Facts, not passes

What each value reads, when it dies, what is independent: every analysis is a stored fact on the graph, and every optimization decision reads facts.

See attention, the loop.

Hardware is physical properties

Compilation matches the shape of the work to compute units and storages: sizes, bandwidths, latencies. Never a branch on a chip's name.

See one source, three machines.

Correct within a stated error

A result is guaranteed within a bound you can see, not bit for bit. That frees the compiler to choose the fastest correct order, tensor cores included.

See the norm and fold: bf16 | f32 in the projection.

Readable code is the target

If the natural version of a program runs slower, the compiler is fixed; the program is never rewritten to suit it.

See softmax, RMSNorm.

The full philosophy text, with the decisions behind it, is in In depth.

4The architecture as an equation

Code becomes a dataflow graph plus the facts deduced from it. Hardware becomes compute units plus storages. Put together, and compiled, they give something runnable. Every component, the data it reads and makes, and where each piece lives in the code: the Architecture Map.

The program

Sourcereadable Mapal: map, fold, loops, guards
Dataflow graphvalues and the steps that make them
Factsreads, death, independence, bounds

The hardware

Physical propertiesSMs, registers, shared memory, L2, bandwidth, latency
Compute unitsoperations as geometry, rates
Storagesplaces, capacities, movers
compile: placement, then loweringplacement decides which work runs where and what lives where; lowering emits LLVM IR, then PTX or machine code
Runnablea native executable: host code, kernels, a runtime

Step 1 of 6

Keyboard: focus the diagram, then ← and → step, Space plays and pauses.

Where this stands. The hardware model is ADR-0050: the machine as memory places and compute units with operations as geometry, and one cost model plus a search that places the dataflow on it. It is being built; step 1 (matrix products) is in progress and the search is off by default (machine-place). Today the placement is decided by about seventeen separate rules, each reading the hardware properties it needs, and every rule is replayed against the measurements that justified it. The compiler you see in the demos is that one.

5Components and how they connect

One direction of flow, one hub. Select a component to see what it owns.

source→syntax→lower→check→graph (mapal-ir)→rewrite→backends→runnable+ rt

The detailed table of files and the connection diagram are in the code map.

6Artifacts on one running example

The same dense layer from the top, at each stage. Every pane is output of the real tools.

Text, as written. mapal fmt owns its layout.

// A dense layer: a matrix product, a bias and a ReLU. What to compute, not how.
64 -> n;

fn main() {
    "dense-a.bin" -> read -> a: [f32; n * n];
    "dense-b.bin" -> read -> b: [f32; n * n];
    n -> iota -> along;
    n * n -> iota -> map {
        c ->
        c / n -> row;
        c % n -> column;
        (0.0, along) -> fold {
            sum, k -> sum + a[row * n + k] * b[k * n + column]
        } -> dot;
        (dot + 1.0 > 0.0) -> {
            -true-> dot + 1.0;
            -false-> 0.0;
        }
    } -> out;
    out[0] -> println;
    out[n * n - 1] -> println;
}
the source — docs/exposition/dense.mapal, 22 lines
Stage 1 of 6

The long version of this walk, with three programs through every layer, is In depth: end to end.

7Where Mapal is different

Where the language is different — the map

Few of Mapal’s ideas are new on their own. What is new is where they sit: one system of facts from the source text to the hardware, with correctness separated from the order of execution by a stated bound.

AreaWhat Mapal doesClosest prior artWhat is differentStatus
The program is the flowSource is a dataflow graph: pipelines x -> f -> y, map / fold / loops, immutable unless mut, effects threaded as tokensSISAL, Id / Val, Lucid, StreamIt; Futhark, JAXThe graph’s structure (products, projections, composition) is both the language’s meaning and the compiler’s IR; no translation step loses meaningbuilt
Facts on the graphEach analysis is a stored fact — liveness and death, write deltas, reuse, residence, bounds, independence; facts depend on facts; every decision reads them (In depth §6)Every compiler has analyses, but they live inside individual passesOne stored, queryable fact catalog that every decision must use; a mixed result is treated as a missing factbuilt
No “fusion”Which work runs together and what stays on chip follow from producer / consumer footprints and death pointsXLA’s fusion heuristics, Halide schedules, Futhark’s fusion rulesKernel boundaries are an output, decided at compile time, never runtime graphsbuilt
Hardware as facts (ADR-0050)The machine as memory places, executors with operations as geometry, movers and dispatch, each fact with its source; one cost model + a search places the dataflow on it (In depth §8)Sequoia’s memory tree, Legion’s mappers, Timeloop / MAESTRO for accelerators, TVM / Ansor, Halide’s autoschedulerAnalytic rather than learned or measured, general-purpose (CPU, GPU, ASIC), driven by the language’s facts; measurement checks the model instead of picking the answer; a new target is a translation into the modelADR accepted; GEMM step 1 in progress
Correctness = flow + bound (ADR-0040, 0049)Precision is part of the program (fold: bf16 | f32); the compiler proves an a-priori error bound, then reorders freely; bit-identity is a development modeHerbie, FPTaylor, Precimonious; fast-math flagsA bound the language states and the compiler proves, instead of flags that trade correctness away; it admits hardware realizations no flag expresses (tf32x3, bf16x2n split forms on tensor cores)built
Builtins as contracts (ADR-0046)exp, sqrt, sin, cos: a contract and a reference definition; each target’s units admitted by the contract, chosen by error and costlibm variants, CUDA __expf, OpenCL native_*Chosen from facts, not from a flag or a function namebuilt
Compile time by dataflow (ADR-0048)No const or comptime: any value whose dataflow has no run-time input is computed beforehand — or materialized against recomputed by costZig comptime, C++ constexpr, partial evaluationInferred from the graph, not annotatedbuilt
Generics over sizes and formats (ADR-0047, 0051)fn project<rows, columns>, cache: float, x -> to<bf16>; an explicit prefix, the rest inferredFuthark’s size types, Dex, C++ templatesSizes stay in the type, so every fact sees exact extents; formats are generic and precision loss stays visible (to against widen)sizes built; formats in progress
Placement across devicesCPU, GPU and the host spine in one program; tasks and residency derived from path_plan and the residence factsLegion, StarPU, SYCL, OpenMP targetDerived from facts, not from annotations or run-time discoverybuilt (CPU + GPU)
One language down to siliconThe same program and the same machine model; for synthesis the search also picks the hardware’s free parametersHLS (Vitis, Catapult), Spatial, Calyx / CIRCTGPU and ASIC from one fact model; the hardware’s design and the placement in one searchplanned (the Verilog backend is a stub)
How the compiler is builtEvery optimization declares its intent; PTX / SASS is checked against it; every measurement becomes a replay test; every rule has an OFF armPerformance regression suitesCompiler decisions are evidence-backed and re-checked like proofsin practice

Not new on its own: dataflow languages (SISAL, Id — the 1980s and 1990s), size types (Futhark), separating the algorithm from its schedule (Halide), analytic mapping onto accelerators (Timeloop), floating-point error analysis (FPTaylor).

New — the combination: (1) the language’s meaning, the compiler’s facts and the hardware’s facts are one connected system; (2) the program states its numerical bound, which frees the compiler to choose any order and any realization within it, tensor cores included; (3) placement is derived from that system, not written by hand, tuned by measurement or learned, so a new target is a translation, not a new backend’s worth of heuristics.

This map is drawn from the project’s knowledge of the field, not a literature survey; check each “closest prior art” against current work before using it outside the project.

How it differs from today’s methods

Every serious toolchain has some model of the hardware. The differences are where that knowledge lives, what makes the decision, and whether the decision can be explained from facts. A fair summary — the last column marks what ships today and what is ADR-0050’s design:

ApproachWhere the hardware knowledge livesHow a placement / schedule is chosenWhat Mapal does differently
Conventional compilers (LLVM, GCC)Per-target backends: instruction descriptions and per-CPU scheduling models (latencies, ports), plus cost hooks that answer one question at a time (LLVM’s TargetTransformInfo).Each pass decides locally with its own heuristic and thresholds — the vectorizer a width, the unroller a count, the inliner a budget — in a fixed pass order. Placement across devices and cache-level blocking are mostly outside their model.Mapal keeps LLVM for what it does well after lowering (instruction selection, register allocation, scheduling) and makes the placement decisions above it from both fact layers. Today each decision is its own rung rule in a fixed order — closer to LLVM’s per-pass heuristics than the goal. ADR-0050: once, over the whole schedule, with caches, waves and copies in one price.
Vendor libraries (cuBLAS / cuBLASLt, CUTLASS, cuDNN)Hand-written or templated kernels per architecture (CUTLASS is parameterized by an architecture tag and tile shapes).Heuristics and tables pick a kernel per shape (cuBLASLt’s heuristic query, cuDNN’s heuristic modes), optionally confirmed by autotuning or a profiler.Very fast on the shapes they target — Mapal measures itself against them (README). But the knowledge is in kernels and tables: a new part needs new kernels, and a choice is not explained by facts. A library also sees little beyond its own call: an epilogue can take in the immediate consumer (cuBLASLt epilogues, CUTLASS epilogue visitor trees), but not the producers or what stays resident between calls — which Mapal reads from the dataflow facts (today).
XLAPer-backend passes; on GPU an analytic performance model and library calls.Fusion passes driven by heuristics and that model; GEMMs and convolutions mostly handed to cuBLAS / cuDNN or to autotuned Triton tiles.Closest in spirit (a whole-graph compiler). Today: there is no fusion pass — kernel boundaries fall out of footprints and death points — and Mapal emits its own GEMM kernels instead of delegating them, their tile and traversal chosen by rung rules. ADR-0050: the GEMM’s schedule is priced by the same evaluator that is meant to price everything else (step 1 covers GEMM-shaped sites only).
TVM / Ansor / MetaScheduleMeasurements on the device, plus a learned cost model trained on them.Search over a space generated from schedule rules; candidates measured on the hardware; the learned model ranks them.Today Mapal is partly in this family: a site may carry candidate kernels (candidate 0 the rules’ plan) that the GPU runtime times in trials and remembers per device (“wisdom”, mapal_choice.h, §8.5). ADR-0050: search scored by an analytic model whose inputs are measured facts with provenance, so it can decide for parts not at hand and for ASIC templates not yet built, and say why a choice wins; measurement becomes the model’s check (alternatives rejected).
TritonIn the compiler’s layouts and pipelining, and in the programmer’s choice of block size.The programmer writes the block-level kernel; @triton.autotune times a hand-written list of configurations.No kernel, block or tile size appears in Mapal source; the tile, traversal and launch are generated from both fact layers (today by rung rules, ADR-0050 by one search).
HalideIn a separate schedule.Written by hand, or by an autoscheduler (an analytic one, and later a learned cost model).Shares the separation of “what” from “how”, but there is no schedule language to write: the compiler chooses the schedule (today by rung rules, visible only in the emitted code and the rules’ comments). ADR-0050: the schedule is an explicit output, printed with the module (; mapal.place).
MLIR-based compilers (e.g. IREE)Per-target dialects (NVGPU/NVVM, AMDGPU/ROCDL, ArmSME, x86 vector…) and lowering pipelines.Tiling and mapping in transform-dialect scripts or per-backend configuration logic.Today the decisions live in the LLVM backend’s rules, which read physical properties rather than a target name — one rule chain for every GPU, not one pipeline per target. ADR-0050: one target-agnostic placement over abstract facts; the per-target code is the translation into facts and the lowering of a chosen schedule.
Polyhedral (Pluto, PPCG)Exact affine access relations and dependences; hardware mostly as tile sizes.An ILP over a locality and parallelism objective (dependence distances).Mapal uses exact access maps too (tile_plan, tensor_form, today), but its objective is time on the machine: slots, waves, copy engines, bandwidth per level — today weighed rule by rule, under ADR-0050 as one predicted time — which the locality objective does not see.

What Mapal borrows: exact access maps (polyhedral), the separation of algorithm from schedule (Halide), LLVM for everything after lowering; under ADR-0050 also search with pruning (TVM) and measurement as a check (every autotuner). What ADR-0050 costs: a search at compile time, facts that must be measured or declared per part (calibration probes), and a model that can be wrong — which is why the evidence pass and the falsification criteria below exist. Where it stands today: the libraries still win several GEMM shapes on the RTX 3090, A100 and H100 (README, “Current results”) — the case step 1 targets.

8In depth

The full reference, in the order the compiler works. Sections are closed; open the one you need. A link into a closed section opens it.

0How to read this page

Read it in order the first time — each layer only uses ideas from the layer above. After that, use the left navigation as an index. Three reading aids recur:

  • Diagrams show flow. Boxes are artifacts (text, tree, graph, code); arrows are compiler steps. Dotted arrows mean “consults, does not modify.”
  • Expand areas (click the ▸ line) hold full examples, DAGs, and catalog tables. Skim past them on a first read; open them when you need the detail.
  • Plain-words boxes translate the project’s categorical vocabulary. The translation is the whole point: object = a value, morphism = a step that makes a value, functor = a translator that preserves meaning. Nothing deeper is required.

The 60-second version. Mapal source is parsed into a thin tree (AST), then lowered into a single dataflow graph — the Category IR — where every value has exactly one producer. Values whose dataflow reads no input are computed before the program runs. Everything else the compiler knows about the program is deduced from the graph by pure queries called plans (loops, parallelism, tiling geometry, lifetimes, bytes moved, proven-safe indices, error bounds…). A rewriter simplifies the graph without changing its answer. On the other side sit machine facts: the hardware described as abstract compute and placement facts (places with capacities and bandwidths, executors with their operations, movers, dispatch). Today these are TargetProfile records — the device query and calibration measurements, with fallbacks borrowed from another part’s measurement or keyed by compute capability; under ADR-0050 every fact also carries its source (queried, measured, declared, derived, nominal). Placement reconciles the two fact layers: it chooses where and how each piece of work runs — today by one rung rule per decision, under ADR-0050 by one evaluator and one search (§8). Only then is the result lowered to LLVM IR / PTX, which LLVM turns into an executable. The interpreter, which runs the graph directly, is the reference: a compiled result is correct when its flow of operations is the program’s dataflow and every value lies within the error bound stated before the run; bit-for-bit agreement with the interpreter is a development mode for testing (ADR-0049).

0.1 Philosophy

  • The language is the flow. A program states data and how it flows, data -> transform -> result;, not the control that moves it. A map says every cell is independent, a fold says how values combine, a binding says who reads what.
  • Data is category-theoretic. Values are objects, transforms are morphisms, a program is their composition. The compiler’s IR is that graph, and its rewrites are the category’s laws (spec/category-ir.md; §5).
  • Expressing the flow beats expressing control. Because the source states only what depends on what, the compiler derives what runs in parallel, what merges into one kernel, what stays in registers, shared memory or cache, and what moves between devices, from facts on the graph (independence, reuse, death points, footprints) against the hardware’s facts. Control written by hand fixes each of those decisions for one machine.

What follows from it:

  • Two kinds of facts, reconciled by the compiler. The dataflow’s facts (what each value reads, when it dies, what is independent) and the hardware’s facts as abstract compute and placement: where bytes can live, what computes (operations as shapes, with the place each operand must be in), what moves bytes, how work is dispatched — each fact measured, queried or declared, never a part’s name. Compilation places the dataflow on the machine with one cost model and one search, then lowers it; the few hardware-specific steps come last, kept minimal. A new chip, vendor or ASIC is described as facts, not given a new backend’s worth of heuristics (§8, ADR-0050; its first step is in progress — today rules over the same physical properties decide).
  • No runtime graph recording. Which work merges into one kernel, vertically along a chain and horizontally across independent branches, is decided at compile time from the dataflow. Nothing is traced or captured while the program runs.
  • Correct numerics: the flow and the bound, not bit-identity. Every result is within an error bound stated before the program runs (ADR-0040). The compiler orders and combines operations freely, so parallel sums may differ in the last bits between runs; bit-reproducible runs are a development mode (ADR-0049). Reduced precision is opt-in, per product.
  • Readable, idiomatic source. Programs read like the math they compute. If natural code compiles worse than a hand-shaped version, the compiler is fixed, not the program.
1The whole journey: code → Mapal → executable

This is the master map. Every later section zooms into one box of this diagram.

flowchart TD SRC["Your program
.mapal source text"] --> LEX["1 · Lex + Parse
mapal-syntax
text → AST (thin tree)"] LEX --> LOW["2 · Lower
mapal-lower
AST → Category IR (graph)
sizes inferred · top-level values computed"] LOW --> CHK{"3 · Gates
validate + check
accept or diagnose"} CHK -->|"accepted"| IR["Category IR
sealed dataflow graph
the only stored truth"] IR --> PLANS["4 · Dataflow facts (plans)
mapal-ir · algo*
loops · parallelism · tiling · bytes · lifetimes · bounds"] IR --> RW["5 · Compile-time evaluation + rewrite
mapal-rewrite
same answer, smaller graph"] PLANS -.->|"facts"| RW RW --> IR2["Rewritten graph
facts recomputed on demand"] HW["Hardware
device query · calibration probes
· a design's declared parameters"] --> MF["Machine facts
places · executors + operations
movers · dispatch · provenance"] IR2 --> PL["6 · Placement = reconciliation (§8)
dataflow facts × machine facts → schedule
today: rung rules · ADR-0050: one evaluator + one search"] PLANS -.->|"facts"| PL MF -.->|"facts"| PL PL --> LOWER2["7 · Lower the schedule
LLVM IR (CPU) · NVPTX → PTX (GPU)
+ a minimal target-specific step"] LOWER2 --> CLANG["clang -O3 / ptxas
vectorize · unroll · schedule"] CLANG --> EXE["Executable
+ mapal-rt (thread pool, GPU runtime)"] IR -.->|"defines the answer"| ORACLE["Interpreter — the reference
mapal-interp
runs the graph directly"] EXE -.->|"within the stated bound
(bit for bit in development modes)"| ORACLE

Two fact layers, one reconciliation — the idea to keep in mind. The program side and the hardware side are both written down as facts. Dataflow facts (§6, mapal-ir) say what the program needs: which cells are independent, what each one reads, how many bytes cross each edge, when a value dies, how large the error bound is. Machine facts (§8.2) say what the hardware offers, without naming the chip: places where bytes can live (registers, shared memory, caches, DRAM, a link to the host) with their capacities, bandwidths and latencies; executors and the operations they run, each one a row of geometry (a scalar FMA, a tensor-core mma, a CPU vector FMA, a systolic array); movers (copy engines, prefetchers, links); and how work is dispatched. Placement reconciles them: it decides where each piece of work runs and how, as an ordinary phase of compilation, before any target code is written. In most toolchains that knowledge lives in hand-written kernels, per-chip tables or one heuristic per pass (§8.6). Status: the reconciliation by one model is ADR-0050, accepted 2026-11-26, step 1 (GEMM) in progress. Today the same two layers meet in per-decision rung rules that read physical properties (§9.3).

Who owns what — and what each step erases

Stage (crate)Input → OutputOwnsErases / normalizes
lex + parse (mapal-syntax)&str → ParseOutput { program, diagnostics }Tokens, spans, error recovery. The only stage that can hold a broken program.Nothing — it preserves even rejected forms so errors can point at exact spans.
lower (mapal-lower)(&str, &Program) → Result<CategoryIr, Vec<Diagnostic>>Name resolution, typing, desugaring, graph construction; size inference (one fixed-size function per size tuple, ADR-0047); top-level values computed by the interpreter (ADR-0048).seq (no IR footprint), spelling differences (arrow vs call forms become one op), error nodes (rejected as L1000).
check (mapal-check)(&str, &Program, &CategoryIr) → Vec<Diagnostic>Return exclusivity (T0101), effect legality (T0201). Reads both tree and graph, because lowering erased fanout scope.— (a gate, not a transform)
Plans (mapal-ir)CategoryIr → Facts (per function, cached on the graph)All structural knowledge: loops, tasks, tile geometry, lifetimes, proofs.— (read-only views; silence = “take the slow path”)
fold_static + rewrite (mapal-rewrite)CategoryIr → CategoryIrCompile-time evaluation of values whose dataflow reads no input (static_plan); const-fold, dead-code, CSE, map fusion, inlining, loop lifting.Redundant work — never the answer (eval ∘ rewrite = eval).
Machine facts (backends/llvm profile.rs today; Machine::of, ADR-0050)target → TargetProfile (→ machine facts)The hardware as data: device query, calibration lines, declared capabilities. Today without per-fact provenance (an uncalibrated part borrows the RTX 5080’s numbers; some fallbacks are keyed by compute capability, §9.1); under ADR-0050 each fact with its source.Chip names: no rule reads one.
Placement (backends/llvm rules today; mapal-place, ADR-0050)CategoryIr × Plans × machine facts → scheduleWhere each piece of work runs and how: host or device, operation, tile, traversal, residency, launch (§8).All portability: this is where one program becomes this machine’s plan.
Lowering (backends/llvm, backends/cuda, backends/verilog)schedule → text (LLVM IR, PTX)Spelling the chosen schedule in the target’s language; then a minimal target-specific step.— (decides nothing the machine facts could state)
interp (mapal-interp)CategoryIr → output / trapThe reference semantics (the oracle): compiled values are checked within the bound, bit for bit in development modes.—

Why this shape matters. Lowering is deliberately many-to-one: different spellings of the same computation become the same graph. That is why optimization can be uniform — backends never pattern-match on syntax. The measured cost of keeping the tree is tiny (parse + lower ≈ 0.06% of a compile; LLVM is ≈ 99%), and it buys error recovery and precise diagnostics. See docs/architecture/INDEX.md.

Expand: the CLI commands that expose each stage

The mapal CLI (crates/mapal-cli/src/main.rs) is the lone renderer of diagnostics and the driver of the pipeline:

mapal run      prog.mapal              # frontend → (rewrite) → emit → clang → execute
mapal build    prog.mapal -o prog      # same, keep the executable
mapal dump-ir  prog.mapal --stage=lowered     # sealed graph, as lowered
mapal dump-ir  prog.mapal --stage=rewritten   # graph after rewriting
mapal dump-ir  prog.mapal --stage=llvm        # emitted LLVM IR text
mapal dump-ir  prog.mapal --stage=device      # emitted device (PTX) text, when placed
mapal dump-ir  prog.mapal --mermaid           # the graph as a string diagram (=category, =graph, =flow)
mapal test     prog.mapal              # differential: compiled vs the interpreter (development mode, bit for bit)
mapal fmt      prog.mapal              # formatter (owns layout; --check to verify)

Useful flags while exploring: --interp (run the oracle instead of compiling), --interp --bound (print each value’s composed default-face error bound instead of the value), --no-rewrite (skip the optimizer), --static=off (no compile-time evaluation), --emit-only (stop after emission), --target=<profile> (e.g. native, native-gpu, rtx-3090), --exact / --order=sequential|fixed (development modes, §9.2), --gpu-off=<rung> / --gpu-on=<rung> (a GPU rule’s measurement arms, §9.3). If the CLI is not installed, every command works as cargo run -p mapal-cli -- <args>.

2Language syntax — Mapal-Core in one sitting

Mapal programs are flows: values move left-to-right through steps joined by ->. There is no hidden control flow — the text you read is the dependency structure the compiler will use. This section covers Mapal-Core, the subset that compiles today (HANDOFF.md §4, docs/spec/user-guide.md), including the model-scale additions of ADR-0042…0048: math builtins, narrow storage, read, size-generic functions and types, top-level values (§2.10). Constructs outside Core still parse and are rejected with a precise P- or L-code diagnostic. A whole real program in this style: examples/llama.mapal (§11).

2.1 The smallest useful program

fn main() {
    1048576 -> iota -> ts;
    ts -> map { t -> t * 2 } -> doubled;
    doubled[1048575] -> println;
}

Read each line as a pipeline: make the range 0..1048576, double every element (in parallel — nothing says so, the graph proves it), print the last one. Bindings (-> ts;) name an intermediate so later flows can use it. A flow is a statement, not an expression: it routes a value; it does not itself produce one.

2.2 Types

KindSpellingNotes
Integersi32, i64, u8The three Core integer types. Literals default to i32.
Floatsf32, f64Literal type is directed by context (e.g. binding annotation).
Narrow float storagebf16, f16, f8e4m3, f8e5m2Values stored in fewer bytes; no arithmetic on them. In by one rounding (x -> to<bf16>), out by an exact widening (w -> widen<f32>); compute stays f32 (ADR-0043).
Bool / unit / stringbool, (), "…"Strings exist to be printed in Core.
Fixed arrays[f32; 8], [Pixel; 16], [f32; tokens * hidden_size]Size is part of the type and always ≥ 1 — a literal, a top-level integer, or a size expression over a function’s size parameters (ADR-0047). Dynamic [T] is rejected (P0104).
Tuples(i32, f32), value (a, b)The product type; multi-argument calls are tuple inputs. Project with p.0, p.1.
Named productstype Pixel { r: f32, g: f32, b: f32 }Keyword is type (erratum E5). Construct as Pixel { r: 1.0, g: 2.0, b: 3.0 }, read fields as px.r.
Size-generic types, _type Matrix<rows, columns> { _: [bf16; rows * columns] }A use states its sizes: Matrix<hidden_size, hidden_size>. A field named _ is the type’s default interpretation: alone, the type is a zero-cost alias; beside other fields, the value reads as x._ wherever only that fits (ADR-0048 D4/D5).

2.3 Bindings, mutation, element update

2048 -> hidden_size;      // top-level binding: program-wide, immutable, computed before the run
5 -> x: i32;              // immutable binding (flow form)
mut counter: i32 <- 0;    // mutable binding (assignment form)
counter + 1 -> counter;   // legal only because counter is mut
c[t] <- v;                // element update: "c with slot t replaced" (a fresh value in the IR)

Everything is immutable unless declared mut — there is no const keyword, and a top-level binding is never mut (L1801). Immutability by default is load-bearing: an immutable value can be read by any number of parallel branches safely, and a value whose dataflow reads no input can be computed before the program runs (§2.10). c[t] <- v looks like mutation but denotes a new array value in the graph (Update, §5) — whether it is stored in place is a backend decision guided by last_use_plan (§6).

2.4 Functions

fn clamp(v: f32, lo: f32, hi: f32) -> f32 {
    (v > hi) -> {
        -true->  hi;
        -false-> v;
    } -> ret;
}

fn main() {
    (270.2, 0.0, 255.0) -> clamp -> r;   // tuple input, one step
    r -> println;                          // 255
}
  • ret names the function’s output; ret.0 / ret.1 fill tuple slots. At most one full-value writer may reach ret (checked as T0101).
  • A function conceptually takes one input — a tuple when it has several parameters. This single-input rule is what keeps the graph uniform (§5).
  • Recursion is out of Core by design (L1008): cycles live in loop dataflow, never in the call graph. Iteration is written with loop (§2.7) or fold (§2.6).
  • main takes no parameters and declares no return.
  • Size-generic functions declare their sizes once after the name — fn project<tokens, rows, columns>(weight: Matrix<rows, columns>, x: [f32; tokens * columns]) -> [f32; tokens * rows]. There is no call-site syntax: the sizes are inferred from the argument types at each call, and lowering emits one fixed-size function per size tuple, so every later fact still sees concrete extents (ADR-0047).

2.5 Pipelines and shorthand stages

fn f(data: i32) -> i32 {
    data * 2
        -> + 5        // shorthand: piped value is the left operand
        -> ret;
}
// f(10) = 25

A shorthand stage like -> + 5 means “pair the piped value with 5, then add.” In the AST it is an OpShorthand stage whose expression contains a single Hole leaf for the piped value; in the IR it becomes an ordinary Pair + Add (§4, §5). Naming intermediates (-> s1;) changes nothing semantically — it only labels a graph node.

2.6 Collections: map, fold, and the pure builtins

(a, b) -> zip -> map { p -> p.0 + p.1 } -> c: [i32; 16];   // elementwise add
(0, c) -> fold { acc, x -> acc + x } -> total;              // sum, in order
16 -> iota -> ts;                                            // [0,1,…,15]
arr -> enumerate -> indexed;                                 // [(0,a0),(1,a1),…]
7 -> fill -> sevens: [i32; 4];                               // [7,7,7,7] (count from the type)
t -> widen<f64> -> wide;                                      // i32 → f64 (also widen<i64>, widen<f32>)
x -> to<bf16> -> stored;                                      // f32 → bf16, rounded once (also to<f16>, to<f8e4m3>, to<f8e5m2>)
v -> sqrt -> root;                                          // math builtins: pipeline form only
angle -> sin -> sine;                                       //   (also cos, exp)
-x -> exp -> decay;
  • map { x -> … } applies an inline block to every element: [T; n] → [U; n]. The block may capture enclosing values (arrays included) — captures are broadcast to every element and recorded explicitly in the IR.
  • fold { acc, x -> … } threads an accumulator in index order: (Acc × [T; n]) → Acc. The compiler may regroup it — lane partials and a tree, split or walked pieces — where step_algebra / fold_tree_step prove the step is a combine whose order is free (§6). On the default face that includes float +, within the stated bound (ADR-0040, ADR-0049); the development modes keep source order.
  • The block is not a first-class function value; lowering turns it into a real (anonymous) function in the graph (MapBody / FoldBody).
  • Math builtins exp, sqrt, sin, cos are written only in pipeline position (x -> sqrt, never sqrt(x)). Each has a contract (its error bound), a reference definition written once from plain operations, and per-target realizations the target declares as capability data — a CPU’s correctly rounded sqrt, a GPU’s measured ex2.approx unit, an ASIC’s CORDIC unit or none. Among the realizations the contract admits, the cheapest is chosen; nothing reads a target’s name (ADR-0042, ADR-0046; mapal_ir::math::choose).

2.7 Choice and repetition: guards and loop

// Choice — a guard block. Arms are pure; only the taken arm computes.
op -> {
    -0-> a + b;
    -1-> a - b;
    -2-> a * b;
    -3-> a / b;      // does NOT run (and cannot trap) when op is 0
    -_-> a % b;      // default
} -> ret;

// Repetition — a loop is a cycle in the dataflow, steered by a guard.
mut k: i32   <- 0;
mut acc: f32 <- 0.0;
loop {
    (k < 4) -> {
        -true-> {
            acc + coeffs[k] * signal[4 + k] -> acc;
            k + 1 -> k;
            -> loop;          // back-edge: go around again
        }
        -false-> acc -> ret;  // exit edge
    }
}

Guard discriminants in Core: -true->, -false->, integer literals (-3->), and the default -_->. Pure guard blocks lower to a Phi (choose-one) step in the IR; which arm’s work is gated (skipped when not taken) is decided by guard_plan (§6). Both arms are always compiled; computing is what is conditional.

2.8 Fanout (parallel by default) and seq

6 -> {
    -> square -> sq;     // branch 1 — independent
    -> double -> db;     // branch 2 — independent, may run at the same time
}
// implicit join: both sq and db are available here
sq -> println;
db -> println;

Fanout branches are headless flows starting from the piped value. Independence is structural: if no branch needs another’s result, they are parallel — no keyword required. Effects (print) may not appear inside a fanout branch (T0201); they belong to the sequential “host spine.” A seq { … } stage is the opposite: an explicitly ordered statement block. It leaves no footprint in the IR — ordering there comes from data dependencies and the effect token (§5).

2.9 Effects, time, and precision annotations

"total = " -> print;      // raw, no newline
total -> println;         // with newline
() -> time -> t0;         // monotonic clock read (milliseconds, f64) — effectful, never reordered
"model.bin" -> read -> model: Model;   // raw bytes of a file → a typed value (annotation required)

(a, b) -> fold: tf32 | f32 { acc, k -> acc + a[k] * b[k] } -> s;
                          // ": compute" — products in this body admit TF32 operands (ADR-0041)
  • print/println, time and read are the effects in Core. In the graph they thread a linear IO token; for prints and clock reads that token pins their order (§5). A read takes the token too, but the token orders nothing it computes: the read is an independent task that starts when the run launches, and only its failure is ordered — delivered as a trap at the first checkpoint past it, in source order (ADR-0045 D8). read loads an array — or a whole struct of arrays, like a model’s weights — from a file; a relative path resolves against MAPAL_DATA_DIR; the array it yields is an ordinary immutable value (ADR-0045).
  • A : compute annotation (: tf32 | f32, : bf16 | f32) on a function, loop/seq block, or map/fold step widens the set of precisions its float products admit. Default is full f32 with an a-priori error bound (§6, precision_plan; §9.2).
  • Operators: + - * / %, comparisons == != < > <= >=, logic && || !, unary -. Division/modulo by zero and out-of-bounds indexing are traps (defined failures), reported in source order.

2.10 Programs at model scale: top-level values, generics, _

Real programs name their sizes once and reuse functions across shapes. Excerpts from examples/llama.mapal (each line unedited; lines between them omitted; the whole file, highlighted, is the full model in §11):

2048 -> hidden_size;
32 -> query_heads;
64 -> head_size;
query_heads * head_size -> query_size;

// A linear layer's weights as the checkpoint stores them: `rows` outputs of `columns` inputs, row by row.
type Matrix<rows, columns> {
    _: [bf16; rows * columns]
}

fn project<tokens, rows, columns>(weight: Matrix<rows, columns>, x: [f32; tokens * columns]) -> [f32; tokens * rows] {
    columns -> iota -> along;
    tokens * rows -> iota -> map {
        cell ->
        cell / rows -> t;
        cell % rows -> row;
        (0.0, along) -> fold {
            sum, column ->
            weight[row * columns + column] -> widen<f32> -> w;
            sum + w * x[t * columns + column]
        }
    } -> ret;
}
  • Compile-time evaluation by dataflow. A non-mut value whose dataflow cone holds no effect and no run-time input is computed before the program runs — by the interpreter, so the value is exact — and replaced by its value. Top-level scalars are computed during lowering (a size must come out as an integer ≥ 1, else L1808); for every other value the graph fact static_plan weighs bytes against work: small and cheap values are embedded, everything else is computed at run time, once (ADR-0048 D3; mapal-lower/src/globals.rs, mapal-rewrite/src/statics.rs).
  • weight[row * columns + column] indexes a Matrix directly: Matrix has only the _ field, so it is its array.
  • (weights.query, normed) -> project needs no sizes at the call: tokens, rows, columns are inferred from the argument types (ADR-0047 D3).
Expand: grammar cheat-sheet (Core productions)
program   := item* EOF
item      := fn-decl | type-decl | top-bind
top-bind  := chain ';'                           // binds program-wide values; no mut, ret, loop or effect
fn-decl   := 'fn' IDENT sizes? '(' params? ')' ('->' type)? (':' compute)? block
type-decl := 'type' IDENT sizes? '{' (IDENT ':' type ','?)* '}'   // a field may be named _
sizes     := '<' IDENT (',' IDENT)* ','? '>'
type      := IDENT ('<' size (',' size)* '>')? | '(' type (',' type)+ ')' | '[' type ';' size ']'
size      := term (('+'|'-') term)* ;  term := atom ('*' atom)* ;  atom := INT | IDENT | '(' size ')'
block     := '{' (stmt | guard-arm)* chain? '}'
stmt      := chain ';' | bind ';' | 'loop' (':' compute)? block
bind      := 'mut'? IDENT ('[' expr ']')? (':' type)? '<-' expr
chain     := expr? stage+                     // headless inside fanout branches
stage     := '->' ( expr | 'mut'? IDENT (':' type)? | 'ret' ('.' INT)?
                  | 'loop' | op expr
                  | '{' guard-arm+ '}' | '{' chain+ '}'
                  | ('map'|'fold') (':' compute)? '{' params '->' block-body '}'
                  | 'seq' (':' compute)? block )
guard-arm := '-' ('true'|'false'|'_'|INT) '->' (chain | block) ';'?
expr      := or ;  or := and ('||' and)* ;  and := cmp ('&&' cmp)*
cmp       := add (('=='|'!='|'<'|'>'|'<='|'>=') add)?
add       := mul (('+'|'-') mul)* ;  mul := unary (('*'|'/'|'%') unary)*
unary     := ('-'|'!')? postfix
postfix   := primary ( '.' (IDENT|INT) | '[' expr ']' )*
primary   := INT | FLOAT | STRING | 'true' | 'false' | '()' | IDENT
           | '(' expr (',' expr)* ')' | '[' expr (',' expr)* ']'
           | IDENT '{' (IDENT (':' expr)? ','?)* '}'

Authoritative grammar: docs/components/syntax/DESIGN.md §14 (the size lists, top-level bindings and generic types are specified in ADR-0047 / ADR-0048 and implemented in crates/mapal-syntax/src/ast.rs: FnDecl::sizes, TypeDecl::sizes, Item::Bind, TyKind::Generic); parser: crates/mapal-syntax/src/parser.rs. Formatting is owned by mapal fmt (four spaces, multiline brace bodies) — run it on every .mapal file you touch.

3AST — what it is and how it is created

The AST is a thin parse tree: syntax, names, spans, literal values, and flags — nothing more. It does no name resolution, no type inference, and no effect classification (crates/mapal-syntax/src/ast.rs). Think of it as the deserializer’s scratch space: faithful to the text, including its mistakes, so diagnostics can be precise. The program, for all later purposes, is the graph (§5).

flowchart LR TXT["source text
&str"] --> LEX["Lexer
lexer.rs → tokens + spans
L-codes for bad literals"] LEX --> PAR["Parser (recursive descent)
parser.rs → Program tree
P-codes, error recovery"] PAR --> OUT["ParseOutput
{ program: Program,
diagnostics: Vec (sorted by span) }"] OUT -->|"clean (no diagnostics)"| NEXT["to lowering §4"] OUT -->|"dirty"| STOP["stop: CLI renders diagnostics"]

3.1 Step by step

  1. Lex. lex(&str) produces tokens, each a kind plus a byte-range SourceLoc { start, end } into the original text. Token text is never copied — consumers slice &source[span] (single source of truth). Malformed literals yield L-code diagnostics but lexing continues.
  2. Parse. A hand-written recursive-descent parser builds the tree following the §2 grammar. Every node carries its span. On error it recovers (synchronizes to a plausible boundary) and records an Error node, so one run can report many problems — 34 P-codes in total (crates/mapal-syntax/src/parser.rs).
  3. Keep the rejected. Forms outside Core (function-call syntax f(x), ?, dynamic arrays [T], custom loop labels, pattern guards) are kept as dedicated node kinds with their diagnostic, rather than silently mis-parsed. Lowering’s job is then a clean “defined exactly on Core” partial map (§4).
  4. Merge + sort. Lex and parse diagnostics are merged and stably sorted by (span.start, span.end). The public entry is parse(&str) -> ParseOutput (crates/mapal-syntax/src/lib.rs).

3.2 The node catalogue

Every node below is a plain Rust struct/enum in ast.rs with a span: SourceLoc. Name is just a span (the identifier’s text is sliced from source on demand). There is deliberately no Display anywhere in the crate — rendering belongs to the CLI.

NodeShapeCarries
Program{ items: Vec<Item> }The whole file.
ItemFn(FnDecl) | Type(TypeDecl) | Bind(TopBind) | Error(span)Top-level declarations; Bind = a top-level binding chain (ADR-0048); Error = recovery region.
FnDecl{ name, sizes, params, ret_ty?, body: Block }Param { mut?, name, ty }; body block may carry a : compute Precision.
TypeDecl{ name, sizes, fields: Vec<Field> }Named product types; sizes non-empty for a size-generic type; a field may be _.
Ty / TyKindNamed | Generic{name,args} | Tuple | Array{elem,len,size?} | Dynamic | ErrorSurface types (distinct from IR types — §4 translates).
Block{ items: Vec<BlockItem>, tail: Option<Chain>, compute? }Statements or guard arms (mixing draws P0006), plus an optional tail chain (the block’s value in map/fold bodies and arm payloads).
Stmt / StmtKindChain | Bind | Loop | ErrorBindStmt { mut?, name, index?, ty?, value } covers both x <- e and c[i] <- e; LoopStmt { label, body }.
Chain{ head: Option<Expr>, stages: Vec<Stage> }One flat pipeline. Chains never nest arrows; headless chains appear in fanout branches.
Stage / StageKindExpr | Bind | Ret | LoopJump | OpShorthand | Guard | Fanout | MapFold | SeqBlock | StmtBlock | ErrorEverything that can follow ->. MapFold { op: Map|Fold, params, body }; OpShorthand wraps an expr with one Hole.
GuardArm{ discr: True|False|Default|Int|OutOfCore, payload: Chain|Block }One -d-> arm.
Expr / ExprKindInt | Float | Str | Bool | Unit | Var | Hole | Unary | Binary | Member | Index | Tuple | Array | Struct | Call | Question | ErrorOrdinary expressions. Float/Str keep only a span (value is type-directed / unescaped later). Call/Question are rejected-but-kept.
Expand: worked example — source text to AST (pipeline function)
fn f(data: i32) -> i32 {
    data * 2
        -> + 5
        -> ret;
}
flowchart TD P["Program"] --> F["Item::Fn FnDecl f
params: [data: i32] · ret_ty: i32"] F --> B["body: Block
items: [Stmt], tail: none"] B --> S["StmtKind::Chain"] S --> C["Chain
head + 2 stages"] C --> H["head: Expr Binary(Mul)
Var(data) · Int(2)"] C --> S1["Stage 1: OpShorthand
Binary(Add, Hole, Int 5)
Hole = the piped value"] C --> S2["Stage 2: Ret
proj: none"]

Three things to notice. (1) The shorthand -> + 5 is already an expression tree with a Hole placeholder — the parser classifies it; lowering just substitutes the incoming value. (2) Nothing here knows that data is the parameter or that the types agree — that is lowering’s typing walk. (3) Every node knows exactly which bytes it came from, which is what later diagnostics (and trap ordering, §10) rely on.

Expand: why keep a tree at all? (vs parsing straight to the graph)

Because the tree is the only place that can represent a broken program, declaration order freedom (lowering walks items three times: types, signatures, bodies), and fanout scope for the effect check. The measured price is ~4 µs of parsing against ~140 ms of LLVM on a real compile. Skipping the tree would save microseconds and cost all three properties. Full argument: docs/architecture/INDEX.md.

4Lowering & checks: tree → graph

lower(&str, &Program) -> Result<CategoryIr, Vec<Diagnostic>> (crates/mapal-lower/src/lib.rs) turns a parse-clean tree into the sealed graph. It is the one place where names become edges. Precondition: the tree came from a diagnostic-free parse; anything else yields L1000, never a panic.

flowchart TD T["Program (clean tree)"] --> R0["Rounds — top-level values + size instances
globals.rs: evaluate top-level chains on the interpreter
sizes.rs: infer each call's sizes, one instance per size tuple"] R0 --> A["Pass A — type table
tys.rs: surface Ty ⇀ IR Ty
struct inlining, Core whitelist"] A --> B["Pass B — effects + call graph
effects.rs: who can print?
recursion rejected (L1008)"] B --> D1["Pass D1 — typing walk, per fn
typing.rs: multi-error surface
return completeness (L1306)"] D1 --> C["Pass C — declare
one input + one output object per fn"] C --> D2["Pass D2/D3 — emit
emit.rs + scope.rs: names → objects
every step → one morphism (fail-fast)"] D2 --> E["Pass E — seal
IrBuilder::seal → immutable CategoryIr"] E --> V{"validate (oracle)
re-derives every invariant
seal Ok ⇒ validate empty"} V --> K["check (mapal-check)
T0101 return exclusivity
T0201 no effects in fanout"]

4.1 What lowering does, in words

  1. Sizes and top-level values (rounds). Top-level bindings form a dependency graph; their scalar values are computed by the interpreter on a small synthetic program and become literals, so they can serve as sizes (ADR-0048 D3). A call to a size-generic function infers the sizes from its argument types; each distinct size tuple becomes one ordinary fixed-size function, so nothing downstream ever sees a size parameter (ADR-0047).
  2. Types first (A). Surface TyKind values are resolved to IR Ty values: named types are looked up and structs inlined, depth is bounded (MAX_TY_DEPTH = 64), and anything outside the Core whitelist is refused. The two Ty types are genuinely different types joined by this partial translation — do not conflate them.
  3. Effects + call graph (B). Which functions can (transitively) print or read the clock, and is the call graph acyclic? A recursive cycle aborts here with the teaching diagnostic L1008.
  4. Typing walk (D1). Each function body is type-checked; this pass collects many errors. Emission afterwards is fail-fast and assumes a well-typed-enough tree.
  5. Declare + emit (C, D2/D3). Each function gets exactly one input object and one output object. Scopes map names to objects; every computation step becomes one morphism built through the checked IrBuilder. Inline map/fold blocks become anonymous functions; captured variables become leading tuple components.
  6. Seal (E). The builder freezes the graph. From here on it is immutable; the only way to “change” it is to build a new one (which is exactly what the rewriter does, §7).

4.2 Desugaring table — surface form to graph form

You writeThe graph getsWhy
a + bPair both operands into a 2-tuple object, then one Add edgeEvery step has exactly one input value. Binary ops take the pair. (“Pair-then-primitive.”)
-> + 5Same as above, with the piped value substituted for the AST HoleShorthand is pure syntax.
(a, b) -> f and x -> fOne Call(f) edge from the (tuple) input objectArrow and call spellings collapse (ADR-0031).
Pure guard blockArm values + discriminant paired, then one Phi edge: (T × T × Bool) → T (multi-arm = nested Phis)Choice is a value-level step, not control flow. Gating is decided later (§6).
Guard steering a loopLoopEnter into a LoopMerge object; LoopBack (fires on true) / LoopExit (fires on false) sharing one BoolThe cycle is the loop. No separate loop node is stored.
c[i] <- xOne Update edge: (array × index × value) → array′Functional update; in-place storage is a backend decision.
map/fold with capturesMap{body, captures=k} / Fold{body, captures=k}; source is (c₁…cₖ, array)Captures are explicit inputs, never hidden environment reads.
x -> printPrint edge: (IoToken × P) → IoTokenThe token threads effects in source order.
"w.bin" -> read -> w: [bf16; n];Read edge from (IoToken × Str); Proj 0 rebinds the token, Proj 1 is the arrayA file read is an effect like time in the graph (ADR-0045); unlike the clock it is not pinned to the host spine — path_plan makes it a task of its own (D8, §6).
2048 -> hidden_size; (top level)Nothing of its own: computed during lowering, then a literal at every use; non-scalar top-level values are emitted where a function reads themCompile-time evaluation by dataflow (ADR-0048 D3).
(w, x) -> project with fn project<rows, columns>Call of the instance project<2048, 512> for the inferred sizesOne fixed-size function per size tuple (ADR-0047 D5/D6).
seq { … }NothingOrdering inside comes from dependencies + token (ADR-0019).
x -> retOne Output edge (the only identity-shaped step)Keeps “every value has one producer” true for the return object.

4.3 The two gates after lowering

  • validate (crates/mapal-ir/src/validate.rs) is an independent oracle: it re-derives every graph invariant from scratch without sharing builder code. The property “seal succeeded ⇒ validate finds nothing” is property-tested. It runs in tests/debug, not as a mandatory production pass.
  • check (crates/mapal-check/src/lib.rs) discharges exactly what the interpreter assumes: T0101 — at most one full-value writer per return object; T0201 — no effectful step inside a parallel fanout branch. It needs the tree as well as the graph, because fanout scope is precisely what lowering erased. This is the one place the tree is consulted after lowering; everything downstream sees only the graph.
5Category IR — the graph, in plain words

Forget the word “category” for a moment. The Category IR (CategoryIr, crates/mapal-ir/src/graph.rs) is a dataflow graph: circles are values, arrows are steps that compute a value. The categorical names stuck because the design borrows two ideas from that world — compose steps by matching output-to-input types and translate the whole graph with meaning preserved — but the data structure itself is ordinary Rust: three slotmap arenas with deterministic iteration order and no HashMap anywhere.

Vocabulary translation (the only category theory on this page).
Object → a value (with a type).   Morphism → a step: one directed edge source → target labeled with an operation.   Composition (f -> g) → plumbing: feed f’s output into g.   Product (A × B) → a tuple.   Functor → a translator (a backend) that maps the graph to another world while preserving the plumbing, hence the answer.   Trace → feedback: a loop.

5.1 What the graph is made of

flowchart LR IR["CategoryIr (sealed)"] --> OB["objects: SlotMap<ObjectId, Object>
ty · kind · value? · name? · loc"] IR --> MO["morphisms: SlotMap<MorphismId, Morphism>
source · target · op · loc"] IR --> FU["funcs: SlotMap<FuncId, FuncDef>
input · output · morphism list"] IR --> ED["in/out edge lists + owner map
(SecondaryMaps, insertion-ordered)"] IR --> FA["facts store (§6)
per-fn OnceLock slots, filled on demand"] IR --> EN["entry: FuncId (main)"]

Objects — the values

Object { id, ty: Ty, value: Option<Value>, kind: ObjectKind, name: Option<String>, loc }
ObjectKindMeaningRule
ParameterThe function’s single input (tuple-typed when multi-param).Exactly one per function.
ConstantA literal.value = Some(v) exactly here; in-degree 0.
TemporaryA computed intermediate (the default).Exactly one producing edge.
ReturnThe function’s output.Exactly one per function.
LoopMergeThe meeting point of a loop: initial value in, next-iteration values around.One LoopEnter + at least one LoopBack.

One struct with an optional value field, rather than separate “constant node” / “inner node” types — the kind tag plus the option carries the distinction. name is the surface variable name, kept only for dumps and debugging; no semantics reads it.

Morphisms — the steps

Morphism { id, source: ObjectId, target: ObjectId, op: Operation, loc }

Exactly one source, exactly one target (invariant I1). Multi-input operations take a tuple object built by Pair edges — there is no “wide edge” type. Well-typedness is therefore a local check at each edge: does this operation accept the source’s type and produce the target’s type?

Expand: the full operation set (37 operations, grouped)
GroupOperationSignature (plain words)
StructuralPair{slot, arity}Inject a value into slot k of a tuple/struct/array product being built.
Proj{index}Read component k out of a tuple/struct.
OutputThe single identity-shaped step: route a value to Return.
ArithmeticAdd Sub Mul Div Mod NegBinary ops take the 2-tuple; Neg is unary (IEEE fneg ≠ 0 − x). Div/Mod may trap.
Compare/logicEq Neq Lt Gt Le Ge And Or NotProduce Bool.
SelectionPhi(T × T × Bool) → T: choose one of two values.
CallsCall(FuncId)Named functions only; input is the argument tuple.
CollectionsMap{body, captures}[T; n] → [U; n] via body T → U (captures prepended when present).
Fold{body, captures}(Acc × [T; n]) → Acc via body (Acc × T) → Acc, in index order.
Index([T; n] × I) → T; out-of-bounds traps.
Update([T; n] × I × T) → [T; n] with one slot replaced; may trap.
Zip / Enumerate([A;n] × [B;n]) → [(A,B);n] / [A;n] → [(i32,A);n].
Iota / Filln → [0..n) (count is a constant object) / T → [T; n] (count carried by the type).
NumbersWideni32→i64, i32→f32, i32→f64, f32→f64; bf16|f16 → f32|f64 (exact).
Narrowf32 → bf16 | f16 | f8e4m3 | f8e5m2: rounded once, to nearest-even (fp8 saturating).
Math(MathFn)Float → Float for Exp, Sqrt, Sin, Cos: pure, total; realization chosen per target by its contract.
EffectsPrint{newline}(IoToken × P) → IoToken.
TimeMsIoToken → (IoToken × f64).
Read(IoToken × Str) → (IoToken × T): a file’s little-endian bytes as the annotated type — an array, or a struct / tuple whose every leaf is one (mapal_ir::read::readable).
LoopsLoopEnter / LoopBack / LoopExitInit into merge / (U × Bool) → U back-edge (true) / (B × Bool) → B exit (false).

Added since the first edition: Read (ADR-0045), Narrow and the narrow Widens (ADR-0043), Math(Exp | Sqrt | Sin | Cos) (ADR-0042, ADR-0046). Deliberately absent vs the frozen spec: Identity (only Output), Const (constants are objects), Trace (the cycle is the trace). Source: crates/mapal-ir/src/graph.rs (Operation).

Types and functions

Ty ::= Int{bits, signed}   // i32, i64, u8 only
     | Float{bits}         // f32, f64 only
     | Narrow(fmt)         // bf16, f16, f8e4m3, f8e5m2 — storage only, no arithmetic
     | Bool | Unit | Str | IoToken
     | Tuple(Vec<Ty>)               // arity ≥ 2
     | Struct{name, fields}         // name is part of equality
     | Array{elem, size}            // size ≥ 1

FuncDef { name, kind: Named | MapBody | FoldBody, input, output, morphisms: Vec<MorphismId> }
  • IoToken is the linear “world” value threaded through effects. It may never be duplicated, stored in an array, chosen by Phi, or captured by a map/fold body — one shared predicate (ty_contains_token) enforces all token rules, deeply (it finds a token nested in ((IoToken, x), y)).
  • A function’s morphism list is an insertion-ordered set, not a schedule. Execution order is recomputed by topo_order (§6) whenever someone needs one — never stored, so it can never go stale.
  • Each float Mul also carries an admitted-precision set (default {f32}; widened by : compute) in a side table on the graph.

5.2 What it looks like — three small DAGs

Graph dumps use Mermaid too (crates/mapal-ir/src/mermaid.rs), so what you see here is the same shape dump-ir tooling shows you. Ellipses are objects (values); labels on arrows are operations.

Example A — pipeline f(x) = x*2 + 5 (straight-line DAG)
flowchart LR IN(["Parameter
data: i32"]) -->|"Pair slot 0"| T1(["(i32 × i32)"]) C2(["Constant 2"]) -->|"Pair slot 1"| T1 T1 -->|"Mul"| M(["t1: i32"]) M -->|"Pair slot 0"| T2(["(i32 × i32)"]) C5(["Constant 5"]) -->|"Pair slot 1"| T2 T2 -->|"Add"| A(["t2: i32"]) A -->|"Output"| R(["Return: i32"])

Notice the pairs: Mul and Add each consume one tuple object. It looks verbose, but it is what makes every later analysis local and uniform — and emission_plan (§6) dissolves these product objects back into plain operand lists at emission time, so they cost no memory.

Example B — fanout (parallelism is just missing edges)
6 -> { -> square -> sq;  -> double -> db; }
flowchart LR C6(["Constant 6"]) -->|"Call square"| SQ(["sq: i32"]) C6 -->|"Call double"| DB(["db: i32"]) SQ --> USE(["…later uses…"]) DB --> USE

There is no path between the two calls, so neither can observe the other. That reachability fact — not an annotation — is the entire parallelism story. path_plan (§6) turns it into tasks.

Example C — a loop (the only cycles in the graph)
flowchart TD INIT(["init state U
(k, acc) packed"]) -->|"LoopEnter"| M{"LoopMerge U"} M --> BODY["decide + advance
cond = k < 4 · next = step(U)"] BODY -->|"LoopBack · fires on true"| M BODY -->|"LoopExit · fires on false"| OUT(["exit value"])

All carried state (k, acc, any mut arrays) is packed into the single merge type U. LoopBack and LoopExit read the same Bool object and fire mutually exclusively — validate enforces that they share it. loop_plan (§6) recovers the canonical init/decide/advance/exit reading from this cycle; the interpreter, rewriter, and both backends all consume that one reading.

5.3 The rules the graph guarantees

These invariants (DESIGN “I-codes”) are what every plan silently relies on. In plain words:

  • One producer. Every non-constant, non-parameter value is written by exactly one edge (a LoopMerge excepted: one enter + back-edges). Dataflow dependencies are therefore exact — no alias analysis, no “may-def” guessing.
  • Typed plumbing. Every edge type-checks locally against its operation’s signature.
  • Tokens stay linear. The IO token is never duplicated or dropped, so effect order is structural.
  • Determinism. Arena storage iterates in insertion order; dumps, topo orders, and emissions are byte-stable across runs.
  • Sealed = trustworthy. Graphs can only be built through the checked builder and are immutable afterwards. Consumers never defensive-check structure the builder already proved.
6Plans — the facts deduced from the graph

A note on the title first, because it corrects a common first guess: plans are not built on the AST. The tree is discarded after lowering/checking. Every plan is a pure query over the sealed graph: fn plan(&self, f: FuncId) -> Plan on CategoryIr in crates/mapal-ir/src/algo.rs and algo/ (≈ 14,400 lines together — the intellectual center of the compiler), with byte and residency facts beside them (access.rs, residence.rs, unit.rs) and the numerics in split.rs, math.rs, narrow.rs. The authoritative one-line-per-fact list is the facts catalog in CLAUDE.md. “Code → plan” therefore means: source → graph → the fact the graph proves. This section is the central record of those plans, their algorithms, and who consumes them.

6.1 The four rules every plan obeys

  1. Facts live on the graph. Each fact is computed at most once per (graph, function) and stored in a pre-allocated OnceLock slot (crates/mapal-ir/src/facts.rs). Facts depend on other facts (path_plan reads loop_plan; tile_plan reads bounds_proof), forming a small dataflow of their own. A query reads the stored value; nothing recomputes per call site.
  2. Partial = safe. If a plan cannot prove its shape, it returns None / empty / false and the compiler takes the slow correct path. A plan can cost performance when silent; it can never change the answer.
  3. Machine-free. mapal-ir answers “is this legal, and what does it need?” (geometry, independence, bytes, lifetimes, proofs, error bounds). Whether it is worth it on a given machine is answered by placement, which reconciles these facts with the machine facts (§8). No chip name and no measured hardware number is stored in a plan; where a fact needs a capacity to answer (e.g. residence_plan: does this value’s working set fit a cache of C bytes?), the capacity is an argument, supplied by the machine side.
  4. One question each. New logic starts by checking this catalog. If a needed fact is missing, it is added here as one tested query — never re-derived inside a backend pass (AGENTS.md standing rule).
flowchart TD G["sealed graph"] --> T["topo_order · sccs
(structure)"] T --> LP["loop_structure · loop_plan"] T --> BP["bounds_proof"] LP --> PP["path_plan
(parallel tasks)"] BP --> PP BP --> TP["tile_plan · cell_plan
footprint_plan (geometry)"] LP --> LU["last_use_plan · write_delta
(lifetimes)"] T --> EP["elem_plan · map_law
(closed-form elements)"] T --> GP["guard_plan · trip_split"] T --> EM["emission_plan
(what materializes)"] LU --> UN["unchanged_plan · call_keep
static_plan (what is fixed)"] TP --> AC["access_plan · residence_plan
(bytes, where they live)"] TP --> US["unit_plan · stream_plan
fold_combine (what runs together)"] PP --> BE["placement (§8) → lowering (§9)"] TP --> BE EP --> BE LU --> BE AC --> BE US --> BE UN --> BE

6.2 The catalog

Filter by text or by group. Each card states the question in plain words, the algorithm sketch, the consumer, and the fallback when the proof fails. Groups: structure order & loops · parallel tasks & gating · geometry kernel shapes · memory lifetimes & materialization · safety proofs & precision.

topo_order(f) -> Vec<MorphismId>structure

Question: in what single order could this function execute, respecting every dependency?

Algorithm
Kahn-style ready walk with a min-heap keyed by (loc.start, loc.end, insertion index) — source order, not compiler-construction order. That choice is observable: when two independent steps can both trap, the one earlier in your source is reported (§10).
Consumers
Everyone: interpreter walk, sequential emission, and as the position basis for last_use_plan.
Fallback
None — total on well-formed graphs (cycles only inside loop SCCs, handled by loop_plan).

sccs(f) · loop_structure(f) -> Vec<LoopScc> · loop_plan(f, merge) -> Option<LoopPlan>structure

Question: where are the loops, and for each one: what is the initial state, the merge point, the decide/advance order, and the exits?

Algorithm
Tarjan SCC over objects; an SCC containing a LoopMerge is a loop region. loop_plan then checks the canonical shape (one LoopEnter, shared condition Bool, exits leaving the region) and records init/merge/decide/advance/exits.
Consumers
Interpreter loop driver, rewrite replayer + loop lifting, both backends’ loop CFGs, path_plan, trip_split, last_use_plan (two-iteration liveness).
Fallback
None ⇒ the region is treated as opaque sequential work; never miscompiled.

path_plan(f) -> PathPlan (+ is_single_path)parallel

Question: what can run at the same time, as an explicit task DAG — and where must the sequential (effectful) world wait?

Algorithm
(1) Order by topo_order. (2) Set aside the host spine: token-touching steps (prints, clock reads) and effectful loops become ordered checkpoints. A file read is the exception (ADR-0045 D8): the Read and its array’s Proj form a task of their own with no inputs, which starts when the run launches; its failure is a trap delivered at the first checkpoint past it. (3) Bulk ops (Map/Zip/Enumerate/Iota/Fill) → Split tasks (element range sliceable); Fold → Seq task; each loop region → one Seq task; remaining scalars grouped by dataflow+co-writing connectivity (never mere sibling reads). (4) Dependencies = “the task that produced each input object” — direct dataflow is the complete relation. (5) Rank = critical-path weight, long poles first. (6) Checkpoints carry per-task watermarks (past-last-trap) or completion when the value is consumed.
Consumers
LLVM backend → one @taskN per task + static dep/rank table → mapal-rt work-stealing pool (§9, §10).
Fallback
Single-path (or malformed) plan ⇒ plain sequential emission.

guard_plan(f) -> Vec<GuardSite> (+ gated())parallel

Question: for each Phi (guard), which work belongs exclusively to each arm — and must that work be gated (not computed when the arm is not taken)?

Algorithm
Per-arm consumer closure (work whose every consumer is inside the arm), with loops joining as whole units via loop_plan. Transitive can_trap/heavy flags through nested sites. Legality first (can-trap must gate), then cost (heavy work gates; two scalar arms are left branchless).
Consumers
Interpreter (skip unchosen arm), LLVM + CUDA host emission (branch around gated work). Both arms stay in the binary.
Fallback
Not gated ⇒ both arms compute, Phi selects — correct only where both arms are total, hence the must-gate rule.

tile_plan(f) · tile_plan_strided(f) · tile_plan_radix(f) → TileSite / TileReadgeometry

Question: is this innocent “one result per element” map secretly a tiled kernel — neighboring outputs computed by lockstep folds reading broadcasts and vector runs?

Algorithm
(1) Skeleton: Map over iota whose body ends in exactly one Fold. (2) Coordinates from a t/C, t%C split (2-D) or the element itself (1-D). (3) Chain shape acc + x*y (either operand order). (4) Each read address decomposed affinely as base + ci·i + clane·lane + ck·k: clane=0 ⇒ broadcast, clane=1 ⇒ vector load, anything else ⇒ refuse. Strided/radix variants widen the coordinate reading (see radix_plan). TileKSplit records when the k axis itself may be split.
Consumers
CPU tiled micro-kernels (NEON/AVX/SME), GPU tile kernels (§9). Records geometry only — tile sizes come from TargetProfile.
Fallback
No site ⇒ ordinary elementwise map emission. Matmul, FIR, conv and attention shapes all match; there is no “matrix” concept in the recognizer.

cell_plan(f) → CellSite / CellRead (+ tree)geometry

Question: per output cell of a map, exactly what does it read — and is its fold step regroupable as lane partials + a tree?

Algorithm
Generalizes the tile reading per cell: affine reads with reach classification, independent cells across threads. CellSite::tree marks steps whose order is free (§6 fold_tree_step), enabling tree reductions where the float face permits (§9).
Consumers
GPU one-thread-per-cell / cooperative kernels; CPU cell kernels.
Fallback
No site ⇒ generic map path.

footprint_plan(f) -> FootprintPlan (of, rect, at)geometry

Question: for each consumer, what region of each producer does it actually touch?

Algorithm
Per producer→consumer edge, the touched footprint (rectangles / affine reaches with taps). This is the fact that replaces any “fusion pass”: whether work runs together, stays in registers/shared memory, or is stored follows from footprints + death points + the target (§9). Kernel boundaries are a result, never a pass.
Consumers
Backend work-unit formation, residency and staging decisions.
Fallback
Whole-array footprint ⇒ materialize and pass the buffer.

elem_plan(f) -> ElemPlan · map_law(m) -> Option<ElemSrc> (+ Outside)geometry

Question: what is out[i], as a closed function of i — can a consumer recompute (or directly source) elements instead of materializing the array?

Algorithm
Per array object, an ElemSrc law: element i expressed via sources, piecewise when every cell outside a row/range/column/single cell is a capture’s own element (the in-place range-map shape). map_law gives the same for one Map.
Consumers
Backends decide recompute-vs-store per target (GPU: usually recompute; CPU: vs L2 round-trip; FPGA: BRAM vs area) — the plan records legality, never the choice.
Fallback
No law ⇒ the array materializes.

row_fold(f) · whole_fold(f) → RowFoldSite / RowFoldOp · fold_tree_step(fold)geometry

Question: is this fold really “one row at a time” (or the whole function folded over one affine read) — and may its step be regrouped?

Algorithm
Recognize folds whose reads are affine in (row, k): softmax/decode and reduction shapes. fold_tree_step proves the step is an order-free combine (e.g. +/max under the admitted face), licensing lane-partials + tree reduction.
Consumers
Row kernels, split-K / tree-reduction emission.
Fallback
Sequential accumulator chain, exact source order.

move_plan(f) -> MovePlan / MoveSitegeometry

Question: where is data merely moved (transposed, gathered, re-laid-out) rather than computed — with what affine source pattern?

Algorithm
Sites whose element law is a pure affine re-indexing of one source. Backends traverse them in cache-blocked panels derived from TargetProfile geometry instead of element order.
Consumers
Transpose/pack/panel traversals on CPU; staging on GPU.
Fallback
Element-order copy.

emission_plan(f) -> EmissionPlan (class(o))memory

Question: which objects must actually materialize in emitted code — and which are just graph plumbing?

Algorithm
Classify each object: dissolved (products/views — no bytes, e.g. Pair tuples), inline (single-use scalar, emitted at its use), or named (needs storage), from consumer counts and kinds. Minimal emission: if it has no bytes in the semantics, it gets no bytes in the binary.
Consumers
All backends (naming, SSA/alloca decisions); CUDA minimal-emission path.
Fallback
Named ⇒ allocate; always safe.

last_use_plan(f) -> LastUsePlan (position · death · escapes · carried_by · dead_after, view variants)memory

Question: for each value, where is its last read — does it escape into the output, is it carried around a loop, and after which step is its storage free?

Algorithm
Positions from topo_order; death = max position over consumers; carried_by marks values crossing a LoopBack (live across two iterations); view-aware variants track dissolved products to their storage. Lifetimes are exact because every read is an edge.
Consumers
Buffer coloring/reuse (arena), in-place Update, free-at-back-edge, host↔device retention (§9). This is Mapal’s “memory model”: no GC, no ownership annotations — last-use is the lifetime.
Fallback
Escaping/unknown ⇒ keep alive to function end.

write_delta(f) → per-object Deltamemory

Question: for a loop-carried array, what contiguous range does each trip actually write?

Algorithm
Chase Updates and piecewise map laws around the loop to a per-trip written interval. A partial update then moves/retains only the delta across host↔device or iterations, instead of the whole array.
Consumers
Residency/retention, delta copies, cache decisions.
Fallback
Whole array is the delta.

trip_split(f) -> Vec<TripSplit> (TripPhase)structure

Question: for a counted loop, what trip intervals do guards on the counter cut out — which state is recurrent in each, what work sits outside, and can all-but-last trips of the first interval be skipped?

Algorithm
Counter-guard analysis over the loop_plan: phases with their recurrent slots, batched row writes, and the skip fact. Turns “loop with cases inside” into “phases the backend can schedule separately.”
Consumers
Loop emission (phase splitting, batching).
Fallback
One phase = the whole loop, guard evaluated per trip.

bounds_proof(f) -> BoundsProof (proven(m))safety

Question: which Index/Update steps are provably in bounds, so their trap guard can be dropped?

Algorithm
Affine/range reasoning over index expressions against static array sizes (iota-derived indices, div/mod decompositions, counter ranges). Only proven guards drop — “which bounds checks are provably unnecessary, and only those.”
Consumers
Guard elision in LLVM + CUDA emission; also read by tile_plan/path_plan (trap capability feeds watermarks).
Fallback
Unproven ⇒ keep the check; the trap remains possible and ordered.

precision_plan → set · round_at · cross · bound · exp · math · narrow · store (+ mapal_ir::split; ADR-0040…0044, 0046)safety

Question: which precisions does each float product admit, where may a value be rounded (once, at its producer), which edges must a rounded copy not cross, and what is each tile site’s a-priori error bound?

Algorithm
From the per-Mul admitted sets (innermost : compute wins): propagate rounding points to producers, mark edges a rounded copy would corrupt, and compose the weakest-member bound per site. Default face: full precision + bound + unspecified order, fastest on the native CPU+GPU; exact/contract faces are opt-in (§9).
Also
Each math builtin’s form and contract (math, exp); each narrow rounding’s form (narrow) and whether one format embeds exactly in another (the tensor-core admission over narrow storage); store: an f32 array read only by bf16-admitting products is stored rounded once by its producer. mapal_ir::split prices split realizations of a full-f32 product on a matrix instruction (two or three narrow parts per operand, ADR-0044): a coefficient admitted only if it meets the default face’s bound at the site’s K.
Consumers
Tensor-core eligibility (TF32, 16-bit, split forms), narrow storage, the choice of math realizations, value gates in tests (check the bound, not bit-equality, on the default face; mapal run --interp --bound prints the composed bound).
Fallback
{f32} everywhere — no rounding, bound is the f32 one.

radix_plan(f) → RadixFormgeometry

Question: is this integer really “digits” of the inputs — (x ÷ s) % r with constant divisors?

Algorithm
Recognize constant div/mod digit decompositions per object. Map/fold reads affine per digit then become tile sites over (i, lane, k) — the implicit-GEMM reading that lets convolution-shaped index arithmetic reuse the tile machinery.
Consumers
tile_plan_radix → tile kernels for conv/window shapes.
Fallback
Plain integer arithmetic, ordinary addressing.

static_plan(f) -> StaticPlan (fixed · roots → StaticRoot · Realize; ADR-0048 D3)structure

Question: which values can be computed before the program runs — and is it worth embedding them?

Algorithm
A value is computable when it depends on no input slot (unchanged_plan.inputs = 0 — the IO token counts as an input), its cone reads no file, and a loop is taken only whole. The roots are the computable values a run-time value reads. Each root carries its bytes, cells and the interpreter’s work over its cone; the rule weighs bytes against work: Embed (≤ 1 KiB, ≤ 2²⁰ steps, more steps than cells, no closed-form element law), Attempt (an uncounted loop, 2¹⁸ steps), else Compute.
Consumers
fold_static (crates/mapal-rewrite/src/statics.rs), before the rewriter; OFF arm --static=off.
Fallback
Compute: the value is computed at run time, once, where the other facts place it.

unchanged_plan(f) (trip · same · inputs) · call_keepmemory

Question: what is unchanged since last time — per loop-body array, which cells may differ from the previous trip; which values are equal on every trip; which input slots each value depends on; and per call site, which callee inputs are the same at every execution?

Algorithm
write_delta carried through row-local maps (row folds, per-row scales, projections, windows) as Rows / Pieces / Top; equal-every-trip values; input-slot masks. call_keep reads the callee’s masks at each site.
Consumers
Retained cells and gathered rows: a decode loop written without a cache, recomputing every position each trip, gets one from this fact — only the changed rows are recomputed (func/retain.rs, func/resident.rs; benches/results/evidence/local-rtx-5080/caching-memory.md). Values the same on every trip are made once; retain-call.
Fallback
Everything recomputed and moved every trip.

access_plan (reads · writes · class · edges) · residence_plan (at → Chip | L2 | Dram)memory

Question: how many bytes does each step read and write, which steps conflict (read-after-write, write-after-read, write-after-write) within a loop trip — and where do a value’s bytes live between their producer and their last reader?

Algorithm
access_plan: bytes through Pair/Proj views, storage classes (a carried slot’s views, an Update with its array), hazard edges per trip — the order device work is placed from. residence_plan: the peak live bytes over a value’s interval against a cache capacity the machine side supplies.
Consumers
Device placement by bytes moved, whether a GPU operand is read from DRAM or L2 (MAPAL_SITE_COLD trials, evict-first loads), the cost terms in §8.
Fallback
Whole-object bytes; DRAM residence.

unit_plan (UnitGroup) · stream_plan (StreamGroup, roles)geometry

Question: which tile sites, folds and cells reading the same rows can run as one unit with their rows kept on chip — and which of those groups can stream, as one pass over windows of an axis?

Algorithm
unit_plan: row-block groups whose every edge stays inside its rows; on-chip row buffers colored by death. stream_plan: a group whose tile folds over an in-group row’s cells — scores → softmax → weighted sum, i.e. attention — each member with a role (Produce, Cell, Fold, Consume, Row), each fold’s combine and each per-row value’s law from fold_combine, guard sides (a causal mask through a positions array) decided per window. Axis-wide values are never stored.
Consumers
The streamed (“flash-style”) attention kernel, on tensor cores for 16-bit operands; causal window skip; bf16 key/value windows.
Fallback
Each member its own launch; rows stored between them.

fold_combine (DepLaw::{Factor, Shift, Rescale, Phase}) · step_algebrageometry

Question: if a fold is cut into blocks, how do the blocks’ partial states combine — and what happens to values that are constant along the fold’s axis?

Algorithm
The state combines by the fold’s own operator. A value constant along the axis enters by a law: a factor applied once after the combine, a shift of a max/min, a rescale (it enters only as exp(κ·(x − v))·y: each block takes its own shift and is rescaled when combined — the online-softmax law, ADR-0042 D7), or a phase (it needs the partials combined first). step_algebra: product–accumulate pairs that may be one FMA, and fold steps that may regroup as lane partials + a tree — one realization rule shared by host and device.
Consumers
Row slices, split-K, stream-K walks, streamed attention, FMA contraction.
Fallback
One block, in order.

tensor_form · tile_plan_post (TilePost) · tile_plan_narrowgeometry

Question: is a tile operand a dense tensor whose panels are rectangular boxes; what does the cell compute after its fold (an epilogue); and which operands are exact widenings of 16-bit storage?

Algorithm
tensor_form: the operand as a ≤ 3-axis tensor over (row, lane, k), and whether boxes tile it exactly (what a bulk-copy engine such as TMA can fetch). tile_plan_post: the residual, scale, mask or per-row divisor after the fold, derived from the body, ending possibly in the stored rounding. tile_plan_narrow: each read’s storage format and bytes.
Consumers
Tensor-core tiles and their copies, epilogues computed in the tile instead of a separate pass, operand traffic in the cost terms.
Fallback
No box: lane copies; no epilogue: a separate cell map; f32 operand bytes.

trap_cell_plan (CellSite::traps)safety

Question: which maps are refused as device cells only because an index could not be proven in bounds?

Algorithm
The cell_plan refusals whose only reason is an unproven Index. Such a map runs on the device anyway: each cell checks its index, a failure is recorded in a module word, and the trap is raised at the next host checkpoint — a print, a clock read, a host trap, the exit, or a device-to-host copy, the only ways a device value reaches the host (rung device-trap).
Consumers
GPU cells; the runtime’s checkpoint hook (mapal_rt_checkpoint_hook, mapal_gpu_trap_arm).
Fallback
The map stays on the host.

Supporting queries you will meet in the source: func_objects (a function’s object set) and per-function trap capability (can this function trap, transitively?) — both stored facts feeding the plans above. Deep dives with line references: docs/architecture/deduced-queries.md.

6.3 Code → plan walkthroughs

Three programs, three different plans. In each case the source says nothing about the optimization — the graph proves it.

Walkthrough 1 — independent maps → path_plan tasks
fn main() {
    [1, 2, 3, 4] -> a: [i32; 4];
    a -> map { x -> x * 2 }  -> b: [i32; 4];
    a -> map { x -> x + 10 } -> c: [i32; 4];
    (b, c) -> zip -> map { p -> p.0 + p.1 } -> d: [i32; 4];
    d[0] -> println;
}
flowchart TD A(["a"]) -->|"Map ×2"| B(["b"]) A -->|"Map +10"| C(["c"]) B --> Z["Zip + Map add"] C --> Z Z --> D(["d"]) D --> P["Print d.0 — host spine"]
StepWhat the plan concludes
ClassifyTwo Maps → two Split tasks (T1, T2). Zip+Map → Split task T3. Print → checkpoint, not a task.
DependenciesT3 depends on T1 and T2 (they produced b, c). T1, T2 independent — they merely share a read of a, which never creates an edge.
CheckpointPrint consumes d[0], so T3 must complete (not just pass its last trap point) before the host proceeds.
EmissionThree @taskN functions + dep/rank table; the pool runs T1‖T2, then T3 sliced across lanes. Output bytes identical at any thread count.

The same mechanism at program scale: two independent neural nets in one main overlap for free (measured 1.34–1.36× vs the same flops chained) — nothing in the source asks for it.

Walkthrough 2 — idiomatic matmul → tile_plan geometry
16384 -> iota -> ta;                       // the 128×128 cells, flattened
128 -> iota -> krange;
ta -> map { t ->
    t / 128 -> i;
    t % 128 -> j;
    (0.0, krange) -> fold { acc, k -> acc + a[i * 128 + k] * b[k * 128 + j] }
} -> c;                                       // examples/matmul128.mapal (abridged)
Recognition stepResult
SkeletonMap over iota(16384), body returns one Fold over iota(128). ✓
Coordinatesi = t/128, j = t%128, same constant ⇒ 2-D, 128 rows, lane = j.
Chainacc + (a[…] * b[…]) — multiply-accumulate. ✓
Read a[i*128 + k]base + 128·i + 0·lane + 1·k → clane = 0: every lane reads the same a element per k — a broadcast.
Read b[k*128 + j]base + 0·i + 1·lane + 128·k → clane = 1: neighboring lanes read neighbors — one vector load per k.
Safetybounds_proof: indices affine over proven ranges ⇒ trap-free site; guards elided inside the kernel.
flowchart LR LANE["lanes j, j+1, j+2, j+3
(one vector register of cells)"] --> STEP["per k: acc += broadcast a[i,k]
× vector-load b[k, j..j+3]"] STEP --> STORE["after k = 0..128:
store 4 finished cells once"]

The plan records only this geometry. How many lanes per register block, how deep to tile for L1/L2, whether to pack b — those constants come from the machine profile in §9. The same recognizer (one affine-address rule, no matrix concept) also fires on FIR windows and conv stencils.

Walkthrough 3 — FIR loop → loop_plan + bounds_proof + last_use_plan
fn fir4(signal: [f32; 8], coeffs: [f32; 4]) -> f32 {
    mut k: i32   <- 0;
    mut acc: f32 <- 0.0;
    loop {
        (k < 4) -> {
            -true-> {
                acc + coeffs[k] * signal[4 + k] -> acc;
                k + 1 -> k;
                -> loop;
            }
            -false-> acc -> ret;
        }
    }
}   // examples/fir.mapal
PlanWhat it proves herePayoff
loop_planMerge U = (k, acc); init (0, 0.0); decide k<4; advance computes next U; single exit carrying acc.One canonical reading shared by interpreter, rewriter, CPU loop CFG, GPU loop handling.
bounds_proofOn the true arm 0 ≤ k ≤ 3, so coeffs[k] (size 4) and signal[4+k] (size 8, index ≤ 7) are in bounds.Both trap guards dropped inside the loop body.
last_use_plank/acc are carried_by the merge (live across the back-edge); signal/coeffs die at loop exit; nothing escapes except via Return.Carried scalars live in registers/frame slots reused each trip; no per-trip allocation.
guard_planThe loop fork is the LoopBack/LoopExit pair on one Bool — mutually exclusive by construction.The exit arm’s work never runs mid-loop and vice versa.
Walkthrough 4 — sepia image filter → map law, gating, single-path check

examples/sepia.mapal maps a per-pixel block (three clamped channel mixes) over [Pixel; 16], then folds the red channel. What the plans see:

  • map_law/elem_plan: out[i] = Pixel{ clamp(…pxᵢ…), … } — each output pixel is a closed function of input pixel i alone ⇒ cells independent; a backend may fuse the following fold’s reads or recompute instead of storing, per target economics.
  • guard_plan: inside clamp, both Phi arms are scalars (no trap, not heavy) ⇒ left branchless — gating them would cost the map body its vectorization. Legality-then-cost in action.
  • path_plan: the map is one Split task, the fold one Seq task depending on it, the final println a checkpoint. At 16 pixels the backend’s roofline test (§9) will run it on the calling thread — dispatch must pay for itself.
7Rewriting — same answer, smaller graph

Plans observe; the rewriter (crates/mapal-rewrite/) is the one component allowed to change the program — under a strict contract: eval ∘ rewrite = eval (the interpreter must produce byte-identical output, traps included, before and after). Because sealed graphs are immutable, every pass works as analyze → plan → replay: a pure analysis produces a RewritePlan, and one shared replayer rebuilds a fresh sealed graph through the public builder — so output well-formedness holds by construction.

flowchart TD G0["sealed graph"] --> FS["fold_static
compile-time evaluation (static_plan)"] FS --> G["sealed graph"] G --> AN["analyses (pure)
const-fold · DCE · CSE
map fusion · inline · loop lift"] AN --> RP["RewritePlan
(six channels)"] RP --> RE["replay via IrBuilder
→ new sealed graph"] RE -->|"changed? (≤ MAX_ROUNDS)"| G RE -->|"fixpoint"| OUT["rewritten graph → backends"]
Layer / passDoesJustified by
Compile-time evaluation (statics.rs, fold_static)Before the rounds: embed the values static_plan marks Embed (computed by the interpreter, so exact) and drop their cones; leave the rest computed at run time.ADR-0048 D3: a value whose cone reads no input and no effect has one value on every run.
Inline (strip)Expand small single-use calls into their callers (body-size capped).Call = composition; substitution preserves the plumbing.
Loop lifting (R-LF/R-LM)Recognize counted loops and lift them to Map/Fold form where the cycle is a disguised bulk op.loop_plan canonical shape + trip analysis.
Map fusion + map(id) (functor_laws)map g ∘ map f → map (g∘f); drop identity maps.The functor laws for Map — with the hard lesson pinned by tests: a body is judged by all its effects (a dead trapping division still traps), never by its return value alone.
Constant folding (equations)Evaluate closed subgraphs; resolve constant guards (dropping the losing arm only under the same conditions gating would apply).Interpreter semantics on constants; guard-ownership discipline from guard_plan.
DCE / CSE (graph_rewrites)Remove unread pure work; merge duplicate steps. Equal element views outside guard arms are keyed by value, so they are one object — one host view, one device copy (a model’s weights upload once). Trapping cones are pinned (a dead 7/0 still traps) unless gated away soundly.Purity + trap-preservation rules (R4).
Naturality table (naturality)Data-only law table (e.g. Proj commutes with Map over products) consulted by the passes above.Stated equations between operations.

The standing design pressure: move work from rewrite into plans. A wrong plan costs speed; a wrong rewrite costs correctness. So tiling is a plan (not a “tiling pass”), element laws are recorded rather than deleted, and after every rewrite round all facts are simply recomputed on the new graph — cheap and safe precisely because plans are pure functions with nothing to invalidate. The gate is the differential suite: thousands of generated programs (crates/mapal-rewrite/tests/testgen/) checked against the oracle at -O0 and -O2, values and traps.

Skip it with mapal … --no-rewrite; compare stages with dump-ir --stage=lowered|rewritten.

8Reconciliation — placing the dataflow on the machine

Sections 5–7 built one side of the picture: a graph and the facts it proves. This section adds the other side — the hardware, written down as facts of the same kind — and the compile phase that brings the two together. The design is ADR-0050 (“the machine model”); the idea in one sentence: compilation places the dataflow on an abstract machine by one evaluator and one search, and only then writes the target’s language. Which work runs on the host or the device, which instruction computes it, how it is tiled and walked, where each operand lives and how it gets there — all of that is placement, and placement is a phase of compilation like typing or lowering, not a set of choices hidden inside kernels or tables.

Status, honestly. ADR-0050 was accepted on 2026-11-26. Step 1 — GEMM-shaped (sum-of-products) tile sites on the GPU — is in progress: its first commit (C1, 30f1a32f) added the target-agnostic crate crates/mapal-place — machine facts with provenance, the schedule, the evaluator, reuse by distinct bytes and an exact LRU simulator — but it depends on no other workspace crate, nothing depends on it, and no placement decision reads it yet. When it lands, it sits behind the switch machine-place, off by default until a measured confirmation turns it on. Until then, and as its OFF arm afterwards, placement is decided by today’s rung rules: per-decision rules that already read physical properties rather than chip names (crates/backends/llvm/src/rules.rs, §9.3). Everything below marked “today” describes the shipped code; everything marked “ADR-0050” describes the design being built.

flowchart TD subgraph DF["Dataflow side — what the program needs (mapal-ir, §6)"] G["sealed, rewritten graph"] --> DFACTS["dataflow facts
tile_plan · tensor_form · access_plan · residence_plan
last_use_plan · path_plan · unit/stream_plan
precision_plan: the error bound each site admits"] end subgraph MS["Machine side — what the hardware offers"] HWQ["device query · calibration probes (calib.cu)
· a design's declared parameters (ASIC)"] --> TRX["Machine::of(target)
the only target-specific code placement reads"] TRX --> MFACTS["machine facts, each with its provenance
places (a graph of instances) · executors + operations
movers · dispatch"] end DFACTS --> GEN["candidate schedules
generated bottom-up from both layers"] MFACTS --> GEN GEN --> FEAS["feasibility filter
capacity ∧ numerics (the bound)
∧ the lowering admits it"] FEAS --> EVAL["one evaluator
predicted time per phase = max over resources of work ÷ rate
compute · movement · latency · issue · combine · fixed"] EVAL --> SEARCH["one search
branch and bound · intervals evaluated at their ends · error band"] SEARCH --> SCHED["schedule
operation + operand roles · levels · homes, layout, depth
traversal: ordered / split / walk / hybrid · launch mode"] SCHED --> LOWER["lowering into the target's language
LLVM IR · NVPTX to PTX · later AMD, Verilog"] LOWER --> GATE["post-lowering gate
real registers and spills"] GATE -->|"infeasible: take the next candidate"| SEARCH GATE --> TS["target-specific step
kept minimal, each item listed"] TS --> EXE["executable
+ the schedule and its predicted terms in the module (mapal.place)"] EXE -.->|"measured against predicted"| CHK["evidence pass: outside the error band = a finding
a missing machine fact or evaluator term, fixed in the model"] CHK -.-> MFACTS

8.1 Two fact layers

Dataflow facts — what the program needs

Deduced from the sealed graph by mapal-ir (§6): which cells are independent, what each cell reads and with what geometry (tile_plan, tensor_form), how many bytes cross each edge and conflict per loop trip (access_plan), when each value dies (last_use_plan), which work can run as one unit (unit_plan, stream_plan), how partial results combine (fold_combine), and how much error each product may carry (precision_plan).

Machine-free: the same facts for every target. Checked by property tests over generated programs.

Machine facts — what the hardware offers

The target described as abstract compute and placement facts: places where bytes can live, executors and the operations they run, movers that carry bytes, and how work is dispatched (§8.2). Nothing in them is a chip name or an instruction-set version; a new part is a new set of facts. Under ADR-0050 each fact says where it came from: measured, queried, declared (by a spec, RTL parameters, a simulation), derived or nominal, with an interval (mapal-place’s Src).

Today these live in TargetProfile (crates/backends/llvm/src/profile.rs): the device query plus the calibration line of benches/gpu/calib.cu for native-gpu, with no provenance per value — an uncalibrated part borrows the RTX 5080’s measurements, and some fallbacks are tables keyed by compute capability (§9.1). ADR-0050 translates them by Machine::of(target), marking each borrowed value as derived.

Placement is the phase whose job is to read both. That is the separation the project has been heading toward since its first optimization rule: “Optimizations derive from Mapal dataflow facts … + TargetProfile hardware facts” (CLAUDE.md, standing rules) and “hardware is physical properties, never a name or version” (2026-11-20). ADR-0050 takes the last step: the decision itself becomes one model over both layers instead of many rules.

8.2 The machine facts

Four kinds of fact describe any target, CPU, GPU, accelerator or a design still being synthesized. Each target sets the depth of its own trees; nothing below assumes a GPU (ADR-0050 D2).

Places — where bytes can live

A graph of instances (a tree is the common case): registers, shared memory, tensor memory, an ASIC’s SRAM banks, each L2 partition, a NUMA node, the host’s memory. A place has a capacity; a scope — the executors that reach it, by reach edges carrying bandwidth, latency and transaction size; a banking rule; and a management: explicit (the program addresses it) or cache. A cache also lists its instances, which executor or address maps to which, whether a line read through two instances is held twice, and its measured hit-against-distance curve — how many distinct bytes it really keeps for a cyclic, rotated or strided pattern, never the nominal size. Splits the schedule chooses (shared memory against L1) are places too.

Executors — what computes

A tree of the target’s depth (device → units → sub-partitions → groups → lanes). Operations are rows of geometry owned by some executor level: the shape (m, the set of n, k, batch), the operand and accumulator formats, each operand’s home place, its allowed layouts and which lane holds which element, latency and how many may be in flight, the measured rate and efficiency curve, and the accumulator’s numerics (ADR-0043). A scalar FMA is the 1 × 1 × 1 row; tensor-core instructions, a CPU vector FMA, an SME outer product and a systolic array are rows of the same table (below).

Movers — how bytes move

Program-issued copies (lane loads, cp.async, bulk-copy engines such as TMA with their box shapes, swizzles and multicast), hardware-issued ones (prefetch streams: what starts them, how far they reach), and links between machines — host ↔ device, with the rate by source (pinned or pageable) and the copy engines. Per-access cache policies (evict-first, persisting windows) are mover options.

Dispatch — how work reaches executors

A unit’s resources as capacities — so occupancy is derived from a schedule’s footprint, never a constant; which grid index lands on which unit; how a grid’s blocks start (all at once or staggered, measured); launch modes (plain, dependent overlap, cooperative, cluster) and their costs; barriers; atomics as a resource at the place that resolves them; the zero pass; the clock the part sustains under load.

Operation row (examples)Issued byShape m × n × kOperands from → accumulator inIn Mapal today
Scalar FMAone lane1 × 1 × 1registers → registersCPU and GPU
CPU vector FMAone core’s vector unit1 × w × 1 (w lanes)vector registers → vector registersvia LLVM’s vectorizer
Arm SME fmopaone corean outer product per instruction (16 × 16 f32 at a 512-bit vector length)vector registers → the ZA arrayapple-m4-sme profile
mma.sync.m16n8k16 (bf16/f16), m16n8k8 (tf32)a warp (32 lanes)16 × 8 × 16 / 16 × 8 × 8registers (fragments) → registers, f32yes (sm_80 and later)
wgmma.m64nNk8 (tf32), m64nNk16 (bf16/f16)a warpgroup (4 warps)64 × N × 8 / 64 × N × 16, N a multiple of 8a: shared memory or registers, b: shared memory → registersyes (H100), fed by TMA
tcgen05.mmaone thread for a block or a block pairlarger tilesshared memory → tensor memoryno — a row the table must hold
AMD MFMAa 64-lane wavefronte.g. 32 × 32 × 8 (f16)vector registers → accumulation registersno — the AMD translation (roadmap)
Systolic arrayan ASIC’s PE arrayR × C, k streamedSRAM banks → the PEsno — a synthesis template (D7)

Rows are geometry, not names: placement maps a site’s tile geometry onto whichever rows the target has. The fact categories are kept apart on purpose: machine facts (above); lowering-declared counts (a schedule’s registers, instructions per class per trip, its in-flight ring — checked against ptxas -v and SASS); and fits (a curve of one Mapal kernel), which the evaluator never reads — they stay only as replay lines until the evaluator reproduces them, then are deleted. Under ADR-0050 a missing fact takes a visibly marked derived or nominal interval, or removes the candidates that need it; no value is borrowed silently from another part or looked up by version. Today’s profiles still do both (§9.1).

8.3 The reconciliation: a schedule, one evaluator, one search

For each site (step 1: sum-of-products tile sites; later every cell, fold and streamed unit) placement produces a schedule (ADR-0050 D3):

Schedule partWhat it fixes
Executor subtreeHost, device, or both.
Operation and operand rolesWhich row of the operation table computes it, and which input plays a and which b (a transposed product is a role swap).
LevelsAny number of loop extents, each bound either to an executor level (parallel: blocks, warps, lanes) or to a place (sequential blocking: a CPU’s register tile, L1 and L2 panels).
Homes, layout, depthEach operand’s place at each level, its padding and swizzle, how many buffers deep; packing as a scheduled copy priced by its bytes; producer and consumer roles inside a block (warp specialization).
TraversalOrdered with a raster; split along k into S pieces (atomic or workspace); walked (stream-K over every resident slot); hybrid (whole waves ordered, the tail walked).
Launch and policiesLaunch mode, cache policy per access, capacity splits; operands still resident from the previous call (residence_plan) are inputs.

Feasibility = every place’s footprint fits its share ∧ the numerics admit it (the operation and its number of pieces — 1, S, or unbounded for a walk — are within the site’s a-priori bound, ADR-0040/0041/0043/0044) ∧ the lowering can emit it. Then one evaluator prices every feasible schedule the same way (ADR-0050 D4):

TermWhat it counts
computeThe busiest unit’s work — ⌈tiles / slots⌉: full waves and the tail — at the operation’s measured rate and efficiency, at the sustained clock.
movementBytes across each place boundary ÷ its bandwidth. Into explicit places the bytes follow from the levels exactly; out of a cache they follow from reuse distance: the distinct bytes the cache sees between two reads of a slice, counting every stream through it (operands, stores, partial sums, the zero pass, workspaces), checked against an exact LRU simulation.
latencyBytes in flight per unit against bandwidth × latency of the source.
issueThe lowering’s declared instruction counts per class against the unit’s issue rates.
combineAtomics as a resource at their place, workspace bytes, the zero pass once, a pipeline fill per split or walked piece.
fixedLaunches and gaps, barriers, grid syncs, link transfers.

One search (D5) generates candidates bottom-up from the facts — operations the precision set admits, group tiles whose footprint fits the operation’s home, block tiles and depths within capacities for every feasible occupancy, traversals and launch modes — and prunes by admissible lower bounds (peak compute; every operand read once) and dominance. The top candidates go through a post-lowering gate: the code generator’s real registers and spills; a spill makes a candidate infeasible and the next one is taken. Facts with intervals are evaluated at both ends; a pick that flips inside them is marked open. The model’s error band is itself a fact (replay residuals): a new schedule replaces the incumbent only beyond it, so a re-measured rate does not churn the emitted code.

8.4 After placement: lowering, then a minimal target-specific step

A lowering emits any feasible schedule of the kinds it declares, and declares its constraints, its instruction counts and its footprints (D6). Layout is in the model (its bank-conflict cost is a fact); only the bit encoding is the lowering’s. What cannot yet be a machine fact — a code generator’s register-allocation quirk, a driver fault’s workaround, an index-width or unroll flag — is a separate step after lowering, keyed by properties and listed with why it is not a fact yet and what would make it one (the planned docs/target-specific.md; that list must shrink over time and must not grow per target). Each site’s schedule, predicted time, terms and any open flip are written into the module as a ; mapal.place line (D8), next to the existing ; mapal.ptx capability line.

8.5 How it helps — with this project’s own evidence

Interactions are priced, not patched

Today about seventeen decisions — placement, kernel kind, tile shape, staging, combine and split, raster order, the walk, epilogue and kernel boundaries, the zero pass, residency, concurrency — are each made by their own rule, in a fixed order, each reading the subset of facts it was written for (304 cited measurements over 68 rung names in rung_replay.tsv). The mma-walk rung (2026-11-25) priced how full the SMs were but not where the operands live while the walk scatters their readers: the L2 fact (l2_keep_bytes) existed, outside that rule’s view, and the walk lost — ×1.21 on the RTX 3090’s suite row, ×1.04 on the A100’s down projection (788 against 761 µs a layer; benches/results/evidence/hopper/disasm-rented.md). The fix added the fact to that one rule (MmaWalk::walk_bytes, b3ad75f4). ADR-0050’s design check then found that rule counts requested bytes where a cache evicts on distinct bytes. By the model’s count — an exact LRU simulation, not a measurement (the rented boxes had no profiler counters) — the RTX 5080’s 3072 × 4096 × 8192 product requests 1685 MB against 124 MB distinct, so the rule refused that walk for a reason the simulation does not support. The measured times there favoured refusal anyway (ordered 1836 µs against the walk’s 1829 µs + a 39.8 µs zero pass): a wrong reason, not a wrong pick. In one evaluator, reuse distance is one term every traversal pays.

A new target is a translation and a lowering

Because placement reads only machine facts, adding a target means writing Machine::of for it and a lowering — AMD (MFMA, LDS, 64-lane wavefronts, Infinity Cache, per-XCD L2s), CPUs (cores, vector units, cache levels, prefetchers, SME), ASICs (PE arrays, SRAM banks, a network-on-chip). A synthesis target is a machine template with free parameters (array dimensions, SRAM sizes and banks, NoC width) and a resource budget (area, DSPs, BRAM, LUTs, fmax): the same search ranges over the template’s parameters as well as the schedule (D7). Today the tile-shape ladder carries built-in assumptions — two resident blocks per SM (GPU_RESIDENT_BLOCKS), half the register file, powers of two — and parts without a measurement borrow the RTX 5080’s numbers; under ADR-0050 occupancy is derived and a missing fact is visible.

Every decision is explained in the output

The ; mapal.place line states the chosen schedule, its predicted time and each term. A reviewer can see why a site walks instead of running an ordered grid — say, because the ordered grid’s movement term exceeds the walk’s combine term — without rerunning anything. Today the explanation is spread over rule comments and replay lines.

Measurement checks the model; it does not choose the answer

Today a site may carry several candidate kernels (--cands, candidate 0 being the rules’ plan) and the GPU runtime can time them in trials and remember the winner per device (“wisdom”, crates/mapal-rt/gpu/mapal_choice.h). On noisy rented parts that loop reverted good picks (the A100’s ±50 % noise, docs/sessions/2026-11-26-readable-llama-and-five-gpu.md). Under ADR-0050 a measurement is a replay line in place_replay.tsv: a realized time outside the predicted band is a finding — a missing machine fact or evaluator term, fixed in the model, never a per-site override. A run-time confirmation, where kept, chooses only among the top candidates and only on pairs that differ beyond the null.

The bound frees the order — so the search space is large

ADR-0049 made correctness “the flow and the bound”: the compiler may order, split and combine freely, including atomics and stream-K walks whose order depends on arrival, as long as every value stays within the a-priori bound (ADR-0040 D2). That turns split-K, stream-K and hybrid traversals into ordinary points of the schedule space, admitted by a numerics fact (how many pieces the site’s bound allows; ADR-0044’s split coefficients) rather than refused to reproduce bits.

It must win back the earlier single model’s losses

An earlier single cost model, plan-cost (site_ns), already priced the scalar tile site; it measured mixed — it lost 2.7× on mm_1x1024x4096 on the RTX 4090 — and ships off. ADR-0050 is held to naming the term plan-cost lacked and winning those rows back (the replay corpus is seeded with them).

8.6 How it differs from today’s methods

Every serious toolchain has some model of the hardware. The differences are where that knowledge lives, what makes the decision, and whether the decision can be explained from facts. A fair summary — the last column marks what ships today and what is ADR-0050’s design:

ApproachWhere the hardware knowledge livesHow a placement / schedule is chosenWhat Mapal does differently
Conventional compilers (LLVM, GCC)Per-target backends: instruction descriptions and per-CPU scheduling models (latencies, ports), plus cost hooks that answer one question at a time (LLVM’s TargetTransformInfo).Each pass decides locally with its own heuristic and thresholds — the vectorizer a width, the unroller a count, the inliner a budget — in a fixed pass order. Placement across devices and cache-level blocking are mostly outside their model.Mapal keeps LLVM for what it does well after lowering (instruction selection, register allocation, scheduling) and makes the placement decisions above it from both fact layers. Today each decision is its own rung rule in a fixed order — closer to LLVM’s per-pass heuristics than the goal. ADR-0050: once, over the whole schedule, with caches, waves and copies in one price.
Vendor libraries (cuBLAS / cuBLASLt, CUTLASS, cuDNN)Hand-written or templated kernels per architecture (CUTLASS is parameterized by an architecture tag and tile shapes).Heuristics and tables pick a kernel per shape (cuBLASLt’s heuristic query, cuDNN’s heuristic modes), optionally confirmed by autotuning or a profiler.Very fast on the shapes they target — Mapal measures itself against them (README). But the knowledge is in kernels and tables: a new part needs new kernels, and a choice is not explained by facts. A library also sees little beyond its own call: an epilogue can take in the immediate consumer (cuBLASLt epilogues, CUTLASS epilogue visitor trees), but not the producers or what stays resident between calls — which Mapal reads from the dataflow facts (today).
XLAPer-backend passes; on GPU an analytic performance model and library calls.Fusion passes driven by heuristics and that model; GEMMs and convolutions mostly handed to cuBLAS / cuDNN or to autotuned Triton tiles.Closest in spirit (a whole-graph compiler). Today: there is no fusion pass — kernel boundaries fall out of footprints and death points — and Mapal emits its own GEMM kernels instead of delegating them, their tile and traversal chosen by rung rules. ADR-0050: the GEMM’s schedule is priced by the same evaluator that is meant to price everything else (step 1 covers GEMM-shaped sites only).
TVM / Ansor / MetaScheduleMeasurements on the device, plus a learned cost model trained on them.Search over a space generated from schedule rules; candidates measured on the hardware; the learned model ranks them.Today Mapal is partly in this family: a site may carry candidate kernels (candidate 0 the rules’ plan) that the GPU runtime times in trials and remembers per device (“wisdom”, mapal_choice.h, §8.5). ADR-0050: search scored by an analytic model whose inputs are measured facts with provenance, so it can decide for parts not at hand and for ASIC templates not yet built, and say why a choice wins; measurement becomes the model’s check (alternatives rejected).
TritonIn the compiler’s layouts and pipelining, and in the programmer’s choice of block size.The programmer writes the block-level kernel; @triton.autotune times a hand-written list of configurations.No kernel, block or tile size appears in Mapal source; the tile, traversal and launch are generated from both fact layers (today by rung rules, ADR-0050 by one search).
HalideIn a separate schedule.Written by hand, or by an autoscheduler (an analytic one, and later a learned cost model).Shares the separation of “what” from “how”, but there is no schedule language to write: the compiler chooses the schedule (today by rung rules, visible only in the emitted code and the rules’ comments). ADR-0050: the schedule is an explicit output, printed with the module (; mapal.place).
MLIR-based compilers (e.g. IREE)Per-target dialects (NVGPU/NVVM, AMDGPU/ROCDL, ArmSME, x86 vector…) and lowering pipelines.Tiling and mapping in transform-dialect scripts or per-backend configuration logic.Today the decisions live in the LLVM backend’s rules, which read physical properties rather than a target name — one rule chain for every GPU, not one pipeline per target. ADR-0050: one target-agnostic placement over abstract facts; the per-target code is the translation into facts and the lowering of a chosen schedule.
Polyhedral (Pluto, PPCG)Exact affine access relations and dependences; hardware mostly as tile sizes.An ILP over a locality and parallelism objective (dependence distances).Mapal uses exact access maps too (tile_plan, tensor_form, today), but its objective is time on the machine: slots, waves, copy engines, bandwidth per level — today weighed rule by rule, under ADR-0050 as one predicted time — which the locality objective does not see.

What Mapal borrows: exact access maps (polyhedral), the separation of algorithm from schedule (Halide), LLVM for everything after lowering; under ADR-0050 also search with pruning (TVM) and measurement as a check (every autotuner). What ADR-0050 costs: a search at compile time, facts that must be measured or declared per part (calibration probes), and a model that can be wrong — which is why the evidence pass and the falsification criteria below exist. Where it stands today: the libraries still win several GEMM shapes on the RTX 3090, A100 and H100 (README, “Current results”) — the case step 1 targets.

8.7 Where the language is different — the map

Few of Mapal’s ideas are new on their own. What is new is where they sit: one system of facts from the source text to the hardware, with correctness separated from the order of execution by a stated bound.

AreaWhat Mapal doesClosest prior artWhat is differentStatus
The program is the flowSource is a dataflow graph: pipelines x -> f -> y, map / fold / loops, immutable unless mut, effects threaded as tokensSISAL, Id / Val, Lucid, StreamIt; Futhark, JAXThe graph’s structure (products, projections, composition) is both the language’s meaning and the compiler’s IR; no translation step loses meaningbuilt
Facts on the graphEach analysis is a stored fact — liveness and death, write deltas, reuse, residence, bounds, independence; facts depend on facts; every decision reads them (§6)Every compiler has analyses, but they live inside individual passesOne stored, queryable fact catalog that every decision must use; a mixed result is treated as a missing factbuilt
No “fusion”Which work runs together and what stays on chip follow from producer / consumer footprints and death pointsXLA’s fusion heuristics, Halide schedules, Futhark’s fusion rulesKernel boundaries are an output, decided at compile time, never runtime graphsbuilt
Hardware as facts (ADR-0050)The machine as memory places, executors with operations as geometry, movers and dispatch, each fact with its source; one cost model + a search places the dataflow on it (§8)Sequoia’s memory tree, Legion’s mappers, Timeloop / MAESTRO for accelerators, TVM / Ansor, Halide’s autoschedulerAnalytic rather than learned or measured, general-purpose (CPU, GPU, ASIC), driven by the language’s facts; measurement checks the model instead of picking the answer; a new target is a translation into the modelADR accepted; GEMM step 1 in progress
Correctness = flow + bound (ADR-0040, 0049)Precision is part of the program (fold: bf16 | f32); the compiler proves an a-priori error bound, then reorders freely; bit-identity is a development modeHerbie, FPTaylor, Precimonious; fast-math flagsA bound the language states and the compiler proves, instead of flags that trade correctness away; it admits hardware realizations no flag expresses (tf32x3, bf16x2n split forms on tensor cores)built
Builtins as contracts (ADR-0046)exp, sqrt, sin, cos: a contract and a reference definition; each target’s units admitted by the contract, chosen by error and costlibm variants, CUDA __expf, OpenCL native_*Chosen from facts, not from a flag or a function namebuilt
Compile time by dataflow (ADR-0048)No const or comptime: any value whose dataflow has no run-time input is computed beforehand — or materialized against recomputed by costZig comptime, C++ constexpr, partial evaluationInferred from the graph, not annotatedbuilt
Generics over sizes and formats (ADR-0047, 0051)fn project<rows, columns>, cache: float, x -> to<bf16>; an explicit prefix, the rest inferredFuthark’s size types, Dex, C++ templatesSizes stay in the type, so every fact sees exact extents; formats are generic and precision loss stays visible (to against widen)sizes built; formats in progress
Placement across devicesCPU, GPU and the host spine in one program; tasks and residency derived from path_plan and the residence factsLegion, StarPU, SYCL, OpenMP targetDerived from facts, not from annotations or run-time discoverybuilt (CPU + GPU)
One language down to siliconThe same program and the same machine model; for synthesis the search also picks the hardware’s free parametersHLS (Vitis, Catapult), Spatial, Calyx / CIRCTGPU and ASIC from one fact model; the hardware’s design and the placement in one searchplanned (the Verilog backend is a stub)
How the compiler is builtEvery optimization declares its intent; PTX / SASS is checked against it; every measurement becomes a replay test; every rule has an OFF armPerformance regression suitesCompiler decisions are evidence-backed and re-checked like proofsin practice

Not new on its own: dataflow languages (SISAL, Id — the 1980s and 1990s), size types (Futhark), separating the algorithm from its schedule (Halide), analytic mapping onto accelerators (Timeloop), floating-point error analysis (FPTaylor).

New — the combination: (1) the language’s meaning, the compiler’s facts and the hardware’s facts are one connected system; (2) the program states its numerical bound, which frees the compiler to choose any order and any realization within it, tensor cores included; (3) placement is derived from that system, not written by hand, tuned by measurement or learned, so a new target is a translation, not a new backend’s worth of heuristics.

This map is drawn from the project’s knowledge of the field, not a literature survey; check each “closest prior art” against current work before using it outside the project.

8.8 Status and what would prove it wrong

  1. Step 1, GEMM (in progress, one implementer, commits in order): C1 (committed, 30f1a32f) the crate mapal-place (machine, schedule and fact types with provenance; reuse closed forms; an exact LRU trace simulator; property tests) · C2 Machine::of for every GPU profile and the lowerings’ declarations, with a coverage test that today’s launches are points of the space, emitting byte-identical text · C3 place_replay.tsv and its scoring, the calibration probes the evaluator needs · C4 the search, the rung machine-place (default off; its OFF arm is the rule chain) and the ; mapal.place line · C5 the hybrid traversal · C6 the local ABBA, a rented confirmation, then the default flipped and later the rule chain removed.
  2. Later steps: attention and the streamed units; cells, folds and row folds; the co-schedule and residence across the whole system (filling free slots with independent work); the CPU translation; AMD.
  3. What would falsify it (ADR-0050): after the missing machine facts are added, the evaluator predicts the replay corpus’s winners less often than the rules did, or does not win back plan-cost’s losers; the target-specific list grows with each target instead of shrinking; the CPU cases the first draft could not state (a prefetcher’s reach, conflict misses from set mapping) stay unexplained.
9Plan → device compilation

A backend is a translator (the spec’s word is functor: F : Mapal-Cat → T) from the graph to one target world. It never re-derives program structure — it reads plans (§6) for what is legal and the machine facts for what this machine rewards, then emits code shaped so that LLVM can finish the job (vectorize, unroll, contract FMAs, schedule). In today’s code the placement decisions of §8 are made inside the LLVM backend by the rung rules (§9.3); ADR-0050 moves them into one evaluator and leaves the backend the lowering. Same graph, different profile, different code — same answer.

flowchart TD G["rewritten graph + stored plans"] --> DEC["placement (§8)
today: rung rules over properties
work units · tile · traversal · residency · dispatch"] PROF["TargetProfile (machine facts)
caches · vector width · matrix operations
GPU: SMs, registers, smem, L2 keep, rates, Caps"] --> DEC DEC --> HOST["host LLVM IR
tasks · loops · kernels as functions"] DEC --> DEV["device module (when placed)
NVPTX → PTX kernels"] HOST --> CLANG["clang -O3
LLVM opt: SROA · vectorize · unroll · LSR"] DEV --> PTXAS["ptxas / driver JIT
PTX → SASS (cubin)"] CLANG --> EXE["executable + mapal-rt"] PTXAS --> EXE

9.1 TargetProfile — machine facts as data

crates/backends/llvm/src/profile.rs: one record per part — CPUs (generic, apple-m, apple-m4-sme, zen3, raptorlake, x86-64-v3, auto-detected native) and GPUs (rtx-3090, a100, cuda-ada (an RTX 4070 Ti box), rtx-4090, h100, h100-pcie, rtx-5090, rtx-5080, and native-gpu = the device query plus the calibration line of benches/gpu/calib.cu, read from MAPAL_GPU_CALIB, the user cache, or the repository). It holds hardware facts — L1d geometry (sets/ways/line), L2 size, vector width, matrix-unit shape, measured dispatch economics, and for GPUs: SM count, schedulers, warp size, shared-memory budget, MMA/WGMMA capability, copy costs — and some fits of particular Mapal kernels (DeviceCost). Derived helpers (tile_i, move_block, gpu_tile, pack_pays, device_pays, raster…) turn facts + a site’s extents into concrete constants. Where a part has no measurement, today’s code mostly prices it anyway: the RTX 5080’s measured cycles at this part’s clock and SM count (coop_body_cycles, chain_cost, the plan rates — “derived, never unpriced”), or tables keyed by compute capability (barrier cycles Gpu::bar_cycles, FP32 lanes per SM fp32_lanes_of_cc, matrix rates). No value records which of these it is; ADR-0050 makes that provenance a fact (§8.1).

Geometry ports; constants are derived from properties. Which reads broadcast, which axes split, what may interleave — deduced once, backend-independent (tile_plan, path_plan). Tile factors, panel depths, unroll counts, task grain — derived from a cache hierarchy’s and a register file’s physical properties, not switched on a part’s name: “a new chip is a new property set, not a new code path” (CLAUDE.md, 2026-11-20). Two exceptions remain today: fallback tables keyed by compute capability, and the RTX 5080’s numbers borrowed by parts nobody calibrated (§8.5). ADR-0050 goes one step further: the constants are not computed by one rule each but chosen together, by the evaluator of §8, and a borrowed or nominal value is marked as such.

9.2 The CPU path (LLVM backend)

Entry: emit_detailed(ir, &EmitOpts) -> Emission { text, device, profile_name } (crates/backends/llvm/src/lib.rs). Emission is a pure function of (graph, options, profile) — same triple, same text. Per function, the emitter (src/func/: core · frame · drive · ops · tile · window · conv · packed · trio · vec · bulk · sme · hostpar · calls; GPU: gpu · flow · stream · resident · retain · rowfold · horizontal · zero) walks the plans:

  1. Frame + storage (frame, reuse.rs): emission_plan decides what gets an alloca slot vs dissolving to SSA; last_use_plan colors buffers so dead storage is reused; frame aliases let an Update whose source dies here write in place.
  2. Scheduling (drive): if path_plan is not single-path, emit one @taskN per task + the static dependency/rank/checkpoint tables for mapal-rt (§10). Before dispatching, a roofline test asks whether the task can pay for its own dispatch (max(flops/rate, bytes/rate) vs measured dispatch_ns); one-slice tasks run on the calling thread. Otherwise emit plain sequential code in topo_order.
  3. Kernels (tile · packed · window · conv · vec · bulk): a TileSite becomes a register-blocked micro-kernel nest — pack the strided operand into panels (only when pack_pays: working set > L2), block for L1/L2 from profile geometry, keep accumulators resident across k, store once. The innermost leaf differs per part (scalar FMA / NEON / AVX / ARM SME fmopa into ZA tiles); the nest around it is shared. MoveSites traverse in conflict-avoiding panels; window/conv sites reuse the same geometry with tap reads.
  4. Loops + guards (loops.rs, trio): loop_plan → a CFG with phis for carried state; guard_plan.gated() → branches around gated arm work; bounds_proof → omitted trap branches. Traps that remain call the runtime trap path with the source-order index (§10).
  5. Hand off to LLVM. The emitted IR is deliberately shaped for LLVM to derive the schedule: accumulators as SSA so SROA keeps them in registers, affine accesses so the vectorizer and LSR fire, FMA contract flags on the default and contract faces, never on --exact. clang -O3 does the rest (≈ 99% of compile time).
Expand: numerics — the default face and the development modes

Correct means the flow and the bound (ADR-0049): a program is correct when its flow of operations is the program’s dataflow and every value lies within the a-priori bound stated before the run. The compiler orders, splits and combines freely — atomics, split-K and stream-K included — so the last bits may differ between runs and between targets. Bit-for-bit modes remain, as development modes for testing and debugging, never as a language promise and never as a goal the compiler optimizes for.

Face (ADR-0040)Steps · orderFlagChecked against
DefaultFMA · free (any order of a tile site’s k fold whose combine is the fold’s own +)noneThe a-priori bound |out − exact| ≤ γK+1 · M (D2) — or the bound composed through every operation (mapal run --interp --bound) — never bits.
Exact (development)separate · sequential--exactThe interpreter, bit for bit.
Contract (development)FMA · sequential--order=sequentialThe CPU contract build, bit for bit.
Fixed (development)separate or FMA · a fixed partition order--order=fixed (± --no-contract)The interpreter replaying the compiled order, bit for bit.

The default face never changes a storage format. Reduced precision is opt-in per product (: tf32 | f32, : bf16 | f32, ADR-0041) with values rounded once at their producer; narrow storage (bf16, f16, fp8) is explicit in the types (ADR-0043). A full-f32 product may still run on tensor cores through a split realization (two or three narrow parts per operand) when its coefficient meets the default bound (ADR-0044, candidate status). Math builtins take the cheapest realization the face admits: on the development modes only exact ones, on the default face measured units within the contract (ADR-0046).

9.3 The GPU path (NVPTX device module + host orchestration)

The GPU leg reuses the same LLVM backend: device-suitable sites are emitted as an NVPTX module (PTX text embedded beside the host IR), and the host code launches them. This is the one place physical location is real — host vs device are different places, and every host↔device copy is a typed, costed transmission the facts must justify.

  1. Placement. For each candidate site (tile/cell/row-fold/streamed unit/bulk), device_pays compares estimated device time + required copies against staying on the host, using footprints, extents vs SM count, and whether operands are already resident. A per-trip cell is placed where it moves fewer bytes a trip (bytes-place); a map one of whose operands a placed site makes is a candidate too, so a chain is decided whole (cand-made) — which is what keeps a whole decode step on the device. Unplaced work runs as CPU tasks: a program is CPU-only, GPU-only, or mixed, per site.
  2. Residency + arena. last_use_plan, write_delta, unchanged_plan, access_plan and residence_plan deduce, per object (loop-carried state included), where it lives, what is reused, and what is retained across launches. Equal weight views are one object, so a model’s weights upload once; a prompt writes its key/value rows in place on the device and the decode loop takes those buffers (once-range, carry-take). Buffers are lifetime-colored in a device arena; any copy or allocation the dataflow facts do not require is treated as a bug (a “finding”), never a default. Partial loop updates move only their delta.
  3. Kernel formation (the flow rung). There is no fusion pass and no run-time graph capture. Work units follow producer/consumer footprints, death points, and cell independence, merged at compile time along a chain and across independent branches (func/flow.rs, func/horizontal.rs): a value with several readers is computed once; independent cells spread across threads; folds with a proven tree step become lane partials + warp-shuffle trees. Kernel boundaries fall out of where values must materialize.
  4. Streamed attention. stream_plan + fold_combine’s rescale law turn scores → softmax → weighted sum into one pass over key windows with a running maximum (the “flash attention” shape), derived from facts rather than recognized by name (func/stream.rs). A causal mask skips whole windows (with a run-time finiteness check where the skipped values are only known then, rung finite-check); 16-bit windows fold on mma.sync.
  5. Kernel leaves. Per site geometry: thread/block tile, shared-memory staging (cp.async rings), register accumulators. Tensor cores where precision_plan admits them: TF32 mma.sync under : tf32 | f32; 16-bit mma.sync.m16n8k16 with f32 accumulation over bf16/f16 operands (bf16 weights against f32 activations included); split forms of full-f32 products within the default bound (ADR-0044). On Hopper, wgmma (TF32 m64nNk8, 16-bit m64nNk16) fed by whole-tile TMA boxes with warp specialization: producer warps issue the copies, consumer warpgroups the products. Traversals: rasterized ordered grids (gated by b’s re-reads past the L2 keep), split-K, stream-K priced by the part’s rates (streamk_priced), and mma-walk — the 16-bit tensor tile walked over every SM’s matrix pipe; its operand re-reads are now priced against the L2 keep (walk-reuse, b3ad75f4), the case §8.5 retells.
  6. Device traps. A map refused as a device cell only because an index is unproven runs on the device anyway (trap_cell_plan): each cell checks its index, a failure is recorded in a module word, and the trap is raised at the next host checkpoint — a print, the clock, a host trap, the exit, or a device-to-host copy (rung device-trap).
  7. Rungs — today’s reconciliation. Each GPU decision is a named rung in GpuRungs (crates/backends/llvm/src/lib.rs) decided by a rule in rules.rs that reads the site’s fill and face and the part’s physical properties — FFMA per DRAM byte, registers per resident thread, L2 per SM and the L2 keep, matrix rates, measured launch and copy costs, capabilities as geometry (Caps: matrix operations, copy engines, evict-first loads, the PTX ISA each needs) — never a part’s name or version. Every cited measurement is a replay line (rung_replay.tsv, test rung_rules_replay); --gpu-off=/--gpu-on= are measurement flags. A site can carry a table of candidate kernels resolved when the module loads; candidate 0 is the rules’ plan, and the runtime may time the others and remember the winner (mapal-rt/gpu/mapal_choice.h). This rule chain is what ADR-0050 replaces (§8) and keeps as its OFF arm.
  8. Lowering. LLVM NVPTX emits PTX; each device module declares the largest PTX ISA its capabilities need (; mapal.ptx, checked by a ptxas preflight); ptxas/driver produces SASS. What LLVM must derive (vector widths, unroll, FFMA contraction…) is declared up front per rung and then checked in the realized PTX/SASS — see the evidence pass below. One known workaround that is not a fact yet: warp-specialized kernels launch alone, because a merged launch crashed (root cause open, docs/sessions/2026-11-26-readable-llama-and-five-gpu.md).

The older standalone CUDA-text backend (crates/backends/cuda/: host emitter + kernel emitter + arena) remains as the host-form reference; new device work lands in the NVPTX leg. The Verilog backend (crates/backends/verilog/) is the planned third translator — the same graph to clocked hardware with a done-protocol — evidence that the dataflow model reaches past SIMT machines.

Expand: the evidence pass — how optimization decisions are kept honest

No keep/remove/gate decision stands on timing alone (AGENTS.md). For every optimization or codegen change:

  1. Intent, before measuring. Declare machine-checkably what LLVM/NVPTX must derive from the emitted IR, which PTX/SASS features must appear/disappear (instruction mix, vector widths, FFMA-per-load, registers, spills, occupancy, launches), and what data movement the facts require per program and per loop trip.
  2. Realized. Collect LLVM optimization remarks, PTX, SASS (cuobjdump/nvdisasm), and ptxas -v for every measured kernel/arch; check against intent. A mismatch is a finding, never a pass. Library kernels (cuBLAS/CUTLASS) are captured from the actual launch.
  3. Explain. Every decision-driving timing difference cites the SASS/usage difference that explains it. Unexplained ⇒ the decision stays “open.”
  4. Breadth + genericity. Judge on the multi-workload suite (GEMM/MLP, attention/softmax, reductions, FIR/conv/window, elementwise chains, fan-in/out, loops; CPU-only, GPU-only, mixed) against the best library or PyTorch — and validate every rule on unseen generated programs (values vs oracle/bound, plus movement/kernel intents). Benchmarks are acceptance only; programs are written idiomatically and never reshaped to flatter the recognizer. Tooling: benches/gpu/intent.py, evidence.py — a GPU run without its evidence.tsv is not a result.

9.4 Algorithm summary: plan → device, end to end

flowchart TD S1["1 · Read stored facts per fn
path · tile/cell · footprint · elem · access
residence · unit/stream · bounds · precision"] --> S2["2 · Form work units
footprints + deaths + independence
(no fusion pass; boundaries fall out)"] MF["machine facts
TargetProfile: device query + calibration"] --> S3 S2 --> S3["3 · Place each unit = reconcile (§8)
host or device · operation · tile · traversal
residency · launch — today: rung rules"] S3 --> S4["4 · Lower the chosen schedule
constants follow from the placement
(+ minimal target-specific step)"] S4 --> S5["5 · Emit LLVM-shaped IR
SSA accumulators · affine access
gated branches · elided guards"] S5 --> S6["6 · LLVM derives the schedule
vectorize · unroll · SROA · contract"] S6 --> S7["7 · Evidence check
remarks + PTX/SASS vs declared intent"]
10Runtime & execution semantics

10.1 The thread pool (mapal-rt)

Compiled parallel programs link mapal-rt (crates/mapal-rt/src/lib.rs), a work-stealing pool executing the static task table the backend emitted from path_plan. Tasks unlock as their producer dependencies retire; Split tasks slice their element range across lanes; ranks schedule long poles first. MAPAL_PAR sets total executors including the host thread (MAPAL_PAR=1 is the sequential lever). Hard-won details, all measured: dispatch wakes only the lanes it filled; the completion path is lock-free; the host spins briefly before parking while workers do not (spinning workers measured worse and were removed).

Programs with device work also link the GPU runtime (crates/mapal-rt/gpu/mapal_gpu.c, CUDA driver API): it loads the module, resolves each site’s candidate table and its pick at load time (off the timed path), keeps the device arena, and launches. On a machine without a GPU the same calls run on a host emulation (mapal_gpu_emu.c), which is how the tests drive the shipped decision code.

10.2 Checkpoints, watermarks, and trap order

  • Effectful steps (prints, clock reads) run on the host in program order. A file read is not pinned (ADR-0045 D8): it is a path_plan task that starts when the run launches, beside work that does not read it; a failure zero-fills its array, is recorded at the read’s position in topo order and is delivered by the first checkpoint past it. (A read left on the spine — inside an effectful loop, in a sequential function or on a GPU build’s host — is a checkpoint like a print.) Before each effect, the runtime waits only as much as the checkpoint demands: completion if the effect consumes the task’s value, else its watermark — past its last trap-capable point — so “the task trapped” is always observed before “the print ran.”
  • When several independent steps could trap, the reported trap is the earliest in source order: the interpreter walk, sequential emission, and the parallel runtime’s minimum-index reporting all derive from the same topo_order key, so they cannot disagree. Output written before the trap is preserved.
  • The interpreter (mapal-interp: fueled graph evaluator + SCC loop driver) is the reference for all of this. On the default face compiled values are checked against it within the stated bound, in whatever order the compiler chose. In the development modes (--exact, --order=sequential|fixed) differential tests require compiled stdout/traps to match it byte-for-byte at -O0 and -O2, at any MAPAL_PAR, and under any CPU/GPU placement — for the examples and for programs from the random generator (ADR-0049 D3).
  • Device traps join the same order: a trap recorded by a device cell is raised at the next host checkpoint (a print, the clock, a host trap, the exit or a device-to-host copy), through mapal_rt_checkpoint_hook.

What is deterministic, and what is deliberately not. The compiler is deterministic: arena-ordered storage, source-ordered topo and rank-ordered tasks mean the same source produces the same emitted text, and traps are reported in source order. The values of floating-point combines are not promised bit for bit on the default face: parallel sums, atomics and stream-K walks may differ in the last bits between runs, always within the bound (ADR-0049). Bit-reproducible runs are a development mode, used to test and debug.

11End-to-end: three programs through every layer
sepia.mapal — the whole surface in 60 lines
LayerWhat happens to sepia
Source (§2)type Pixel, a pure clamp via nested guards, map with an inline block capturing nothing but the pixel, fold summing red, one final println. Expected: 4080 (clamp fires: 270.2 → 255, × 16).
AST (§3)Two FnDecls + one TypeDecl; the map/fold bodies are Blocks with tail chains; guards are Guard stages with True/False arms.
Lower (§4)Pixel → IR Struct; each channel mix → Pair+Mul/Add chains; clamp calls → Call; guards → nested Phis; map/fold bodies → MapBody/FoldBody functions; print → token-threaded Print.
Plans (§6)map_law: per-pixel closed form. guard_plan: scalar arms, not gated (vectorization preserved). path_plan: Split(map) → Seq(fold) → checkpoint(print). bounds_proof: no indexing to prove. emission_plan: all pair tuples dissolved.
Rewrite (§7)clamp inlined into the map body (small, single-purpose); constants folded where closed.
Device (§8–10)16 elements fails the roofline dispatch test ⇒ runs on the calling thread as a vectorized loop; LLVM keeps channel math in registers. Output 4080, equal to --interp (every sum here is exact in f32).
mapal run examples/sepia.mapal        # compiled
mapal run --interp examples/sepia.mapal   # oracle — must agree
matmul128.mapal — from textbook loops to a tiled kernel
LayerWhat happens
Sourceiota ranges, two generator maps (with widen<f64>), one cell map with an inner dot-product fold capturing a, b, krange (§6, Walkthrough 2).
GraphThree Map sites; the cell site’s source is (a, b, krange, ta) with captures = 3; the fold body reads two affine Indexes.
Planstile_plan fires (broadcast + vector reads, §6.3). path_plan: generator maps are independent Split tasks; the cell map depends on both. last_use_plan: ta dies after the generators; a/b live into the kernel; c escapes to the prints.
CPU deviceProfile picks register block + panel depths; b packed if the working set exceeds L2; accumulators resident across k; tasks sliced by row blocks across the pool.
GPU devicedevice_pays at this size typically declines (copies dominate) — at 2048²+ the same source places, stages tiles in shared memory, and runs the rung-gated kernel. Placement changes; values stay within the bound (bit for bit in the development modes).

The same idiom at 4096² (examples/matmul4096.mapal) was an early CPU result against NumPy, kept in docs/performance/earlier-readme-results.md — from source that never mentions a tile, a thread, or a vector.

llama.mapal — a real model, Llama-3.2-1B-Instruct, through every layer

examples/llama.mapal (403 lines, written to be read) runs Llama-3.2-1B-Instruct with its real weights: one read of the checkpoint, one forward for the whole prompt and then for each generated token through the 16 layers, greedy decoding. It is the program that drove most of the changes since the first edition of this page.

The full model — examples/llama.mapal, 412 lines
The whole file, highlighted as in the editors: examples/llama.mapal
// llama.mapal — Llama-3.2-1B-Instruct: read the weights, run the prompt, generate greedily.
//
// The whole model is the functions below; the weights are data, read from one file (`model.bin`, written
// by `benches/model/export_weights.py` from the Hugging Face checkpoint) and the prompt from another.
// Run with `MAPAL_DATA_DIR` set to the directory holding them:
//
//   MAPAL_DATA_DIR=~/.cache/mapal/models/llama-3.2-1b-instruct/mapal mapal run examples/llama.mapal
//
// It prints one line per generated token: the token id, its logit, and the milliseconds since the prompt
// was submitted (when the token is on the host). Every activation is f32; the weights stay bf16; the key/value
// cache is stored in the format `main` chooses (f32 here; `to<bf16>` keeps it in bf16, as the competitors do).
//
// One function serves the prompt and every generated token: `forward` runs a chunk of `tokens` new tokens
// (the whole prompt at once, then one token at a time) through every layer, appending their keys and values
// to the cache, and returns the logits after the chunk's last token.

// ---------------------------------------------------------------------------------------------------------
// The model's sizes (the checkpoint's config.json).

128256 -> vocabulary_size;
2048 -> hidden_size;
16 -> layer_count;
32 -> query_heads;
8 -> key_value_heads;
64 -> head_size;
8192 -> feed_forward_size;
0.00001 -> rms_epsilon;

// Rotary position embedding: theta 500000 with llama3 frequency scaling.
13.122363377404328 -> log_rope_theta; // ln(500000)
32.0 -> rope_factor;
1.0 -> rope_low_frequency_factor;
4.0 -> rope_high_frequency_factor;
8192.0 -> rope_original_context;

// The run: the prompt's length (its first ids from `prompt.bin`) and how many tokens to generate.
512 -> prompt_length;
128 -> generated_tokens;
2048 -> prompt_file_length;

// Derived sizes.
query_heads * head_size -> query_size;
key_value_heads * head_size -> key_value_size;
query_heads / key_value_heads -> heads_per_key_value_head;
head_size / 2 -> rotation_pairs;
prompt_length + generated_tokens -> context_length;
layer_count * context_length * key_value_size -> cache_size;

// ---------------------------------------------------------------------------------------------------------
// Types.

// A linear layer's weights as the checkpoint stores them: `rows` outputs of `columns` inputs, row by row.
type Matrix<rows, columns> {
    _: [bf16; rows * columns]
}

type DecoderLayerWeights {
    attention_norm: [bf16; hidden_size],
    query: Matrix<query_size, hidden_size>,
    key: Matrix<key_value_size, hidden_size>,
    value: Matrix<key_value_size, hidden_size>,
    output: Matrix<hidden_size, query_size>,
    feed_forward_norm: [bf16; hidden_size],
    gate: Matrix<feed_forward_size, hidden_size>,
    up: Matrix<feed_forward_size, hidden_size>,
    down: Matrix<hidden_size, feed_forward_size>,
}

// The token embedding is also the output head (tied weights).
type Model {
    embedding: Matrix<vocabulary_size, hidden_size>,
    layers: [DecoderLayerWeights; layer_count],
    final_norm: [bf16; hidden_size],
}

// Every layer's keys and values for every position of the context: cell
// `((layer * context_length + position) * key_value_heads + key_value_head) * head_size + dimension`,
// stored as `element`.
type KeyValueCache<element: float> {
    keys: [element; cache_size],
    values: [element; cache_size],
}

// ---------------------------------------------------------------------------------------------------------
// Rotary position embedding.

// The rotation frequency of pair `pair` of a head: theta^(-2 pair / head_size). Llama 3 stretches the slow
// ones: wavelengths longer than the original context / low factor are divided by the factor, those shorter
// than the original context / high factor are kept, and those between are blended smoothly.
fn inverse_frequency(pair: i32) -> f32 {
    pair * 2 -> to<f32> -> twice_pair;
    head_size -> widen<f32> -> width;
    -(twice_pair / width) * log_rope_theta -> exp -> frequency;
    6.2831855 / frequency -> wavelength;
    (wavelength > rope_original_context / rope_low_frequency_factor) -> {
        -true-> frequency / rope_factor;
        -false-> {
            (wavelength < rope_original_context / rope_high_frequency_factor) -> {
                -true-> frequency;
                -false-> {
                    rope_original_context / wavelength - rope_low_frequency_factor -> above_low;
                    above_low / (rope_high_frequency_factor - rope_low_frequency_factor) -> smooth;
                    (1.0 - smooth) * frequency / rope_factor + smooth * frequency
                }
            }
        }
    } -> ret;
}

// Computed before the program runs: it depends on nothing the run reads.
rotation_pairs -> iota -> map {
    pair -> pair -> inverse_frequency
} -> inverse_frequencies: [f32; rotation_pairs];

// Rotate each head of each token by its position's angles: in a head, element i < half and its partner
// i + half are a pair (x, y) that becomes (x cos - y sin, y cos + x sin), at angle position * frequency.
fn rotate<tokens, width>(x: [f32; tokens * width], positions: [i32; tokens]) -> [f32; tokens * width] {
    tokens * width -> iota -> map {
        cell ->
        cell / width -> t;
        cell % head_size -> within_head;
        within_head % rotation_pairs -> pair;
        positions[t] -> to<f32> -> position;
        position * inverse_frequencies[pair] -> angle;
        angle -> cos -> cosine;
        angle -> sin -> sine;
        (within_head < rotation_pairs) -> {
            -true-> x[cell] * cosine - x[cell + rotation_pairs] * sine;
            -false-> x[cell] * cosine + x[cell - rotation_pairs] * sine;
        }
    } -> ret;
}

// ---------------------------------------------------------------------------------------------------------
// Building blocks. Activations are `tokens` vectors stored one after another.

fn embed<tokens>(embedding: Matrix<vocabulary_size, hidden_size>, ids: [i32; tokens]) -> [f32; tokens * hidden_size] {
    tokens * hidden_size -> iota -> map {
        cell ->
        ids[cell / hidden_size] * hidden_size + cell % hidden_size -> row_cell;
        embedding[row_cell] -> widen<f32>
    } -> ret;
}

// RMSNorm of each vector: x / sqrt(mean(x^2) + epsilon), times a learned gain per feature.
fn rms_norm<tokens>(x: [f32; tokens * hidden_size], gain: [bf16; hidden_size]) -> [f32; tokens * hidden_size] {
    hidden_size -> iota -> features;
    hidden_size -> widen<f32> -> width;
    tokens -> iota -> map {
        t -> (0.0, features) -> fold {
            sum, i -> sum + x[t * hidden_size + i] * x[t * hidden_size + i]
        }
    } -> sum_of_squares;
    tokens * hidden_size -> iota -> map {
        cell ->
        sum_of_squares[cell / hidden_size] / width + rms_epsilon -> sqrt -> root;
        gain[cell % hidden_size] -> widen<f32> -> g;
        x[cell] * (1.0 / root) * g
    } -> ret;
}

// A linear layer without bias: out[t][row] = sum over columns of weight[row][column] * x[t][column].
fn project<tokens, rows, columns>(weight: Matrix<rows, columns>, x: [f32; tokens * columns]) -> [f32; tokens * rows] {
    columns -> iota -> along;
    tokens * rows -> iota -> map {
        cell ->
        cell / rows -> t;
        cell % rows -> row;
        (0.0, along) -> fold {
            sum, column ->
            weight[row * columns + column] -> widen<f32> -> w;
            sum + w * x[t * columns + column]
        }
    } -> ret;
}

fn add<n>(a: [f32; n], b: [f32; n]) -> [f32; n] {
    n -> iota -> map {
        i -> a[i] + b[i]
    } -> ret;
}

fn larger(a: f32, b: f32) -> f32 {
    (a > b) -> {
        -true-> a;
        -false-> b;
    } -> ret;
}

// SiLU, the gate activation of SwiGLU: x * sigmoid(x).
fn silu(x: f32) -> f32 {
    -x -> exp -> decay;
    x / (1.0 + decay) -> ret;
}

// ---------------------------------------------------------------------------------------------------------
// Attention.

// The cache with the chunk's rows (keys or values, one row per token) written at positions
// first_position, first_position + 1, ... of layer `layer`, each new element rounded once to the cache's format.
fn write_rows<tokens, element: float>(cache: [element; cache_size], rows: [f32; tokens * key_value_size], layer: i32, first_position: i32) -> [element; cache_size] {
    cache_size -> iota -> map {
        cell ->
        cell / key_value_size - layer * context_length - first_position -> t;
        (t >= 0 && t < tokens) -> {
            -true-> rows[t * key_value_size + cell % key_value_size] -> to<element>;
            -false-> cache[cell];
        }
    } -> ret;
}

// Causal grouped-query attention over layer `layer`'s cached keys and values: each token's query head h reads
// key/value head h / 4 of every cached position up to its own, scores are scaled by 1 / sqrt(head_size),
// softmax over each head's scores, and the result is the weighted sum of the cached values.
fn attend<tokens, element: float>(
    query: [f32; tokens * query_size],
    positions: [i32; tokens],
    cache: KeyValueCache<element>,
    layer: i32,
) -> [f32; tokens * query_size] {
    head_size -> iota -> dimensions;
    context_length -> iota -> past_positions;
    head_size -> widen<f32> -> sqrt -> scale_root;
    tokens * query_heads * context_length -> iota -> map {
        cell ->
        cell / context_length -> token_head;
        cell % context_length -> past;
        token_head / query_heads -> t;
        token_head % query_heads / heads_per_key_value_head -> key_value_head;
        (past <= positions[t]) -> {
            -true-> {
                (layer * context_length + past) * key_value_heads + key_value_head -> key_row;
                (0.0, dimensions) -> fold {
                    sum, d ->
                    query[token_head * head_size + d] -> q;
                    cache.keys[key_row * head_size + d] -> widen<f32> -> key;
                    sum + q * key
                } -> dot;
                dot / scale_root
            }
            -false-> -1000000000.0;
        }
    } -> scores;
    tokens * query_heads -> iota -> token_heads;
    token_heads -> map {
        token_head -> (-1000000000.0, past_positions) -> fold {
            best, past -> (best, scores[token_head * context_length + past]) -> larger
        }
    } -> row_maximum;
    tokens * query_heads * context_length -> iota -> map {
        cell -> scores[cell] - row_maximum[cell / context_length] -> exp
    } -> exponentials;
    token_heads -> map {
        token_head -> (0.0, past_positions) -> fold {
            sum, past -> sum + exponentials[token_head * context_length + past]
        }
    } -> row_total;
    tokens * query_size -> iota -> map {
        cell ->
        cell / head_size -> token_head;
        cell % head_size -> d;
        token_head % query_heads / heads_per_key_value_head -> key_value_head;
        (0.0, past_positions) -> fold {
            sum, past ->
            (layer * context_length + past) * key_value_heads + key_value_head -> value_row;
            exponentials[token_head * context_length + past] -> weight;
            cache.values[value_row * head_size + d] -> widen<f32> -> value;
            sum + weight * value
        } -> weighted;
        weighted / row_total[token_head]
    } -> ret;
}

// ---------------------------------------------------------------------------------------------------------
// The decoder layer and the whole model.

// SwiGLU feed-forward: down(silu(gate(x)) * up(x)).
fn feed_forward<tokens>(x: [f32; tokens * hidden_size], weights: DecoderLayerWeights) -> [f32; tokens * hidden_size] {
    (weights.gate, x) -> project -> gate: [f32; tokens * feed_forward_size];
    (weights.up, x) -> project -> up: [f32; tokens * feed_forward_size];
    tokens * feed_forward_size -> iota -> map {
        i ->
        gate[i] -> silu -> activated;
        activated * up[i]
    } -> mixed;
    (weights.down, mixed) -> project -> ret;
}

// One decoder layer over the chunk: attention with a residual connection, then the feed-forward block with
// a residual connection. The chunk's keys and values enter the cache before its queries attend.
fn decoder_layer<tokens, element: float>(
    hidden: [f32; tokens * hidden_size],
    weights: DecoderLayerWeights,
    layer: i32,
    cache: KeyValueCache<element>,
    positions: [i32; tokens],
) -> ([f32; tokens * hidden_size], KeyValueCache<element>) {
    (hidden, weights.attention_norm) -> rms_norm -> normed;
    (weights.query, normed) -> project -> query: [f32; tokens * query_size];
    (weights.key, normed) -> project -> key: [f32; tokens * key_value_size];
    (weights.value, normed) -> project -> value: [f32; tokens * key_value_size];
    (query, positions) -> rotate -> rotated_query;
    (key, positions) -> rotate -> rotated_key;
    (cache.keys, rotated_key, layer, positions[0]) -> write_rows -> keys;
    (cache.values, value, layer, positions[0]) -> write_rows -> values;
    KeyValueCache {
        keys: keys,
        values: values,
    } -> updated_cache;
    (rotated_query, positions, updated_cache, layer) -> attend -> attended;
    (weights.output, attended) -> project -> attention_output: [f32; tokens * hidden_size];
    (hidden, attention_output) -> add -> after_attention;
    (after_attention, weights.feed_forward_norm) -> rms_norm -> normed_again;
    (normed_again, weights) -> feed_forward -> feed_forward_output;
    (after_attention, feed_forward_output) -> add -> ret.0;
    updated_cache -> ret.1;
}

// Run a chunk of tokens, the first at `first_position`, through every layer; return the logits after the
// chunk's last token and the cache holding the chunk's keys and values.
fn forward<tokens, element: float>(ids: [i32; tokens], first_position: i32, model: Model, cache: KeyValueCache<element>) -> ([f32; vocabulary_size], KeyValueCache<element>) {
    tokens -> iota -> map {
        t -> first_position + t
    } -> positions;
    (model.embedding, ids) -> embed -> embedded;
    mut hidden: [f32; tokens * hidden_size] <- embedded;
    mut updated: KeyValueCache<element> <- cache;
    mut layer: i32 <- 0;
    loop {
        (layer < layer_count) -> {
            -true-> {
                (hidden, model.layers[layer], layer, updated, positions) -> decoder_layer -> result;
                result.0 -> hidden;
                result.1 -> updated;
                layer + 1 -> layer;
                -> loop;
            }
            -false-> {
                hidden_size -> iota -> map {
                    i -> hidden[(tokens - 1) * hidden_size + i]
                } -> last;
                (last, model.final_norm) -> rms_norm -> normed;
                (model.embedding, normed) -> project -> logits: [f32; vocabulary_size];
                (logits, updated) -> ret;
            }
        }
    }
}

// Greedy decoding: the token with the largest logit (the first one on a tie).
fn most_likely_token(logits: [f32; vocabulary_size]) -> i32 {
    vocabulary_size -> iota -> tokens;
    ((logits[0], 0), tokens) -> fold {
        best, token -> (logits[token] > best.0) -> {
            -true-> (logits[token], token);
            -false-> best;
        }
    } -> winner;
    winner.1 -> ret;
}

// ---------------------------------------------------------------------------------------------------------

fn main() {
    "model.bin" -> read -> model: Model;
    // The cache's format, chosen here once: f32 (`0.0 -> to<bf16>` stores it in bf16).
    0.0 -> to<f32> -> zero;
    (zero, cache_size) -> fill -> nothing_cached;
    KeyValueCache {
        keys: nothing_cached,
        values: nothing_cached,
    } -> empty_cache;

    // The prompt arrives (the clock starts), and all of it at once, from position 0, gives the first token.
    () -> time -> submitted;
    "prompt.bin" -> read -> prompt_file: [i32; prompt_file_length];
    prompt_length -> iota -> map {
        t -> prompt_file[t]
    } -> prompt;
    (prompt, 0, model, empty_cache) -> forward -> prefilled;
    prefilled.0 -> most_likely_token -> first_token;
    () -> time -> first_token_time;
    first_token -> print;
    " " -> print;
    prefilled.0[first_token] -> print;
    " " -> print;
    first_token_time - submitted -> println;

    // Each later token: feed the previous one at the next position.
    mut token: i32 <- first_token;
    mut cache <- prefilled.1;
    mut position: i32 <- prompt_length;
    loop {
        (position < prompt_length + generated_tokens - 1) -> {
            -true-> {
                [token] -> ids;
                (ids, position, model, cache) -> forward -> stepped;
                stepped.0 -> most_likely_token -> token;
                stepped.1 -> cache;
                () -> time -> now;
                token -> print;
                " " -> print;
                stepped.0[token] -> print;
                " " -> print;
                now - submitted -> println;
                position + 1 -> position;
                -> loop;
            }
            -false-> position -> last_position;
        }
    }
}
LayerWhat happens to the model
Source (§2)Top-level sizes from the checkpoint’s config (2048 -> hidden_size;); type Matrix<rows, columns> { _: [bf16; rows * columns] }; size-generic rms_norm<tokens>, project<tokens, rows, columns>, attend<tokens>; exp, sqrt, sin/cos for SiLU, RMSNorm and the rotary embedding; "model.bin" -> read -> model: Model;; a loop carrying the token, the key/value cache and the position.
Lower (§4)Top-level scalars computed by the interpreter and used as sizes; one fixed-size instance per size tuple — forward once for the prompt length and once for one token; read threads the IO token.
Facts (§6)static_plan: values that read no input (the rotary frequencies, for one) are embedded or computed at run time by its bytes-against-work rule. tile_plan/tensor_form: every projection is a tile site over bf16 storage (tile_plan_narrow). stream_plan: the prompt’s attention streams over key windows with a causal mask read through a positions array. unchanged_plan, access_plan, residence_plan: weights the same on every call; the cache written in place.
Placement (§8, today by rules)The decode step stays on the device (cand-made); the weights upload once (CSE value scope); the prompt writes its cache rows on the device and the loop takes the buffers (once-range, carry-take); projections on tensor cores in both classes (in the f32 class as a split form — two bf16 parts of each f32 activation against the bf16 weight, ADR-0044; 16-bit mma.sync, wgmma on the H100), the prompt’s attention as one streamed kernel.
NumericsTwo classes, compared type to type: the program as written (f32 activations, bf16 weights widened exactly in registers) and the bf16 class (fold: bf16 | f32, a bf16 key/value cache). Every value gate checks the bound; in the bf16 class the tensor tile adds partial sums in arrival order, so greedy tokens can vary from run to run — within the bound, as ADR-0049 allows.
python3 benches/model/export_weights.py              # weights, exported outside the repository
MAPAL_DATA_DIR=~/.cache/mapal/models/llama-3.2-1b-instruct/mapal mapal run examples/llama.mapal

Results — the full model on five GPUs against the fastest engine of the same precision class, and the 120-program kernel suite — are in the README (“Current results”) and benches/results/evidence/; this page does not copy them.

12Code map & glossary

12.1 Where everything lives

ConcernCrate / filesStart reading
Lexer, parser, AST, formattercrates/mapal-syntax/ (lexer.rs · parser.rs · ast.rs · format.rs)ast.rs, then docs/components/syntax/DESIGN.md §14–15
Graph IR + dataflow factscrates/mapal-ir/ (graph.rs · ty.rs · builder.rs · validate.rs · algo.rs + algo/ · facts.rs · access.rs · residence.rs · unit.rs · math.rs · narrow.rs · split.rs · exp.rs · read.rs · mermaid.rs)graph.rs, then docs/architecture/deduced-queries.md
Loweringcrates/mapal-lower/ (lib.rs · tys.rs · effects.rs · typing.rs · emit.rs · scope.rs · globals.rs · sizes.rs)lib.rs pass map (§4)
Checkscrates/mapal-check/ (exclusivity.rs · effects.rs)lib.rs (T0101/T0201)
Compile-time evaluation + optimizercrates/mapal-rewrite/ (statics.rs · driver.rs · plan.rs · replay.rs · equations.rs · graph_rewrites.rs · functor_laws.rs · inline.rs · lift.rs · unroll.rs · naturality.rs)lib.rs + tests/testgen/
Oraclecrates/mapal-interp/ (eval.rs · loops.rs · value.rs)lib.rs: run
Machine facts + today’s placement rules + CPU/GPU loweringcrates/backends/llvm/ (profile.rs machine facts · rules.rs + rung_replay.tsv rung rules · lib.rs · module.rs · loops.rs · reuse.rs · math.rs · narrow.rs · flags.rs · func/*)profile.rs, rules.rs, then func/drive.rs and func/gpu.rs
Placement by one model (ADR-0050, step 1 in progress)crates/mapal-place/ (C1 committed: machine, schedule and fact types with provenance, the evaluator, reuse closed forms, an exact LRU simulator, the candidate space; no placement reads it yet; the search follows in C4); place_replay.tsv (planned)docs/decisions/ADR-0050-the-machine-model-placement-by-one-cost-model.md
CUDA-text backendcrates/backends/cuda/ (module.rs · func.rs · kernel.rs · arena.rs · loops.rs)lib.rs
FPGA backend (planned)crates/backends/verilog/docs/components/backend-verilog/DESIGN.md
Runtimecrates/mapal-rt/src/lib.rs (thread pool) · crates/mapal-rt/gpu/ (mapal_gpu.c, mapal_choice.h, mapal_gpu_emu.c)FlowParRun + pool; the GPU module load and site choice
Hardware calibration + evidence toolingbenches/gpu/calib.cu, benches/local/mma_calib.cu · benches/gpu/intent.py, evidence.pycalib.cu (what native-gpu measures)
CLI (build/run/dump-ir/test/fmt)crates/mapal-cli/ (main.rs · fmt.rs)frontend() → rewritten() → emit()
Programs to learn fromexamples/*.mapal · benches/algorithms/*.mapal (idiomatic snapshot)sepia, fib, fir, matmul128, calc, then llama
flowchart LR CLI["mapal-cli"] --> SYN["mapal-syntax"] CLI --> LOW["mapal-lower"] CLI --> CHK["mapal-check"] CLI --> RW["mapal-rewrite"] CLI --> BE["backends/llvm (+cuda)"] CLI --> IN["mapal-interp"] LOW --> IR["mapal-ir ★ hub
(zero deps on syntax)"] CHK --> IR RW --> IR BE --> IR IN --> IR LOW --> SYN CHK --> SYN BE -.->|"links at runtime"| RT["mapal-rt"] PLC["mapal-place (ADR-0050, C1 committed)
machine · schedule · evaluator
no workspace deps · nothing reads it yet"] BE -.->|"planned: C2–C4"| PLC

mapal-ir is the depended-on hub and depends on nothing in the workspace — which is why it defines its own field-identical SourceLoc (one declared conversion seam in mapal-lower) instead of importing the syntax crate’s.

12.2 Glossary — project words, plain meanings

WordPlain meaning
Object / MorphismA value / a step that computes a value (graph node / labeled edge).
Sealed graphAn immutable, builder-checked CategoryIr. The only stored truth.
Plan / deduced query / dataflow factThe same thing: a pure, cached, possibly-silent proof about the graph (§6).
Machine factA fact about the hardware as abstract compute and placement — a place, an executor’s operation, a mover, a dispatch rule — with its provenance (measured, queried, declared, derived, nominal) and an interval (§8.2).
Place / executor / operation row / mover / dispatchWhere bytes can live / what computes / one instruction or unit described by its geometry, operand homes and rate / how bytes move (copy engines, prefetchers, links) / how work reaches executors (occupancy derived, launch modes, atomics).
Reconciliation / placementThe compile phase that places the dataflow on the machine: reads both fact layers and produces a schedule per site (§8). Today: the rung rules; ADR-0050: one evaluator + one search.
SchedulePlacement’s output for a site: executor subtree, operation + operand roles, levels, homes/layout/depth, traversal (ordered / split / walk / hybrid), launch mode (§8.3).
Evaluator / searchThe one cost model that predicts a schedule’s time from both fact layers (compute, movement, latency, issue, combine, fixed) / the bottom-up branch-and-bound over feasible schedules.
L2 keepHow many distinct bytes a cache really holds for a given access pattern — measured, not the nominal size (l2_keep_bytes).
Walk (stream-K)A traversal that splits the whole k-range of all tiles evenly over every resident slot; the pieces’ partial sums are combined (in mma-walk, by atomic adds in arrival order).
Host spine / checkpoint / watermarkThe sequential effectful thread of a program / a wait point on it / “past the last possible trap” (weaker than finished).
Split vs Seq taskElement range can be sliced across lanes / must run in order as one unit.
SiteA place a plan recognized a shape (tile site, cell site, move site…).
RungOne named, evidence-gated backend decision with measured on/off arms, decided today by a rule over physical properties (§9.3). The work-unit rung is called flow — there is no “fusion” concept; boundaries follow footprints. machine-place (ADR-0050) will be the rung whose OFF arm is the whole rule chain.
TargetProfileToday’s home of the machine facts for one part (device query + calibration, never a name lookup for decisions). Backends read it; plans never see it. ADR-0050 translates it into machine facts by Machine::of.
Face / development modeFloat contract level. The default face: FMA, free order, an a-priori bound. Exact / contract / fixed: development modes that reproduce bits for testing and debugging (§9.2, ADR-0049).
BoundThe a-priori error a value may carry on the default face (ADR-0040 D2, composed through every operation by --interp --bound); correctness = the flow + the bound.
Static valueA non-mut value whose dataflow reads no input or effect: computed before the program runs (ADR-0048).
_ fieldA type’s default interpretation: alone, the type is an alias of it; beside other fields, the value reads as x._ where only that fits.
Size-genericfn f<n, m> / type T<n, m>: sizes inferred per call, one fixed-size instance per size tuple (ADR-0047).
OracleThe interpreter: the reference semantics. Compiled values are checked against it within the bound, and bit for bit in the development modes.
TrapA defined runtime failure (divide-by-zero, out-of-bounds), reported in source order.
FindingAn intent-vs-realized mismatch (extra copy, missing vectorization…). Findings block “pass” claims until explained.
13Keeping this doc true

This page is a map, not a second source of truth — the code wins any disagreement, and every claim above names its file so drift is checkable. When you change the compiler, update this file in the same change:

  • New/changed plan? Add or edit its card in §6.2 (question, algorithm, consumer, fallback) and the facts diagram in §6.1. A plan without a card does not exist for onboarding purposes.
  • New operation / AST node / type? Update the §5 operation table, §3 node catalogue, and §2 syntax as applicable.
  • New backend decision or rung? Record it in §9 with its evidence citation; a rung rule names the property it reads and its measurements go into rung_replay.tsv.
  • New machine fact, schedule dimension or evaluator term (ADR-0050)? Update §8.2–8.3 (the fact kinds, the operation-row table, the schedule and evaluator tables) and the status in §8.8. A step that cannot yet be a machine fact belongs in the target-specific list, not here as a rule. When machine-place lands or flips its default, update the status callouts in §1 and §8 the same day.
  • New language surface? Update §2 (and §2.10 / the grammar cheat-sheet), the §3 node catalogue and the §5 operation table.
  • Pipeline change? Fix the §1 master diagram first — if the top-level story changed, say so loudly there.
  • Mapal code on this page? It is generated: every Mapal block, and the whole of examples/llama.mapal in §11, is highlighted by docs/tools/highlight_mapal.py with the editors’ classes (editors/test/classes.tsv, names from mapal lsp). Edit a snippet’s text in place (or the example file) and re-run the script; a new snippet is a plain <pre><code> between <!-- mapal:hl begin id=… --> and <!-- mapal:hl end -->. --check fails when a block is stale (a rename in the language, a changed example), --test checks the page against the server.
  • Reconcile alongside the living docs (docs/STATUS.md, component DESIGN/IMPLEMENTATION.md) and run the drift check; session narrative belongs in docs/sessions/, not here.

Try it now (5 minutes). cargo run -p mapal-cli -- run examples/sepia.mapal → 4080. Then … dump-ir examples/fib.mapal --stage=lowered and find the LoopMerge; … dump-ir examples/matmul128.mapal --stage=llvm and find the tiled kernel; finally re-read §6 Walkthrough 2 next to tile_plan in algo.rs, and §8 next to ADR-0050. You now have both fact layers and the phase that joins them in your head — welcome aboard.