JIT Tracing fails with basic EmbeddingBag when changing devices

then4p: <p>For saving and distributing models we use JIT and trace our models with example input. We use tracing instead of scripting because we use Huggingface Transformers, which recommends tracing.</p>
<p>We encountered issues at multiple points, usually in combination with reshaping. There was apparently a bug with this a couple years ago, but we could still reproduce it with a minimal EmbeddingBag example.</p>
<pre><code class="lang-auto">import tempfile

import torch
from torch import nn

folder = tempfile.mkdtemp()

my_model = nn.EmbeddingBag(5, 10).to('cuda:0')
my_input = torch.tensor([[1, 2], [1, 2]]).to('cuda:0')

my_model(my_input)

traced_model = torch.jit.trace(my_model, my_input)
traced_model.save(f'{folder}/model_jit.pt')

model_jit_loaded = torch.jit.optimize_for_inference(
    torch.jit.load(f'{folder}/model_jit.pt',
                   map_location='cpu').eval())

model_jit_loaded(my_input.to('cpu'))
</code></pre>
<p>This fails with the following error:</p>
<pre><code class="lang-auto">Traceback (most recent call last):
  File "/home/user/repos/team/repo/_scripts/trace_test.py", line 20, in &lt;module&gt;
    model_jit_loaded(my_input.to('cpu'))
  File "/home/user/repos/team/repo/.venv/lib/python3.9/site-packages/torch/nn/modules/module.py", line 1194, in _call_impl
    return forward_call(*input, **kwargs)
RuntimeError: The following operation failed in the TorchScript interpreter.
Traceback of TorchScript, serialized code (most recent call last):
  File "code/__torch__/torch/nn/modules/sparse.py", line 15, in forward
    offsets = torch.arange(0, _1, annotate(number, _2), dtype=4, layout=None, device=torch.device("cuda:0"), pin_memory=False)
    input0 = torch.reshape(input, [-1])
    _3, _4, _5, _6 = torch.embedding_bag(weight, input0, offsets, False, 1, False, None, False, None)
                     ~~~~~~~~~~~~~~~~~~~ &lt;--- HERE
    return _3

Traceback of TorchScript, original code (most recent call last):
/home/user/repos/team/repo/.venv/lib/python3.9/site-packages/torch/nn/functional.py(2392): embedding_bag
/home/user/repos/team/repo/.venv/lib/python3.9/site-packages/torch/nn/modules/sparse.py(387): forward
/home/user/repos/team/repo/.venv/lib/python3.9/site-packages/torch/nn/modules/module.py(1182): _slow_forward
/home/user/repos/team/repo/.venv/lib/python3.9/site-packages/torch/nn/modules/module.py(1194): _call_impl
/home/user/repos/team/repo/.venv/lib/python3.9/site-packages/torch/jit/_trace.py(976): trace_module
/home/user/repos/team/repo/.venv/lib/python3.9/site-packages/torch/jit/_trace.py(759): trace
/home/user/repos/team/repo/_scripts/trace_test.py(13): &lt;module&gt;
RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument offsets in method wrapper___embedding_bag_forward_only)

</code></pre>
<p>Is there a fix or are we doing something wrong in general?</p>

ptrblck: <p>Based on your code it seems you are tracing the model on the GPU first and try to move it to the CPU later, which seems to cause the issue.<br>
Would it be possible to trace and export the model on the same device?</p>

then4p: <p>Yes, if we ran it on the same device the code would work. We want to be able to train our networks on GPUs and serve them on CPUs though. We thought that was possible with JIT trace and it’s a requirement for our orchestration.</p>
<p>For tracing, we thought it’s a bad practice to move tensors around on devices in forward steps, which is exactly why this built in model fails.</p>
<pre><code class="lang-auto">offsets = torch.arange(0, _1, annotate(number, _2), dtype=4, layout=None, 
                       device=torch.device("cuda:0"), pin_memory=False)
input0 = torch.reshape(input, [-1])
</code></pre>
<p>This code looks supsiciously like something that would cause this to happen if we did it in our forward step, but it happens in the builtin EmbeddingBag.</p>
<p>With Huggingface Transformers we can freely move onto different instances after tracing, and we thought this was the point of having traced models.</p>

ptrblck: <p>Yes, I think you’ve narrowed down the offending line of code, which seems to bake in the used device in <a href="https://github.com/pytorch/pytorch/blob/166117e050bb9484dae3d0da77b7e2e77b76e9ba/torch/nn/functional.py#L2355">this line of code</a>. The general recommendation was to use <code>torch.jit.script</code> as it would also allow to capture if conditions etc., but note that <code>TorchScript</code> is also in maintenance mode and won’t get any new features anymore.</p>

then4p: <aside class="quote no-group" data-username="ptrblck" data-post="2" data-topic="174719">
<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/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p>Would it be possible to trace and export the model on the same device?</p>
</blockquote>
</aside>
<p>Generally yes, but tracing without a baked in device would be preferable. We also have instances with multiple GPUs for inference and only having ‘cpu’ and ‘cuda:0’ would be limiting there.</p>
<blockquote>
<p>but note that <code>TorchScript</code> is also in maintenance mode</p>
</blockquote>
<p>Good to know, and as I’ve mentioned above, because we use the Transformers library, not really an option anyway.</p>
<p>Do I understand correctly, that exporting models without baking the device in is only possible in ONNX then?</p>
<p>Just as a quick info on why we would have liked to avoid going back to ONNX: We came from ONNX and moved to jit.trace because we had some problems with packed-padded-sequences in RNNs which were sorted unexpectedly during export and were destroying our internal structure. Plus jit could handle **kwargs or dictionaries in the forward step which is a very nice feature.</p>
<p>In any case thank you for the fast and helpful replies!</p>

ptrblck: <p>No, <code>torch.jit.script</code> will also record the <code>.device</code> attribute (and other control-flow) and should work as seen here:</p>
<pre><code class="lang-python">my_model = nn.EmbeddingBag(5, 10).to('cuda:0')
my_input = torch.tensor([[1, 2], [1, 2]]).to('cuda:0')

# works
out = my_model(my_input)

# trace
traced_model = torch.jit.trace(my_model, my_input)
# works
out = traced_model(my_input)
# breaks
traced_model.cpu()
traced_model(my_input.cpu())
# RuntimeError: Expected all tensors to be on the same device, but found at least two devices, cpu and cuda:0! (when checking argument for argument offsets in method wrapper_CUDA___embedding_bag)

# script
my_model = nn.EmbeddingBag(5, 10).to('cuda:0')
my_input = torch.tensor([[1, 2], [1, 2]]).to('cuda:0')
scripted_model = torch.jit.script(my_model, my_input)
# works
out = scripted_model(my_input)
# works
scripted_model.cpu()
out = scripted_model(my_input.cpu())
</code></pre>
<p>However, I don’t know if your model requires <code>trace</code> and will fail otherwise.</p>

C_H: <aside class="quote no-group" data-username="ptrblck" data-post="4" data-topic="174719">
<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/ptrblck/48/1823_2.png" class="avatar"> ptrblck:</div>
<blockquote>
<p><code>TorchScript</code></p>
</blockquote>
</aside>
<p>(in colab with then4p)</p>
<p>Yes it requires tracing, sadly on multiple occasions. The example we gave is just a very condensed part where we found the problem for this forum discussion. We include multiple external models (which can’t use scripting) and internal operations such as reshape and repeat (which can’t use tracing as apparent for EmbeddingBag).</p>
<p>Did we get that right, that the entire <code>TorchScript</code> is not in development any more, including scripting and tracing? So in the future there will be only ONNX for exporting and serializing models?</p>
<p>For the above reasons if this is the case we will probably sadly have to switch back to ONNX then.</p>

ptrblck: <aside class="quote no-group" data-username="C_H" data-post="7" data-topic="174719">
<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/c_h/48/58335_2.png" class="avatar"> C_H:</div>
<blockquote>
<p>Did we get that right, that the entire <code>TorchScript</code> is not in development any more, including scripting and tracing?</p>
</blockquote>
</aside>
<p>Yes, based on <a href="https://discuss.pytorch.org/t/consequences-of-pytorch-2-0-on-libtorch/167576/2">this message</a> from a code owner.</p>
<aside class="quote no-group" data-username="C_H" data-post="7" data-topic="174719">
<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/c_h/48/58335_2.png" class="avatar"> C_H:</div>
<blockquote>
<p>So in the future there will be only ONNX for exporting and serializing models?</p>
</blockquote>
</aside>
<p>I don’t know what the desired export path will be.</p>
<p>EDIT: <a href="https://pytorch.org/get-started/pytorch-2.0/#inference-and-export">here</a> <code>torch.export</code> is mentioned for the 2.0 stack, which seems to be the planned approach.</p>