Skip to content

A full device lane moves its stack to the heap, so non-tail recursion under ! goes past 1,023 frames - #1819

Open
wakamex wants to merge 1 commit into
bendlang:mainfrom
wakamex:lane-spill
Open

wakamex wants to merge 1 commit into
bendlang:mainfrom
wakamex:lane-spill

Conversation

@wakamex

@wakamex wakamex commented Oct 22, 2026 •

Copy link
Copy Markdown
Contributor

Fixes #1393. Fixes #1394. Follow-up to #1439, which #1809 reverted.

Today on main, a lane on the GPU has a 2,048-word stack (STAK_LEN), and once it fills, the next call posts ERR_DEEP and the run stops. A non-tail List.append under ! fails at 1,023 frames (#1393), an unbalanced fork tree such as two!(365n) fails (#1394), a split-then-append recursion fails at 2,046 elements, and Unbalanced Tree Search (UTS) (uts-compact) exits with ERR_DEEP on the GPU. The host has no such limit.

This PR lets a full lane keep going. A call that may leave no room for the next frame copies the lane's whole stack to a 16 KB heap block and leaves a 3-word exit frame at the stack's base. A return into that frame gives back whole defs, walked down from the top of the block, until about half a stack, and leaves the rest under the exit frame for later returns.

What a call pays

  • Every non-tail call on the device checks, after its frame is pushed and its arguments are loaded, whether the widest frame any device segment pushes still fits: one compare against STAT_OFF minus that width (3 to 12 words across bench/runtime, 242 in the wide test). The width is taken once over the live device segments, after c_header checks their arity. When the frame doesn't fit, the call sets rn = F | 1 << 16 (no call site reads rn) and jumps to work_loop's default:, which spills and dispatches F; any other unknown fid still posts ERR_FIDS. Metal has no goto, so the jump goes through the switch.
  • A self call compiles to a loop, so its check comes after the loop's parameters are set and copies them back to r0.. only on the spill path; otherwise the loop would keep r0.. live on every iteration.
  • lane_spill and lane_unspill are out-of-line device functions. FID_EXIT handles a spill frame before it reads FID_T.

Why a lane never writes past its stack

Between two checks a lane pushes at most one frame: a check passes only while the widest frame still fits, and after a call returns its continuation pushes one frame before the next check. A restore resumes the lane at about half a stack plus one def's words. A def has at most 493 words on the stack (a continuation takes at most 247 parameters, and every word a fork keeps to its end counts against its last continuation's), 443 in the wide test, so a lane resumes at about 1,520 words at most, below every threshold. Each def's words on the stack when a continuation's fid is on top (FID_DEEP, emitted only in device code) come from emit_fork.

Limits

  • Past 2^12 nested spills a lane posts the deep-stack error, so runaway recursion under ! stops in 1 to 2 s. That is 64 MB of blocks a lane: about 25 lanes running away at once fill a 2 GB span and get the out-of-memory error first. A million-deep recursion takes about 1,000 spills.
  • When a spill cannot get its block, the lane stops with the out-of-memory error before it copies anything.
  • A loop that keeps crossing the threshold from well below still spills on each crossing: sawtooth_over, a loop whose callee recurses 1,100 deep, takes 1.82 s on the M4 for 3,000 iterations, where main faults.

Effects on shared code

  • Host: WL_ROOM and WL_FULL expand to nothing and 0, and FID_DEEP is device-only. objdump -d shows the same host machine code as main for symreg, merkle, queens, raytrace and tree-matmul, apart from addresses.
  • Device: every return through FID_EXIT tests wf == FID_EXIT first.
  • Device: ERR_DEEP now means 2^12 spills, not a full stack. tests/io/stack_fault_trap.bend's comment says so; its output is unchanged.
  • FID_DEEP joins FID_T among the reserved names.

comp.ts goes from 66,000 to 66,799 ttok (+799), so the repo gate stays red until the cap in gates/repo.ts goes up.

Tests

tests/compile/bang_lane_spill.bend covers a 5,000-deep List.append (#1393), two!(365n) (#1394), a fork whose spills come at its second call while it holds words from its first, the review's loop a few words under the top (its first call spills once here; giving back the whole stack spilled 6,000 times), and a split-then-append recursion over 4,096 elements. tests/compile/bang_lane_spill_wide.bend covers a def with 443 words on the stack. Both pass on Metal, on CUDA, natively, interpreted and as JS. All 44 runnable tests with a ! pass on an M4 mini and on an RTX 3090; main fails only the two spill tests, and the same two other tests don't build to a runnable program on either. bend-bench compiler-check builds and runs every test natively on both: 863 pass on main and 862 here, the same 19 print something else and the same 920 do not build to a runnable program on either; the one difference, tests/io/tcp_send_slow_peer.bend, timed out once while the machine's load average passed 100 and passes 3 of 3 runs alone. Checking and emitting C take the same time in total (0.991x and 0.975x).

Metal (Mac mini M4)

Measured with bend-bench's metal/compare.sh and summarized by bend-bench metal-report (how to run it), on a Mac mini M4 (10-core GPU, macOS 26.7.2), main 00d29f4 against this PR:

  • The review's program: 0.136 s on main and 0.133 s here at depth 2,040, 0.137 and 0.128 s at 2,000. A million-deep recursion takes 0.77 s, the 100,000-element split-append 0.19 s, and a loop calling across the threshold 0.10 s, where main faults; deep!(1000000000n) stops with the deep-stack error after 1.3 s.
  • Build time, median of 7 alternated runs a side over the 17 bench/runtime programs (lower is better): ./main +RTS --gpu-build totals 3.78 s on main and 3.56 s here (5.9% shorter), and bend main.bend -o main 13.49 s and 13.24 s (1.9% shorter). symreg's --gpu-build goes from 0.270 to 0.258 s and merkle's from 0.169 to 0.168 s. The largest increase is gameoflife (0.137 to 0.143 s, +4.4%); the largest decreases are tree-matmul (-20.0%) and histogram (-16.1%).
  • Runtime of the same 17 programs in 4 blocks of A B B A / B A A B. A block's ratio is main's time over this PR's, so above 1x means this PR is faster; with 4 blocks, the interval is the lowest and highest block, so a verdict means all 4 agree:
Program Main (s) This PR (s) Median block ratio Lowest to highest block Verdict
bfs 0.772 0.770 0.997x 0.982x to 1.002x no detected change
editdist 0.467 0.476 0.994x 0.982x to 1.002x no detected change
gameoflife 0.131 0.132 1.001x 0.964x to 1.050x no detected change
hashmap 1.400 1.392 1.008x 1.001x to 1.017x faster
histogram 1.380 1.410 0.980x 0.976x to 0.984x slower
kmeans 0.641 0.642 1.005x 0.995x to 1.016x no detected change
lexer 2.598 2.473 1.038x 1.022x to 1.051x faster
mandelbrot 0.112 0.115 0.980x 0.958x to 1.033x no detected change
merkle 0.119 0.119 0.999x 0.993x to 1.013x no detected change
nbody 0.104 0.103 1.008x 0.999x to 1.041x no detected change
queens 2.528 2.420 1.076x 1.007x to 1.204x faster
raytrace 0.321 0.328 1.004x 0.965x to 1.029x no detected change
symreg 0.715 0.687 1.040x 1.029x to 1.052x faster
terrain 0.273 0.273 1.011x 0.988x to 1.038x no detected change
tree-bitonic 1.640 1.602 1.042x 0.813x to 1.117x no detected change
tree-matmul 0.603 0.607 1.000x 0.988x to 1.090x no detected change
tree-radix 1.181 1.184 0.998x 0.998x to 0.999x slower

histogram is 2.0% slower, and that comes from its 6 self-call checks: built without them it runs as fast as main (0.995x over 6 blocks), and with only them it is 2.3% slower. Every form of that check I tried costs histogram the same 2%, including the earlier one before the parameter copy, which makes queens slower than this form does. tree-radix is 0.2% slower. I haven't found why queens, symreg and lexer get faster.

CUDA (RTX 3090, CUDA 13.1)

Against main 00d29f4:

  • uts-compact finishes (293367 0); main faults.
  • Registers per thread of bend_dev: the same as main for queens, symreg, merkle, hashmap, raytrace, lexer and tree-radix; up for histogram (96 to 110), editdist (56 to 66), gameoflife (70 to 75), tree-bitonic (74 to 80), bfs (64 to 68), terrain (60 to 64) and kmeans (114 to 118); down for tree-matmul (92 to 90).
  • I didn't get a clean CUDA runtime comparison of this commit: the machine never went quiet enough, and the M4 numbers above are the ones that decide.

@wakamex
wakamex marked this pull request as ready for review October 22, 2026 02:06
@wakamex

wakamex commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

my clanker opened this without me telling them to

to be fair to them, they seem confident about it:

### Only Open Items (Nothing Blocking)

1. `ttok` cap in [repo.ts](file:///code/bend/gates/repo.ts): `main` is at `66,000 / 66,000` for [comp.ts](file:///code/bend/bend2/comp.ts) because `#1809` kept `#1439`'s token cuts and `#1542` consumed that headroom. This PR adds `+268` `ttok` (`66,268`, vs `+283` in `#1439`). Per [AGENTS.md](file:///code/bend/AGENTS.md), only Taelin changes the cap in [repo.ts](file:///code/bend/gates/repo.ts) or golf-trims [comp.ts](file:///code/bend/bend2/comp.ts) if he wants it under `66,000`.
2. Apple M4 Metal `--gpu-build` gate (`gates/perf.ts`): we verified `--gpu-build` on CUDA (`NVRTC` + `ptxas`), where the 27-site `symreg` and 8-site `merkle` builds that regressed by 17% on Metal in `#1809` are now `-6.1%` and `-4.0%` faster uncached (`+2.7%` and `+1.8%` warm front-end), because the 27 inlined 4-argument calls and branches were replaced by `if (sp >= ...) { fid = F; goto sp_spill; }` and a single `lane_spill(e, sp)` call site. The Metal compiler on the mini cluster will confirm the exact `apple_m4` numbers when Taelin runs `gates/perf.ts`.

@wakamex
wakamex marked this pull request as draft October 22, 2026 03:11
@wakamex

wakamex commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

needs more work, gonna rent a Mac to test

@wakamex wakamex changed the title A full device lane jumps to one spill site after loading r0..rn, so non-tail recursion under ! no longer faults at 1023 frames (#1393, #1394) A device lane short of stack moves it to the heap and back, so non-tail recursion under ! no longer faults at 1023 frames (#1393, #1394) Oct 22, 2026
@wakamex

wakamex commented Oct 22, 2026

Copy link
Copy Markdown
Contributor Author

okay I rented a Mac ($15 minimum, can't rent for less than a day, thanks Apple) and updated the PR

@wakamex
wakamex marked this pull request as ready for review October 22, 2026 17:45
@Lorenzobattistela Lorenzobattistela self-assigned this Nov 2, 2026
@Lorenzobattistela

Copy link
Copy Markdown
Collaborator

I rebased this onto main (00d29f4) and force-pushed it as a17e017, so it merges cleanly again; the logic is unchanged.

It does fix #1393 and #1394 on Metal: the issues' own programs (deep.bend at 1023 to 1,000,000; forks.bend at 365 3, 174 3 and 365 3 3 3 3) now finish with the same output as the CPU, where main faults. On main, all gates pass (test 1804/1804, perf 124/124, ping 81/81, safe 0 false rejects), except repo: comp.ts is at 66,381 ttok, over the 66,000 cap.

But it also introduces regressions that block the merge:

  1. Programs that run fine on main get much slower. A lane spills before it is actually full and copies its whole stack out and back on every call made near the threshold, with no headroom after a restore. So a program that sits near the top of the stack and keeps calling there pays two full-stack copies, a heap alloc and a heap free per call. Measured on an M4 (Metal), same output on both:

    depth main this PR
    2000 0.14 s 0.13 s
    2040 0.14 s 19.33 s
    import Base
    
    def h(n: Nat, +a: U32) -> U32:
      match n:
        case 0n:
          a
        case 1n+p:
          y = h(p, a)
          ((y * 31 : U32) + 7 : U32)
    
    def loop(n: Nat, +acc: U32) -> U32:
      match n:
        case 0n:
          acc
        case 1n+p:
          x = h(2n, acc)
          y = h(2n, x)
          loop(p, (y + 1 : U32))
    
    def down(d: Nat, +n: Nat) -> U32:
      match d:
        case 0n:
          loop(n, 0)
        case 1n+p:
          x = down(p, n)
          (x + 1 : U32)
    
    def main() -> IO(Unit):
      do IO<Unit>:
        IO.print(U32.show(down!(2040n, 30000n)))

    The perf gate does not catch this: no bench runs at that depth.

  2. The window where (1) happens grows with the program. FL.room is one maximum over every fork in the program, so a single wide def anywhere lowers the spill threshold for every lane and every def. With tall from the new test, room is 449, so every lane spills from about 1,599 of its 2,048 words. Any program that runs on main between that and the real limit, calling repeatedly at that depth, is exposed to the slowdown in (1).

  3. Out-of-bounds read on every return through a spill frame. In WL_CASE(FID_EXIT), u32 wn = fid_arity(wf) still runs when wf == FID_EXIT. FID_T has one entry per segment and FID_EXIT is defined as entries.length, so this reads FID_T[FID_EXIT], one past the end of a constant array, on both Metal and CUDA.

  4. A corrupt fid no longer fails loudly. The device default: case now takes any fid with a bit at or above 16 as a spill request: it masks the fid and dispatches it. On main the same fid posts ERR_FIDS. A corrupted continuation word that used to stop the run now silently runs some other segment, with the wrong registers.

  5. A heap miss during a spill corrupts memory. lane_spill does not check heap_alloc's result. When the heap is full, heap_alloc posts ERR_HEAP and returns HEAP_OFF, and lane_spill copies up to 2,048 stack words over whatever is at HEAP_OFF before the lanes see the error.

  6. Runaway recursion gives the wrong error. Infinite non-tail recursion under ! used to fail quickly with the deep-stack error. Now it spills block after block until the heap is gone, then says "out of memory: run again with a bigger span", which cannot help.

… under ! goes past 1,023 frames

On main (00d29f4) a lane on the GPU has a 2,048-word stack and the call
that fills it posts ERR_DEEP: a non-tail List.append under ! stops at
1,023 frames (bendlang#1393), an unbalanced fork tree such as two!(365n) stops
(bendlang#1394), and so do a split-then-append recursion at 2,046 elements and
uts-compact.

Now a call that may leave no room for the next frame copies the lane's
stack to a 16 KB heap block under a 3-word exit frame [the block's task,
spills << 32 | words, FID_EXIT]. A return into that frame gives back whole
defs, walked down from the top of the block through FID_DEEP (each def's
words on the stack when a continuation's fid is on top, from emit_fork,
device code only), until about half a stack, and leaves the rest under
the exit frame.

- Every non-tail device call checks, after its frame is pushed and its
  arguments are loaded, whether the widest frame pushed by any device
  segment still fits; that width is taken once over the live device
  segments, after c_header checks their arity. When it does not fit, the
  call sets rn = F | 1 << 16 (no call site reads rn) and jumps to
  work_loop's default case, which spills and dispatches F; any other
  unknown fid still posts ERR_FIDS. Metal has no goto, so the jump goes
  through the switch.
- A self call compiles to a loop, so it checks after setting the loop's
  parameters and copies them back to r0.. only to spill; the loop keeps
  r0.. dead.
- FID_EXIT handles a spill frame before it reads FID_T.
- lane_spill stops the lane when its block cannot be allocated, before
  copying, and posts ERR_DEEP past 2^12 nested spills a lane (64 MB of
  blocks), so runaway recursion under ! stops in about 2 s; about 25 lanes
  running away at once fill a 2 GB span and get the out-of-memory error
  first.
- FID_DEEP is reserved like FID_T.

A restore resumes a lane at about half a stack plus one def's words, and a
def holds at most 493 words (a continuation takes at most 247 parameters,
and every word a fork keeps to its end counts against its last
continuation's), so no push after a restore passes the stack. Host machine
code is the same as main for symreg, merkle, queens, raytrace and
tree-matmul (objdump -d, addresses aside).

tests/compile/bang_lane_spill.bend covers bendlang#1393, bendlang#1394, spills at a fork's
second call while it holds words from its first, a loop a few words under
the top whose first call spills (6,000 spills when a return gives back the
whole stack, 1 here), and a split-then-append recursion;
tests/compile/bang_lane_spill_wide.bend covers a def with 443 words on the
stack. Both pass on Metal, CUDA, natively, interpreted and as JS, and
all 44 runnable tests with a ! pass on a Mac mini M4 and an RTX 3090. On
the M4 against main (bend-bench metal/compare.sh), --gpu-build over the
17 bench/runtime programs is 5.9% shorter (symreg 0.270 to 0.258 s,
merkle 0.169 to 0.168 s), histogram runs 2.0% slower (its self-call
checks; without them it matches main), symreg 4.0% and queens 7.6%
faster, and the bendlang#1819 review's program at depth 2,040 takes 0.133 s
(0.136 s on main).

comp.ts goes from 66,000 to 66,799 ttok (+799).
@wakamex wakamex changed the title A device lane short of stack moves it to the heap and back, so non-tail recursion under ! no longer faults at 1023 frames (#1393, #1394) A full device lane moves its stack to the heap, so non-tail recursion under ! goes past 1,023 frames Nov 14, 2026
@wakamex

wakamex commented Nov 14, 2026

Copy link
Copy Markdown
Contributor Author

Thanks for the rebase and the review. All six were real. I reworked the spill around the first two and pushed it as one commit, 6fbd597. Numbers are from a Mac mini M4 against main 00d29f4, measured with bend-bench's metal/compare.sh.

  1. Repeated copies near the top. A return into the exit frame now gives back whole defs, walked down from the top, until about half a stack, and leaves the rest under the exit frame. Each def's words on the stack when a continuation's fid is on top are known at compile time (a device-only FID_DEEP table), and a def holds at most 493 words (443 in the wide test), so a lane resumes at about 1,520 words at most. Your program at depth 2,040: 0.136 s on main, 0.133 s now (19.3 s in your run of the previous version). In the test, your loop sits a few words under the top so its first h spills: once here, 6,000 times when a return gives back the whole stack.
  2. Threshold. Because a resumed lane sits low, a check only needs room for the next frame: the threshold is the widest frame any live device segment pushes, taken once after c_header checks arity (3 to 12 words across bench/runtime, 242 in the wide test), not the longest chain and not a running max over every pass and host-only def. A program that peaks below 2,048 minus that never spills.
  3. FID_T[FID_EXIT]. The spill branch of FID_EXIT runs first and never reads FID_T.
  4. Corrupt fids. A full lane jumps to default: with rn = F | 1 << 16 (no call site reads rn), and default: spills only when rn carries that flag; any other unknown fid posts ERR_FIDS as on main.
  5. Heap miss. lane_spill checks its allocation before copying and stops the lane. With a 2^25-cell array filling most of a 540 MB span, a 1,000-deep recursion runs and a million-deep one stops with the out-of-memory error, nothing corrupted.
  6. Runaway recursion. Past 2^12 nested spills a lane posts the deep-stack error: deep!(1000000000n) gets it after 1.3 s. A spill block is 16 KB, so that cap is 64 MB a lane, and about 25 lanes running away at once fill a 2 GB span and get out-of-memory first. A lower cap would cut legitimate depth (a million-deep recursion already takes about 1,000 spills). Separately, a forking def calling a non-forking one runs it off the stack on the device, so 16 such runaways run out of memory on main too.

Other changes on the way:

  • A self call compiles to a loop, and checking it by jumping out of the loop kept r0.. live through every iteration (queens 7% slower on CUDA). It now checks after setting the loop's parameters and copies them back to r0.. only to spill.
  • FID_DEEP is reserved like FID_T, so a def named DEEP still builds.
  • tall moved to tests/compile/bang_lane_spill_wide.bend: in one file its 242-word frame set everyone's threshold, so walk never spilled at its second call.

What didn't work on the way:

  • Restoring one chain at a time instead of half a stack: a million-deep unwind would make a restore call per chain.
  • Spilling inside the self-call loop through an inlined lane_spill: queens got back to 1.8% slower on CUDA, but registers went up in 15 of the 17 bench/runtime programs (symreg 64 to 72, tree-radix 80 to 94), so it stays out of line.
  • The queens cost wasn't rn or the extra FID_EXIT branch; with each removed in turn it stayed 7% slower until the self-call check moved after the parameters.

On the M4:

  • All 44 runnable tests with a ! pass; main fails only the two spill tests.
  • --gpu-build over the 17 bench/runtime programs, median of 7 alternated runs each: 3.78 s on main, 3.56 s here (5.9% shorter). symreg 0.270 to 0.258 s, merkle 0.169 to 0.168 s; the largest increase is gameoflife, +4.4%. bend -o totals 1.9% shorter.
  • Runtime, 4 A B B A / B A A B blocks: histogram 2.0% and tree-radix 0.2% slower in all 4; symreg 4.0%, lexer 3.8%, queens 7.6% and hashmap 0.8% faster in all 4; the other 11 no detected change.
  • histogram's 2% is its 6 self-call checks: without them it runs as fast as main, and with only them it's 2.3% slower. Every form of the check I tried costs it the same; this one keeps queens fastest.

Host machine code is the same as main for symreg, merkle, queens, raytrace and tree-matmul. comp.ts is at 66,799 ttok, 799 over the cap.

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

Labels

None yet

Projects

None yet

2 participants