Skip to content

[comm] Per-mesh-axis NCCL CTA counts and SM carveout for communication - #5940

Open
rakkit wants to merge 1 commit into
pytorch:mainfrom
rakkit:comm-nccl-ctas-sm-carveout
Open

rakkit wants to merge 1 commit into
pytorch:mainfrom
rakkit:comm-nccl-ctas-sm-carveout

Conversation

@rakkit

@rakkit rakkit commented Nov 7, 2026

Copy link
Copy Markdown
Contributor

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

Before After
NCCL picks channels per communicator; global env var only comm.nccl_ctas={"<mesh axis>": N} per axis (default {}: unchanged)
no SM reservation for communication comm.sm_carveout=N (default 0: 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):

collective NCCL default (4 channels) 32 channels
all-gather 21.7 ms 17.7 ms
reduce-scatter 42.4 ms 35.2 ms
both at once 63.9 ms 52.8 ms
bandwidth per node ~75 GB/s ~93 GB/s

Training, nccl_ctas={"dp_shard": N}:

N tps/GPU
4 (NCCL's own choice) 8,557-8,629
8 10,084-10,207
16 10,549-10,565
24 10,506-10,532
32 10,476-10,512
16 + sm_carveout=16 11,063-11,069

GEMM beside a running FSDP all-gather (one GH200):

case throughput
expert grouped GEMM alone 488-516 TFLOP/s
beside all-gather, 32 CTAs, no carveout 280-313
beside all-gather, 16 CTAs + carveout 16 380-458
dense bf16 GEMM alone, carveout 16 / 32 -5% / -14%

(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 stay fake (catches the override not reaching the mesh); config validation (catches typos in axis names silently doing nothing).

@pytorch-bot pytorch-bot Bot added the ciflow/fake-pg Run 1-GPU Fake PG integration tests label Nov 7, 2026
@meta-cla meta-cla Bot added the CLA Signed This label is managed by the Meta Open Source bot. label Nov 7, 2026
@pytorch-bot

pytorch-bot Bot commented Nov 7, 2026

Copy link
Copy Markdown

The following ciflow label(s) have been added but CI has not been triggered yet because the workflows are awaiting approval:

  • ciflow/fake-pg

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.

@rakkit

rakkit commented Nov 7, 2026

Copy link
Copy Markdown
Contributor Author

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..

@tianyu-l

tianyu-l commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

@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?

@claude

claude Bot commented Nov 8, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 3m 2s —— View job


Request changes: the motivation holds up, but the NCCL-specific logic should move behind per-backend options objects. The review gives three design options.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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

  1. Design: NCCL-specific code in core config and mesh construction, duplicating build_alternative_fsdp_mesh. Fix: options A+B above.
  2. parallelism_context.py:305 -- "nccl" is hardcoded. It fails late on non-NCCL devices and drops gloo when fsdp_enable_cpu_offloading is on.
  3. training_engine.py:331 -- the setting is silently ignored under fake backends. It should raise in __post_init__.
  4. training_engine.py:337 -- private API with no TODO issue link, and no device check.
  5. 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 from MeshAxisName instead of copying it.
  • test_parallelism_context.py:1198 -- the mock-based test swallows AssertionError. 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.

Comment on lines +305 to +306
elif axis in self.nccl_ctas:
backend_override[axis] = _nccl_with_ctas(self.nccl_ctas[axis])

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 hits AttributeError on dist.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_distributed uses "cuda:nccl,cpu:gloo" (distributed/utils.py:548). This override switches the axis to plain "nccl" and drops gloo, so CPU-tensor collectives on dp_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.

Comment thread torchtitan/training_engine.py Outdated
config.parallelism,
topology,
dump_folder=self.output_dir,
nccl_ctas=config.comm.nccl_ctas

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread torchtitan/training_engine.py Outdated
Comment on lines +335 to +337
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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment thread torchtitan/config/configs.py Outdated
"""

def __post_init__(self) -> None:
axes = {"pp", "dp_replicate", "dp_shard", "cp", "tp", "dp", "ep", "edp_shard"}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +1198 to +1205
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

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

@tianyu-l

tianyu-l commented Nov 8, 2026

Copy link
Copy Markdown
Contributor

@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.
@rakkit
rakkit force-pushed the comm-nccl-ctas-sm-carveout branch from e5e18e1 to 17addd9 Compare November 13, 2026 12:56
@rakkit
rakkit requested a review from d4l3k as a code owner November 13, 2026 12:56
@rakkit

rakkit commented Nov 13, 2026 •

Copy link
Copy Markdown
Contributor Author

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:

config.comm = CommConfig(
    process_group_options={
        "dp_shard": NCCLProcessGroupOptions.Config(min_ctas=16, max_ctas=16),
    },
    sm_carveout=16,
)

Comment on lines +162 to +164
process_group_options: "dict[str, NCCLProcessGroupOptions.Config]" = field(
default_factory=dict
)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

from torchtitan.config.configurable import Configurable


class NCCLProcessGroupOptions(Configurable):

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

should this be a config dataclass only, and provide backend_override as a property?

@tianyu-l

Copy link
Copy Markdown
Contributor

@claude review again

@claude

claude Bot commented Nov 17, 2026 •

Copy link
Copy Markdown
Contributor

Claude finished @tianyu-l's task in 2m 15s —— View job


Request changes: @tianyu-l's three comments are still open, and typos in axis names are silently ignored again. See the review.

@claude claude Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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) group

Earlier must-fix items

  1. Design A+B: A resolved. B is partly done, see @tianyu-l's comments below.
  2. Hardcoded "nccl": still open. On XPU, dist.ProcessGroupNCCL raises AttributeError at engine init, not at config time. With fsdp_enable_cpu_offloading, the world group is "cuda:nccl,cpu:gloo" (distributed/utils.py:570), and the override replaces it with plain "nccl" on dp_shard. Either raise for that combination or keep gloo. Unverified on GPU.
  3. Silent no-op under fake backends: resolved (configs.py:195).
  4. Private torch._C._set_sm_carveout_experimental: still open, and the TODO was removed (distributed/utils.py:545). Add a TODO with an upstream issue link (CLAUDE.md principle 3).
  5. 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

  1. @tianyu-l configs.py:164: make DistMuon's max_nccl_ctas_for_comms: int = -1 an options config, e.g. comm_process_group_options: NCCLProcessGroupOptions.Config | None = None. This removes the <= 0 "disabled" sentinel (rules/config.md). build_alternative_fsdp_mesh then takes the config directly and only adds split_share = 0.
  2. @tianyu-l process_group_options.py:32: make it a plain config dataclass with a backend_override property. Correct. The Configurable instance 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 ...}.
  3. @tianyu-l process_group_options.py:14: add a neutral ProcessGroupOptions base. This reverses my earlier "no base until a second backend" advice. The base has a current consumer, the CommConfig.process_group_options type, and it keeps the vendor name out of core config. Keep it minimal: only an abstract backend_override. The backend-availability check from item 2 above belongs in the subclass's __post_init__ (dist.is_nccl_available()).
  4. parallelism_context.py:303 -- unknown axis names are silently ignored; validate against MeshAxisName (inline).
  5. 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_carveout is 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.

Comment on lines +303 to +304
elif axis in self.axis_backend_overrides:
backend_override[axis] = self.axis_backend_overrides[axis]

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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).

Comment on lines +95 to +100
@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)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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.

Comment on lines +171 to +174
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."""

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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 branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

ciflow/fake-pg Run 1-GPU Fake PG integration tests CLA Signed This label is managed by the Meta Open Source bot.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants