-
Notifications
You must be signed in to change notification settings - Fork 774
Fix duplicate FP8 state updates during activation checkpoint recomputation #3213
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
Open
AlbertYang514
wants to merge
3
commits into
NVIDIA:main
Choose a base branch
from
AlbertYang514:fix/checkpoint-fp8-update-bookkeeping-main
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,158 @@ | ||
| # Copyright (c) 2022-2026, NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
| # | ||
| # See LICENSE for license information. | ||
|
|
||
| """Regression tests for FP8 update ownership during activation recompute.""" | ||
|
|
||
| import pytest | ||
| import torch | ||
|
|
||
| import transformer_engine.pytorch as te | ||
| from transformer_engine.common import recipe | ||
| from transformer_engine.pytorch.distributed import ( | ||
| in_fp8_activation_recompute_phase, | ||
| is_fp8_activation_recompute_enabled, | ||
| ) | ||
| from transformer_engine.pytorch.quantization import FP8GlobalStateManager | ||
|
|
||
|
|
||
| fp8_available, reason_for_no_fp8 = te.is_fp8_available(return_reason=True) | ||
|
|
||
|
|
||
| @pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8) | ||
| @pytest.mark.parametrize( | ||
| ("checkpoint_mode", "segments", "num_layers"), | ||
| ( | ||
| ("none", "single", 3), | ||
| ("non-reentrant", "single", 3), | ||
| ("non-reentrant", "per-layer", 3), | ||
| ("reentrant", "single", 1), | ||
| ("reentrant", "single", 3), | ||
| ("reentrant", "per-layer", 3), | ||
| ("nested-reentrant", "nested", 3), | ||
| ), | ||
| ) | ||
| def test_delayed_scaling_updates_once_per_autocast( | ||
| monkeypatch, checkpoint_mode, segments, num_layers | ||
| ): | ||
| """Activation recompute must not advance global FP8 state per module/segment.""" | ||
|
|
||
| FP8GlobalStateManager.reset() | ||
| counts = {"forward": 0, "backward": 0} | ||
| original_update = FP8GlobalStateManager.reduce_and_update_fp8_tensors | ||
|
|
||
| def counted_update(_cls, forward=True): | ||
| counts["forward" if forward else "backward"] += 1 | ||
| return original_update(forward=forward) | ||
|
|
||
| monkeypatch.setattr( | ||
| FP8GlobalStateManager, | ||
| "reduce_and_update_fp8_tensors", | ||
| classmethod(counted_update), | ||
| ) | ||
|
|
||
| torch.manual_seed(20260715) | ||
| torch.cuda.manual_seed_all(20260715) | ||
| layers = [ | ||
| te.Linear(16, 16, bias=False, params_dtype=torch.float32).cuda() for _ in range(num_layers) | ||
| ] | ||
| network = torch.nn.Sequential(*layers) | ||
| inp = torch.randn( | ||
| 16, | ||
| 16, | ||
| device="cuda", | ||
| dtype=torch.bfloat16, | ||
| requires_grad=True, | ||
| ) | ||
| fp8_recipe = recipe.DelayedScaling(fp8_format=recipe.Format.HYBRID) | ||
|
|
||
| with torch.autocast("cuda", dtype=torch.bfloat16), te.autocast( | ||
| enabled=True, | ||
| recipe=fp8_recipe, | ||
| ): | ||
| if checkpoint_mode == "none": | ||
| out = network(inp) | ||
| elif checkpoint_mode == "nested-reentrant": | ||
|
|
||
| def inner(x): | ||
| return layers[0](x) | ||
|
|
||
| def outer(x): | ||
| x = te.checkpoint(inner, x, use_reentrant=True) | ||
| for layer in layers[1:]: | ||
| x = layer(x) | ||
| return x | ||
|
|
||
| out = te.checkpoint(outer, inp, use_reentrant=True) | ||
| elif segments == "single": | ||
| out = te.checkpoint( | ||
| network, | ||
| inp, | ||
| use_reentrant=checkpoint_mode == "reentrant", | ||
| ) | ||
| else: | ||
| out = inp | ||
| for layer in layers: | ||
| out = te.checkpoint( | ||
| layer, | ||
| out, | ||
| use_reentrant=checkpoint_mode == "reentrant", | ||
| ) | ||
| loss = out.float().sum() | ||
|
|
||
| loss.backward() | ||
| torch.cuda.synchronize() | ||
|
|
||
| assert torch.isfinite(loss) | ||
| assert inp.grad is not None | ||
| assert torch.isfinite(inp.grad).all() | ||
| assert inp.grad.abs().max() > 0 | ||
| for layer in layers: | ||
| assert layer.weight.grad is not None | ||
| assert torch.isfinite(layer.weight.grad).all() | ||
| assert layer.weight.grad.abs().max() > 0 | ||
| assert counts == {"forward": 1, "backward": 1} | ||
| assert FP8GlobalStateManager.quantization_state.autocast_depth == 0 | ||
| assert not FP8GlobalStateManager.is_fp8_enabled() | ||
| assert not is_fp8_activation_recompute_enabled() | ||
| assert not in_fp8_activation_recompute_phase() | ||
|
|
||
|
|
||
| @pytest.mark.skipif(not fp8_available, reason=reason_for_no_fp8) | ||
| def test_reentrant_checkpoint_gradients_match_uncheckpointed(): | ||
| """Reentrant recompute should preserve the uncheckpointed FP8 numerics.""" | ||
|
|
||
| def run(checkpoint): | ||
| FP8GlobalStateManager.reset() | ||
| torch.manual_seed(20260715) | ||
| torch.cuda.manual_seed_all(20260715) | ||
| layers = [ | ||
| te.Linear(16, 16, bias=False, params_dtype=torch.float32).cuda() for _ in range(3) | ||
| ] | ||
| network = torch.nn.Sequential(*layers) | ||
| inp = torch.randn( | ||
| 16, | ||
| 16, | ||
| device="cuda", | ||
| dtype=torch.bfloat16, | ||
| requires_grad=True, | ||
| ) | ||
| fp8_recipe = recipe.DelayedScaling(fp8_format=recipe.Format.HYBRID) | ||
| with torch.autocast("cuda", dtype=torch.bfloat16), te.autocast( | ||
| enabled=True, | ||
| recipe=fp8_recipe, | ||
| ): | ||
| out = te.checkpoint(network, inp, use_reentrant=True) if checkpoint else network(inp) | ||
| loss = out.float().sum() | ||
| loss.backward() | ||
| torch.cuda.synchronize() | ||
| return ( | ||
| loss.detach(), | ||
| inp.grad.detach(), | ||
| *(layer.weight.grad.detach() for layer in layers), | ||
| ) | ||
|
|
||
| reference = run(checkpoint=False) | ||
| checkpointed = run(checkpoint=True) | ||
| for actual, expected in zip(checkpointed, reference): | ||
| torch.testing.assert_close(actual, expected, rtol=0.05, atol=0.01) | ||
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
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
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
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
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.
Uh oh!
There was an error while loading. Please reload this page.