Skip to content

A read-only borrow of an Array for a parallel let, without @unsafe #1376

Open

Description

@nuxyel

What Bend should do

# A read-only view of an Array that many tasks can read at once, checked by the
# type system, so a library that publishes laws can share a weight matrix
# across a parallel let without copying it and without @unsafe.
#
# For example (the name and shape are only a suggestion):
#
#   Array.borrow(a: Array<T>, f: ReadOnly<T> -> R) -> Array<T> & R
#
# where ReadOnly<T> is Data (so it can go down both sides of a parallel let
# with +) and only offers get and size. No write can reach the shared block.
 
# rows i0 .. i0+n-1 of W · x, reading W through the view
def rows(+w: ReadOnly<F32>, +x: ReadOnly<F32>, +k: U32, i0: U32, n: Nat) -> List<&2, F32>:
  ...
 
def halves(+w: ReadOnly<F32>, +x: ReadOnly<F32>, +k: U32, +i0: U32, +n: Nat) -> List<&2, F32>:
  # both halves read the same W, nothing is copied
  a b = rows(w, x, k, i0, Nat.div(n, 2n)) rows(w, x, k, (i0 + U32.from_nat(Nat.div(n, 2n)) : U32), Nat.sub(n, Nat.div(n, 2n)))
  List.append(&2, F32, a, b)

Why

In matrix · vector (the inner loop of LLM inference) every weight is read once. To run it on several cores each task must read part of the weight matrix, and today a library that proves laws has no good way to do it:

way cost problem
Array.clone per task O(n) per task per call costs more than the products: 2304 × 768 with 8 tasks takes 10.4 ms, the sequential product 0.80 ms
Array.fork / Array.join (#885) O(1) @unsafe: --check-only and --verdict report SOME PROOFS FAIL: 1 def relies on unsafe or foreign code
split the matrix into one array per task, once one copy at load time works and is proved, but the split is fixed when the matrix is loaded

The guide's Ownership section (guide/SHADERS.md) says "The compiler borrows a boxed parameter (not an Array) that the def only matches or passes to a borrower": arrays are the one kind of data a library cannot share read-only between tasks without copying or @unsafe.

What we do today in bend-ml is the third row (Bands<r, c>, a tree of row bands, each its own Array). Time per product, 16 threads, Bend 2.0.35, Intel Core Ultra 7 155H:

W sequential clone per task (8) 16 bands
2304 × 768 0.80 ms 10.4 ms 0.32 ms
3072 × 768 1.07 ms 23.5 ms 0.42 ms
50257 × 768 25.1 ms 337 ms 6.1 ms

A read-only borrow would give the same speed without fixing the split at load time, and would let operations that need the whole matrix (an embedding lookup, a transposed product for training) read it directly. It matches two items of the roadmap (2026-09-29): "way better support for shared atomic arrays" and "more parallelism options (not just fork/join)".

Benchmark and numbers: bench/mv_bands.py, full table, NOTES.md (experiments 9 and 11).

Activity

  1. added
    enhancement
    on Oct 7, 2026
  2. luiscleto commented on Oct 27, 2026

    @luiscleto

    Another use case, with numbers: a VCF normalizer whose implementation is proven against laws, processing text packed four bytes per U32 in an Array<U32> (GIAB HG002 whole genome, 2.84 GB, 32 threads):

    way to give 32 tasks the input cost
    split by matching ANode 0.90 s (2 parts) to 5.77 s (32 parts) for the splits alone; slower with more threads (page faults on the copies)
    Array.fork, each task reading its own byte range the whole judging pass takes 0.31 s (2.94 s on 1 thread); the aliasing costs 0-10% in single-thread loops

    --verdict rejects the Array.fork version, so the proven version will have the driver read each piece of the file into its own block instead. A read-only view offering only get and size, as proposed here, would cover our case completely.

  3. jkbennitt commented on Nov 10, 2026

    @jkbennitt
    Contributor

    A use-case data point from a nearest-reference argmin: each of N points walks R refs and keeps the closest index. It came up while benchmarking a U-NSGA-III implementation in Bend.

    Points and refs are cons lists, mid-split and walked recursively (the guide: an Array cannot ride a fork tree). End-to-end on an M4, Metal 4, Bend 2.0.40, versus a separate flat-array Metal kernel (one thread per point; different implementation):

    The small size is dispatch-bound (most of that 0.365 ms is launch). A sequential host-side Array packing of the refs did not help; I never shared an Array down the map.

    Would a read-only Array borrow, as proposed here, cover this — shared refs, and one leaf or flat loop per point?

  4. nuxyel commented on Nov 11, 2026

    @nuxyel
    ContributorAuthor

    Thanks for the use case, @jkbennitt. I can't speak for the maintainers, but here's how I read it against what this issue asks for.

    The refs are the part a borrow would cover. Every point reads all of them and nothing writes them, which is the shape this issue is about: one array that every task of a parallel let reads in full. With a borrow, the refs could be one Array<F32> passed down the whole map, with no copy and no @unsafe.

    The points are a different question. Giving each leaf its own part of one array is what #1991 and #2019 are about (a match on ANode that views the block instead of copying it), and #2019 is still a draft that only views on the host.

    The Metal fault wouldn't go away with either one. That's #1393: List.append recurses once per element of its first list, and at N = 2046 the first half has 1023 elements, which is where the lane stack runs out. #1819 is the open PR for that.

    One thing that might help before any of this lands. In my case copying cost more than the work (10.4 ms of clones against a 0.80 ms product), because each task reads a big matrix once. In yours every point already walks all 276 refs, so a copy of the refs once per task, not once per point, costs about as much as one point's work. If each task handles many points, Array.clone per task may already be cheap enough. I haven't measured that on your program, though. And if you don't need --verdict, Array.fork shares an array in O(1) today, at the price of @unsafe.

  5. jkbennitt commented on Nov 11, 2026

    @jkbennitt
    Contributor

    Thanks, @nuxyel — I measured both ideas on the nearest-ref argmin (refs as one Array, each leaf walking a chunk of points). Indices matched the cons-list map on every completed run.

    Same M4, Bend 2.0.40, CPU +RTS --threads 1, median of several process runs (ms/rep):

    184×91: list 0.388; clone c=1/32/128: 2.44/2.05/1.69; fork ~3.29 any chunk.
    2048×276: list 13.3; clone 71.9/55.9/61.2; fork ~112.
    32000×3003: list 2047; clone 13957/9481/9425; fork ~19600.

    Larger chunks did make Array.clone cheaper than once-per-point, as you expected, but the array-backed walk stayed slower than the cons-list map. Array.fork (@unsafe) was slower still and almost unchanged with chunk size — I think Array.get on the refs dominates the copy.

    Metal at 184×91 ran (list 6.0 ms/rep; clone/fork slower, worse with bigger chunks). At 2048×276 every ! variant still hit the #1393 stack overflow, chunked or not.

  6. nuxyel commented on Nov 17, 2026

    @nuxyel
    ContributorAuthor

    Thanks for measuring both, @jkbennitt, and for keeping the bench in the repository. I read assoc_array.bend and ran it here, and the time is in the shape of the walk, not in Array.get.

    Every read there is wrapped in a closure and two pairs. sqnorm_slice hands (d => sqnorm_slice(k, d, ...)) to .got, which opens the pair Array.get returned and calls the closure, and .add builds the next pair on the way back, so no call is a tail call. dot_slice and resid_slice have the same shape, and nearest_go_arr goes through a closure once more per reference. On a probe that only sums the squares of 3 cells, that shape costs 499 instructions a walk and a tail loop costs 20.

    So I rewrote those four as tail loops in a copy of your file at 31812fc and left the rest as it is: the clone and fork maps, seq_pts, the harness. Each loop takes the pair of the read it is about to use as its last parameter and passes the array straight into the next read. To keep your sums bit for bit, x0*y0 + (x1*y1 + (x2*y2 + 0.0)), they walk from the last cell down, with the point reversed once per point. Every run printed match_list=1 and your sum_idx (8819 and 279827).

    User instructions per rep, in millions (Bend 2.0.40, clang 23.1.3, a Core Ultra 7 155H, one thread, perf stat, the difference between two rep counts):

    N x R x M cons lists clone, as merged fork, as merged clone, tail loops fork, tail loops
    184 x 91 x 3, chunk 128 10.6 48.7 83.2 6.2 6.2
    2048 x 276 x 3, chunk 32 337 1,685 2,805 212 202

    As merged, the array maps take 4.6 to 8.3 times the lists' instructions; with the tail loops they take about 0.6 of them. My machine wasn't idle, so I leave the times out (the program's own total_ms moved the same way), and I have no Mac to run Metal. The fault at 2048 x 276 hits the list variant too, so it isn't in these walks; that one is #1393.

    These replace everything from dot_slice.add to nearest_arr:

    def sqr(+y: F32) -> F32:
      F32.mul(y, y)
    
    # The three walks as tail loops. Each takes the pair of the read it is about to use as its last parameter and passes
    # the array on to the next read, so no closure and no pair is built per cell. They walk from the last cell down and
    # add into `acc`, which gives the sums the cons-list version nests: x0*y0 + (x1*y1 + (x2*y2 + 0.0)).
    # `fr` is the point reversed (done once per point in nearest_arr); `i` is the index of the cell in hand.
    def sqnorm_tail(left: Nat, +i: U32, +acc: F32, r: Array<F32> & F32) -> Array<F32> & F32:
      match left r:
        case 0n Tuple{a, +y}:
          (a, F32.add(F32.mul(y, y), acc))
        case 1n+k Tuple{a, +y}:
          +j = (i - 1 : U32)
          sqnorm_tail(k, j, F32.add(F32.mul(y, y), acc), Array.get(F32, a, j))
    
    def dot_tail(fr: List<&2, F32>, +i: U32, +acc: F32, r: Array<F32> & F32) -> Array<F32> & F32:
      match fr r:
        case Nil{} Tuple{a, y}:
          (a, acc)
        case x <> Nil{} Tuple{a, y}:
          (a, F32.add(F32.mul(x, y), acc))
        case x <> xs Tuple{a, y}:
          +j = (i - 1 : U32)
          dot_tail(xs, j, F32.add(F32.mul(x, y), acc), Array.get(F32, a, j))
    
    def resid_tail(+t: F32, fr: List<&2, F32>, +i: U32, +acc: F32, r: Array<F32> & F32) -> Array<F32> & F32:
      match fr r:
        case Nil{} Tuple{a, y}:
          (a, acc)
        case x <> Nil{} Tuple{a, y}:
          (a, F32.add(sqr(F32.sub(x, F32.mul(t, y))), acc))
        case x <> xs Tuple{a, y}:
          +j = (i - 1 : U32)
          resid_tail(t, xs, j, F32.add(sqr(F32.sub(x, F32.mul(t, y))), acc), Array.get(F32, a, j))
    
    def perp_arr.fin(pair: Array<F32> & F32) -> Array<F32> & F32:
      (dirs2, rs) = pair
      (dirs2, F32.sqrt(rs))
    
    def perp_arr.after_dot(+fr: List<&2, F32>, +last: U32, +ww: F32, pair: Array<F32> & F32) -> Array<F32> & F32:
      (dirs1, fw) = pair
      +t = F32.div(fw, ww)
      perp_arr.fin(resid_tail(t, fr, last, 0.0, Array.get(F32, dirs1, last)))
    
    def perp_arr.pick(+f: List<&2, F32>, +fr: List<&2, F32>, dirs: Array<F32>, +last: U32, +ww: F32, tiny: Bool) -> Array<F32> & F32:
      match tiny:
        case True{}:
          (dirs, F32.sqrt(Util.vec_sqnorm(f)))
        case False{}:
          perp_arr.after_dot(fr, last, ww, dot_tail(fr, last, 0.0, Array.get(F32, dirs, last)))
    
    def perp_arr.after_ww(+f: List<&2, F32>, +fr: List<&2, F32>, +last: U32, pair: Array<F32> & F32) -> Array<F32> & F32:
      (dirs1, +ww) = pair
      perp_arr.pick(f, fr, dirs1, last, ww, F32.is_lt(ww, 0.0000000000000001))
    
    # the distance from the point to the reference whose m cells end at index `last` (m = 1 + k)
    def perp_arr(+f: List<&2, F32>, +fr: List<&2, F32>, dirs: Array<F32>, +last: U32, +k: Nat) -> Array<F32> & F32:
      perp_arr.after_ww(f, fr, last, sqnorm_tail(k, last, 0.0, Array.get(F32, dirs, last)))
    
    # `r` is the distance to reference i, already computed; the next one is computed in the call's last argument
    def nearest_tail(remaining: Nat, +f: List<&2, F32>, +fr: List<&2, F32>, +k: Nat, +mu: U32, +last: U32, +i: Nat, +best_i: Nat, +best_d: F32, r: Array<F32> & F32) -> Array<F32> & Nat:
      match remaining r:
        case 0n Tuple{a, +d}:
          (a, Bool.pick(Nat, F32.is_lt(d, best_d), i, best_i))
        case 1n+rest Tuple{a, +d}:
          +lt = F32.is_lt(d, best_d)
          +last2 = (last + mu : U32)
          nearest_tail(rest, f, fr, k, mu, last2, Nat.add(i, 1n), Bool.pick(Nat, lt, i, best_i), Bool.pick(F32, lt, d, best_d), perp_arr(f, fr, a, last2, k))
    
    def nearest_arr.go(+f: List<&2, F32>, +fr: List<&2, F32>, dirs: Array<F32>, +m: Nat, +r: Nat) -> Array<F32> & Nat:
      match m r:
        case 0n 0n:
          (dirs, 0n)
        case 0n 1n+rest:
          (dirs, 0n)
        case 1n+k 0n:
          (dirs, 0n)
        case 1n+k 1n+rest:
          +last = U32.from_nat(k)
          nearest_tail(rest, f, fr, k, U32.from_nat(1n+k), last, 0n, 0n, 1000000000.0, perp_arr(f, fr, dirs, last, k))
    
    def nearest_arr(+f: List<&2, F32>, dirs: Array<F32>, +m: Nat, +r: Nat) -> Array<F32> & Nat:
      nearest_arr.go(f, List.reverse(&2, F32, f), dirs, m, r)
  7. jkbennitt commented on Nov 17, 2026

    @jkbennitt
    Contributor

    Thank you @nuxyel, this was really helpful. I dropped your four loops into a copy at 31812fc and timed it on an M4 Mac mini (Bend 2.0.40, +RTS --threads 1, median of 5 runs, ms/rep). Every run printed match_list=1 and the same sum_idx.

    N x R x M lists clone c=128, merged → tail fork c=128, merged → tail
    184 x 91 0.39 1.85 → 0.14 3.41 → 0.15
    2048 x 276 12.5 62.1 → 4.3 113.7 → 4.5
    32000 x 3003 2030 ~9400 → 687 ~19600 → 724

    So you were right that it was the walks. With default threads at 32000, clone took 132 ms against 357 for lists, and fork stayed around 725.

    On Metal at 184 x 91, lists took 5.7 ms, clone c=1 10.4 (was 47) and fork about 57–66 (was about 1150). At 2048 x 276 everything still faulted until I used wakamex's two-loop append from #1393. After that, lists took 34.6 ms, clone c=1 50.2 and fork about 1.9 s.

  8. nuxyel commented on Nov 17, 2026

    @nuxyel
    ContributorAuthor

    Thanks for running it on the M4, and at 32000 x 3003, which I hadn't.

    The fork map staying at 725 ms with default threads is the bench again, not Array.fork. map_clone.after_clone runs its two halves in a parallel let, lo hi = rec_lo(d1) rec_hi(d2). map_fork.after_fork passes them as two arguments, map_fork.join(rec_lo(d1), rec_hi(d2)), and those run one after the other. With the same let there:

    def map_fork.after_fork(rec_lo: Array<F32> -> (List<&2, Nat> & Array<F32>), rec_hi: Array<F32> -> (List<&2, Nat> & Array<F32>), pair: Array<F32> & Array<F32>) -> List<&2, Nat> & Array<F32>:
      (d1, d2) = pair
      lo hi = rec_lo(d1) rec_hi(d2)
      map_fork.join(lo, hi)

    the fork map scales like the clone one here. At 2048 x 276, chunk 32, with the tail loops, ms per rep on 1 and on 16 threads (Bend 2.0.40, a Core Ultra 7 155H, median of 5 runs, same sum_idx, match_list=1):

    1 thread 16 threads
    lists 23.5 3.1
    clone 7.9 1.7
    fork, as merged 7.2 7.2
    fork, with the let 7.2 1.5

    My machine was in use, so take the times as direction. I'd expect the same let to account for your 725 ms at 32000; whether it also explains fork on Metal I can't tell without a Mac.

  9. jkbennitt commented on Nov 19, 2026

    @jkbennitt
    Contributor

    Thanks @nuxyel, that was it. I put the two calls in map_fork.after_fork into the same let, exactly as you wrote it, and reran on the M4 Mac mini (Bend 2.0.40, median of 5 runs, ms/rep). Every run printed match_list=1 and the same sum_idx.

    CPU, chunk 32, 1 thread / default threads (10 cores):

    N x R lists clone fork, as merged fork, with the let
    2048 x 276 12.5 / 2.7 4.8 / 1.3 4.6 / 5.0 4.7 / 1.3
    32000 x 3003 2079 / 364 806 / 153 727 / 729 732 / 136

    So the 725 ms was the bench, as you said. Chunk 128 looked the same.

    The let fixed fork on Metal too. With wakamex's two-loop append from #1393, chunk 1:

    N x R lists clone fork, as merged fork, with the let
    184 x 91 5.75 10.6 68.0 4.5
    2048 x 276 34.2 50.2 1969 32.5
    32000 x 3003 650 out of memory ~304,000 (one rep) 549

    At 32000 the Metal numbers are a median of 3 runs. Clone ran out of GPU memory there with the default span. With +RTS --gpu 8GB it finished at 1791, with lists at 705 and fork with the let at 568 under the same flag. Bigger chunks were still slower on Metal for both clone and fork; fork with the let took 76 ms at chunk 32 and 204 at chunk 128 for 2048 x 276.

    Thanks again for taking the time to dig into this.

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

    enhancement

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions