Skip to content

Fix megatron_preprocess_data multi-worker segfault: use forkserver instead of fork - #2726

Merged
shengliangxu merged 7 commits into
mainfrom
shengliangx/preprocess-spawn-fix
Oct 13, 2026
Merged

shengliangxu merged 7 commits into
mainfrom
shengliangx/preprocess-spawn-fix

Conversation

@shengliangxu

@shengliangxu shengliangxu commented Oct 9, 2026 •

Copy link
Copy Markdown
Collaborator

What does this PR do?

Type of change: Bug fix

megatron_preprocess_data(..., workers>1) built its tokenization pool with the default
multiprocessing.Pool, i.e. the fork start method on Linux. Forking a process that has already
initialized CUDA is unsafe. In the failing gpu_megatron CI jobs the forked worker died with
Fatal Python error: Segmentation fault in garbage collection while the pool initializer loaded
the HF fast tokenizer
(example job).
The pool kept respawning the dying workers and the main process hung until pytest-timeout fired at
120 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:

  • Create the pool from a forkserver context and preload this module into the server
    (_worker_context()). Each worker is forked from a separate server process that never held the
    parent's CUDA objects, and the server imports torch/megatron once instead of once per worker.
    Windows has no forkserver, so it falls back to spawn, which is what the default context already
    used there.
  • The server's first start cold-imports torch/megatron, and Pool() blocks until that is done, so
    the wait would land inside the caller. _prestart_forkserver() starts the server without waiting:
    at the top of megatron_preprocess_data when workers > 1 (overlapping the tokenizer and dataset
    loading), and in a session fixture in tests/gpu_megatron/conftest.py (overlapping the earlier
    tests; the repo sets timeout_func_only, and _prebuild_quant_cuda_extensions already uses this
    pattern).
  • The workers docstring notes the if __name__ == "__main__": requirement (see Usage).

Why not fork or spawn:

  • fork: the segfault above.
  • spawn: safe, but every worker cold-imports the full torch/megatron stack. In CI that took about
    1.6 min per pool
    (job), and
    the two *_stops_at_max_tokens tests, which build two pools each, timed out at the 120 s cap.

Usage

No API change. Behavior notes:

  • With workers > 1, call from under if __name__ == "__main__":. Workers re-import the main
    script, 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 first multi-worker call in a process starts a forkserver (about 1 GB resident) that stays until
    the process exits.

Testing

CPU only (Python 3.13, CUDA hidden, tiny local tokenizer plus the cached gpt2):

  • Pre-commit hooks on the changed files: ruff, ruff-format, mypy, bandit, license.
  • workers=2 output is byte-identical to workers=1: full run over three files, max_tokens early
    stop, two calls in one process, and the python -m CLI.
  • test_megatron_preprocess_data.py under pytest on CPU: with_jsonl_path, jsonl_stops_at_max_tokens
    (workers=2), with_gzip_input, and the two new _worker_context tests pass.
  • Early start: with 25 s of earlier tests, the workers=2 test's call took 1.8 s with the fixture and
    15.0 s without. With a simulated 20 s tokenizer/dataset load, megatron_preprocess_data took 20.3 s
    with the early start and 41.5 s without. (The import takes about 14 s on a dev box; the lane is slower.)
  • Spawn fallback (get_all_start_methods reporting only spawn): identical output, no forkserver
    started.

Not run yet: the gpu_megatron lane on GPUs (Python 3.12, nemo:26.08). Kept in draft until that
validates 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"

  • Is this change backward compatible?: ⚠️ API unchanged, but scripts that call workers > 1 without an if __name__ == "__main__": guard now hang (documented in the docstring)
  • If you copied code from any other sources or added a new PIP dependency, did you follow guidance in CONTRIBUTING.md: N/A
  • Did you write any new necessary tests?: ✅
  • Did you update Changelog?: ✅
  • Did you get Claude approval on this PR?: ❌

Additional Information

Addresses the intermittent gpu_megatron failure in
test_megatron_preprocess_data_*_stops_at_max_tokens (fork after CUDA initialization). Whether it
fails depends on what ran earlier in the lane's process, which is why it passes on some runs and
segfaults on others.

…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]>
@shengliangxu
shengliangxu requested review from a team as code owners October 9, 2026 19:37
@coderabbitai

coderabbitai Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor

Review in Change Stack →

Note

Currently processing new changes in this PR. This may take a few minutes, please wait...

⚙️ Run configuration
  • Configuration used: Repository: NVIDIA/Model-Optimizer/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Enterprise
  • Run ID: 2250139b-f0c2-46de-a61c-dc56f95b7350
📥 Commits

Reviewing files that changed from the base of the PR and between b8a78dd and f977e24.

📒 Files selected for processing (4)
  • CHANGELOG.rst
  • modelopt/torch/utils/plugins/megatron_preprocess_data.py
  • tests/gpu_megatron/conftest.py
  • tests/gpu_megatron/torch/utils/plugins/test_megatron_preprocess_data.py
 ___________________________________________________________________________________________________________
< A CodeRabbit review a day keeps the merge cop away: https://x.com/ThePrimeagen/status/1986151686839116209 >
 -----------------------------------------------------------------------------------------------------------
  \
   \   (\__/)
       (•ㅅ•)
       /   づ

No actionable comments were generated in the recent review. 🎉

ℹ️ Recent review info
⚙️ Run configuration
  • Configuration used: Repository: NVIDIA/Model-Optimizer/.coderabbit.yaml
  • Review profile: CHILL
  • Plan: Enterprise
  • Run ID: f09fb642-a55b-4989-839b-dba6ce1f7f61
📥 Commits

Reviewing files that changed from the base of the PR and between 55e5788 and b8a78dd.

📒 Files selected for processing (2)
  • CHANGELOG.rst
  • modelopt/torch/utils/plugins/megatron_preprocess_data.py
🚧 Files skipped from review as they are similar to previous changes (1)
  • CHANGELOG.rst

Included review availability: This review used your included allowance. Your plan provides up to 12 included reviews per hour; 11 remain after this review.

📝 Walkthrough

Walkthrough

When workers > 1, _encode_docs now creates its process pool with the spawn start method. The single-worker inline path is unchanged. The 0.48.0 changelog records the change.

Changes

Worker start method

Layer / File(s) Summary
Use spawned workers
modelopt/torch/utils/plugins/megatron_preprocess_data.py, CHANGELOG.rst
_encode_docs now uses the spawn context for multi-worker pool creation. Its docstring describes spawned workers and the encoder’s picklable fields. The changelog records the change.

Priority: ➖ Normal

Estimated code review effort: 2 (Simple) | ~8 minutes

Change: Bug fix · Severity of issue fixed: Medium

Merge Risk: ⚪ Minimal · up to b8a78

Multi-worker preprocessing now uses spawned workers to avoid the reported fork-related crash. The checked repository callers are import-safe, and no actionable merge risk remains.

Pre-merge checks · Passed 5 · Failed 1

Failed Failed checks (1 warning)

Check name Status Explanation Resolution
Title check Warning The title describes using forkserver, but the changes use spawn. This misstates the main implementation change. Rename the pull request to state that megatron_preprocess_data uses spawn instead of fork for multi-worker processing.
Passed Passed checks (5 passed)
Check name Status Explanation
Docstring Coverage Passed Docstring coverage is 100.00% which is sufficient. The required threshold is 80.00%. Docstring coverage is scoped to functions touched by this diff. Analyzed 2 functions across 1 files. (1 skipped: 1 …
Linked Issues check Passed Check skipped because no linked issues were found for this pull request.
Out of Scope Changes check Passed Check skipped because no linked issues were found for this pull request.
Security Anti-Patterns Passed PASS. The pull request changes only CHANGELOG.rst and modelopt/torch/utils/plugins/megatron_preprocess_data.py. The Python change replaces the worker pool with `multiprocessing.get_context("spawn"…
Description Check Passed Check skipped - CodeRabbit’s high-level summary is enabled.
  • Fix all pre-merge checks with AI
✨ Finishing Touches
📝 Generate docstrings
  • Commit to this branch
  • Create a new PR
🧪 Generate unit tests (beta)
  • Commit to this branch
  • Create a new PR
  • Autofix · Keep fixing CodeRabbit findings and required CI, and resolving merge conflicts

Comment @coderabbitai help to get the list of available commands.

@github-actions

github-actions Bot commented Oct 9, 2026 •

Copy link
Copy Markdown
Contributor
PR Preview Action v1.8.1
Preview removed because the pull request was closed.
2026-10-13 00:30 UTC

@codecov

codecov Bot commented Oct 9, 2026 •

Copy link
Copy Markdown

Codecov Report

✅ All modified and coverable lines are covered by tests.
✅ Project coverage is 78.27%. Comparing base (89632ac) to head (f977e24).
⚠️ Report is 3 commits behind head on main.

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     
Flag Coverage Δ
examples-diffusers 20.29% <6.66%> (-0.01%) ⬇️
examples-gpt-oss 13.54% <6.66%> (+<0.01%) ⬆️
examples-hf_ptq 23.38% <6.66%> (-0.03%) ⬇️
examples-llm_distill 13.62% <6.66%> (+<0.01%) ⬆️
examples-llm_eval 17.33% <6.66%> (+<0.01%) ⬆️
examples-llm_qat 17.63% <6.66%> (-0.01%) ⬇️
examples-llm_sparsity 15.87% <6.66%> (+<0.01%) ⬆️
examples-megatron_bridge 26.71% <26.66%> (-0.14%) ⬇️
examples-specdec_bench 13.32% <6.66%> (+<0.01%) ⬆️
examples-speculative_decoding 17.62% <6.66%> (-0.07%) ⬇️
examples-torch_onnx 21.67% <6.66%> (-0.01%) ⬇️
examples-torch_trt 15.31% <6.66%> (+<0.01%) ⬆️
examples-vllm_serve 13.99% <6.66%> (+<0.01%) ⬆️
gpu 59.17% <100.00%> (+37.44%) ⬆️
regression 15.16% <6.66%> (-0.01%) ⬇️
unit 59.88% <6.66%> (-0.02%) ⬇️

Flags with carried forward coverage won't be shown. Click here to find out more.

☔ View full report in Codecov by Harness.
📢 Have feedback on the report? Share it here.

🚀 New features to boost your workflow:
  • ❄️ Test Analytics: Detect flaky tests, report on failures, and find test suite problems.

@cjluo-nv cjluo-nv left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

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

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 _Encoder and it holds only primitives. The tokenizer is a class attribute that initializer sets separately in each worker, so pickling it into spawned workers is safe. _is_main_or_first_worker and the per-worker _chat_template_logged still behave correctly under spawn.
  • Under spawn, each worker re-imports __main__. A user script that calls megatron_preprocess_data(workers>1) at top level, without an if __name__ == "__main__" guard, will now raise an error at startup. The in-repo callers (this module's CLI and prepare_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, datasets and megatron.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.rst entry is present.

@shengliangxu
shengliangxu marked this pull request as draft October 9, 2026 23:32
@copy-pr-bot

copy-pr-bot Bot commented Oct 9, 2026

Copy link
Copy Markdown

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]>
@shengliangxu shengliangxu changed the title Fix megatron_preprocess_data multi-worker segfault: spawn instead of fork Fix megatron_preprocess_data multi-worker segfault: use forkserver instead of fork Oct 10, 2026
shengliangxu and others added 3 commits October 10, 2026 19:29
…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]>
@shengliangxu

Copy link
Copy Markdown
Collaborator Author

/ok to test f977e24

@shengliangxu
shengliangxu marked this pull request as ready for review October 13, 2026 00:29
@shengliangxu
shengliangxu merged commit af6964c into main Oct 13, 2026
54 of 55 checks passed
@shengliangxu
shengliangxu deleted the shengliangx/preprocess-spawn-fix branch October 13, 2026 00:30
@rohansjoshi rohansjoshi added the cherry-pick-done Added by bot once PR is cherry-picked to the release branch label Oct 16, 2026
rohansjoshi added a commit that referenced this pull request Oct 17, 2026
#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]>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

cherry-pick-0.48.0 cherry-pick-done Added by bot once PR is cherry-picked to the release branch

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants