pytorch - 💡(How to fix) Fix [Dynamo] RuntimeError when tracing pad_packed_sequence: tensor data not allocated in fake tensor mode [1 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#178260Fetched 2026-04-08 01:20:55
View on GitHub
Comments
0
Participants
1
Timeline
120
Reactions
0
Participants
Timeline (top)
subscribed ×57mentioned ×56labeled ×7

Error Message

torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: call_function <built-in method _pad_packed_sequence of type object at 0x...>(*(FakeTensor(..., size=(10, 10)), FakeTensor(..., size=(5,), dtype=torch.int64), True, 0.0, 5), **{}): got RuntimeError("The tensor has a non-zero number of elements, but its data is not allocated yet. If you're using torch.compile/export/fx, it is likely that we are erroneously tracing into a custom kernel. To fix this, please wrap the custom kernel into an opaque custom op. Please see the following for details: https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html")

from user code: File "example.py", line 18, in forward output, _ = nn.utils.rnn.pad_packed_sequence(packed, batch_first=True) File "/path/to/torch/nn/utils/rnn.py", line 400, in pad_packed_sequence padded_output, lengths = _VF._pad_packed_sequence(

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 32 On-line CPU(s) list: 0-31 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i9-14900HX CPU family: 6 Model: 183 Thread(s) per core: 2 Core(s) per socket: 24 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 31% CPU max MHz: 5800.0000 CPU min MHz: 800.0000 BogoMIPS: 4838.40 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 896 KiB (24 instances) L1i cache: 1.3 MiB (24 instances) L2 cache: 32 MiB (12 instances) L3 cache: 36 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-31 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: 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: Mitigation; Clear Register File Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected 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; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Code Example

import torch
import torch.nn as nn
import torch.nn.functional as F

class RaggedTensorExample1(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(10, 5)
    
    def forward(self, x, lengths):
        packed = nn.utils.rnn.pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)
        output, _ = nn.utils.rnn.pad_packed_sequence(packed, batch_first=True)
        return self.linear(output)

model = RaggedTensorExample1()
model.eval()

# Create variable length sequences
batch_size = 3
max_len = 5
feature_dim = 10
x = torch.randn(batch_size, max_len, feature_dim)
lengths = torch.tensor([3, 5, 2])

# Eager mode works
with torch.no_grad():
    output = model(x, lengths)

# Compilation fails
compiled_model = torch.compile(model)
with torch.no_grad():
    output_compile = compiled_model(x, lengths)  # ERROR

---

torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: 
call_function <built-in method _pad_packed_sequence of type object at 0x...>(*(FakeTensor(..., size=(10, 10)), FakeTensor(..., size=(5,), dtype=torch.int64), True, 0.0, 5), **{}): 
got RuntimeError("The tensor has a non-zero number of elements, but its data is not allocated yet.
If you're using torch.compile/export/fx, it is likely that we are erroneously tracing into a custom kernel.
To fix this, please wrap the custom kernel into an opaque custom op. Please see the following for details: 
https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html")

from user code:
   File "example.py", line 18, in forward
    output, _ = nn.utils.rnn.pad_packed_sequence(packed, batch_first=True)
  File "/path/to/torch/nn/utils/rnn.py", line 400, in pad_packed_sequence
    padded_output, lengths = _VF._pad_packed_sequence(
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Description: When using torch.compile() on a model that uses pad_packed_sequence (from nn.utils.rnn), Dynamo fails with a RuntimeError indicating that tensor data is not allocated. The error occurs during fake tensor propagation when tracing the _pad_packed_sequence operation. code:

import torch
import torch.nn as nn
import torch.nn.functional as F

class RaggedTensorExample1(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(10, 5)
    
    def forward(self, x, lengths):
        packed = nn.utils.rnn.pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)
        output, _ = nn.utils.rnn.pad_packed_sequence(packed, batch_first=True)
        return self.linear(output)

model = RaggedTensorExample1()
model.eval()

# Create variable length sequences
batch_size = 3
max_len = 5
feature_dim = 10
x = torch.randn(batch_size, max_len, feature_dim)
lengths = torch.tensor([3, 5, 2])

# Eager mode works
with torch.no_grad():
    output = model(x, lengths)

# Compilation fails
compiled_model = torch.compile(model)
with torch.no_grad():
    output_compile = compiled_model(x, lengths)  # ERROR

output:

torch._dynamo.exc.TorchRuntimeError: Dynamo failed to run FX node with fake tensors: 
call_function <built-in method _pad_packed_sequence of type object at 0x...>(*(FakeTensor(..., size=(10, 10)), FakeTensor(..., size=(5,), dtype=torch.int64), True, 0.0, 5), **{}): 
got RuntimeError("The tensor has a non-zero number of elements, but its data is not allocated yet.
If you're using torch.compile/export/fx, it is likely that we are erroneously tracing into a custom kernel.
To fix this, please wrap the custom kernel into an opaque custom op. Please see the following for details: 
https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html")

from user code:
   File "example.py", line 18, in forward
    output, _ = nn.utils.rnn.pad_packed_sequence(packed, batch_first=True)
  File "/path/to/torch/nn/utils/rnn.py", line 400, in pad_packed_sequence
    padded_output, lengths = _VF._pad_packed_sequence(

Versions

PyTorch version: 2.8.0+cu126 Is debug build: False CUDA used to build PyTorch: 12.6 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.1 LTS (x86_64) GCC version: (Ubuntu 9.5.0-6ubuntu2) 9.5.0 Clang version: Could not collect CMake version: version 4.0.3 Libc version: glibc-2.39

Python version: 3.9.7 (default, Jul 16 2025, 16:34:47) [GCC 13.3.0] (64-bit runtime) Python platform: Linux-6.14.0-29-generic-x86_64-with-glibc2.39 Is CUDA available: False CUDA runtime version: Could not collect CUDA_MODULE_LOADING set to: N/A GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4060 Laptop GPU Nvidia driver version: 580.65.06 cuDNN version: Could not collect HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 32 On-line CPU(s) list: 0-31 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i9-14900HX CPU family: 6 Model: 183 Thread(s) per core: 2 Core(s) per socket: 24 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 31% CPU max MHz: 5800.0000 CPU min MHz: 800.0000 BogoMIPS: 4838.40 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush dts acpi mmx fxsr sse sse2 ss ht tm pbe syscall nx pdpe1gb rdtscp lm constant_tsc art arch_perfmon pebs bts rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq dtes64 monitor ds_cpl vmx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves split_lock_detect user_shstk avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req hfi vnmi umip pku ospke waitpkg gfni vaes vpclmulqdq rdpid movdiri movdir64b fsrm md_clear serialize arch_lbr ibt flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 896 KiB (24 instances) L1i cache: 1.3 MiB (24 instances) L2 cache: 32 MiB (12 instances) L3 cache: 36 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-31 Vulnerability Gather data sampling: Not affected Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: 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: Mitigation; Clear Register File Vulnerability Retbleed: Not affected Vulnerability Spec rstack overflow: Not affected 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; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

cc @mikaylagawarecki @chauhang @penguinwu @eellison @aorenste @voznesenskym @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @kadeng @amjames @Lucaskabela @jataylo @bdhirsh @bobrenjc93

extent analysis

Fix Plan

To fix the issue with torch.compile() failing when using pad_packed_sequence, we need to wrap the custom kernel into an opaque custom op.

Here are the steps:

  • Define a custom function that wraps nn.utils.rnn.pad_packed_sequence.
  • Use torch.ops.load_library to load a custom PyTorch extension that defines the custom op.
  • Replace the call to nn.utils.rnn.pad_packed_sequence with a call to the custom function.

Example Code

import torch
import torch.nn as nn
import torch.nn.functional as F

# Define a custom function that wraps nn.utils.rnn.pad_packed_sequence
class CustomPadPackedSequence(nn.Module):
    def forward(self, packed, batch_first):
        return nn.utils.rnn.pad_packed_sequence(packed, batch_first=batch_first)

# Load the custom PyTorch extension
torch.ops.load_library('./custom_op.so')

# Define the model
class RaggedTensorExample1(nn.Module):
    def __init__(self):
        super().__init__()
        self.linear = nn.Linear(10, 5)
        self.custom_pad = CustomPadPackedSequence()
    
    def forward(self, x, lengths):
        packed = nn.utils.rnn.pack_padded_sequence(x, lengths, batch_first=True, enforce_sorted=False)
        output, _ = self.custom_pad(packed, batch_first=True)
        return self.linear(output)

model = RaggedTensorExample1()
model.eval()

# Create variable length sequences
batch_size = 3
max_len = 5
feature_dim = 10
x = torch.randn(batch_size, max_len, feature_dim)
lengths = torch.tensor([3, 5, 2])

# Compile the model
compiled_model = torch.compile(model)

# Run the compiled model
with torch.no_grad():
    output_compile = compiled_model(x, lengths)

Verification

To verify that the fix worked, run the compiled model with the example input and check that it produces the expected output.

Extra Tips

  • Make sure to build the custom PyTorch extension (custom_op.so) using the PyTorch C++ API.
  • The custom op should be defined in a separate file (e.g., custom_op.cpp) and compiled into a shared library (e.g., custom_op.so).
  • The torch.ops.load_library function is used to load the custom PyTorch extension.
  • The custom function (CustomPadPackedSequence) should be defined as a PyTorch module and used in the model.

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…

Still need to ship something?

×6

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

Back to top recommendations

TRENDING