RuntimeError: one of the variables needed for gradient computation has been modified by an inplace operation. (BatchNorm2d track_running_stats)

Priyank_Pathak: <p>If we do a second forward pass on the model having <code>nn.BatchNorm2d</code> with  <strong>track_running_stats = True</strong>, while in ``torch.nn.parallel.DistributedDataParallel` mode, the code throws the error:<br>
<code>RuntimeError: one of the variables needed for gradient computation has been modified by an in-place operation</code></p>
<p>I’m attaching the code to recreate the error. (<a href="https://drive.google.com/file/d/1HGjI6SCfavZy-lXwtMsh78Q0abpnhvpu/view?usp=sharing" class="inline-onebox" rel="noopener nofollow ugc">debug2.py - Google Drive</a>)<br>
Run the above as :</p>
<pre><code class="lang-auto">CUDA_VISIBLE_DEVICES=0 python -W ignore -m torch.distributed.launch --master_port 12345 --nproc_per_node=1 --use_env debug2.py
</code></pre>
<p>The only way to resolve the error is either</p>
<ul>
<li><strong>track_running_stats = False</strong>, or</li>
<li>not running the model in <code>torch.nn.parallel.DistributedDataParallel</code>.</li>
</ul>
<p>Is there a better way to solve this problem?  This problem doesn’t exist outside <code>torch.nn.parallel.DistributedDataParallel</code>. For example, doing <code>model = nn.DataParallel(model).cuda()</code> will work</p>

Priyank_Pathak: <p>In the nn.BatchNorm2d implementation</p>
<pre><code class="lang-auto">F.batch_norm(
            input,
            self.running_mean if not self.training or self.track_running_stats else None,
            self.running_var if not self.training or self.track_running_stats else None,
            self.weight,
            self.bias,
            bn_training,
            exponential_average_factor,
            self.eps,
)        
</code></pre>
<p>does in place an update of <code>self.running_mean</code> &amp; <code>self.running_var</code> which creates the version mismatch.</p>
<p>doing:</p>
<pre><code class="lang-auto">self.running_mean_copy = copy.deepcopy(self.running_mean)
self.running_var_copy = copy.deepcopy(self.running_var)

F.batch_norm(
            input,
            self.running_mean_copy if not self.training or self.track_running_stats else None,
            self.running_var_copy if not self.training or self.track_running_stats else None,
            self.weight,
            self.bias,
            bn_training,
            exponential_average_factor,
                self.eps,
)        
self.running_mean = self.running_mean * 0 + self.running_mean_copy
self.running_var = self.running_var * 0 + self.running_var_copy
</code></pre>
<p>solves the issue</p>

albanD: <p>Ho this is surprising that DDP is causing this. Could you open an issue on github to track this please?</p>

Priyank_Pathak: <aside class="quote no-group" data-username="Priyank_Pathak" data-post="1" data-topic="189071">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/user_avatar/discuss.pytorch.org/priyank_pathak/48/19974_2.png" class="avatar"> Priyank_Pathak:</div>
<blockquote>
<p>BatchNorm2d</p>
</blockquote>
</aside>
<p>Done:</p><aside class="onebox githubissue" data-onebox-src="https://github.com/pytorch/pytorch/issues/110363">
  <header class="source">

      <a href="https://github.com/pytorch/pytorch/issues/110363" target="_blank" rel="noopener nofollow ugc">github.com/pytorch/pytorch</a>
  </header>

  <article class="onebox-body">
    <div class="github-row">
  <div class="github-icon-container" title="Issue">
	  <svg width="60" height="60" class="github-icon" viewBox="0 0 14 16" aria-hidden="true"><path fill-rule="evenodd" d="M7 2.3c3.14 0 5.7 2.56 5.7 5.7s-2.56 5.7-5.7 5.7A5.71 5.71 0 0 1 1.3 8c0-3.14 2.56-5.7 5.7-5.7zM7 1C3.14 1 0 4.14 0 8s3.14 7 7 7 7-3.14 7-7-3.14-7-7-7zm1 3H6v5h2V4zm0 6H6v2h2v-2z"></path></svg>
  </div>

  <div class="github-info-container">
    <h4>
      <a href="https://github.com/pytorch/pytorch/issues/110363" target="_blank" rel="noopener nofollow ugc">nn.BatchNorm2d (track_running_stats = True) causes "modified by an in-place operation" error when in torch.nn.parallel.DistributedDataParallel</a>
    </h4>

    <div class="github-info">
      <div class="date">
        opened <span class="discourse-local-date" data-format="ll" data-date="2023-10-01" data-time="19:28:47" data-timezone="UTC">07:28PM - 01 Oct 23 UTC</span>
      </div>


      <div class="user">
        <a href="https://github.com/ppriyank" target="_blank" rel="noopener nofollow ugc">
          <img alt="ppriyank" src="https://avatars.githubusercontent.com/u/6764941?v=4" class="onebox-avatar-inline" width="20" height="20">
          ppriyank
        </a>
      </div>
    </div>

    <div class="labels">
        <span style="display:inline-block;margin-top:2px;background-color: #B8B8B8;padding: 2px;border-radius: 4px;color: #fff;margin-left: 3px;">
          oncall: distributed
        </span>
        <span style="display:inline-block;margin-top:2px;background-color: #B8B8B8;padding: 2px;border-radius: 4px;color: #fff;margin-left: 3px;">
          triaged
        </span>
    </div>
  </div>
</div>

  <div class="github-row">
    <p class="github-body-container">### 🐛 Describe the bug

I have already raised this issue on Torch Discussions [(<span class="show-more-container"><a href="" rel="noopener" class="show-more">…</a></span><span class="excerpt hidden">link)](https://discuss.pytorch.org/t/runtimeerror-one-of-the-variables-needed-for-gradient-computation-has-been-modified-by-an-inplace-operation-batchnorm2d-track-running-stats/189071/1). 
The above issue has a snippet of code and a temporary working solution. 

If we do a second forward pass on the model having nn.BatchNorm2d with track_running_stats = True, while in `torch.nn.parallel.DistributedDataParallel` mode, the code throws the error:

```RuntimeError: one of the variables needed for gradient computation has been modified by an in-place operation```

Only way to prevent this error is: 

1. Run with Track_running_stats = False, or
2. Disable torch.nn.parallel.DistributedDataParallel.
3. Modify the nn.BatchNorm2d implementation 

```
self.running_mean_copy = copy.deepcopy(self.running_mean)
self.running_var_copy = copy.deepcopy(self.running_var)

F.batch_norm(
            input,
            self.running_mean_copy if not self.training or self.track_running_stats else None,
            self.running_var_copy if not self.training or self.track_running_stats else None,
            self.weight,
            self.bias,
            bn_training,
            exponential_average_factor,
                self.eps,
)        
self.running_mean = self.running_mean * 0 + self.running_mean_copy
self.running_var = self.running_var * 0 + self.running_var_copy
```


### Versions

Collecting environment information...
PyTorch version: 1.13.1+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.26.4
Libc version: glibc-2.35

Python version: 3.8.18 (default, Sep 11 2023, 13:40:15)  [GCC 11.2.0] (64-bit runtime)
Python platform: Linux-5.19.0-38-generic-x86_64-with-glibc2.17
Is CUDA available: True
CUDA runtime version: Could not collect
CUDA_MODULE_LOADING set to: LAZY
GPU models and configuration: 
GPU 0: NVIDIA RTX A6000
GPU 1: NVIDIA RTX A6000
GPU 2: NVIDIA RTX A6000

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:                   46 bits physical, 48 bits virtual
Byte Order:                      Little Endian
CPU(s):                          36
On-line CPU(s) list:             0-35
Vendor ID:                       GenuineIntel
Model name:                      Intel(R) Xeon(R) W-2295 CPU @ 3.00GHz
CPU family:                      6
Model:                           85
Thread(s) per core:              2
Core(s) per socket:              18
Socket(s):                       1
Stepping:                        7
CPU max MHz:                     4800.0000
CPU min MHz:                     1200.0000
BogoMIPS:                        6000.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 avx512_vnni md_clear flush_l1d arch_capabilities
Virtualization:                  VT-x
L1d cache:                       576 KiB (18 instances)
L1i cache:                       576 KiB (18 instances)
L2 cache:                        18 MiB (18 instances)
L3 cache:                        24.8 MiB (1 instance)
NUMA node(s):                    1
NUMA node0 CPU(s):               0-35
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 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] numpy==1.24.4
[pip3] pytorch-msssim==1.0.0
[pip3] torch==1.13.1+cu117
[pip3] torchaudio==0.13.1+cu117
[pip3] torchvision==0.14.1+cu117
[conda] numpy                     1.24.4                   pypi_0    pypi
[conda] pytorch-msssim            1.0.0                    pypi_0    pypi
[conda] torch                     1.13.1+cu117             pypi_0    pypi
[conda] torchaudio                0.13.1+cu117             pypi_0    pypi
[conda] torchvision               0.14.1+cu117             pypi_0    pypi


cc @mrshenli @pritamdamania87 @zhaojuanmao @satgera @rohan-varma @gqchen @aazzolini @osalpekar @jiayisuse @H-Huang @kwen2501 @awgu @penguinwu</span></p>
  </div>

  </article>

  <div class="onebox-metadata">
    
    
  </div>

  <div style="clear: both"></div>
</aside>


fduwjj: <p>Are <code>self.running_mean_copy</code> and <code>self.running_var_copy</code> buffers or are they params?</p>