Repository navigation
Fix megatron_preprocess_data multi-worker segfault: use forkserver instead of fork - #2726
Conversation
…fork
megatron_preprocess_data with workers>1 created its tokenization pool via the default
multiprocessing.Pool, which uses the fork start method. Forking a process that has already
initialized a CUDA context or other native threads is unsafe: the child inherits the
parent's locks and half-initialized native state, and segfaults when it next touches them
(here, loading the HF fast tokenizer in the pool initializer). In a process where CUDA was
already up -- e.g. the gpu_megatron CI lane running this in-process after other GPU tests --
every forked worker died in its initializer; the pool kept respawning them and the main
process hung in pool.map(...).get() until pytest-timeout killed it at 120s.
Use multiprocessing.get_context("spawn").Pool(...) for the multi-worker path. Spawn starts
clean workers that inherit none of the parent's threads/CUDA state. _Encoder carries only
picklable fields (the tokenizer is loaded per-worker in initializer), so it crosses the
spawn boundary. The single-worker path is unchanged (still inline, no process at all). This
also aligns the module with the rest of the codebase, which already uses spawn everywhere
it creates worker processes.
Signed-off-by: Shengliang Xu <[email protected]>
|
Codecov Report✅ All modified and coverable lines are covered by tests. Additional details and impacted files@@ Coverage Diff @@
## main #2726 +/- ##
==========================================
+ Coverage 69.48% 78.27% +8.78%
==========================================
Files 647 647
Lines 71692 71706 +14
==========================================
+ Hits 49813 56125 +6312
+ Misses 21879 15581 -6298
Flags with carried forward coverage won't be shown. Click here to find out more. ☔ View full report in Codecov by Harness. 🚀 New features to boost your workflow:
|
cjluo-nv
left a comment
There was a problem hiding this comment.
Bot review (bedrock-claude-opus-5-5) — DM the bot to share feedback.
Approving: this is a small, correct fix. Switching to a spawn pool removes the fork-after-CUDA segfault, and the existing workers=2 test covers this path.
No action needed.
- I checked
_Encoderand it holds only primitives. The tokenizer is a class attribute thatinitializersets separately in each worker, so pickling it into spawned workers is safe._is_main_or_first_workerand the per-worker_chat_template_loggedstill behave correctly under spawn. - Under
spawn, each worker re-imports__main__. A user script that callsmegatron_preprocess_data(workers>1)at top level, without anif __name__ == "__main__"guard, will now raise an error at startup. The in-repo callers (this module's CLI andprepare_megatron_data_blend.py) are both guarded. It's optional, but you could mention this in the docstring. - Spawned workers start more slowly because each one re-imports
transformers,datasetsandmegatron.core. That cost is paid once per pool, and a new pool is created for each file or split, so it shouldn't matter. - The
CHANGELOG.rstentry is present.
|
Auto-sync is disabled for draft pull requests in this repository. Workflows must be run manually. Contributors can view more details about this message here. |
… the worker pool The earlier spawn change removed the fork-after-CUDA segfault but the gpu_megatron tests still timed out: a spawn worker must cold-import the full torch/megatron stack (the encode path reaches prepare_messages_for_chat_template in modelopt.torch.utils, which imports torch and torch.utils.data), and two workers doing that blow the 120s pytest-timeout. forkserver forks each worker from a separate, clean server process (so no CUDA-poisoned fork, no segfault) and we preload this module into that server, so the heavy torch/megatron import is paid once in the server and inherited by every worker -- avoiding spawn's per-worker re-import. Single-worker path unchanged (inline, no subprocess). Pending CI validation on the gpu_megatron (nemo:26.08) lane. Signed-off-by: Shengliang Xu <[email protected]>
…o shengliangx/preprocess-spawn-fix
…awn on Windows
Pool() blocks until the forkserver has finished its cold torch/megatron import, so the first
multi-worker call paid that import itself, which in the gpu_megatron lane falls inside the 120 s
per-test timeout. Start the server without waiting instead: at the top of megatron_preprocess_data
when workers > 1, so the import overlaps the tokenizer and dataset loading, and in a
session-scoped gpu_megatron fixture, so it overlaps the earlier tests.
Windows has no forkserver (get_context("forkserver") raises ValueError there), so use spawn when it
is unavailable; the early start is then a no-op. Also document that workers > 1 needs an
`if __name__ == "__main__":` guard, because workers re-import the main script.
Signed-off-by: Shengliang Xu <[email protected]>
|
/ok to test f977e24 |
#2769 #2770 #2719 #2796 #2801 #2794 #2787 #2682 #2793 #2791 #2792 #2766 #2823 #2777 #2773 #2813 #2832 #2795 #2684 #2822 #2838 #2807 #2772 #2837 #2820 (#2843) ## Cherry-picked PRs - #2647 - #2700 - #2718 - #2578 - #2580 - #2711 - #2731 - #2726 - #2697 - #2769 - #2770 - #2719 - #2796 - #2801 - #2794 - #2787 - #2682 - #2793 - #2791 - #2792 - #2766 - #2823 - #2777 - #2773 - #2813 - #2832 - #2795 - #2684 - #2822 - #2838 - #2807 - #2772 - #2837 - #2820 <!-- This is an auto-generated comment: release notes by coderabbit.ai --> ## Summary by CodeRabbit * **New Features** * Expanded quantized model export support for MXFP4, MXFP8, FP8, and additional block-quantization formats. * Added quantization support for GPT-OSS and Step-family models, plus export support for native FP8 experts. * Added chat JSONL data preparation for Megatron workflows and an option to freeze the student MTP head during distillation. * Added model recipes for Kimi, Gemma, DiffusionGemma, and GLM variants. * **Bug Fixes** * Improved ONNX quantization and export compatibility, distributed calibration consistency, and handling of packed attention caches. * Improved safe model loading and low-precision quantization accuracy. * **Documentation** * Updated the 0.48.0 changelog and guidance for data preparation and quantization recipes. <!-- end of auto-generated comment: release notes by coderabbit.ai --> Also includes a partial backport of #2656 (only the `_validate_fold_weight` hook and the `mtq.fold_weight` pre-check), which #2820 depends on. --------- Signed-off-by: Shengliang Xu <[email protected]> Signed-off-by: Rohan Joshi <[email protected]> Signed-off-by: Juhi Mittal <[email protected]> Signed-off-by: Fridah-nv <[email protected]> Signed-off-by: Chenjie Luo <[email protected]> Signed-off-by: yingguo-trt <[email protected]> Signed-off-by: weimingc <[email protected]> Signed-off-by: Yue <[email protected]> Signed-off-by: joe-nv <[email protected]> Signed-off-by: ajrasane <[email protected]> Signed-off-by: Ajinkya Rasane <[email protected]> Signed-off-by: ColinM-sys <[email protected]> Signed-off-by: Keval Morabia <[email protected]> Signed-off-by: Meng Xin <[email protected]> Signed-off-by: gcunhase <[email protected]> Signed-off-by: Chad Voegele <[email protected]> Co-authored-by: Shengliang Xu <[email protected]> Co-authored-by: Claude Opus 5 (1M context) <[email protected]> Co-authored-by: Juhi Mittal <[email protected]> Co-authored-by: Frida Hou <[email protected]> Co-authored-by: Chenjie Luo <[email protected]> Co-authored-by: yingguo-trt <[email protected]> Co-authored-by: Wei-Ming Chen <[email protected]> Co-authored-by: yueshen2016 <[email protected]> Co-authored-by: joe <[email protected]> Co-authored-by: Ajinkya Rasane <[email protected]> Co-authored-by: Colin McDonough <[email protected]> Co-authored-by: Keval Morabia <[email protected]> Co-authored-by: mxinO <[email protected]> Co-authored-by: Gwena Cunha <[email protected]> Co-authored-by: Chad Voegele <[email protected]>
What does this PR do?
Type of change: Bug fix
megatron_preprocess_data(..., workers>1)built its tokenization pool with the defaultmultiprocessing.Pool, i.e. the fork start method on Linux. Forking a process that has alreadyinitialized CUDA is unsafe. In the failing
gpu_megatronCI jobs the forked worker died withFatal Python error: Segmentation faultin garbage collection while the poolinitializerloadedthe HF fast tokenizer
(example job).
The pool kept respawning the dying workers and the main process hung until
pytest-timeoutfired at120 s. The crash is state-dependent: roughly 4% of lane runs in 10-02..10-08 and none before, because
the tests run late in the lane, after in-process CUDA tests.
Fix:
forkservercontext and preload this module into the server(
_worker_context()). Each worker is forked from a separate server process that never held theparent's CUDA objects, and the server imports torch/megatron once instead of once per worker.
Windows has no
forkserver, so it falls back tospawn, which is what the default context alreadyused there.
Pool()blocks until that is done, sothe wait would land inside the caller.
_prestart_forkserver()starts the server without waiting:at the top of
megatron_preprocess_datawhenworkers > 1(overlapping the tokenizer and datasetloading), and in a session fixture in
tests/gpu_megatron/conftest.py(overlapping the earliertests; the repo sets
timeout_func_only, and_prebuild_quant_cuda_extensionsalready uses thispattern).
workersdocstring notes theif __name__ == "__main__":requirement (see Usage).Why not
forkorspawn:fork: the segfault above.spawn: safe, but every worker cold-imports the full torch/megatron stack. In CI that took about1.6 min per pool
(job), and
the two
*_stops_at_max_tokenstests, which build two pools each, timed out at the 120 s cap.Usage
No API change. Behavior notes:
workers > 1, call from underif __name__ == "__main__":. Workers re-import the mainscript, so a script without the guard now hangs (the pool keeps respawning workers that die on the
re-import), where it ran under fork. In-repo callers are guarded.
the process exits.
Testing
CPU only (Python 3.13, CUDA hidden, tiny local tokenizer plus the cached
gpt2):workers=2output is byte-identical toworkers=1: full run over three files,max_tokensearlystop, two calls in one process, and the
python -mCLI.test_megatron_preprocess_data.pyunder pytest on CPU:with_jsonl_path,jsonl_stops_at_max_tokens(
workers=2),with_gzip_input, and the two new_worker_contexttests pass.workers=2test's call took 1.8 s with the fixture and15.0 s without. With a simulated 20 s tokenizer/dataset load,
megatron_preprocess_datatook 20.3 swith the early start and 41.5 s without. (The import takes about 14 s on a dev box; the lane is slower.)
get_all_start_methodsreporting onlyspawn): identical output, no forkserverstarted.
Not run yet: the
gpu_megatronlane on GPUs (Python 3.12, nemo:26.08). Kept in draft until thatvalidates the change. Given the roughly 4% crash rate, one green run proves little, so it needs
repeated runs.
Before your PR is "Ready for review"
workers > 1without anif __name__ == "__main__":guard now hang (documented in the docstring)CONTRIBUTING.md: N/AAdditional Information
Addresses the intermittent
gpu_megatronfailure intest_megatron_preprocess_data_*_stops_at_max_tokens(fork after CUDA initialization). Whether itfails depends on what ran earlier in the lane's process, which is why it passes on some runs and
segfaults on others.