pytorch - ✅(Solved) Fix torch.lu_unpack crashes when LU_pivots is an empty tensor [2 pull requests, 2 comments, 3 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#177829Fetched 2026-04-08 01:01:34
View on GitHub
Comments
2
Participants
3
Timeline
56
Reactions
0
Timeline (top)
mentioned ×19subscribed ×19labeled ×9referenced ×4

Fix Action

Fix / Workaround

CPU: Architecture: x86_64 CPU op-mode(s): 32-bit, 64-bit Byte Order: Little Endian Address sizes: 46 bits physical, 57 bits virtual CPU(s): 64 On-line CPU(s) list: 0-63 Thread(s) per core: 2 Core(s) per socket: 16 Socket(s): 2 NUMA node(s): 2 Vendor ID: GenuineIntel CPU family: 6 Model: 106 Model name: Intel(R) Xeon(R) Gold 6326 CPU @ 2.90GHz Stepping: 6 CPU MHz: 895.670 CPU max MHz: 3500.0000 CPU min MHz: 800.0000 BogoMIPS: 5800.00 Virtualization: VT-x L1d cache: 1.5 MiB L1i cache: 1 MiB L2 cache: 40 MiB L3 cache: 48 MiB NUMA node0 CPU(s): 0-15,32-47 NUMA node1 CPU(s): 16-31,48-63 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 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 and seccomp 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 SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected 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 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 vnmi 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 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

PR fix notes

PR #177836: [lu_unpack] Fix segfault when LU_pivots is empty tensor

Description (problem / solution / changelog)

What does this PR do?

Fixes a segmentation fault in torch.lu_unpack that occurs when the LU_pivots tensor is empty (has no elements) while LU_data has a valid non-empty shape.

Root Cause

The original code did not validate the shape of LU_pivots before accessing its elements, leading to out-of-bounds memory access (segmentation fault) when LU_pivots is empty.

Solution

Added shape validation for LU_pivots using TORCH_CHECK:

  • Calculate the expected shape of LU_pivots (LU_data's first N-2 dimensions + min(m, n), where m/n are the last two dimensions of LU_data)
  • Check if LU_pivots' shape matches the expected shape; if not (e.g., empty tensor), throw a clear error message instead of crashing.

Related Issue

Fixes #177829

Test Cases

Updated a unit test to verify the fix (in test/test_linalg.py/test_lu_unpack_check_input):

        # invalid pivots shape should be rejected with error, not segfault
        wrong_dim_pivots = torch.empty((0,), dtype=torch.int32, device=device)
        with self.assertRaisesRegex(RuntimeError, r"Expected LU_pivots shape to be \[5, 5\], but got \[0\]"):
            torch.lu_unpack(lu_data, wrong_dim_pivots)

        wrong_size_pivots = torch.ones(5, 3, dtype=torch.int32, device=device)
        with self.assertRaisesRegex(RuntimeError, r"Expected LU_pivots shape to be \[5, 5\], but got \[5, 3\]"):
            torch.lu_unpack(lu_data, wrong_size_pivots)

        wrong_batch_pivots = torch.ones(6, 5, dtype=torch.int32, device=device)
        with self.assertRaisesRegex(RuntimeError, r"Expected LU_pivots shape to be \[5, 5\], but got \[6, 5\]"):
            torch.lu_unpack(lu_data, wrong_batch_pivots)
import torch
LU_data = torch.tensor([[2., 3., 1.],
                        [0.5, 1., 2.],
                        [0.25, 0.5, 1.]])
LU_pivots = torch.tensor([], dtype=torch.int32)
P, L, U = torch.lu_unpack(LU_data, LU_pivots)

Traceback (most recent call last):
  File "/Users/lillian/Desktop/Python/pytorch/test/test_issue.py", line 11, in <module>
    P, L, U = torch.lu_unpack(LU_data, LU_pivots)
              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
RuntimeError: torch.lu_unpack: Expected LU_pivots shape to be [3], but got [0]

Changed files

  • aten/src/ATen/native/BatchLinearAlgebra.cpp (modified, +20/-6)
  • test/test_linalg.py (modified, +13/-0)
  • torch/_meta_registrations.py (modified, +24/-6)

PR #177911: fix(linalg): validate lu_unpack pivot shape before unpack kernel

Description (problem / solution / changelog)

Summary

  • add shape validation for torch.lu_unpack pivots in C++ meta to prevent out-of-bounds reads
  • mirror the same validation in Python meta registration to keep fake/meta behavior aligned
  • add a regression test in test_linalg.py for empty pivots

Root cause

lu_unpack validated pivot dtype but not pivot shape. When LU_pivots is empty (or otherwise too short), the unpack kernel indexed past the pivot buffer and could segfault.

Testing

  • /mnt/d/ubuntu/27/OSS_1/pytorch/.venv/bin/python -m compileall /mnt/d/ubuntu/27/OSS_1/pytorch/torch/_meta_registrations.py /mnt/d/ubuntu/27/OSS_1/pytorch/test/test_linalg.py
  • /mnt/d/ubuntu/27/OSS_1/pytorch/.venv/bin/python /mnt/d/ubuntu/27/OSS_1/pytorch/test/test_linalg.py -k test_lu_unpack_check_input -v (on current upstream wheel, this test reproduces the pre-fix crash path and terminates at the lu_unpack empty-pivots case)

Fixes #177829

Changed files

  • aten/src/ATen/native/BatchLinearAlgebra.cpp (modified, +22/-0)
  • test/test_linalg.py (modified, +5/-0)
  • torch/_meta_registrations.py (modified, +21/-0)

Code Example

import torch
LU_data = torch.tensor([[2., 3., 1.],
                        [0.5, 1., 2.],
                        [0.25, 0.5, 1.]])
LU_pivots = torch.tensor([], dtype=torch.int32)
P, L, U = torch.lu_unpack(LU_data, LU_pivots)
RAW_BUFFERClick to expand / collapse

🐛 Describe the bug

I encountered a bug in PyTorch when using the API torch.lu_unpack. The crash is triggered when the LU_pivots tensor is provided as an empty tensor, while the LU_data tensor has a defined shape. The code to reproduce this is as follows:

import torch
LU_data = torch.tensor([[2., 3., 1.],
                        [0.5, 1., 2.],
                        [0.25, 0.5, 1.]])
LU_pivots = torch.tensor([], dtype=torch.int32)
P, L, U = torch.lu_unpack(LU_data, LU_pivots)

Output:

segmentation fault

Versions

Collecting environment information... 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 20.04.3 LTS (x86_64) GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0 Clang version: Could not collect CMake version: Could not collect Libc version: glibc-2.31

Python version: 3.13.12 | packaged by Anaconda, Inc. | (main, Feb 24 2026, 16:13:31) [GCC 14.3.0] (64-bit runtime) Python platform: Linux-5.15.0-139-generic-x86_64-with-glibc2.31 Is CUDA available: True CUDA runtime version: Could not collect CUDA_MODULE_LOADING set to: GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3090 GPU 1: NVIDIA GeForce RTX 3090 GPU 2: NVIDIA GeForce RTX 3090 GPU 3: NVIDIA GeForce RTX 3090 GPU 4: NVIDIA GeForce RTX 3090 GPU 5: NVIDIA GeForce RTX 3090 GPU 6: NVIDIA GeForce RTX 3090 GPU 7: NVIDIA GeForce RTX 3090

Nvidia driver version: 535.183.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 Byte Order: Little Endian Address sizes: 46 bits physical, 57 bits virtual CPU(s): 64 On-line CPU(s) list: 0-63 Thread(s) per core: 2 Core(s) per socket: 16 Socket(s): 2 NUMA node(s): 2 Vendor ID: GenuineIntel CPU family: 6 Model: 106 Model name: Intel(R) Xeon(R) Gold 6326 CPU @ 2.90GHz Stepping: 6 CPU MHz: 895.670 CPU max MHz: 3500.0000 CPU min MHz: 800.0000 BogoMIPS: 5800.00 Virtualization: VT-x L1d cache: 1.5 MiB L1i cache: 1 MiB L2 cache: 40 MiB L3 cache: 48 MiB NUMA node0 CPU(s): 0-15,32-47 NUMA node1 CPU(s): 16-31,48-63 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 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 and seccomp 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 SW loop, KVM SW loop Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Not affected 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 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 vnmi 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 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

Versions of relevant libraries: [pip3] numpy==2.4.3 [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.19.0 [pip3] torch==2.10.0 [pip3] triton==3.6.0 [conda] numpy 2.4.3 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.19.0 pypi_0 pypi [conda] torch 2.10.0 pypi_0 pypi [conda] triton 3.6.0 pypi_0 pypi

cc @malfet @jianyuh @nikitaved @mruberry @walterddr @xwang233 @Lezcano

extent analysis

Fix Plan

To fix the segmentation fault caused by passing an empty tensor to torch.lu_unpack, we need to ensure that the LU_pivots tensor is not empty when calling this function.

Here are the steps to fix the issue:

  • Check if the LU_pivots tensor is empty before calling torch.lu_unpack.
  • If LU_pivots is empty, either provide a valid pivot tensor or handle this case according to your application's requirements.

Example code:

import torch

LU_data = torch.tensor([[2., 3., 1.],
                        [0.5, 1., 2.],
                        [0.25, 0.5, 1.]])

# Ensure LU_pivots is not empty
LU_pivots = torch.tensor([], dtype=torch.int32)
if LU_pivots.numel() == 0:
    # Handle the case when LU_pivots is empty
    # For example, you can raise an error or provide a default pivot tensor
    raise ValueError("LU_pivots cannot be empty")
else:
    P, L, U = torch.lu_unpack(LU_data, LU_pivots)

Verification

To verify that the fix worked, you can test the code with both empty and non-empty LU_pivots tensors. The code should handle the empty tensor case without crashing and correctly perform the LU unpack operation when LU_pivots is not empty.

Extra Tips

  • Always validate the inputs to PyTorch functions to prevent crashes and ensure the correctness of your application.
  • Consider adding error handling code to handle cases where the input tensors are invalid or empty.
  • Refer to the PyTorch documentation for the specific requirements and constraints of each function, including torch.lu_unpack.

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