pytorch - ✅(Solved) Fix MaxUnpool2d can infer negative output dimensions for valid input shapes under torch.compile [1 pull requests, 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#178483Fetched 2026-04-08 01:30:15
View on GitHub
Comments
1
Participants
2
Timeline
29
Reactions
0
Author
Timeline (top)
labeled ×8mentioned ×8subscribed ×8referenced ×2

torch.nn.MaxUnpool2d may infer an invalid output shape with negative dimensions for some kernel_size/stride/padding combinations. The same case also fails under torch.compile during fake tensor/meta execution.

Error Message

MaxUnpool2d should either return a valid output tensor shape or raise a clear validation error for unsupported parameters.

Root Cause

torch.nn.MaxUnpool2d may infer an invalid output shape with negative dimensions for some kernel_size/stride/padding combinations. The same case also fails under torch.compile during fake tensor/meta execution.

Fix Action

Fix / Workaround

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): 112 On-line CPU(s) list: 0-111 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Gold 6330 CPU @ 2.00GHz CPU family: 6 Model: 106 Thread(s) per core: 2 Core(s) per socket: 28 Socket(s): 2 Stepping: 6 CPU(s) scaling MHz: 28% CPU max MHz: 3100.0000 CPU min MHz: 800.0000 BogoMIPS: 4000.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 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 invpcid_single intel_ppin 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 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 2.6 MiB (56 instances) L1i cache: 1.8 MiB (56 instances) L2 cache: 70 MiB (56 instances) L3 cache: 84 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 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 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable 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 Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

PR fix notes

PR #178577: [Pooling] Validate non-positive inferred output dimensions in MaxUnpool

Description (problem / solution / changelog)

Issue

Fixes #178483

Summary

MaxUnpool1d/2d/3d silently produce tensors with negative or zero output dimensions when padding is large relative to input_size/stride/kernel_size. In eager mode this yields an invalid tensor shape (e.g. torch.Size([1, 1, 0, -2])); under torch.compile it triggers an unclear RuntimeError.

Added validation in _unpool_output_size() (Python and C++ frontend) to raise a clear ValueError when the inferred output size is non-positive. Also added defense-in-depth checks in the decomposition layer and ATen C++/CUDA implementations.

Checklist

  • Passes lint (spin fixlint)
  • Added/updated tests
  • Updated documentation (if applicable)
  • Included benchmark results (for PRs impacting perf)

BC-breaking?

No. This only adds validation that rejects previously undefined behavior (negative output dimensions). Any code that was producing valid results before will continue to work unchanged.

Test plan

  • New test test_max_unpool_negative_output_size covers MaxUnpool1d, MaxUnpool2d, MaxUnpool3d and functional API
  • All existing test_max_unpool* tests pass
<details> <summary>Before (bug — no validation)</summary>
$ python agent_space/repro_178483.py

W0327 15:45:39.146000 63006 /ssd1/jianglidang/workspace/pytorch/torch/utils/flop_counter.py:29] triton not found; flop counting will not work for triton kernels
=== MaxUnpool2d: negative output size repro ===
Eager: got shape torch.Size([1, 1, 0, -2]) (BUG: should have raised error)

=== MaxUnpool2d: torch.compile path ===
Compiled: TorchRuntimeError: RuntimeError when making fake tensor call
  Explanation: Dynamo failed to run FX node with fake tensors: call_function <function max_unpool2d at 0x7efbc54eeca0>(*(FakeTensor(..., size=(1, 1, 2, 2)), FakeTensor(..., size=(1, 1, 2, 2), dtype=torch.int64), (1, 1), (5, 5), (3, 4), None), **{}): got RuntimeError('Trying to create tensor with negative dimension -2: [1, 1, 0, -2]')
  Hint: Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance("force_eager")`. 

  Developer debug context: 

 For more details about this graph break, please visit: https://meta-pytorch.github.io/compile-graph-break-site/gb/gb4315.html

from user code:
   File "/ssd1/jianglidang/workspace/pytorch/agent_space/repro_178483.py", line 23, in torch_dynamo_resume_in_call_func_at_23
    return torch.nn.MaxUnpool2d(kernel_size, stride, padding)(x, idx)
  File "/ssd1/jianglidang/workspace/pytorch/torch/nn/modules/pooling.py", line 498, in forward
    return F.max_unpool2d(

Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo"


=== MaxUnpool1d: negative output size ===
Eager: RuntimeError: numel: integer multiplication overflow

=== MaxUnpool3d: negative output size ===
Eager: RuntimeError: numel: integer multiplication overflow
</details> <details> <summary>After (fix — clear ValueError)</summary>
$ python agent_space/repro_178483.py

W0327 15:49:03.669000 84960 /ssd1/jianglidang/workspace/pytorch/torch/utils/flop_counter.py:29] triton not found; flop counting will not work for triton kernels
=== MaxUnpool2d: negative output size repro ===
Eager: ValueError raised (FIXED): max_unpooling: inferred output size for dimension 0 is 0, which is non-positive. The combination of input size 2, kernel_size 1, stride 5, and padding 3 leads to invalid output dimensions.

=== MaxUnpool2d: torch.compile path ===
Compiled: TorchRuntimeError: RuntimeError when making fake tensor call
  Explanation: Dynamo failed to run FX node with fake tensors: call_function <function max_unpool2d at 0x7ff24e60afc0>(*(FakeTensor(..., size=(1, 1, 2, 2)), FakeTensor(..., size=(1, 1, 2, 2), dtype=torch.int64), (1, 1), (5, 5), (3, 4), None), **{}): got ValueError('max_unpooling: inferred output size for dimension 0 is 0, which is non-positive. The combination of input size 2, kernel_size 1, stride 5, and padding 3 leads to invalid output dimensions.')
  Hint: Your code may result in an error when running in eager. Please double check that your code doesn't contain a similar error when actually running eager/uncompiled. You can do this by removing the `torch.compile` call, or by using `torch.compiler.set_stance("force_eager")`. 

  Developer debug context: 

 For more details about this graph break, please visit: https://meta-pytorch.github.io/compile-graph-break-site/gb/gb4315.html

from user code:
   File "/ssd1/jianglidang/workspace/pytorch/agent_space/repro_178483.py", line 23, in torch_dynamo_resume_in_call_func_at_23
    return torch.nn.MaxUnpool2d(kernel_size, stride, padding)(x, idx)
  File "/ssd1/jianglidang/workspace/pytorch/torch/nn/modules/pooling.py", line 498, in forward
    return F.max_unpool2d(

Set TORCHDYNAMO_VERBOSE=1 for the internal stack trace (please do this especially if you're reporting a bug to PyTorch). For even more developer context, set TORCH_LOGS="+dynamo"


=== MaxUnpool1d: negative output size ===
Eager: ValueError raised (FIXED): max_unpooling: inferred output size for dimension 0 is -2, which is non-positive. The combination of input size 2, kernel_size 1, stride 5, and padding 4 leads to invalid output dimensions.

=== MaxUnpool3d: negative output size ===
Eager: ValueError raised (FIXED): max_unpooling: inferred output size for dimension 0 is -2, which is non-positive. The combination of input size 2, kernel_size 1, stride 5, and padding 4 leads to invalid output dimensions.
</details> <details> <summary>Test results</summary>
$ python -m pytest test/nn/test_pooling.py -xvs -k "test_max_unpool_negative_output_size or test_max_unpool3d_input_check or test_max_unpool "

test/nn/test_pooling.py::TestPoolingNN::test_max_unpool PASSED [0.3437s]
test/nn/test_pooling.py::TestPoolingNN::test_max_unpool2d_nhwc_cpu PASSED [0.0033s]
test/nn/test_pooling.py::TestPoolingNN::test_max_unpool3d_input_check PASSED [0.0015s]
test/nn/test_pooling.py::TestPoolingNN::test_max_unpool_negative_output_size PASSED [0.0011s]

====================== 4 passed, 239 deselected in 0.84s =======================
</details>

Authored with Claude.

Changed files

  • aten/src/ATen/native/MaxUnpooling.cpp (modified, +10/-0)
  • aten/src/ATen/native/cuda/MaxUnpooling.cu (modified, +10/-0)
  • test/nn/test_pooling.py (modified, +28/-0)
  • torch/_decomp/decompositions.py (modified, +18/-0)
  • torch/csrc/api/include/torch/nn/functional/pooling.h (modified, +17/-0)
  • torch/nn/functional.py (modified, +9/-0)

Code Example

import torch

def call_func(kernel_size, stride, x, idx, padding):
    return torch.nn.MaxUnpool2d(kernel_size, stride, padding)(x, idx)

kernel_size = [1, 1]
stride = 5
padding = [3, 4]
x = torch.randn(1, 1, 2, 2)
idx = torch.zeros(1, 1, 2, 2, dtype=torch.long)

print(call_func(kernel_size, stride, x, idx, padding).shape)
print(torch.compile(call_func, dynamic=True)(kernel_size, stride, x, idx, padding).shape)
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

Summary

torch.nn.MaxUnpool2d may infer an invalid output shape with negative dimensions for some kernel_size/stride/padding combinations. The same case also fails under torch.compile during fake tensor/meta execution.

Repro

import torch

def call_func(kernel_size, stride, x, idx, padding):
    return torch.nn.MaxUnpool2d(kernel_size, stride, padding)(x, idx)

kernel_size = [1, 1]
stride = 5
padding = [3, 4]
x = torch.randn(1, 1, 2, 2)
idx = torch.zeros(1, 1, 2, 2, dtype=torch.long)

print(call_func(kernel_size, stride, x, idx, padding).shape)
print(torch.compile(call_func, dynamic=True)(kernel_size, stride, x, idx, padding).shape)

Expected

MaxUnpool2d should either return a valid output tensor shape or raise a clear validation error for unsupported parameters.

Actual

  • Eager mode prints an invalid shape: torch.Size([1, 1, 0, -2])
  • torch.compile fails in fake/meta execution with: RuntimeError: Trying to create tensor with negative dimension ...

Notes

This appears to come from incorrect output-size inference in MaxUnpool2d when padding is large relative to the input/stride.

Versions

PyTorch version: 2.10.0+cu128 Is debug build: False CUDA used to build PyTorch: 12.8 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: Could not collect Libc version: glibc-2.39

Python version: 3.12.0 | packaged by Anaconda, Inc. | (main, Oct 2 2023, 17:29:18) [GCC 11.2.0] (64-bit runtime) Python platform: Linux-6.5.11-060511-generic-x86_64-with-glibc2.39 Is CUDA available: True CUDA runtime version: Could not collect CUDA_MODULE_LOADING set to: GPU models and configuration: GPU 0: NVIDIA RTX A6000 GPU 1: NVIDIA RTX A6000

Nvidia driver version: 580.65.06 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: 46 bits physical, 57 bits virtual Byte Order: Little Endian CPU(s): 112 On-line CPU(s) list: 0-111 Vendor ID: GenuineIntel Model name: Intel(R) Xeon(R) Gold 6330 CPU @ 2.00GHz CPU family: 6 Model: 106 Thread(s) per core: 2 Core(s) per socket: 28 Socket(s): 2 Stepping: 6 CPU(s) scaling MHz: 28% CPU max MHz: 3100.0000 CPU min MHz: 800.0000 BogoMIPS: 4000.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 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 invpcid_single intel_ppin 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 wbnoinvd dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req vnmi avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg tme avx512_vpopcntdq la57 rdpid fsrm md_clear pconfig flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 2.6 MiB (56 instances) L1i cache: 1.8 MiB (56 instances) L2 cache: 70 MiB (56 instances) L3 cache: 84 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 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 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable 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 Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected

Versions of relevant libraries: [pip3] numpy==2.4.1 [pip3] nvidia-cublas-cu12==12.8.4.1 [pip3] nvidia-cuda-cupti-cu12==12.8.90 [pip3] nvidia-cuda-nvrtc-cu12==12.8.93 [pip3] nvidia-cuda-runtime-cu12==12.8.90 [pip3] nvidia-cudnn-cu12==9.10.2.21 [pip3] nvidia-cufft-cu12==11.3.3.83 [pip3] nvidia-curand-cu12==10.3.9.90 [pip3] nvidia-cusolver-cu12==11.7.3.90 [pip3] nvidia-cusparse-cu12==12.5.8.93 [pip3] nvidia-cusparselt-cu12==0.7.1 [pip3] nvidia-nccl-cu12==2.27.5 [pip3] nvidia-nvjitlink-cu12==12.8.93 [pip3] nvidia-nvtx-cu12==12.8.90 [pip3] optree==0.18.0 [pip3] torch==2.10.0 [pip3] triton==3.6.0 [conda] numpy 2.4.1 pypi_0 pypi [conda] nvidia-cublas-cu12 12.8.4.1 pypi_0 pypi [conda] nvidia-cuda-cupti-cu12 12.8.90 pypi_0 pypi [conda] nvidia-cuda-nvrtc-cu12 12.8.93 pypi_0 pypi [conda] nvidia-cuda-runtime-cu12 12.8.90 pypi_0 pypi [conda] nvidia-cudnn-cu12 9.10.2.21 pypi_0 pypi [conda] nvidia-cufft-cu12 11.3.3.83 pypi_0 pypi [conda] nvidia-curand-cu12 10.3.9.90 pypi_0 pypi [conda] nvidia-cusolver-cu12 11.7.3.90 pypi_0 pypi [conda] nvidia-cusparse-cu12 12.5.8.93 pypi_0 pypi [conda] nvidia-cusparselt-cu12 0.7.1 pypi_0 pypi [conda] nvidia-nccl-cu12 2.27.5 pypi_0 pypi [conda] nvidia-nvjitlink-cu12 12.8.93 pypi_0 pypi [conda] nvidia-nvtx-cu12 12.8.90 pypi_0 pypi [conda] optree 0.18.0 pypi_0 pypi [conda] torch 2.10.0 pypi_0 pypi [conda] triton 3.6.0 pypi_0 pypi

cc @malfet @mikaylagawarecki @chauhang @penguinwu @eellison @aorenste @bdhirsh @bobrenjc93

extent analysis

Fix Plan

To fix the issue with torch.nn.MaxUnpool2d inferring an invalid output shape, we need to add input validation to ensure that the output shape is valid.

Here are the steps to fix the issue:

  • Check if the output shape is valid before returning it.
  • If the output shape is not valid, raise a clear validation error.

Code Changes

import torch

class MaxUnpool2d(torch.nn.MaxUnpool2d):
    def forward(self, input, indices):
        output = torch.nn.functional.max_unpool2d(input, indices, self.kernel_size, self.stride, self.padding)
        output_shape = output.shape
        if output_shape[2] < 0 or output_shape[3] < 0:
            raise ValueError("Invalid output shape")
        return output

def call_func(kernel_size, stride, x, idx, padding):
    return MaxUnpool2d(kernel_size, stride, padding)(x, idx)

kernel_size = [1, 1]
stride = 5
padding = [3, 4]
x = torch.randn(1, 1, 2, 2)
idx = torch.zeros(1, 1, 2, 2, dtype=torch.long)

print(call_func(kernel_size, stride, x, idx, padding).shape)
print(torch.compile(call_func, dynamic=True)(kernel_size, stride, x, idx, padding).shape)

Verification

To verify that the fix worked, we can check if the output shape is valid and if a clear validation error is raised when the output shape is not valid.

Extra Tips

  • Always validate the input and output shapes of PyTorch modules to ensure they are valid.
  • Use clear and descriptive error messages to help with debugging.
  • Test the fix thoroughly to ensure it works as expected.

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

pytorch - ✅(Solved) Fix MaxUnpool2d can infer negative output dimensions for valid input shapes under torch.compile [1 pull requests, 1 comments, 2 participants]