`torch.utils.checkpoint` drops custom Tensor attributes
Labels: module: checkpoint, triaged

### 🐛 Describe the bug

Hi,

I noticed that if I have a torch.Tensor with a custom attribute, say `my_tensor.foo = "huhu"`, PyTorch raises an error if this attribute is accessed in the backward when using `torch.utils.checkpoint`.

There are no issues without torch.utils.checkpoint.

Reproduction:

```python
from typing import List, Optional, Tuple, Union

import torch
import torch.utils.checkpoint
from torch import nn

class GPTBigCodeAttention(nn.Module):
    def __init__(self, config, layer_idx=None):
        super().__init__()
        self.c_attn = nn.Linear(config.hidden_size, config.hidden_size + 2 * 15)

    def forward(
        self,
        hidden_states: torch.Tensor,
        attention_mask: Optional[torch.Tensor] = None,
    ) -> torch.Tensor:
        print("attention_mask.huhu", attention_mask.huhu)
        print("attention_mask._padding_mask", attention_mask._padding_mask)
        query = self.c_attn(hidden_states)

        return query

class GPTBigCodeModel(nn.Module):
    def __init__(self, config):
        super().__init__()
        self.wte = nn.Embedding(config.vocab_size, config.hidden_size)
        self.h = nn.ModuleList([GPTBigCodeAttention(config, layer_idx=i) for i in range(config.num_hidden_layers)])

    def forward(
        self,
        input_ids: Optional[torch.Tensor] = None,
        attention_mask: Optional[torch.Tensor] = None,
    ) -> Tuple:
        attention_mask = torch.Tensor([4, 5, 6])
        attention_mask._padding_mask = None

        attention_mask.huhu = "is this working?"

        hidden_states = self.wte(input_ids)
        
        def create_custom_forward(module):
            def custom_forward(*inputs):
                # None for past_key_value
                return module(*inputs)

            return custom_forward

        outputs = torch.utils.checkpoint.checkpoint(
            create_custom_forward(self.h[0]),
            hidden_states,
            attention_mask,
        )
        #outputs = self.h[0](hidden_states, attention_mask)

        return outputs


from transformers import AutoConfig, AutoTokenizer

cfg = AutoConfig.from_pretrained("hf-internal-testing/tiny-random-GPTBigCodeForCausalLM")

model = GPTBigCodeModel(cfg)
tokenizer = AutoTokenizer.from_pretrained("hf-internal-testing/tiny-random-GPTBigCodeForCausalLM")

torch_device = "cuda"

inp = tokenizer("this is me", return_tensors="pt").to(torch_device)

model.to(torch_device)
model = model.train()

result = model(inp["input_ids"])

loss = result[0].sum()

print("call backward ------")
loss.backward()
```

raising:

```
attention_mask.huhu is this working?
attention_mask._padding_mask None
call backward ------
Traceback (most recent call last):
  File "/fsx/felix/transformers/src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py", line 77, in <module>
    loss.backward()
  File "/fsx/felix/condaenvs/fx/lib/python3.9/site-packages/torch/_tensor.py", line 492, in backward
    torch.autograd.backward(
  File "/fsx/felix/condaenvs/fx/lib/python3.9/site-packages/torch/autograd/__init__.py", line 251, in backward
    Variable._execution_engine.run_backward(  # Calls into the C++ engine to run the backward pass
  File "/fsx/felix/condaenvs/fx/lib/python3.9/site-packages/torch/autograd/function.py", line 288, in apply
    return user_fn(self, *args)
  File "/fsx/felix/condaenvs/fx/lib/python3.9/site-packages/torch/utils/checkpoint.py", line 271, in backward
    outputs = ctx.run_function(*detached_inputs)
  File "/fsx/felix/transformers/src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py", line 44, in custom_forward
    return module(*inputs)
  File "/fsx/felix/condaenvs/fx/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1518, in _wrapped_call_impl
    return self._call_impl(*args, **kwargs)
  File "/fsx/felix/condaenvs/fx/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1527, in _call_impl
    return forward_call(*args, **kwargs)
  File "/fsx/felix/transformers/src/transformers/models/gpt_bigcode/modeling_gpt_bigcode.py", line 17, in forward
    print("attention_mask.huhu", attention_mask.huhu)
AttributeError: 'Tensor' object has no attribute 'huhu'
```

Note: subclassing `torch.Tensor` does not help. Tried with:

```python
class QTensor(torch.Tensor):
    @staticmethod 
    def __new__(cls, x, _padding_mask, *args, **kwargs): 
        return super().__new__(cls, x, *args, **kwargs) 
    
    def __init__(self, data, _padding_mask=False):
        self._padding_mask = _padding_mask
```

### Versions

```
Collecting environment information...
PyTorch version: 2.1.0+cu118
Is debug build: False
CUDA used to build PyTorch: 11.8
ROCM used to build PyTorch: N/A

OS: Ubuntu 20.04.5 LTS (x86_64)
GCC version: (Ubuntu 9.4.0-1ubuntu1~20.04.2) 9.4.0
Clang version: Could not collect
CMake version: version 3.26.4
Libc version: glibc-2.31

Python version: 3.9.16 (main, May 15 2023, 23:46:34)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-1023-aws-x86_64-with-glibc2.31
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA A100-SXM4-80GB
GPU 1: NVIDIA A100-SXM4-80GB
GPU 2: NVIDIA A100-SXM4-80GB
GPU 3: NVIDIA A100-SXM4-80GB
GPU 4: NVIDIA A100-SXM4-80GB
GPU 5: NVIDIA A100-SXM4-80GB
GPU 6: NVIDIA A100-SXM4-80GB
GPU 7: NVIDIA A100-SXM4-80GB

Nvidia driver version: 510.73.08
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
Byte Order:                      Little Endian
Address sizes:                   46 bits physical, 48 bits virtual
CPU(s):                          96
On-line CPU(s) list:             0-95
Thread(s) per core:              2
Core(s) per socket:              24
Socket(s):                       2
NUMA node(s):                    2
Vendor ID:                       GenuineIntel
CPU family:                      6
Model:                           85
Model name:                      Intel(R) Xeon(R) Platinum 8275CL CPU @ 3.00GHz
Stepping:                        7
CPU MHz:                         3000.006
BogoMIPS:                        6000.01
Hypervisor vendor:               KVM
Virtualization type:             full
L1d cache:                       1.5 MiB
L1i cache:                       1.5 MiB
L2 cache:                        48 MiB
L3 cache:                        71.5 MiB
NUMA node0 CPU(s):               0-23,48-71
NUMA node1 CPU(s):               24-47,72-95
Vulnerability Itlb multihit:     KVM: Mitigation: VMX unsupported
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 Retbleed:          Vulnerable
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, PBRSB-eIBRS Not affected
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 arch_perfmon rep_good nopl xtopology nonstop_tsc cpuid aperfmperf tsc_known_freq pni pclmulqdq monitor 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

Versions of relevant libraries:
[pip3] mypy-extensions==1.0.0
[pip3] mypy-protobuf==3.4.0
[pip3] numpy==1.24.3
[pip3] onnx==1.13.1
[pip3] onnxruntime-gpu==1.15.1
[pip3] onnxruntime-training==1.15.1
[pip3] torch==2.1.0+cu118
[pip3] torchaudio==2.1.0+cu118
[pip3] torchvision==0.16.0+cu118
[pip3] triton==2.1.0
[conda] numpy                     1.24.3                   pypi_0    pypi
[conda] torch                     2.1.0+cu118              pypi_0    pypi
[conda] torchaudio                2.1.0+cu118              pypi_0    pypi
[conda] torchvision               0.16.0+cu118             pypi_0    pypi
[conda] triton                    2.1.0                    pypi_0    pypi
```