Multi model and multi forward in distirbuted data parallel

username: zhouzh
cooked: <p>Q1: If I have two models named A and B, both wrapped with DDP,  and loss = A(B(inputs)), will DDP work? It seems that gradients will be sync when loss.backward() is called.</p>
<p>Q2: If loss = A(B(inputs1), B(inputs2)), will DDP work ? The forward funciton of B is called twice . btw, I don’t know what does reducer.prepare_for_backward do…</p>

username: mrshenli
cooked: <aside class="quote no-group" data-username="zhouzh" data-post="1" data-topic="84503">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/z/919ad9/48.png" class="avatar"> zhouzh:</div>
<blockquote>
<p>Q1: If I have two models named A and B, both wrapped with DDP, and loss = A(B(inputs)), will DDP work?</p>
</blockquote>
</aside>
<p>It should work. This is using the output from <code>B(inputs)</code> to connect two graphs together. The <code>AllReduce</code> communication from A and B won’t run interleavingly I think. If it hangs somehow, you could trying setting the <a href="https://pytorch.org/docs/master/generated/torch.nn.parallel.DistributedDataParallel.html#torch.nn.parallel.DistributedDataParallel" rel="noopener nofollow ugc"><code>process_group</code></a> argument of two DDP instances to different <code>ProcessGroup</code> objects created using the <a href="https://pytorch.org/docs/stable/distributed.html#torch.distributed.new_group" rel="noopener nofollow ugc"><code>new_group</code></a> API. This will fully decouple the communication of A and B.</p>
<blockquote>
<p>It seems that gradients will be sync when loss.backward() is called.</p>
</blockquote>
<p>Yes, see this page for more detail: <a href="https://pytorch.org/docs/stable/notes/ddp.html" class="inline-onebox" rel="noopener nofollow ugc">Distributed Data Parallel — PyTorch 2.1 documentation</a></p>
<blockquote>
<p>Q2: If loss = A(B(inputs1), B(inputs2)), will DDP work ? The forward funciton of B is called twice . btw, I don’t know what does reducer.prepare_for_backward do…</p>
</blockquote>
<p>This won’t work. DDP requires forward and backward to run alternatively. The above code would run forward on B twice before one backward, which would mess up DDP internal states. However, the following would work. Suppose the local module wrapped by B is C</p>
<pre data-code-wrap="python"><code class="lang-python">
class Wrapper(nn.Module):
    def __init__(self):
        self.c = C()

    def forward(inputs):
        return self.c(inputs[0]), self.c(inputs[1])

B = DistributedDataParallel(Wrapper(), ...)

loss = A(B([input21, inputs2]))
</code></pre>
<p>This is basically using a sheer wrapper over C to process two inputs in one forward call.</p>

username: qianyizhang
cooked: <p>Hi,<br>
I have a different but related problem.<br>
I have a detection model with unfixed input size. At some extreme case, the RuntimeError with OOM occurs, so I wrap the forward+backward around try+except</p>
<pre><code class="lang-auto">for images, targets in data_loader:
        images = images.to(device)
        targets = [target.to(device) for target in targets]
        try:
            loss_dict = model(images, targets)
            losses = sum(loss for loss in loss_dict.values())
            optimizer.zero_grad()
            losses .backward()
        except Exception as ex:
            torch.cuda.ipc_collect()
            torch.cuda.empty_cache()
            continue
</code></pre>
<p>this would help to some extend, until:</p>
<blockquote>
<p>RuntimeError: Expected to have finished reduction in the prior iteration before starting a new one. This error indicates that your module has parameters that were not used in producing its output (the return value of <code>forward</code>). You can enable unused parameter detection by passing the keyword argument <code>find_unused_parameters=True</code> to <code>torch.nn.parallel.DistributedDataParallel</code>. If you already have this argument set, then the distributed data parallel module wasn’t able to locate the output tensors in the return value of your module’s <code>forward</code> function. Please include the structure of the return value of <code>forward</code> of your module when reporting this issue (e.g. list, dict, iterable). (prepare_for_backward at /opt/conda/conda-bld/pytorch_1556653099582/work/torch/csrc/distributed/c10d/reducer.cpp:408)</p>
</blockquote>
<p>To be clear, I already set find_unused_parameters=True, and broadcast_buffers=False. My guess is some internal state was strained somehow. Is it possible to reset all the state during my except catch?</p>

username: mrshenli
cooked: <p>Hey <a class="mention" href="/u/qianyizhang">@qianyizhang</a></p>
<p>Yes, the error is expected. Because, say you have two DDP processes, X and Y. If process X hits a OOM error in the forward pass of one iteration but Y runs correctly, as a result, X would skip its backward pass in that iteration causing a de-synchronization. DDP itself cannot recover from this error.</p>
<p>However, <a href="https://pytorch.org/elastic" rel="nofollow noopener">torchelastic</a> is built to solve this exact problem. It would kill the entire DDP gang, reconstruct a new DDP gang, and revert to the previous checkpoint when such OOM occurs. cc <a class="mention" href="/u/kiuk_chung">@Kiuk_Chung</a></p>

username: Kiuk_Chung
cooked: <p>Adding a bit more context to <a class="mention" href="/u/mrshenli">@mrshenli</a>’s comments, you <em>could</em> try to reset the DDP state by calling <code>destroy_process_group()</code> and re-initializing it, however that doesn’t guarantee that your tensors (distributed among multiple workers) are also reset. In short, a complete state reset on the worker is application dependent (and often non-trivial). For transient exceptions you can use torchelastic to launch your workers, and just let the worker process throw the exception out and fail. Elastic will monitor the worker pids and will restart the world if it detects that one (or more) workers have failed. Note, that due to this behavior, (assuming you have checkpoints) you will lose progress between checkpoints.</p>

username: qianyizhang
cooked: <p><a class="mention" href="/u/kiuk_chung">@Kiuk_Chung</a>  Can your elaborate more on the last part?<br>
My goal is to keep the training process going with minimum withdraw from failed synchronization.<br>
I assume your elastic feature offers the flexibility of leaving + rejoining the sync pool at any given point?<br>
If one failed worker = all process have to restart from last checkpoint, it’s basically the same as I ran a background monitor process constantly checks-&gt;kills-&gt;restarts the whole process, which is not very efficient…</p>

username: qianyizhang
cooked: <p>the funny part is the mentioned RuntimeError only happens 10% of the time, while the training process could tough it out most of times as if one worker has a slow start (by retraining a second round). I suspect it hits OOM before finish computing first bucket of gradients…</p>

username: Kiuk_Chung
cooked: <p>Its the later, elastic monitors worker pids and restarts the world whenever one or more pids fail. Elastic was designed to be more general purpose to fit a variety of distributed training use-cases. For pure torch rpc apps it might be possible to allow workers to leave/join the job on the fly, but if you are using process groups the backend may not allow this by design - for instance if you are using NCCL backend, NCCL itself does not allow resizing of communicators unless you destroy them and restart them.</p>

username: qianyizhang
cooked: <p><a class="mention" href="/u/kiuk_chung">@Kiuk_Chung</a> I see.<br>
But is it possible to reset DDP state on one worker (with NCCL backend)? Without resetting everything, which is somewhat expansive.<br>
After all, in my case the connection is not lost, it’s simply halted with OOM. The ideal scenario could be:<br>
(assuming a bad case where bucket 1 gradients already reduced, and stuck on bucket2 with worker#0 OOM)</p>
<ol>
<li>worker#0 rerun another batch and only sync bucket2 + later, to “catch up” with the rest.</li>
<li>worker#0 continue to sync while only sending 0.0 gradients without further computation.</li>
</ol>
<p>I imagine solution#1 is very tricky if not impossible, whereas solution#2 is very much feasible?<br>
If so, can you point me some directions to make it work? (files, watch-outs, etc.) Thanks!</p>

username: zhouzh
cooked: <p>Thanks, this helps me a lot !</p>

username: Kiuk_Chung
cooked: <p>If the collective operation fails (with an OOM or other exception) and you are able to catch it you <em>may</em> be able to reissue the operation. Whether this works or not depends on whether the distributed backend is still in a good state or not. With NCCL once the state goes bad you have to destroy the process group and re initialize it. You could try to salvage your processes but you’d have to call destroy and initialize on all your workers together. There may be other states in your application that goes out of sync whenever there is an exception only observed in a subset of your workers. if you are able to recover that state you can try to restore the workers into a well defined point in time. Based on what we’ve observed with distributed applications it’s non trivial to restore the full application state (ddp + user code) in a distributed setting and the cleanest restore is to tear the processes down and restore from a checkpoint. This is why elastic was designed as such. Trade off is restart overhead versus correctness and maintainability. Note that with elastic you are simply restarting your worker processes so the penalty you pay is your initialization time (loading the model, allocating mem for data, etc) and not actually restarting the node or container.</p>

username: EachOneChew
cooked: <p>Thank you very much. This thread has saved me a lot of headache!</p>