Skip to content

A heap node's U32 and tag fields share a word when that drops its size class (rbtree ports -9% to -31% cycles) - #2218

Closed
nicolas-abril wants to merge 4 commits into
bendlang:mainfrom
nicolas-abril:opt/packed-node-fields
Closed

nicolas-abril wants to merge 4 commits into
bendlang:mainfrom
nicolas-abril:opt/packed-node-fields

Conversation

@nicolas-abril

Copy link
Copy Markdown
Collaborator

comp.ts is 66,856 ttok, 856 over the 66,000 cap (main 65,995, +861), so repo-gate fails until that is settled; every other repo check passes locally (55 / 56). Measured on one Mac (M4) under load from other sessions, not on the cluster: the test and perf gates have not been run.

What it does

A heap node keeps each field in its own 64-bit word, so a Bool or an enumeration tag takes a whole word, and the node's block is the next power of two. The Perceus rbtree's

type Tree is Data:
  Leaf{}
  Node{color: Color, lchild: Tree, key: U32, value: Bool, rchild: Tree}

is 5 words in an 8-word block, 3 of them for 34 bits. This PR lays color, key and value in one word, key | color << 32 | value << 33, so Node is 3 words in a 4-word block. The program cannot tell: the layout is per constructor and every build and read goes through the same two functions.

  • node_pack(k) (lay_bits gives each word's bits: a tag's ceil(log2 arms), 32 for a w32, 64 for a box or w64): the w32 and tag words are packed first-fit, widest first, into words of at most 56 bits (so at most one U32 per word), the shared words first, then the boxes in order. It is used only when that lowers the node's size class.
  • ctr_build writes each shared word as (u64)((u32)(x) & mask) << shift | ... (the static image too); node_fields reads a field back as (u32)(w >> shift) & mask; c_header gives the runtime the new arity and spine.
  • Not for Base's runtime types (OWNED), nor for a type that foreign C names (CID(..) in an effect source) or takes (in a foreign def's signature), nor anything those hold (ty_fix): such C writes the words itself.

The condition, and why it suffices

The layout is a function of the constructor alone, the same in every def, closure, fork task, ! call and polymorphic caller of one binary, so a node built anywhere is read correctly everywhere. Where a node's words are observed:

  • Emitted code (host and device, one source): only ctr_build writes them and only node_fields reads them (fresh, shared through ctr_take, or peeked through a lent root), and both use node_pack. A generic field is a box (64 bits) and is never packed, so instances agree.
  • The runtime's generic walks (term_drop, span_fade under ctr_take, rfc_seal): they read each word as a term. A shared word is below 2^56 (masks on write keep it there even if a tag were out of range), so its tag byte is 0 and its RFC bit clear: a trivial term, skipped like any U32 field today. CID_T carries the new arity (the block's class) and the spine at its new slot.
  • Foreign and IO C: excluded types keep their layout. The runtime itself names only constructors of Base's runtime types (OWNED) and List's Con and Nil, whose fields are boxes.
  • The JS lane and the interpreter: untouched; the JS of all 985 test and demo programs that emit JS is byte-identical.
  • The value: a tag word is its constructor's index (built by emit_ctr, val_arms, emit_zero or a comparison), below 2^bits; a w32 is a u32.

Reach, counted before building

A hook over the checked terms (Base, the tests, the demos, the 17 benches, the 22 koru kernels and their 17 forked ports, the 7 Perceus ports; 862 files that check) and a run-time count of every node built, per constructor, in the 63 runnable programs. Branch bench/representation (nicolas-abril/bend) has both, the scripts, the other candidates and their counts, and every measurement below.

count
heap-node constructors 838
... with a tag word 20
... where sharing a word lowers the size class (this PR) 5: the 4 rbtree ports' Node, tests/reg/show_shared_layout's Other (25 words to 1)
... where it would not (left alone) 15
records (non-recursive) that are boxed into nodes at run time at most 10 boxes per run anywhere

On a hot path: only the rbtree ports, 340M to 504M Nodes per run. No bench or kernel builds a node this changes: their hot nodes are boxes only (tree-bitonic's Node, 4.26G per run; tree-radix, tree-matmul), a word and boxes (merkle's Mn, hashmap's CCons), or three U32 (kmeans' Sl, 168M per run, which two shared words cannot hold under 2^56).

As built, the C changes in 4 Perceus ports, raytrace (a CID_T entry only: Hit is never boxed at run time), 4 demos (pong's Pong, slash boss's Cue, Sound, Voice, the netcode walkers test's Key, pure_hvm5_mini's Bind), 9 tests and the 2 new tests. Every other bench, kernel, forked port, Perceus port, test and demo emits byte-identical C.

Results

M4, one thread, GPU off, cc -O3. Instructions (median), and P-core cycles least / median / most over 16 placements (0 to 15 nops before the first segment), 3 rounds in all, the least per placement; load average 6 to 18 from other sessions.

Perceus port instructions, main this cycles, main this this / main
rbtree 22.21G 19.21G -13.5% 8.32G / 8.51G / 8.81G 7.41G / 7.81G / 7.93G 0.846 to 0.936
rbtree-ck 81.81G 69.71G -14.8% 15.50G / 20.52G / 23.76G 11.98G / 14.10G / 15.89G 0.614 to 0.778
rbtree-unsafe 11.30G 10.08G -10.8% 2.75G / 2.83G / 2.91G 2.61G / 2.68G / 2.79G 0.917 to 0.978
rbtree-ck-unsafe 54.49G 45.70G -16.1% 11.35G / 13.88G / 15.51G 9.14G / 9.88G / 12.64G 0.638 to 0.893

Every placement is faster on all four. The -ck ports keep every fifth tree alive, so they are bound by memory and their ranges are wide under load; the median gain there is about 30%.

Maximum resident set: rbtree 270 MB to 132 MB (one run each).

Where the gain comes from, rbtree and rbtree-ck (a variant that shares the words but pads the node back to 5 words, so the block stays at 8):

port build instructions cycles over main, per placement
rbtree main 22.07G 8.36G / 8.59G / 8.86G
words shared, block kept 19.97G 8.37G / 8.45G / 8.74G 0.969 to 1.019
this PR 19.18G 7.70G / 7.85G / 8.06G 0.891 to 0.937
rbtree-ck main 81.68G 15.34G / 21.32G / 25.84G
words shared, block kept 78.33G 15.02G / 19.69G / 22.96G 0.692 to 1.147
this PR 68.17G 11.79G / 13.80G / 16.26G 0.546 to 0.818

Sharing the words alone saves instructions (one load for three fields) and no cycles; the cycles come with the smaller block. That is why the rule asks for a lower size class, and leaves the 15 constructors where it would not drop alone.

The rest of the suite: the 16 other benches, the 22 kernels, the 17 forked ports and the other 3 Perceus ports emit byte-identical C, so they are not rerun. raytrace (its CID_T differs in one entry): 83.02G / 83.24G instructions on main, 83.20G / 83.16G here, two runs each.

Checks

  • The native lane on every program whose C changes (13 tests and demos, the 2 new tests), main against this branch: C lane, JS lane and interpreter, and the C with -DBEND_POISON and a live-word count at exit (heap_alloc / heap_free patched) at 1 and 8 threads. All the same on both, every test's #| lines met, 0 live words at exit everywhere. The other 919 tests and demos that build emit byte-identical C, so their status cannot differ.
  • New tests: tests/run/node_pack.bend (three packed types built, matched, rebuilt in place, shared, captured by a closure and a partial application, held in a List and a Maybe, dropped, handed to a fork and to a ! call, read down a deep spine, and laid out in the static image; keys with the top bit set), tests/io/node_pack_foreign.bend (foreign C writes a type that would pack). Interpreter, JS and C agree; also with a 1,000,000-node spine (C only, the interpreter overflows), and on Metal (--gpu on) for node_pack.
  • Wrong versions, each caught by the new tests (C, poisoned frees, 1 and 8 threads):
wrong version new tests the repo's 9 tests whose C changes
pack a type foreign C writes caught (faults) not caught
a tag read without its mask caught (hashes) not caught
a field one bit short of its width caught (hashes) caught (bst_insert)
CID_T keeps the old word count caught (faults) not caught
the spine's slot not remapped caught (102,260 live words at exit) not caught
two U32 in one word (the top byte then holds data) caught (faults) not caught
no mask on write not caught: a tag is in range by construction, the mask is a guard not caught
a reused node's class from the old word count caught (faults) caught (bst_insert)

The spine and two-U32 versions passed the first spellings of node_pack.bend; the test now shares and drops nodes and drops a big tree next to a live one.

  • tsc: no new errors in comp.ts (the same 3 as main).
  • bun gates/repo.ts: 55 / 56, the ttok cap.

Not covered

  • Not run: the cluster gates (test, perf, ping, safe); CUDA; Linux.
  • Records in registers and frames are untouched: packing their words would add shifts where nothing is loaded or stored (101 of 704 records could lose a word; queens' Stats, lexer's Mode, raytrace's Hit, tree-radix's Chk are on hot paths, none bounded by hand).
  • A node whose shared words do not lower its size class is left alone (15 constructors, none hot): fewer stores against more shifts, not measured.
  • Two U32 cannot share a word: the word would no longer look like a trivial term to term_drop and span_fade. Allowing it (and so kmeans' Sl) needs the runtime to know a node's raw words.
  • A type that foreign C takes or names keeps its layout even where that C only passes it through.

🤖 Generated with Claude Code

nicolas-abril and others added 4 commits November 21, 2026 23:50
…ts size class

A node of a user type keeps each field in its own 64-bit word, so a Bool or
an enumeration tag takes a word, and rbtree's Node{color, l, key, value, r}
fills 5 words of an 8-word block. node_pack lays such a node's w32 and tag
words into shared words under 2^56 (the top byte zero, so the runtime reads
them as trivial terms: drop, sharing and span_fade skip them), at most one
U32 per word, and is used only when that drops the node a size class
(rbtree's Node: 5 words in 8 to 3 in 4). ctr_build writes the shared words,
node_fields reads them back, and c_header gives the runtime the new arity
and spine. Base's runtime types and any type foreign C names or takes (and
what it holds) keep their layout.

Tests: tests/run/node_pack.bend (three packed types through builds,
matches, reuse, sharing, closures, a List, a Maybe, a fork, a `!` call),
tests/io/node_pack_foreign.bend (foreign C writes a packable type itself).

Co-Authored-By: Claude Opus 5.5 <[email protected]>
The wrong version that lets two U32 share a word (its top byte then holds
bits of the second) printed the right hashes when Qn nodes were only built
and matched; sharing and dropping them make the runtime read that word as a
term, and it faults.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
A drop that walks the wrong slot as the spine leaks 102,260 words or
overwrites the live tree; the earlier spellings of the test did not show it.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 22, 2026
… fields share a word when that drops its size class

Conflict in comp.ts, node_fields' reads (bendlang#2218 against bendlang#2207): bendlang#2207
takes a node with ctr_take only when its constructor is hot (a static one
is read in place), bendlang#2218 reads each field from its packed word. Both kept:
the word a field lives in is bendlang#2218's (slot, shift, bits), read from the
take's buffer when hot and from the node otherwise, as bendlang#2207 decides.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 22, 2026
…d word

Interaction of bendlang#2207 and bendlang#2218. bendlang#2207 splits an arm that opens with a
match on the node's first field, an enumeration, and tests that field
through the reference as `(u32)e.mem[term_peek(e.mem, t)]`, word 0 of the
node. bendlang#2218 packs a node's U32 and tag fields into shared words when that
drops the size class, so for a 5-field Node{color, l, key, val, r} word 0
is `key | color << 32 | val << 34`: the split read the key's low bits as
the colour and took the wrong arm. Checked rbtree-shaped programs printed
wrong numbers on C (both drafts alone, main, JS and the interpreter agree).

The read of a field's word is now one function, node_word (slot, shift
and mask from node_pack), used by node_fields and by the split; for a node
that is not packed the split's C is unchanged. Tests
tests/run/mix_pack_split.bend (unique trees) and mix_pack_split_shared.bend
(shared, so ctr_take) fail without the fix.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
nicolas-abril added a commit to nicolas-abril/bend that referenced this pull request Nov 22, 2026
mix_sink_calls: bendlang#2217's U32 lets that sink below a non-tail call, in a
tree recursion whose returning arms run at the call (bendlang#2177), in sum loops
of two and three self calls and one whose arm answers 0 (bendlang#2175), next to a
fixed call (bendlang#2180), a let the call reads (stays), and a parallel call.
mix_reform_slots: trees in an Array's slots (bendlang#2135: read borrowed, taken
and written back) walked by a selector-first lookup and insert (bendlang#2211),
split by colour and re-formed (bendlang#2207), lent to a flat def, with the node's
U32, Bool and colour in one word (bendlang#2218), in @unsafe helper cycles.
Both print main's numbers on C at 1 and 8 threads and on JS.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator Author

Moved to nicolas-abril#26, which keeps it saved off the main queue until it can be accepted.

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant