Repository navigation
fix(gdn): toggle sequence parallelism on the projection parameters too #242
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
li-lizhe
wants to merge
2
commits into
modelscope:main
Choose a base branch
from
li-lizhe:fix/gdn-gamma-tp-finalize
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.
+191
−5
Open
Changes from 1 commit
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
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,95 @@ | ||
| # Copyright (c) ModelScope Contributors. All rights reserved. | ||
| """The GDN sequence-parallel toggle has to reach the projection parameters. | ||
|
|
||
| ``GatedDeltaNet`` gathers the sequence before the projections and turns sequence parallelism off on them for | ||
| that call, because Transformer Engine then all-reduces the projection gradient itself. Megatron's gradient | ||
| finalizer decides from ``param.sequence_parallel`` (see ``finalize_model_grads``) whether a gradient still | ||
| has to be summed over the tensor parallel group, so the flag has to be off on the parameters as well: with | ||
| only the module attribute off, the finalizer sums the already complete gamma gradient once more and | ||
| multiplies it by the tensor parallel size. Parameters that do not carry the flag are left alone. | ||
| """ | ||
| import pytest | ||
| import torch | ||
| import torch.nn as nn | ||
| from types import SimpleNamespace | ||
|
|
||
|
|
||
| class _FakeLayerNormLinear(nn.Module): | ||
| """Stand-in for a Transformer Engine ``LayerNormLinear``. | ||
|
|
||
| Transformer Engine flags the module and the parameters it wants reduced over the tensor parallel group | ||
| with ``sequence_parallel``; ``layer_norm_weight`` is the one the reported case loses in the finalizer. | ||
| """ | ||
|
|
||
| def __init__(self, sequence_parallel: bool = True, mark_parameters: bool = True): | ||
| super().__init__() | ||
| self.sequence_parallel = sequence_parallel | ||
| self.layer_norm_weight = nn.Parameter(torch.ones(4)) | ||
| self.weight = nn.Parameter(torch.ones(2, 4)) | ||
| if mark_parameters: | ||
| self.layer_norm_weight.sequence_parallel = sequence_parallel | ||
|
|
||
|
|
||
| def _gdn(): | ||
| """Return ``GatedDeltaNet``, skipping the module when Megatron is not installed.""" | ||
| pytest.importorskip('megatron.core') | ||
| from mcore_bridge.model.modules.gated_delta_net import GatedDeltaNet | ||
| return GatedDeltaNet | ||
|
|
||
|
|
||
| def _projections(**modules): | ||
| """Only the four projection attributes the toggle walks are needed.""" | ||
| attributes = {'in_proj': None, 'in_proj_qkvz': None, 'in_proj_ba': None, 'out_proj': None} | ||
| attributes.update(modules) | ||
| return SimpleNamespace(**attributes) | ||
|
|
||
|
|
||
| def _finalize_layernorm_grad(param, tp_size): | ||
| """Megatron's branch: a sequence-parallel parameter has its complete gradient summed over the TP group.""" | ||
| if getattr(param, 'sequence_parallel', False): | ||
| return param.main_grad * tp_size | ||
| return param.main_grad | ||
|
|
||
|
|
||
| def test_toggle_marks_the_parameters_and_the_restore_keeps_them_off(): | ||
| gated_delta_net = _gdn() | ||
| layer = _FakeLayerNormLinear() | ||
| model = _projections(in_proj=layer) | ||
| saved = gated_delta_net._set_linear_sequence_parallel(model, False) | ||
|
|
||
| assert layer.sequence_parallel is False | ||
| assert layer.layer_norm_weight.sequence_parallel is False | ||
| assert len(saved) == 2 | ||
| assert saved[0][0] is layer | ||
| assert saved[1][0] is layer.layer_norm_weight | ||
|
|
||
| gated_delta_net._restore_linear_sequence_parallel(model, saved) | ||
| # The module goes back to its configured value, the parameter stays off: the finalizer reads it after | ||
| # the backward, long after the module attribute was restored. | ||
| assert layer.sequence_parallel is True | ||
| assert layer.layer_norm_weight.sequence_parallel is False | ||
|
|
||
|
|
||
| def test_the_finalizer_leaves_the_gamma_gradient_unscaled(): | ||
| gated_delta_net = _gdn() | ||
| layer = _FakeLayerNormLinear() | ||
| model = _projections(in_proj=layer) | ||
| saved = gated_delta_net._set_linear_sequence_parallel(model, False) | ||
| gated_delta_net._restore_linear_sequence_parallel(model, saved) | ||
|
|
||
| layer.layer_norm_weight.main_grad = torch.ones(4) | ||
| assert torch.equal(_finalize_layernorm_grad(layer.layer_norm_weight, 4), torch.ones(4)) | ||
|
|
||
|
|
||
| def test_parameters_without_the_flag_are_left_alone(): | ||
| gated_delta_net = _gdn() | ||
| layer = _FakeLayerNormLinear(mark_parameters=False) | ||
| model = _projections(in_proj=layer) | ||
| saved = gated_delta_net._set_linear_sequence_parallel(model, False) | ||
|
|
||
| assert not hasattr(layer.weight, 'sequence_parallel') | ||
| assert len(saved) == 1 | ||
| assert saved[0][0] is layer | ||
|
|
||
| gated_delta_net._restore_linear_sequence_parallel(model, saved) | ||
| assert layer.sequence_parallel is True | ||
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.
Can this be replaced with the Megatron API?