Repository navigation
Conversation
|
The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:
Once a maintainer approves the workflows (scroll to the bottom of the PR page), the corresponding CI jobs will be triggered automatically. Please ping one of the reviewers if you do not have access to approve and run workflows. |
|
one can just set it via environment. but i think only FSDP's communication is the problem, so set per mesh axis is more reasonable, this PR anyway makes such tunning more flexible.. |
|
@claude review The motivation sounds quite plausible, but the current implementation seems not friendly to non-nvidia hardware. Could you give some design options to make it more object-oriented that is easy to maintain? |
There was a problem hiding this comment.
Verdict: Request changes -- The goal is sound and the measurements support it (+23% tps on a comm-bound FSDP MoE). But the code puts NCCL-specific logic into CommConfig and ParallelismContext, and it adds a second way of building NCCL CTA options next to the one already in distributed/utils.py.
What this PR does. It adds comm.nccl_ctas: dict[axis, int]. Each listed mesh axis is rebuilt with a ("nccl", ProcessGroupNCCL.Options(min_ctas=max_ctas=N)) backend override during unflatten_mesh. It also adds comm.sm_carveout, which calls the private torch._C._set_sm_carveout_experimental once at engine init.
Example.
# 16 nodes x 4 GH200, FSDP only. NCCL picks 4 channels/GPU, about 75 GB/s per node.
before: NCCL_MIN_NCHANNELS=16 # every communicator, including HSDP dp_replicate
after: comm.nccl_ctas={"dp_shard": 16} # only the FSDP shard communicator
on XPU / cpu-offload / fake backends: fails late, or the setting is silently ignored
Design options (answering @tianyu-l)
The current code mixes three different things in one place: which axes get a setting (generic), what the setting is (backend-specific), and where the mesh is built (generic). The options below separate them. They can be combined.
A. ParallelismContext takes generic per-axis backend overrides (needed for every option). Replace the nccl_ctas field with axis_backend_overrides: dict[str, str | tuple[str, dist.Backend.Options]]. That is the type DeviceMesh already accepts. unflatten_mesh only merges it with its own "fake" entries. Mesh code then never mentions NCCL, and the vLLM generator's ParallelismContext(...) needs no changes. This deletes _nccl_with_ctas from parallelism_context.py.
B. Per-backend options config, selected by config type (recommended on top of A).
class NCCLProcessGroupOptions(Configurable):
@dataclass(kw_only=True, slots=True)
class Config(Configurable.Config):
min_ctas: int | None = None
max_ctas: int | None = None
def build(self) -> tuple[str, dist.Backend.Options]: ... # the only place ProcessGroupNCCL.Options() is built
CommConfig.process_group_options: dict[str, NCCLProcessGroupOptions.Config] # keyed by mesh axis__post_init__ checks that the device's default backend (dist.Backend.default_device_backend_map[device_type]) matches the options type and that comm.backend == "default". If not, it raises. A vendor such as XCCL later adds a sibling XCCLProcessGroupOptions.Config to the union, and nothing in the mesh or engine code changes. Per design.md, don't add an abstract base until that second backend exists. build_alternative_fsdp_mesh (distributed/utils.py:402, used by DistMuon max_nccl_ctas_for_comms) should build its options through the same class. That leaves a single point that knows NCCL's config fields. Estimated size: about +50 / -25.
C. No core config (the alternative to B). Keep NCCL_MIN_NCHANNELS (the global env var) and add only A, so a recipe can supply overrides through OVERRIDE.md. This is smaller, but it treats the feature as out-of-repo. Given the measured gains and the HSDP use case the author mentions, I'd pick A+B.
sm_carveout is separate from all three. It is a PyTorch-level GEMM setting, not an NCCL one. Keep the upstream name, but validate the device type at config time and link an upstream issue for the private API (see the inline comment).
Must fix
- Design: NCCL-specific code in core config and mesh construction, duplicating
build_alternative_fsdp_mesh. Fix: options A+B above. parallelism_context.py:305--"nccl"is hardcoded. It fails late on non-NCCL devices and drops gloo whenfsdp_enable_cpu_offloadingis on.training_engine.py:331-- the setting is silently ignored under fake backends. It should raise in__post_init__.training_engine.py:337-- private API with no TODO issue link, and no device check.- Unverified: with CP > 1, FSDP shards over
("dp_shard", "cp")(distributed/fsdp.py:148), which FSDP flattens into a new group. That group likely doesn't inherit the CTA options, so{"dp_shard": N}would silently do nothing under FSDP+CP. The same applies to the flattened groups proposed in #5663. Either cover the flattened FSDP group, or raise when CP > 1.
Should consider
configs.py:174-- derive the axis set fromMeshAxisNameinstead of copying it.test_parallelism_context.py:1198-- the mock-based test swallowsAssertionError. Test the pure config -> overrides function instead.
Questions
- Did you check whether a fixed channel count changes NCCL's algorithm selection (ring/tree/NVLS) and therefore the bitwise reduce-scatter result? The default path is unchanged, but the description's Numerics section has no loss comparison for the enabled path.
Not verified: CPU-offload gloo breakage, CP flatten inheritance, and which kernels honor the SM carveout. All need a GPU run.
| elif axis in self.nccl_ctas: | ||
| backend_override[axis] = _nccl_with_ctas(self.nccl_ctas[axis]) |
There was a problem hiding this comment.
This hardcodes the "nccl" backend string for any listed axis, whatever backend the world group uses. Two consequences:
- On XPU (
xccl) or any other non-NCCL device, a listed axis either hitsAttributeErrorondist.ProcessGroupNCCL, or gets an NCCL group created on the wrong device during mesh construction. Either way the failure comes late and is hard to read, not at config time. - With
fsdp_enable_cpu_offloading,init_distributeduses"cuda:nccl,cpu:gloo"(distributed/utils.py:548). This override switches the axis to plain"nccl"and drops gloo, so CPU-tensor collectives ondp_shard(for example grad-norm over offloaded grads) have no backend. Unverified on GPU.
ParallelismContext should not know about NCCL at all. It should take a backend-agnostic dict[str, str | tuple[str, dist.Backend.Options]] (the type DeviceMesh already accepts) and merge it with its own "fake" entries. The config-to-options conversion and the "this backend is unsupported" check belong in one place outside mesh construction. See the design options in the review body.
| config.parallelism, | ||
| topology, | ||
| dump_folder=self.output_dir, | ||
| nccl_ctas=config.comm.nccl_ctas |
There was a problem hiding this comment.
When comm.backend is "fake" or "real_pp_fake_spmd", a non-empty nccl_ctas is silently ignored. Both fields live on CommConfig, so CommConfig.__post_init__ should raise ValueError for that combination. Then this call site can pass the value unconditionally, and the | None default on from_config can go.
| if config.comm.sm_carveout: | ||
| # TODO: switch to a public API once PyTorch has one. | ||
| torch._C._set_sm_carveout_experimental(config.comm.sm_carveout) |
There was a problem hiding this comment.
This calls the private torch._C._set_sm_carveout_experimental, and the TODO has no upstream issue link (CLAUDE.md principle 3). Please file or link the PyTorch issue for a public API.
It also runs on every device type with no check. Which kernels honor the carveout is backend-specific. My understanding is that cuBLASLt and CUTLASS grouped mm honor it, Triton/Inductor templates don't, and ROCm and XPU are unclear (unverified). So on unsupported hardware it may silently do nothing. The trainer should raise at config time for devices where the carveout isn't known to be honored, and the docstring should say which GEMMs it affects. Otherwise the benchmark table won't carry over to torch.compile'd runs.
This feature is also independent of nccl_ctas. Consider splitting it into its own PR (one concern per PR) with its own end-to-end number. The table already shows its delta: 10,549 -> 11,063 tps.
| """ | ||
|
|
||
| def __post_init__(self) -> None: | ||
| axes = {"pp", "dp_replicate", "dp_shard", "cp", "tp", "dp", "ep", "edp_shard"} |
There was a problem hiding this comment.
This hand-copies MeshAxisName, so the two lists can drift apart. Derive the set from the enum instead, e.g. {axis.value for axis in MeshAxisName}, or a lazily imported equivalent if importing from torchtitan.distributed here creates a cycle.
| with patch( | ||
| "torchtitan.distributed.parallelism_context.init_device_mesh", | ||
| return_value=world, | ||
| ): | ||
| try: | ||
| context.build_mesh() | ||
| except AssertionError: | ||
| pass # mocked meshes have no sizes; the calls are recorded |
There was a problem hiding this comment.
The test mocks init_device_mesh with a MagicMock and swallows AssertionError from build_mesh. It is coupled to the private _unflatten call shape (call.args[2]), and it would also pass if build_mesh started failing for an unrelated reason. Once the override building moves out of ParallelismContext, the useful invariant is "config -> per-axis backend overrides". That is a pure function and can be tested directly, with no mocked mesh. The validation test below can stay, apart from the CommConfig(...) positive line, which only re-reads its own config.
|
@rakkit A + B makes sense to me |
…ication
Two CommConfig options, off by default:
- process_group_options, e.g.
{"dp_shard": NCCLProcessGroupOptions.Config(min_ctas=16, max_ctas=16)}:
options for the process group of one mesh axis. ParallelismContext takes
them as generic per-axis backend overrides; NCCLProcessGroupOptions is the
one place that builds NCCL options (build_alternative_fsdp_mesh uses it too).
- sm_carveout: SMs that GEMMs leave free for communication kernels
(torch._C._set_sm_carveout_experimental), set in init_distributed.
e5e18e1 to
17addd9
Compare
|
thx. i took what claude said and make comm config to be NCCL "NCCLProcessGroupOptions" FOR gemm SM controls, it originally from "pytorch/pytorch#144974" so its a pytorch flag, not NCCL env varible. I dont have AMD chip here and i know nothing about it - ) example of usage: |
| process_group_options: "dict[str, NCCLProcessGroupOptions.Config]" = field( | ||
| default_factory=dict | ||
| ) |
There was a problem hiding this comment.
could you also help turn this config into a PGOption?
https://github.com/pytorch/torchtitan/blob/main/torchtitan/components/optim/optimizer.py#L224
| from torchtitan.config.configurable import Configurable | ||
|
|
||
|
|
||
| class NCCLProcessGroupOptions(Configurable): |
There was a problem hiding this comment.
Maybe we should have a base ProcessGroupOptions class to inherit from, so that the typing stays neutral.
| if config.max_ctas is not None: | ||
| options.config.max_ctas = config.max_ctas | ||
| # The (backend, options) pair DeviceMesh takes for one mesh axis. | ||
| self.backend_override = ("nccl", options) |
There was a problem hiding this comment.
should this be a config dataclass only, and provide backend_override as a property?
|
@claude review again |
There was a problem hiding this comment.
Verdict: Request changes -- The generic axis_backend_overrides split (option A) is done. @tianyu-l's three comments from today are not yet addressed, and the axis-name validation was dropped, so typos are silently ignored again.
What changed since the last review. ParallelismContext now takes a backend-neutral axis_backend_overrides and merges it with its "fake" entries. A new NCCLProcessGroupOptions builds the ("nccl", Options) pair, and build_alternative_fsdp_mesh reuses it. CommConfig.__post_init__ raises for non-default comm.backend and for non-CUDA sm_carveout. The carveout call moved into init_distributed.
Example.
config.comm = CommConfig(
process_group_options={"dp_shard": NCCLProcessGroupOptions.Config(min_ctas=16, max_ctas=16)},
sm_carveout=16,
)
# {"dp-shard": ...} -> silently ignored; NCCL default channels (no error)
# dp_shard with cp=2 -> silently ignored; FSDP uses a flattened (dp_shard, cp) groupEarlier must-fix items
- Design A+B: A resolved. B is partly done, see @tianyu-l's comments below.
- Hardcoded
"nccl": still open. On XPU,dist.ProcessGroupNCCLraisesAttributeErrorat engine init, not at config time. Withfsdp_enable_cpu_offloading, the world group is"cuda:nccl,cpu:gloo"(distributed/utils.py:570), and the override replaces it with plain"nccl"ondp_shard. Either raise for that combination or keep gloo. Unverified on GPU. - Silent no-op under fake backends: resolved (
configs.py:195). - Private
torch._C._set_sm_carveout_experimental: still open, and the TODO was removed (distributed/utils.py:545). Add aTODOwith an upstream issue link (CLAUDE.md principle 3). - FSDP+CP flattened group: still open. It is now documented in the docstring, but it is still a silent no-op. Raise instead (principle 8); see the inline comment for where.
Must fix
- @tianyu-l
configs.py:164: make DistMuon'smax_nccl_ctas_for_comms: int = -1an options config, e.g.comm_process_group_options: NCCLProcessGroupOptions.Config | None = None. This removes the<= 0"disabled" sentinel (rules/config.md).build_alternative_fsdp_meshthen takes the config directly and only addssplit_share = 0. - @tianyu-l
process_group_options.py:32: make it a plain config dataclass with abackend_overrideproperty. Correct. TheConfigurableinstance exists only to hold one attribute. Each of the three callers builds it and then reads it back (training_engine.py:341,torchft/trainer.py:113,utils.py:476), and the two trainer copies of the dict comprehension become{axis: o.backend_override for ...}. - @tianyu-l
process_group_options.py:14: add a neutralProcessGroupOptionsbase. This reverses my earlier "no base until a second backend" advice. The base has a current consumer, theCommConfig.process_group_optionstype, and it keeps the vendor name out of core config. Keep it minimal: only an abstractbackend_override. The backend-availability check from item 2 above belongs in the subclass's__post_init__(dist.is_nccl_available()). parallelism_context.py:303-- unknown axis names are silently ignored; validate againstMeshAxisName(inline).- PR description is stale: it still documents
comm.nccl_ctas={...}and a typo-catching test that no longer exists. Please update the Numerics table and the Testing section.
Should consider
test_config_validation.py:95-- this test only re-reads its own config; delete it (inline).configs.py:171-- the docstring disagrees with the ROCm check, and the claimed kernel list wasn't measured (inline).sm_carveoutis independent of the PG options. It could still go in its own PR with its own number (10,549 -> 11,063 tps).
Questions
- Still unanswered from the last review: with a fixed channel count, is the reduce-scatter result bitwise identical? Does it change NCCL's algorithm selection? A loss/grad_norm comparison with the option enabled would settle it.
Not verified: CPU-offload gloo breakage and which kernels honor the SM carveout. Both need a GPU run.
| elif axis in self.axis_backend_overrides: | ||
| backend_override[axis] = self.axis_backend_overrides[axis] |
There was a problem hiding this comment.
The previous revision rejected unknown axis names, and this revision dropped that check. Now a typo such as {"dp-shard": ...} or {"fsdp": ...} matches no axis in any unflatten_mesh call, so the options are silently dropped and training runs at NCCL's default channel count. The PR description still says this is covered ("catches typos in axis names silently doing nothing").
The circular import that pushed validation out of CommConfig doesn't apply here, because MeshAxisName lives in this module. Validate in _validate():
unknown = set(self.axis_backend_overrides) - {a.value for a in MeshAxisName}
if unknown:
raise ValueError(f"Unknown mesh axes in comm.process_group_options: {sorted(unknown)}")The same place could also raise for "dp_shard" when cp > 1, where FSDP shards over a flattened (dp_shard, cp) group. That case is currently only documented as a no-op (earlier must-fix 5).
| @pytest.mark.skipif(not dist.is_nccl_available(), reason="PyTorch built without NCCL") | ||
| def test_nccl_process_group_options_build() -> None: | ||
| config = NCCLProcessGroupOptions.Config(min_ctas=16, max_ctas=32) | ||
| backend, options = config.build().backend_override | ||
| assert backend == "nccl" | ||
| assert (options.config.min_ctas, options.config.max_ctas) == (16, 32) |
There was a problem hiding this comment.
This test sets min_ctas/max_ctas and then reads the same values back from the options object. It is a re-read of its own config (rules/tests.md), so it doesn't guard the invariant that matters: that the options reach the dp_shard process group. Two more problems:
- It needs
dist.is_nccl_available(), so on CPU-only torch wheels it is skipped in the CPU suite. - It lives in
config/test_config_validation.py, but it isn't a validation test.
Please delete it. If you add the axis-name check in ParallelismContext._validate(), a one-line assertRaises in test_parallelism_context.py is the test worth having.
| sm_carveout: int = 0 | ||
| """SMs that GEMMs leave free for communication kernels (0: off). Read by | ||
| cuBLASLt matmuls, Inductor's persistent matmul templates and FlashAttention-3. | ||
| Tested on NVIDIA GPUs only; it may not work on ROCm or other accelerators.""" |
There was a problem hiding this comment.
The docstring and the __post_init__ check disagree. On ROCm builds, torch.version.cuda is None, so __post_init__ already raises there. "It may not work on ROCm" is therefore unreachable. Say what the code does: "Requires a CUDA build; raises otherwise."
The list of kernels that read the carveout (cuBLASLt, Inductor persistent templates, FA3) is the important part for users. It is also the one claim the PR doesn't measure: the benchmark covers only expert grouped GEMM and dense bf16. Please either add a PyTorch source reference for each kernel, or trim the list to what you measured.
THIS IS NOT FREE, GEMM FOR SURE GETS SLOW but on the case of communication become bottleneck, (each layer need to wait gather/reduce, this help a lot because compute is not bottleneck)
Summary (human-written)
For A100/H100 users, there is a know limitation that train small model (espically moe) with FSDP always struggle on communication cannot over computation. (unfortunately not everyone are rich to have NV72)
I somehow found an interesting solution with help of claude can better trade off this, unexpected yet reasonable to just allocate more SMs to NCCL. (torch 2.15 new features reduce-scatter communicator does not really help for my case, see below)
(i am still exploring how can use this to tackle the annoying replicated group gradient reduce on HSDP)
Why (Claude wrote)
FSDP's all-gather / reduce-scatter run on NCCL communicators whose channel (CTA) count NCCL picks from its topology search.
On our nodes (4x GH200, 4x NDR200 per node) it picks 4 channels per GPU, which reaches ~75 GB/s per node of a 100 GB/s line rate, so FSDP communication is exposed in both passes. The only knob today is the global
NCCL_MIN_NCHANNELS, which applies to every communicator (e.g. also HSDP's replica all-reduce). Second, a GEMM that runs beside a collective competes with NCCL for SMs: an expert grouped GEMM next to an FSDP all-gather drops ~40%.Numerics
comm.nccl_ctas={"<mesh axis>": N}per axis (default{}: unchanged)comm.sm_carveout=N(default0: unchanged)Communication configuration only, off by default.
Performance
FSDP over 16 nodes (4x GH200 per node, 64 in total ), ~30B-A3B MoE, 64k tokens per GPU, tps/GPU.
Collectives at FSDP's message sizes (16 nodes, 64 ranks):
Training,
nccl_ctas={"dp_shard": N}:sm_carveout=16GEMM beside a running FSDP all-gather (one GH200):
(human write: so we with more SMs asigned to NCCL, the GEMM get slow, but the end2end net is quiet optimistic, at least 15% throughput gains for free..)
Testing
tests/unit_tests/cpu/distributed/test_parallelism_context.py: the listed axes' communicators get min = max CTAs, size-1 axes stayfake(catches the override not reaching the mesh); config validation (catches typos in axis names silently doing nothing).