pytorch - 💡(How to fix) Fix torch.nn.utils.weight_norm triggers a UBSan null pointer error for nn.Linear(0, 1) on CPU [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#181510Fetched 2026-04-27 05:28:52
View on GitHub
Comments
0
Participants
1
Timeline
140
Reactions
0
Author
Participants
Timeline (top)
mentioned ×65subscribed ×65labeled ×10

Error Message

Running the snippet triggers undefined behavior in the CPU weight_norm kernel.

Under an ASAN/UBSAN build, this is reported as: runtime error: null pointer passed as argument 2, which is declared to never be null

Stack trace: #0 at::vec::AVX2::Vectorized<float>::loadu(void const*, long) #1 map_reduce_all<...> #2 weight_norm_first_dim_kernel<float, float> #3 weight_norm_kernel #4 at::native::weight_norm_cpu(...)

This indicates that a tensor with a null data pointer (e.g., zero-sized tensor) is passed into the vectorized kernel without proper guarding, leading to undefined behavior.

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 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) Xeon(R) Gold 6242R CPU @ 3.10GHz CPU family: 6 Model: 85 Thread(s) per core: 1 Core(s) per socket: 32 Socket(s): 1 Stepping: 7 BogoMIPS: 6199.99 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm arch_perfmon rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor 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 mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat vnmi umip pku ospke avx512_vnni md_clear arch_capabilities Virtualization: VT-x Hypervisor vendor: KVM Virtualization type: full L1d cache: 1 MiB (32 instances) L1i cache: 1 MiB (32 instances) L2 cache: 128 MiB (32 instances) L3 cache: 16 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-31 Vulnerability Gather data sampling: Unknown: Dependent on hypervisor status Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: Mitigation; Aligned branch/return thunks Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown Vulnerability Old microcode: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Mitigation; Enhanced IBRS 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 SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Mitigation; TSX disabled Vulnerability Vmscape: Not affected

Code Example

import torch
import torch.nn as nn
from torch.nn.utils import weight_norm

m = nn.Linear(0, 1)
m = weight_norm(m)

x = torch.empty((1, 0), dtype=torch.float32)
print(m(x))

---

Running the snippet triggers undefined behavior in the CPU weight_norm kernel.

Under an ASAN/UBSAN build, this is reported as:
runtime error: null pointer passed as argument 2, which is declared to never be null

Stack trace:
#0  at::vec::AVX2::Vectorized<float>::loadu(void const*, long)
#1  map_reduce_all<...>
#2  weight_norm_first_dim_kernel<float, float>
#3  weight_norm_kernel
#4  at::native::weight_norm_cpu(...)

This indicates that a tensor with a null data pointer (e.g., zero-sized tensor) is passed into the vectorized kernel without proper guarding, leading to undefined behavior.

---

and returns:
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

I found this while fuzzing torch.nn.utils.weight_norm, and I was able to reduce it to the following self-contained CPU-only reproducer.

Applying torch.nn.utils.weight_norm to nn.Linear(0, 1) and then running a forward pass with an empty input triggers a UBSan runtime error in the CPU weight norm kernel:

aten/src/ATen/cpu/vec/vec256/vec256_float.h:124:16: runtime error: null pointer passed as argument 2, which is declared to never be null

A plain nn.Linear(0, 1) does not trigger this issue in the same ASAN/UBSAN build, so this looks specific to the weight_norm code path rather than zero-sized linear layers in general.

Minimal repro

import torch
import torch.nn as nn
from torch.nn.utils import weight_norm

m = nn.Linear(0, 1)
m = weight_norm(m)

x = torch.empty((1, 0), dtype=torch.float32)
print(m(x))

Observed behavior Running the snippet above under an ASAN/UBSAN PyTorch build reports:

Running the snippet triggers undefined behavior in the CPU weight_norm kernel.

Under an ASAN/UBSAN build, this is reported as:
runtime error: null pointer passed as argument 2, which is declared to never be null

Stack trace:
#0  at::vec::AVX2::Vectorized<float>::loadu(void const*, long)
#1  map_reduce_all<...>
#2  weight_norm_first_dim_kernel<float, float>
#3  weight_norm_kernel
#4  at::native::weight_norm_cpu(...)

This indicates that a tensor with a null data pointer (e.g., zero-sized tensor) is passed into the vectorized kernel without proper guarding, leading to undefined behavior.

The non-weight_norm control case completes normally:

import torch
import torch.nn as nn

m = nn.Linear(0, 1)
x = torch.empty((1, 0), dtype=torch.float32)
print(m(x))

and returns:

tensor([[0.]], grad_fn=<AddmmBackward0>)

Expected behavior PyTorch should handle this case without triggering undefined behavior in the CPU kernel.

I would expect one of these outcomes instead:

Return a valid tensor, similar to the plain nn.Linear(0, 1) case. Raise a regular Python/PyTorch error if zero-sized inputs are unsupported here. But it should not hit a UBSan null-pointer violation in internal kernel code.

Environment PyTorch version: 2.8.0a0+gitba56102 Git commit: ba56102387ef21a3b04b357e5b183d48f0afefc7 Python: 3.10.20 OS: Ubuntu 24.04.3 LTS (x86_64) This was reproduced on an ASAN/UBSAN build of PyTorch

Versions

[W426 16:03:36.508076009 Module.cpp:1514] Warning: torch.cuda: your pytorch binary has address sanitizer (asan) built in, asan is currently not compatible with torch.cuda module, you might get unexpected behavior (eg. out of memory, crash, etc.), please rebuild pytorch without asan if you need to use this module (function THCPModule_initExtension) PyTorch version: 2.8.0a0+gitba56102 Is debug build: False CUDA used to build PyTorch: 12.9 ROCM used to build PyTorch: N/A

OS: Ubuntu 24.04.3 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.10.20 | packaged by conda-forge | (main, Mar 5 2026, 16:42:22) [GCC 14.3.0] (64-bit runtime) Python platform: Linux-6.17.0-19-generic-x86_64-with-glibc2.39 Is CUDA available: True CUDA runtime version: Could not collect CUDA_MODULE_LOADING set to: LAZY GPU models and configuration: GPU 0: NVIDIA GeForce RTX 2080 Ti GPU 1: NVIDIA GeForce RTX 2080 Ti GPU 2: NVIDIA GeForce RTX 2080 Ti GPU 3: NVIDIA GeForce RTX 2080 Ti

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

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Address sizes: 46 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) Xeon(R) Gold 6242R CPU @ 3.10GHz CPU family: 6 Model: 85 Thread(s) per core: 1 Core(s) per socket: 32 Socket(s): 1 Stepping: 7 BogoMIPS: 6199.99 Flags: fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm arch_perfmon rep_good nopl xtopology cpuid tsc_known_freq pni pclmulqdq vmx ssse3 fma cx16 pdcm pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor 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 mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves arat vnmi umip pku ospke avx512_vnni md_clear arch_capabilities Virtualization: VT-x Hypervisor vendor: KVM Virtualization type: full L1d cache: 1 MiB (32 instances) L1i cache: 1 MiB (32 instances) L2 cache: 128 MiB (32 instances) L3 cache: 16 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-31 Vulnerability Gather data sampling: Unknown: Dependent on hypervisor status Vulnerability Ghostwrite: Not affected Vulnerability Indirect target selection: Mitigation; Aligned branch/return thunks Vulnerability Itlb multihit: Not affected Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown Vulnerability Old microcode: Not affected Vulnerability Reg file data sampling: Not affected Vulnerability Retbleed: Mitigation; Enhanced IBRS 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 SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsa: Not affected Vulnerability Tsx async abort: Mitigation; TSX disabled Vulnerability Vmscape: Not affected

Versions of relevant libraries: [pip3] numpy==2.2.6 [pip3] optree==0.19.0 [pip3] torch==2.8.0a0+gitba56102 [conda] numpy 2.2.6 pypi_0 pypi [conda] optree 0.19.0 pypi_0 pypi [conda] torch 2.8.0a0+gitba56102 pypi_0 pypi

cc @albanD @mruberry @jbschlosser @walterddr @mikaylagawarecki @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10 @jerryzh168 @aditew01

extent analysis

TL;DR

The issue can be fixed by adding a check to handle zero-sized tensors before applying the weight_norm function.

Guidance

  • Verify that the input tensor is not zero-sized before applying weight_norm.
  • Modify the weight_norm function to handle zero-sized tensors, either by returning a valid tensor or raising a Python/PyTorch error.
  • Check the PyTorch version and consider upgrading to a newer version if available, as this issue may be fixed in later releases.
  • Test the modified code with different input sizes to ensure it works correctly.

Example

import torch
import torch.nn as nn
from torch.nn.utils import weight_norm

def safe_weight_norm(module):
    if module.weight.shape[1] == 0:  # check for zero-sized tensor
        raise ValueError("Zero-sized tensor is not supported")
    return weight_norm(module)

m = nn.Linear(0, 1)
m = safe_weight_norm(m)

Notes

This fix assumes that the issue is specific to the weight_norm function and zero-sized tensors. Further investigation may be needed to determine the root cause of the issue.

Recommendation

Apply the workaround by adding a check to handle zero-sized tensors before applying the weight_norm function, as shown in the example code. This will prevent the undefined behavior and provide a clear error message instead.

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