Repository: pytorch
Issue: `DataLoader` generic argument is dropped in `__iter__`, making it non type-safe
Labels: module: dataloader,module: typing,triaged

### 🐛 Describe the bug

Both `Dataset` and `DataLoader` are in principle properly typed with a `Generic[T_co]` to express what's the type of the underlying batch element.

Unfortunately the generic type dropped exactly where it matters: The `__iter__` is not properly typed, and therefore when iterating over a dataset with a data loader the entire type information is lost, and bugs cannot be caught on type checking level. This kind of defeats the purpose of encoding the generic argument, because that's when it would matter (doing something with the batch element).

Reproducing example:

```py
from typing import TypedDict

import torch
from torch.utils.data import DataLoader, Dataset

class MyDatasetBatch(TypedDict):
    X: torch.Tensor
    y: torch.Tensor

class MyDataset(Dataset[MyDatasetBatch]):
    def __len__(self) -> int:
        return 100

    def __getitem__(self, idx: int) -> MyDatasetBatch:
        return MyDatasetBatch(
            X=torch.tensor(0.0),
            y=torch.tensor(0.0),
        )

dataset = MyDataset()
data_loader = DataLoader[MyDatasetBatch](dataset)

# This nicely reveals DataLoader[MyDatasetBatch], i.e., the type information is there.
reveal_type(data_loader)

for batch in data_loader:
    # ... but when actually doing something with the batch it is lost.
    # This is typed as `Any`:
    reveal_type(batch)
    # And bugs like these are not caught.
    X = batch["non_existing"]
    # Even worse, because `X` is now typed as `Any` we can do arbitrarily bad things with it,
    # i.e., not only the wrong name "non_existing" is missed, but we would e.g. also ignored
    # wrong method calls on `X`.
```

Possible solution: Use the generic type argument `T_co` as well on the `__iter__`, i.e., in `_BaseDataLoaderIter`.

### Versions

<details>

<summary>Version details</summary>

```
PyTorch version: 2.1.2+cu121
Is debug build: False
CUDA used to build PyTorch: 12.1
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: 14.0.0-1ubuntu1.1
CMake version: version 3.22.1
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-5.15.0-92-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 11.8.89
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce GTX 980
Nvidia driver version: 535.154.05
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):                             4
On-line CPU(s) list:                0-3
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Core(TM) i5-4670 CPU @ 3.40GHz
CPU family:                         6
Model:                              60
Thread(s) per core:                 1
Core(s) per socket:                 4
Socket(s):                          1
Stepping:                           3
CPU max MHz:                        3800,0000
CPU min MHz:                        800,0000
BogoMIPS:                           6800.03
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 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 cpuid_fault epb invpcid_single pti ssbd ibrs ibpb stibp tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid xsaveopt dtherm ida arat pln pts md_clear flush_l1d
Virtualization:                     VT-x
L1d cache:                          128 KiB (4 instances)
L1i cache:                          128 KiB (4 instances)
L2 cache:                           1 MiB (4 instances)
L3 cache:                           6 MiB (1 instance)
NUMA node(s):                       1
NUMA node0 CPU(s):                  0-3
Vulnerability Gather data sampling: Not affected
Vulnerability Itlb multihit:        KVM: Mitigation: VMX disabled
Vulnerability L1tf:                 Mitigation; PTE Inversion; VMX conditional cache flushes, SMT disabled
Vulnerability Mds:                  Mitigation; Clear CPU buffers; SMT disabled
Vulnerability Meltdown:             Mitigation; PTI
Vulnerability Mmio stale data:      Unknown: No mitigations
Vulnerability Retbleed:             Not affected
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; Retpolines, IBPB conditional, IBRS_FW, STIBP disabled, RSB filling, PBRSB-eIBRS Not affected
Vulnerability Srbds:                Mitigation; Microcode
Vulnerability Tsx async abort:      Not affected

Versions of relevant libraries:
[pip3] flake8==6.1.0
[pip3] mypy==1.7.1
[pip3] mypy-extensions==1.0.0
[pip3] numpy==1.26.2
[pip3] torch==2.1.2
[pip3] torchinfo==1.8.0
[pip3] torchviz==0.0.2
[pip3] triton==2.1.0
[conda] Could not collect
```

</details>

cc @SsnL @VitalyFedyunin @ejguan @dzhulgakov @ezyang @malfet @xuzhao9 @gramster