Skip to content

[PyTorch] Fix deferred initialization in fusible ops - #3327

Merged
denera merged 1 commit into
NVIDIA:mainfrom
denera:pytorch/fusible-ops-meta-init-fix
Oct 13, 2026
Merged

denera merged 1 commit into
NVIDIA:mainfrom
denera:pytorch/fusible-ops-meta-init-fix

Conversation

@denera

@denera denera commented Aug 7, 2026 •

Copy link
Copy Markdown
Collaborator

Description

Ops replace their params when materializing them on the first fuser forward pass, which invalidated the fuser's cached params and ops.Linear's parameter aliases. Backward then failed with a meta-vs-cuda device mismatch. This is an incorrect use of deferred initialization.

Deferred initialization requires invoking .reset_parameters() before the first fuser forward pass to materialize the parameters in fusible operations. This PR adds the missing .reset_parameters() implementations for te.ops.Linear(), te.ops.Bias() and te.ops.Sequential() in order to enable this workflow the same way deferred parameters are materialized on device for standard torch.nn.Modules and TE custom modules.

New tests added for deferred initialization with the affected ops. First-forward now raises error if it's invoked with unmaterialized meta-device params in any of the fusible ops.

Fixes #3322

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

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

@denera denera self-assigned this Aug 7, 2026
@denera
denera requested a review from timmoon10 as a code owner August 7, 2026 15:04
@greptile-apps

greptile-apps Bot commented Aug 7, 2026 •

Copy link
Copy Markdown
Contributor

RetriggerConfidence Score: 4/5

[Medium impact] Refactors deferred parameter initialization in PyTorch ops.

Fix resetting children inside plain nested containers before merging.

Findings

  1. P1 Nested parameters stay on meta ▶

Summary

The PR makes deferred initialization explicit: fusible ops must be reset before their first forward.

  • Fusible ops need their parameters reset before the first forward pass.
  • Quantized deferred weights keep their existing parameter references.

Diagram

%%{init: {'theme': 'neutral'}}%%
flowchart TD
  A[Construct ops on meta] --> B[Call reset_parameters]
  B --> C{Child has reset_parameters?}
  C -->|Yes| D[Reset child parameters]
  C -->|No| E[Skip child and its descendants]
  D --> F[First forward]
  E --> F
  F --> G{Any parameters on meta?}
  G -->|Yes| H[Raise RuntimeError]
  G -->|No| I[Run forward and backward]
Loading

Reviews (6) · Last reviewed commit: "[PyTorch] Fix deferred initialization in..." · Reviewed by Greptile

@denera

denera commented Aug 7, 2026

Copy link
Copy Markdown
Collaborator Author

/te-ci pytorch

@vthumbe1503 vthumbe1503 left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM, have some question and a minor suggestion for adding grouped_linear test case as well for quantized_model_int case

Comment thread tests/pytorch/test_fusible_ops.py Outdated
# Construct operation on meta device
recipe = make_recipe(quantization)
with te.quantized_model_init(enabled=quantized_weight, recipe=recipe):
op = te_ops.Linear(size, size, bias=True, device="meta", dtype=dtype)

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we extend this test for GroupedLinear as well?

Comment thread transformer_engine/pytorch/ops/fuser.py Outdated
Comment on lines +448 to +452
op.reset_recipe_state(recipe=recipe)
for op in self._ops:
op.pre_first_fuser_forward()

# Cache params now that ops have initialized them

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If somebody calls register_parameter on the ops in a later iteration, this means it would not get cached in fuser's parameter list

I know it is a weird use-case, and maybe nobody does this. But was this always intended, @timmoon10 ?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This gap actually gets resolved neatly with the new parameter versioning. Registering a new param bumps the version, which automatically invalidates the pre-existing cache and forces the fuser to re-cache and re-fuse.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

UPDATE: This mechanism is entirely removed now in favor of requiring explicit .reset_parameters() call before the first forward.

if op_type.startswith("grouped_linear"):
in_shape = (size * num_groups, size)
extra_inputs.append(torch.tensor([size] * num_groups, dtype=torch.int, device=device))
x = torch.randn(in_shape, dtype=dtype, device=device, requires_grad=True)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should test both requires_grad = True and False

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Materialization no longer happens in the forward pass. It requires an explicit .reset_parameters() call in line with how we support it in TE custom modules. So I dropped this parameterization entirely in the tests.

Comment thread tests/pytorch/test_fusible_ops.py Outdated
Comment on lines +775 to +784
# Check that params have been materialized
assert op.weight is op.basic_ops[op._linear_idx].weight
assert op.bias is op.basic_ops[op._bias_idx].bias
if quantized_weight:
assert isinstance(op.weight, QuantizedTensor)
for name, param in op.named_parameters():
assert param.device.type == device, f"{name} was not materialized on {device}"
assert param.grad is not None, f"{name} did not get a grad"
assert param.grad.device.type == device, f"{name} got a grad on {param.grad.device}"
assert x.grad is not None and x.grad.device.type == device

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

In addition to that there should be some testing that the resulting output/gradients actually match the op that did not go through this materialization step.

@timmoon10 timmoon10 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Are we sure there is actually a bug? I see this PR adds logic to defer some OperationFuser setup to the first forward pass. However, OperationFuser is an internal class that is only instantiated by Sequential in the first forward pass:

self._module_groups = self._make_module_groups(self._modules.values())

It's perfectly possible that different fusions are available with quantized/unquantized params, so trying to "fix" the OperationFuser is dangerous. If a change is detected, better to destroy and create a new one.


# Forward and backward pass
in_shape = (size, size)
extra_inputs = []

@vthumbe1503 vthumbe1503 Aug 10, 2026 •

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Isnt the normal flow for deferred initialization to call reset_parameters before doing the first forward pass?

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yes, the tests now follow this supported workflow.

@denera
denera force-pushed the pytorch/fusible-ops-meta-init-fix branch from 8f1fd24 to 0d12e9a Compare August 13, 2026 15:14
Comment thread tests/pytorch/test_fusible_ops.py Outdated
assert isinstance(weight, QuantizedTensor)
assert x.grad is not None and x.grad.device.type == device

def test_param_replaced_after_first_forward(

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I dont think this is a use-case @denera

The way this test def test_deferred_param_init_explicit(
calls reset_parameters before calling the first forward is the realistic use-case. Can we make all the tests follow this use-case.

And I think the fix in fuser is not needed as @timmoon10 pointed out. Since the cache_parameters that is going to be called will be after the parameters are materialized using reset_parameters() and so it will be right.

I think we should modify this PR to have an example in pytorch's example folder, showing how deferred initialization works and some test cases in this file for that.

Copy link
Copy Markdown
Collaborator Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Updated. Tests call .reset_parameters() before the first forward, and the fuser changes are removed. The supported usage is documented in the te.ops.Sequential docstring.

@denera
denera force-pushed the pytorch/fusible-ops-meta-init-fix branch from 0d12e9a to 558eaae Compare October 1, 2026 19:24
@denera

denera commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

Are we sure there is actually a bug? I see this PR adds logic to defer some OperationFuser setup to the first forward pass. However, OperationFuser is an internal class that is only instantiated by Sequential in the first forward pass:

self._module_groups = self._make_module_groups(self._modules.values())

It's perfectly possible that different fusions are available with quantized/unquantized params, so trying to "fix" the OperationFuser is dangerous. If a change is detected, better to destroy and create a new one.

@timmoon10 I dropped all the OperationFuser changes in the PR. te.Sequential.reset_parameters() rebuilds its fusers instead, and the first-forward on the fuser explicitly requires .reset_parameters() to be called to materialize meta tensors on device first.

@denera
denera force-pushed the pytorch/fusible-ops-meta-init-fix branch from 558eaae to 398968c Compare October 1, 2026 19:50
@denera
denera requested a review from vthumbe1503 October 1, 2026 19:51
@denera
denera dismissed timmoon10’s stale review October 1, 2026 19:52

Requested changes are no longer applicable to the latest state of the PR. Requesting a re-review.

@denera

denera commented Oct 1, 2026

Copy link
Copy Markdown
Collaborator Author

/te-ci pytorch

@timmoon10 timmoon10 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Overall LGTM, although I have some nits.

I'll note that our device='meta' behavior is different from torch.nn.Linear. For that, calling reset_parameters does not initialize weights and the only way to initialize is to manually overwrite the params. TE is treating reset_parameters in a non-standard way to make this workflow more convenient than plain PyTorch.

Comment thread transformer_engine/pytorch/ops/op.py Resolved
Comment thread tests/pytorch/test_fusible_ops.py Resolved
@denera
denera force-pushed the pytorch/fusible-ops-meta-init-fix branch from 398968c to 306e60d Compare October 8, 2026 11:58
@denera

denera commented Oct 8, 2026 •

Copy link
Copy Markdown
Collaborator Author

I'll note that our device='meta' behavior is different from torch.nn.Linear. For that, calling reset_parameters does not initialize weights and the only way to initialize is to manually overwrite the params. TE is treating reset_parameters in a non-standard way to make this workflow more convenient than plain PyTorch.

@timmoon10 The documented PyTorch workflow for deferred initialization of meta-modules is:

with torch.device('meta'):
    model = torch.nn.Linear(...)
model.to_empty(device='cuda')
model.reset_parameters()

So I don't believe it is required to manually overwrite params for native PyTorch modules.

I don't believe we've ever reliably supported .to_empty(device=...) or .to(dtype=..., device=...) style of operations on TE custom modules, and we only support CUDA devices anyway, so .to_empty(device='cuda') ends up mandatory and implied for any invocation of .reset_parameters(). Therefore, pinning our own deferred initialization in TE to .reset_parameters() is a pretty close reproduction of deferred initialization for native PyT modules. That was the original logic behind the implementation anyway.

I've updated the PR to support .reset_parameters() for every fusible op that could end up in te.Sequential as a submodule, and so it is now fully equivalent to either call te.Sequential.reset_parameters() OR loop over the submodules and call .reset_parameters() on each of them separately. Docstrings are updated accordingly.

@denera
denera requested a review from timmoon10 October 8, 2026 12:12
timmoon10
timmoon10 previously approved these changes Oct 8, 2026

@timmoon10 timmoon10 left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

@timmoon10

Copy link
Copy Markdown
Member

/te-ci pytorch

Deferred initialization requires calling reset_parameters() before the
first forward pass. Add reset_parameters() to all fusible ops and
te.ops.Sequential, support resetting already materialized params in
te.ops.Bias and quantized te.ops.BasicLinear, and raise an error if
params are still on the meta device in the first forward pass instead
of materializing them.

Fixes NVIDIA#3322

Signed-off-by: Alp Dener <adener@nvidia.com>
@denera
denera force-pushed the pytorch/fusible-ops-meta-init-fix branch from 306e60d to 660a9d6 Compare October 13, 2026 19:57
@denera
denera requested a review from timmoon10 October 13, 2026 20:01
Comment on lines +149 to +151
for module in self:
if hasattr(module, "reset_parameters"):
module.reset_parameters()

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.

P1 Nested parameters stay on meta

Sequential.reset_parameters() skips children inside a nested torch.nn.Sequential, which has no reset_parameters() method. For example, te.ops.Sequential(torch.nn.Sequential(te.ops.Linear(32, 32, device="meta"))) still has meta parameters after resetting the outer container. Its first forward then raises instead of running.

Reset children of containers that lack their own reset method.

@ptrendx

ptrendx commented Oct 13, 2026

Copy link
Copy Markdown
Member

/te-ci pytorch

@denera
denera merged commit 53e241c into NVIDIA:main Oct 13, 2026
14 of 23 checks passed
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.

[Bug] Deferred init issue in te.pytorch.ops

4 participants