How to move all tensors to cuda?

Zeyu: <p>I am kind of new to PyTorch and training on GPU. When I define a model (a network) myself, I can move all tensor I define in the model to cuda using xx.to(device). However, if I want to use the model defined by others, for example, cloning from others’ github repo, I cannot modify the model.<br>
In this case, if I just move the network to cuda, it won’t work. I wonder how I can move all tesnors they define in the model to cuda? <img src="https://discuss.pytorch.org/images/emoji/apple/thinking.png?v=9" title=":thinking:" class="emoji" alt=":thinking:"></p>

JuanFMontesinos: <p>Pytorch works with a recursive calling.</p>
<p>A nn.Module  instance (aka, neural network/layer) is usually composed by other nn.Module instances.<br>
once you have defined the main one (let’s call it model) you can move all the instances and subinstances (layers) inside that by doing model=model.cuda()</p>
<p>nn.Modules are composed of 2 main parts.<br>
The <strong>init</strong> method in which you define the layers (which are also nn.Modules as I aforementioned) and the forward, which defines how those layers are used.</p>
<p>Following good practices, code shouldn’t hardcode allocation (whether cuda or cpu) in neither <strong>init</strong> or forward.<br>
That means that, once you have a model, you can choose whether to process it using the cpu or cuda.</p>
<p>For the former case you have to do nothing (as tensors are defined as cpu tensors by default). For the latter you just need to allocate the model and inputs in cuda:<br>
Pseudocode</p>
<pre><code class="lang-auto">model = model.cuda()
for batch in dataloader:
   output = model(batch.cuda())
</code></pre>

Zeyu: <p>Hi, thanks for the reply!</p>
<p>I try to do that and the same error still occurs.<br>
“expected device cpu but got device cuda:0”.</p>
<p>I think the problem is that when they define some tensors in the main model or subinstances, they do not allocate the device. I wonder whether there is a way to move all those tensors to cuda.<br>
I once met the same problem and what I did that time is to allocate all tensors defined in the model and subinstances to the same device as the input. However, this time the model is larger and I may not want to modfiy their code.(I am tryin to directly import their model this time)</p>

Zeyu: <p>I read some posts and think maybe the problem is that those tensors are not defined as parameters or buffers. For example, maybe they are just defined to do some computation in forward function. Does that make sense to you? And is there a way to solve this problem?</p>
<p>The best way I can find is to use register_buffer. However, it seems that it has to be used when you defined the model.</p>

JuanFMontesinos: <p>hmmm in theory when you register a tensor inside a nn.Module it does internally calls register_buffer.</p>
<p>if you use a debugger (for example in pycharm, spyder or ipdb) to stop the execution in the exception. You will be able to see which tensor is at cpu.</p>
<p>BTW are you sure it’s not about the input tensors?<br>
That error can be thrown whether because the model is allocated at cuda but the input is not or the other way around.<br>
Without seeing the code it’s difficult to provide more clue.</p>
<p>The only exception in which calling model.cuda() would map tensors to gpu is if any parameter isn’t properly registered as a nn.parameter/buffer.</p>
<p>This happens, for example, if you create an ordinary list/tuple/dictionary of tensors/layers. The recursive allocator only explores nn.Modules.</p>
<p>That is why pytorch provide their own list-like object and dict-like object.</p>

Zeyu: <p>Hi, I try to debug it and find where the problem occurs. I copy a small part of the code to explain the situation. In the function _permute, they define a tensor using</p>
<pre><code class="lang-python">logabsdet = torch.zeros(batch_size)
</code></pre>
<p>After I modify the code to</p>
<pre><code class="lang-python">logabsdet = torch.zeros(batch_size, device = inputs.device)
</code></pre>
<p>The code works. Is there anyway to solve this problem without modifying the model since in real case I am using a much larger model and it may not be very convenient to modify all of them in this way. <img src="https://discuss.pytorch.org/images/emoji/apple/pensive.png?v=9" title=":pensive:" class="emoji" alt=":pensive:"></p>
<pre><code class="lang-python">class Permutation(Transform):
    """Permutes inputs on a given dimension using a given permutation."""

    def __init__(self, permutation, dim=1):
        if permutation.ndimension() != 1:
            raise ValueError("Permutation must be a 1D tensor.")
        if not is_positive_int(dim):
            raise ValueError("dim must be a positive integer.")

        super().__init__()
        self._dim = dim
        self.register_buffer("_permutation", permutation)

    @property
    def _inverse_permutation(self):
        return torch.argsort(self._permutation)

    @staticmethod
    def _permute(inputs, permutation, dim):
        if dim &gt;= inputs.ndimension():
            raise ValueError("No dimension {} in inputs.".format(dim))
        if inputs.shape[dim] != len(permutation):
            raise ValueError(
                "Dimension {} in inputs must be of size {}.".format(
                    dim, len(permutation)
                )
            )
        batch_size = inputs.shape[0]
        outputs = torch.index_select(inputs, dim, permutation)
        logabsdet = torch.zeros(batch_size)
        return outputs, logabsdet

    def forward(self, inputs, context=None):
        return self._permute(inputs, self._permutation, self._dim)

    def inverse(self, inputs, context=None):
        return self._permute(inputs, self._inverse_permutation, self._dim)
</code></pre>

Zeyu: <p>Hmm… I do find one way to do this by setting the default tensor type to cuda. But this does not seem like a decent way…</p>

JuanFMontesinos: <p>Hmm I’m afraid there is not.</p>
<p>Once again I doubt that if the code is properly done it can fall in issues like that. I imagine that original authors also used a gpu. Therefore it should be somehow adapted to a gpu allocation.</p>
<p>Anyway if you plan to use that code, reformating to be adapted to cpu/gpu/multi-gpu is not a loss of time.</p>
<p>In the end, you are creating a new tensor there (which is the only case in which you have to choose allocation device)</p>

Zeyu: <p>Hi, I also once assumed they should be adapted to a gpu allocation. Maybe it’s because I  miss something. Anyway, the code is working now. In future, modifying their code myself or asking the author directly might be a good idea.<br>
Thanks for your help!! <img src="https://discuss.pytorch.org/images/emoji/apple/smile.png?v=9" title=":smile:" class="emoji" alt=":smile:"></p>