Skip to content

Add fast_set_attr to modules not inheriting from base.py - #2724

Merged
vthumbe1503 merged 3 commits into
NVIDIA:mainfrom
vthumbe1503:fsdp_example_test_fix
Mar 3, 2026
Merged

vthumbe1503 merged 3 commits into
NVIDIA:mainfrom
vthumbe1503:fsdp_example_test_fix

Conversation

@vthumbe1503

Copy link
Copy Markdown
Collaborator

Description

Please include a brief summary of the changes, relevant motivation and context.

Fixes # (issue)

Type of change

  • Documentation change (change only to the documentation, either a fix or a new content)
  • Bug fix (non-breaking change which fixes an issue)
  • New feature (non-breaking change which adds functionality)
  • Breaking change (fix or feature that would cause existing functionality to not work as expected)
  • Infra/Build change
  • Code refactoring

Changes

Please list the changes introduced in this PR:

  • Change A
  • Change B

Checklist:

  • I have read and followed the contributing guidelines
  • The functionality is complete
  • I have commented my code, particularly in hard-to-understand areas
  • I have made corresponding changes to the documentation
  • My changes generate no new warnings
  • I have added tests that prove my fix is effective or that my feature works
  • New and existing unit tests pass locally with my changes

Signed-off-by: Varun Thumbe <vthumbe@nvidia.com>
@vthumbe1503
vthumbe1503 requested a review from ptrendx March 2, 2026 20:49
@vthumbe1503
vthumbe1503 marked this pull request as ready for review March 2, 2026 20:50
@greptile-apps

greptile-apps Bot commented Mar 2, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes an AttributeError crash by adding a fast_setattr method to five TE modules that are recognized as TE modules by _is_te_module in distributed.py but do not inherit from TransformerEngineBaseModule (which already defines this method). The affected classes are LayerNorm, RMSNorm, MultiheadAttention, UnfusedDotProductAttention, and TransformerLayer. Without this fix, prepare_te_modules_for_fsdp would raise AttributeError when calling module.fast_setattr("fsdp_group", ...) on any of these modules.

Key observations:

  • The fix is functionally correct — all five classes are listed in te_classes_list inside both _is_te_module and has_te_modules, and prepare_te_modules_for_fsdp calls fast_setattr on every module that passes the _is_te_module check.
  • DotProductAttention (also in te_classes_list) already inherits from TransformerEngineBaseModule and is unaffected.
  • The new fast_setattr implementations are identical to the one in TransformerEngineBaseModule.base.py in behavior, but duplicate the code five times; a mixin class would be a cleaner approach.
  • All five new docstrings are less informative than the original in base.py — they omit the important caveat that the method must not be used for properties or registered parameters/buffers.
  • The PR description checklist is largely unchecked and contains only placeholder text with no description of the actual change, motivation, or test coverage.

Confidence Score: 4/5

  • This PR is safe to merge — it fixes a real crash with a correct implementation — but code duplication is a minor concern.
  • The fix is functionally correct and targets a genuine bug (AttributeError when FSDP wrapping non-base TE modules). The implementation is identical to the existing pattern in base.py. The only concerns are code duplication (same 4-line method in 6 places instead of a mixin) and slightly weaker docstrings — neither affects correctness. No tests are added to verify the fix.
  • No files require special attention beyond the style/duplication concern present uniformly across all five changed files.

Important Files Changed

Filename Overview
transformer_engine/pytorch/module/layernorm.py Adds fast_setattr to LayerNorm (which inherits from _LayerNormOp/BasicOperation, not TransformerEngineBaseModule) so that prepare_te_modules_for_fsdp in distributed.py can call it without raising AttributeError; implementation is functionally correct but duplicates code from base.py with a weaker docstring.
transformer_engine/pytorch/module/rmsnorm.py Same fast_setattr addition as LayerNorm; RMSNorm inherits from _RMSNormOp/BasicOperation, not TransformerEngineBaseModule; functionally correct but has the same duplication and docstring issues.
transformer_engine/pytorch/attention/multi_head_attention.py Adds fast_setattr to MultiheadAttention (pure torch.nn.Module subclass); also adds Any to the typing imports; change is correct but duplicates the pattern from base.py.
transformer_engine/pytorch/attention/dot_product_attention/backends.py Adds fast_setattr to UnfusedDotProductAttention (pure torch.nn.Module subclass); Any was already imported; functionally correct.
transformer_engine/pytorch/transformer.py Adds fast_setattr to TransformerLayer (pure torch.nn.Module subclass) and adds Any to typing imports; same duplication and docstring quality concerns as other files.

Flowchart

%%{init: {'theme': 'neutral'}}%%
flowchart TD
    A["prepare_te_modules_for_fsdp(fsdp_root)"] --> B{"_is_te_module(module)?"}
    B -->|Yes| C["module.fast_setattr('fsdp_group', process_group)"]
    B -->|No| D[Skip]

    C --> E{Inherits from\nTransformerEngineBaseModule?}
    E -->|Yes - DotProductAttention,\nLinear, LayerNormLinear,\nLayerNormMLP, etc.| F["fast_setattr defined in base.py ✅"]
    E -->|No - before this PR| G["AttributeError ❌\nfast_setattr not found"]
    E -->|No - after this PR| H["fast_setattr defined in class ✅\nLayerNorm, RMSNorm,\nMultiheadAttention,\nUnfusedDotProductAttention,\nTransformerLayer"]

    F --> I["self.__dict__[name] = value\n(bypasses torch.nn.Module.__setattr__)"]
    H --> I
Loading

Last reviewed commit: d099cfc

@greptile-apps greptile-apps 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.

5 files reviewed, 2 comments

Edit Code Review Agent Settings | Greptile

@vthumbe1503

Copy link
Copy Markdown
Collaborator Author

/te-ci L1 pytorch

@vthumbe1503
vthumbe1503 merged commit c68ec31 into NVIDIA:main Mar 3, 2026
9 of 12 checks passed
Comment on lines +105 to +107
def fast_setattr(self, name: str, value: Any) -> None:
"""Fast attribute set for non-parameter fields."""
self.__dict__[name] = value

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.

Code duplication across 5 new fast_setattr implementations

The same 4-line fast_setattr method is now copy-pasted into LayerNorm, RMSNorm, MultiheadAttention, UnfusedDotProductAttention, and TransformerLayer, in addition to the existing definition in TransformerEngineBaseModule. A lightweight mixin would eliminate this duplication and ensure consistency:

class _FastSetAttrMixin:
    def fast_setattr(self, name: str, value: Any) -> None:
        """
        Fast version of the Module's set attribute function.
        Should be used for regular attributes, but not properties nor parameters/buffers.
        """
        self.__dict__[name] = value

Then each class can simply inherit from this mixin. This also reduces the risk of the implementations diverging in the future (e.g., if the base class docstring is updated but the copies are forgotten).

This same duplication exists at transformer_engine/pytorch/module/rmsnorm.py:109-111, transformer_engine/pytorch/attention/multi_head_attention.py:481-483, transformer_engine/pytorch/attention/dot_product_attention/backends.py:296-298, and transformer_engine/pytorch/transformer.py:548-550.

Comment on lines +105 to +107
def fast_setattr(self, name: str, value: Any) -> None:
"""Fast attribute set for non-parameter fields."""
self.__dict__[name] = value

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.

Incomplete docstring compared to base.py

The docstring here (and in all four other new fast_setattr implementations) is less informative than the one in TransformerEngineBaseModule:

# base.py docstring (full):
Fast version of the Module's set attribute function.
Should be used for regular attributes, but not properties nor parameters/buffers.

# new docstring (incomplete):
Fast attribute set for non-parameter fields.

The key warning — "not properties nor parameters/buffers" — is missing. Because this method bypasses torch.nn.Module.__setattr__ entirely, using it to set a parameter name or a property will silently shadow the parameter/buffer with a plain dict entry rather than updating it correctly, which can cause subtle, hard-to-debug issues. The full constraint should be documented.

Suggested change
def fast_setattr(self, name: str, value: Any) -> None:
"""Fast attribute set for non-parameter fields."""
self.__dict__[name] = value
def fast_setattr(self, name: str, value: Any) -> None:
"""
Fast version of the Module's set attribute function.
Should be used for regular attributes, but not properties nor parameters/buffers.
"""
self.__dict__[name] = value

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

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants