RuntimeError: cuda runtime error (59) : device-side assert triggered , 2 different places please help me understand

barakb: <p>Hi guys, I’m getting this kind of error in two places:"RuntimeError: cuda runtime error (59) : device-side assert triggered ".</p>
<ol>
<li>when calculating accuracy:</li>
</ol>
<pre><code class="lang-auto">      _, pred = outputs.topk(1, 1, True)
      pred = pred.t()
      correct = pred.eq(targets.view(1, -1))
      n_correct_elems = correct.float().sum().data[0]
</code></pre>
<p>Tried to do this:</p>
<pre><code class="lang-auto">       n_correct_elems = correct.float().sum().item
</code></pre>
<p>still didn’t help the exect error is:</p>
<blockquote>
<p>/opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THCUNN/ClassNLLCriterion.cu:105: void cunn_ClassNLLCriterion_updateOutput_kernel(Dtype *, Dtype *, Dtype *, long *, Dtype *, int, int, int, int, long) [with Dtype = float, Acctype = float]: block: [0,0,0], thread: [1,0,0] Assertion <code>t &gt;= 0 &amp;&amp; t &lt; n_classes</code> failed.<br>
THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THC/generated/…/THCReduceAll.cuh line=317 error=59 : device-side assert triggered<br>
Traceback (most recent call last):<br>
File “main.py”, line 141, in <br>
train_logger, train_batch_logger)<br>
File “/path/train.py”, line 37, in train_epoch<br>
acc = calculate_accuracy(outputs, targets)<br>
File “/path/utils.py”, line 58, in calculate_accuracy<br>
n_correct_elems = correct.float().sum().item()<br>
RuntimeError: cuda runtime error (59) : device-side assert triggered at /opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THC/generated/…/THCReduceAll.cuh:317</p>
</blockquote>
<p>I wanted to go forward, so I skipped this function (just entered a number), and then I got, that he is falling in csv.writer (I checked the path for the file):</p>
<p>the exact error log is:</p>
<pre><code class="lang-auto">/opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THCUNN/ClassNLLCriterion.cu:105: void cunn_ClassNLLCriterion_updateOutput_kernel(Dtype *, Dtype *, Dtype *, long *, Dtype *, int, int, int, int, long) [with Dtype = float, Acctype = float]: block: [0,0,0], thread: [1,0,0] Assertion `t &gt;= 0 &amp;&amp; t &lt; n_classes` failed.
THCudaCheck FAIL file=/opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THC/generic/THCTensorCopy.cpp line=70 error=59 : device-side assert triggered
Exception ignored in: &lt;bound method _DataLoaderIter.__del__ of &lt;torch.utils.data.dataloader._DataLoaderIter object at 0x7f80c09ac748&gt;&gt;
Traceback (most recent call last):
  File "path/anaconda3/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 399, in __del__
    self._shutdown_workers()
  File "path/anaconda3/lib/python3.6/site-packages/torch/utils/data/dataloader.py", line 378, in _shutdown_workers
    self.worker_result_queue.get()
  File "path/anaconda3/lib/python3.6/multiprocessing/queues.py", line 337, in get
    return _ForkingPickler.loads(res)
  File "path/anaconda3/lib/python3.6/site-packages/torch/multiprocessing/reductions.py", line 151, in rebuild_storage_fd
    fd = df.detach()
  File "path/anaconda3/lib/python3.6/multiprocessing/resource_sharer.py", line 57, in detach
    with _resource_sharer.get_connection(self._id) as conn:
  File "path/anaconda3/lib/python3.6/multiprocessing/resource_sharer.py", line 87, in get_connection
    c = Client(address, authkey=process.current_process().authkey)
  File "path/anaconda3/lib/python3.6/multiprocessing/connection.py", line 493, in Client
    answer_challenge(c, authkey)
  File "path/anaconda3/lib/python3.6/multiprocessing/connection.py", line 737, in answer_challenge
    response = connection.recv_bytes(256)        # reject large message
  File "path/anaconda3/lib/python3.6/multiprocessing/connection.py", line 216, in recv_bytes
    buf = self._recv_bytes(maxlength)
  File "path/anaconda3/lib/python3.6/multiprocessing/connection.py", line 407, in _recv_bytes
    buf = self._recv(4)
  File "path/anaconda3/lib/python3.6/multiprocessing/connection.py", line 379, in _recv
    chunk = read(handle, remaining)
ConnectionResetError: [Errno 104] Connection reset by peer
Traceback (most recent call last):
  File "main.py", line 141, in &lt;module&gt;
    train_logger, train_batch_logger)
  File "path/train.py", line 55, in train_epoch
    'lr': optimizer.param_groups[0]['lr']
  File "path/utils.py", line 41, in log
    self.logger.writerow(write_values)
  File "path/anaconda3/lib/python3.6/site-packages/torch/tensor.py", line 57, in __repr__
    return torch._tensor_str._str(self)
  File "path/anaconda3/lib/python3.6/site-packages/torch/_tensor_str.py", line 256, in _str
    formatter = _Formatter(get_summarized_data(self) if summarize else self)
  File "path/anaconda3/lib/python3.6/site-packages/torch/_tensor_str.py", line 82, in __init__
    copy = torch.empty(tensor.size(), dtype=torch.float64).copy_(tensor).view(tensor.nelement())
RuntimeError: cuda runtime error (59) : device-side assert triggered at /opt/conda/conda-bld/pytorch_1535491974311/work/aten/src/THC/generic/THCTensorCopy.cpp:70
</code></pre>
<p>I must day the I debugged on the windows, and the program ran, now I’m running it on distance machine, and it’s killing me, every step different error, I’m not far from breaking down, please help.</p>
<p>Thanks.</p>

SimonW: <aside class="quote no-group" data-username="barakb" data-post="1" data-topic="27434">
<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/barakb/48/47322_2.png" class="avatar"> barakb:</div>
<blockquote>
<p>Assertion <code>t &gt;= 0 &amp;&amp; t &lt; n_classes</code> failed.</p>
</blockquote>
</aside>
<p>This is the error message. The target tensor you passed to nll_loss has some out-of-bound class.</p>
<p>You can’t recover from a CUDA device assert failure. This is a CUDA limitation. All you can do is fixing the bug and restart your process.</p>

barakb: <p>can you elaborate just  a bit, what does it means “out-of-bounds class” and what is the nll_loss (last one for curiosity), the sizes of each tensor were checked carefully, I’ll be happy for your help, because it’s seems that every step I’m getting this error , also in:</p>
<pre><code class="lang-auto"> targets = targets.to('cuda')
</code></pre>
<p>Edit, I checked again and it works on cpu with batch = 1, when batch &gt; 1, I get some similar error:<br>
“cur_target &gt;= 0 &amp;&amp; cur_target &lt; n_classes”<br>
One more thing, it crashes only after few steps… is this “hinting” about the problem.</p>
<p>Thanks.</p>

ptrblck: <p>The out of bounds error is thrown if you pass class indices, which are negative (<code>t &lt; 0</code>) or greater or equal to the number of classes (<code>t &gt;= n_classes</code>).<br>
E.g. if you have 5 classes, the class indices shoule be in <code>[0, 4]</code>.</p>
<p>Could you check your target tensor for these out of bounds values?</p>
<p><code>nn.NLLLoss</code> is the negative log likelihood loss which is used in the usual classification use case.<br>
<code>nn.CrossEntropyLoss</code> uses internally a <code>nn.LogSoftmax</code> layer and <code>nn.NLLLoss</code> to calculate the loss.</p>

barakb: <p>Thanks for your answer, But I still have some issues with that.<br>
I’m debugging on my windows (cpu only) , and I don’t have this problem, but when I take exactly the same files to  my machine on (unix  with 1 GPU) I do get this error, do you have any Idea , why is that happening?<br>
maybe the nn.CrossEntropyLoss.cuda() is acting differently?</p>
<p>Thanks.</p>

ptrblck: <p>That’s a bit strange indeed!<br>
Could you load all your target values and check for the value range?<br>
<code>torch.unique</code> might be helpful or just a comparison.</p>
<p>If you don’t find any out of bounds values, would it be possible to provide the target tensor, i.e. upload it somewhere? I would like to have a look at it, as I would like to exclude a possible silent bug on the CPU side.</p>

barakb: <p>After printing the target I see I have out of bound values.<br>
I’ll go figure out why</p>

sunshinesjw1: <p>Continuing the discussion from <a href="https://discuss.pytorch.org/t/runtimeerror-cuda-runtime-error-59-device-side-assert-triggered-2-different-places-please-help-me-understand/27434/3">RuntimeError: cuda runtime error (59) : device-side assert triggered , 2 different places please help me understand</a>:</p>
<p>Sorry,I have the same problem as you.Can I ask that why the problem of “it crashes only after few steps… is this “hinting” about the problem.” happened?And finally how you solve your problem.I am not far from breakind down,please give me some advices,thanks very much.</p>

Sivakumar_Rajendran: <p>I too face the same issue sporadically. I am using GPU. during first few runs, there are no issues but all of sudden receiving the error even there is no change in the code.</p>
<p>Can someone highlight how this can be fixed?</p>

ZiqiChai: <p>I found the total number of output class of multi-class claasifier is less than number of labels. That’s why I got this error.</p>
<p>As for me:<br>
number of  label:  0-31, 32 classes.<br>
number of output: 0-30, 31 classes.</p>

Mickey215: <p>I met the same issue with you.<br>
Did you solve it？<br>
Can you tell me how to solve it？<br>
Best wishes！</p>