Repository navigation
Description
What Bend should do
# File.read_at and File.read_bytes return a List<U32> with one cell per byte.
# A read straight into an Array<U32>, four little-endian bytes per word:
def File.read_at_u32(file: File, offset: U32, count: U32) ->
IO(File & Result<&1, &1, U32 & String, Array<U32>>)
# A loader of F32 weights then needs one bitcast per element, and no list:
r : File & Result<&1, &1, U32 & String, Array<U32>> <- File.read_at_u32(f, off, n)
# Smaller alternatives, in order of how much they would change:
# - File.read_at with four bytes packed per U32 (a quarter of the cells, same shape)
# - a read-only map of a file into an Array<U32> (like mmap), for programs that only readWhy
Loading a neural network means reading hundreds of megabytes of little-endian F32, and in Bend almost all of that time goes to building and walking the per-byte lists, not to decoding the numbers.
Standalone repro: read a 384 MiB file in 1 MiB blocks with File.read_at and add up the bytes, against the same loop in C with pread. Bend 2.0.37, Core Ultra 7 155H, Linux, one thread pinned to a P-core, five alternated runs each, same sum:
| program | time |
|---|---|
Bend, File.read_at |
1.52-1.57 s |
C, pread |
56-58 ms |
The work per byte is one addition in both; the difference is the list.
In llama.bend, loading SmolLM2-1.7B (6.8 GB of F32) and generating one token takes 66 s at 16 threads, against 4.1 s for transformers and 0.5 s for llama.cpp; loading alone takes as long as ~150 generated tokens. In bend-ml I tried decoding in parallel lets (NOTES, exp. 13): no gain and twice the memory, since the cost is the list the host builds, not the decoding. Dropping a block unread is even slower than walking it. So I can't work around it from user code.
Repro (head -c 402653184 /dev/urandom > w.bin):
import Base
def walk(bs: List<&2, U32>, acc: U32) -> U32:
match bs:
case Nil{}:
acc
case Con{b, t}:
walk(t, (acc + b : U32))
def loop(k: Nat, +off: U32, m: File & Result<&1, &1, U32 & String, List<&2, U32>>, acc: U32) -> IO(U32):
match k m:
case 0n Tuple{f, r}:
do IO<U32>:
File.close(f)
return acc
case 1n+p Tuple{f, r}:
do IO<U32>:
bs : List<&2, U32> <- IO.pass(List<&2, U32>, r)
m2 : File & Result<&1, &1, U32 & String, List<&2, U32>> <- File.read_at(f, (off + 1048576 : U32), 1048576)
loop(p, (off + 1048576 : U32), m2, walk(bs, acc))
def main() -> IO(Unit):
do IO<Unit>:
t0 : Nat <- IO.now()
f : File <- IO.try(File, File.open("w.bin", "r"))
m : File & Result<&1, &1, U32 & String, List<&2, U32>> <- File.read_at(f, 0, 1048576)
s : U32 <- loop(384n, 0, m, 0)
t1 : Nat <- IO.now()
IO.print("sum " ++ U32.show(s) ++ " ms " ++ Nat.show(Nat.sub(t1, t0)))The C twin and the full numbers: bend-ml docs/upstream.
Activity
docs/upstream: the dense file read draft is posted as bendlang/bend#1573
NOTES: the dense file read taken upstream (bendlang/bend#1573), with …
nuxyel commentedon Oct 15, 2026
Before opening a PR I found #1430, which proposed
File.read_intoand was closed with the note that a Base-shaped fix would be a general byte primitive, discussed in an issue first. So this is that issue, and I'd like to settle the shape before writing anything.Base effects take and give
U32,String,List, handles andResult. Within that, the smallest change I see is a read that packs four little-endian bytes perU32: the sameList, a quarter of the cells, andF32weights decode with one bitcast per cell. Would that fit Base, or would you rather have a dedicated byte value that later reads and writes could share? If neither belongs in Base, I'll ship the read as a library effect, as #1430 suggests.nuxyel commentedon Oct 16, 2026
A data point while the shape is open: I took the library route #1430's review suggested.
bend-ml-binary-read(onBendHub,
0.1.0.0) is one effect with a.cand a.jsside,read_f32(file, offset, n, a), which reads F32 wordsstraight into an
Array<F32>, kept out of every package with laws.What it changed, on an idle Core Ultra 7 155H, alternated runs, the same outputs bit for bit:
File.read_at, 1 MB blocksSo the list is most of the cost of loading a model, as the issue says. The library works, with the trade-off the review
named: its C side uses
blk_locandblk_cls, which have no ABI promise, so it has to follow the runtime. That is thepart a Base primitive would remove for everyone who loads binary data.
The question from my last comment is still the one I'd like to settle before writing anything: within the types Base
effects use, would a read that packs four little-endian bytes per
U32(the sameList, a quarter of the cells;F32decoded with one
bitcastper cell) fit, or would you rather have a dedicated byte value? I can prepare either, withtests on both lanes.
docs/upstream: the dense file read draft is posted as bendlang/bend#1573
NOTES: the dense file read taken upstream (bendlang/bend#1573), with …
chenhunghan commentedon Oct 28, 2026
A data point from a different kind of program, on the shape question (packed
List<U32>or a dedicated byte value).bend-vmm is a virtual machine monitor written in Bend 2.0.39: the device models (virtio block, network, 9p, vsock), the NAT and the qcow2 reader are pure Bend proven against laws, over a thin C layer for Hypervisor.framework and KVM. It moves bytes between three places: guest memory, files (disk images) and sockets (the NAT, vsock). Two designs ran on the same device (virtio-vsock, Linux 6.8 guest), on an M2 Pro:
List<U32>through Bend (one cell per byte:io_listfrom a socket read,io_cbufinto a send, guest memory read and written as lists)(address, length)pieces and sizes; C effects copy guest memory to and from socketsThe block device and the NAT were built the second way from the start and run at ~2.8 GB/s (sequential disk reads) and ~650 MB/s (TCP download). In all three, Bend still makes every decision: it parses and builds the headers, does the flow control and credit accounting, and decides which guest memory takes how many bytes. Only the copying is in C.
What this means for the shape:
U32would not be enough here. It cuts the cells by 4×, which moves 7 MB/s to roughly 28 MB/s. The cost we measured is per list cell (allocate, link, walk, convert at the boundary), so it stays two orders of magnitude off amemcpyfor any program that moves bulk data.Bytes.to_list/Bytes.of_list) would keep laws and small header parsing as easy as today. With that, this program would hold a received chunk as a value, slice it to the guest's buffer sizes and hand the slices on, and no byte would be walked in Bend.io_list/io_cbufand parse(address, length)lists by hand; they follow the runtime, not a stable ABI. A Base byte value would remove that for every program that moves bytes, not only for loaders of model weights.I'm happy to test a prototype on both workloads (the vsock path and the NAT) and report the numbers here.
nuxyel commentedon Nov 2, 2026
Thanks for the numbers, @chenhunghan. They answer the question I left open better than model loading could on its own. If the cost is per list cell, packing four bytes per
U32only divides it by four, and my own numbers point the same way: the library read gained by not building a list at all (GPT-2's weights in 0.8 s instead of 4.7 s), not by building a shorter one.So I'd drop the packed
List<U32>and go with a byte value along the lines you describe: reads that return it, writes that take it, its length, O(1) slices, and a list view for small parsing and for laws. Turning those bytes into anArray<U32>for model weights can stay in my package, on top of the byte value, as the note on #1430 suggested for anything that fills one array type.@nicolas-abril, since your note on #1430 asked for the shape to be settled in an issue first: would a byte value like this be welcome in Base, and in what shape? If you'd like a first version from me, I can write one for
File.read_atand its write counterpart, with tests on the C and JS sides; if you'd rather shape it yourselves, I'll measure it on model loading, and @chenhunghan has offered to measure it on his vsock and NAT workloads.duanebester commentedon Nov 9, 2026
A data point from a network protocol, on the same shape question.
Blink is a PostgreSQL driver in pure Bend: the framer, SCRAM and the session are folds proven against laws, and
bend PROOF.bend --verdictpasses. It reads withTCP.recv_bytes. bend-kit-postgres also decodes in Bend, but receives through its own C effect intoArray<U32>Same machine, Postgres 17, one core:
List<U32>Array<U32>So the cost is the list cell per byte here too, as @chenhunghan measured
The library route has one more trade-off for a program like this: a foreign effect fails
--verdict, so Blink can't take it and keep its proofs checked by the kernel. A byte value along the lines above (reads that return it, writes that take it, its length, O(1) slices and a list view for laws) would remove that choiceduanebester commentedon Nov 11, 2026
A concrete shape for the byte value, from a prototype against v2.0.40.
Today a read builds a cell per byte:
With a Data byte value, a read is one block, and slices point into it:
Type.
type Bytes is Data: Bytes{data: List<&2, U32>}in base.bend. The theory sees the list and every op is defined on it, the same way U32 sits on Word and Array on its tree. JS runs those definitions. In C each op is an intrinsic over a refcounted slice. It reuses the existing rfc wrapping, as Chan does, so it needs no new memory machinery.flowchart LR t["<b>Theory</b>: checker, laws, JS<br/>Bytes{data: List<&2, U32>}<br/>ops defined on the list"] r["<b>C runtime</b><br/>[blob, off, len] over a refcounted block<br/>ops are intrinsics"] t <-->|same results| rBeing Data rather than wrapping Array is what makes it shareable: a slice can sit in a list or a constructor field, and many slices can share one read.
Ops. len, get, be16, be32, slice/take/drop in O(1) (in place when the slice is held once), copy (to let go of a large block), concat, eq, utf8, to_list/of_list, and freeze from an Array.
Effects. Each byte API gets a twin that returns or takes Bytes: TCP.recv_buf/try_recv_buf (in the prototype), send_buf, the UDP pair, and File.read_buf/read_buf_at/write_buf/write_buf_at. The C side is the existing effect with io_list swapped for a block. Args and paths can stay lists.
Laws. Since the theory is the list, they prove with ordinary list lemmas, and
--verdictpasses:to_list(of_list(xs)) == xsto_list(slice(b, o, n)) == take(n, drop(o, to_list(b)))to_list(concat(a, b)) == List.append(to_list(a), to_list(b))Costs. Each slice is a small alloc plus an atomic increment. The native ops are trusted like U32's, with differential tests against the Bend definitions as the evidence. There's no device path, and JS is slow because it runs the lists.
Bytes{xs}with a value over 255 stops at runtime, while of_list masks.For scale, parsing 100k Postgres rows with one 100-character text column and keeping each field as a slice:
Memory went from 244 MB to 30 MB.
The patch is here, against v2.0.40: https://github.com/duanebester/blink/blob/proto-shared-bytes/proto/bend-shared-bytes.patch.
Happy to open a draft PR if the shape or approach looks right.
nuxyel commentedon Nov 17, 2026
Thanks, @duanebester. That's the shape I had in mind when I dropped the packed list above: reads that return the bytes as one block, O(1) slices, and a list underneath so the laws still pass
--verdict. With your numbers it's three programs where the list cell per byte is the cost: @chenhunghan's VMM, your driver (0.73 s to 0.08 s, 244 MB to 30 MB) and model loading here (4.7 s against 0.8 s for GPT-2's weights with a read that builds no list).I read the patch with model weights in mind, and that case needs two things it doesn't have yet. Neither changes the type.
TCP.recv_bufandTCP.try_recv_buf;File.read_buf_atis in your list but not in the prototype. Weights come from a file, at an offset.Bytesto words without a call per byte.Bytes.freezegoes from anArray<U32>toBytes, and loading needs the other direction: four little-endian bytes to a word, over a whole slice.be32reads big-endian, and weight files (safetensors, GGUF) are little-endian. Ale32would already let my package fill anArray<U32>with one call per word and no list cell; a native "the words of this slice" would make it one copy.If you add the file read, I'll measure it on GPT-2's and SmolLM2's weights against the foreign read that
bend-ml-binary-readdoes today, and post the numbers here.A practical note for a draft PR: the patch adds about 220 lines to
comp.ts, and that file sits at its token cap on main (other open PRs are already over it), so the natives may need a smaller form, or a word from the maintainers on the cap.@nicolas-abril, the question from my comment above is still the open one: would Base take a byte value like this? There's now a prototype against 2.0.40 and three programs that would use it.
Prototype: smaller Bend patch, file twins, le32 and words (bendlang/b…
duanebester commentedon Nov 17, 2026
Thanks @nuxyel. Both are in the patch now:
File.read_buf,read_buf_at,write_bufandwrite_buf_at, on C and JS, matchingread_bytes/read_at/write_bytes/write_at(including EINVAL for a positioned write on an append handle).Bytes.le16/le32, andBytes.words(b, d) -> Array<U32>: 2^d words, word k isle32(b, 4k), filled in one pass. A length that isn't a multiple of 4 ends in a word padded with zero bytes. Laws for both over the list view, and--verdictpasses.On a 64 MB file,
read_atinto a list takes 1.28 s and 1.5 GB;read_buf_atthenwordstakes 0.14 s and 133 MB. Looking forward to your numbers on GPT-2 and SmolLM2.On comp.ts: the runtime side moved to
effs/bytes.c, and every native goes through onebytes_opcall, so comp.ts grows by 25 lines and 330 tokens (from about 220 lines and 2,447 tokens). On main that's still 311 over the 66,000 cap, which has 19 tokens to spare. So it needs either about 310 tokens of simplification elsewhere in comp.ts or a word on the cap. Whether new runtime C can live ineffs/is also a question for the maintainers.One more for @nicolas-abril:
tests/base/bytes_ops.bendsays a Bytes value "is an Array of U32 by ruling", with no Bytes namespace in Base. This proposal would change that, so I'd like to know if the ruling still stands.Patch against main: https://github.com/duanebester/blink/blob/proto-shared-bytes/proto/bend-shared-bytes-main.patch
nuxyel commentedon Nov 25, 2026
Here are the numbers I promised, @duanebester. I built main (6180be5) with your
bend-shared-bytes-main.patch; it applied cleanly andtests/io/file_buf.bendpasses. Each program reads every file whole into an array of 2^d words and checksums all of them. GPT-2 small is 148 F32 files (498 MB) and SmolLM2-135M is onemodel.safetensors(269 MB). The baseline isbend-ml-binary-read's foreignread_f32_at, which reads straight into the array. One thread, idle machine, medians of 5. The three versions give the same checksum in every run.read_buf_at+wordsmemcpyinbytes_wordsread_buf_at+wordsmemcpySo it works with no foreign code in the program, the bits are right, and it's already far from the list read (4.7 s against 0.8 s on GPT-2 in my comment of 11-02). Against the foreign read it costs 3.3-3.6x the time and 6.6-7.4x the instructions.
Most of that is
bytes_words: a profile puts half the user cycles inbytes_op, which builds each word from four bytes with a bounds check and writes it withblk_write. A BUF block is flatu32cells, so on a little-endian host the whole words are one copy. With this ineffs/bytes.cthe instructions match the foreign read's:What's left, 1.6-1.8x the foreign read's time, is the second copy: the file goes into the
Bytesblock and then into the array, and both are alive at the peak (+185 MB on GPT-2, +258 MB on SmolLM2). A read that writes into an existingArray<U32>would close that, but it's a different op from what you have, so I'm only noting it.One case it doesn't cover yet: SmolLM2's real weights are BF16, and my loader widens each number to F32 as it reads. With
wordsthat's a pass in Bend over the words afterwards. I haven't measured that pass.Prototype: Bytes.words is one memcpy on little-endian hosts (bendlang…
duanebester commentedon Nov 25, 2026
Thanks @nuxyel! I added your
memcpychange to both patches now (v2.0.40 and main), with the old loop kept for big-endian hosts.On a 4 MB slice at an odd offset,
wordswent from about 1.3 ms to 0.3 ms a call, and a new test checks the words of an offset, odd-length slice against Python's struct. comp.ts is unchanged, since it's all ineffs/bytes.c.The other natives were already a single copy (reads, copy, concat, writes) or a
memcmp(eq); freeze narrows each cell to a byte, so it stays a loop.Agree that a read into an existing
Array<U32>would remove the second copy. I left it out to keep this to one new value.Prototype: File.read_words_at, a read into an existing Array (bendlan…