Skip to content

[Pytorch] Fix RecursionError when dequantizing cpu-resident QuantizedTensor - #3279

Closed
janekb04 wants to merge 1 commit into
NVIDIA:mainfrom
janekb04:fix_recursion_error
Closed

janekb04 wants to merge 1 commit into
NVIDIA:mainfrom
janekb04:fix_recursion_error

Conversation

@janekb04

Copy link
Copy Markdown
Collaborator

Description

Trying to use a QuantizedTensor in certain ways causes a RecursionError if it has been moved to the CPU. For instance,

import torch
from transformer_engine.pytorch import NVFP4Quantizer

x = torch.randn(128, 128, device="cuda")
q = NVFP4Quantizer()
xq = q(x)
xq_cpu = xq.cpu()

xq_cpu + 0

will cause:

Traceback (most recent call last):
  File "/workspace/repro.py", line 9, in <module>
    xq_cpu + 0
    ~~~~~~~^~~
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/nvfp4_tensor.py", line 806, in __torch_dispatch__
    return super().__torch_dispatch__(func, types, args, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/quantized_tensor.py", line 804, in __torch_dispatch__
    args = tree_map(maybe_unwrap, args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/utils/_pytree.py", line 1578, in tree_map
    return treespec.unflatten(map(func, *flat_args))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/utils/_pytree.py", line 1313, in unflatten
    leaves = list(leaves)
             ^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/quantized_tensor.py", line 772, in maybe_unwrap
    return arg.dequantize()
           ^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/nvfp4_tensor.py", line 444, in dequantize
    return _FromNVFP4Func.apply(self, dtype)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/autograd/function.py", line 625, in apply
    return super().apply(*args, **kwargs)  # type: ignore[misc]
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/storage/nvfp4_tensor_storage.py", line 58, in forward
    cuda_tensor = tensor.to(device=torch.device("cuda"))
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/nvfp4_tensor.py", line 806, in __torch_dispatch__
    return super().__torch_dispatch__(func, types, args, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/quantized_tensor.py", line 804, in __torch_dispatch__
    args = tree_map(maybe_unwrap, args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/utils/_pytree.py", line 1578, in tree_map
    return treespec.unflatten(map(func, *flat_args))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/utils/_pytree.py", line 1313, in unflatten
    leaves = list(leaves)
             ^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/quantized_tensor.py", line 772, in maybe_unwrap
    return arg.dequantize()
           ^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/nvfp4_tensor.py", line 445, in dequantize
    return _FromNVFP4Func.forward(None, self, dtype)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/storage/nvfp4_tensor_storage.py", line 58, in forward
    cuda_tensor = tensor.to(device=torch.device("cuda"))
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/nvfp4_tensor.py", line 806, in __torch_dispatch__
    return super().__torch_dispatch__(func, types, args, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/quantized_tensor.py", line 804, in __torch_dispatch__
    args = tree_map(maybe_unwrap, args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/utils/_pytree.py", line 1578, in tree_map
    return treespec.unflatten(map(func, *flat_args))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/utils/_pytree.py", line 1313, in unflatten
    leaves = list(leaves)
             ^^^^^^^^^^^^
[...]
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/quantized_tensor.py", line 772, in maybe_unwrap
    return arg.dequantize()
           ^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/nvfp4_tensor.py", line 445, in dequantize
    return _FromNVFP4Func.forward(None, self, dtype)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/storage/nvfp4_tensor_storage.py", line 58, in forward
    cuda_tensor = tensor.to(device=torch.device("cuda"))
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/nvfp4_tensor.py", line 806, in __torch_dispatch__
    return super().__torch_dispatch__(func, types, args, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/quantized_tensor.py", line 804, in __torch_dispatch__
    args = tree_map(maybe_unwrap, args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/utils/_pytree.py", line 1578, in tree_map
    return treespec.unflatten(map(func, *flat_args))
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/utils/_pytree.py", line 1313, in unflatten
    leaves = list(leaves)
             ^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/quantized_tensor.py", line 772, in maybe_unwrap
    return arg.dequantize()
           ^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/nvfp4_tensor.py", line 445, in dequantize
    return _FromNVFP4Func.forward(None, self, dtype)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/storage/nvfp4_tensor_storage.py", line 58, in forward
    cuda_tensor = tensor.to(device=torch.device("cuda"))
                  ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/tensor/nvfp4_tensor.py", line 806, in __torch_dispatch__
    return super().__torch_dispatch__(func, types, args, kwargs)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/transformer_engine/pytorch/quantized_tensor.py", line 804, in __torch_dispatch__
    args = tree_map(maybe_unwrap, args)
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/utils/_pytree.py", line 1576, in tree_map
    leaves, treespec = tree_flatten(tree, is_leaf=is_leaf)
                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
  File "/usr/local/lib/python3.12/dist-packages/torch/utils/_pytree.py", line 1485, in tree_flatten
    treespec = helper(tree, leaves)
               ^^^^^^^^^^^^^^^^^^^^
RecursionError: maximum recursion depth exceeded

I noticed this when trying to use torch.testing.assert_close on a tensor quantized with NVFP4Quantizer and a custom Pytorch implementation on the CPU.

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

@github-actions github-actions Bot added the community-contribution PRs from external contributor outside the core maintainers, representing community-driven work. label Jul 29, 2026
@pggPL pggPL removed the community-contribution PRs from external contributor outside the core maintainers, representing community-driven work. label Jul 30, 2026
@janekb04 janekb04 closed this Jul 30, 2026
@janekb04
janekb04 deleted the fix_recursion_error branch July 31, 2026 18:04
@janekb04
janekb04 restored the fix_recursion_error branch August 10, 2026 22:06
@janekb04 janekb04 reopened this Aug 10, 2026
@github-actions github-actions Bot added the community-contribution PRs from external contributor outside the core maintainers, representing community-driven work. label Aug 10, 2026
siddhant-rajhans pushed a commit to siddhant-rajhans/TransformerEngine that referenced this pull request Nov 5, 2026
Calling .to() on a QuantizedTensor from inside __torch_dispatch__ reaches
the dispatcher as an aten.to.* overload rather than aten._to_copy,
because the CompositeImplicitAutograd decomposition is skipped there.
Those overloads fell through to the dequantizing fallback, so an op such
as `x_cpu + 0` on a CPU-resident MXFP8 or NVFP4 tensor recursed: the
fallback dequantizes, dequantization moves the tensor to the GPU with
.to(), and .to() dispatches back into the fallback.

Handle the aten.to.* overloads like aten._to_copy in the base class, as
proposed in NVIDIA#3279. This replaces the MXFP8- and NVFP4-specific buffer
copies from the earlier commits of this PR, and the test moves into
test_quantized_tensor.py, parametrized over all quantization formats.

Co-authored-by: Jan Bielak <[email protected]>
Signed-off-by: Siddhant Rajhans <[email protected]>
siddhant-rajhans added a commit to siddhant-rajhans/TransformerEngine that referenced this pull request Nov 6, 2026
Calling .to() on a QuantizedTensor from inside __torch_dispatch__ reaches
the dispatcher as an aten.to.* overload rather than aten._to_copy,
because the CompositeImplicitAutograd decomposition is skipped there.
Those overloads fell through to the dequantizing fallback, so an op such
as `x_cpu + 0` on a CPU-resident MXFP8 or NVFP4 tensor recursed: the
fallback dequantizes, dequantization moves the tensor to the GPU with
.to(), and .to() dispatches back into the fallback.

Handle the aten.to.* overloads like aten._to_copy in the base class, as
proposed in NVIDIA#3279. This replaces the MXFP8- and NVFP4-specific buffer
copies from the earlier commits of this PR, and the test moves into
test_quantized_tensor.py, parametrized over all quantization formats.

Co-authored-by: Jan Bielak <[email protected]>
Signed-off-by: Siddhant Rajhans <[email protected]>
vthumbe1503 added a commit that referenced this pull request Nov 7, 2026
…#3812)

* Fix CPU QuantizedTensor dequantize RecursionError

_FromNVFP4Func.forward() and _FromMXFP8Func.forward() call
tensor.to(device=cuda) on the full QuantizedTensor when
dequantizing a CPU-resident quantized tensor. This triggers
__torch_dispatch__, which calls maybe_unwrap -> dequantize() ->
forward() -> tensor.to() -> __torch_dispatch__ in an infinite loop.

Move the raw inner data tensors to CUDA individually via
get_metadata() and construct a plain TensorStorage for the
tex.dequantize call. Plain torch.Tensor.to() on the inner
buffers does not enter __torch_dispatch__, breaking the cycle.

Fixes #3294

Signed-off-by: Siddhant Rajhans <[email protected]>

* fix: add GPU capability checks and MXFP8 fp8_dtype to tests

- MXFP8Quantizer requires fp8_dtype argument; pass kFloat8E4M3
- Skip NVFP4/MXFP8 tests on GPUs that lack support via
  is_nvfp4_available() / is_mxfp8_available()

Signed-off-by: Siddhant Rajhans <[email protected]>

* Fix CPU dequantize recursion in the QuantizedTensor base class

Calling .to() on a QuantizedTensor from inside __torch_dispatch__ reaches
the dispatcher as an aten.to.* overload rather than aten._to_copy,
because the CompositeImplicitAutograd decomposition is skipped there.
Those overloads fell through to the dequantizing fallback, so an op such
as `x_cpu + 0` on a CPU-resident MXFP8 or NVFP4 tensor recursed: the
fallback dequantizes, dequantization moves the tensor to the GPU with
.to(), and .to() dispatches back into the fallback.

Handle the aten.to.* overloads like aten._to_copy in the base class, as
proposed in #3279. This replaces the MXFP8- and NVFP4-specific buffer
copies from the earlier commits of this PR, and the test moves into
test_quantized_tensor.py, parametrized over all quantization formats.

Co-authored-by: Jan Bielak <[email protected]>
Signed-off-by: Siddhant Rajhans <[email protected]>

* Update tests/pytorch/test_quantized_tensor.py

Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
Signed-off-by: vthumbe1503 <[email protected]>

---------

Signed-off-by: Siddhant Rajhans <[email protected]>
Signed-off-by: vthumbe1503 <[email protected]>
Co-authored-by: Jan Bielak <[email protected]>
Co-authored-by: vthumbe1503 <[email protected]>
Co-authored-by: greptile-apps[bot] <165735046+greptile-apps[bot]@users.noreply.github.com>
@pggPL

pggPL commented Nov 25, 2026

Copy link
Copy Markdown
Collaborator

Closing as fixed by #3812.

@pggPL pggPL closed this Nov 25, 2026
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

community-contribution PRs from external contributor outside the core maintainers, representing community-driven work.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants