pytorch / pytorch/pytorch

vmap of autograd.grad fails on the output of model run on AMP

Open
#184,890 1 comment 0 reactions 0 assignees View on GitHub
bot-triaged has workaround module: amp (automated mixed precision) module: autograd module: functorch module: norms and normalization module: vmap triaged
Dominant language
Python
Stars
103k
Forks
29.5k
PR merge metrics
PR metrics pending

Description

### 🐛 Describe the bug

When running with automatic mixed precision (`torch.autocast`) a model that contains a normalization layer (all kinds of `BatchNorm`, `InstanceNorm`, `LayerNorm` and `GroupNorm`), a vmapped call to `torch.autograd.grad` fails.

```python
import torch
from torch import nn

model = nn.Sequential(nn.Linear(4, 4), nn.BatchNorm1d(4), nn.Linear(4, 1))
with torch.autocast("cpu", dtype=torch.float16):
output = model(torch.randn(8, 4)).squeeze()

def get_vjp(v: torch.Tensor) -> torch.Tensor:
return torch.autograd.grad(output, list(model.parameters()), grad_outputs=v)[0]

torch.vmap(get_vjp)(torch.eye(8))
```

Gives the error: `RuntimeError: expected scalar type Half but found Float`

Full stack trace

```
Traceback (most recent call last):
File "/home/valerian/Documents/Repos/TorchJD/tests/unit/autojac/test_torch_bug.py", line 9, in
torch.vmap(get_vjp)(torch.eye(8))
~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^
File "/home/valerian/Documents/Repos/TorchJD/.venv/lib/python3.14/site-packages/torch/_functorch/apis.py", line 220, in wrapped
return vmap_impl(
# pyrefly: ignore[bad-argument-type]
...<6 lines>...
**kwargs,
)
File "/home/valerian/Documents/Repos/TorchJD/.venv/lib/python3.14/site-packages/torch/_functorch/vmap.py", line 316, in vmap_impl
return _flat_vmap(
func,
...<6 lines>...
**kwargs,
)
File "/home/valerian/Documents/Repos/TorchJD/.venv/lib/python3.14/site-packages/torch/_functorch/vmap.py", line 507, in _flat_vmap
batched_outputs = func(*batched_inputs, **kwargs)
File "/home/valerian/Documents/Repos/TorchJD/tests/unit/autojac/test_torch_bug.py", line 8, in get_vjp
return torch.autograd.grad(output, list(model.parameters()), grad_outputs=v)[0]
~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
File "/home/valerian/Documents/Repos/TorchJD/.venv/lib/python3.14/site-packages/torch/autograd/__init__.py", line 530, in grad
result = _engine_run_backward(
outputs,
...<5 lines>...
accumulate_grad=False,
)
File "/home/valerian/Documents/Repos/TorchJD/.venv/lib/python3.14/site-packages/torch/autograd/graph.py", line 882, in _engine_run_backward
return Variable._execution_engine.run_backward( # Calls into the C++ engine to run the backward pass
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
t_outputs, *args, **kwargs
^^^^^^^^^^^^^^^^^^^^^^^^^^
) # Calls into the C++ engine to run the backward pass
^
RuntimeError: expected scalar type Half but found Float
```

Note that the bug happens regardless of the device (I tested "cpu" and "cuda"), of the autocast dtype (I tested `torch.float16` and `torch.bfloat16`). I could only make the bug happen when the model contains some normalization layer.

Also note that the bug does not happen if instead of vmapping manually, we use the `is_grads_batched` param of `torch.autograd.grad`:
```python
import torch
from torch import nn

model = nn.Sequential(nn.Linear(4, 4), nn.BatchNorm1d(4), nn.Linear(4, 1))

with torch.autocast("cpu", dtype=torch.float16):
output = model(torch.randn(8, 4)).squeeze()

torch.autograd.grad(output, list(model.parameters()), grad_outputs=torch.eye(8), is_grads_batched=True)
```
works fine.

I would expect both approaches to work similarly.

I think this issue is quite important because normalization layers and autocast are all over the place, and vmapping autograd is currently the main way to compute jacobians efficiently (at least that's what we use in [TorchJD](https://github.com/SimplexLab/TorchJD)).

Using the first approach is also the only way to specify the `chunk_size` of `torch.vmap`, which gives some control on the speed vs memory tradeoff of using `torch.vmap`.

### Versions

My full environment

Collecting environment information...
PyTorch version: 2.12.0+cu126
Is debug build: False
CUDA used to build PyTorch: 12.6
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.5 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04.3) 11.4.0
Clang version: 14.0.0-1ubuntu1.1
CMake version: Could not collect
Libc version: glibc-2.35

Python version: 3.14.0 (main, Nov 19 2025, 22:48:15) [Clang 21.1.4 ] (64-bit runtime)
Python platform: Linux-6.8.0-117-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.6.20
CUDA_MODULE_LOADING set to:
GPU models and configuration: GPU 0: NVIDIA GeForce GTX 1080
Nvidia driver version: 580.159.03
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): 12
On-line CPU(s) list: 0-11
Vendor ID: GenuineIntel
Model name: Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
CPU family: 6
Model: 158
Thread(s) per core: 2
Core(s) per socket: 6
Socket(s): 1
Stepping: 10
CPU max MHz: 4100,0000
CPU min MHz: 800,0000
BogoMIPS: 4399.99
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 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb pti ssbd ibrs ibpb stibp tpr_shadow flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx rdseed adx smap clflushopt intel_pt xsaveopt xsavec xgetbv1 xsaves dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp vnmi md_clear flush_l1d arch_capabilities ibpb_exit_to_user
Virtualization: VT-x
L1d cache: 192 KiB (6 instances)
L1i cache: 192 KiB (6 instances)
L2 cache: 1,5 MiB (6 instances)
L3 cache: 9 MiB (1 instance)
NUMA node(s): 1
NUMA node0 CPU(s): 0-11
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Indirect target selection: Not affected
Vulnerability Itlb multihit: KVM: Mitigation: VMX disabled
Vulnerability L1tf: Mitigation; PTE Inversion; VMX conditional cache flushes, SMT vulnerable
Vulnerability Mds: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Meltdown: Mitigation; PTI
Vulnerability Mmio stale data: Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Reg file data sampling: Not affected
Vulnerability Retbleed: Mitigation; 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; IBRS; IBPB conditional; STIBP conditional; RSB filling; PBRSB-eIBRS Not affected; BHI Not affected
Vulnerability Srbds: Mitigation; Microcode
Vulnerability Tsa: Not affected
Vulnerability Tsx async abort: Not affected
Vulnerability Vmscape: Mitigation; IBPB before exit to userspace

Versions of relevant libraries:
[pip3] Could not collect
[conda] Could not collect

cc @ezyang @albanD @gqchen @nikitaved @soulitzer @Varal7 @bobrenjc93 @zou3519 @mcarilli @ptrblck @leslie-fang-intel @jgong5 @Chillee @samdow @kshitij12345

Contributor guide

Open the contributing guide

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.