PyTorch 2.0.0 encountered CUDA error: an illegal memory access was encountered
Labels: module: cuda, triaged, module: multithreading

### 🐛 Describe the bug

Running PyTorch 2.0.0 encountered CUDA error: an illegal memory access was encountered.

We wrote a [benchmark](https://github.com/deepjavalibrary/djl-serving/tree/master/benchmark) tool to use pytorch to run inference (See the commands below on how to run).

Specifically, this benchmark tool uses libtorch. And we use JNI to use with our Java program.

It worked with multi-threading. We were having no problems with previous Pytorch version. Since recently upgrading to 2.0.0, using libtorch 2.0.0-cu118, we start having error with multi-threaded inference, it only fail when using 20+ threads.

Steps to reproduce:

1) Run in docker:

```
docker run -it --runtime=nvidia --rm nvidia/cuda:11.8.0-cudnn8-devel-ubuntu20.04 /bin/bash
```

2) Inside docker:

```
apt-get update \
        && DEBIAN_FRONTEND=noninteractive apt-get install -y  \
        openjdk-11-jdk-headless \
        locales \
        git \
        curl

git clone https://github.com/deepjavalibrary/djl-serving.git
cd djl-serving

export PYTORCH_VERSION=2.0.0
export PYTORCH_NVFUSER_DISABLE=fallback
export PYTORCH_JIT_USE_NNC_NOT_NVFUSER=1
./gradlew benchmark '--args=-e PyTorch -t 20 -c 1200 -s 1,3,224,224 -u djl://ai.djl.pytorch/resnet/0.0.1/traced_resnet18'
```

Error message:

```
root@fc40d69fadbf:/djl-serving# export PYTORCH_VERSION=2.0.0
root@fc40d69fadbf:/djl-serving# export PYTORCH_NVFUSER_DISABLE=fallback
root@fc40d69fadbf:/djl-serving# export PYTORCH_JIT_USE_NNC_NOT_NVFUSER=1
root@fc40d69fadbf:/djl-serving# ./gradlew benchmark '--args=-e PyTorch -t 20 -c 1200 -s 1,3,224,224 -u djl://ai.djl.pytorch/resnet/0.0.1/traced_resnet18'


> Task :benchmark:benchmark
[WARN ] - Override PyTorch version: 2.0.0.
[INFO ] - PyTorch graph executor optimizer is enabled, this may impact your inference latency and throughput. See: https://docs.djl.ai/docs/development/inference_performance_optimization.html#graph-executor-optimization
[INFO ] - Number of inter-op threads is 1
[INFO ] - Number of intra-op threads is 1
[INFO ] - Load PyTorch (2.0.0) in 0.046 ms.
[INFO ] - Running MultithreadedBenchmark on: [gpu(0)].
[INFO ] - Multithreading inference with 20 threads.
Loading:     100% |========================================|
[INFO ] - Model traced_resnet18 loaded in: 2015.853 ms.
[INFO ] - Warmup with 2 iteration ...
[INFO ] - Warmup latency, min: 4.081 ms, max: 1631.479 ms
[ERROR] - 
java.util.concurrent.ExecutionException: ai.djl.translate.TranslateException: ai.djl.engine.EngineException: CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

        at java.util.concurrent.FutureTask.report(FutureTask.java:122) ~[?:?]
        at java.util.concurrent.FutureTask.get(FutureTask.java:191) ~[?:?]
        at ai.djl.benchmark.MultithreadedBenchmark.predict(MultithreadedBenchmark.java:110) [main/:?]
        at ai.djl.benchmark.AbstractBenchmark.runBenchmark(AbstractBenchmark.java:125) [main/:?]
        at ai.djl.benchmark.Benchmark.main(Benchmark.java:56) [main/:?]
Caused by: ai.djl.translate.TranslateException: ai.djl.engine.EngineException: CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

        at ai.djl.inference.Predictor.batchPredict(Predictor.java:191) ~[api-0.22.1-SNAPSHOT.jar:?]
        at ai.djl.inference.Predictor.predict(Predictor.java:128) ~[api-0.22.1-SNAPSHOT.jar:?]
        at ai.djl.benchmark.MultithreadedBenchmark$PredictorCallable.call(MultithreadedBenchmark.java:179) ~[main/:?]
        at ai.djl.benchmark.MultithreadedBenchmark$PredictorCallable.call(MultithreadedBenchmark.java:140) ~[main/:?]
        at java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[?:?]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[?:?]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[?:?]
        at java.lang.Thread.run(Thread.java:829) ~[?:?]
Caused by: ai.djl.engine.EngineException: CUDA error: an illegal memory access was encountered
CUDA kernel errors might be asynchronously reported at some other API call, so the stacktrace below might be incorrect.
For debugging consider passing CUDA_LAUNCH_BLOCKING=1.
Compile with `TORCH_USE_CUDA_DSA` to enable device-side assertions.

        at ai.djl.pytorch.jni.PyTorchLibrary.torchTo(Native Method) ~[pytorch-engine-0.22.1-SNAPSHOT.jar:?]
        at ai.djl.pytorch.jni.JniUtils.to(JniUtils.java:324) ~[pytorch-engine-0.22.1-SNAPSHOT.jar:?]
        at ai.djl.pytorch.engine.PtNDArray.toDevice(PtNDArray.java:165) ~[pytorch-engine-0.22.1-SNAPSHOT.jar:?]
        at ai.djl.pytorch.jni.JniUtils.getByteBuffer(JniUtils.java:1635) ~[pytorch-engine-0.22.1-SNAPSHOT.jar:?]
        at ai.djl.pytorch.engine.PtNDArray.toByteBuffer(PtNDArray.java:221) ~[pytorch-engine-0.22.1-SNAPSHOT.jar:?]
        at ai.djl.benchmark.AbstractBenchmark$BenchmarkTranslator.processOutput(AbstractBenchmark.java:316) ~[main/:?]
        at ai.djl.benchmark.AbstractBenchmark$BenchmarkTranslator.processOutput(AbstractBenchmark.java:293) ~[main/:?]
        at ai.djl.inference.Predictor.batchPredict(Predictor.java:172) ~[api-0.22.1-SNAPSHOT.jar:?]
        at ai.djl.inference.Predictor.predict(Predictor.java:128) ~[api-0.22.1-SNAPSHOT.jar:?]
        at ai.djl.benchmark.MultithreadedBenchmark$PredictorCallable.call(MultithreadedBenchmark.java:179) ~[main/:?]
        at ai.djl.benchmark.MultithreadedBenchmark$PredictorCallable.call(MultithreadedBenchmark.java:140) ~[main/:?]
        at java.util.concurrent.FutureTask.run(FutureTask.java:264) ~[?:?]
        at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128) ~[?:?]
        at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628) ~[?:?]
        at java.lang.Thread.run(Thread.java:829) ~[?:?]
[ERROR] - Only 0/20 threads finished.

> Task :benchmark:benchmark FAILED
```

### Versions

Collecting environment information...
PyTorch version: N/A
Is debug build: N/A
CUDA used to build PyTorch: N/A
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.1) 9.4.0
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.31

Python version: 3.8.10 (default, Mar 13 2023, 10:26:41)  [GCC 9.4.0] (64-bit runtime)
Python platform: Linux-5.4.0-1081-aws-x86_64-with-glibc2.29
Is CUDA available: N/A
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: N/A
GPU models and configuration: GPU 0: Tesla T4
Nvidia driver version: 510.47.03
cuDNN version: Probably one of the following:
/usr/lib/x86_64-linux-gnu/libcudnn.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_adv_train.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_cnn_train.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_infer.so.8.7.0
/usr/lib/x86_64-linux-gnu/libcudnn_ops_train.so.8.7.0
HIP runtime version: N/A
MIOpen runtime version: N/A
Is XNNPACK available: N/A

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):                          8
On-line CPU(s) list:             0-7
Thread(s) per core:              2
Core(s) per socket:              4
Socket(s):                       1
NUMA node(s):                    1
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) Platinum 8259CL CPU @ 2.50GHz
Stepping:                        7
CPU MHz:                         3099.937
BogoMIPS:                        4999.99
Hypervisor vendor:               KVM
Virtualization type:             full
L1d cache:                       128 KiB
L1i cache:                       128 KiB
L2 cache:                        4 MiB
L3 cache:                        35.8 MiB
NUMA node0 CPU(s):               0-7
Vulnerability Itlb multihit:     KVM: Vulnerable
Vulnerability L1tf:              Mitigation; PTE Inversion
Vulnerability Mds:               Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Meltdown:          Mitigation; PTI
Vulnerability Mmio stale data:   Vulnerable: Clear CPU buffers attempted, no microcode; SMT Host state unknown
Vulnerability Spec store bypass: Vulnerable
Vulnerability Spectre v1:        Mitigation; usercopy/swapgs barriers and __user pointer sanitization
Vulnerability Spectre v2:        Mitigation; Retpolines, STIBP disabled, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ss ht syscall nx pdpe1gb rdtscp lm constant_tsc rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq ssse3 fma cx16 pcid sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand hypervisor lahf_lm abm 3dnowprefetch invpcid_single pti fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid mpx avx512f avx512dq rdseed adx smap clflushopt clwb avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves ida arat pku ospke avx512_vnni

Versions of relevant libraries:
[pip3] No relevant packages
[conda] Could not collect

cc @ngimel