pytorch - 💡(How to fix) Fix ConvTranspose + BatchNorm fusion broken for `groups != 1` [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#180995Fetched 2026-04-22 07:43:06
View on GitHub
Comments
0
Participants
1
Timeline
18
Reactions
0
Author
Participants
Timeline (top)
mentioned ×8subscribed ×8labeled ×2

Error Message

RuntimeError: The size of tensor a (2) must match the size of tensor b (4) at non-singleton dimension 1

Fix Action

Fix

I have a working fix (reshape the weight into its per-group layout, apply the per-group scale in torch.nn.utils.fusion.fuse_conv_bn_weights).

Code Example

import torch.nn as nn
from torch.ao.quantization.quantize_fx import fuse_fx

class ConvTransposeBNModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.deconv = nn.ConvTranspose2d(
            in_channels=4, out_channels=4, kernel_size=3,
            stride=1, padding=1, groups=2, bias=False,
        )
        self.bn = nn.BatchNorm2d(4)

    def forward(self, x):
        return self.bn(self.deconv(x))

model = ConvTransposeBNModel().eval()
fused_model = fuse_fx(model)   # RuntimeError

---

RuntimeError: The size of tensor a (2) must match the size of tensor b (4) at non-singleton dimension 1
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

torch.ao.quantization.quantize_fx.fuse_fx cannot fuse a ConvTransposeNd + BatchNormNd pair when the ConvTranspose has groups > 1. It raises a shape-mismatch RuntimeError during fusion. The same model fuses fine with groups=1.

Repro

import torch.nn as nn
from torch.ao.quantization.quantize_fx import fuse_fx

class ConvTransposeBNModel(nn.Module):
    def __init__(self):
        super().__init__()
        self.deconv = nn.ConvTranspose2d(
            in_channels=4, out_channels=4, kernel_size=3,
            stride=1, padding=1, groups=2, bias=False,
        )
        self.bn = nn.BatchNorm2d(4)

    def forward(self, x):
        return self.bn(self.deconv(x))

model = ConvTransposeBNModel().eval()
fused_model = fuse_fx(model)   # RuntimeError

Error

RuntimeError: The size of tensor a (2) must match the size of tensor b (4) at non-singleton dimension 1

Fix

I have a working fix (reshape the weight into its per-group layout, apply the per-group scale in torch.nn.utils.fusion.fuse_conv_bn_weights).

Versions

Collecting environment information... .venv/lib/python3.11/site-packages/torch/cuda/init.py:180: UserWarning: CUDA initialization: The NVIDIA driver on your system is too old (found version 12040). Please update your GPU driver by downloading and installing a new version from the URL: http://www.nvidia.com/Download/index.aspx Alternatively, go to: https://pytorch.org to install a PyTorch version that has been compiled with your version of the CUDA driver. (Triggered internally at /pytorch/c10/cuda/CUDAFunctions.cpp:119.) return torch._C._cuda_getDeviceCount() > 0 PyTorch version: 2.11.0+cu130 Is debug build: False CUDA used to build PyTorch: 13.0 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.3 LTS (x86_64) GCC version: (Ubuntu 13.3.0-6ubuntu2~24.04) 13.3.0 Clang version: Could not collect CMake version: version 3.28.3 Libc version: glibc-2.39

Python version: 3.11.13 (main, Jun 4 2025, 08:57:30) [GCC 13.3.0] (64-bit runtime) Python platform: Linux-6.8.0-71-generic-x86_64-with-glibc2.39 Is CUDA available: False CUDA runtime version: 12.0.140 CUDA_MODULE_LOADING set to: N/A GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3090 Ti Nvidia driver version: 550.163.01 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: 39 bits physical, 48 bits virtual Byte Order: Little Endian CPU(s): 20 On-line CPU(s) list: 0-19 Vendor ID: GenuineIntel Model name: 13th Gen Intel(R) Core(TM) i5-13600KF CPU family: 6 Model: 183 Thread(s) per core: 2 Core(s) per socket: 14 Socket(s): 1 Stepping: 1 CPU(s) scaling MHz: 37% CPU max MHz: 5100,0000 CPU min MHz: 800,0000 BogoMIPS: 6988,80 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 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault 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: 544 KiB (14 instances) L1i cache: 704 KiB (14 instances) L2 cache: 20 MiB (8 instances) L3 cache: 24 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-19 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: 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; 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] numpy==2.4.4 [pip3] nvidia-cublas==13.1.0.3 [pip3] nvidia-cuda-cupti==13.0.85 [pip3] nvidia-cuda-nvrtc==13.0.88 [pip3] nvidia-cuda-runtime==13.0.96 [pip3] nvidia-cudnn-cu13==9.19.0.56 [pip3] nvidia-cufft==12.0.0.61 [pip3] nvidia-curand==10.4.0.35 [pip3] nvidia-cusolver==12.0.4.66 [pip3] nvidia-cusparse==12.6.3.3 [pip3] nvidia-cusparselt-cu13==0.8.0 [pip3] nvidia-nccl-cu13==2.28.9 [pip3] nvidia-nvjitlink==13.0.88 [pip3] nvidia-nvtx==13.0.85 [pip3] torch==2.11.0 [pip3] torch-mlir==20260416.784 [pip3] torchvision==0.26.0 [pip3] triton==3.6.0 [conda] Could not collect

cc @jerryzh168 @jianyuh @raghuramank100 @jamesr66a @vkuzo @jgong5 @Xia-Weiwen @leslie-fang-intel

extent analysis

TL;DR

The issue can be resolved by modifying the torch.nn.utils.fusion.fuse_conv_bn_weights function to correctly handle the per-group layout of the weights when groups > 1 in ConvTranspose2d.

Guidance

  • Identify the specific line of code in torch.nn.utils.fusion.fuse_conv_bn_weights that is causing the shape mismatch error.
  • Modify this line to reshape the weight into its per-group layout before applying the per-group scale.
  • Verify that the modified function correctly fuses the ConvTranspose2d and BatchNorm2d layers when groups > 1.
  • Test the modified function with different values of groups to ensure it works as expected.

Example

# Assuming the issue is in the fuse_conv_bn_weights function
def fuse_conv_bn_weights(conv_weight, bn_weight, bn_bias):
    # Reshape the conv_weight into its per-group layout
    conv_weight = conv_weight.view(conv_weight.size(0) // conv_weight.size(1), conv_weight.size(1), *conv_weight.size()[2:])
    # Apply the per-group scale
    fused_weight = conv_weight * bn_weight[:, None, None, None]
    return fused_weight

Notes

The provided fix is specific to the ConvTranspose2d and BatchNorm2d layers, and may not work for other types of layers. Additionally, the modification to the fuse_conv_bn_weights function may have unintended consequences and should be thoroughly tested before being used in production.

Recommendation

Apply the workaround by modifying the torch.nn.utils.fusion.fuse_conv_bn_weights function to correctly handle the per-group layout of the weights when groups > 1 in ConvTranspose2d, as this is a more targeted and efficient solution than upgrading to a potentially non-existent fixed version.

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 - 💡(How to fix) Fix ConvTranspose + BatchNorm fusion broken for `groups != 1` [1 participants]