[RFC] Cleanup: move process-wide parallel-group globals to per-engine groups — follow-up to #8241 / #8851
メンテナーはふだん 2 日以内に返信
評価
- 難易度
- 5/5
- 見積もり時間
- 1週間以上
- 初心者へのやさしさ
- 5/100
- issue の種類
- リファクタリング
- 明瞭さ
- 説明が足りない
- 活発さ
- 活発
調査の方向性
Start with _init_tp_mesh_device in deepspeed/utils/groups.py, where the early return on an already-set _TENSOR_MODEL_PARALLEL_GROUP causes the second-engine problem, then read the groups.mpu assignment in engine.py. Run the four-rank reproducer in the issue to see the mismatch. This is an RFC: the maintainers must first decide between a guard, engine-owned groups and a snapshot API, so no change is ready to start.
索引モデルが issue の本文から書いたものです。
説明
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, ...) fromtp_shardglobals onto a per-modelAutoTPMeta. - #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_GROUPand_DATA_PARALLEL_GROUP; - it saves
_TENSOR_MODEL_PARALLEL_GROUP,_MODEL_PARALLEL_GROUP,_DATA_PARALLEL_GROUP,_MPU_TENSOR_MODEL_PARALLEL_*,mesh_deviceandmpuper engine, and writes them back before that engine trains again.
- before each
- #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 explicitgroup, andautotp_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 inself.mpu, and kept its ownself.data_parallel_group. Nothing about the layout was process-wide. - #1310 (MoE, August 2021) added
deepspeed/utils/groups.pyas a registry of expert groups. - #1798 (February 2022) began copying the engine's
mpuinto 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 byself.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
groupsorengine.mpulater reads B's groups. That is why #1021 saves and restores the globals per engine.
- 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
What reads and writes the globals
Writers (all in deepspeed/utils/groups.py unless noted):
_init_tp_mesh_deviceand_init_tp_groups_with_new_group:_TENSOR_MODEL_PARALLEL_GROUP,_MODEL_PARALLEL_GROUP,_DATA_PARALLEL_GROUP.mesh_device; also assigned inengine.py(groups.mesh_device = self.mesh_device).mpu, assigned inengine.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 overgroups.get_tensor_model_parallel_group()and usesgroups.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
- Keep the globals; document a supported way to switch.
- Make what #1021 and #9074 do external, for example a public
groupssnapshot/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.
- Make what #1021 and #9074 do external, for example a public
- Each engine owns its groups (return to the pre-2022 design).
_init_tp_mesh_devicebuilds a small per-engine object with the same interface as today'smpu.engine.mpupoints 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.
- A guard only: raise if a second
initializeasks for a differentautotp_sizethan 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:
- The guard (option 3), plus a test that builds TP2 and TP4 engines in one process.
- Per-engine group object;
engine.py, ZeRO and AutoTP readers move to it. - Checkpoint and
zero_affinereaders. - MoE / AutoEP and compile readers.
- 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)
- 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)?
- If supported: is returning to engine-owned groups (option 2) the right direction, or is an official snapshot/activate API (option 1) preferred?
- In stages as above, or as one change?
- 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.
- 主要言語
- Python
- スター
- 43.3k
- フォーク
- 5.1k
- 平均マージ
- 5日 10時間
- マージ済み PR(30日)
- 85
環境構築
- Dockerfile・Docker Compose ファイルなし
- プルリクエストのテンプレートなし
- コントリビューションガイドを読む
はじめの一歩
- issue を最後まで読み、次にプロジェクトのコントリビューションガイドを読みます。
- 着手することを issue にコメントします — 二人が同じ作業をするのを防げます。
- リポジトリをフォークし、ブランチを切って変更します。
- issue 番号を参照したプルリクエストを送ります。
deepspeedai/DeepSpeed のほかの issue
-
[Bug] DeepSpeedEngine.step leaves _running_engine_step=True permanently on exception, corrupting is_gradient_accumulation_boundary()対応中かも @its-amann が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 85/100
deepspeedai/DeepSpeed#9190 · コメント 1 件 ·
メンテナーはふだん 2 日以内に返信
-
[Bug] PipelineEngine._exec_reduce_grads and _exec_optimizer_step leave _force_grad_boundary=True permanently after any exception対応中かも @bantianyue が今日担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
deepspeedai/DeepSpeed#9183 ·
メンテナーはふだん 2 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 84/100
deepspeedai/DeepSpeed#9019 · コメント 2 件 ·
メンテナーはふだん 2 日以内に返信
-
fp16 `hysteresis: 0` (or negative) makes DynamicLossScaler never lower the loss scale, so every overflowing step is skipped forever対応中かも @damienen が 26 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 72/100
deepspeedai/DeepSpeed#8982 ·
メンテナーはふだん 2 日以内に返信
-
[BUG] OneCycle applies the minimum momentum to the first Adam update対応中かも @ai-yang が 30 日前に担当しました。 オープン
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
deepspeedai/DeepSpeed#8951 ·
メンテナーはふだん 2 日以内に返信
deepspeedai/DeepSpeed の issue をすべて見る
似ている issue
-
area/auth comp/agent P3 type/bug
難易度 2/5 1〜3時間 初心者へのやさしさ 88/100
NousResearch/hermes-agent#161417 ·
メンテナーはふだん 1 日以内に返信
-
難易度 1/5 1〜3時間 初心者へのやさしさ 75/100
メンテナーはふだん 2 日以内に返信
-
難易度 2/5 1〜3時間 初心者へのやさしさ 88/100
Dao-AILab/flash-attention#3251 ·
メンテナーはふだん 2 日以内に返信
-
[New Check]: sqlserver_public_network_access_disabled対応中かも @pouria-l が今日担当しました。 オープンfeature-request status/needs-triage
難易度 2/5 1〜3時間 初心者へのやさしさ 78/100
prowler-cloud/prowler#13607 · コメント 1 件 ·
メンテナーはふだん 1 日以内に返信
-
external langchain
難易度 1/5 1時間未満 初心者へのやさしさ 90/100
langchain-ai/docs#8184 ·
メンテナーはふだん 1 日以内に返信