Skip to content

A file read into an Array<U32>, so loading model weights is not one list cell per byte #1573

Open

Description

@nuxyel

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 read

Why

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

  1. added
    enhancement
    on Oct 15, 2026
  2. nuxyel commented on Oct 15, 2026

    @nuxyel
    ContributorAuthor

    Before opening a PR I found #1430, which proposed File.read_into and 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 and Result. Within that, the smallest change I see is a read that packs four little-endian bytes per U32: the same List, a quarter of the cells, and F32 weights 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.

  3. nuxyel commented on Oct 16, 2026

    @nuxyel
    ContributorAuthor

    A data point while the shape is open: I took the library route #1430's review suggested. bend-ml-binary-read (on
    BendHub, 0.1.0.0) is one effect with a .c and a .js side, read_f32(file, offset, n, a), which reads F32 words
    straight 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 blocks the library effect
    GPT-2 small weights loaded, 1 thread 4.7 s 0.8 s
    SmolLM2-1.7B, load and one token, 16 threads 72.2 s 9.1 s

    So 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_loc and blk_cls, which have no ABI promise, so it has to follow the runtime. That is the
    part 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 same List, a quarter of the cells; F32
    decoded with one bitcast per cell) fit, or would you rather have a dedicated byte value? I can prepare either, with
    tests on both lanes.

  4. chenhunghan commented on Oct 28, 2026

    @chenhunghan

    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:

    guest to host host to guest
    payload as List<U32> through Bend (one cell per byte: io_list from a socket read, io_cbuf into a send, guest memory read and written as lists) ~27 MB/s ~7 MB/s
    payload never in Bend: Bend handles only (address, length) pieces and sizes; C effects copy guest memory to and from sockets ~1500 MB/s ~100 MB/s (bound by the guest's 3.7 KiB rx buffers; the VMM is mostly idle)

    The 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:

    • Packing four bytes per U32 would 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 a memcpy for any program that moves bulk data.
    • What would let this program drop its C byte-moving layer is a dedicated byte value that effects pass through without converting. Concretely: a socket or file read returns one, a send or write takes one, and Bend code can take its length, slice it in O(1) (for headers versus payload), and concatenate it. A list view (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.
    • Our workaround has the same trade-off the library route in this thread names. Our C effects use the runtime's io_list / io_cbuf and 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.

  5. nuxyel commented on Nov 2, 2026

    @nuxyel
    ContributorAuthor

    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 U32 only 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 an Array<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_at and 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.

  6. duanebester commented on Nov 9, 2026

    @duanebester

    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 --verdict passes. It reads with TCP.recv_bytes. bend-kit-postgres also decodes in Bend, but receives through its own C effect into Array<U32>

    Same machine, Postgres 17, one core:

    Blink, List<U32> bend-kit, Array<U32>
    100k rows, one 100-char text column 0.40 s, 249 MB 0.04 s, 24 MB
    1M rows, three columns 2.1 s, 685 MB 0.32 s, 170 MB

    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 choice

  7. duanebester commented on Nov 11, 2026

    @duanebester

    A concrete shape for the byte value, from a prototype against v2.0.40.

    Today a read builds a cell per byte:

    flowchart LR
      k["recv() buffer"] -->|io_list| c1["68"] --> c2["0"] --> c3["0"] --> c4["0"] --> c5["…"] --> n["Nil"]
    
    Loading

    With a Data byte value, a read is one block, and slices point into it:

    flowchart LR
      k["recv() buffer"] -->|one copy| b["packed block, refcounted"]
      s1["Bytes [blob, 0, 5]"] -.-> b
      s2["Bytes [blob, 5, 100]"] -.-> b
      s3["Bytes [blob, 105, 3]"] -.-> b
    
    Loading

    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&lt;&amp;2, U32&gt;}<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| r
    
    Loading

    Being 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 --verdict passes:

    • to_list(of_list(xs)) == xs
    • to_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:

    xychart-beta
      title "100k rows, one 100-char text column"
      x-axis ["recv_bytes (List)", "shared Bytes"]
      y-axis "seconds" 0 --> 0.8
      bar [0.73, 0.08]
    
    Loading

    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.

  8. nuxyel commented on Nov 17, 2026

    @nuxyel
    ContributorAuthor

    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.

    • A file twin. The patch has TCP.recv_buf and TCP.try_recv_buf; File.read_buf_at is in your list but not in the prototype. Weights come from a file, at an offset.
    • A way from Bytes to words without a call per byte. Bytes.freeze goes from an Array<U32> to Bytes, and loading needs the other direction: four little-endian bytes to a word, over a whole slice. be32 reads big-endian, and weight files (safetensors, GGUF) are little-endian. A le32 would already let my package fill an Array<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-read does 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.

  9. duanebester commented on Nov 17, 2026

    @duanebester

    Thanks @nuxyel. Both are in the patch now:

    • File.read_buf, read_buf_at, write_buf and write_buf_at, on C and JS, matching read_bytes/read_at/write_bytes/write_at (including EINVAL for a positioned write on an append handle).
    • Bytes.le16/le32, and Bytes.words(b, d) -> Array<U32>: 2^d words, word k is le32(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 --verdict passes.

    On a 64 MB file, read_at into a list takes 1.28 s and 1.5 GB; read_buf_at then words takes 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 one bytes_op call, 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 in effs/ is also a question for the maintainers.

    One more for @nicolas-abril: tests/base/bytes_ops.bend says 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

  10. nuxyel commented on Nov 25, 2026

    @nuxyel
    ContributorAuthor

    Here are the numbers I promised, @duanebester. I built main (6180be5) with your bend-shared-bytes-main.patch; it applied cleanly and tests/io/file_buf.bend passes. 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 one model.safetensors (269 MB). The baseline is bend-ml-binary-read's foreign read_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 time instructions peak RSS
    GPT-2, binary-read 107 ms 1.03 G 293 MB
    GPT-2, read_buf_at + words 381 ms 6.81 G 478 MB
    GPT-2, the same with a memcpy in bytes_words 188 ms 1.04 G 478 MB
    SmolLM2-135M, binary-read 87 ms 0.57 G 520 MB
    SmolLM2-135M, read_buf_at + words 283 ms 4.19 G 778 MB
    SmolLM2-135M, the same with a memcpy 141 ms 0.60 G 778 MB

    So 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 in bytes_op, which builds each word from four bytes with a bounds check and writes it with blk_write. A BUF block is flat u32 cells, so on a little-endian host the whole words are one copy. With this in effs/bytes.c the instructions match the foreign read's:

      BLK_ALLOC(l, blk_wcls(false, (u32)d))
    #if defined(__BYTE_ORDER__) && __BYTE_ORDER__ == __ORDER_LITTLE_ENDIAN__
      u8* dst = (u8*)blk_ptr(e.mem, l, 0);
      u64 cap = 4ull << d;
      u64 m = n < cap ? n : cap;
      memcpy(dst, p, m);
      memset(dst + m, 0, cap - m);
    #else
      for (u64 i = 0; i < (1ull << d); i += 1) {
        blk_write(e.mem, false, l, (u32)i, bytes_word(p, n, 4 * i, 4, true));
      }
    #endif

    What's left, 1.6-1.8x the foreign read's time, is the second copy: the file goes into the Bytes block 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 existing Array<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 words that's a pass in Bend over the words afterwards. I haven't measured that pass.

  11. duanebester commented on Nov 25, 2026

    @duanebester

    Thanks @nuxyel! I added your memcpy change 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, words went 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 in effs/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.

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