Skip to content

Mixed midtraining: opt-in batch building in a child process - #925

Merged
jason718 merged 3 commits into
jasonr/olmo35-mixed-midtrainingfrom
rustins/loader-speed
Oct 18, 2026
Merged

jason718 merged 3 commits into
jasonr/olmo35-mixed-midtrainingfrom
rustins/loader-speed

Conversation

@RustinS

@RustinS RustinS commented Oct 16, 2026 •

Copy link
Copy Markdown

Into #916's branch, after #923 (1a2064c): three commits. batch_prefetch_process and
prefetch_processes are off by default and should be turned on
(see Turning it on); the
allocation changes are always on, and the recipe now builds 8 batches ahead. None of it changes
the batches.

Summary

Three commits, reviewable separately:

  1. Batch building in a child process, behind batch_prefetch_process (off by default):
    • BatchProcessPrefetcher runs the producer of BatchPrefetcher in a child forked from the
      trainer process. Batches cross a torch.multiprocessing queue, so their tensors travel through
      shared memory, each paired with the loader state right after it: the batches, their order and
      the checkpointed state are the thread prefetcher's. A receiver thread takes them off the queue
      ahead of the trainer and copies their large tensors to pinned memory. An exception in the
      child, or its death, reaches the trainer as a RuntimeError with the child's traceback.
    • MixtureDataLoaderConfig.batch_prefetch_process and MixedMidtrainingRecipeConfig.batch_prefetch_process
      (--recipe.batch_prefetch_process=true); it requires a positive batch_prefetch_depth.
  2. Fewer large fresh allocations while packing and collating:
    • The buffered packer's knapsack keeps one DP table per thread instead of allocating one per
      packed sequence (about 400 MB at a 65K sequence's buffer).
    • The mixed mid-training recipe sets defer_packed_image_copy, so packed crops are copied into the
      collated batch only.
    • In the prefetch process, the collator builds compact images in shared memory, casting each
      part straight into them (MultimodalCollator(shared_memory_images=True)), so queueing a batch
      copies nothing; and NumPy asks for no transparent huge pages there.
  3. Example loading in worker processes, behind prefetch_processes (off by default):
    • prefetch_map(..., processes=True) runs the per-example function in processes forked from
      the caller (like DataLoader workers) instead of threads, still yielding in input order. The
      function is inherited, not pickled; the workers are stopped when the stream closes, also in a
      batch prefetch process, whose own exit would leave them running.
    • MixtureDataLoaderConfig.prefetch_processes and MixedMidtrainingRecipeConfig.prefetch_processes
      (--recipe.prefetch_processes=true); it requires positive prefetch_workers.
    • The mixed mid-training recipe's batch_prefetch_depth is 8 instead of 2.

Turning it on

--recipe.batch_prefetch_process=true --recipe.prefetch_processes=true \
--recipe.prefetch_workers=16 --recipe.prefetch_max_in_flight=512

The worker and in-flight counts are the ones measured below (16 worker processes and 512
examples in flight per rank). With the child process the queued batches take /dev/shm: about
batch_prefetch_depth + 1 batches per rank, 6.4 GB each at 8 GPUs on the 90/10 stage and 0.8 GB
at 64, so about 60 GB a node at 8 nodes (the 128 GiB of the v3 run's launch suffices) and 460 GB
at one node, which needs a larger --launch.shared_memory or a lower depth.

Why

With batch_prefetch_depth > 0 the next rank batches are built on a thread of the trainer, whose
interpreter lock that Python work shares with the training step. On the 90/10 stage at 8 GPUs a
rank's batch holds about 570 image examples. While it is built, micro-batches take 3-4 s instead
of 1 s, and the interpreter-lock probe shows 1-3 ms waits in exactly that window: about 20 s per
step. Since every micro-batch costs the slowest rank's time, one slow rank slows all of them.

Building a rank batch also allocated and filled a fresh 400 MB knapsack table per packed sequence,
a fresh float32 concatenation of each pack's crops (about 740 MB), and the collated images twice
more. On nodes whose page cache had fragmented their free memory, NumPy's transparent-huge-page
requests made those page faults compact memory synchronously: in a 2-node run, batch building
stalled for minutes at a time on one node (stacks of the stalled child: idle worker threads, the
producer inside the knapsack, the concatenation and the collator's casts). The dev node, same
kernel settings, showed 15M compaction stalls, 14.6M of them failed.

At 8 nodes the steps are short enough that loading stalls of another kind showed: every few steps
one rank's batch came late, by 15-120 s, and every rank waited for it. In a stalled batch, dozens
of example loads started in the same second and took the same 40-120 s, while the child used 0.45
cores instead of 3.2, with no compaction and no reclaim. The sources read Arrow tables
(load_from_disk, Dataset.from_file) and numpy memmaps from Weka, and a thread that page-faults
on a memory-mapped file keeps the interpreter lock until the page arrives: reading random cold
pages of a Weka file through np.memmap froze a second, spinning thread for 1.66 s of 2.34, while
os.pread did not, at read latencies up to 13 s. So one slow page stalled every loading thread of
the rank, and also the hand-over of batches already built, whose tensors the child's
multiprocessing resource sharer hands to the trainer: with up to 16 batches built ahead, ranks
still waited up to 94 s. In worker processes such a stall holds up one example only.

Results

90/10 split (--recipe.visual_data=stage1_v3 --recipe.text_loss_share=0.9, the 21,000-step
schedule of the v3 90/10 run), crops balanced, 8 B300s, same batches; seconds per step, training
loop + data wait:

8 GPUs, batches built Trainable encoder Cached encoder output
On a trainer thread 113.5 + 0.5 55.4 + 0.5
In a child process 92.0 + 3.9 33.4 + 1.0

With the child process the cached-feature step is 1.08x the text-only step (30.8 s). The data wait
left in the trainable runs came from head-of-line blocking: at most 32 examples in flight, so one
slow example (a PDF render, a large image) held up the batch. With --recipe.prefetch_max_in_flight=512 --recipe.prefetch_workers=32, the data wait is 0.0 s, and those are the settings measured below.

Allocation changes, after the 2-node stall above, 200 steps on 16 GPUs (node-wide kernel
counters, logged per batch):

Node Batch build, median / slowest Compaction stalls Direct reclaims Lowest free memory
Node where a 1-node run had stalled 14.2 / 92 s 0 0 269 GB
Other node 15.7 / 153 s 208 321 8 GB

The slow batches were absorbed by the read-ahead: data wait median 0.02 s, largest 11 s. On a node
with free huge pages the reused knapsack table takes 0.19 s per pack, against 0.22 s for a fresh
one.

Worker processes, 8 nodes, with #924 (the batch child process on in all three; steps 11-41, or
11-30 for depth 16):

64 GPUs, examples loaded s/step, median / mean Steps over 20 s
On 32 threads, depth 2 9 / 17.2 6 of 31
On 32 threads, depth 16 10 / 23.8 6 of 20
In 16 worker processes, depth 2 9 / 9.1 0 of 31

Over steps 11-300 of the worker-process run, 6 of the 19,008 rank batches came more than 1 s
late. Four of them, in three steps, came 27-53 s late: each rank's queue had run dry on a single
example that took 80-95 s, and ranks on different nodes slowed from the same second, a pause of
the file system rather than of the interpreter lock. With batches handed over freely again, a
deeper queue can absorb those: the recipe's depth is now 8, over a minute of steps at 8 nodes
(not yet measured end to end). Batches are built in 1.7-2.1 s (median per node) instead of 3.5 s.
With 128 worker processes a node, at least 2.5 TB of memory stayed available and no memory
compaction stalled; the first batches took up to 167 s, within the trainer's startup compile.

End to end

90/10 split, the branches as committed (with #924), same batches as the reference runs; medians
over steps 11-200 on 16 GPUs (11-100 for the branches), 11-300 on 64 GPUs:

16 GPUs 64 GPUs
Text-only merged MT+LC 15.0 4.05
90/10 on #916 75.1 20.92
+ #923, crops balanced 62.3
+ #924 and this PR 31.2 8.42

On 64 GPUs: the 90/10 step is 2.08x the text-only step (#916: 5.17x); 2.49x faster than #916 by
the median, 2.33x by the mean (8.98 s, the three file-system pauses included). The reference is
the v3 90/10 run's first segment (its console log, metrics every 10 steps); the 16-GPU runs are
our own, from the same parent and schedule. Rank-0 peak reserved memory is 124 GiB (174 on #916).

The 16-GPU row ran the first two commits (examples on threads); the 64-GPU row all three, with
the loader's timings logged.

Mean CE by window, 16 GPUs:

Steps #916 + both PRs
1-10 1.6697 1.6696
11-50 1.5880 1.5876
51-100 1.5019 1.5016

Mean CE by window, 64 GPUs:

Steps #916 + both PRs
1-50 1.6057 1.6059
51-100 1.4892 1.4892
101-200 1.4613 1.4612
201-300 1.4158 1.4158

Tests

  • batch_prefetch_test.py: the existing order, resume, live-state, error, shutdown and epoch-mode
    tests run for the thread and the process prefetcher; compact images arrive in shared memory and
    equal to the synchronous loader's; a unit test of BatchProcessPrefetcher (order, states, small
    and pinned large tensors, idempotent close); the configuration checks. With examples loaded in
    worker processes, the batches and state equal the synchronous loader's with batches built on
    the caller's thread, a thread or a child process; source errors are skipped or raised the same
    way; a checkpoint resumes the synchronous stream; no worker process outlives the iterator.
  • prefetch_test.py: prefetch_map on threads and processes keeps input order, runs functions
    that cannot be pickled, raises the function's errors in order and stops its workers on close,
    also when its caller is a forked child; a worker holding the interpreter lock for 3 s does not
    delay the other results (0.21 s for 16 of them, 3.10 s on threads).
  • collator_compact_images_test.py: shared-memory compact images equal the default ones, plain
    and packed, and a text-only batch.
  • dynamic_packing_test.py: knapsack selections with the reused table, across sizes and on four
    threads at once, equal those of a fresh table.
  • vision_midtraining_test.py: the recipe's depth is 8, and both process options are off by
    default and reach the loader when set.
  • src/test/data/multimodal/ and src/test/internal/: all pass.

How to test

pytest src/test/data/multimodal/batch_prefetch_test.py src/test/data/multimodal/prefetch_test.py \
  src/test/data/multimodal/collator_compact_images_test.py \
  src/test/data/multimodal/dynamic_packing_test.py
pytest src/test/internal/vision_midtraining_test.py -k prefetch

🤖 Generated with Claude Code

https://claude.ai/code/session_0159PTUsp2w3YTANVDZ4BUss

RustinS and others added 2 commits October 16, 2026 09:47
With batch_prefetch_depth > 0 the next rank batches are built on a thread
of the trainer, whose interpreter lock that Python work then shares with
the training step. On the 90/10 merged mid-training stage at 8 GPUs (about
570 image examples per rank and step) it cost about 20 s per step.

batch_prefetch_process (MixtureDataLoaderConfig, and the mixed mid-training
recipe) runs the same producer in a forked child process instead
(BatchProcessPrefetcher). Batches cross a torch.multiprocessing queue
through shared memory, each with the loader state right after it, so the
batches, their order and the checkpointed state are the thread loader's.
A receiver thread takes them off the queue ahead of the trainer and copies
their large tensors to pinned memory. Off by default.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0159PTUsp2w3YTANVDZ4BUss
…ting

Building a 90/10 rank batch filled a fresh 400 MB knapsack table for every
packed sequence, a fresh float32 concatenation of each pack's crops (about
740 MB), and the collated images twice more. On nodes whose page cache had
fragmented their free memory, NumPy's transparent-huge-page requests made
those page faults compact memory synchronously, and batch building stalled
for minutes at a time.

- The buffered packer's knapsack keeps one DP table per thread.
- The mixed mid-training recipe sets defer_packed_image_copy, so packed
  crops are copied into the collated batch only.
- In the prefetch process, the collator builds compact images in shared
  memory, casting each part straight into them (queueing them copies
  nothing), and NumPy asks for no huge pages.

The batches are unchanged.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0159PTUsp2w3YTANVDZ4BUss
@chatgpt-codex-connector

chatgpt-codex-connector Bot commented Oct 16, 2026 •

Copy link
Copy Markdown

Codex Review Summary

This comment shows the latest Codex review activity on this pull request.

Review Status Commit Review trigger
📝 Code Review ✅ Completed 2026-10-17T02:50:11.856177Z 724e542 New commits
ℹ️ About Codex in GitHub

Your team has set up Codex to review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review" or "@codex security review".

Codex reacts with 👀 while any review is running, comments if it has suggestions, and reacts with 👍 once all reviews finish with no findings.

A loading thread that page-faults on a memory-mapped source (the Arrow tables and numpy memmaps
the multimodal sources read from Weka) keeps the interpreter lock until the page arrives, so one
slow read stalls every loading thread of the rank; in a batch prefetch process it also stalls
the hand-over of batches already built, whose tensors are passed by a thread of that process.
prefetch_processes (MixtureDataLoaderConfig and the mixed mid-training recipe) runs
prefetch_map's workers in forked processes instead, which confines such a stall to one worker.
The examples, their order and the checkpointed state are unchanged.

Like batch_prefetch_process, it is off by default and should be turned on. The mixed
mid-training recipe now builds 8 rank batches ahead instead of 2, to ride out file-system pauses.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
Claude-Session: https://claude.ai/code/session_0159PTUsp2w3YTANVDZ4BUss
@RustinS

RustinS commented Oct 17, 2026

Copy link
Copy Markdown
Author

@jason718 Added a third commit (724e542): prefetch_processes, example loading in forked worker processes. At 8 nodes one rank's batch came 15-120 s late every few steps: the sources are memory-mapped from Weka, and a thread that page-faults keeps the interpreter lock until the page arrives, so one slow read froze every loading thread of that rank, and every rank waited for it. Your crop-balanced relaunch on the thread loader shows the same stalls (data waits up to 135 s).

Both process options are off by default; please turn them on:

--recipe.batch_prefetch_process=true --recipe.prefetch_processes=true \
--recipe.prefetch_workers=16 --recipe.prefetch_max_in_flight=512

8 nodes, 90/10, steps 11-300, with #924: 8.42 s/step median (8.98 mean) against 20.92 on #916, with the same CE; details in the description. The recipe now builds 8 batches ahead: with the child process that takes about 60 GB of /dev/shm a node at 8 nodes, within the 128 GiB your launches use, and more on fewer nodes.

@chatgpt-codex-connector chatgpt-codex-connector Bot left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 724e542ecf

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +281 to +283
self._stop.set()
self._finished = True
self._receiver.join()

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

P1 Badge Avoid joining a receiver blocked on an abandoned queue frame

When an iterator is closed while the child queue's feeder thread is still serializing a batch, the child observes _stop and calls out.cancel_join_thread(), allowing it to exit with a partially written queue frame. The receiver may already have entered multiprocessing.Queue.get() for that frame; its timeout no longer applies after data becomes readable, and the parent's still-open writer prevents EOF, so this unbounded join() can hang shutdown indefinitely. Coordinate draining/closing the queue without abandoning an in-progress write, or make receiver shutdown independently bounded.

Useful? React with 👍 / 👎.

@jason718
jason718 merged commit eb8ebd4 into jasonr/olmo35-mixed-midtraining Oct 18, 2026
1 check passed
@jason718
jason718 deleted the rustins/loader-speed branch October 18, 2026 02:31
jason718 pushed a commit that referenced this pull request Oct 23, 2026
Into #916's branch, after #925 (eb8ebd4): the mixed mid-training
recipe's `batch_prefetch_depth` goes back from 8 to 2.

## Why

#925 raised the depth to 8 so the queue would ride out the file-system
pauses left at 8 nodes, and said it was not yet measured end to end.
Measured now, on the same setup as #925's 8-node row (90/10 split, crops
balanced, `batch_prefetch_process`, `prefetch_processes`, 16 workers,
512 examples in flight, 128 GiB of shared memory), depth 8 is no faster:

| 64 GPUs, steps 11-300 | Depth 2 | Depth 8 |
|---|---|---|
| s/step, median | 8.42 | 9.06 |
| s/step, mean | 8.98 | 9.75 |
| Rank-0 data waits over 1 s | 4 (41, 2, 53, 27 s) | 1 (156 s) |

- The time lost to late batches is about the same (134 s against 158 s
over the 290 steps). The pause at depth 8 was longer than any queue
covers.
- A first depth-8 run ran during a file-system slowdown that stalled
every job on these sources, including the v3 90/10 run. Over its clean
steps (170-300) it took 8.75 s/step, against 8.37 at depth 2.
- Over steps 11-31, both depth-8 runs were slower than all four of our
other 8-node runs (9.51 and 9.98 s/step against 9.09-9.32, steps with
data waits left out). The trainer side is the same at any depth, since
the receiver holds at most one batch, so this may be node placement. But
it went the same way twice.
- With the batch prefetch process, the queued batches take `/dev/shm`:
about `batch_prefetch_depth + 1` batches per rank. At depth 2 that is
about 150 GB a node on one node and 20 GB at 8 nodes, against 460 and 60
GB at depth 8.
- CE matches #916 at every logged step (largest gap 0.0007).

Runs launched from eb8ebd4 get depth 8 unless they pass
`--recipe.batch_prefetch_depth=2`.

## Changes

- `MixedMidtrainingRecipeConfig.batch_prefetch_depth`: 2, and its
docstring without the depth-8 rationale.
- `batch_prefetch_process` docstring: the `/dev/shm` figures for depth
2.
- CHANGELOG: the `prefetch_processes` entry no longer says the recipe
builds 8 batches ahead.
- `vision_midtraining_test.py`: the default depth is 2.

## How to test

```bash
pytest src/test/internal/vision_midtraining_test.py
```
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