Repository: pytorch
Issue: No fake impl or Meta kernel for Communication Operator 
Labels: oncall: distributed,triaged

### 🐛 Describe the bug

There is no fake implementation or meta kernel for the Communication Operator. If I want to contribute to this feature, what can I do? Are there any examples that I can reference?
```python
import torch
import torch.nn.functional as F
from torch.utils.data import Dataset, DataLoader
from datautils import MyTrainDataset

import torch.multiprocessing as mp
from torch.utils.data.distributed import DistributedSampler
from torch.nn.parallel import DistributedDataParallel as DDP
from torch.distributed import init_process_group, destroy_process_group
import os
import logging

def ddp_setup():
    init_process_group(backend="nccl")
    torch.cuda.set_device(int(os.environ["LOCAL_RANK"]))

class Trainer:
    def __init__(
        self,
        model: torch.nn.Module,
        train_data: DataLoader,
        optimizer: torch.optim.Optimizer,
        device:torch.device,
    ) -> None:
        self.device = device
        self.gpu_g  = int(os.environ["RANK"]) 
        self.gpu_id = int(os.environ["LOCAL_RANK"])
        self.model = model.to(self.device)
        self.train_data = train_data
        self.optimizer = optimizer
        self.epochs_run = 0
        # self.model = DDP(self.model, device_ids=[self.gpu_id])
        self.model = DDP(self.model)

    def _run_batch(self, source, targets):
        self.optimizer.zero_grad()
        output = self.model(source)
        loss = F.cross_entropy(output, targets)
        loss.backward()
        self.optimizer.step()

    def _run_epoch(self, epoch):
        b_sz = len(next(iter(self.train_data))[0])
        print(f"[GPU{self.gpu_g}] Epoch {epoch} | Batchsize: {b_sz} | Steps: {len(self.train_data)}")
        self.train_data.sampler.set_epoch(epoch)
        for source, targets in self.train_data:
            source = source.to(self.device)
            targets = targets.to(self.device)
            self._run_batch(source, targets)

    def train(self, max_epochs: int):
        for epoch in range(self.epochs_run, max_epochs):
            self._run_epoch(epoch)


def load_train_objs(device:torch.device):
    train_set = MyTrainDataset(2048)  # load your dataset
    model = torch.nn.Linear(20, 1,device=device)  # load your model
    optimizer = torch.optim.SGD(model.parameters(), lr=1e-3)
    return train_set, model, optimizer


def prepare_dataloader(dataset: Dataset, batch_size: int):
    return DataLoader(
        dataset,
        batch_size=batch_size,
        pin_memory=False,
        shuffle=False,
        sampler=DistributedSampler(dataset)
    )


def main(device, total_epochs: int, batch_size: int):
    ddp_setup()
    dataset, model, optimizer = load_train_objs(device)
    train_data = prepare_dataloader(dataset, batch_size)
    trainer = Trainer(model, train_data, optimizer, device)
    trainer.train(total_epochs)
    destroy_process_group()

if __name__ == "__main__":
    import argparse
    torch._logging.set_logs(all=logging.DEBUG)
    parser = argparse.ArgumentParser(description='simple distributed training job')
    parser.add_argument('total_epochs', type=int, help='Total epochs to train the model')
    parser.add_argument('--batch_size', default=32, type=int, help='Input batch size on each device (default: 32)')
    args = parser.parse_args()
    device = torch.device('meta') 
    main(device, args.total_epochs, args.batch_size)
#torchrun --nproc_per_node=1 --nnodes=2 --node_rank=0 --master_addr=192.167.1.1 --master_port=10002 ddp_meta.py 10

```

```
[rank1]: Traceback (most recent call last):
[rank1]:   File "/home/pc06/wyl/Torch-sim/ddp_tutorial/ddp_meta.py", line 89, in <module>
[rank1]:     main(device, args.total_epochs, args.batch_size)
[rank1]:   File "/home/pc06/wyl/Torch-sim/ddp_tutorial/ddp_meta.py", line 77, in main
[rank1]:     trainer = Trainer(model, train_data, optimizer, device)
[rank1]:               ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank1]:   File "/home/pc06/wyl/Torch-sim/ddp_tutorial/ddp_meta.py", line 33, in __init__
[rank1]:     self.model = DDP(self.model)
[rank1]:                  ^^^^^^^^^^^^^^^
[rank1]:   File "/home/pc06/anaconda3/envs/torch25/lib/python3.12/site-packages/torch/nn/parallel/distributed.py", line 825, in __init__
[rank1]:     _verify_param_shape_across_processes(self.process_group, parameters)
[rank1]:   File "/home/pc06/anaconda3/envs/torch25/lib/python3.12/site-packages/torch/distributed/utils.py", line 288, in _verify_param_shape_across_processes
[rank1]:     return dist._verify_params_across_processes(process_group, tensors, logger)
[rank1]:            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
[rank1]: NotImplementedError: c10d::allgather_: attempted to run this operator with Meta tensors, but there was no fake impl or Meta kernel registered. You may have run into this message while using an operator with PT2 compilation APIs (torch.compile/torch.export); in order to use this operator with those APIs you'll need to add a fake impl. Please see the following for next steps:  https://pytorch.org/tutorials/advanced/custom_ops_landing_page.html
E1114 23:05:38.298000 195576 site-packages/torch/distributed/elastic/multiprocessing/api.py:869] failed (exitcode: 1) local_rank: 0 (pid: 195676) of binary: /home/pc06/anaconda3/envs/torch25/bin/python
```

### Versions

PyTorch version: 2.5.0a0
Is debug build: False
CUDA used to build PyTorch: 12.2
ROCM used to build PyTorch: N/A

OS: Ubuntu 22.04.4 LTS (x86_64)
GCC version: (Ubuntu 11.4.0-1ubuntu1~22.04) 11.4.0
Clang version: Could not collect
CMake version: version 3.26.4
Libc version: glibc-2.35

Python version: 3.12.7 | packaged by Anaconda, Inc. | (main, Oct  4 2024, 13:27:36) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.15.0-43-generic-x86_64-with-glibc2.35
Is CUDA available: True
CUDA runtime version: 12.2.91
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: NVIDIA GeForce RTX 4090
Nvidia driver version: 550.78
cuDNN version: Probably one of the following:
/usr/local/cuda-12.2/targets/x86_64-linux/lib/libcudnn.so.8
/usr/local/cuda-12.2/targets/x86_64-linux/lib/libcudnn_adv_infer.so.8
/usr/local/cuda-12.2/targets/x86_64-linux/lib/libcudnn_adv_train.so.8
/usr/local/cuda-12.2/targets/x86_64-linux/lib/libcudnn_cnn_infer.so.8
/usr/local/cuda-12.2/targets/x86_64-linux/lib/libcudnn_cnn_train.so.8
/usr/local/cuda-12.2/targets/x86_64-linux/lib/libcudnn_ops_infer.so.8
/usr/local/cuda-12.2/targets/x86_64-linux/lib/libcudnn_ops_train.so.8
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:                   46 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          32
On-line CPU(s) list:             0-31
Vendor ID:                       GenuineIntel
Model name:                      13th Gen Intel(R) Core(TM) i9-13900K
CPU family:                      6
Model:                           183
Thread(s) per core:              2
Core(s) per socket:              24
Socket(s):                       1
Stepping:                        1
CPU max MHz:                     4300.0000
CPU min MHz:                     800.0000
BogoMIPS:                        5990.40
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 tsc_known_freq 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 rdseed adx smap clflushopt clwb intel_pt sha_ni xsaveopt xsavec xgetbv1 xsaves avx_vnni dtherm ida arat pln pts hwp hwp_notify hwp_act_window hwp_epp hwp_pkg_req umip pku ospke waitpkg gfni vaes vpclmulqdq tme rdpid movdiri movdir64b fsrm md_clear serialize pconfig arch_lbr flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       896 KiB (24 instances)
L1i cache:                       1.3 MiB (24 instances)
L2 cache:                        32 MiB (12 instances)
L3 cache:                        36 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-31
Vulnerability Itlb multihit:     Not affected
Vulnerability L1tf:              Not affected
Vulnerability Mds:               Not affected
Vulnerability Meltdown:          Not affected
Vulnerability Mmio stale data:   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; Enhanced IBRS, IBPB conditional, RSB filling
Vulnerability Srbds:             Not affected
Vulnerability Tsx async abort:   Not affected

Versions of relevant libraries:
[pip3] bert_pytorch==0.0.1a4
[pip3] bert_pytorch==0.0.1a4
[pip3] bert_pytorch==0.0.1a4
[pip3] numpy==1.26.4
[pip3] optree==0.13.0
[pip3] torch==2.5.0a0+gitunknown
[conda] blas                      1.0                         mkl    defaults
[conda] mkl                       2023.1.0         h213fc3f_46344    defaults
[conda] mkl-include               2025.0.0                 pypi_0    pypi
[conda] mkl-service               2.4.0           py312h5eee18b_1    defaults
[conda] mkl-static                2025.0.0                 pypi_0    pypi
[conda] mkl_fft                   1.3.10          py312h5eee18b_0    defaults
[conda] mkl_random                1.2.7           py312h526ad5a_0    defaults
[conda] numpy                     2.1.2                    pypi_0    pypi
[conda] numpy-base                1.26.4          py312h0da6c21_0    defaults
[conda] optree                    0.13.0                   pypi_0    pypi
[conda] torch                     2.5.0a0+gitunknown          pypi_0    pypi
```[tasklist]
### Tasks
```


cc @H-Huang @awgu @kwen2501 @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o