-
Notifications
You must be signed in to change notification settings - Fork 202
Add L2NormHook and use it in megatron.py #599
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
danielkorzekwa
merged 19 commits into
feature/compress
from
dkorzekwa/pruning_scores_redesign_new
Nov 26, 2025
Merged
Changes from all commits
Commits
Show all changes
19 commits
Select commit
Hold shift + click to select a range
659742d
Add L2NormHook and use it in megatron.py
danielkorzekwa 60d98c6
Add TODO
danielkorzekwa 3242dd0
rename hooks.py to megatron_hooks.py
danielkorzekwa 85b0229
Remove not needed if (it was not there before)
danielkorzekwa 5bdb08b
Support moe layer in L2NormHook
danielkorzekwa b5de20a
debugging
danielkorzekwa 889eb4b
debugging
danielkorzekwa 675dca4
debugging
danielkorzekwa 9526a0d
debugging
danielkorzekwa dedc036
Fix broken unit tests -initialize model weights on CPU.
danielkorzekwa f5b85bf
debugging
danielkorzekwa 839ba74
debugging
danielkorzekwa 594127e
Reduce assert precision from 1e-5 to 1e-3
danielkorzekwa 1b70f3d
enable all tests
danielkorzekwa 992058c
remove debug messages
danielkorzekwa 674e823
Update modelopt/torch/nas/plugins/megatron.py
danielkorzekwa f6fc88b
Update modelopt/torch/nas/plugins/megatron.py
danielkorzekwa 0ba14fd
Update modelopt/torch/nas/plugins/megatron_hooks.py
danielkorzekwa 5aaaf1a
RenameL2NormHook to MegatronL2NormHook
danielkorzekwa 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,104 @@ | ||
| # SPDX-FileCopyrightText: Copyright (c) 2024 NVIDIA CORPORATION & AFFILIATES. All rights reserved. | ||
AAnoosheh marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| # SPDX-License-Identifier: Apache-2.0 | ||
| # | ||
| # Licensed under the Apache License, Version 2.0 (the "License"); | ||
| # you may not use this file except in compliance with the License. | ||
| # You may obtain a copy of the License at | ||
| # | ||
| # http://www.apache.org/licenses/LICENSE-2.0 | ||
| # | ||
| # Unless required by applicable law or agreed to in writing, software | ||
| # distributed under the License is distributed on an "AS IS" BASIS, | ||
| # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| # See the License for the specific language governing permissions and | ||
| # limitations under the License. | ||
| """Forward hooks for activation-based importance estimation (megatron NAS plugin).""" | ||
|
|
||
| from abc import ABC, abstractmethod | ||
|
|
||
| import torch | ||
| from megatron.core.tensor_parallel import gather_from_tensor_model_parallel_region | ||
| from torch import nn | ||
|
|
||
|
|
||
| class ForwardHook(ABC): | ||
| """Base class for PyTorch forward hooks. | ||
|
|
||
| This follows the PyTorch forward hook API where the second | ||
| parameter is 'args' (a tuple of positional arguments passed to forward()). | ||
|
|
||
| Usage: | ||
| hook = MyHook() | ||
| module.register_forward_hook(hook) | ||
| """ | ||
|
|
||
| @abstractmethod | ||
| def __call__( | ||
| self, module: nn.Module, args: tuple[torch.Tensor, ...], output: torch.Tensor | ||
| ) -> None: | ||
| """Forward hook that is called after the module's forward pass. | ||
|
|
||
| Args: | ||
| module: The module this hook is registered on | ||
| args: Tuple of positional arguments passed to module.forward() | ||
| output: The output from module.forward() | ||
|
|
||
| Returns: | ||
| None (does not modify the output) | ||
| """ | ||
| ... | ||
|
|
||
|
|
||
| class MegatronL2NormHook(ForwardHook): | ||
| """Hook for accumulating activation statistics for importance estimation. | ||
|
|
||
| Activations are computed as mean over seq_len and then squared and summed over batch_size. | ||
| In the accumulate() method we take the square root of the sum to get the L2 norm. | ||
|
|
||
| Args: | ||
| max_size: Optional maximum expected size to validate against (skips if mismatch). | ||
| Useful for skipping non-max subnets during profiling. | ||
| """ | ||
|
|
||
| def __init__(self, max_size: int | None = None): | ||
| """Initialize the L2NormHook.""" | ||
| self.max_size = max_size | ||
| self._activations: torch.Tensor | None = None | ||
|
|
||
| def __call__( | ||
| self, module: nn.Module, args: tuple[torch.Tensor, ...], output: torch.Tensor | ||
| ) -> None: | ||
| """Accumulate activation statistics from the forward pass.""" | ||
| # Gather input [seq_len, batch_size, hidden_size] over all TP regions | ||
| # NOTE: This is not used at the moment since we restrict to TP=1 | ||
| input_tensor = gather_from_tensor_model_parallel_region(args[0]).detach() | ||
|
|
||
| if input_tensor.dim() == 2: | ||
| # For sparse experts, there is no batch dimension. | ||
| input_tensor = input_tensor[:, None, :] | ||
|
|
||
| # Dont aggregate activations from non-max subnets (e.g. from profiling) | ||
| if self.max_size is not None and input_tensor.shape[-1] != self.max_size: | ||
| return | ||
|
|
||
| input_tensor = input_tensor.to(torch.float32) # use full precision to avoid overflow | ||
| activations = input_tensor.abs().mean(dim=0) # [batch_size, hidden_size] | ||
| activations = activations.pow(2).sum(dim=0) # [hidden_size] | ||
|
|
||
| if self._activations is None: | ||
| self._activations = activations | ||
| else: | ||
| self._activations += activations | ||
|
|
||
| def accumulate(self) -> torch.Tensor: | ||
| """Return the accumulated L2 norm of activations. | ||
|
|
||
| Returns: | ||
| Tensor of accumulated scores, one per channel | ||
|
|
||
| Raises: | ||
| AssertionError: If no activations have been collected yet | ||
| """ | ||
| assert self._activations is not None, "No activations collected for importance estimation." | ||
| # Convert squared sum to L2 norm | ||
| return self._activations.pow(0.5) | ||
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
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.
even if we register hook_handle as temp attribute, we still need to call
hook_handle.remove()to remove the hook so there's no change. Temp attribute will be remove from model i.e.self.hook_handlereference will be dropped but that still doesnt remove the actuall pytorch hook added to the forwardThere 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.
I understand now.