Skip to content

A forking call no longer pays a condvar wake per pool turn: turns count rows, the main thread takes rows, and a turn visits only the rows that can hold a task - #1092

Closed
costamatheus97 wants to merge 2 commits into
bendlang:mainfrom
costamatheus97:fork-cost-pool-229

Conversation

@costamatheus97

Copy link
Copy Markdown
Contributor

On 2.0.29 (574b6d39). Three commits; the third (a yield before sleeping) is optional and last, so it can be dropped on its own.

Why

Once a program forks, corpus_eval hands it to the pool (task_deal, pool_open, cube_run(H, false)) until the root is done. Each fork tree is one cube_run iteration: a grow turn (pool_turn(true)) and a drain turn (pool_turn(false)), each a full barrier. A call that forks pays at least two barriers per tree, however little work the tree holds. bend-parallel's scan forks two trees per call, its histogram two, its sort six.

On 2.0.28 I timed the pool with counters in the generated C: a 1K-key scan at fork depth 6, 2,000 calls in one corpus_eval. 2.0.29's pool is the same design, and costs the same (the main column below).

--threads per call per turn where a turn goes
16 1.79 ms 450 us workers wake 138 us after the tick on average, the slowest over 500 us; the main thread wakes 250 us after the last one is done; the work itself is 2.7 us per worker
1 0.33 ms 80 us wake 25 us, join 25 us, work 31 us

Three things cost that, each in bend2/comp.ts:

  1. Every turn waits for every worker. pool_turn sets pool_done to pool_size and sleeps on pool_wake until it reaches 0. Each worker must wake from the condvar, find no rows left and check in, and the last one's pthread_cond_broadcast(&pool_wake) also wakes the sleeping workers again, since both directions share one condvar. The main thread sleeps meanwhile.
  2. Workers sleep between turns (pool_work's pthread_cond_wait). The next turn is often a few microseconds away, but a condvar wake costs over 100 us on this machine.
  3. A turn walks the whole bag. The grow turn runs row_grow over all 128 rows (CUBE_G) and the drain turn walks all 1024 units (LANES / LINE), reading every ring's head, however small the frontier is. For a 64-leaf tree that walk is most of a turn: on one thread, 48 of the grow turn's 60 us.

What changes (bend2/comp.ts only; ttok 62,584 → 63,019 with commits 1–2 below, 63,085 with the third, against 64,000)

The pool keeps 2.0.29's atomics: a32_* on plain u32, no _Atomic or atomic_*_explicit.

  1. A pool turn ends when its rows are done, not when every worker has woken; the main thread takes rows too (+219).
    • A claim is one relaxed a32_add on pool_row, a u32 that carries the turn, the grow flag and the row.
    • pool_done counts down the turn's rows. Each worker subtracts its count once (a32_sub_rel), when a claim comes back past the last row. The worker that brings it to 0 signals the main thread on its own condvar, pool_join. The main thread waits with a32_load_acq(&pool_done) != 0, as before.
    • The main thread is worker 0: after it opens a turn, it claims rows like the others. --threads N now runs N − 1 pool threads.
    • A worker that wakes late for a turn claims from whatever turn is open. It gets that turn's rows, or none, and no one waits for its wake.
    • pool_tick and pool_grow go away; the worker's body moves into pool_rows, unchanged.
  2. A pool turn visits only the rows that can hold a task, not all 128 rows and 1024 units (+216).
    • Frontier deal i goes to ring_flip(i), whose row is at most i, and a grow turn pushes only within its own row (ring_pick(base, 1, cur)).
    • So the grow turn visits the rows below min(f, CUBE_G), and the drain turn the rows below the deals made so far (the frontier, plus any continuation that forked while growing). The main thread's column grow can reach any row, so a turn after it visits all of them.
    • The bound rides in the claim word.
    • The invariant is written at the deal site (above ring_flip) and checked where breaking it would show: a task dealt past a turn's rows would sit in its ring until the frontier drained, so cube_run, on that failure path only, walks the rings and fails with "a task left past its pool turn's rows" rather than "frontier drained without a result". A run that succeeds never reaches the walk.
  3. A pool wait yields a while before it sleeps (+66, optional, last so it can be dropped). POOL_WAIT calls sched_yield() up to 128 times while its condition holds (about 80 us here), then blocks on the condvar as before. It serves both waits: a worker's for the next turn, and the main thread's for the last row. See "The third commit" below.

The claim word

turn << 20 | rows << 12 | grow << 11 | counter (commit 1 alone has no rows field: turn << 12 | grow << 11 | counter).

  • counter, 11 bits. A turn has at most LANES / LINE units: CUBE_T (128) × CUBE_G / LINE (16), with CUBE_G at most 128 (CUBE_LOG is 7 on the host; CUDA's gpu_shape clamps it to 4..7), so 1024. Past them, each thread makes at most one claim per opening: it leaves pool_rows on its first claim past the end and then waits for a turn value different from that claim's. pool_size is at most CUBE_T, so the counter stays below 1024 + 128 = 1152 < 2048 and never carries into grow.
  • rows, 8 bits. 1..128.
  • turn, 12 bits. It wraps every 4096 turns, routinely in a long run. A worker compares the turn in the word with the last one it saw. If it sleeps through exactly a multiple of 4096 turns, it sees its old value and keeps sleeping through that turn. That costs nothing: a turn completes when its rows are done, not when its workers check in, and the main thread takes rows itself, so no turn needs any particular worker.

Why it's safe

  • Every row of a turn is processed exactly once. A row index comes from one a32_add on the word that names the turn. Two threads can't get the same (turn, row).
  • No row is processed with the wrong mode or bound. The grow flag and the bound come from the same atomic read as the row.
  • A turn can't end early. A worker subtracts its rows from pool_done only when it leaves the loop, so while it holds an unfinished row of turn T, pool_done isn't 0 and the main thread can't open T + 1. That also means every claim a worker makes before leaving is still in T.
  • Ordering. The main thread stores pool_done (relaxed) and then opens the turn with a32_store_rel(&pool_row, ...). A worker claims with a relaxed a32_add, then calls a32_acq(&pool_row) before it touches a claimed row. That is the shape task_deliver already uses (a32_sub_rel, then a32_acq). The acquire load reads the opening store or a later claim in its release sequence. It can't read the next opening's store, because this worker holds an unfinished row. So the worker sees the rings, the grow's pushes and the pool_done reset. The main thread's a32_load_acq(&pool_done) == 0 reads the last of the release subtractions, so it sees every row's writes.
  • No lost wakeup. A worker checks the turn under pool_lock before pthread_cond_wait, and the main thread opens the turn and broadcasts under the same lock. The join is symmetric: the last row's worker signals pool_join under the lock.
  • The rows bound (commit 2):
    • At the top of each cube_run iteration, every ring that holds a task is in a row below the bound. After a drain, only task_deal with stride 0 pushes, to ring_flip(g) for g below the cursor.
    • A grow turn pushes only within its own row.
    • The one push that can reach any row, the main thread's column row_grow (stride CUBE_G), sets the bound to CUBE_G.
    • ring_flip(i)'s row is i % CUBE_T (at CUBE_LOG 7) or below (at smaller CUBE_LOG), so at most i.
    • These are all the host's ring pushes on 2.0.29: task_deal, monk_step's push of a fork-free continuation (stride ≠ 0 only, so within its row), row_grow, and corpus_eval's first deal. The GPU seam's ring_push(H, 0, t) runs cube_run(H, true), not the pool.
    • Liveness: a task dealt during a drain, past that drain's bound, isn't lost. It lands in ring_flip(g), where g is below the cursor at the end of the drain. The next iteration reads that cursor as its f before resetting it, so f > g >= the task's row, f > 0, and the next bound, min(f, CUBE_G), covers the task's row. Such a task waits one iteration, where the full walk on one thread could have reached it in the same turn. That changes the one-thread schedule of tree-bitonic, not its result.

The third commit: optional

What commit 3 gives on this machine, on top of 1+2 (bend-parallel, c16, 5 rounds, rounds don't overlap):

case main 1+2 1+2+3
scan d10 b6 c16, ms per call 1.830 0.111 0.0435
sort d17 b6 c16 3.63 0.92 0.375
sort d17 b12 c16 10.39 7.84 7.39
hist d17 b12 c16 4.34 2.70 2.42
hist d20 b6 c16 1.88 0.63 0.25

Before timing, I set the bar for keeping it: at least 25% off scan d10 b6 c16 and at least 3% off sort d17 b12 c16. It clears both: −61% (67 us per call) and −5.8%. At c1 it does nothing: one thread finishes every row before it waits, so there's nothing to yield for.

It's last so it can be dropped. It is tuned to this host, where a futex wake costs about 140 us. Upstream's runtime has no yield-spin anywhere else, and its perf gate runs on Mac minis, where a condvar wake is likely cheaper and 128 sched_yields take an unmeasured time. What it costs:

  • up to about 80 us of yielding per wait, on a pool that is between turns;
  • about 2% more CPU on kmeans c16 at matched layout (below).

Without it, the branch still takes scan d10 b6 c16 from 1.83 ms to 0.11 ms per call.

Measurements

The machine is an AMD Ryzen 7 5800XT (8 cores / 16 threads) under WSL2 (kernel 6.18), with AMD clang 22 (ROCm 7.2.1) at -O3 and no GPU. It's a shared machine. I give the 1-minute load average with each table; the c16 runs themselves push it up. Every value is a median.

bend-parallel benches (ms per call; 5 interleaved rounds, order rotated each round; load 0.8 → 3.8)

bend-parallel 7fb04de. "1+2" is the first two commits, "all" this PR. scan d10 is 2,000 calls in one run; the precise drivers run d=17 64 calls and d=20 and d=22 16 calls each. Checksums match across all builds, lanes and rows.

case main 1+2 all
scan d10 b6 c16 1.830 0.111 0.0435
scan d10 b6 c1 0.3185 0.0155 0.0155
sort d17 b6 c16 3.625 0.922 0.375
sort d17 b6 c1 1.578 0.906 0.906
sort d17 b12 c16 10.39 7.84 7.39
sort d17 b12 c1 5.375 4.531 4.500
sort d20 b6 c16 4.31 2.00 1.50
sort d22 b6 c16 7.38 5.25 5.19
sort d22 b12 c16 15.94 13.50 13.19
hist d17 b6 c16 1.797 0.328 0.109
hist d17 b12 c16 4.34 2.70 2.42
hist d22 b12 c16 5.69 4.06 3.75
  • The fixed cost of a forking call drops from about 1.8 ms to about 0.04 ms at c16, and from 0.32 ms to 0.016 ms at c1.
  • The b=0 rows don't fork. They are within 2% of main at c16. At c1 the largest gap is sort d20 b0, where main is 6.88 ms, 1+2 is 7.25 (+5.5%) and all is 7.13 (+3.6%). The other c1 b=0 rows are within 2%.

bench/runtime (seconds; 16 programs, c1 and c16, --gpu off; 5 interleaved rounds, order rotated; load 2.3 → 4.1)

All 16 programs print the same output on every build. Rows not shown are within 2.5% of main on both builds.

bench lane main 1+2 all 1+2 / main all / main
tree-radix c16 0.985 0.890 0.872 0.904 0.886
kmeans c16 0.776 0.753 0.736 0.971 0.949
hashmap c16 0.453 0.432 0.433 0.955 0.957
lexer c16 0.403 0.420 0.405 1.043 1.005
bfs c16 0.472 0.478 0.486 1.012 1.029
tree-matmul c16 0.573 0.578 0.590 1.008 1.029
tree-matmul c1 4.002 4.001 4.109 1.000 1.027
tree-bitonic c1 11.932 12.207 12.103 1.023 1.014

Rows that move by more than about 3% are checked at matched layout before they're attributed.

The PR adds libc imports (pthread_cond_signal, and sched_yield in commit 3) and a function, pool_rows, with its .eh_frame entry. That moves .text, and with it the program's hot code (WL_FID_*, monk_step), by 16–48 bytes mod 64. On 2.0.28 that shift alone moved CPU time by up to 11% on this Zen 3 host, in a direction that depends on the program and lane. It produced that version's editdist, symreg and tree-matmul c16 slowdowns (+4–10%). On 2.0.29 the layout has moved again, and those three are within 3% of main.

The check: pad.py puts a 64-aligned pad at the start of .text, so at each pad N (0, 16, 32, 48) main and both branches put monk_step and main at the same address mod 64 (checked with nm). c16, 9 rounds, load 1.0 → 14.6 from the runs themselves; the geometric mean over the four pads, against main:

bench lane 1+2 wall 1+2 CPU all wall all CPU reading
tree-radix c16 0.923 0.942 0.912 0.931 real gain (0.90–0.95 at every pad)
kmeans c16 0.953 0.994 0.956 1.019 real wall gain; the yields cost about 2% CPU
hashmap c16 1.007 1.003 0.997 1.000 layout
lexer c16 0.989 0.998 0.987 0.996 layout
bfs c16 1.002 0.999 1.005 1.000 layout
tree-matmul c16 1.002 1.002 1.002 1.001 layout
tree-matmul c1 (5 rounds) 1.003 1.002 1.004 1.004 layout
  • Unpadded, the layout-attributed rows are the ones whose hot code moved: monk_step mod 64 for main / 1+2 / all is hashmap 0/0/16, lexer 32/16/32, bfs 32/32/48 and tree-matmul 48/48/0. tree-radix (16/16/16) and kmeans (0/0/0) didn't move.
  • No alignment is best for every program, so there's nothing to fix in the pool code. A different compiler, CPU or later commit will reshuffle these rows again, and upstream's perf gate may see a different set on its hardware.
  • tree-bitonic c1 (+1.4–2.3%, under the 3% bar) wasn't padded. On 2.0.28, about +2% of it was real, from commit 2's schedule: at --threads 1, a drain turn visits the rows below the deals made before it started, so tree-bitonic runs half as many cube_run iterations (258 → 121 there), with the same output.

Verification

  • The row bound, as a runtime check (a patched copy of the emitted C, not committed). A debug build aborts in pool_turn if any ring at or past the bound holds a task. It sleeps 0–50 us before one claim in eight and before each final subtraction, to force late workers. It aborts if a claim's counter reaches all + pool_size, and it can cut the turn field to k bits (DBG_WRAP), so sleepers constantly meet wrapped turns.
    • All 50 tests that fork (tests/*), at --threads 1, 2, 3, 7, 16, 32: every output right, no abort. The first two commits alone: the same at 1, 2, 16, 32.
    • With a 1-bit turn at 2, 4, 16, 32, and a 2-bit turn at 2, 16, 32: every output right.
    • bend-parallel's 10 tests and the 16 bench/runtime programs at 1 to 32 threads: every output right. bend-parallel's tests with a 1-bit turn: right.
    • scan d10 b6 (8,000 turns) with a 1-bit turn: right at 2, 4, 16, 32 threads, with 334, 970, 3,019 and 3,445 workers late for their turn.
    • Past a turn's end, a turn never took more claims than there were threads, well inside the 1152 the word allows for.
    • Positive control. Halving the grow bound ((f + 1) / 2) makes the debug check fire (ring 128 holds a task past grow bound 1). On the committed code, without hooks, the same mutant fails with the new message: bend: a task left past its pool turn's rows.
  • ThreadSanitizer (AMD clang 22, -O1 -g -fsanitize=thread, the plain runtime, no hooks; the 50 forking tests at --threads 2, 4, 16):
  • bun gates/repo.ts: 46/46.
  • Local gate (gates/test.ts's rules on one machine, no GPU lane, io_tcp_send_slow_peer excluded): 1473 / 1477, the same four failures as main (io_audio_only_{open,write,close}: no ALSA headers here; io_process_run on interp and JS).
  • bend-parallel's run_tests.sh (check, proof, JS, c1, c16), stacked on A spin reads a shared Array's redirect once, atomically: blk_loc no longer races its count #1084: 41/41.

With #1084

Not run

  • CUDA and Metal. The device loop doesn't use the pool. On a GPU build, the CPU pool runs only for forks outside ! calls, through this same code.
  • macOS. sched_yield is POSIX and <sched.h> is included on every host. How long 128 yields take there, and what commit 3 gains there, wasn't measured.
  • The cluster, perf and GPU gates.
  • One machine. WSL2 on 16 vCPUs.

@nicolas-abril

Copy link
Copy Markdown
Collaborator

Thank you for this, the gains hold up on an Apple M4 too. I pushed three commits to your branch: one dropping the comments the rework added, a merge of current main, and a simplification commit, because the PR put comp.ts at 64,187 ttok, over the permanent 64,000 cap.

Pool. The same three mechanisms, written more simply:

  • The claim word carries each turn's claim limit (turn << 23 | grow << 22 | limit << 11 | counter), so cube_run passes plain row counts.
  • One condvar instead of two.
  • The main thread yields while the last rows finish, so a worker neither locks nor signals when it's done.
  • The failure path's ring walk is gone. A lost task still fails the run, as "frontier drained without a result".

Emitter. Eight redundancies removed elsewhere in comp.ts. The emitted C, JS and .mjs are byte-identical for every test and bench.

comp.ts is now at 63,999 ttok.

Measured on an Apple M4:

  • Full local suite: 1500 / 1502, the same two display-dependent gfx tests as on main.
  • The 52 forking tests are correct in 3 runs at each of 1, 2, 3, 7, 16 and 32 threads, and ThreadSanitizer reports nothing at 2, 4 and 16 threads.
  • 2,000 calls that each fork a 64-leaf tree take 330 ms on main and 57 ms here at 16 threads, and 274 ms against 50 ms in the Metal build's CPU pool. Your version took 64 and 54 ms.
  • The yield spin pays on macOS as well. Without it, the same run takes about 95 ms.
  • The 16 runtime benches match their pins and are within ±2% of main when timed back to back.

Note: this comment was written by an AI after it validated and simplified the PR for me. If anything here is wrong, reply and I will review it myself.

@nicolas-abril nicolas-abril self-assigned this Sep 28, 2026
costamatheus97 and others added 2 commits October 1, 2026 17:10
…nt rows, the main thread takes rows, and a turn visits only the rows that can hold a task

bendlang#1092's five commits, squashed onto main. The emitter cleanups its last
commit carried are already on main (bendlang#1235); the column grow keeps bendlang#1171's
row per thread, and a column grow still opens every row to the turns.

Co-Authored-By: Nicolas Abril <[email protected]>
Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
… row bound says why it holds

pool_turn waited for the last rows with a sched_yield loop that never
slept; on macOS that is a busy core for as long as the slowest row runs.
The main thread now yields 128 times and then sleeps on pool_join, which
the last finisher signals; a short turn still ends inside the yields and
pays no wake. cube_run's comment states the invariant the turn bound
rests on: a drain deals task g to a row at most g, a row grows into
itself, and only a column grow reaches any row.

Co-Authored-By: Claude Opus 5.5 (1M context) <[email protected]>
nicolas-abril added a commit that referenced this pull request Oct 2, 2026
…lits its rows into units of 32 a thread, and rings rewind between turns (stacked on #1092) (#1269)

Co-authored-by: Matheus Costa <[email protected]>
Co-authored-by: Claude Opus 5.5 (1M context) <[email protected]>
@nicolas-abril

Copy link
Copy Markdown
Collaborator

Closing as superseded: #1269 (fb6f32a), which was stacked on this PR, squash-merged these pool changes into main along with later work (pool_step, ring_rewind, and a column grow that returns cur). This branch now conflicts with main in bend2/comp.ts, and resolving the conflict toward it would revert #1269. Thanks for the groundwork!

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.

2 participants