Repository navigation
Mixed midtraining: opt-in batch building in a child process - #925
Conversation
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
Codex Review SummaryThis comment shows the latest Codex review activity on this pull request.
ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
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
|
@jason718 Added a third commit (724e542): 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=5128 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 |
There was a problem hiding this comment.
💡 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".
| self._stop.set() | ||
| self._finished = True | ||
| self._receiver.join() |
There was a problem hiding this comment.
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 👍 / 👎.
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 ```
Into #916's branch, after #923 (1a2064c): three commits.
batch_prefetch_processandprefetch_processesare off by default and should be turned on (see Turning it on); theallocation changes are always on, and the recipe now builds 8 batches ahead. None of it changes
the batches.
Summary
Three commits, reviewable separately:
batch_prefetch_process(off by default):BatchProcessPrefetcherruns the producer ofBatchPrefetcherin a child forked from thetrainer process. Batches cross a
torch.multiprocessingqueue, so their tensors travel throughshared 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
RuntimeErrorwith the child's traceback.MixtureDataLoaderConfig.batch_prefetch_processandMixedMidtrainingRecipeConfig.batch_prefetch_process(
--recipe.batch_prefetch_process=true); it requires a positivebatch_prefetch_depth.packed sequence (about 400 MB at a 65K sequence's buffer).
defer_packed_image_copy, so packed crops are copied into thecollated batch only.
part straight into them (
MultimodalCollator(shared_memory_images=True)), so queueing a batchcopies nothing; and NumPy asks for no transparent huge pages there.
prefetch_processes(off by default):prefetch_map(..., processes=True)runs the per-example function in processes forked fromthe caller (like
DataLoaderworkers) instead of threads, still yielding in input order. Thefunction 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_processesandMixedMidtrainingRecipeConfig.prefetch_processes(
--recipe.prefetch_processes=true); it requires positiveprefetch_workers.batch_prefetch_depthis 8 instead of 2.Turning it on
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: aboutbatch_prefetch_depth + 1batches per rank, 6.4 GB each at 8 GPUs on the 90/10 stage and 0.8 GBat 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_memoryor a lower depth.Why
With
batch_prefetch_depth > 0the next rank batches are built on a thread of the trainer, whoseinterpreter 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-faultson a memory-mapped file keeps the interpreter lock until the page arrives: reading random cold
pages of a Weka file through
np.memmapfroze a second, spinning thread for 1.66 s of 2.34, whileos.preaddid not, at read latencies up to 13 s. So one slow page stalled every loading thread ofthe rank, and also the hand-over of batches already built, whose tensors the child's
multiprocessingresource sharer hands to the trainer: with up to 16 batches built ahead, ranksstill 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-stepschedule of the v3 90/10 run), crops balanced, 8 B300s, same batches; seconds per step, training
loop + data wait:
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):
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):
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:
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:
Mean CE by window, 64 GPUs:
and [Do not merge yet] Mixed midtraining on OLMo 3.5: the OLMo-core side of scaling-ladders#83 #916; the load-balancing loss differs by at most 0.0001.
largest 0.0014; load-balancing loss at most 0.0002.
Tests
batch_prefetch_test.py: the existing order, resume, live-state, error, shutdown and epoch-modetests 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, smalland 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_mapon threads and processes keeps input order, runs functionsthat 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, plainand packed, and a text-only batch.
dynamic_packing_test.py: knapsack selections with the reused table, across sizes and on fourthreads at once, equal those of a fresh table.
vision_midtraining_test.py: the recipe's depth is 8, and both process options are off bydefault and reach the loader when set.
src/test/data/multimodal/andsrc/test/internal/: all pass.How to test
🤖 Generated with Claude Code
https://claude.ai/code/session_0159PTUsp2w3YTANVDZ4BUss