Repository: pytorch
Issue: ❓Different results between normal batching and `vmap` while using lower precision (e.g., bfloat16)
Labels: module: numerical-stability,triaged,module: vmap,module: functorch

### 🐛 Describe the bug

## Description

Hi there,
I would like to get per-sample gradients (application: transformer classifier for text). in a preliminary test, I noticed that when computing the losses in the various modes:

1. batched (typical torch)
2. manually batched
3. vmap batched

I get different results when running with lower precision. When computing in higher precision, 32 or 64, the differences shrink and disappear altogether, respectively. Is this expected? Can it be avoided?

Also, I noticed that the the `grad_fn` differ between 1 and 3. Specifically, in normal batched mode I get `NllLossBackward0` while with vmap I get `DivBackward0`. Would be great to understand better why vmap returns this "Div".

Below, I report a snippet of the code that I am using. Thank you very much in advance for your attention.




```python
# ===================
# Load model and data
# ===================
# unpack inputs
data_loader = ...  # classification dataset with "input_ids", "attention_mask", and "labels"
batch = next(iter(data_loader))   # returns a dict for this example
ids, attmask, y = batch["input_ids"], batch["attention_mask"], batch["labels"]

# load in bfloat16
model_instance = ... # any `AutoModelForSequenceClassification`

# passing embeddings directly instead of "input_ids" as I wanted to ultimately compute
# grads with respect to embeddings; results does not change if I pass "input_ids"
x = model_instance.get_input_embeddings()(ids) 


# ============================
# Test 1. typical forward pass
# ============================
logits = model_instance(inputs_embeds=x, attention_mask=attmask).logits
batched_losses = torch.nn.functional.cross_entropy(logits, y, reduction="none")


# ============================================================================
# Test 2. manually batched (super inefficient, this is for debugging purposes)
# ============================================================================
# note that we need to add the batch dimension with `.unsqueeze(0)` because transformers expects it
def compute_loss(x: Tensor, attmask: Tensor, y: Tensor) -> Tensor:
    logits = model_instance(inputs_embeds=x.unsqueeze(0), attention_mask=attmask.unsqueeze(0)).logits
    return torch.nn.functional.cross_entropy(logits, y.unsqueeze(0))

manual_losses = torch.tensor([compute_loss(x[d], attmask[d], y[d])[0] for d in range(x.size(0))])


# ================
# Test 3. use vmap
# ================
vmaped_losses = vmap(compute_loss, in_dims=(0, 0, 0))(x, attmask, y)


# Results: `batched_losses == manual_losses` but `!= vmaped_losses`
```


### Versions

## Env info (same issue with torch 2.2.*)

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 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.26.4
Libc version: glibc-2.35

Python version: 3.10.13 (main, Sep 11 2023, 13:44:35) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-6.2.0-36-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.2.140
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA A100 80GB PCIe
Nvidia driver version: 550.54.14
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):                             8
On-line CPU(s) list:                0-7
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Silver 4210R CPU @ 2.40GHz
CPU family:                         6
Model:                              85
Thread(s) per core:                 1
Core(s) per socket:                 1
Socket(s):                          8
Stepping:                           7
BogoMIPS:                           4800.14
Flags:                              fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush acpi mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl cpuid tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c hypervisor lahf_lm abm 3dnowprefetch cpuid_fault invpcid_single intel_ppin ssbd ibrs ibpb stibp ibrs_enhanced fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid adx smap clflushopt xsaveopt xsavec xgetbv1 xsaves pku ospke md_clear flush_l1d arch_capabilities
Hypervisor vendor:                  Xen
Virtualisation type:                full
L1d cache:                          256 KiB (8 instances)
L1i cache:                          256 KiB (8 instances)
L2 cache:                           8 MiB (8 instances)
L3 cache:                           110 MiB (8 instances)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-7
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        KVM: Mitigation: VMX unsupported
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT Host state unknown
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 IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] flake8==7.0.0
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.4
[pip3] pytorch-lightning==2.2.1
[pip3] pytorch-pretrained-bert==0.6.2
[pip3] pytorch-ranger==0.1.1
[pip3] torch==2.3.0
[pip3] torch-optimizer==0.3.0
[pip3] torch-tb-profiler==0.4.3
[pip3] torchmetrics==1.3.2
[pip3] triton==2.3.0
[conda] numpy                     1.26.4                   pypi_0    pypi
[conda] pytorch-lightning         2.2.1                    pypi_0    pypi
[conda] pytorch-ranger            0.1.1                    pypi_0    pypi
[conda] torch                     2.3.0                    pypi_0    pypi
[conda] torch-optimizer           0.3.0                    pypi_0    pypi
[conda] torch-tb-profiler         0.4.3                    pypi_0    pypi
[conda] torchfix                  0.1.1                    pypi_0    pypi
[conda] torchmetrics              1.3.2                    pypi_0    pypi
[conda] triton                    2.3.0                    pypi_0    pypi

cc @zou3519 @Chillee @samdow @kshitij12345 @janeyx99