Loss becoms NaN. But, in cpu mode, loss is calculated normally

Soohwan_Kim: <p>I made a speech recognition Transformer.<br>
But, After the first iteration, the loss becomes NaN.</p>
<p>Another strange thing, however, is that loss is calculated normally in CPU mode.</p>
<p>I will attach the address of GitHub with my code below, my test code and test result.</p>
<ul>
<li>
<p>Transformer source code: <a href="https://github.com/sooftware/KoSpeech/blob/latest/kospeech/models/transformer/model.py" class="inline-onebox" rel="noopener nofollow ugc">KoSpeech/model.py at latest · sooftware/KoSpeech · GitHub</a></p>
</li>
<li>
<p>My Test Code</p>
</li>
</ul>
<pre><code class="lang-auto"># Copyright (c) 2020, Soohwan Kim. All rights reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import torch
import torch.nn as nn

from kospeech.model_builder import build_transformer

batch_size = 4
seq_length = 200
target_length = 10
input_size = 80

cuda = torch.cuda.is_available()
device = torch.device('cuda' if cuda else 'cpu')

transformer = build_transformer(
    num_classes=10,
    d_model=16,
    d_ff=32,
    num_heads=2,
    input_dim=input_size,
    num_encoder_layers=3,
    num_decoder_layers=2,
    extractor='vgg',
    dropout_p=0.1,
    device=device,
    pad_id=0,
    sos_id=1,
    eos_id=2,
    joint_ctc_attention=False,
    max_length=10,
)

criterion = nn.CrossEntropyLoss(ignore_index=0, reduction='mean')
optimizer = torch.optim.Adam(transformer.parameters(), lr=1e-04)

for i in range(10):
    inputs = torch.FloatTensor(batch_size, seq_length, input_size).to(device)
    input_lengths = torch.LongTensor([seq_length, seq_length - 10, seq_length - 20, seq_length - 30])
    targets = torch.LongTensor([[1, 3, 3, 3, 3, 3, 4, 5, 6, 2],
                                [1, 3, 3, 3, 3, 3, 4, 5, 2, 0],
                                [1, 3, 3, 3, 3, 3, 4, 2, 0, 0],
                                [1, 3, 3, 3, 3, 3, 4, 2, 0, 0]]).to(device)

    outputs, _, _ = transformer(inputs, input_lengths, targets)
    loss = criterion(outputs.contiguous().view(-1, outputs.size(-1)), targets[:, 1:].contiguous().view(-1))
    loss.backward()
    optimizer.step()
    print(loss)

</code></pre>
<ul>
<li>Result in CUDA mode</li>
</ul>
<pre><code class="lang-auto">tensor(10.6171, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
tensor(nan, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
tensor(nan, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
tensor(nan, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
tensor(nan, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
tensor(nan, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
tensor(nan, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
tensor(nan, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
tensor(nan, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
tensor(nan, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
</code></pre>
<ul>
<li>Result in CPU mode</li>
</ul>
<pre><code class="lang-auto">tensor(12.8601, grad_fn=&lt;MeanBackward0&gt;)
tensor(12.5969, grad_fn=&lt;MeanBackward0&gt;)
tensor(12.4775, grad_fn=&lt;MeanBackward0&gt;)
tensor(10.8609, grad_fn=&lt;MeanBackward0&gt;)
tensor(11.9296, grad_fn=&lt;MeanBackward0&gt;)
tensor(9.9925, grad_fn=&lt;MeanBackward0&gt;)
tensor(11.5225, grad_fn=&lt;MeanBackward0&gt;)
tensor(9.3546, grad_fn=&lt;MeanBackward0&gt;)
tensor(11.4693, grad_fn=&lt;MeanBackward0&gt;)
tensor(9.2175, grad_fn=&lt;MeanBackward0&gt;)
</code></pre>
<p>Please help me!</p>

KFrank: <p>Hi Soohwan!</p>
<aside class="quote no-group quote-modified" data-username="Soohwan_Kim" data-post="1" data-topic="110437" data-full="true">
<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/soohwan_kim/48/30165_2.png" class="avatar"> Soohwan_Kim:</div>
<blockquote>
<p>After the first iteration, the loss becomes NaN.</p>
<p>Another strange thing, however, is that loss is calculated normally in CPU mode.</p>
<pre><code class="lang-auto">    inputs = torch.FloatTensor(batch_size, seq_length, input_size).to(device)
...
    outputs, _, _ = transformer(inputs, input_lengths, targets)
</code></pre>
</blockquote>
</aside>
<p>If I am reading your code correctly, <code>inputs</code> (the tensor you pass into your<br>
<code>transformer</code>) is uninitialized.  This could definitely cause the problems you<br>
see.</p>
<aside class="quote no-group">
<blockquote>
<ul>
<li>Result in CUDA mode</li>
</ul>
<pre><code class="lang-auto">tensor(10.6171, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
tensor(nan, device='cuda:0', grad_fn=&lt;MeanBackward0&gt;)
...
</code></pre>
<ul>
<li>Result in CPU mode</li>
</ul>
<pre><code class="lang-auto">tensor(12.8601, grad_fn=&lt;MeanBackward0&gt;)
tensor(12.5969, grad_fn=&lt;MeanBackward0&gt;)
...
</code></pre>
</blockquote>
</aside>
<p>It is true that your cuda result becomes <code>nan</code> after only one <code>optimizer.step()</code><br>
iteration.  But even before your first iteration, your cuda and gpu results differ.<br>
This could certainly be due to your uninitialized <code>inputs</code>.  (It could also be due<br>
to differing random initialization of the weights in <code>transformer</code>, depending on<br>
how it is constructed.)  But in any event, you should start by tracking down<br>
this difference.  You should be able to get the results (including, among other<br>
things, the <code>loss</code>) returned by your cuda computation to agree (up to some<br>
reasonable round-off error) with those of your gpu computation, at least before<br>
round-off error has begun to accumulate over the course of a number of<br>
iterations.</p>
<p>Best.</p>
<p>K. Frank</p>

Soohwan_Kim: <p>Hi! K. Frank!</p>
<p>Thanks for your answer.<br>
But, It looks like that in the test file, but it actually looks like that when train with speech files.<br>
I think there are other problems, do you have any idea?</p>