Repository: pytorch
Issue: Inconsistent results when training a model containing SyncBatchNorm with multiple GPUs
Labels: oncall: distributed

### 🐛 Describe the bug

I detected large inconsistencies when training a model containing a SyncBatchnorm layer with distributed settings.

In the below code, I first defined a simple model containing three layers: BatchNorm2d (later converted to SyncBatchnorm), Flatten, and Linear. I trained the model with a small batch of randomly generated inputs for one epoch. I compared the distributed training results (2 gpus) with non-distributed training results, and there's a relatively large Linf difference, i.e., 0.0008. I would expect a smaller inconsistency, e.g., less than 1e-5.

Note that below code load model's weights from file state_dict.pt and inputs from input.pkl. The two files are provided in the file [reproduction.zip](https://github.com/pytorch/pytorch/files/15069446/reproduction.zip) to reproduce the large Linf difference, i.e., 0.0008.

```
import copy
from copyreg import pickle
import os
import sys
import pickle
import numpy as np
import socket
from contextlib import closing
import multiprocessing


import torch
import torch.distributed as dist
import torch.nn as nn
from torch.nn.parallel import DistributedDataParallel as DDP

class TestModel(nn.Module):
    def __init__(self):
        super(TestModel, self).__init__()
        self.batch_norm = nn.BatchNorm2d(num_features=3, momentum=0.1, eps=0.5741792376830336, affine=True, track_running_stats=True)
        self.flatten = nn.Flatten()
        self.dense = nn.Linear(32 * 32 * 3, 10)

    def forward(self, x):
        dims = [0, 3, 2, 1]
        x = x.permute(dims)
        x = self.batch_norm(x)
        x = x.permute(dims)
        x = self.flatten(x)
        x = self.dense(x)
        x = x.view(-1, 10)
        return x

def get_free_port() -> int:
    # print('in get_free_port')
    # LT: hack forcing port
    if socket.has_ipv6:
        family = socket.AF_INET6
        address = "localhost6"
    else:
        family = socket.AF_INET
        address = "localhost4"
    with socket.socket(family, socket.SOCK_STREAM) as s:
        try:
            s.bind((address, 0))
            s.listen(0)
            with closing(s):
                return s.getsockname()[1]
        except socket.gaierror:
            if address == "localhost6":
                address = "::1"
            else:
                address = "127.0.0.1"
            s.bind((address, 0))
            s.listen(0)
            with closing(s):
                return s.getsockname()[1]
        except Exception as e:
            raise Exception(
                f"Binding failed with address {address} while getting free port {e}"
            )
    
def softmax_pred(pred):
    pred = torch.nn.functional.softmax(pred, -1)
    return pred

def copy_state_dict(
    loc,
    glob,
) -> None:
    for name, tensor in loc.items():
        name = name.replace("module.", "")
        global_tensor = glob[name]
        tensor.copy_(global_tensor)

def sharding_single_rank_test_sequential(
    rank,
    world_size,
    model,
    inputs,
    backend,
) -> None:
    dist.init_process_group(backend=backend, world_size=world_size, rank=rank)
    device = torch.device("cuda", rank)

    model = model.to(device)
    model = nn.SyncBatchNorm.convert_sync_batchnorm(model)
    
    global_model = copy.deepcopy(model)
    global_model = global_model.to(device)

    global_input_train = inputs[0][0].to(device)
    global_input_eval = inputs[1][0].to(device)
    global_label_train = inputs[0][1].to(device)
    # global_label_eval = inputs[1][1].to(device)

    local_model = copy.deepcopy(model)
    local_model = DDP(local_model, device_ids=[rank])

    # Load model state from the global model.
    copy_state_dict(local_model.state_dict(), global_model.state_dict())
    
    # Run a single training step of the sharded model.
    local_batch_size = len(global_input_train)/world_size
    start = int(local_batch_size * rank)
    end = int(local_batch_size * (rank + 1))
    local_input_train = global_input_train[start:end].to(device)
    local_input_eval = global_input_eval[start:end].to(device)
    local_label_train = global_label_train[start:end].to(device)
    # local_label_eval = global_label_eval[start:end].to(device)

    local_pred = gen_full_pred_after_one_step(local_model, local_input_train, local_label_train, local_input_eval)
    all_local_pred = []
    for _ in range(world_size):
        all_local_pred.append(torch.empty_like(local_pred))
    dist.all_gather(all_local_pred, local_pred)
    
    global_pred = gen_full_pred_after_one_step(global_model, global_input_train, global_label_train, global_input_eval)
    
    if rank == 0:
        global_pred = softmax_pred(global_pred)
        local_pred = softmax_pred(torch.cat(all_local_pred))
        print("Linf: ", torch.max(torch.abs(global_pred - local_pred)))
        sys.stdout.flush()
        torch.testing.assert_close(global_pred, local_pred)


def gen_full_pred_after_one_step(
    model,
    input_train,
    label_train,
    input_eval
) -> torch.Tensor:
    # Run a single training step of the global model.
    criterion = torch.nn.CrossEntropyLoss()
    opt = torch.optim.SGD(model.parameters(), lr=10)
    opt.zero_grad()
    model.train(True)
    outputs = model(input_train)
    loss = criterion(outputs, label_train)
    loss.backward()
    opt.step()

    # Run a forward pass of the global model.
    with torch.no_grad():
        model.train(False)
        full_pred = model(input_eval)
        return full_pred


def setUp():
    os.environ["MASTER_ADDR"] = str("localhost")
    os.environ["MASTER_PORT"] = str(get_free_port())
    os.environ["GLOO_DEVICE_TRANSPORT"] = "TCP"
    os.environ["NCCL_SOCKET_IFNAME"] = "lo"

    torch.use_deterministic_algorithms(True)
    if torch.cuda.is_available():
        torch.backends.cudnn.allow_tf32 = False
        torch.backends.cuda.matmul.allow_tf32 = False
        os.environ["CUBLAS_WORKSPACE_CONFIG"] = ":4096:8"

def run_multi_process_test(
    callable,
    world_size,
    # pyre-ignore
    **kwargs,
) -> None:
    setUp()

    ctx = multiprocessing.get_context("forkserver")
    processes = []
    for rank in range(world_size):
        kwargs["rank"] = rank
        kwargs["world_size"] = world_size
        p = ctx.Process(
            target=callable,
            kwargs=kwargs,
        )
        p.start()
        processes.append(p)
    
    for p in processes:
        p.join()


def main_test(
    backend,
    world_size,
) -> None:
    model = TestModel()
    model.load_state_dict(torch.load("state_dict.pt"))
    model = model.to("cpu")

    with open("input.pkl", 'rb') as f:
        ((train_input, train_label), (test_input, test_label)) = pickle.load(f)

    train_input = torch.tensor(train_input, dtype=torch.float32)
    train_label = torch.tensor(train_label, dtype=torch.float32)
    test_input = torch.tensor(test_input, dtype=torch.float32)
    test_label = torch.tensor(test_label, dtype=torch.float32)
    # Load test data
    inputs = ((train_input, train_label), (test_input, test_label))

    run_multi_process_test(
        callable=sharding_single_rank_test_sequential,
        world_size=world_size,
        
        model=model,
        inputs=inputs,
        backend=backend,
    )

if __name__ == "__main__":
    main_test("nccl", 2)
```

Running the above code will get the following output
```
Linf:  tensor(0.0008, device='cuda:0')
Process ForkServerProcess-1:
Traceback (most recent call last):
  File "/root/miniconda3/envs/pt22tr06/lib/python3.8/multiprocessing/process.py", line 313, in _bootstrap
    self.run()
  File "/root/miniconda3/envs/pt22tr06/lib/python3.8/multiprocessing/process.py", line 108, in run
    self._target(*self._args, **self._kwargs)
  File "/mnt/reproduce_sync_batchnorm.py", line 124, in sharding_single_rank_test_sequential
    torch.testing.assert_close(global_pred, local_pred)
  File "/root/miniconda3/envs/pt22tr06/lib/python3.8/site-packages/torch/testing/_comparison.py", line 1520, in assert_close
    raise error_metas[0].to_error(msg)
AssertionError: Tensor-likes are not close!

Mismatched elements: 2 / 240 (0.8%)
Greatest absolute difference: 0.0008089542388916016 at index (5, 6) (up to 1e-05 allowed)
Greatest relative difference: 0.002903233515098691 at index (5, 7) (up to 1.3e-06 allowed)
```

### Versions

```
Collecting environment information...
PyTorch version: 2.2.2+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.6 LTS (x86_64)
GCC version: Could not collect
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.31

Python version: 3.8.0 (default, Nov  6 2019, 21:49:08)  [GCC 7.3.0] (64-bit runtime)
Python platform: Linux-5.15.0-101-generic-x86_64-with-glibc2.10
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 2080 Ti
GPU 1: NVIDIA GeForce RTX 2080 Ti
GPU 2: NVIDIA GeForce RTX 2080 Ti
GPU 3: NVIDIA GeForce RTX 2080 Ti
GPU 4: NVIDIA GeForce RTX 2080 Ti
GPU 5: NVIDIA GeForce RTX 2080 Ti
GPU 6: NVIDIA GeForce RTX 2080 Ti
GPU 7: NVIDIA GeForce RTX 2080 Ti

Nvidia driver version: 535.161.07
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.2.1
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.2.1
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.2.1
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.2.1
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.2.1
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.2.1
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.2.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
Address sizes:                      46 bits physical, 48 bits virtual
CPU(s):                             56
On-line CPU(s) list:                0-55
Thread(s) per core:                 2
Core(s) per socket:                 14
Socket(s):                          2
NUMA node(s):                       2
Vendor ID:                          GenuineIntel
CPU family:                         6
Model:                              85
Model name:                         Intel(R) Xeon(R) Gold 5120 CPU @ 2.20GHz
Stepping:                           4
CPU MHz:                            2599.999
CPU max MHz:                        3200.0000
CPU min MHz:                        1000.0000
BogoMIPS:                           4400.00
Virtualization:                     VT-x
L1d cache:                          896 KiB
L1i cache:                          896 KiB
L2 cache:                           28 MiB
L3 cache:                           38.5 MiB
NUMA node0 CPU(s):                  0-13,28-41
NUMA node1 CPU(s):                  14-27,42-55
Vulnerability Gather data sampling: Mitigation; Microcode
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 Retbleed:             Mitigation; IBRS
Vulnerability Spec rstack overflow: Not affected
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; IBRS, IBPB conditional, STIBP conditional, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Mitigation; Clear CPU buffers; SMT vulnerable
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 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 cpuid_fault epb cat_l3 cdp_l3 invpcid_single pti ssbd mba ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad 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 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 pku ospke md_clear flush_l1d arch_capabilities

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.4
[pip3] onnx==1.16.0
[pip3] onnx2pytorch==0.4.1
[pip3] torch==2.2.2
[pip3] torchmetrics==1.0.3
[pip3] torchrec==0.6.0+cu121
[pip3] torchvision==0.17.2
[pip3] triton==2.2.0
[conda] numpy                     1.24.4                   pypi_0    pypi
[conda] onnx2pytorch              0.4.1                    pypi_0    pypi
[conda] torch                     2.2.2                    pypi_0    pypi
[conda] torchmetrics              1.0.3                    pypi_0    pypi
[conda] torchrec                  0.6.0+cu121              pypi_0    pypi
[conda] torchvision               0.17.2                   pypi_0    pypi
[conda] triton                    2.2.0                    pypi_0    pypi

```

cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu @fegin @XilunWu @wanchaol @fduwjj @wz337 @tianyu-l @wconstab @yf225 @chauhang @d4l3k