Repository: pytorch
Issue:  Segmentation fault (core dumped) during Torch finetuning (at random step)
Labels: needs reproduction,module: crash,triaged

### 🐛 Describe the bug

I’m encountering a problem while running a finetune script for my FlanT5(-large) model. The script crashes with the message Segmentation fault (core dumped) after a few (thousand) steps. The error seems to occur randomly, sometimes within a few minutes and sometimes it takes around 40 minutes.

I initially attempted to use the stable version of PyTorch, but based on advice from @ptrblck, I decided to upgrade to the nightly version. Unfortunately, neither option resolved my issue, but the nightly version did provide a more detailed stack trace, which is shown below.

My imports:

```python
import torch
import torch.nn as nn
from tqdm import tqdm
from pathlib import Path
from collections import OrderedDict
from torch.utils.data import DataLoader, Dataset
from torch.optim import AdamW
from transformers import get_linear_schedule_with_warmup
from transformers import AutoModelForSeq2SeqLM, AutoTokenizer
from tensorboardX import SummaryWriter

from transformers.optimization import Adafactor
from rouge import Rouge

import re
import os
import glob
import torch
import random
import logging
import numpy as np
import json
```

Some snippets from my training loop:

```python
        epoch += 1

        ### Training
        model.train()

        with torch.enable_grad(), tqdm(total=num_train) as progress_bar:
            for batch_num, batch in enumerate(train_loader):
                real_batch_size = len(batch["source_ids"])

                loss, logits = forward(model, device, batch)
        
                loss = loss / k_gradient_accumulation_steps
                loss = loss.mean()
                
                loss.backward()
                loss_val = loss.item() * k_gradient_accumulation_steps  # get the item since loss is a tensor
                
                if ((batch_num + 1) % k_gradient_accumulation_steps == 0) or (batch_num + 1 == len(train_loader)):

                    # Backward
                    nn.utils.clip_grad_norm_(model.parameters(), k_max_grad_norm)
                    optimizer.step()
                    scheduler.step()
                    
                    optimizer.zero_grad()
                    (...)
```

With the following forward function:

```python
def forward(model, device, batch):
    src_ids = batch["source_ids"].to(device, dtype=torch.long)
    src_mask = batch["source_mask"].to(device, dtype=torch.long)
    tgt_ids = batch["target_ids"].to(device, dtype=torch.long)

    tgt_ids[tgt_ids[:, :] == 0] = -100
    label_ids = tgt_ids.to(device)

    out_dict = model(src_ids, attention_mask=src_mask, labels=label_ids, return_dict=True)
    loss, logits = out_dict['loss'], out_dict['logits']
    return loss, logits
```

Let me know if the provided information is insufficient. In that case I can try to create a simple application. 

```
stacktrace
Thread 1 "python3" received signal SIGSEGV, Segmentation fault.
__GI__dl_find_object (pc1=0x7ffff6706058 <_Unwind_RaiseException+72>, result=0x7fffffffb8c8) at ./elf/dl-find_object.c:442
442     ./elf/dl-find_object.c: No such file or directory.
(gdb) bt
#0  __GI__dl_find_object (pc1=0x7ffff6706058 <_Unwind_RaiseException+72>, result=0x7fffffffb8c8) at ./elf/dl-find_object.c:442
#1  0x00007ffff67080f6 in _Unwind_Find_FDE () from /lib/x86_64-linux-gnu/libgcc_s.so.1
#2  0x00007ffff6704833 in ?? () from /lib/x86_64-linux-gnu/libgcc_s.so.1
#3  0x00007ffff6705ad0 in ?? () from /lib/x86_64-linux-gnu/libgcc_s.so.1
#4  0x00007ffff6706059 in _Unwind_RaiseException () from /lib/x86_64-linux-gnu/libgcc_s.so.1
#5  0x00007fffd88ae50b in __cxa_throw () from /lib/x86_64-linux-gnu/libstdc++.so.6
#6  0x00007fffd88a538a in std::__throw_logic_error(char const*) () from /lib/x86_64-linux-gnu/libstdc++.so.6
#7  0x00007fffd88f66b1 in char* std::string::_S_construct<char const*>(char const*, char const*, std::allocator<char> const&, std::forward_iterator_tag) ()
   from /lib/x86_64-linux-gnu/libstdc++.so.6
#8  0x00007fffd88f6b14 in std::basic_string<char, std::char_traits<char>, std::allocator<char> >::basic_string(char const*, std::allocator<char> const&) ()
   from /lib/x86_64-linux-gnu/libstdc++.so.6
#9  0x00007fffbde17b03 in torch::Library::_parseNameForLib(char const*) const () from /home/ruben/.local/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so
#10 0x00007fffbde1df85 in torch::Library::_impl(char const*, torch::CppFunction&&, torch::_RegisterOrVerify) & ()
   from /home/ruben/.local/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so
--Type <RET> for more, q to quit, c to continue without paging--
#11 0x00007fffbdb6c3e1 in at::native::TORCH_LIBRARY_IMPL_init_aten_Conjugate_3(torch::Library&) ()
   from /home/ruben/.local/lib/python3.10/site-packages/torch/lib/libtorch_cpu.so
#12 0x0000555614ecd120 in ?? ()
#13 0x0000000000000000 in ?? ()
````

Originates from https://discuss.pytorch.org/t/segmentation-fault-core-dumped-during-torch-finetuning-on-new-setup/174570

### Versions

ollecting environment information...
PyTorch version: 2.1.0.dev20230313+cu117
Is debug build: False
CUDA used to build PyTorch: 11.7
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.2 LTS (x86_64)
GCC version: (Ubuntu 11.3.0-1ubuntu1~22.04) 11.3.0
Clang version: Could not collect
CMake version: version 3.25.0
Libc version: glibc-2.35

Python version: 3.10.6 (main, Nov 14 2022, 16:10:14) [GCC 11.3.0] (64-bit runtime)
Python platform: Linux-5.19.0-35-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.7.99
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA GeForce RTX 3090
GPU 1: NVIDIA GeForce RTX 3090

Nvidia driver version: 530.30.02
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:                   43 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          48
On-line CPU(s) list:             0-47
Vendor ID:                       AuthenticAMD
Model name:                      AMD Ryzen Threadripper 3960X 24-Core Processor
CPU family:                      23
Model:                           49
Thread(s) per core:              2
Core(s) per socket:              24
Socket(s):                       1
Stepping:                        0
Frequency boost:                 enabled
CPU max MHz:                     3800,0000
CPU min MHz:                     2200,0000
BogoMIPS:                        7600.78
Flags:                           fpu vme de pse tsc msr pae mce cx8 apic sep mtrr pge mca cmov pat pse36 clflush mmx fxsr sse sse2 ht syscall nx mmxext fxsr_opt pdpe1gb rdtscp lm constant_tsc rep_good nopl nonstop_tsc cpuid extd_apicid aperfmperf rapl pni pclmulqdq monitor ssse3 fma cx16 sse4_1 sse4_2 movbe popcnt aes xsave avx f16c rdrand lahf_lm cmp_legacy svm extapic cr8_legacy abm sse4a misalignsse 3dnowprefetch osvw ibs skinit wdt tce topoext perfctr_core perfctr_nb bpext perfctr_llc mwaitx cpb cat_l3 cdp_l3 hw_pstate ssbd mba ibpb stibp vmmcall fsgsbase bmi1 avx2 smep bmi2 cqm rdt_a rdseed adx smap clflushopt clwb sha_ni xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local clzero irperf xsaveerptr rdpru wbnoinvd amd_ppin arat npt lbrv svm_lock nrip_save tsc_scale vmcb_clean flushbyasid decodeassists pausefilter pfthreshold avic v_vmsave_vmload vgif v_spec_ctrl umip rdpid overflow_recov succor smca sev sev_es
Virtualization:                  AMD-V
L1d cache:                       768 KiB (24 instances)
L1i cache:                       768 KiB (24 instances)
L2 cache:                        12 MiB (24 instances)
L3 cache:                        128 MiB (8 instances)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-47
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   Not affected
Vulnerability Retbleed:          Mitigation; untrained return thunk; SMT enabled with STIBP protection
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; Retpolines, IBPB conditional, STIBP always-on, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.24.2
[pip3] pytorch-triton==2.1.0+2c32f43999
[pip3] torch==2.1.0.dev20230313+cu117
[pip3] torch-tb-profiler==0.4.1
[pip3] torchaudio==2.0.0.dev20230313+cu117
[pip3] torchmetrics==0.11.3
[pip3] torchvision==0.15.0.dev20230313+cu117
[conda] Could not collect