Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

RuntimeError when using Adam(fused=True) with torch.compile #126585

Open
mitchellgoffpc opened this issue May 17, 2024 · 3 comments
Open

RuntimeError when using Adam(fused=True) with torch.compile #126585

mitchellgoffpc opened this issue May 17, 2024 · 3 comments
Labels
module: inductor module: optimizer Related to torch.optim oncall: pt2 triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module

Comments

@mitchellgoffpc
Copy link

mitchellgoffpc commented May 17, 2024

馃悰 Describe the bug

When using Adam(fused=True) in combination with torch.compile and certain model architectures, torch seems to consistently raise the following error during the call to optimizer.step:

RuntimeError: params, grads, exp_avgs, and exp_avg_sqs must have same dtype, device, and layout

I wrote a short script to reproduce the error and tested it on several machines with different nvidia GPUs and different versions of pytorch between 2.1.0 and 2.3, and also on google colab with the Tesla T4 gpus. In my testing, the exception seemed to trigger whenever the model contains three or more 1x1 convs with in_channels and out_channels both greater than 64. There may be other ways to trigger it as well, but I so far I haven't been able to reproduce the error with any kernel size other than 1.

import torch
import torch.nn as nn
import torch.nn.functional as F

dim = 128
conv_sizes = [
    (3, dim),
    (dim, dim),
    (dim, dim),
    (dim, dim),
]

class ConvNet(nn.Module):
    def __init__(self):
        super().__init__()
        self.layers = nn.ModuleList([])
        for in_channels, out_channels in conv_sizes:
            self.layers.append(nn.Conv2d(in_channels=in_channels, out_channels=out_channels, kernel_size=1))

    def forward(self, x):
        for layer in self.layers:
            x = layer(x)
        return x

# Create random input-output pairs
num_samples = 4
inputs = torch.randn(num_samples, 3, 256, 256)
targets = torch.randint(0, 1024, (num_samples,))

# Create the model
device = torch.device("cuda:0")
model = ConvNet().to(device)
model = torch.compile(model)
optimizer = torch.optim.Adam(model.parameters(), lr=0.001, fused=True)

# Training
optimizer.zero_grad()
outputs = model(inputs.to(device))
loss = F.cross_entropy(outputs.view(num_samples, -1), targets.to(device))
loss.backward()
optimizer.step()

Versions

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

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: 10.0.0-4ubuntu1
CMake version: version 3.27.0
Libc version: glibc-2.31

Python version: 3.11.4 (main, Jul 25 2023, 17:17:47) [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.15.0-105-generic-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: 12.1.105
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration:
GPU 0: NVIDIA GeForce RTX 4090
GPU 1: NVIDIA GeForce RTX 4090
GPU 2: NVIDIA GeForce RTX 4090
GPU 3: NVIDIA GeForce RTX 4090
GPU 4: NVIDIA GeForce RTX 4090
GPU 5: NVIDIA GeForce RTX 4090
GPU 6: NVIDIA GeForce RTX 4090
GPU 7: NVIDIA GeForce RTX 4090

Nvidia driver version: 530.41.03
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_precompiled.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_engines_runtime_compiled.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_graph.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_heuristic.so.9.1.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops.so.9.1.0
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
Byte Order: Little Endian
Address sizes: 52 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: AuthenticAMD
CPU family: 25
Model: 17
Model name: AMD EPYC 9124 16-Core Processor
Stepping: 1
Frequency boost: enabled
CPU MHz: 2077.508
CPU max MHz: 3711.9141
CPU min MHz: 1500.0000
BogoMIPS: 6000.13
Virtualization: AMD-V
L1d cache: 1 MiB
L1i cache: 1 MiB
L2 cache: 32 MiB
L3 cache: 128 MiB
NUMA node0 CPU(s): 0-15,32-47
NUMA node1 CPU(s): 16-31,48-63
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 Retbleed: Not affected
Vulnerability Spec rstack overflow: Mitigation; safe RET
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; Retpolines, IBPB conditional, IBRS_FW, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
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 mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 invpcid_single hw_pstate ssbd mba ibrs ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 erms invpcid cqm rdt_a avx512f avx512dq rdseed adx smap avx512ifma clflushopt clwb avx512cd sha_ni avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local avx512_bf16 clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin cppc arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl avx512vbmi umip pku ospke avx512_vbmi2 gfni vaes vpclmulqdq avx512_vnni avx512_bitalg avx512_vpopcntdq la57 rdpid overflow_recov succor smca fsrm flush_l1d

Versions of relevant libraries:
[pip3] msgpack-numpy==0.4.8
[pip3] mypy==1.10.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] onnx==1.16.0
[pip3] onnx2torch==1.5.14
[pip3] onnxoptimizer==0.3.13
[pip3] onnxruntime-gpu==1.17.1
[pip3] torch==2.3.0
[pip3] torchsummary==1.5.1
[pip3] torchvision==0.18.0
[pip3] triton==2.3.0
[pip3] tritonclient==2.33.0

cc @vincentqb @jbschlosser @albanD @janeyx99 @crcrpar @ezyang @msaroufim @bdhirsh @anijain2305 @chauhang @voznesenskym @penguinwu @EikanWang @jgong5 @Guobing-Chen @XiaobingSuper @zhuhaozhe @blzheng @wenzhe-nrv @jiayisunx @peterbell10 @ipiszy @yf225 @chenyang78 @kadeng @muchulee8 @ColinPeppler @amjames @desertfire @mlazos

@mikaylagawarecki mikaylagawarecki added module: pt2 optimizer Relating to torch.compile'd optim oncall: pt2 labels May 20, 2024
@janeyx99 janeyx99 added module: optimizer Related to torch.optim and removed module: pt2 optimizer Relating to torch.compile'd optim labels May 20, 2024
@janeyx99
Copy link
Contributor

Could be related to #110758

@xmfan
Copy link
Member

xmfan commented May 20, 2024

works on aot_eager backend, looks like a stride mismatch?

{(1,), (3, 1, 1, 1), (128, 1, 1, 1)}  # aot_eager
{(1,), (3, 1, 3, 3), (128, 1, 128, 128), (128, 1, 1, 1)}  # inductor
diff --git a/torch/optim/adam.py b/torch/optim/adam.py
index fba4b2027b0..f7f13029cef 100644
--- a/torch/optim/adam.py
+++ b/torch/optim/adam.py
@@ -672,6 +672,13 @@ def _fused_adam(
             lr_dict[device] = lr.to(device=device, non_blocking=True)  # type: ignore[union-attr]
             lr = lr_dict[device]
         torch._foreach_add_(device_state_steps, 1)
+
+        strides = set()
+        for l in [device_params, device_grads, device_exp_avgs, device_exp_avg_sqs]:
+            for x in l:
+                strides.add(x.stride())
+        breakpoint()
+
         torch._fused_adam_(
             device_params,
             device_grads,

@xmfan xmfan added the triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module label May 20, 2024
@mlazos
Copy link
Contributor

mlazos commented May 20, 2024

@shunting314 isnt there a stride optimization in inductor? Iirc there was a similar issue with distributed

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
module: inductor module: optimizer Related to torch.optim oncall: pt2 triaged This issue has been looked at a team member, and triaged and prioritized into an appropriate module
Projects
None yet
Development

No branches or pull requests

5 participants