Model parallelism in pytorch for large(r than 1 GPU) models?

ajdroid: <p>Hi! I have a model that is too large to fit inside a single TITAN X (even with 1 batch size). I want to split it over several GPUs such that the memory cost is shared between GPUs. That is, place different parts of the same model on different GPUs and train it end-to-end.</p>
<p>Questions:</p>
<ol>
<li>Is this possible in pyTorch? If not, is this possible in Torch?</li>
<li>Would inter-GPU communication (say, for transferring activations to later layers) involve GPU-&gt;host-&gt;GPU type transfers?</li>
</ol>

apaszke: <ol>
<li>Yes it is possible. Just put some of the layers in GPU0 (<code>.cuda(0)</code>) and others on GPU1 (<code>.cuda(1)</code>). Then, in the forward function, once the base on the first GPU finishes processing, call <code>.cuda(1)</code> on the output. Of course this can be extended to as many GPUs as you want. See an example below.</li>
<li>No. Calling <code>.cuda(i)</code> on a CUDA tensor that’s on GPU j (j != i) is purely a peer to peer copy. Host doesn’t have to do anything.</li>
</ol>
<pre><code class="lang-python">class MyModel(nn.Module):
    def __init__(self, split_gpus):
        self.large_submodule1 = ...
        self.large_submodule2 = ...

        self.split_gpus = split_gpus
        if split_gpus:
            self.large_submodule1.cuda(0)
            self.large_submodule1.cuda(1)

    def forward(self, x):
        x = self.large_submodule1(x)
        if split_gpus:
            x = x.cuda(1) # P2P GPU transfer
        return self.large_submodule2(x)
</code></pre>

ajdroid: <p>This was so easy! I love your work with PyTorch. Minimum fuss! Cheers!</p>

D-X-Y: <aside class="quote no-group" data-username="apaszke" data-post="2" data-topic="778">
<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/apaszke/48/21_2.png" class="avatar"> apaszke:</div>
<blockquote>
<p>and others on GPU1 (.cuda(1)). Then, in the forward function, once the base on the first GPU finishes processing, call .c</p>
</blockquote>
</aside>
<p><a class="mention" href="/u/apaszke">@apaszke</a>  Hi, very thanks for your examples.</p>
<p>I notice that when I split the whole model in 4 gpus and do forward/backward, the GPU memory on the fisrt GPU cost much more than it should be. For example, if the whole model cost 12GB on a single GPU, when split it to four GPUs, the first GPU cost 11GB and the sum of others cost about 11GB.<br>
Is there an explaination for how does the GPU memory be malloced when using multiple GPUs for model parallelism.</p>
<p>Another question, when forward with the model parallelism, there is only one gpu hasing the Volatile GPU-Util with 100%, the others are 0%.<br>
Is there any method to leverage all GPU-Util with the all four GPUs?</p>

Hengck: <p>I am doing late fusion of features extracted by two large resnet.<br>
After that, the classifier on the concatenated features can be run in the second GPU?<br>
Will that be slow?</p>
<p>How to combine data parallel and model parallel?<br>
(say if i have 4 gpu)</p>
<pre><code class="lang-auto">   def forward(self, x):
         
        x1= self.resnet_1(x[:,0:3,:,:]).cuda(0)
        x2= self.resnet_2(x[:,3:6,:,:]).cuda(1)

        flat  = torch.cat([x1, x2],1).cuda(???)
        logit = self.fc(flat).cuda(???) 
        return logit

</code></pre>

isalirezag: <p>did you figure out how to do this?</p>

dimtsi: <p>I am also interested in late fusion and running particular submodels in different GPUs. Did someone find out anything on how to do it? I am currently doing something similar as <a class="mention" href="/u/hengck">@Hengck</a> suggested but it is not working.<br>
Thanks</p>

LeiGuan: <p>Dear apaszke,</p>
<p>I am trying to implement inter-GPU communiation by using pytorch+mpi+gpu.</p>
<p>Following are the tested code, which is designed to make sure that process0 runs on GPU0 and process1 runs on GPU1. However, the code can not be run successfully. Do you know why?</p>
<p>import os<br>
import socket<br>
import torch<br>
import torch.distributed as dist<br>
from torch.multiprocessing import Process<br>
import platform</p>
<p>def run(rank, size):</p>
<p>if rank == 0:<br>
tensor = torch.zeros(1).cuda(0)<br>
# Send the tensor to process 1<br>
tensor += 1<br>
dist.send(tensor=tensor, dst=1)<br>
else:<br>
tensor = torch.zeros(1).cuda(1)<br>
# Receive tensor from process 0<br>
dist.recv(tensor=tensor, src=0)<br>
print('Rank ', rank, ’ has data ', tensor[0])</p>
<p>def init_processes(fn):<br>
“”" Initialize the distributed environment. “”"<br>
dist.init_process_group(‘mpi’)<br>
rank = dist.get_rank()<br>
size = dist.get_world_size()<br>
print('I am rank ', rank, ’ on ', platform.node())<br>
fn(rank, size)</p>
<p>if  <strong>name</strong> == “ <strong>main</strong> ”:<br>
init_processes(run)</p>
<h2>
<strong>Following is the error message.</strong><br>
[osherlab:21377] *** Process received signal ***<br>
[osherlab:21377] Signal: Segmentation fault (11)<br>
[osherlab:21377] Signal code: Invalid permissions (2)<br>
[osherlab:21377] Failing at address: 0x10030800000<br>
[osherlab:21377] [ 0] /lib/x86_64-linux-gnu/libpthread.so.0(+0x11390)[0x7f9cd4e4b390]<br>
[osherlab:21377] [ 1] /lib/x86_64-linux-gnu/libc.so.6(+0x14e04b)[0x7f9cd4bbe04b]<br>
[osherlab:21377] [ 2] /home/osherlab/guanlei/software/openmpi-4.0.0/openmpi/lib/libopen-pal.so.40(opal_convertor_unpack+0x11b)[0x7f9c79c0363b]<br>
[osherlab:21377] [ 3] /home/osherlab/guanlei/software/openmpi-4.0.0/openmpi/lib/openmpi/mca_pml_ob1.so(mca_pml_ob1_recv_frag_callback_match+0x4de)[0x7f9c51f9c1fe]<br>
[osherlab:21377] [ 4] /home/osherlab/guanlei/software/openmpi-4.0.0/openmpi/lib/openmpi/mca_btl_smcuda.so(mca_btl_smcuda_component_progress+0x3b9)[0x7f9c51d6be99]<br>
[osherlab:21377] [ 5] /home/osherlab/guanlei/software/openmpi-4.0.0/openmpi/lib/libopen-pal.so.40(opal_progress+0x2c)[0x7f9c79bf1dac]<br>
[osherlab:21377] [ 6] /home/osherlab/guanlei/software/openmpi-4.0.0/openmpi/lib/libopen-pal.so.40(ompi_sync_wait_mt+0xb5)[0x7f9c79bf86a5]<br>
[osherlab:21377] [ 7] /home/osherlab/guanlei/software/openmpi-4.0.0/openmpi/lib/libmpi.so.40(ompi_request_default_wait+0x20f)[0x7f9ca9f11c9f]<br>
[osherlab:21377] [ 8] /home/osherlab/guanlei/software/openmpi-4.0.0/openmpi/lib/libmpi.so.40(PMPI_Wait+0x4e)[0x7f9ca9f56c2e]<br>
[osherlab:21377] [ 9] /home/osherlab/guanlei/venv/lib/python3.6/site-packages/torch/lib/libtorch_python.so(_ZN4c10d15ProcessGroupMPI9AsyncWork4waitEv+0x6d)[0x7f9cc375191d]<br>
[osherlab:21377] [10] /home/osherlab/guanlei/venv/lib/python3.6/site-packages/torch/lib/libtorch_python.so(+0x5fd98e)[0x7f9cc369298e]<br>
[osherlab:21377] [11] /home/osherlab/guanlei/venv/lib/python3.6/site-packages/torch/lib/libtorch_python.so(+0x112f5d)[0x7f9cc31a7f5d]<br>
[osherlab:21377] [12] python(_PyCFunction_FastCallDict+0x154)[0x563fdb4a0b94]<br>
[osherlab:21377] [13] python(+0x19e7ce)[0x563fdb5307ce]<br>
[osherlab:21377] [14] python(_PyEval_EvalFrameDefault+0x2fa)[0x563fdb552cba]<br>
[osherlab:21377] [15] python(+0x197a94)[0x563fdb529a94]<br>
[osherlab:21377] [16] python(+0x198941)[0x563fdb52a941]<br>
[osherlab:21377] [17] python(+0x19e755)[0x563fdb530755]<br>
[osherlab:21377] [18] python(_PyEval_EvalFrameDefault+0x10ba)[0x563fdb553a7a]<br>
[osherlab:21377] [19] python(+0x19870b)[0x563fdb52a70b]<br>
[osherlab:21377] [20] python(+0x19e755)[0x563fdb530755]<br>
[osherlab:21377] [21] python(_PyEval_EvalFrameDefault+0x2fa)[0x563fdb552cba]<br>
[osherlab:21377] [22] python(+0x197a94)[0x563fdb529a94]<br>
[osherlab:21377] [23] python(+0x198941)[0x563fdb52a941]<br>
[osherlab:21377] [24] python(+0x19e755)[0x563fdb530755]<br>
[osherlab:21377] [25] python(_PyEval_EvalFrameDefault+0x10ba)[0x563fdb553a7a]<br>
[osherlab:21377] [26] python(PyEval_EvalCodeEx+0x329)[0x563fdb52b459]<br>
[osherlab:21377] [27] python(PyEval_EvalCode+0x1c)[0x563fdb52c1ec]<br>
[osherlab:21377] [28] python(+0x2149a4)[0x563fdb5a69a4]<br>
[osherlab:21377] [29] python(PyRun_FileExFlags+0xa1)[0x563fdb5a6da1]<br>
[osherlab:21377] *** End of error message ***<br>
Rank  0  has data  tensor(1., device=‘cuda:0’)</h2>
<h2>Primary job  terminated normally, but 1 process returned<br>
a non-zero exit code. Per user-direction, the job has been aborted.</h2>
<hr>
<p>mpirun noticed that process rank 1 with PID 0 on node osherlab exited on signal 11 (Segmentation fault).</p>
<p>Your help will be appreciated. Thank you.</p>

marcel1991: <p>Would this also work for one 1 gpu with two sequential steps somehow? If my model is too large to fit on one gpu can I somehow do the forward/backward pass sequtially where I only have one part in gpu memory and somehow cache the other part for the backward pass later.</p>
<p>Somehow like this:</p>
<pre><code class="lang-auto">x = submodule1(x)
#somehow unload intermediate results of submodule1 from gpu here and cache for later backward pass 
#(and then load on gpu again when needed in backward pass of submodule1)
x = submodule2(x)
</code></pre>
<p>I could imagine how this works but then I don’t know how I would pass the gradients that come from submodule2 back to submodule1 and initiate the backward pass on submodule1.</p>

RaayChen: <p>Same problem here. Inter-GPU communication gets a similar error with pytorch+mpi+gpu.<br>
Have you found a way out?</p>
<p>Thx</p>

shinx: <p>You may want to checkout the concept of Gradient checkpointing.<br>
Here is an example repo <a href="https://github.com/csrhddlam/pytorch-checkpoint" rel="nofollow noopener">csrhddlam/pytorch-checkpoint</a></p>