cuDNN causing inconsistent test results depending on batch_size

I have encountered an odd problem. I have a trained model with many Conv1d layers. When I set the model to eval() and run the test set through, I receive different accuracies depending on the batch_size.

For example, when I run the same test data through my model all at once vs one at a time, my predictions are wildly different.

model.eval()
model.train(False)

batch_size = len(xtest)
batch_guesses = np.array([])
print("BATCH SIZE ", batch_size)
for i in range(0, len(xtest), batch_size):
    inputs = torch.Tensor(xtest[i : i + batch_size]).to(device)
    output = model(inputs)
    prediction = torch.argmax(output, dim=1)
    prediction = prediction.detach().cpu().numpy()
    batch_guesses = np.append(batch_guesses, prediction)

print("INDIVIDUAL")
batch_size = 1
single_guesses = np.array([])
for i in range(0, len(xtest), batch_size):
    inputs = torch.Tensor(xtest[i : i + batch_size]).to(device)
    output = model(inputs)
    prediction = torch.argmax(output, dim=1)
    prediction = prediction.detach().cpu().numpy()
    single_guesses = np.append(single_guesses, prediction)


# find % single_guesses and batch_guesses that are the same
print(np.sum(single_guesses == batch_guesses) / len(single_guesses))
# 1.0 with torch.backends.cudnn.enabled = False
# 0.790625 torch.backends.cudnn.enabled = True

However, I found that this was only the case when torch.backends.cudnn.enabled = True. Setting it to false caused single_guesses and batch_guesses to be identical regardless of batch size. I also found that the larger the difference between the batch sizes, the more predictions would be different, so batch size 1 and 64 had 92% similarity in comparison to a batch size of 1 and 2056’s 79% similarity.

Why does cudnn have such a great impact on classification depending on the batch size?

It seems you are comparing for equal values, which is a bad idea using floating point math.
Small numerical mismatches are expected and you should use a small threshold to compare different algorithms against each other. Here is a small example on the CPU not using cuDNN at all:

x = torch.randn(10, 10, 10)
s1 = x.sum()
s2 = x.sum(0).sum(0).sum(0)
print((s1 - s2).abs())
# tensor(7.6294e-06)
print(s1 == s2)
# tensor(False)
print(torch.allclose(s1, s2))
# True

Thank you for your prompt response!

In the example I’m comparing the argmax of the output, not the logits themselves. So it’s a comparison of integer values where == should be fine.

Ah, I see. In this case, could you post a minimal and executable code snippet to reproduce the issue as well as the output of python -m torch.utils.collect_env, please?

I believe I encountered the same issue today. Here is the minimal executable code snippet:

import torch
from torchvision.models.resnet import resnet50, ResNet50_Weights

torch.use_deterministic_algorithms(mode=True)


def test_batch_independence(device: str):
    # Init model
    model = resnet50(weights=ResNet50_Weights.IMAGENET1K_V1)
    model.eval()
    model.to(device)
    # Random input tensor
    x = torch.randn((16, 3, 224, 224)).to(device)
    y_ref = model(x).to("cpu")
    # Pass only a fraction of the same batch of data
    y_test = model(x[:4]).to("cpu")
    if torch.all(torch.eq(y_ref[:4], y_test)):
        print(f"Test passed on device {device}")
    else:
        print(f"Test failed on device {device}")
    # Make sure that the second run is identical to the first
    y_ref_2 = model(x).to("cpu")
    y_test_2 = model(x[:4]).to("cpu")
    assert torch.all(torch.eq(y_ref, y_ref_2))
    assert torch.all(torch.eq(y_test, y_test_2))

test_batch_independence("cpu")
test_batch_independence("cuda:0")

The test passes on the CPU and fails on the GPU. To be fair, the discrepancies are small but they are reproducible from on run to the next.

And here is the result of collect_envs:

Collecting environment information...
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: Ubuntu 22.04.3 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.27.5
Libc version: glibc-2.35

Python version: 3.10.12 (main, Nov 20 2023, 15:14:05) [GCC 11.4.0] (64-bit runtime)
Python platform: Linux-6.2.0-37-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.5.119
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: Quadro T2000 with Max-Q Design
Nvidia driver version: 535.129.03
cuDNN version: Could not collect
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:                      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) Xeon(R) W-10855M CPU @ 2.80GHz
CPU family:                         6
Model:                              165
Thread(s) per core:                 2
Core(s) per socket:                 6
Socket(s):                          1
Stepping:                           2
CPU max MHz:                        5100,0000
CPU min MHz:                        800,0000
BogoMIPS:                           5599.85
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 sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb invpcid_single ssbd ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi 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 pku ospke md_clear flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          192 KiB (6 instances)
L1i cache:                          192 KiB (6 instances)
L2 cache:                           1,5 MiB (6 instances)
L3 cache:                           12 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-11
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        KVM: Mitigation: VMX disabled
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
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:                Mitigation; Microcode
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.0
[pip3] torch==2.0.1
[pip3] torchaudio==2.0.2
[pip3] torchvision==0.15.2
[conda] Could not collect

Did you check the relative error and read the previous post explaining it might be expected as different algorithms could be used or is the error too large?

The error is large enough to lead to some significant changes in my final model. Naïvely, i believed that the use of torch.use_deterministic_algorithms would prevent such discrepancies. Does it mean that different algorithms are used by the backend depending on the size of batch, and that these algorithms schedule operations in a different order, leading to different rounding of floating values?

Yes, as also seen in the previously mentioned minimal example:

x = torch.randn(10, 10, 10)
s1 = x.sum()
s2 = x.sum(0).sum(0).sum(0)
print((s1 - s2).abs())
# tensor(7.6294e-06)
print(s1 == s2)
# tensor(False)
print(torch.allclose(s1, s2))
# True

That’s quite unexpected since neither result is “more correct” when compared to a wider dtype, e.g. float64.

Apologies, you are indeed correct that neither result is “more correct”. What I meant was that, from a reproducibility point of view, these slight errors are enough for me to not to get identical results between experiments depending on the size of the batch, which was something that I didn’t think possible during inference time. Thanks for your answer, I guess I’ll put a warning somewhere in my code so that users can be aware of this behavior.

Ah OK, thanks for clarifying.