Skip to content

Metal's OUTLINE is noinline, so a large kernel stays under the AGX backend's 256 flow states - #1433

Closed
totaland wants to merge 1 commit into
bendlang:mainfrom
totaland:metal-outline-noinline
Closed

totaland wants to merge 1 commit into
bendlang:mainfrom
totaland:metal-outline-noinline

Conversation

@totaland

@totaland totaland commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Why

On an M1 Pro, a small ! job gives a wrong answer on Metal when a large, unrelated function is compiled into the same program. The job is correct on the CPU, and correct on Metal in a small program.

The repro is a 46-line driver (below) that runs mk!(xs(2048n, 0)): a tail-recursive mulk over 2048 F32s, then a sum. Its other branch would call one Qwen3.5 decode step (M.step, from a TensorFold model outside this repo). That branch never runs, but M.step's device code is compiled into the same kernel.

--gpu off --gpu 8GB
upstream 60fa05dc 85.39297 hangs (3/3 runs, 60 s timeout)
this PR 85.39297 85.39297 (3/3 runs)

Depending on the build, the wrong branch shows up as a hang (the host sums a garbage list), as frontier drained without a result, or as a function the device does not hold.

How it failed

The AGX backend miscompiles the kernel once its control flow needs more than 256 states.

  • A device trace takes the wrong branch. The lane runs FID_ENTER → FID_MK, and the inlined mulk.go spin runs all 2049 iterations. On the last one, xs is Nil, yet neither else branch runs. Control falls into MK's tail with the spin's output unwritten (0), or work_loop returns 0 and the task is lost. The front-end AIR (xcrun metal -O2 -S -emit-llvm) for that spin is correct.
  • The backend tests a 16-bit state with an 8-bit immediate. I extracted _agc.main from the .gpu archive and disassembled it with dougallj/applegpu. The backend's structurizer keeps one 16-bit flow-state register per function (r4h) and numbers states across the whole function. It sets a state with a 16-bit mov_imm or with icmpsel. The dispatch compares (if_icmp, else_icmp, while_icmp) only hold an 8-bit immediate, so a state of 256 or above is tested as state - 256.
  • Upstream's mp3 kernel has states above 255. It uses 262 distinct states, up to 335. Six of them are 256 or above, and every value from 0 to 255 is also in use, so each truncated test matches another real state:
    • mov_imm r4h, 319 at 0x3158dc, then if_icmp r0l, ueq, r4h, 63 at 0x3158f2;
    • 326 is tested as 70, 332 as 76, and 335 as 79.
  • Inlined helpers make the count grow with program size. On Metal, OUTLINE was plain static, so the backend inlined every cold runtime helper (heap_alloc_miss, rfc_wrap, blk_copy, span_fade, heap_hand, …) at each call site inside the single work_loop kernel. Each inlined copy of the rfc_wrap → heap_alloc → heap_alloc_miss chain adds about 4 states, and mp3's kernel holds about 51 of them. That is why the failure needs enough unrelated code. When I made device segments host-only one at a time, the threshold was cumulative, with no single culprit. Filler code of the same size that adds no helper call sites does not reproduce it.

Ruled out on the way:

  • WL_RESW > 16 (a 22-word return without M.step passes);
  • maxTotalThreadsPerThreadgroup, maxCallStackDepth and threadgroup memory;
  • the binary archive, the volatile local in a32_load, and uninitialized WL_BANK registers;
  • coherent(device), the blk_loc arguments and the err_spun poll.

Change

On Metal, OUTLINE is now static __attribute__((noinline)), as it already is on the host and on CUDA. A comment above the dialect block says why. The helpers become real device calls, so their flow states stay in their own functions instead of piling into _agc.main.

Verification

Everything below was run on this branch (60fa05dc plus this commit) and on 60fa05dc, on an Apple M1 Pro (Darwin 25.6.0, Metal compiler 32023.850), with GPU jobs one at a time.

  • mp3 repro: see the table above.

  • Flow states in _agc.main (r4h):

    program upstream this PR
    mp3 repro 262, max 335 134, max 134
    same, with TensorFold's non-tail V.mulk 262, max 333 132, max 132
  • The 28 runnable tests in tests/ that contain a !: built -o t and run as ./t, as gates/test.ts does. All 56 runs (upstream and this PR) print their #| lines. printer/offload_bang_g and _h can't be built, because their main is a function; the gate only checks and interprets them.

  • An rms repro (mulk without M.step): 591.4099 on GPU and CPU, upstream and this PR.

  • mandelbrot (big): 3101455856 in every run. Over 8 alternating pairs after a warm-up, both builds took 0.187–0.222 s.

  • tree-matmul (big): 3797651056 in every completed run. Over 10 alternating pairs:

    • upstream: median 1.74 s, fastest 1.43 s;
    • this PR: median 1.71 s, fastest 1.38 s.

    One upstream run was killed by macOS with kIOGPUCommandBufferCallbackErrorImpactingInteractivity (the machine was not idle), so that median is over 9 runs.

ttok -m gpt-3.5-turbo < bend2/comp.ts (the encoding that gives upstream's 63,905): 63,905 → 63,975 (+70), still under the 64,000 cap. Without the comment it would be +8.

mp3 repro driver (needs TensorFold's bend/model)
import Base
import ./model.bend as M
import ./vec.bend as V

def xval(+i: U32) -> F32:
  (U32.to_f32((((i * 2654435761 : U32) >> 24n) : U32)) * 0.00390625 - 0.5 : F32)

def xs(n: Nat, +i: U32) -> V.V:
  match n:
    case 0n:
      Nil{}
    case 1n+p:
      xval(i) <> xs(p, (i + 1 : U32))

def mulk.go(xs: V.V, ys: V.V, +k: F32, acc: V.V) -> V.V:
  match xs ys:
    case Con{x, xt} Con{y, yt}:
      mulk.go(xt, yt, k, (x * y * k : F32) <> acc)
    case _ _:
      List.reverse.go(&2, F32, acc, Nil{})

def mk(+x: V.V) -> V.V:
  mulk.go(x, x, 0.5, Nil{})

def stp(m: M.Model) -> M.Model & V.V:
  M.step(m, 760, 0)

def snd.model(r: M.Model & V.V) -> V.V:
  (t, y) = r
  y

def never(+k: U32, m: M.Model) -> IO(Unit):
  IO.print(F32.show(V.fsum(snd.model(stp!(m)))))

def pick(xs2: List<String>) -> IO(Unit):
  match xs2:
    case Con{_, Con{_, _}}:
      never(0, M.Model{M.HP{0.000001, 10000.0, 2048, 6144, 256, 8, 2, 64, 4, 16, 16, 2048, 4, 248320, 0}, M.Mat{0, 0, 0, M.Leaf{0, [0 : U32^0n]}}, Nil{}, Nil{}})
    case _:
      IO.print(F32.show(V.fsum(mk!(xs(2048n, 0)))))

def main() -> IO(Unit):
  do IO<Unit>:
    a : List<String> <- IO.args()
    pick(a)

Notes / open questions

  • I tested only on an M1 Pro (G13). The gate's M4 minis may not have this 8-bit limit. If they don't, the change only turns cold helpers into calls there.
  • This lowers the count; it doesn't bound it. The count still grows by about 3 per inlined spin site and per return 0 exit in the kernel, so a kernel about twice mp3's size could reach 256 again. A single-exit spin shape (do { … } while (again)) halves mp3's count again (67, measured on hand-edited generated C). It rewrites the spin macros, spin functions and call sites, so it's left as a follow-up with its own timing pass. Running count on the extracted _agc.main is the check.
  • There's no regression test. A failing case needs a kernel with more than 255 flow states, which takes a model-sized program, and the gate runs on M4.
  • This is separate from the Metal: non-tail recursion under a bang faults at 1023 list elements; CPU completes through 100000 #1393/Metal: one ! over a two-leaf fork tree (a 365-fork spine beside a 3-fork spine) faults; each leaf alone, a balanced 365+365, and --gpu off all pass #1394 lane-stack fix. With TensorFold's current non-tail V.mulk, the same repro also needs that fix, because 2048 frames overflow the 2048-word lane stack. The driver above uses a tail loop to isolate this bug. On a tree with both fixes, deep, forks and lsum from those issues still pass on GPU and CPU.

…l past 255 AGX flow states, which the backend tests with 8-bit immediates, so mp3 took wrong branches on an M1 Pro
@Lorenzobattistela

Copy link
Copy Markdown
Collaborator

Thanks @totaland, the write-up is very thorough. I tested 626c841 merged on main 03c3fd8, on an M4 Pro and on the gate's M4 minis.

Gates: repo 54/54, ping 48/48, test 1596/1596, same as main.

I could not reproduce the bug on M4. I built your mulk job (with a 500-element list, since 2048 overflows the lane stack on both trees) next to four renamed copies of demos/pure_hvm5_mini, all called under a ! in branches that never run. The GPU archive grows from about 1.5 MB with one copy to 5.5 MB with four. Main and this PR both print the right sum on the GPU in 3 of 3 runs, and every hvm5 copy also runs correctly under !. So on the hardware the gates use, this change fixes nothing we can see, and we have no way to confirm the M1 fault here.

It does cost time on M4. terrain PAR-GPU is slower in all 4 perf runs: 0.337 to 0.363 s against main's 0.306 to 0.310 s (median +12%), and one run fails the gate at 1.16x. Locally on the M4 Pro it is 0.167 s against 0.157 s. The cost is heap_alloc_miss: making only that helper noinline gives the whole slowdown, while making only rfc_wrap and blk_copy noinline costs nothing. heap_alloc_miss is not cold on the device, because a device lane starts every kernel with empty lists, so it takes the miss path often. The other GPU cells are within noise.

As you say in the description, this lowers the state count but does not bound it. A kernel about twice the size of yours would cross 255 again on an M1, so the fault stays reachable, it just needs a bigger program.

There is no test, and the gate hardware does not show the fault, so nothing would catch it coming back.

comp.ts goes from 63,905 to 63,975 tokens, which leaves 25 under the 64,000 cap. 62 of the 70 are the comment, and it states a fact about Apple's backend that we cannot check from our side.

So as it stands this trades a measured slowdown on the gate's hardware for a partial workaround of an Apple compiler bug on M1 that we can't reproduce, and we can't merge it like this.

@totaland

totaland commented Oct 9, 2026

Copy link
Copy Markdown
Contributor Author

Thanks I will check again and let you know

@Lorenzobattistela

Copy link
Copy Markdown
Collaborator

Could not reproduce, closing because it is stale

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants