Repository navigation
Pipeline parallel: per-stage sharded loading (load models larger than one GPU) - #15656
Conversation
… zero bubble, ZBV, DualPipeV) apply_pipeline_parallel accepts every torch.distributed.pipelining schedule. Multi-stage schedules cut pp x PPConfig.stages_per_rank stages (default 2) and keep several per rank, looped (r, r + pp, ...) or V (r, 2 pp - 1 - r). Every local stage runs the same model with only its own layers active, so parameter names, adapter keys and the 1-GPU LoRA initialization do not change. The torch schedule is built on parameter-free placeholder stages before the model is cut, so its micro-batch checks run first, and its compute order decides the gradient checkpointing gates: a rank running a forward after a backward needs zoo host slot leases (as 1F1B), and zero-bubble input / weight backward splits need non-reentrant checkpointing or none. Several stages per rank with native FSDP2 over a dp mesh is refused before the cut; pp x tp composes.
…under multi-stage schedules
… gated on torch support num_items_in_batch reaches every stage forward from the stage context instead of a schedule kwarg: torch 2.10's split backward (zero bubble) treats every kwarg as a stage input and fails on the int. V schedules (ZBVZeroBubble, DualPipeV) need PipelineStage's same-rank adjacent stage handling (torch 2.13+); older torch is refused before the model is cut. The compute-order check reads action kinds by name (int values on torch 2.10).
Inside pipeline_sharded_loading(pp_mesh, schedule, config) every transformers from_pretrained builds the model on meta, derives the split apply_pipeline_parallel will use and reads from the safetensors checkpoint only this rank's stages' layers, the norms, and the embedding / output head where their stage lives; every other weight is a storage-free placeholder. get_peft_model attaches LoRA with the 1-GPU init, and apply_pipeline_parallel checks the split is the loaded one before it cuts the model (refused otherwise, together on every rank for a trainable placeholder embedding / head). A forward before the split is refused. 16-bit checkpoints only. The load peak per rank is its stages, not the whole model, so a model larger than one GPU can be split.
…eStage gained same-rank stages
…refuses V placement
…hout donated buffers Split-backward schedules (InterleavedZeroBubble, ZBVZeroBubble, DualPipeV) run the input pass as torch.autograd.grad(..., retain_graph = True). Unsloth compiles every decoder block, and AOTAutograd's compiled backward with donated buffers refuses retain_graph (Kaggle T4, torch 2.14.1: 'compiled with non-empty donated buffers'), so apply_pipeline_parallel turns torch._functorch.config.donated_buffer off for those schedules before the first forward. Tests: the setting per schedule, and zero bubble over torch.compile'd decoder layers on CPU.
…LoRA kernels A split backward runs the graph twice (input pass, then weight pass); the fused LoRA_QKV / LoRA_O / LoRA_MLP backward reuses saved activations in place, so the weight pass fails on a modified saved tensor (Kaggle T4, torch 2.14.1). Refused before the model is cut with a pointer to interleaved1f1b; full-backward schedules keep the fused kernels.
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. |
|
@codex review |
|
@codex review |
There was a problem hiding this comment.
💡 Codex Review
Here are some automated review suggestions for this pull request.
Reviewed commit: d21505fa9f
ℹ️ 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".
If Codex has suggestions, it will comment; otherwise it will react with 👍.
Codex can also answer questions or update the PR. Try commenting "@codex address that feedback".
| trainable = [ | ||
| n | ||
| for module, held in zip((parts.embed, parts.lm_head), holds) | ||
| if not held | ||
| for n, p in module.named_parameters() | ||
| if p.requires_grad |
There was a problem hiding this comment.
Check trainable decoder placeholders before synchronizing weights
When LoRA also trains decoder norms through modules_to_save=["input_layernorm"] with an unchanged stage split, this check passes because it examines only the embedding and head. However, _materialize replaced every nonlocal decoder parameter, including those norms, with zeros, so PEFT creates checkpoint-derived trainable copies from placeholders. With the default sync_trainable=True, _sync_trainable then broadcasts rank 0's zero copies over the real norms on later stages, corrupting their initialization before training (the fp16 Unsloth path converts these trainable copies to ordinary fp32 tensors). Check checkpoint-derived trainables inside decoder layers too, and either refuse this configuration collectively or synchronize them from the stage that actually loaded their weights.
Useful? React with 👍 / 👎.
There was a problem hiding this comment.
Confirmed: with modules_to_save=["input_layernorm"] (and likewise DoRA magnitudes or trainable token rows), rank 0's copies of later-stage layers are built from zero placeholders, and the sync broadcast them over the owning stage's real values, so training drifted from a full load. Fixed in 5355005 without a refusal: the trainable sync now knows which pp ranks read each decoder layer, the embedding and the head (pp_load.loaded_by). Tensors under those modules are synced only among the ranks that loaded them (from the lowest owner), and a single owner keeps its own copy, since every other stage drops that module at the split. This also replaces the old trainable embedding / head refusal. New gloo cases (input_layernorm on 2 ranks, input_layernorm plus lm_head on 4 ranks, DoRA with Interleaved1F1B, trainable tokens with 1F1B) match a full load bitwise in losses, grads and weights; the first and third drift on the previous head.
…ubble schedules [skip ci]
…ded them modules_to_save copies, DoRA magnitudes and trainable token rows built on a rank that only holds a placeholder are zeros; sync_trainable broadcast pp rank 0's copy over the owning stage's real one (e.g. input_layernorm of later stages). Parameters under a decoder layer, the embedding or the head are now synced only among the pp ranks that read them (a single owner keeps its own), which also replaces the trainable embedding / head refusal.
|
@codex review |
1 similar comment
|
@codex review |
…loo shard stays under its 2100 s cap
…ded (#15915) `(Python 3.13, g-r)` on #15656's staging run failed a test #15656 does not touch: ``` tests/test_managed_engines_rocm.py:613: in test_a_startup_timeout_names_where_the_engine_stalled with pytest.raises(RuntimeError, match = "(?s)timed out.*JIT kernel warmup finished"): E Failed: DID NOT RAISE RuntimeError ``` It passes on main when run alone. ## Cause The fake engine in that test never listens; it prints a line and sleeps. The only way `ManagedEngine._start_once` returns instead of timing out is a `200` from `GET {base_url}/health`. `managed_engine._free_port()` binds port 0, reads the port and closes the socket, so the port goes back to the ephemeral pool before the engine is spawned. Any `bind(0)` on the runner in that gap can be handed the same port. On a busy runner that is mostly another xdist worker's test server, and its 200 on `/health` turns a start that must time out into "ready". About a dozen engine tests depend on nothing answering. A plugin that hands the released ephemeral port to a listener answering 200 (only ephemeral ports, since only those can reach another `bind(0)`) fails these on main: - `test_a_startup_timeout_names_where_the_engine_stalled` - `test_rocm_engine_sees_one_device_mask_and_its_own_memory_budget` - `test_server_outlives_short_lived_start_thread` - `test_startup_deadline_counts_engine_silence` - `test_vllm_does_not_retry_other_failures_or_twice` - `test_vllm_drafter_retry_respects_an_external_stop` - `test_vllm_mamba_retry_respects_a_cancelled_load` - `test_vllm_mamba_retry_respects_an_external_stop` - `test_vllm_relaunches_at_the_tightest_data_parallel_rank` - `test_vllm_relaunches_once_at_the_mamba_block_count` - `test_vllm_retries_once_without_a_drafter_that_breaks_startup` ## Fix A backend conftest autouse fixture replaces `managed_engine._free_port` during tests. Each xdist worker gets its own block of 250 ports from 21000 up. That is below the ephemeral range on Linux (32768+), macOS and Windows (49152+), so `bind(0)` never hands those ports out, and two workers never share one. The two tests of the allocator itself request the new `real_engine_free_port` fixture and get the real function back: - `test_engine_port_stays_below_the_limit_when_the_os_offers_high_ports` - `test_only_sglang_reserves_space_for_its_derived_port` New guard, `test_the_suite_hands_engines_ports_no_other_process_can_be_given`: the ports engines get in the suite are in that block. Against main's conftest it fails (`43577`). ## Verification | run | main `9258bfc732` | this branch | |---|---|---| | `test_managed_engines.py` + `test_managed_engines_rocm.py`, `-n 8` with the port-stealing plugin | 12 failed, 251 passed (twice) | 263 passed (three times) | | the same two files, normal | | 263 passed | | every backend test file that touches `managed_engine` (24 files), `-n 16` | | 2381 passed, 5 skipped | ## Cross-platform run of this branch `test_engine_ports.py` + `test_managed_engines_rocm.py` on the staging cross-platform legs, including the new guard: - `ubuntu-latest`: 40 passed - `macos-15`: 20 passed, 20 skipped - `windows-latest`: 20 passed, 20 skipped The skips are the Linux-only tests of the ROCm file. ## Not changed The product side of this: a foreign listener that answers `/health` on the port Studio picked is taken as the engine. In real use the window is milliseconds and needs another local process to bind that port in it. `llama_cpp._find_free_port` already notes the same gap. A real fix would have the engine report its pid on `/health` or bind the port itself, which is a separate change.
|
@codex review |
|
Codex Review: Didn't find any major issues. Hooray! Reviewed commit: ℹ️ About Codex in GitHubYour team has set up Codex to review pull requests in this repo. Reviews are triggered when you
If Codex has suggestions, it will comment; otherwise it will react with 👍. Codex can also answer questions or update the PR. Try commenting "@codex address that feedback". |
Conflicts in .github/workflows/studio-backend-ci.yml and tests/studio/test_backend_ci_parallel_isolation.py: main already moved the pipeline parallel gloo files (test_pp*) into their own gloo-tp-pp shard, which also picks up tests/test_pp_schedules_gloo.py, so main's version is kept for both. [skip ci]
unsloth/models/pp_native.py: main's copy equals dh/s9-par-interleaved as merged (its squash), so this branch's version, which builds on it, is kept. [skip ci]
…shards (#16634) ## Summary `Repo tests (CPU, gloo-tp-pp)` is at its 2100 s cap. On #16618, which only touches the Studio MLX worker, it was interrupted with the suite almost done: ``` !!!!!!!!!!!!!!!!!!!!!!!!!!!!!! KeyboardInterrupt !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! 174 passed, 7 skipped, 79 warnings, 320 subtests passed in 2088.59s (0:34:48) ##[error]Process completed with exit code 124. ``` The other recent runs of that job, across the last 20 PRs, took 30.5 to 36.2 minutes end to end, setup included, so a slightly slower runner is enough to tip it over. When this shard was created (#15951 split, #16447 comment) tensor plus pipeline parallel were about 1397 s. Pipeline parallel has grown a lot since then: every `torch.distributed.pipelining` schedule (#15655), per-stage sharded loading (#15656), no graph break on a non-last stage (#16167), and explicit-unscale overflow agreement (#16417). Nothing is wrong with those tests. The shard just outgrew its slot, the same way `gloo` did in #15951 and #16447. ## Change - `.github/workflows/studio-backend-ci.yml`: `gloo-tp-pp` becomes two shards with the same settings (`-n 4`, the 2100 s cap, the marker filter): - `gloo-tp`: `tests/test_tp_n*gloo*.py` (2 files); - `gloo-pp`: `tests/test_pp*gloo*.py` (8 files). - `tests/studio/test_backend_ci_parallel_isolation.py`: `test_the_command_scan_sees_the_parallel_run_and_the_serial_steps` pins the number of parallel pytest runs. It asks to be told when a shard is added, so its counts go from 12 to 13 parallel runs and from 9 to 10 repo-root shards. The selections are the old one split in two, so every file still runs exactly once. ## Testing - `tests/test_ci_repo_cpu_shards.py`: 15 passed. With `test_pp*gloo*` narrowed to `test_pp_[!n]*gloo*` as a sabotage, `test_no_file_is_dropped_or_run_twice` fails, so a dropped file is still caught. - `tests/studio/test_backend_ci_parallel_isolation.py`, `tests/test_ci_repo_cpu_shards.py` and the workflow and cache-budget guards under `tests/studio`: 164 passed. - The two new shards' run times on this PR's own CI are the real check. Both should finish well under the cap.
Stacked on the multi-stage schedules PR (
dh/s9-par-interleaved); merge that first.Today every rank loads the whole model, then
apply_pipeline_paralleldrops the other stages' layers, so the loadpeak is the full model on every GPU and pipeline parallelism cannot split a model that does not fit one GPU, which
is its main use on small cards. torchtitan and NeMo Automodel load each stage on its own; this does the same for any
model Unsloth can split:
(
load_pipeline_parallel(name, mesh["pp"], schedule, config, **kwargs)is the one-call form.)How
tp_native._sharded_from_pretrained): the model is built onmeta, the split
apply_pipeline_parallelwill use is derived from the weight shapes (LoRA added later does notmove it), and each rank reads only its stages' decoder layers, the norms, and the embedding / output head where
their stage lives (tied pairs where either end lives). Every other weight is a storage-free placeholder of the
right shape, dtype and device, so get_peft_model attaches full-size LoRA with the 1-GPU initialization.
apply_pipeline_parallelchecks the split is the loaded one (mesh ranks, schedule, stages per rank, layerranges) before it cuts the model, and refuses, on every rank together, a trainable embedding / head on a rank that
did not load it (pp rank 0's placeholder copy would be broadcast over the real one). A forward before the split is
refused. 4-bit / pre-quantized checkpoints are refused (QLoRA keeps the full-load path).
New file
unsloth/models/pp_load.py;pp_native.apply_pipeline_parallelgains the split check and guard release.Tests
tests/test_pp_load_gloo.py(CPU gloo, 2 and 4 ranks): Llama GPipe pp 2 / pp 4 (middle ranks hold neither end),Qwen3 1F1B, Gemma3 tied, interleaved 1F1B, ZBV with tied embeddings. Per rank: the loaded parameter count equals
exactly what that rank's stage keeps after a full load is split, memory after the split equals the full-load split,
LoRA init and every tensor bitwise equal, 3 training steps bitwise equal (losses and gradients); refusals (another
split, another
layers_per_stage, trainable placeholder head, 4-bit, unknown schedule). 7 passed; on origin/mainthe module does not exist. Mutants (read everything, no split check, first local stage only, guards kept, embedding
read on every rank): 5 / 5 killed.
GPU, Kaggle T4x2:
pipeline_sharded_loadingNot covered