DeepSpeed icon indicating copy to clipboard operation
DeepSpeed copied to clipboard

[RFC] Cleanup: move process-wide parallel-group globals to per-engine groups — follow-up to #8241 / #8851

Open jinyouzhi opened this issue 2 weeks ago • 12 comments

Summary

DeepSpeed keeps an engine's tensor-parallel and data-parallel process groups as module globals in deepspeed/utils/groups.py. The first engine that sets them up decides them for every later engine in the process. This RFC proposes that each engine own its groups again, as it did before the global registry existed.

This continues two earlier fixes:

  • #8241 (fixing #8231) moved the AutoTP shape state (num_kv_heads, n_embd, tp_grain_size, ...) from tp_shard globals onto a per-model AutoTPMeta.
  • #8851 made the AutoTP training/inference mode per model instead of the process-wide DEEPSPEED_AUTOTP_MODE.

The process groups are the remaining process-wide state of this kind. They are also what flexible TP/DP redistribution needs: a trainer and a rollout, or the same trainer before and after a resize, living in one process with different layouts.

I found no existing issue or PR for this. I'd like the maintainers' view on whether and how to change it before writing code.

Why it matters now

Several pieces of open work need two engines with different layouts in one process:

  • RFC #9026, live TP/DP redistribution. Moving weights and training state between layouts without a checkpoint assumes both layouts exist side by side.
  • deepspeedai/DeepSpeedExamples#1021. It moves training state across DP, ZeRO stage, AutoTP size and AutoEP size mid-training (results, 8× H20). To build a second AutoTP engine, it works around the globals:
    • before each deepspeed.initialize, it clears _TENSOR_MODEL_PARALLEL_GROUP and _DATA_PARALLEL_GROUP;
    • it saves _TENSOR_MODEL_PARALLEL_GROUP, _MODEL_PARALLEL_GROUP, _DATA_PARALLEL_GROUP, _MPU_TENSOR_MODEL_PARALLEL_*, mesh_device and mpu per engine, and writes them back before that engine trains again.
  • #9074 / #9076 (training-state move, ZeRO-3 DP4 → DP2 → DP4).
    • #9076 moves ZeRO-3's rank-agreement checks and barriers from the world to the partition group, so a ZeRO-3 engine can run on a subset of the ranks. That is the same class of problem, for ZeRO-3's checks.
    • #9074 changes only the DP size, so it does not reach the TP globals; its known limits list TP, ZeRO-1/2 and EP as not covered.
  • #9045 (AffineWeightSync) already takes an explicit group, and autotp_storage_affine_maps(model, tp_group=...) takes an explicit TP group. The explicit-group style exists; the engine is what does not follow it.

How it got here

  • Before August 2021, the engine took a user mpu (for example Megatron's), kept it in self.mpu, and kept its own self.data_parallel_group. Nothing about the layout was process-wide.
  • #1310 (MoE, August 2021) added deepspeed/utils/groups.py as a registry of expert groups.
  • #1798 (February 2022) began copying the engine's mpu into the module: groups.mpu = self.mpu, "For subsequent use, just query groups".
  • #7004 (AutoTP training, February 2025) made the module itself the engine's mpu: self.mpu = groups, followed by self.mpu._init_tp_mesh_device(...), which sets the module's TP/DP groups and mesh.

So the proposal is mostly a return to the earlier design, keeping what the registry added.

What happens today

_init_tp_mesh_device returns early if _TENSOR_MODEL_PARALLEL_GROUP is already set. A second engine with another autotp_size therefore silently uses the first engine's groups.

Reproducer (4 ranks)
import sys, torch, transformers, deepspeed
import deepspeed.comm as dist
from deepspeed.utils import groups


def engine(tp):
    torch.manual_seed(0)
    cfg = transformers.LlamaConfig(vocab_size=64, hidden_size=64, intermediate_size=128, num_hidden_layers=2,
                                   num_attention_heads=4, num_key_value_heads=4, use_cache=False,
                                   tie_word_embeddings=False)
    m = transformers.LlamaForCausalLM(cfg)
    ds = {"train_micro_batch_size_per_gpu": 1, "bf16": {"enabled": True}, "zero_optimization": {"stage": 1},
          "optimizer": {"type": "Adam", "params": {"lr": 1e-3, "torch_adam": True}},
          "tensor_parallel": {"autotp_size": tp}}
    return deepspeed.initialize(model=m, model_parameters=m.parameters(), config=ds)[0]


def show(tag, e):
    w = e.module.model.layers[0].self_attn.q_proj.weight
    if dist.get_rank() == 0:
        print(tag, "autotp_size", e.autotp_size(), "mpu tp", e.mpu.get_tensor_model_parallel_world_size(),
              "q_proj", tuple(w.shape))


deepspeed.init_distributed()
a = engine(2)
if sys.argv[1] == "release":  # what DeepSpeedExamples#1021 does before building the second engine
    groups._TENSOR_MODEL_PARALLEL_GROUP = groups._DATA_PARALLEL_GROUP = None
b = engine(4)
show("B", b)
show("A", a)

Run with torchrun --nproc_per_node 4:

Case Engine autotp_size engine.mpu TP size q_proj shard on a rank
B built alone B 4 4 (16, 64)
A (TP2), then B (TP4) B 4 2 (32, 64): B is a TP2 model; its 3-step losses equal A's
A, clear the globals, then B B 4 4 (16, 64)
A 2 4 (32, 64)
  • In the second case, B is not what its config asks for, and nothing warns.
  • In the third case, B is right, but A now reports TP4 for its TP2 shards.
    • A's training steps and checkpoint file names were still correct in this small test: AutoTP layers keep their own group, and ZeRO took its DP group at initialize.
    • Every path that queries groups or engine.mpu later reads B's groups. That is why #1021 saves and restores the globals per engine.

What reads and writes the globals

Writers (all in deepspeed/utils/groups.py unless noted):

  • _init_tp_mesh_device and _init_tp_groups_with_new_group: _TENSOR_MODEL_PARALLEL_GROUP, _MODEL_PARALLEL_GROUP, _DATA_PARALLEL_GROUP.
  • mesh_device; also assigned in engine.py (groups.mesh_device = self.mesh_device).
  • mpu, assigned in engine.py (groups.mpu = self.mpu).
  • _MPU_TENSOR_MODEL_PARALLEL_WORLD_SIZE / _RANK.
  • The expert and expert-data-parallel tables (_EXPERT_PARALLEL_GROUP, ...). These are keyed by name (ep_size_N), so two EP sizes can coexist. They are listed for completeness.

Readers outside groups.py (on master 84481c333; about 48 references in 13 files):

Area Where Reads
Engine engine.py: 13 places, including the dataloader check, tp_config.tp_group, rank getters, checkpoint tp_rank, AutoEP folding TP group, rank and size; DP rank; mpu
ZeRO / BF16 stage_1_and_2.py, stage3.py (2), bf16_optimizer.py TP group for AutoEP folding; in stage3.py also for the universal-checkpoint load of AutoTP shards
AutoTP auto_tp.py (set_tensor_parallel_config in training mode), tp_manager.py (2) TP group and its source rank
Checkpoint model_checkpointing/utils.py (3), checkpoint/zero_affine.py (default tp_group) mpu, TP group
MoE / AutoEP moe/sharded_moe.py, moe/mappings.py, moe/layer.py, auto_ep_layer.py mpu, TP group
Compile compile/custom_ops/tp_collectives.py TP group

Open PRs that add readers. #9037 (multi-turn tool-calling rollout, draft) reads the global TP group in runtime/rollout/hybrid_engine_rollout.py:

  • _host_tensor_parallel_group() builds Gloo groups over groups.get_tensor_model_parallel_group() and uses groups.get_tensor_model_parallel_src_rank() as the rank that forwards tool output;
  • _sync_rng_across_tp() broadcasts the RNG state over the same group.

The rollout takes its TP size from engine.autotp_size() but the group from the module. Next to a trainer with another TP size, both would run over the first engine's groups. Reading engine.mpu instead would not help on master, since under AutoTP engine.mpu is the groups module itself. With stage 2 (#9120), engine.mpu is the engine's own groups object, so these readers can move to it.

Options

  1. Keep the globals; document a supported way to switch.
    • Make what #1021 and #9074 do external, for example a public groups snapshot/activate API.
    • Smallest change, but every engine switch must remember to activate, and any reader that runs at the wrong time reads the other engine's groups without an error.
  2. Each engine owns its groups (return to the pre-2022 design).
    • _init_tp_mesh_device builds a small per-engine object with the same interface as today's mpu. engine.mpu points to it instead of to the module.
    • The readers above take the group from their engine or layer, as #8241 and #8851 did for shape and mode.
    • The groups.get_* functions remain for compatibility and keep returning the first engine's groups, as today. Single-engine users see no change.
  3. A guard only: raise if a second initialize asks for a different autotp_size than the existing groups. This fixes the silent misconfiguration but does not enable two layouts.

My preference is 2, with 3 as an immediate first step, done in stages:

  1. The guard (option 3), plus a test that builds TP2 and TP4 engines in one process.
  2. Per-engine group object; engine.py, ZeRO and AutoTP readers move to it.
  3. Checkpoint and zero_affine readers.
  4. MoE / AutoEP and compile readers.
  5. Group lifetime: destroy an engine's groups with it, share groups between engines, replace them in place.

Each stage keeps the module getters working, so it can merge on its own.

Roadmap and status

Updated after the discussion below: @LiRunGuo and @Achyuthan-S both support option 2, with the guard first.

The ZeRO-3 rank-agreement checks (process-wide ids, trace state) are tracked in #9098 and fixed in a separate PR by Achyuthan-S; stage 2 (#9120) does not touch them.

Stage Scope Owner Status
1. Guard Raise when a later engine asks for another TP layout, including an engine without AutoTP and without its own mpu (@Achyuthan-S). Test with TP2/TP4 engines in one process. @jinyouzhi #9088 (in review)
2. Per-engine groups Per-engine group object; engine.py, ZeRO, BF16 and AutoTP readers move to it. This includes _reduce_non_expert_gradients and the DP case @LiRunGuo reported: an engine without an mpu takes the previous engine's groups.mpu. The rollout readers of #9037 belong here too. @jinyouzhi #9120 (draft, on top of #9088). Every AutoTP engine's engine.mpu is its own groups object; with the process-wide layout it holds the process-wide groups, so no communicator is added. An engine without an mpu no longer inherits an earlier engine's, and an engine can share another's groups with mpu=other.mpu. Tested with #9074's DP4 → DP2 → DP4 order. An engine on groups other than the process-wide ones still raises for mesh_param, AutoEP, the DeepCompile autotp pass and MoE (stage 4). The #9037 readers move once #9037 merges. @LiRunGuo offered to run it against #9074's tests
3. Checkpoint readers model_checkpointing/utils.py, the default tp_group of zero_affine.py, and the universal-checkpoint load of AutoTP shards in stage3.py @Achyuthan-S #9098
4. MoE / AutoEP, compile sharded_moe.py, mappings.py, moe/layer.py, auto_ep_layer.py, tp_collectives.py open not started
5. Group lifetime An owner and a reference count per group: an engine destroys the groups it created when it goes away, unless another engine shares them; groups passed in as mpu stay with their creator; the process-wide groups are never destroyed. Then, optionally, reuse groups automatically by layout (DeepSpeed creates groups without options, so equal ranks give equivalent groups). An API to replace an engine's groups in place, for what #9074's Zero3Repartition does by hand. open not started. Until then, sharing is explicit (mpu=other.mpu) and no group is destroyed

Related, outside these stages:

  • Membership changes: with stage 2, groups belong to their engine; stage 5 lets them be destroyed when it goes away. Rebuilding the world after a rank leaves, and use_local_synchronization, belong to the membership side of the elastic design.

Questions for the maintainers

@delock @tohtana @tjruwase (cc @LiRunGuo @Achyuthan-S from #9026)

  1. Should DeepSpeed support several engines with different TP/DP layouts in one process, or keep the process-wide registry and leave switching to external code (as #1021 and #9074 do now)?
  2. If supported: is returning to engine-owned groups (option 2) the right direction, or is an official snapshot/activate API (option 1) preferred?
  3. In stages as above, or as one change?
  4. Should the module getters (groups.get_tensor_model_parallel_group() and the rest) stay as they are, or become deprecated in favor of the engine's groups?

Tested on: 4× Intel Arc Pro B70 (XPU, oneCCL), torch 2.14.0.dev20260804+xpu, transformers 5.17.0, DeepSpeed master 84481c333. The #1021 results above were on 8× NVIDIA H20.

This RFC was drafted with AI assistance. I checked the code references and ran the reproducer myself.

jinyouzhi avatar Nov 13 '26 16:11 jinyouzhi

Thanks for writing this up, @jinyouzhi. Three data points for the RFC, from #9074 / #9076:

The DP side. engine.py copies an engine's mpu into groups.mpu when one is given, and groups._get_data_parallel_group() returns that mpu's group. An engine initialized without an mpu after one with an mpu silently takes the earlier engine's DP group. In #9074's first DP4 ↔ DP2 test, the engine over all ranks came out over a subgroup on some ranks and over the world on others, and its first collective hung. #9074 works around it by giving every engine its own mpu, including the one over all ranks. That is enough for ZeRO-3, which takes its DP group at initialize. It would not be enough for an engine whose gradient all-reduce goes through _reduce_non_expert_gradients, which asks groups at every step.

Process-wide ids. ZeRO-3 numbers modules and parameters with process-wide counters (_register_deepspeed_module(self, module, count=[0]) and zero.Init.param_id), and the trace checks compare the raw ids. A new engine whose ranks have built different numbers of ZeRO-3 modules or parameters before fails its first trace check ("disagreement on list contents"). #9074 hit this and builds the widest engine first; @Achyuthan-S described it on #9076. It is the same kind of process-wide state, so it may belong in this RFC's list or next to it. One direction, untested: compare each id's position among the engine's own ids instead of the process-wide number.

Membership changes. Both get stricter when the set of ranks changes during a job. A joining process starts with no groups.mpu and its counters at 0, while the survivors keep theirs. After a rank leaves, any group still held in the globals contains it. Option 2 lets a new engine own groups over the new membership and lets the old ones be destroyed with the old engine; the ids would need the same per-engine treatment.

+1 for option 2 with the guard first. I can run stage 2 against #9074's DP4 → DP2 → DP4 test when it is up.

LiRunGuo avatar Nov 14 '26 15:11 LiRunGuo

Thanks @jinyouzhi, +1 for option 2 with the guard first. Two points from the affine-IR side:

  • Where the guard sits. engine.py builds the TP groups only when autotp_size() > 1, so an engine with autotp_size 1 that comes after a TP2 engine never reaches _init_tp_mesh_device. Its get_tensor_parallel_rank() and get_model_parallel_rank() still read the module's groups, so they return the TP2 engine's ranks; built alone, the same calls fail the "not initialized" assertion. That is from reading the code, not a run. A guard in initialize that compares the requested TP size, 1 included, with the groups already set would cover this case too.
  • A reader I touch. When the ZeRO-3 universal-checkpoint load slices an AutoTP shard, it takes the TP group from groups (stage3.py, from #8168), and #9069 sends more loads down that path. I can move that one onto the engine's group in the checkpoint stage.

On the counters @LiRunGuo mentions: I'll open them as their own issue with a reproduction, as promised on #9076, and link it here. They need a per-engine fix inside ZeRO-3, next to stage 2.

Achyuthan-S avatar Nov 14 '26 23:11 Achyuthan-S

@jinyouzhi and team, thanks for the great discussion here. I am aligned with option 2, independent engines per process. This is a feature that we have previously supported, but somehow seems to have suffered regressions.

- Independent engines per process

  1. DS Chat - A key feature was the ability to create independent actor, reference, critic, etc.
  2. HF multi-model training: https://huggingface.co/docs/accelerate/en/usage_guides/deepspeed_multiple_model

- Eliminating process-wide Globals This is a very worthy cause with a long history. Any progress here would be extremely useful.

  1. Diffusers: https://github.com/huggingface/diffusers/pull/3076
  2. ZeRO3: https://github.com/deepspeedai/DeepSpeed/pull/2989, https://github.com/deepspeedai/DeepSpeed/pull/3592

sfc-gh-truwase avatar Nov 17 '26 15:11 sfc-gh-truwase

Thanks @sfc-gh-truwase, and thanks for the history and links. I fully agree: this is more than restoring a basic capability, it is, as you put it, a very worthy cause with a long history. DS-Chat's actor, reference and critic, and Accelerate's multi-model setup will be the regression cases. Beyond them, the goal is for each engine to own its parallel groups and its process-wide state, so that engines in one process can use different TP/DP layouts, and an engine can be torn down and rebuilt when the set of ranks changes. That is what RL weight sync, #9074's DP4 → DP2 → DP4 switch and elastic jobs need. I'll read #2989 / #3592 before touching ZeRO-3.

On the guard, #9088:

  • It already covers @Achyuthan-S's case. A later engine with autotp_size 1 and no mpu of its own is checked against the cached TP groups, and test_different_tp_size_raises[1] covers it.
  • A later engine that passes its own mpu replaces groups.mpu and is not refused.
  • I'll mark #9088 ready for review.

Next steps:

  • Stage 2: move the process-wide group readers onto the engine's own groups, with @LiRunGuo's DP4 → DP2 → DP4 test as the first multi-engine check.
  • ZeRO-3 ids: the per-engine fix for the process-wide ids in #9098 (thanks @Achyuthan-S) is in scope for this RFC, next to stage 2. I'll add it to the list.

jinyouzhi avatar Nov 17 '26 15:11 jinyouzhi

Thanks @sfc-gh-truwase for the direction and the history, and @jinyouzhi for the plan. For stage 2, these are the multi-engine checks on our side, all in #9074 now:

  • tests/unit/runtime/rollout/test_zero3_repartition.py (4 ranks, added to #9074 today) is the DP4 → DP2 → DP4 test. On ranks 0 and 1 it holds four ZeRO-3 engines, each with its own mpu:
    • one engine re-partitioned in place (Zero3Repartition);
    • the two-engine path, engines over four ranks and over two with the state moved between them (Zero3StateMove);
    • a plain four-rank engine as the oracle.
  • tests/unit/runtime/rollout/test_native_rollout.py::TestTrainerSwitch (2 ranks) moves a trainer between rank 0 alone and both ranks, with two engines per process.

Two things in that code that stage 2 should make unnecessary:

  1. Every engine gets its own TrainerMPU, made on every rank, with the engine over all ranks built first. The first part is the groups.mpu inheritance; the ordering is #9098.
  2. Zero3Repartition re-points groups.mpu and every reference the engine holds to its old data-parallel group by hand. With per-engine groups, that becomes a re-point of the engine's own groups.

I'll also run the end-to-end DP4 → DP2 → DP4 on Qwen3-0.6B (4 GPUs, both paths) against stage 2 once it's up.

LiRunGuo avatar Nov 17 '26 20:11 LiRunGuo

@jinyouzhi, @LiRunGuo , @Achyuthan-S FYI Following up on my earlier comment: here is a sketch of a target model for option 2, what we found when we tested its riskiest assumptions on GPUs, and a few suggestions for the stage plan and #9120 that came out of that testing. Feedback welcome, especially on the open questions at the end.

Summary

The proposal, in four points:

  • Four abstractions: a device would host processes; a process would host engines; an engine would own its module and its parallel layout; and process groups would be owned by a process-level registry in deepspeed.comm, with engines as members.
  • Group creation: every rank would create every group of every engine, in the same order, and keep the handle only where it is a member. In our tests, creating groups on a subset of ranks (use_local_synchronization, or split_group/shrink_group called by a subset) hung or returned wrong results.
  • Separate engines: each engine would have its own root group and its own communicators, even with the same ranks as another engine, and no engine would use the default torch group.
  • Failures: a timed-out collective can return a wrong value without raising before torch aborts the process, so DeepSpeed would check communicator health at engine API boundaries and before committing a checkpoint.

A possible target model

Device. A device would host isolated processes, each with its own world. Each process would be bound to one device, fixed at process init. Every engine in the process would use that device, and an engine API call from a thread whose current device is different would raise. Placing processes on devices stays the orchestrator's job.

Process. A process would host engines on its device. The client would run engines one at a time; several threads could call engines, but not concurrently. For a rollout and a trainer, two configurations would be supported:

  • Same device, same process, sequential. The engines take turns (as the hybrid engine and DS-Chat do), so the device is always busy with one phase or the other.
  • Separate devices, separate processes, asynchronous. The rollout and the trainer overlap, with weights synced explicitly between them. This is where overlap recovers idle time.

Asynchronous overlap on the same device is not useful: when the two share a device, running them sequentially already keeps it busy, and overlapping them only makes them compete for memory and bandwidth. It is also not feasible within one process, because engines share process-wide state (the random stream, the patches applied during model construction, the current device and stream) and collectives from overlapping engines would have no guaranteed common order across ranks.

deepspeed.init_distributed would become the one-time, process-level entry point: the first call would fix backend, device, seed, and determinism. A later call with different settings would raise, except for a different seed, which would warn and keep the original. Lazy callers (initialize, zero.Init, MiCS) would keep working, because the function handles the lazy first call.

Engine. An engine would own its module instances: a module is owned by at most one live engine, and state moves between engines only by explicit copy, as in #9045. It would also own its parallel config, expressed as DeviceMeshes built with DeviceMesh.from_group over registry groups. Clients would disambiguate through the engine object (engine.mpu, engine.mesh). The module-level groups.get_* getters would become deprecated compatibility getters that raise when more than one engine is live, switched on once the internal readers have moved. engine.world_size and engine.global_rank would become relative to the engine's root group (unchanged for a full-world engine). All DeepSpeed code would name its process group explicitly; process-level code could still use the default group.

Process groups. A registry in deepspeed.comm would own every group DeepSpeed uses. All ranks of a torch world would declare every engine's groups in the same order, including the groups of engines they don't build. That is an SPMD assumption at setup time only: ranks can still run different engines, and only a group's members take part in its collectives. Programs whose ranks run different code (separate rollout and trainer workers, for example) would use one torch world per role, with weights synced between worlds over an explicit channel. External groups (a user mpu, user meshes) would be recorded and never destroyed by DeepSpeed. destroy() would mark an engine's groups for release, and all ranks would release them, in creation order, at the next all-ranks registry call (an engine declaration, or an explicit collect). After a detected failure, release would be skipped. The lifecycle would sit behind a small comm-backend contract (create_group, release_group, and a capabilities record), because backends differ: for example, the CPU oneCCL backend caches sub-communicators by rank tuple and has no way to free them.

Health checks. These would be on by default and could be turned off per engine: a local read of each engine group's error state at entry and exit of every public engine API call, and a one-element agreement all-reduce over the engine's root group before anything durable, such as writing latest in save_checkpoint.

What we tested

Single node, 4× NVIDIA B200 over NVLink, with three NCCL configurations:

  • torch 2.15 / ProcessGroupNCCL2: torch 2.15.0, NCCL 2.30.7, the default nccl backend in 2.15 (built on the torchcomms engine);
  • torch 2.15 / legacy ProcessGroupNCCL: the same torch with TORCH_DIST_USE_NCCL2=0;
  • torch 2.9.1 / ProcessGroupNCCL: torch 2.9.1, NCCL 2.27.7.

Each case ran in its own process with every result checked against the expected value; key cases were repeated 3 times.

Case Result
The RFC reproducer (TP2 engine, then TP4) Reproduces on CUDA exactly as in the RFC table
Overlapping groups created by member ranks only (use_local_synchronization), same order Fails in all three NCCL configurations (torch 2.15 / ProcessGroupNCCL2, torch 2.15 / legacy ProcessGroupNCCL, torch 2.9.1 / ProcessGroupNCCL), lazy and eager. With legacy ProcessGroupNCCL and lazy init, one group gets different names on different ranks and a rank waits on the wrong store key. With eager init, or with ProcessGroupNCCL2 (which binds a device even when init is lazy), every new_group is a split of the default communicator and the splits pair wrongly: all-reduces return wrong sums (1.0 where 3.0 was expected) before hanging
A member-only split_group, then an all-ranks group Correct results on torch 2.15 / ProcessGroupNCCL2 and torch 2.15 / legacy ProcessGroupNCCL, but the later group's name differs across ranks (group_count drifts). On Gloo it hangs with torch 2.15; with torch 2.9.1, Gloo's split_group raises No device associated with the default pg, not safe to split any process groups
All ranks create every group in the same order: TP2×DP2 and TP4 engines used alternately, then DP4 → DP2 → DP4 with the DP2 engine on ranks 0-1 only and deferred release 12 of 12 runs passed, all values correct: 3 each on torch 2.15 / ProcessGroupNCCL2 (eager), torch 2.15 / legacy ProcessGroupNCCL (eager), torch 2.9.1 / ProcessGroupNCCL (eager), and torch 2.9.1 / ProcessGroupNCCL (lazy)
Destroying two groups in different orders on two ranks Hangs on torch 2.15 / ProcessGroupNCCL2 and on torch 2.9.1 / ProcessGroupNCCL; the same order passes
NCCL memory per full-world communicator About 580 MiB per GPU with NVLS off, 630-646 MiB with NVLS on; destroy returns all of it, flat over 5 create/destroy cycles, in all three NCCL configurations
A collective that one rank never joins (15 s timeout) The call returns a wrong value without raising in all three NCCL configurations. Torch then aborts the process: on torch 2.15 / ProcessGroupNCCL2 the call returns after about 16 s and the abort comes about 15 s later; on torch 2.15 / legacy ProcessGroupNCCL and torch 2.9.1 / ProcessGroupNCCL the call blocks for about 75 s, returns, and the process is killed 1-3 s later. torchrun sets TORCH_NCCL_ASYNC_ERROR_HANDLING=1 for its workers by default
Error query The backend's get_error() reports TIMEOUT by the time the wrong value is returned, in all three NCCL configurations, at about 1 µs per call. ProcessGroup itself has no get_error(); the backend is reached through the private ProcessGroup._get_backend(device)
shrink_group, then an all-ranks group Failed on torch 2.15 / ProcessGroupNCCL2 and torch 2.15 / legacy ProcessGroupNCCL, even with ordering between the shrinking ranks and the excluded rank enforced; not diagnosed
Device inside backward hooks Autograd worker threads run with the tensor's device current, including inside ZeRO-3's fetch and release hooks

Not tested: XPU/oneCCL, HCCL, more than one node, the health-check overhead on a real training step, and an actual multi-engine DeepSpeed run (which needs stage 2).

The checks are device-agnostic and use plain torch.distributed, without DeepSpeed. They are on the DeepSpeedExamples branch sfc-gh-truwase/multi-engines, in benchmarks/multi_engines. bash run_checks.sh runs every case and summarizes the results, and the README lists each case with what the design needs from it.

How this fits the stage plan and #9120

This builds on the plan as it stands: option 2, the guard first (#9088), engines owning their groups, staged delivery with the checkpoint, MoE/AutoEP, and compile readers as later stages, and #9074's DP4 → DP2 → DP4 plus DS-Chat and Accelerate multi-model as the regression cases. A few suggestions that came out of the testing, for consideration alongside #9120:

  1. Giving every engine its own communicators. #9120 lets an engine with the process-wide layout reuse the process-wide groups, which avoids adding a communicator, and allows sharing with mpu=other.mpu. It may be worth considering a separate root group and communicators for every engine, even a lone full-world one, since more engines can be created later and an engine would then never depend on groups another engine might release. The trade-off is memory: about 580-650 MiB per GPU per extra full-world communicator on the hardware above, which single-engine users would also pay. Groups that genuinely span engines (weight sync) would remain explicit shared groups.
  2. Group lifetime for stage 5. One option alongside the owner-plus-reference-count design: let a process-level registry own every group and defer release to a point where all ranks take part. In our tests destroy was blocking and hung when member ranks destroyed groups in different orders, so a single all-ranks release point might make that ordering easier to guarantee.
  3. The module getters. Option 2 keeps groups.get_* returning the first engine's groups. Once the internal readers have moved to the engine's own groups, it could help to deprecate the getters and have them raise when more than one engine is live, so a reader that was missed fails loudly instead of silently using another engine's groups.
  4. Group creation on non-member ranks. Because subset-only creation was unreliable in our tests, ranks that don't build an engine would still need to create its groups. That suggests making every engine's group layout known on every rank before the engine is built: TP/DP/SP sizes already come from config, and MoE expert-parallel sizes could move there too. An undeclared group request inside an engine that spans only some ranks could then raise instead of creating the group.
  5. Scope. Since #9037's HybridEngineRollout builds on the hybrid engine, it might make sense to bring the hybrid engine into scope, narrowly: route its group creation through the shared registry and take its TP group from the engine's own mpu. init_inference and PipelineEngine could stay out for now, behind the #9088 guard.

Open questions

  1. Does the cost of separate communicators seem acceptable, or would it be better to let a lone full-world engine use the default group and handle a later engine differently?
  2. Multi-engine support would require torch ≥ 2.9, and the health check relies on a private torch API (ProcessGroup._get_backend). Is that acceptable, or should we ask upstream for a public error query?
  3. Moving MoE expert-parallel sizes into config: does that break existing MoE users?
  4. Should we ask upstream torch for a member-only group-creation path, with a caller-supplied name and no split of the default communicator? That would remove the requirement that every rank declares every group. Our failures came from group names salted with per-rank counters and from new_group becoming a split of the default communicator once a device is bound; I haven't checked whether an existing option already avoids both.
  5. @jinyouzhi, could you run the checks in benchmarks/multi_engines on XPU (the RFC was tested on Arc Pro B70)? bash run_checks.sh picks the XPU device and its default backend; BACKEND=ccl or BACKEND=xccl selects one explicitly. Backend differences are exactly where this design is least tested.
  6. @LiRunGuo, the DP4 → DP2 → DP4 tests in #9074 would be the first real multi-engine check of this model once stage 2 is up.

This comment was drafted with AI assistance, including the code analysis and the GPU test scripts. I reviewed it before posting.

sfc-gh-truwase avatar Nov 23 '26 13:11 sfc-gh-truwase

Thanks @sfc-gh-truwase, this is very helpful. Three notes from my side.

A trainer and a rollout in one process, following the all-ranks rule. @LiRunGuo's NativeRollout in #9074 already creates its groups this way: every rank calls new_group for every replica of a layout, in the same order, and only members keep the handle (NativeRollout._group in native/rollout.py; its TrainerMPU does the same for a trainer on a subset of the ranks). I ran it next to a ZeRO-3 trainer engine in the same processes. The run was 56 RL-style steps with 6 rollout layout changes, TP4 → TP2 on ranks 0-1 → TP2×DP2 → TP4, twice, on Qwen3-0.6B. Hardware: 4× A40 (PCIe, no NVLink), torch 2.12.1+cu130, NCCL 2.29.7. Nothing hung. The rollout moved in place matched one rebuilt and re-synced at every change bit for bit, in tokens, logprobs, losses at every step, and in the trainer's 930 state tensors at the end. Three limits. The rollout is not a second deepspeed.initialize engine, so this does not exercise stage 2. Its groups are cached and never destroyed, so it says nothing about release. And it is one node.

Stage 3 (checkpoint readers). Besides the ones in the table, zero_affine.py reads groups._get_data_parallel_group() as the replica group of a parameter that is not ZeRO-3, when no group is passed and the parameter has no _dp_group. I'll move that one with the default tp_group, model_checkpointing/utils.py (groups.mpu and the expert tables) and the AutoTP load in stage3.py. One point for the target model: the affine storage maps name their holders by world rank (dist.get_global_rank over the parameter's group), not by the engine's rank. A transfer between two engines, such as trainer → rollout or DP4 → DP2, needs a rank space that both engines' maps share. So I'd keep world ranks there even after engine.global_rank becomes relative to the engine's root group.

#9098. The fix compares each engine's own module and parameter positions instead of the process-wide ids, so it does not depend on how the groups are created. It is ready apart from a GPU rerun, and I'll link it here.

Achyuthan-S avatar Nov 23 '26 14:11 Achyuthan-S

Update to my comment above: running roles in separate processes, under an orchestrator such as a Ray-based framework, is now proposed separately in #9152, "Engine primitives for external orchestrators". That RFC takes over three things from the comment above:

  • the "separate devices, separate processes, asynchronous" configuration;
  • the measurements of communicator memory, collective timeouts, and the error query;
  • the open question about relying on a private torch API (ProcessGroup._get_backend) for the health check.

This thread stays focused on engines inside one process.

sfc-gh-truwase avatar Nov 23 '26 19:11 sfc-gh-truwase

@sfc-gh-truwase thanks, this matches where this RFC is heading. On your first suggestion and open question 1, some context on where #9120 sits:

#9120 is an intermediate step, not the target. The goal of this RFC from the start (option 2) is that every engine owns its process groups, so that groups are decoupled from the process-wide globals and from any other engine. Stage 2 takes the first part of that: every engine gets its own groups object (engine.mpu), and the engine's readers move onto it. What #9120 does not do yet is give every engine its own communicators: an engine whose layout matches the process-wide groups holds those same groups, and mpu=other.mpu shares them explicitly. That is deliberate for this stage:

  • Single-engine users keep exactly today's groups and pay no extra communicator.
  • No group is destroyed before stage 5, so sharing cannot leave an engine on a released group yet.
  • It keeps stage 2 reviewable on its own, while the readers move.

The target, with group lifetime (stage 5): each engine has its own groups, created through the registry you describe, and groups move between engines only by an explicit handover. The handover matters for @LiRunGuo's case in #9074: when one engine is destroyed and a new engine with the same layout replaces it (the DP4 engine rebuilt after DP2, or a trainer rebuilt after a resize), the new engine should be able to take over the old engine's groups instead of creating new communicators. Ownership passes with the handover, so no engine depends on groups that another live engine may release, which is the risk you point out. Zero3Repartition's manual re-pointing of groups.mpu then becomes this handover.

So on question 1: I'd keep sharing the process-wide groups in stage 2, and move to one engine, one set of groups in stage 5, with takeover for the replace-an-engine case rather than a new communicator each time.

@LiRunGuo, on the two workarounds you listed for #9074: #9120 removes the groups.mpu inheritance, so a later engine without an mpu no longer picks up an earlier engine's groups; the ordering part is #9098. An engine over a subset of the ranks still needs its own mpu until engines get their groups from the registry. The manual re-pointing in Zero3Repartition is the handover described above. Could you run #9074's tests, and the DP4 → DP2 → DP4 run on Qwen3-0.6B, against #9120?

@Achyuthan-S, thanks for the NativeRollout run, it is good evidence for the all-ranks rule with a trainer in the same processes. I agree on keeping world ranks in the affine storage maps. A transfer between two layouts from #9026 lines up the source and target maps in one rank space, which world ranks give for free between two engines (trainer → rollout, DP4 → DP2), so engine.global_rank becoming relative to the engine's root group should not change the maps.

XPU results (your question 5). I ran benchmarks/multi_engines on 4× Intel Arc Pro B70 (PCIe), torch 2.14.0.dev20260804+xpu, xccl (ProcessGroupXCCL), oneCCL 2022.0.0 from the torch wheel, every case 3 times with eager init and 3 times with lazy init; all 6 runs of each case gave the same result, and no check ever returned a wrong value. BACKEND=ccl was not run: oneccl_bindings_for_pytorch is not installed there, and xccl is the upstream default.

Case XPU / xccl
registry_path pass, eager and lazy, all values correct
destroy_same_order pass
overlap_members_only, subset_then_all fail, but loudly: no wrong values; ranks time out on the xcclUniqueId store key, and group names differ across ranks
split_then_all not supported (eager: the backend does not support splitting; lazy: no device associated with the default pg)
shrink_then_all not supported (the backend does not support shrinking)
destroy_diff_order pass, unlike NCCL
memory_cycles values correct, but memory is not returned: each full-world communicator takes about 65-73 MiB per device, and free memory drops by that much every cycle (31848 → 31510 MiB over 5 cycles), with nothing freed by destroy_process_group; it comes back when the process exits
timeout_probe hangs, no error, no abort (below)

Timeouts and the error query. I added a small probe beside timeout_probe (2 ranks, rank 1 never joins, process-group timeout 10 s, a thread polling get_error() every 5 s):

  • all_reduce(..., async_op=True) and work.wait() return at once; torch.xpu.synchronize() then blocks indefinitely.
  • The timeout never fires and the process is never aborted; it was still blocked after 125 s, also after rank 1 had exited.
  • get_error() stays SUCCESS the whole time (about 1.3 µs per call).
  • With TORCH_XCCL_BLOCKING_WAIT=1, work.wait() blocks indefinitely instead, and still does not raise.

What this means for the design, as I read it:

  1. On XPU too, every rank has to declare every group, and there is no split-based alternative to fall back on.
  2. Release is a no-op for device memory on xccl today, which fits the capabilities record (a backend that cannot release). A communicator is much cheaper here (about 70 MiB against about 600 MiB on B200), but it accumulates when engines are rebuilt, so taking over a replaced engine's groups, rather than destroying and recreating them, also avoids that growth.
  3. The health check cannot rely on get_error() on XPU yet: the backend reports SUCCESS during the hang, rather than having no error state at all. The agreement all-reduce before writing latest would hang rather than pass a wrong value, which is safe for the checkpoint but needs an outside timeout. So the error query should be an optional backend capability, and a backend should only count as able to report errors once it has been shown to report this case.

jinyouzhi avatar Nov 24 '26 06:11 jinyouzhi

As promised above, the #9098 fix is up as #9176: each engine numbers its own modules and parameters, and ZeRO-3's rank-agreement checks compare those positions instead of the process-wide ids.

Achyuthan-S avatar Nov 26 '26 02:11 Achyuthan-S

@sfc-gh-truwase, on open question 6: I ran #9074's DP4 → DP2 → DP4 tests with #9120 underneath, i.e. stage 2 as it stands now, and everything passes. I applied #9120 (4c51459) on top of #9074 (1f4821a), with no conflicts, and ran on 4x RTX 4090 with torch 2.13.0+cu130 and CUDA 13.0:

  • tests/unit/runtime/rollout/test_zero3_repartition.py (DP4 → DP2 → DP4, both planners, fp32 and bf16): 7 passed. #9074's switch tests: 162 passed. All 12 of the deliberate breaks of Zero3Repartition were caught: 8 by a failing test, 4 by a hang.
  • #9074's other GPU tests: 168 passed. Upstream tests/unit/v1/zero/test_zero.py and test_zero_init_pg_contradiction.py: 149 passed, 1 skipped.
  • End to end on Qwen3-0.6B, DP4 → DP2 → DP4 through both paths: two engines with the state moved between them, and one engine re-partitioned in place. Each ran with both planners, and in all four runs, 6 of 6 moves came out bitwise equal to a plain four-rank engine.
  • #9120's tests/unit/v1/autotp/test_autotp_multiple_models.py: 50 passed.

What these tests exercise, against your model: in test_zero3_repartition.py every engine, the four-rank ones included, is built with an mpu whose groups every rank creates in the same order, with only the members keeping the handle (#9074's TrainerMPU, as Achyuthan described above). So each engine has communicators of its own, even when its ranks are the whole world, and with #9120 its readers go through engine.mpu. What they don't exercise: a process-level registry, process-wide groups shared through mpu=other.mpu, group release (nothing is destroyed), and more than one node.

Replacing an engine's groups in place is outside #9120's scope, so Zero3Repartition still re-points them by hand. The stage-5 handover jinyouzhi describes above would replace that. I'll rerun when either PR moves.

An environment note, in case someone hits it: with CUDA from the pip wheels (cu13), one test of test_autotp_multiple_models.py cannot JIT-build transformer_inference, because cuda_profiler_api.h isn't in those wheels. Adding the header from nvidia-cuda-profiler-api fixes it. It is unrelated to either PR.

LiRunGuo avatar Nov 26 '26 05:11 LiRunGuo

@jinyouzhi, an update on stage 3. #9120 now covers all three checkpoint readers in the table: the checkpoint writer through _GroupsWithMPU, the default tp_group of autotp_storage_affine_maps, and the universal-checkpoint load of AutoTP shards in stage3.py. So stage 3 can land with #9120 rather than as its own PR. The writer and the storage maps have tests there, but the load into a ZeRO-3 engine on its own TP groups doesn't yet, so I wrote one on top of 4814dc5ac: after a TP2 engine, a TP4 ZeRO-3 engine loads a universal checkpoint and gets every state back bit for bit, and the same with TP4 first and TP2 second. With the load reading the process-wide TP group instead, the TP2-then-TP4 case fails. Happy to push it to your branch or open it as a PR against it, whichever you prefer.

The rank-agreement half of stage 3 (#9098) is #9176, which now has its GPU results too.

Achyuthan-S avatar Nov 29 '26 18:11 Achyuthan-S