pytorch / pytorch

Tensors and Dynamic neural networks in Python with strong GPU acceleration
https://pytorch.org
Other
82.8k stars 22.32k forks source link

AoTI wrong results with mul+sum #122784

Closed Thanduriel closed 6 months ago

Thanduriel commented 6 months ago

🐛 Describe the bug

My model has an operation that can be mapped to a batched-matrix-matrix multiply. Implementing it with an element-wise product + sum over one dimension instead is much faster but produces completely wrong results in very specific circumstances.

I narrowed the problem down to a trivial case with batch size 1 and just this operation, giving the following results on GPU (see the provided code):

def bmm1(m1, m2):
    return torch.bmm(m1,m2.unsqueeze(2)).squeeze_(2)

def bmm2(m1,m2):
    return torch.sum(m1 * m2.unsqueeze(1), dim=2)

class MEVP(torch.nn.Module):
    def __init__(self):
        super(MEVP, self).__init__()

    # iMJwPSI [1,3,4], rhs [1,4]
    def forward(self, iMJwPSI, rhs):
        res1 = bmm1(iMJwPSI, rhs)
        res2 = bmm2(iMJwPSI, rhs)

        return res1, res2
AoT mul,sum reference
-1.2321 1
-0.6160 0
2.8481 0

The wrong results are observed if and only if the model exported with AoT Inductor is run in C++ with a specific matrix loaded as left-hand-side. Weirdly enough, when I export the values and construct the tensor in C++ instead of loading it, the computation is correct (see code). I tested this with different versions of PyTorch (2.2.1 release, nightly from 2024.03.26) and on different systems and the problem persists.

Error logs

No response

Minified repro

Since I was unable to reproduce the bug in pure python, with random tensors or with the same tensors but embedded in C++, both the data and a minimal C++ project are provided. To build and run:

mkdir build && cd build
cmake ..
make
mv ../iMJwPSI.pt .
./inference

mul_sum_minimal.zip

Versions

PyTorch version: 2.4.0.dev20240325+cu121 Is debug build: False CUDA used to build PyTorch: 12.1 ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64) GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0 Clang version: Could not collect CMake version: version 3.27.0 Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime) Python platform: Linux-6.5.0-26-generic-x86_64-with-glibc2.35 Is CUDA available: True CUDA runtime version: 12.4.99 CUDA_MODULE_LOADING set to: LAZY GPU models and configuration: GPU 0: NVIDIA GeForce RTX 3090 Nvidia driver version: 550.54.15 cuDNN version: Probably one of the following: /usr/lib/x86_64-linux-gnu/libcudnn.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.9.7 /usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.9.7 HIP runtime version: N/A MIOpen runtime version: N/A Is XNNPACK available: True

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): 20 On-line CPU(s) list: 0-19 Vendor ID: GenuineIntel Model name: Intel(R) Core(TM) i9-10900X CPU @ 3.70GHz CPU family: 6 Model: 85 Thread(s) per core: 2 Core(s) per socket: 10 Socket(s): 1 Stepping: 7 CPU max MHz: 4700,0000 CPU min MHz: 1200,0000 BogoMIPS: 7399.70 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 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 cdp_l3 invpcid_single ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req vnmi avx512_vnni md_clear flush_l1d arch_capabilities Virtualization: VT-x L1d cache: 320 KiB (10 instances) L1i cache: 320 KiB (10 instances) L2 cache: 10 MiB (10 instances) L3 cache: 19,3 MiB (1 instance) NUMA node(s): 1 NUMA node0 CPU(s): 0-19 Vulnerability Gather data sampling: Mitigation; Microcode Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled Vulnerability L1tf: Not affected Vulnerability Mds: Not affected Vulnerability Meltdown: Not affected Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable 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, RSB filling, PBRSB-eIBRS SW sequence Vulnerability Srbds: Not affected Vulnerability Tsx async abort: Mitigation; TSX disabled

Versions of relevant libraries: [pip3] numpy==1.26.4 [pip3] pytorch-triton==3.0.0+989adb9a29 [pip3] torch==2.4.0.dev20240325+cu121 [pip3] triton==2.2.0 [conda] blas 1.0 mkl
[conda] mkl 2021.4.0 h06a4308_640
[conda] mkl-service 2.4.0 py39h7f8727e_0
[conda] mkl_fft 1.3.1 py39hd3c417c_0
[conda] mkl_random 1.2.2 py39h51133e4_0
[conda] numpy 1.21.5 py39he7a7128_1
[conda] numpy-base 1.21.5 py39hf524024_1
[conda] numpydoc 1.2 pyhd3eb1b0_0

cc @ezyang @msaroufim @bdhirsh @anijain2305 @zou3519 @chauhang @desertfire @chenyang78

desertfire commented 6 months ago

Your iMJwPSI.pt is probably not the same as you expected. Here is what I got after adding a little print code,

iMJwPSI.size(): [262144, 3, 4]
iMJwPSIAlt.size(): [1, 3, 4]
Thanduriel commented 6 months ago

Yes, iMJwPSI.pt comes from the actual model. However, if you look into the code, I take out just the first element as a slice, copy it and compare it to the alt matrix to ensure that they are in fact exactly the same before giving them to the test model. I also checked all the options of both tensors but for me there is no discernible difference and yet the results differ.

desertfire commented 6 months ago

Looks like there are stride differences,

iMJwPSI.strides(): [12, 1, 3]
iMJwPSIAlt.strides(): [12, 4, 1]

because the original iMJwPSI has that [12, 1, 3] strides. Calling .contiguous() will produce the correct result.

desertfire commented 6 months ago

@chenyang78 recently added an input sizes/strides checking at https://github.com/pytorch/pytorch/pull/122047, but it is only enabled in a debug build and in the ABI-compatible mode. I have verified if I build with AOT_INDUCTOR_DEBUG_COMPILE=1 TORCHINDUCTOR_ABI_COMPATIBLE=1 make, it will throw a runtime error.

chauhang commented 6 months ago

@desertfire Should we start compiling with above for the main builds as well?

cc: @atalman

desertfire commented 6 months ago

@desertfire Should we start compiling with above for the main builds as well?

cc: @atalman

You mean making it the default behavior? Yes, but after fixing some remaining issues.

Thanduriel commented 6 months ago

Thanks a lot. There is indeed a transpose operation during assembly of the matrix that introduces a different memory format, which I did not consider. Now the whole model works fine. A runtime check would, of course, be appreciated for the future.