Repository navigation
Description
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
luiscleto commentedon Oct 27, 2026
Another use case, with numbers: a VCF normalizer whose implementation is proven against laws, processing text packed four bytes per
U32in anArray<U32>(GIAB HG002 whole genome, 2.84 GB, 32 threads):ANodeArray.fork, each task reading its own byte range--verdictrejects theArray.forkversion, so the proven version will have the driver read each piece of the file into its own block instead. A read-only view offering onlygetand size, as proposed here, would cover our case completely.jkbennitt commentedon Nov 10, 2026
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?
nuxyel commentedon Nov 11, 2026
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
ANodethat 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.appendrecurses 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.cloneper task may already be cheap enough. I haven't measured that on your program, though. And if you don't need--verdict,Array.forkshares an array in O(1) today, at the price of@unsafe.jkbennitt commentedon Nov 11, 2026
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.
nuxyel commentedon Nov 17, 2026
Thanks for measuring both, @jkbennitt, and for keeping the bench in the repository. I read
assoc_array.bendand ran it here, and the time is in the shape of the walk, not inArray.get.Every read there is wrapped in a closure and two pairs.
sqnorm_slicehands(d => sqnorm_slice(k, d, ...))to.got, which opens the pairArray.getreturned and calls the closure, and.addbuilds the next pair on the way back, so no call is a tail call.dot_sliceandresid_slicehave the same shape, andnearest_go_arrgoes 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 printedmatch_list=1and yoursum_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):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_msmoved 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.addtonearest_arr:jkbennitt commentedon Nov 17, 2026
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 printedmatch_list=1and the samesum_idx.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.
nuxyel commentedon Nov 17, 2026
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_cloneruns its two halves in a parallel let,lo hi = rec_lo(d1) rec_hi(d2).map_fork.after_forkpasses 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: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):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.
jkbennitt commentedon Nov 19, 2026
Thanks @nuxyel, that was it. I put the two calls in
map_fork.after_forkinto 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 printedmatch_list=1and the samesum_idx.CPU, chunk 32, 1 thread / default threads (10 cores):
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:
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 8GBit 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.