Repository: pytorch
Issue: log_softmax() on CPU and GPU has expected numerical error when used with low-precision bfloat16
Labels: module: numerical-stability,module: cuda,module: cpu,triaged

### 🐛 Describe the bug

When calling `torch.nn.functional.log_softmax()` on the same tensor but on CPU and GPU device, respectively, the output are different by around 1%.  Instead, my own implementation of [Log Sum Exp method](https://stackoverflow.com/a/61570752/7800276) that manually calculates the log_softmax, gives consistent results across CPU and GPU, and matches the results from torch log_softmax() on CPU as well.

## Outputs

```bash
torch.__version__: 2.0.1+cu117
torch.cuda.get_device_name(0): Tesla V100-SXM2-32GB

tensor_cpu.shape: torch.Size([16, 1024, 8192])
tensor_cpu is initalized on CPU. cuda.memory_allocated:0.0MiB

tensor_gpu.shape: torch.Size([16, 1024, 8192])
tensor_gpu copied to GPU. cuda.memory_allocated:256.0MiB

log_probs_cpu: torch.Size([16, 1024, 8192]), device: cpu. cuda.memory_allocated:256.0MiB
log_probs_gpu: torch.Size([16, 1024, 8192]), device: cuda:0. cuda.memory_allocated:768.0MiB

          a         b  torch.allclose(a, b) torch.sum(|a - b|) torch.max(|a - b|) Mean Absolute Error
0  true_cpu  true_gpu                 False   tensor(1122304.)     tensor(0.0625)              0.836%
1  true_cpu  cust_cpu                  True         tensor(0.)         tensor(0.)              0.000%
2  cust_cpu  cust_gpu                  True         tensor(0.)         tensor(0.)              0.000%
3  true_gpu  cust_gpu                 False   tensor(1122304.)     tensor(0.0625)              0.836%
```

```bash
torch.__version__: 1.13.1+cu117
torch.cuda.get_device_name(0): NVIDIA A800-SXM4-80GB

tensor_cpu.shape: torch.Size([16, 1024, 8192])
tensor_cpu is initalized on CPU. cuda.memory_allocated:0.0MiB

tensor_gpu.shape: torch.Size([16, 1024, 8192])
tensor_gpu copied to GPU. cuda.memory_allocated:256.0MiB

log_probs_cpu: torch.Size([16, 1024, 8192]), device: cpu. cuda.memory_allocated:256.0MiB
log_probs_gpu: torch.Size([16, 1024, 8192]), device: cuda:0. cuda.memory_allocated:768.0MiB

          a         b  torch.allclose(a, b) torch.sum(|a - b|) torch.max(|a - b|) Mean Absolute Error 
0  true_cpu  true_gpu                 False   tensor(1122304.)     tensor(0.0625)              0.836%
1  true_cpu  cust_cpu                  True         tensor(0.)         tensor(0.)              0.000%
2  cust_cpu  cust_gpu                  True         tensor(0.)         tensor(0.)              0.000%
3  true_gpu  cust_gpu                 False   tensor(1122304.)     tensor(0.0625)              0.836%
```

## To Reproduce

```python
import torch
import torch.nn.functional as F

#####################
DIM_1 = 16
DIM_2 = 1024
DIM_3 = 8192
RANDOM_SEED = 1000

def customized_log_softmax(x, dim=-1):
    # Method 2: Log Sum Exp in https://stackoverflow.com/a/61570752/7800276
    maxes = torch.max(x, dim, keepdim=True)[0]
    x_exp_sum_log = torch.logsumexp(x - maxes, dim=dim, keepdim=True)
    output_log = x - maxes - x_exp_sum_log
    return output_log

###########################################################

def main():
    print(f"torch.__version__: {torch.__version__}")
    print(f"torch.cuda.get_device_name(0): {torch.cuda.get_device_name(0)}\n")

    torch.manual_seed(RANDOM_SEED)
    tensor_cpu = torch.rand([DIM_1, DIM_2, DIM_3], dtype=torch.bfloat16)
    print(f"tensor_cpu.shape: {tensor_cpu.shape}")
    print(f"tensor_cpu is initalized on CPU. cuda.memory_allocated:{torch.cuda.memory_allocated()/1024/1024:.1f}MiB\n")

    tensor_gpu = tensor_cpu.detach().clone()
    tensor_gpu = tensor_gpu.cuda()
    print(f"tensor_gpu.shape: {tensor_gpu.shape}")
    print(f"tensor_gpu copied to GPU. cuda.memory_allocated:{torch.cuda.memory_allocated()/1024/1024:.1f}MiB\n")

    log_probs_true_cpu = F.log_softmax(tensor_cpu, dim=-1)
    log_probs_cust_cpu = customized_log_softmax(tensor_cpu, dim=-1)
    print(f"log_probs_cpu: {log_probs_true_cpu.shape}, device: {log_probs_true_cpu.device}. cuda.memory_allocated:{torch.cuda.memory_allocated()/1024/1024:.1f}MiB")

    log_probs_true_gpu = F.log_softmax(tensor_gpu, dim=-1)
    log_probs_cust_gpu = customized_log_softmax(tensor_gpu, dim=-1)
    print(f"log_probs_gpu: {log_probs_true_gpu.shape}, device: {log_probs_true_gpu.device}. cuda.memory_allocated:{torch.cuda.memory_allocated()/1024/1024:.1f}MiB\n")
    try:
        import pandas as pd
        pd.set_option('display.max_columns', None)
        pandas_output = True
        data = []
    except:
        pandas_output = False
    
    for (a, b, namea, nameb) in [
        (log_probs_true_cpu, log_probs_true_gpu, "true_cpu", "true_gpu"),
        (log_probs_true_cpu, log_probs_cust_cpu, "true_cpu", "cust_cpu"),
        (log_probs_cust_cpu, log_probs_cust_gpu, "cust_cpu", "cust_gpu"),
        (log_probs_true_gpu, log_probs_cust_gpu, "true_gpu", "cust_gpu"),
    ]:
        all_close = torch.allclose(a.cpu(), b.cpu())
        diff_abs = torch.abs(a.cpu() - b.cpu())
        diff_sum = torch.sum(diff_abs).cpu()
        diff_max = torch.max(diff_abs).cpu()
        diff_avg = f"{diff_sum.float() / a.numel():.3%}"

        if pandas_output:
            data.append([namea, nameb, all_close, diff_sum.float(), diff_max.float(), diff_avg])
        else:
            print(f"{namea} vs. {nameb}: all_close={all_close}, torch.sum(|{namea}-{nameb}|)={diff_sum}, torch.max(|{namea}-{nameb}|)={diff_max}\ntorch.abs({namea}-{nameb})={diff_abs.view(-1)} {diff_abs.shape}\n")
    
    if pandas_output:
        df = pd.DataFrame(data)
        df.columns = ["a", "b", "torch.allclose(a, b)", "torch.sum(|a - b|)", "torch.max(|a - b|)", "Mean Absolute Error"]
        print(f"{df}\n")
    
if __name__ == "__main__":
    main()
```

### Versions

PyTorch version: 2.0.1+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: CentOS Linux release 7.9.2009 (Core) (x86_64)
GCC version: (GCC) 4.8.5 20150623 (Red Hat 4.8.5-44)
Clang version: Could not collect
CMake version: version 3.26.3
Libc version: glibc-2.17

Python version: 3.11.3 (main, Apr 19 2023, 23:54:32) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-3.10.0-1160.90.1.el7.x86_64-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: 11.2.152
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: Tesla V100-SXM2-32GB
GPU 1: Tesla V100-SXM2-32GB
GPU 2: Tesla V100-SXM2-32GB
GPU 3: Tesla V100-SXM2-32GB
GPU 4: Tesla V100-SXM2-32GB
GPU 5: Tesla V100-SXM2-32GB
GPU 6: Tesla V100-SXM2-32GB
GPU 7: Tesla V100-SXM2-32GB

Nvidia driver version: 470.129.06
cuDNN version: Probably one of the following:
/usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn.so.8.1.1
/usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8.1.1
/usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_adv_train.so.8.1.1
/usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8.1.1
/usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8.1.1
/usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8.1.1
/usr/local/cuda-11.2/targets/x86_64-linux/lib/libcudnn_ops_train.so.8.1.1
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
CPU(s):                48
On-line CPU(s) list:   0-47
Thread(s) per core:    2
Core(s) per socket:    12
Socket(s):             2
NUMA node(s):          2
Vendor ID:             GenuineIntel
CPU family:            6
Model:                 85
Model name:            Intel(R) Xeon(R) Gold 6146 CPU @ 3.20GHz
Stepping:              4
CPU MHz:               2516.210
CPU max MHz:           4200.0000
CPU min MHz:           1200.0000
BogoMIPS:              6400.00
Virtualization:        VT-x
L1d cache:             32K
L1i cache:             32K
L2 cache:              1024K
L3 cache:              25344K
NUMA node0 CPU(s):     0-11,24-35
NUMA node1 CPU(s):     12-23,36-47
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 aperfmperf eagerfpu pni pclmulqdq dtes64 monitor 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 epb cat_l3 cdp_l3 invpcid_single intel_ppin ssbd mba rsb_ctxsw ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid fsgsbase tsc_adjust bmi1 hle avx2 smep bmi2 erms invpcid rtm cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts pku ospke md_clear spec_ctrl intel_stibp flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] numpy==1.24.3
[pip3] torch==2.0.1
[pip3] triton==2.0.0
[conda] numpy                     1.24.3                   pypi_0    pypi
[conda] torch                     2.0.1                    pypi_0    pypi
[conda] triton                    2.0.0                    pypi_0    pypi

cc @ptrblck @jgong5 @mingfeima @XiaobingSuper @sanchitintel @ashokei @jingxu10