Skip to content

Metal: standalone renderer fails with “a function the device does not hold”; CPU and interpreter agree #1954

Closed

Description

@holmesworcester

What you did

On an M1 Mac, save the file below as metal_fids_repro.bend:

bend metal_fids_repro.bend -o mfr
./mfr
./mfr +RTS --gpu 1GB
./mfr +RTS --gpu off
bend metal_fids_repro.bend

What happened

Original Metal investigation:


$ ./mfr
bend: a function the device does not hold

$ ./mfr +RTS --gpu off
57798656

$ bend metal_fids_repro.bend
57798656

The standalone Metal reproducer failed in 5/5 recorded runs, with exit status 1 in under a second. A 1 GB GPU memory cap also failed. Expected: 57798656, matching the CPU and interpreter. Fresh Linux checks with Bend 2.0.39 confirmed that both controls still print 57798656.

The program builds cells on the host, performs an IO.now() step, then calls Frame.node!. Thus the bang is at a fresh IO step, not inside earlier CPU-parallel work.

The original reduction found that replacing the constant Seg{67588, Seg{100532, SegEnd{}}} in Font.pick with a heap-built Seg{c, SegEnd{}}, or returning SegEnd{} from both arms, made the GPU run pass. In this reproducer the glyph code is always 32, so the arm for code 33 is not taken. Changes to that unexecuted arm nonetheless changed GPU success/failure.

Instrumentation during the original investigation observed invalid task words at device task entry and changing invalid function IDs. This suggests memory corruption or a Metal toolchain issue, rather than an ordinary missing function, but the root cause is unverified. No compiler fix is claimed.

Related reports checked: #1128 (F32.show on the device), #1513 (type-family closure discovery), and #1433 (Metal compiler flow-state limit). This file does not call F32.show or use the type-family/closure pattern in #1513. No matching open report was found.

The file

import Base

type Segs is Data:
  SegEnd{}
  Seg{+s: U32, next: Segs}

def Font.pick(b: Bool, +c: U32) -> Segs:
  match b:
    case True{}:
      Seg{67588, Seg{100532, SegEnd{}}}
    case False{}:
      SegEnd{}

def Font.glyph(+c: U32) -> Segs:
  Font.pick(U32.is_eq(c, 33), c)

type Item is Data:
  IGlyph{+x: U32, +y: U32, +code: U32}

type Items is Data:
  INil{}
  ICons{+it: Item, next: Items}

type Cells is Data:
  CNil{}
  CLeaf{ts: Items}
  CQua{tl: Cells, tr: Cells, bl: Cells, br: Cells}

def pick(c: Bool, a: F32, b: F32) -> F32:
  match c:
    case True{}:
      a
    case False{}:
      b

def fmin(+a: F32, +b: F32) -> F32:
  pick((a < b : F32), a, b)

def fmax(+a: F32, +b: F32) -> F32:
  pick((a < b : F32), b, a)

def clamp01(+x: F32) -> F32:
  fmin(1.0, fmax(0.0, x))

# n glyphs in rows of 40, 18 x 40 px apart, codes 32..126.
def Text.grid(n: Nat, +i: U32, acc: Items) -> Items:
  match n:
    case 0n:
      acc
    case 1n+p:
      Text.grid(p, (i + 1 : U32), ICons{IGlyph{(i % 40 * 18 : U32), (i / 40 * 40 : U32), (i % 95 + 32 : U32)}, acc})

def Item.meets(+it: Item, +x0: U32, +y0: U32, +x1: U32, +y1: U32) -> Bool:
  match it:
    case IGlyph{gx, gy, _}:
      ((gx < x1 + 2) && (gx + 16 > x0) && (gy < y1 + 2) && (gy + 30 > y0) : U32)

def Items.keep(meets: Bool, +it: Item, acc: Items) -> Items:
  match meets:
    case True{}:
      ICons{it, acc}
    case False{}:
      acc

def Items.clip(xs: Items, +x0: U32, +y0: U32, +x1: U32, +y1: U32, acc: Items) -> Items:
  match xs:
    case INil{}:
      acc
    case ICons{+it, t}:
      Items.clip(t, x0, y0, x1, y1, Items.keep(Item.meets(it, x0, y0, x1, y1), it, acc))

def Cells.build(+k: Nat, xs: Items, +x: U32, +y: U32) -> Cells:
  match k xs:
    case _ INil{}:
      CNil{}
    case 0n ICons{h, t}:
      CLeaf{ICons{h, t}}
    case 1n+e ICons{h, t}:
      +xs = {ICons{h, t} : Items}
      +s = U32.shln(64, e)
      +x1 = (x + s : U32)
      +y1 = (y + s : U32)
      q0 : Items = Items.clip(xs, x, y, x1, y1, INil{})
      q1 : Items = Items.clip(xs, x1, y, (x1 + s : U32), y1, INil{})
      q2 : Items = Items.clip(xs, x, y1, x1, (y1 + s : U32), INil{})
      q3 : Items = Items.clip(xs, x1, y1, (x1 + s : U32), (y1 + s : U32), INil{})
      a b c d = Cells.build(e, q0, x, y) Cells.build(e, q1, x1, y) Cells.build(e, q2, x, y1) Cells.build(e, q3, x1, y1)
      CQua{a, b, c, d}

def Glyph.d2(segs: Segs, +u: F32, +v: F32, +best: F32) -> F32:
  match segs:
    case SegEnd{}:
      best
    case Seg{s, next}:
      +x0 = U32.to_f32((s .&. 15 : U32))
      +y0 = U32.to_f32(((s >> 4n) .&. 31 : U32))
      +dx = (U32.to_f32(((s >> 9n) .&. 15 : U32)) - x0 : F32)
      +dy = (U32.to_f32(((s >> 13n) .&. 31 : U32)) - y0 : F32)
      +l2 = fmax((dx * dx + dy * dy : F32), 0.0001)
      +t = clamp01((((u - x0) * dx + (v - y0) * dy) / l2 : F32))
      +qx = (x0 + t * dx - u : F32)
      +qy = (y0 + t * dy - v : F32)
      Glyph.d2(next, u, v, fmin(best, (qx * qx + qy * qy : F32)))

def Glyph.cov(near: Bool, +k: U32, +gx: U32, +gy: U32, +px: F32, +py: F32) -> F32:
  match near:
    case False{}:
      0.0
    case True{}:
      +u = ((px - U32.to_f32(gx)) / 1.75 : F32)
      +v = ((py - U32.to_f32(gy)) / 1.75 : F32)
      +d = (F32.sqrt(Glyph.d2(Font.glyph(k), u, v, 1000.0)) * 1.75 : F32)
      d

def Px.go(ts: Items, +x: U32, +y: U32, +px: F32, +py: F32, +ink: F32) -> U32:
  match ts:
    case INil{}:
      F32.to_u32((ink * 255.0 : F32))
    case ICons{IGlyph{gx, gy, k}, t}:
      Px.go(t, x, y, px, py, fmax(ink, Glyph.cov(True{}, k, gx, gy, px, py)))

def Px.at(+ts: Items, +x: U32, +y: U32) -> Image:
  Pix{Px.go(ts, x, y, (U32.to_f32(x) + 0.5 : F32), (U32.to_f32(y) + 0.5 : F32), 0.0)}

def Tile.b2(+ts: Items, +x: U32, +y: U32) -> Image:
  Qua{Px.at(ts, x, y), Px.at(ts, (x + 1 : U32), y), Px.at(ts, x, (y + 1 : U32)), Px.at(ts, (x + 1 : U32), (y + 1 : U32))}

def Tile.b4(+ts: Items, +x: U32, +y: U32) -> Image:
  Qua{Tile.b2(ts, x, y), Tile.b2(ts, (x + 2 : U32), y), Tile.b2(ts, x, (y + 2 : U32)), Tile.b2(ts, (x + 2 : U32), (y + 2 : U32))}

def Tile.b8(+ts: Items, +x: U32, +y: U32) -> Image:
  Qua{Tile.b4(ts, x, y), Tile.b4(ts, (x + 4 : U32), y), Tile.b4(ts, x, (y + 4 : U32)), Tile.b4(ts, (x + 4 : U32), (y + 4 : U32))}

def Tile.b16(+ts: Items, +x: U32, +y: U32) -> Image:
  Qua{Tile.b8(ts, x, y), Tile.b8(ts, (x + 8 : U32), y), Tile.b8(ts, x, (y + 8 : U32)), Tile.b8(ts, (x + 8 : U32), (y + 8 : U32))}

def Tile.go(+cs: Items, +x: U32, +y: U32) -> Image:
  Tile.b16(cs, x, y)

def Cell.fork(+k: Nat, +cs: Items, +x: U32, +y: U32) -> Image:
  match k:
    case 0n:
      Tile.go(cs, x, y)
    case 1n+e:
      +h = U32.shln(16, e)
      a b c d = Cell.fork(e, cs, x, y) Cell.fork(e, cs, (x + h : U32), y)
        Cell.fork(e, cs, x, (y + h : U32)) Cell.fork(e, cs, (x + h : U32), (y + h : U32))
      Qua{a, b, c, d}

def Frame.node(c: Cells, +k: Nat, +x: U32, +y: U32) -> Image:
  match c:
    case CNil{}:
      Pix{0}
    case CLeaf{ts}:
      Cell.fork(2n, ts, x, y)
    case CQua{tl, tr, bl, br}:
      match k:
        case 0n:
          Pix{0}
        case 1n+e:
          +s = U32.shln(64, e)
          a b cc d = Frame.node(tl, e, x, y) Frame.node(tr, e, (x + s : U32), y)
            Frame.node(bl, e, x, (y + s : U32)) Frame.node(br, e, (x + s : U32), (y + s : U32))
          Qua{a, b, cc, d}

def Frame.show(+cells: Cells) -> Image & Cells:
  (Frame.node!(cells, 5n, 0, 0), cells)

def Img.sum(img: Image) -> U32:
  match img:
    case Pix{c}:
      c
    case Qua{a, b, c, d}:
      (Img.sum(a) + Img.sum(b) + Img.sum(c) + Img.sum(d) : U32)

def Frame.sum(p: Image & Cells) -> U32:
  (img, _) = p
  Img.sum(img)

def go(n: Nat, +text: Items, +acc: U32) -> IO(Unit):
  match n:
    case 0n:
      IO.print(U32.show(acc))
    case 1n+p:
      do IO<Unit>:
        cells : Cells = Cells.build(5n, text, 0, 0)
        now : Nat <- IO.now()
        t : U32 = Frame.sum(Frame.show(cells))
        go(p, text, (acc + t : U32))

def main() -> IO(Unit):
  do IO<Unit>:
    cells : Cells = Cells.build(5n, ICons{IGlyph{0, 0, 32}, INil{}}, 0, 0)
    now : Nat <- IO.now()
    IO.print(U32.show(Img.sum(Frame.node!(cells, 5n, 0, 0))))

bend version

bend 2.0.39

uname -sm

Darwin arm64

clang --version (the first line)

Apple clang version 17.0.0 (clang-1700.6.4.2)

Activity

  1. added
    bug
    on Oct 30, 2026
  2. Lorenzobattistela commented on Oct 30, 2026

    @Lorenzobattistela
    Collaborator

    Thanks for the detailed report and the standalone reproducer.

    We can't reproduce it here: we have no M1. On an M4 Pro (macOS 26.5.2) the file prints 57798656 on Metal 100/100 times, both on current main (9d514f3) and on the v2.0.39 tag, with --gpu on and with --gpu 1GB. --gpu off and the interpreter agree, as on your machine.

    The Metal program is compiled on the machine itself (newLibraryWithSource), so an M1 (AGX G13) and an M4 (G16) get different machine code from the same source. That fits a failure that only shows up on M1: either a Metal compiler problem on that GPU family, or an undefined read in our shader that happens to work on the newer GPU. We can't tell those apart without M1 hardware.

    If you can run a few more things on the M1, that would help:

    • your macOS version (sw_vers -productVersion)
    • whether it still fails when built from current main
    • the output of MTL_DEBUG_LAYER=1 ./mfr (Metal API validation)

    Leaving this open for now in case someone with an M1/M2 can take a look.

  3. raramos9 commented on Oct 30, 2026

    @raramos9
    Contributor

    Thankfully I have an M1 Mac so I can try reproducing the Metal failure locally. I'll start by reproducing the issue and reducing the failing example, then investigate the root cause. I'll share my findings here before proposing a fix.

  4. raramos9 commented on Oct 30, 2026

    @raramos9
    Contributor

    I investigated this on an Apple M1 (7-core GPU, 16 GB RAM) running macOS 15.6.1. My mac software version is super old so im planning to update and retest to see if that plays a role.

    I tested both Bend v2.0.39 (a3efe8a3) and current main (f1273d30). Across 466 GPU executions, the reproducer consistently returned the expected 57798656. I also instrumented the generated runtime to confirm that GPU work was actually submitted.

    With MTL_DEBUG_LAYER=1, both versions passed without validation errors.

    One additional observation: enabling MTL_SHADER_VALIDATION=1 caused a crash inside Apple's validation tooling when loading the cached .gpu file. Removing that cache allowed the shader to compile from source and execute successfully.

    I traced the reported error to the GPU function dispatch path, where a function ID without an available GPU implementation triggers ERR_FIDS.

    Would you be able to confirm your macOS version? That would help narrow down the environment difference.

  5. HamedShams commented on Oct 30, 2026

    @HamedShams
    Contributor

    Reproduced here on an M1 Max, every run. The same program passes every run once the shader is compiled at Metal's size optimisation level, which I think is the story. Details below.

    Machines so far

    who chip macOS bend Metal result
    @holmesworcester M1 (which one?) ? v2.0.39 fails 5/5
    @Lorenzobattistela M4 Pro 26.5.2 main 9d514f3, v2.0.39 passes 100/100
    @raramos9 M1, 7-core GPU 15.6.1 main f1273d3, v2.0.39 passes 466/466
    me M1 Max, 32-core GPU, 64 GB 27.2 (26B123) main 9e8d7b7 and 26628b1, v2.0.38, v2.0.37 fails 10/10 on each

    Host toolchain here: Xcode 27.1, Apple clang 21.0.0 (clang-2100.3.34.2), bun 1.4.2; system_profiler reports Metal 4. The shader itself is compiled by the OS (newLibraryWithSource), which on this macOS defaults to MSL 4.1.

    What the failure looks like here

    • ./mfr: mostly a function the device does not hold, sometimes frontier drained without a result, and once a hang past 60 s. +RTS --gpu off and the interpreter print 57798656.
    • MTL_DEBUG_LAYER=1: prints nothing, still fails.
    • MTL_SHADER_VALIDATION=1 with the cached .gpu: segfault inside the validation layer, the same crash raramos9 saw. With the .gpu removed, so the shader is compiled from source: "Metal GPU Validation Enabled", nothing reported, still fails. So there is no out-of-bounds access the validator can see.

    Ruled out, each rebuilt from main and run 10 times:

    • the cached .gpu: compiled from source on every run, same failures
    • the volatile err_peek from On MSL 3.2+, heap_free reads the error flag with a coherent volatile load, not an atomic one (#1143) #1299: rebuilt with the atomic load, same failures
    • the shading language version: pinned to 3.2 and to 4.0, 10/10 failures each (3.1 does not compile, the source needs 3.2)
    • GPU size and concurrency: CUBE_LOG 4 and 6, so 16 and 64 threadgroups per pass instead of 128, still fail 10/10. A 32-core GPU running more groups at once is not the trigger.

    What flips it

    One line in gpu_desc:

    opts.optimizationLevel = MTLLibraryOptimizationLevelSize;

    With it: 40/40 passes, 10/10 with +RTS --gpu 1GB, clean under MTL_DEBUG_LAYER=1. The default build, run in between, still fails 5/5. For this program the binary archive shrinks from 1011 KB to 389 KB. For bench/runtime/mandelbrot and nbody the two levels differ by 32 bytes, give the same checksums (3101455856 and 3516450380) and the same wall time (0.16 to 0.20 s here). So the default-level compiler does something to this particular program that it does not do to those two.

    Reading of it

    The trigger is the machine code the newer Metal compiler produces for the M1 family at the default level. It fits every row of the table: the M1 on macOS 15.6.1 passes (older compiler, same GPU family), the M4 Pro on 26.5.2 passes (same era compiler, different GPU family, so different code), and the M1 Max on 27.2 fails. The reporter's row is the missing cell. Whether the compiler miscompiles, or the shader relies on an ordering that only the optimised code breaks, I cannot tell from outside; both fit the data. It is not a recent regression on Bend's side: v2.0.37 fails the same way.

    Two things would complete the table:

    • @holmesworcester: sw_vers -productVersion, and which M1 it is (M1, Pro, Max)?
    • @raramos9: after your macOS update, does the default build still pass on your M1? If it starts failing, that settles the compiler-version side. And does a build with the line above pass there too? I'd expect yes.

    Next

    I'm preparing a PR that compiles the device program at the size level on M1-family GPUs only (supportsFamily:MTLGPUFamilyApple7 without Apple8), so M2 and later keep the default code, with the runtime bench table for both levels on this machine. In parallel I'll keep narrowing down which construct the default level breaks and report here when I have it, so the workaround can give way to a real fix.

  6. raramos9 commented on Oct 30, 2026

    @raramos9
    Contributor

    @HamedShams Thanks for investigating this! I updated my M1 (7-core GPU) from macOS 15.6.1 to 27.2 (26B123), and the failure now reproduces consistently.

    On 15.6.1, all 466 GPU executions passed. After updating, all 400 executions across v2.0.39 and main (f1273d30) failed, mostly with a function the device does not hold or frontier drained without a result. CPU execution and the interpreter still return the expected result.

    I also instrumented the GPU task dispatch path and found that the failing function IDs come from words containing float-like data rather than valid task words. That suggests the invalid state exists before dispatch, although its origin is still unknown.

    I'm going to test MTLLibraryOptimizationLevelSize on my M1 to see whether it eliminates the failures here as well. I'll report back with the results.

  7. HamedShams commented on Oct 31, 2026

    @HamedShams
    Contributor

    @raramos9 thanks, that settles the compiler side: same M1, same program, 15.6.1 passes and 27.2 fails.

    The fix is #1978 and it is not the size-level gate I announced above. I kept bisecting and the construct is one call: the Metal compiler at its default level inlines ctr_take, and with it the shared-node branch (acquire, last-holder free or fade) into the taken match on the static Seg, and the shader comes out five times bigger and wrong. With that branch a real call on the device the reproducer passes 50/50 here, the shader drops from 1011 KB to 304 KB, and the 17 runtime benches keep their checksums and times.

    Two things since (both in the PR):

    • That branch never runs in this program. The static Seg carries no refcount bit, and a counter in the CPU build shows none of the program's 16 ctr_take calls enters it. Deleting it for two-field takes only, which changes nothing the program executes, makes the GPU result right 10/10 on main. So it is the presence of that inlined code, not anything it does, that breaks the compiled shader. That reads as a compiler defect to me, not an ordering we rely on.
    • Your pre-dispatch corruption shows here too. Capturing the entry word at the failing dispatch gives 0x72f3baae7b12e2fa and the like: function id 0xf3ba in a program with 40 functions, the same pattern within a few bits across 6 runs.

    No GPU-family gate in the PR: your update shows that would have been the wrong knob. If you have a moment, a run of that branch on your M1 is the second machine I can't test on. The size-level line is still a fair data point, but the branch is the thing to test.

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

Metadata

Metadata

Assignees

No one assigned

    Labels

    bug

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions