Repository: pytorch
Issue: [Pipelining] Backward pass tries to detach view tensor in-place
Labels: oncall: distributed,triaged

### 🐛 Describe the bug

When using ``torch.distributed.pipelining`` with a model stage that outputs a view, the error ``RuntimeError: Can't detach views in-place. Use detach() instead.`` is raised. This is due to https://github.com/pytorch/pytorch/commit/32a3dbc6450171dec4ef62a36037dd5dc24790d2#diff-c4c60c227aa9333879c26bbee32896f44902fea81894fe04078a0310897b1eedR698
 that detaches the output in place to free memory after the backward pass.

The fix should simply be to check ``t._is_view()`` and either don't detach, or detach ``t._base``.

```py
import torch
import torch.nn as nn
import torch.distributed as dist
from torch.distributed.pipelining import PipelineStage, Schedule1F1B
import os

local_rank = int(os.getenv("LOCAL_RANK"))
torch.cuda.set_device(local_rank)
dist.init_process_group("nccl")

class ViewModel(nn.Module):
	def forward(self, x):
		return x.view(x.size(0), -1)

model = ViewModel()
stage = PipelineStage(model, local_rank, 2, torch.cuda.current_device())
schedule = Schedule1F1B(stage, 2, loss_fn = nn.functional.mse_loss)

x = torch.randn(4, 3, device = local_rank)
if local_rank == 0:
	schedule.step(x)
if local_rank == 1:
	schedule.step(target = x)

dist.destroy_process_group()
```

Started with command 
``torchrun --nproc-per-node 2 --standalone file.py``

### Versions

PyTorch version: 2.6.0.dev20241205+cu124
Is debug build: False
CUDA used to build PyTorch: 12.4
ROCM used to build PyTorch: N/A

OS: Red Hat Enterprise Linux 9.2 (Plow) (x86_64)
GCC version: (GCC) 11.3.1 20221121 (Red Hat 11.3.1-4)
Clang version: Could not collect
CMake version: Could not collect
Libc version: glibc-2.34

Python version: 3.11.5 (main, Sep 11 2023, 13:54:46) [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.14.0-284.55.1.el9_2.x86_64-x86_64-with-glibc2.34
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: GPU 0: Tesla V100-SXM2-32GB
Nvidia driver version: 550.54.15
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:                      46 bits physical, 48 bits virtual
Byte Order:                         Little Endian
CPU(s):                             80
On-line CPU(s) list:                0-79
Vendor ID:                          GenuineIntel
Model name:                         Intel(R) Xeon(R) Gold 6248 CPU @ 2.50GHz
CPU family:                         6
Model:                              85
Thread(s) per core:                 2
Core(s) per socket:                 20
Socket(s):                          2
Stepping:                           7
CPU max MHz:                        3900.0000
CPU min MHz:                        1000.0000
BogoMIPS:                           5000.00
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 pni pclmulqdq dtes64 monitor ds_cpl vmx smx est tm2 ssse3 sdbg fma cx16 xtpr pdcm pcid dca sse4_1 sse4_2 x2apic movbe popcnt tsc_deadline_timer aes xsave avx f16c rdrand lahf_lm abm 3dnowprefetch cpuid_fault epb cat_l3 cdp_l3 invpcid_single intel_ppin ssbd mba ibrs ibpb stibp ibrs_enhanced tpr_shadow vnmi flexpriority ept vpid ept_ad fsgsbase tsc_adjust bmi1 avx2 smep bmi2 erms invpcid cqm mpx rdt_a avx512f avx512dq rdseed adx smap clflushopt clwb intel_pt avx512cd avx512bw avx512vl xsaveopt xsavec xgetbv1 xsaves cqm_llc cqm_occup_llc cqm_mbm_total cqm_mbm_local dtherm ida arat pln pts hwp hwp_act_window hwp_epp hwp_pkg_req pku ospke avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                     VT-x
L1d cache:                          1.3 MiB (40 instances)
L1i cache:                          1.3 MiB (40 instances)
L2 cache:                           40 MiB (40 instances)
L3 cache:                           55 MiB (2 instances)
NUMA node(s):                       2
NUMA node0 CPU(s):                  0-19,40-59
NUMA node1 CPU(s):                  20-39,60-79
Vulnerability Gather data sampling: Mitigation; Microcode
Vulnerability Itlb multihit:        KVM: Mitigation: VMX disabled
Vulnerability L1tf:                 Not affected
Vulnerability Mds:                  Not affected
Vulnerability Meltdown:             Not affected
Vulnerability Mmio stale data:      Mitigation; Clear CPU buffers; SMT vulnerable
Vulnerability Retbleed:             Mitigation; Enhanced IBRS
Vulnerability Spec rstack overflow: Not affected
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; Enhanced IBRS, IBPB conditional, RSB filling, PBRSB-eIBRS SW sequence
Vulnerability Srbds:                Not affected
Vulnerability Tsx async abort:      Mitigation; TSX disabled

Versions of relevant libraries:
[pip3] configmypy==0.2.0
[pip3] flopco-pytorch==0.1.4
[pip3] numpy==2.1.2
[pip3] nvidia-cublas-cu12==12.4.5.8
[pip3] nvidia-cuda-cupti-cu12==12.4.127
[pip3] nvidia-cuda-nvrtc-cu12==12.4.127
[pip3] nvidia-cuda-runtime-cu12==12.4.127
[pip3] nvidia-cudnn-cu12==9.1.0.70
[pip3] nvidia-cufft-cu12==11.2.1.3
[pip3] nvidia-curand-cu12==10.3.5.147
[pip3] nvidia-cusolver-cu12==11.6.1.9
[pip3] nvidia-cusparse-cu12==12.3.1.170
[pip3] nvidia-cusparselt-cu12==0.6.2
[pip3] nvidia-nccl-cu12==2.21.5
[pip3] nvidia-nvjitlink-cu12==12.4.127
[pip3] nvidia-nvtx-cu12==12.4.127
[pip3] pytorch-triton==3.2.0+git35c6c7c6
[pip3] torch==2.6.0.dev20241205+cu124
[pip3] torchaudio==2.5.0.dev20241205+cu124
[pip3] torchvision==0.20.0.dev20241205+cu124
[pip3] triton==3.0.0

cc @H-Huang @awgu @kwen2501 @wanchaol @fegin @fduwjj @wz337 @wconstab @d4l3k @c-p-i-o