pytorch - 💡(How to fix) Fix Unused jvp function on autograd function causes inscrutable shape error [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#180284Fetched 2026-04-15 06:18:50
View on GitHub
Comments
0
Participants
1
Timeline
31
Reactions
0
Author
Participants
Timeline (top)
mentioned ×12subscribed ×12labeled ×7

Error Message

from typing import Literal

import torch from torch import Tensor, no_grad from torch.nn import Linear, Module

this is a no-op rope for the purposes of minimal repro, you can delete quite a lot from it and it will still trigger the error.

class RopeInPlace(torch.autograd.Function): # we don't currently use vmap, but maybe it will enable compile to fuse QK rope apply into flex attn operations? # benchmark suggests that enabling this didn't incur any additional cold-start time, so I guess it's lazy. generate_vmap_rule = True

@staticmethod
def forward(t: Tensor, freqs_cis: Tensor, coeff: Literal[1, -1] = -1):
    # _rope_inplace(t, freqs_cis, coeff=coeff)
    return t

@staticmethod
def setup_context(ctx, inputs, output):
    t, freqs_cis, coeff = inputs
    # mark t as dirty because we will modify it in-place. this ensures backward() will be called.
    ctx.mark_dirty(t)
    ctx.save_for_backward(freqs_cis)
    # required for jvp, probably
    ctx.save_for_forward(freqs_cis)
    ctx.coeff = coeff

@staticmethod
def backward(ctx, grad_output):
    (freqs_cis,) = ctx.saved_tensors
    # clone made because we must "NEVER" modify grad-w.r.t-input in-place.
    # https://pytorch.org/docs/main/notes/extending.html#how-to-use
    # https://discuss.pytorch.org/t/is-it-safe-to-modify-outputs-grad-and-return-as-inputs-grad/201630
    grad_output = RopeInPlace.apply(grad_output.clone(), freqs_cis, -ctx.coeff)
    return grad_output, None, None

# !!!!!!!!!!!!!!!!!!
# comment out this (unused) jvp function and compilation will succeed
# !!!!!!!!!!!!!!!!!!
# if the jvp function is present, torch.compile will fail to compile backward pass, with mysterious error:
# shape '[132948266552741, 7448426736572743970, 6144]' is invalid for input of size 7864320
# we don't even use jvp, I just added it for fun.
@staticmethod
def jvp(ctx, grad_input, *_):
    """
    none of our code currently uses this, but it gives us forward-mode autodiff support,
    which could be useful for implementing consistency training.
    """
    (freqs_cis,) = ctx.saved_tensors
    grad_input = RopeInPlace.apply(grad_input, freqs_cis, ctx.coeff)
    return grad_input

HEADS = 16 HEAD_DIM = 128 MODEL_DIM = 2048 MIDDLE_DIM = MODEL_DIM HIDDEN_DIM = MODEL_DIM

class AttnBlock(Module): def init( self, dtype: torch.dtype, model_dim=MODEL_DIM, middle_dim=MIDDLE_DIM, head_dim=HEAD_DIM, heads=HEADS, ): super().init() self.heads = heads self.head_dim = head_dim # this is just for testing gradients self.qkv_proj = Linear(in_features=model_dim, out_features=middle_dim * 3, bias=False, dtype=dtype)

def forward(self, x: Tensor) -> Tensor:
    qkv: Tensor = self.qkv_proj(x)
    qkv = qkv.unflatten(-1, (3, self.heads, self.head_dim))
    qk = qkv[..., :2, :, :]
    RopeInPlace.apply(qk.unflatten(-1, ((-1, 2))), None, -1)
    return qkv

device = torch.device("cuda") gen = torch.Generator(device=device) hp_dtype = torch.bfloat16

with torch.device("meta"): attn = AttnBlock(dtype=hp_dtype) attn.to_empty(device=device) with device, no_grad(): attn.qkv_proj.weight.normal_(std=attn.qkv_proj.in_features**-0.5, generator=gen.manual_seed(42)) attn = torch.compile(attn, dynamic=False)

x = torch.randn((2, 640, MODEL_DIM), device=device, dtype=hp_dtype, generator=gen.manual_seed(1), requires_grad=True) ref: Tensor = attn(x) ref.sum().backward() print("survived fwd+bwd")

Root Cause

turns out it's because my custom autograd function declares a jvp function.

Fix Action

Fix / Workaround

it can be fixed by commenting-out the jvp function.

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 128 On-line CPU(s) list: 0-127 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Platinum 8462Y+ CPU family: 6 Model: 143 Thread(s) per core: 2 Core(s) per socket: 32 Socket(s): 2 Stepping: 8 CPU(s) scaling MHz: 95% CPU max MHz: 4100.0000 CPU min MHz: 800.0000 BogoMIPS: 5600.00 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 smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect user_shstk avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hfi vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 3 MiB (64 instances) L1i cache: 2 MiB (64 instances) L2 cache: 128 MiB (64 instances) L3 cache: 120 MiB (2 instances) NUMA node(s): 2 NUMA node0 CPU(s): 0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126 NUMA node1 CPU(s): 1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127 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: 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; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Code Example

shape '[132948266552741, 7448426736572743970, 6144]' is invalid for input of size 7864320

---

from typing import Literal

import torch
from torch import Tensor, no_grad
from torch.nn import Linear, Module


# this is a no-op rope for the purposes of minimal repro, you can delete quite a lot from it and it will still trigger the error.
class RopeInPlace(torch.autograd.Function):
    # we don't currently use vmap, but maybe it will enable compile to fuse QK rope apply into flex attn operations?
    # benchmark suggests that enabling this didn't incur any additional cold-start time, so I guess it's lazy.
    generate_vmap_rule = True

    @staticmethod
    def forward(t: Tensor, freqs_cis: Tensor, coeff: Literal[1, -1] = -1):
        # _rope_inplace(t, freqs_cis, coeff=coeff)
        return t

    @staticmethod
    def setup_context(ctx, inputs, output):
        t, freqs_cis, coeff = inputs
        # mark t as dirty because we will modify it in-place. this ensures backward() will be called.
        ctx.mark_dirty(t)
        ctx.save_for_backward(freqs_cis)
        # required for jvp, probably
        ctx.save_for_forward(freqs_cis)
        ctx.coeff = coeff

    @staticmethod
    def backward(ctx, grad_output):
        (freqs_cis,) = ctx.saved_tensors
        # clone made because we must "NEVER" modify grad-w.r.t-input in-place.
        # https://pytorch.org/docs/main/notes/extending.html#how-to-use
        # https://discuss.pytorch.org/t/is-it-safe-to-modify-outputs-grad-and-return-as-inputs-grad/201630
        grad_output = RopeInPlace.apply(grad_output.clone(), freqs_cis, -ctx.coeff)
        return grad_output, None, None

    # !!!!!!!!!!!!!!!!!!
    # comment out this (unused) jvp function and compilation will succeed
    # !!!!!!!!!!!!!!!!!!
    # if the jvp function is present, torch.compile will fail to compile backward pass, with mysterious error:
    # shape '[132948266552741, 7448426736572743970, 6144]' is invalid for input of size 7864320
    # we don't even use jvp, I just added it for fun.
    @staticmethod
    def jvp(ctx, grad_input, *_):
        """
        none of our code currently uses this, but it gives us forward-mode autodiff support,
        which could be useful for implementing consistency training.
        """
        (freqs_cis,) = ctx.saved_tensors
        grad_input = RopeInPlace.apply(grad_input, freqs_cis, ctx.coeff)
        return grad_input


HEADS = 16
HEAD_DIM = 128
MODEL_DIM = 2048
MIDDLE_DIM = MODEL_DIM
HIDDEN_DIM = MODEL_DIM


class AttnBlock(Module):
    def __init__(
        self,
        dtype: torch.dtype,
        model_dim=MODEL_DIM,
        middle_dim=MIDDLE_DIM,
        head_dim=HEAD_DIM,
        heads=HEADS,
    ):
        super().__init__()
        self.heads = heads
        self.head_dim = head_dim
        # this is just for testing gradients
        self.qkv_proj = Linear(in_features=model_dim, out_features=middle_dim * 3, bias=False, dtype=dtype)

    def forward(self, x: Tensor) -> Tensor:
        qkv: Tensor = self.qkv_proj(x)
        qkv = qkv.unflatten(-1, (3, self.heads, self.head_dim))
        qk = qkv[..., :2, :, :]
        RopeInPlace.apply(qk.unflatten(-1, ((-1, 2))), None, -1)
        return qkv


device = torch.device("cuda")
gen = torch.Generator(device=device)
hp_dtype = torch.bfloat16

with torch.device("meta"):
    attn = AttnBlock(dtype=hp_dtype)
attn.to_empty(device=device)
with device, no_grad():
    attn.qkv_proj.weight.normal_(std=attn.qkv_proj.in_features**-0.5, generator=gen.manual_seed(42))
attn = torch.compile(attn, dynamic=False)

x = torch.randn((2, 640, MODEL_DIM), device=device, dtype=hp_dtype, generator=gen.manual_seed(1), requires_grad=True)
ref: Tensor = attn(x)
ref.sum().backward()
print("survived fwd+bwd")

---

Unsupported custom jvp
  Explanation: Dynamo does not support tracing `torch.autograd.Function` subclasses that define a custom `jvp` method.
  Hint: Remove the custom `jvp` method if possible.
  Hint: It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues.

---

Collecting environment information...
PyTorch version: 2.11.0
Is debug build: False
CUDA used to build PyTorch: 13.2
ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.4 LTS (x86_64)
GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0
Clang version: Could not collect
CMake version: version 4.3.1
Libc version: glibc-2.39

Python version: 3.12.3 (main, Mar  3 2026, 12:15:18) [GCC 13.3.0] (64-bit runtime)
Python platform: Linux-6.8.12-680-6063-coreweave-amd64-f81899c8-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: 13.2.51
CUDA_MODULE_LOADING set to: 
GPU models and configuration: 
GPU 0: NVIDIA H100 80GB HBM3
GPU 1: NVIDIA H100 80GB HBM3

Nvidia driver version: 580.126.20
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.20.0
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:                        46 bits physical, 57 bits virtual
Byte Order:                           Little Endian
CPU(s):                               128
On-line CPU(s) list:                  0-127
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Platinum 8462Y+
CPU family:                           6
Model:                                143
Thread(s) per core:                   2
Core(s) per socket:                   32
Socket(s):                            2
Stepping:                             8
CPU(s) scaling MHz:                   95%
CPU max MHz:                          4100.0000
CPU min MHz:                          800.0000
BogoMIPS:                             5600.00
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 smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect user_shstk avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hfi vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            3 MiB (64 instances)
L1i cache:                            2 MiB (64 instances)
L2 cache:                             128 MiB (64 instances)
L3 cache:                             120 MiB (2 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126
NUMA node1 CPU(s):                    1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127
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:   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; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] clip-anytorch==2.6.0
[pip3] dctorch==0.1.2
[pip3] DISTS_pytorch==0.1
[pip3] lovely-numpy==0.2.20
[pip3] mypy_extensions==1.1.0
[pip3] numpy==2.4.4
[pip3] onnx==1.21.0
[pip3] onnx-ir==0.2.0
[pip3] onnxscript==0.6.2
[pip3] open_clip_torch==3.3.0
[pip3] optree==0.19.0
[pip3] torch==2.11.0
[pip3] torch_c_dlpack_ext==0.1.5
[pip3] torchaudio==2.11.0
[pip3] torchdata==0.11.0
[pip3] torchdiffeq==0.2.5
[pip3] torchsde==0.2.6
[pip3] torchtitan==0.2.2
[pip3] torchvision==0.26.0
[pip3] triton==3.6.0+git9844da95
[pip3] welford-torch==0.2.5
[conda] Could not collect
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

I've been bisecting for days to try and figure out why our model's backward pass doesn't compile.

turns out it's because my custom autograd function declares a jvp function.

this fails despite the test's not even using jvp.
and the error message doesn't mention jvp.

the error is:

shape '[132948266552741, 7448426736572743970, 6144]' is invalid for input of size 7864320

and only appears when doing a compiled backwards pass.

it can be fixed by commenting-out the jvp function.

from typing import Literal

import torch
from torch import Tensor, no_grad
from torch.nn import Linear, Module


# this is a no-op rope for the purposes of minimal repro, you can delete quite a lot from it and it will still trigger the error.
class RopeInPlace(torch.autograd.Function):
    # we don't currently use vmap, but maybe it will enable compile to fuse QK rope apply into flex attn operations?
    # benchmark suggests that enabling this didn't incur any additional cold-start time, so I guess it's lazy.
    generate_vmap_rule = True

    @staticmethod
    def forward(t: Tensor, freqs_cis: Tensor, coeff: Literal[1, -1] = -1):
        # _rope_inplace(t, freqs_cis, coeff=coeff)
        return t

    @staticmethod
    def setup_context(ctx, inputs, output):
        t, freqs_cis, coeff = inputs
        # mark t as dirty because we will modify it in-place. this ensures backward() will be called.
        ctx.mark_dirty(t)
        ctx.save_for_backward(freqs_cis)
        # required for jvp, probably
        ctx.save_for_forward(freqs_cis)
        ctx.coeff = coeff

    @staticmethod
    def backward(ctx, grad_output):
        (freqs_cis,) = ctx.saved_tensors
        # clone made because we must "NEVER" modify grad-w.r.t-input in-place.
        # https://pytorch.org/docs/main/notes/extending.html#how-to-use
        # https://discuss.pytorch.org/t/is-it-safe-to-modify-outputs-grad-and-return-as-inputs-grad/201630
        grad_output = RopeInPlace.apply(grad_output.clone(), freqs_cis, -ctx.coeff)
        return grad_output, None, None

    # !!!!!!!!!!!!!!!!!!
    # comment out this (unused) jvp function and compilation will succeed
    # !!!!!!!!!!!!!!!!!!
    # if the jvp function is present, torch.compile will fail to compile backward pass, with mysterious error:
    # shape '[132948266552741, 7448426736572743970, 6144]' is invalid for input of size 7864320
    # we don't even use jvp, I just added it for fun.
    @staticmethod
    def jvp(ctx, grad_input, *_):
        """
        none of our code currently uses this, but it gives us forward-mode autodiff support,
        which could be useful for implementing consistency training.
        """
        (freqs_cis,) = ctx.saved_tensors
        grad_input = RopeInPlace.apply(grad_input, freqs_cis, ctx.coeff)
        return grad_input


HEADS = 16
HEAD_DIM = 128
MODEL_DIM = 2048
MIDDLE_DIM = MODEL_DIM
HIDDEN_DIM = MODEL_DIM


class AttnBlock(Module):
    def __init__(
        self,
        dtype: torch.dtype,
        model_dim=MODEL_DIM,
        middle_dim=MIDDLE_DIM,
        head_dim=HEAD_DIM,
        heads=HEADS,
    ):
        super().__init__()
        self.heads = heads
        self.head_dim = head_dim
        # this is just for testing gradients
        self.qkv_proj = Linear(in_features=model_dim, out_features=middle_dim * 3, bias=False, dtype=dtype)

    def forward(self, x: Tensor) -> Tensor:
        qkv: Tensor = self.qkv_proj(x)
        qkv = qkv.unflatten(-1, (3, self.heads, self.head_dim))
        qk = qkv[..., :2, :, :]
        RopeInPlace.apply(qk.unflatten(-1, ((-1, 2))), None, -1)
        return qkv


device = torch.device("cuda")
gen = torch.Generator(device=device)
hp_dtype = torch.bfloat16

with torch.device("meta"):
    attn = AttnBlock(dtype=hp_dtype)
attn.to_empty(device=device)
with device, no_grad():
    attn.qkv_proj.weight.normal_(std=attn.qkv_proj.in_features**-0.5, generator=gen.manual_seed(42))
attn = torch.compile(attn, dynamic=False)

x = torch.randn((2, 640, MODEL_DIM), device=device, dtype=hp_dtype, generator=gen.manual_seed(1), requires_grad=True)
ref: Tensor = attn(x)
ref.sum().backward()
print("survived fwd+bwd")

my understanding is that dynamo may not actually support tracing this function?
apparently, under some circumstances, it is possible for dynamo to output this message:

Unsupported custom jvp
  Explanation: Dynamo does not support tracing `torch.autograd.Function` subclasses that define a custom `jvp` method.
  Hint: Remove the custom `jvp` method if possible.
  Hint: It may be possible to write Dynamo tracing rules for this code. Please report an issue to PyTorch if you encounter this graph break often and it is causing performance issues.

it would have saved me a few days if torch had output that message to me instead of the mysterious shape error caused by an unused code path.

Versions

Collecting environment information...
PyTorch version: 2.11.0
Is debug build: False
CUDA used to build PyTorch: 13.2
ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.4 LTS (x86_64)
GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04.1) 13.3.0
Clang version: Could not collect
CMake version: version 4.3.1
Libc version: glibc-2.39

Python version: 3.12.3 (main, Mar  3 2026, 12:15:18) [GCC 13.3.0] (64-bit runtime)
Python platform: Linux-6.8.12-680-6063-coreweave-amd64-f81899c8-x86_64-with-glibc2.39
Is CUDA available: True
CUDA runtime version: 13.2.51
CUDA_MODULE_LOADING set to: 
GPU models and configuration: 
GPU 0: NVIDIA H100 80GB HBM3
GPU 1: NVIDIA H100 80GB HBM3

Nvidia driver version: 580.126.20
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.20.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.20.0
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:                        46 bits physical, 57 bits virtual
Byte Order:                           Little Endian
CPU(s):                               128
On-line CPU(s) list:                  0-127
Vendor ID:                            GenuineIntel
Model name:                           Intel(R) Xeon(R) Platinum 8462Y+
CPU family:                           6
Model:                                143
Thread(s) per core:                   2
Core(s) per socket:                   32
Socket(s):                            2
Stepping:                             8
CPU(s) scaling MHz:                   95%
CPU max MHz:                          4100.0000
CPU min MHz:                          800.0000
BogoMIPS:                             5600.00
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 smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cat_l2 cdp_l3 cdp_l2 ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb intel_pt avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local split_lock_detect user_shstk avx_vnni avx512_bf16 wbnoinvd dtherm ida arat pln pts hfi vnmi avx512vbmi umip pku ospke waitpkg avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid bus_lock_detect cldemote movdiri movdir64b enqcmd fsrm md_clear serialize tsxldtrk pconfig arch_lbr ibt amx_bf16 avx512_fp16 amx_tile amx_int8 flush_l1d arch_capabilities
Virtualization:                       VT-x
L1d cache:                            3 MiB (64 instances)
L1i cache:                            2 MiB (64 instances)
L2 cache:                             128 MiB (64 instances)
L3 cache:                             120 MiB (2 instances)
NUMA node(s):                         2
NUMA node0 CPU(s):                    0,2,4,6,8,10,12,14,16,18,20,22,24,26,28,30,32,34,36,38,40,42,44,46,48,50,52,54,56,58,60,62,64,66,68,70,72,74,76,78,80,82,84,86,88,90,92,94,96,98,100,102,104,106,108,110,112,114,116,118,120,122,124,126
NUMA node1 CPU(s):                    1,3,5,7,9,11,13,15,17,19,21,23,25,27,29,31,33,35,37,39,41,43,45,47,49,51,53,55,57,59,61,63,65,67,69,71,73,75,77,79,81,83,85,87,89,91,93,95,97,99,101,103,105,107,109,111,113,115,117,119,121,123,125,127
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:   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; RSB filling; PBRSB-eIBRS SW sequence; BHI BHI_DIS_S
Vulnerability Srbds:                  Not affected
Vulnerability Tsx async abort:        Not affected

Versions of relevant libraries:
[pip3] clip-anytorch==2.6.0
[pip3] dctorch==0.1.2
[pip3] DISTS_pytorch==0.1
[pip3] lovely-numpy==0.2.20
[pip3] mypy_extensions==1.1.0
[pip3] numpy==2.4.4
[pip3] onnx==1.21.0
[pip3] onnx-ir==0.2.0
[pip3] onnxscript==0.6.2
[pip3] open_clip_torch==3.3.0
[pip3] optree==0.19.0
[pip3] torch==2.11.0
[pip3] torch_c_dlpack_ext==0.1.5
[pip3] torchaudio==2.11.0
[pip3] torchdata==0.11.0
[pip3] torchdiffeq==0.2.5
[pip3] torchsde==0.2.6
[pip3] torchtitan==0.2.2
[pip3] torchvision==0.26.0
[pip3] triton==3.6.0+git9844da95
[pip3] welford-torch==0.2.5
[conda] Could not collect

cc @chauhang @penguinwu @xmfan @aditvenk

extent analysis

TL;DR

The issue can be fixed by removing or commenting out the unused jvp function in the custom autograd function RopeInPlace, as Dynamo does not support tracing torch.autograd.Function subclasses that define a custom jvp method.

Guidance

  • Remove or comment out the jvp function in the RopeInPlace class to allow compilation to succeed.
  • Verify that the error message disappears after removing the jvp function.
  • If the jvp function is needed for forward-mode autodiff support, consider writing custom Dynamo tracing rules for this code.
  • Report an issue to PyTorch if this graph break occurs often and causes performance issues.

Example

# Comment out the jvp function to fix the issue
# @staticmethod
# def jvp(ctx, grad_input, *_):
#     ...

Notes

  • The error message "shape '[132948266552741, 7448426736572743970, 6144]' is invalid for input of size 7864320" is misleading and does not indicate the actual issue with the jvp function.
  • Dynamo's support for custom autograd functions with jvp methods is limited, and removing the jvp function is the simplest solution.

Recommendation

Apply workaround: Remove or comment out the jvp function in the RopeInPlace class, as it is not used in the current code and causes compilation issues with Dynamo.

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