pytorch - 💡(How to fix) Fix `import functorch.dim` silently breaks `torch.Tensor.expand(size=...)` [1 comments, 2 participants]

Official PRs (…)
ON THIS PAGE

Recommended Tools

×6

Utilities matched from this issue’s tags and category — try them while you read without losing context.

GitHub issue graph ai analysis

Paste a GitHub issue URL. We fetch that issue, discover linked issues from bodies/comments/timeline, collect linked pull requests, and produce a structured English report.

The report is written in English Markdown for sharing and archival.

Helpful · Quick feedback

Loading…
GitHub stats
pytorch/pytorch#177654Fetched 2026-04-08 00:52:41
View on GitHub
Comments
1
Participants
2
Timeline
27
Reactions
0
Participants
Timeline (top)
mentioned ×10subscribed ×10labeled ×5commented ×1

Error Message

Before importing functorch.dim: OK Traceback (most recent call last): File "/home/8/ue06348/projects/SSDP/test.py", line 27, in <module> test_expand(input, size) File "/home/8/ue06348/projects/SSDP/test.py", line 11, in test_expand assert output_kwargs.shape == size, ( ^^^^^^^^^^^^^^^^^^^^^^^^^^^ AssertionError: The shape of the output of torch.Tensor.expand(self, size=size) should be (10, 1) but it is different: torch.Size([1]).

Root Cause

functorch/dim/__init__.py#106 replaces torch.Tensor.expand with a C wrapper:

torch.Tensor.expand = _C._instancemethod(_C.expand)

The replacement changes the type of torch.Tensor.expand from method_descriptor to builtin_function_or_method. The new version does not accept the size= keyword argument — it silently ignores it and returns the input tensor as-is, without raising any error.

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 52 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 384 On-line CPU(s) list: 0-383 Vendor ID: AuthenticAMD Model name: AMD EPYC 9654 96-Core Processor CPU family: 25 Model: 17 Thread(s) per core: 2 Core(s) per socket: 96 Socket(s): 2 Stepping: 1 Frequency boost: enabled CPU(s) scaling MHz: 68% CPU max MHz: 3707.8120 CPU min MHz: 1500.0000 BogoMIPS: 4792.45 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap Virtualization: AMD-V L1d cache: 6 MiB (192 instances) L1i cache: 6 MiB (192 instances) L2 cache: 192 MiB (192 instances) L3 cache: 768 MiB (24 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0-95,192-287 NUMA node1 CPU(s): 96-191,288-383 Vulnerability Gather data sampling: Not affected Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Mitigation; Safe RET Vulnerability Spec store bypass: Mitigation; Speculative Store Bypass disabled via prctl Vulnerability Spectre v1: Mitigation; usercopy/swapgs barriers and __user pointer sanitization Vulnerability Spectre v2: Mitigation; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Code Example

torch.Tensor.expand = _C._instancemethod(_C.expand)

---

import torch


def test_expand(input: torch.Tensor, size: tuple[int, ...]) -> None:
    output_args = input.expand(*size)
    output_kwargs = input.expand(size=size)
    assert output_args.shape == size, (
        f"The shape of the output of `torch.Tensor.expand(self, *size)` "
        f"should be `{size}` but it is different: `{output_args.shape}`."
    )
    assert output_kwargs.shape == size, (
        f"The shape of the output of `torch.Tensor.expand(self, size=size)` "
        f"should be `{size}` but it is different: `{output_kwargs.shape}`."
    )


input = torch.zeros(1)
size = (10, 1)

test_expand(input, size)

print("Before importing `functorch.dim`: OK")


import functorch.dim

test_expand(input, size)

print("After importing `functorch.dim`: OK")

---

Before importing `functorch.dim`: OK
Traceback (most recent call last):
  File "/home/8/ue06348/projects/SSDP/test.py", line 27, in <module>
    test_expand(input, size)
  File "/home/8/ue06348/projects/SSDP/test.py", line 11, in test_expand
    assert output_kwargs.shape == size, (
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: The shape of the output of `torch.Tensor.expand(self, size=size)` should be `(10, 1)` but it is different: `torch.Size([1])`.

---

$ curl -sL https://raw.githubusercontent.com/pytorch/pytorch/main/torch/utils/collect_env.py | uv run python
Collecting environment information...
PyTorch version: 2.8.0+cu129
Is debug build: False
CUDA used to build PyTorch: 12.9
ROCM used to build PyTorch: N/A

OS: Red Hat Enterprise Linux 9.4 (Plow) (x86_64)
GCC version: (GCC) 11.4.1 20231218 (Red Hat 11.4.1-3)
Clang version: 17.0.6 (Red Hat, Inc. 17.0.6-5.el9)
CMake version: version 3.26.5
Libc version: glibc-2.34

Python version: 3.11.13 (main, Sep 18 2025, 19:46:39) [Clang 20.1.4 ] (64-bit runtime)
Python platform: Linux-5.14.0-503.40.1.el9_5.x86_64-x86_64-with-glibc2.34
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA H100
  MIG 4g.47gb     Device  0:

Nvidia driver version: 575.57.08
cuDNN version: Could not collect
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
Caching allocator config: N/A

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Address sizes:                        52 bits physical, 57 bits virtual
Byte Order:                           Little Endian
CPU(s):                               384
On-line CPU(s) list:                  0-383
Vendor ID:                            AuthenticAMD
Model name:                           AMD EPYC 9654 96-Core Processor
CPU family:                           25
Model:                                17
Thread(s) per core:                   2
Core(s) per socket:                   96
Socket(s):                            2
Stepping:                             1
Frequency boost:                      enabled
CPU(s) scaling MHz:                   68%
CPU max MHz:                          3707.8120
CPU min MHz:                          1500.0000
BogoMIPS:                             4792.45
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap
Virtualization:                       AMD-V
L1d cache:                            6 MiB (192 instances)
L1i cache:                            6 MiB (192 instances)
L2 cache:                             192 MiB (192 instances)
L3 cache:                             768 MiB (24 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0-95,192-287
NUMA node1 CPU(s):                    96-191,288-383
Vulnerability Gather data sampling:   Not affected
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   Mitigation; Safe RET
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] Could not collect
[conda] Could not collect
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

After import functorch.dim, torch.Tensor.expand silently ignores the size= keyword argument, returning the input tensor unchanged instead of expanding it.

Root cause

functorch/dim/__init__.py#106 replaces torch.Tensor.expand with a C wrapper:

torch.Tensor.expand = _C._instancemethod(_C.expand)

The replacement changes the type of torch.Tensor.expand from method_descriptor to builtin_function_or_method. The new version does not accept the size= keyword argument — it silently ignores it and returns the input tensor as-is, without raising any error.

Reproducing code

import torch


def test_expand(input: torch.Tensor, size: tuple[int, ...]) -> None:
    output_args = input.expand(*size)
    output_kwargs = input.expand(size=size)
    assert output_args.shape == size, (
        f"The shape of the output of `torch.Tensor.expand(self, *size)` "
        f"should be `{size}` but it is different: `{output_args.shape}`."
    )
    assert output_kwargs.shape == size, (
        f"The shape of the output of `torch.Tensor.expand(self, size=size)` "
        f"should be `{size}` but it is different: `{output_kwargs.shape}`."
    )


input = torch.zeros(1)
size = (10, 1)

test_expand(input, size)

print("Before importing `functorch.dim`: OK")


import functorch.dim

test_expand(input, size)

print("After importing `functorch.dim`: OK")

Output

Before importing `functorch.dim`: OK
Traceback (most recent call last):
  File "/home/8/ue06348/projects/SSDP/test.py", line 27, in <module>
    test_expand(input, size)
  File "/home/8/ue06348/projects/SSDP/test.py", line 11, in test_expand
    assert output_kwargs.shape == size, (
           ^^^^^^^^^^^^^^^^^^^^^^^^^^^
AssertionError: The shape of the output of `torch.Tensor.expand(self, size=size)` should be `(10, 1)` but it is different: `torch.Size([1])`.

Expected behavior

torch.Tensor.expand(size=(...)) should work the same before and after import functorch.dim.

Notes

The issue also affects any library that transitively imports functorch.dim (e.g. import tensordict triggers it).

Versions

$ curl -sL https://raw.githubusercontent.com/pytorch/pytorch/main/torch/utils/collect_env.py | uv run python
Collecting environment information...
PyTorch version: 2.8.0+cu129
Is debug build: False
CUDA used to build PyTorch: 12.9
ROCM used to build PyTorch: N/A

OS: Red Hat Enterprise Linux 9.4 (Plow) (x86_64)
GCC version: (GCC) 11.4.1 20231218 (Red Hat 11.4.1-3)
Clang version: 17.0.6 (Red Hat, Inc. 17.0.6-5.el9)
CMake version: version 3.26.5
Libc version: glibc-2.34

Python version: 3.11.13 (main, Sep 18 2025, 19:46:39) [Clang 20.1.4 ] (64-bit runtime)
Python platform: Linux-5.14.0-503.40.1.el9_5.x86_64-x86_64-with-glibc2.34
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA H100
  MIG 4g.47gb     Device  0:

Nvidia driver version: 575.57.08
cuDNN version: Could not collect
Is XPU available: False
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: True
Caching allocator config: N/A

CPU:
Architecture:                         x86_64
CPU op-mode(s):                       32-bit, 64-bit
Address sizes:                        52 bits physical, 57 bits virtual
Byte Order:                           Little Endian
CPU(s):                               384
On-line CPU(s) list:                  0-383
Vendor ID:                            AuthenticAMD
Model name:                           AMD EPYC 9654 96-Core Processor
CPU family:                           25
Model:                                17
Thread(s) per core:                   2
Core(s) per socket:                   96
Socket(s):                            2
Stepping:                             1
Frequency boost:                      enabled
CPU(s) scaling MHz:                   68%
CPU max MHz:                          3707.8120
CPU min MHz:                          1500.0000
BogoMIPS:                             4792.45
Flags:                                fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good amd_lbr_v2 nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba perfmon_v2 ibrs ibpb stibp ibrs_enhanced vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif x2avic v_spec_ctrl vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d debug_swap
Virtualization:                       AMD-V
L1d cache:                            6 MiB (192 instances)
L1i cache:                            6 MiB (192 instances)
L2 cache:                             192 MiB (192 instances)
L3 cache:                             768 MiB (24 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0-95,192-287
NUMA node1 CPU(s):                    96-191,288-383
Vulnerability Gather data sampling:   Not affected
Vulnerability Itlb multihit:          Not affected
Vulnerability L1tf:                   Not affected
Vulnerability Mds:                    Not affected
Vulnerability Meltdown:               Not affected
Vulnerability Mmio stale data:        Not affected
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed:               Not affected
Vulnerability Spec rstack overflow:   Mitigation; Safe RET
Vulnerability Spec store bypass:      Mitigation; Speculative Store Bypass disabled via prctl
Vulnerability Spectre v1:             Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:             Mitigation; Enhanced / Automatic IBRS; IBPB conditional; STIBP always-on; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] Could not collect
[conda] Could not collect

cc @Chillee @samdow @kshitij12345

extent analysis

Fix Plan

To fix the issue, we need to restore the original torch.Tensor.expand method after importing functorch.dim. We can do this by saving a reference to the original method before importing functorch.dim and then restoring it afterwards.

Code Changes

import torch

# Save the original expand method
original_expand = torch.Tensor.expand

import functorch.dim

# Restore the original expand method
torch.Tensor.expand = original_expand

Alternatively, you can use a context manager to restore the original method after importing functorch.dim:

import torch
from contextlib import contextmanager

@contextmanager
def restore_expand():
    original_expand = torch.Tensor.expand
    yield
    torch.Tensor.expand = original_expand

with restore_expand():
    import functorch.dim

Verification

To verify that the fix worked, you can run the test_expand function again after restoring the original torch.Tensor.expand method:

input = torch.zeros(1)
size = (10, 1)

test_expand(input, size)

This should pass without raising any errors.

Extra Tips

Note that this fix only restores the original torch.Tensor.expand method for the current Python session. If you want to make this fix permanent, you may need to modify the functorch library or submit a patch to the functorch developers. Additionally, be aware that restoring the original method may break any code that relies on the modified behavior introduced by functorch.dim.

Vote matrix · Quick signals

Works
Did the solution work? Tap to confirm.
Easy Fix
Was it a quick fix?
Time Saver
Did it save you time?
Blocking
Was it severely blocking?
Common Issue
Are others likely hitting this too?
Flaky / Intermittent
Is it intermittent?
Verified / Reproducible
Can you reproduce it reliably?
Loading…

FAQ

Expected behavior

torch.Tensor.expand(size=(...)) should work the same before and after import functorch.dim.

Still need to ship something?

×6

Another batch ranked right after the header list — different links, same matching logic.

Back to top recommendations

TRENDING

pytorch - 💡(How to fix) Fix `import functorch.dim` silently breaks `torch.Tensor.expand(size=...)` [1 comments, 2 participants]