-
Notifications
You must be signed in to change notification settings - Fork 4.4k
Add FSDP NVTX annotations #5704
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
123 changes: 123 additions & 0 deletions
123
tests/unit_tests/distributed/mfsdp_v1/test_annotation.py
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,123 @@ | ||
| # Copyright (c) 2026, NVIDIA CORPORATION. All rights reserved. | ||
|
|
||
| """Unit tests for experimental Megatron-FSDP annotations.""" | ||
|
|
||
| import re | ||
| from typing import Literal, NamedTuple | ||
|
|
||
| import pytest | ||
| import torch | ||
| from torch import nn | ||
| from torch.distributed.device_mesh import init_device_mesh | ||
|
|
||
| from megatron.core.distributed.fsdp.src.megatron_fsdp.experimental import ( | ||
| Flat, | ||
| Placements, | ||
| fully_shard, | ||
| ) | ||
|
|
||
| _NVTX_LABEL_PATTERN = re.compile(r"MFSDP (.+) (forward|backward)") | ||
|
|
||
|
|
||
| class NvtxEvent(NamedTuple): | ||
| kind: Literal["push", "pop"] | ||
| name: str | ||
| phase: str | ||
|
|
||
|
|
||
| class NestedLinearModel(nn.Module): | ||
| def __init__(self, dim: int) -> None: | ||
| super().__init__() | ||
| self.bias = nn.Parameter(torch.ones(dim)) | ||
| self.layers = nn.ModuleList([nn.Linear(dim, dim, bias=False) for _ in range(2)]) | ||
|
|
||
| def forward(self, x: torch.Tensor) -> torch.Tensor: | ||
| x = x + self.bias | ||
| for layer in self.layers: | ||
| x = torch.relu(layer(x)) | ||
| return x | ||
|
|
||
|
|
||
| def _flat_placements() -> Placements: | ||
| return Placements(dp_axes=[0], parameter=[Flat()], gradient=[Flat()], optimizer=[Flat()]) | ||
|
|
||
|
|
||
| def _setup_nvtx_recording(monkeypatch: pytest.MonkeyPatch, events: list[NvtxEvent]) -> None: | ||
| label_stack: list[tuple[str, str]] = [] | ||
|
|
||
| def parse_nvtx_label(label: str) -> tuple[str, str]: | ||
| match = _NVTX_LABEL_PATTERN.fullmatch(label) | ||
| assert match is not None | ||
| return match.groups() | ||
|
|
||
| def record_push(label: str) -> None: | ||
| name, phase = parse_nvtx_label(label) | ||
| label_stack.append((name, phase)) | ||
| events.append(NvtxEvent("push", name, phase)) | ||
|
|
||
| def record_pop() -> None: | ||
| name, phase = label_stack.pop() | ||
| events.append(NvtxEvent("pop", name, phase)) | ||
|
|
||
| monkeypatch.setattr(torch.cuda.nvtx, "range_push", record_push) | ||
| monkeypatch.setattr(torch.cuda.nvtx, "range_pop", record_pop) | ||
|
|
||
|
|
||
| def _get_distributed_setup(request: pytest.FixtureRequest): | ||
| try: | ||
| return request.getfixturevalue("distributed_setup") | ||
| except pytest.FixtureLookupError: | ||
| pytest.skip("distributed_setup fixture is only available in the Megatron-FSDP test bucket") | ||
|
|
||
|
|
||
| def test_fsdp_sibling_roots_emit_root_nvtx_ranges_after_training_step(request, monkeypatch): | ||
| """Independent FSDP roots should each emit root-labeled NVTX ranges.""" | ||
| distributed_setup = _get_distributed_setup(request) | ||
| events: list[NvtxEvent] = [] | ||
| _setup_nvtx_recording(monkeypatch, events) | ||
| model = NestedLinearModel(dim=4).to(distributed_setup.device) | ||
| mesh = init_device_mesh(distributed_setup.device.type, (distributed_setup.world_size,)) | ||
| fully_shard(model.layers[0], mesh=mesh, placements=_flat_placements()) | ||
| fully_shard(model.layers[1], mesh=mesh, placements=_flat_placements()) | ||
|
|
||
| model(torch.ones(2, 4, device=distributed_setup.device)).sum().backward() | ||
|
|
||
| assert [(event.kind, event.name, event.phase) for event in events] == [ | ||
| ("push", "<root>", "forward"), | ||
| ("pop", "<root>", "forward"), | ||
| ("push", "<root>", "forward"), | ||
| ("pop", "<root>", "forward"), | ||
| ("push", "<root>", "backward"), | ||
| ("pop", "<root>", "backward"), | ||
| ("push", "<root>", "backward"), | ||
| ("pop", "<root>", "backward"), | ||
| ] | ||
|
|
||
|
|
||
| def test_fsdp_training_hooks_emit_stacked_nvtx_ranges(request, monkeypatch): | ||
| """Nested training hooks should emit concise NVTX ranges.""" | ||
| distributed_setup = _get_distributed_setup(request) | ||
| events: list[NvtxEvent] = [] | ||
| _setup_nvtx_recording(monkeypatch, events) | ||
| model = NestedLinearModel(dim=4).to(distributed_setup.device) | ||
| mesh = init_device_mesh(distributed_setup.device.type, (distributed_setup.world_size,)) | ||
| fully_shard(model.layers[0], mesh=mesh, placements=_flat_placements()) | ||
| fully_shard(model.layers[1], mesh=mesh, placements=_flat_placements()) | ||
| fully_shard(model, mesh=mesh, placements=_flat_placements()) | ||
|
|
||
| model(torch.ones(2, 4, device=distributed_setup.device)).sum().backward() | ||
|
|
||
| assert [(event.kind, event.name, event.phase) for event in events] == [ | ||
| ("push", "<root>", "forward"), | ||
| ("push", "layers.0", "forward"), | ||
| ("pop", "layers.0", "forward"), | ||
| ("push", "layers.1", "forward"), | ||
| ("pop", "layers.1", "forward"), | ||
| ("pop", "<root>", "forward"), | ||
| ("push", "<root>", "backward"), | ||
| ("push", "layers.1", "backward"), | ||
| ("pop", "layers.1", "backward"), | ||
| ("push", "layers.0", "backward"), | ||
| ("pop", "layers.0", "backward"), | ||
| ("pop", "<root>", "backward"), | ||
| ] |
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Non-blocking:
pre_backwardalways pushes an NVTX range, but the matching pop happens inpost_backward, which only fires from the grad-completion hook once_ready_grad_parameters == _num_training_parameters. For an FSDP unit that owns only frozen params (_num_training_parameters == 0), no grad hooks are registered sopost_backwardnever runs — yetpre_backwardstill pushes if the module output requires grad. That leaves the NVTX stack unbalanced. Profiling-only and an uncommon config, but worth guarding (e.g. skip the push/pop, or drive post_backward off the module backward hook when there are no trainable params).There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Good catch -- will be fixed in #5710