RuntimeError: cuda runtime error (59)

kundan2510: <p>I am new to pytorch and tried to Run a seq2seq model. My code runs well for few batches (around 4 to 5) before I get the following error:<br>
…<br>
RuntimeError: cuda runtime error (59) : device-side assert triggered at /home/soumith/local/builder/wheel/pytorch-src/torch/lib/THC/generic/THCStorage.cu:76</p>
<p>When I enable cudnn, I get the following error:<br>
…<br>
cudnn.rnn.forward(self, input, hx, weight, output, hy)<br>
File “/u/kumarkun/.local/lib/python2.7/site-packages/torch/backends/cudnn/rnn.py”, line 241, in forward<br>
w.zero_()<br>
RuntimeError: cuda runtime error (59) : device-side assert triggered at /home/soumith/local/builder/wheel/pytorch-src/torch/lib/THC/generic/THCTensorMath.cu:26</p>
<p>Strangely, the source code line-number that causes the error is different for different runs but<br>
Has anyone encountered such an issue before? Is this a known issue and is there an easy way to fix this?</p>
<p>I would greatly appreciate any pointers.</p>

kundan2510: <p>I had an issue with the embedding layer. I had an index which was greater than the vocab-size. Fixing that resolved the issue. I still don’t understand how the error shown is related to that.</p>

smth: <p>Because of the asynchronous nature of cuda, the assert might not point to a full correct stack trace pointing to where the assert was triggered from.</p>
<p>if you run the program with <code>CUDA_LAUNCH_BLOCKING=1 python script.py</code><br>
this will help get a more exact stack trace</p>

ajbrock: <p>So I ran into the same error message for a similar reason just now, and I think it makes sense to add in some error handling to catch it. Feel free to skip to the <strong>TLDR</strong> if you don’t have care for STORYTIME.</p>
<p>STORY TIME!</p>
<p>I recently re-installed my NVIDIA drivers (someone in the lab broke the server trying to install them, and for the life of me I have no idea what went wrong) and managed to compile the latest PyTorch build from source (which previously had thrown errors related to CUDA, suggesting that PyTorch unsurprisingly doesn’t compile if you’re using old drivers). Yay!</p>
<p>Then I went to run a little piece of code that’s basically just GPU-accelerated numpy, and which I had run about a thousand times previously without error, and it starts throwing the device-side assert error 59. The strangest thing about this was that it was throwing the error on an allocation call–the exact line was <code>X=torch.cuda.HalfTensor([5,4,3])</code>.</p>
<p>It turned out the issue was in the line above, where I call index_select on a different tensor using a variable that can vary widely–the issue was that I clamped my indices incorrectly:</p>
<p><code>out = inp.index_select(2, torch.clamp(index, 0, inp.size()[-1])).</code></p>
<p>Which should obviously be clamped to <code>0, inp.size()[-1] - 1</code> since python is zero-indexed. (Sidenote, switching between python and MATLAB daily is awful). Anyhow, there’s two interesting things about this–the first is that while using the previous drivers (361.45) this did <em>not</em> ever throw any errors, and I was able to incorrectly index_select these tensors without issue (I know for certain that the “index” value was able to go above the size of that axis, so it’s not that I wasn’t hitting that use-case), and the second is that the error only became apparent <em>after</em> the calls to index_select; i.e. I’m able to cause this error, but it won’t show up until I try to do something else, at which point it shows up as a cuda runtime error.</p>
<p><strong>TL; DR:</strong> I think it makes sense to add some index checking in index_select that says “if you’re trying to select a value along this index which is greater than the length of the index minus one, raise an error,” or clamp it if there’s some other intended behavior. Otherwise it throws an assert error <em>after</em> the line that actually causes the error.</p>

smth: <p><a class="mention" href="/u/ajbrock">@ajbrock</a> the fundamental problem with throwing more informative errors is that they are not allowed by CUDA. CUDA can only do device asserts, and wont even tell you what the triggered assert it. We are constrained by this to make stuff more user-friendly.</p>

ajbrock: <p>I think it makes sense not to try and catch all the CUDA-side errors, but would it be possible to institute a check in the index_select function itself (similar to the fixes for <a href="https://github.com/pytorch/pytorch/pull/905/files" rel="nofollow noopener">the recent slicing issues</a>, maybe) that ensure that users don’t try to grab an index that’s not in the array? I.e. if X.size()=[5,5,5] and you call X.index_select(2,5) (or more egregiously X.index_select(2,7)) it raises an error.</p>
<p>Or is the tensor.index_select function just something that’s hard-baked into CUDA that PyTorch doesn’t actually wrap? I might be misunderstanding how it’s put together.</p>

apaszke: <p>What’s <code>index_select(2, 5)</code>? It expects a Tensor argument as the second argument</p>

ajbrock: <p>Sorry, I was just trying to do that as an example of indexing outside the allowable array size. Here’s a better example:</p>
<p>X = torch.randn(5,5,5)<br>
y = torch.LongTensor([5])<br>
X.index_select(2,y)</p>
<p>returns RuntimeError: out of range at /data/users/soumith/miniconda2/conda-bld/pytorch-0.1.7_1485444530918/work/torch/lib/TH/generic/THTensor.c:379</p>
<p>but if I run<br>
X = torch.randn(5,5,5).cuda()<br>
y = torch.LongTensor([5]).cuda()<br>
X.index_select(2,y) # Works, but should not<br>
X.index_select(2,y+5) # Also works, but really should not</p>
<p>On the version I installed off conda this allows me to grab random junk (presumably it’s grabbing things from nearby memory locations) but it doesn’t throw any errors. On the version I compiled yesterday this may or may not throw a device-side assert error (the GPUs are all tied up on that machine so I can’t properly test it atm) but in the case I was previously encountering it was <em>not</em> throwing that assert error until after I had done the bad indexing.</p>
<p>Is it not possible to insert a value check in the index_select function to ensure that the elements of the second argument are all less than the size of the indexed tensor along that axis?</p>

apaszke: <p>It’s impossible, because we’d have to execute max and min over the whole tensor, synchronize the CPU with the GPU, and execute the index_select kernel only if the values are correct. It would be too slow.</p>

ajbrock: <p>Got it, that makes sense.</p>

11129: <p>This help me, thanks.</p>

euwern: <p>same here, thanks for the hint… I was converting some code from torch to pytorch. Lua is 1 based index but Python is 0 based index. My dataset was created for lua hence it is off by one.</p>

gleb: <p>I had this error when have created the model with the wrong number of classes:</p>
<p><code>model=resnet.resnet34(num_classes=2)</code>, whereas there were 4 possible classes.  Setting <code>num_classes=4</code> fixed the problem.</p>

miladiouss: <p>Similar to gleb , I faced this error when my class labels were wrong.<br>
I had 3 classes but the class indices were not 0, 1, 2 and instead it was 3, 5, 6.</p>

Fengzi: <p>I faced with the problem that is very similar: ‘reduce failed to synchronize: device-side assert triggered’,and the problem occurred in the circumstance that I used the BCEloss.finally I found the cause that my output is a mat consists of the elements that is negative numbers,but the implement of BCEloss is about log(),which has no meaning in the negative area, thus I add a sigmoid to constrain the output between 0-1and my problem is solved.</p>

jdenim: <aside class="quote no-group" data-username="gleb" data-post="13" data-topic="750">
<div class="title">
<div class="quote-controls"></div>
<img loading="lazy" alt="" width="24" height="24" src="https://discuss.pytorch.org/letter_avatar_proxy/v4/letter/g/f4b2a3/48.png" class="avatar"> gleb:</div>
<blockquote>
<p>num_classes</p>
</blockquote>
</aside>
<ol>
<li>How did you check the class indices?<br>
and 2) how did you change the class indices from 3,5,6 to 0,1,2?</li>
</ol>
<p>Thanks</p>

m0nster: <p>I am getting the same error. I have 10 classes in my dataset. I have seen that labels are in the in the range of 1 to 10 instead or 0 to 9. How do I fix that. <a class="mention" href="/u/miladiouss">@miladiouss</a> <a class="mention" href="/u/euwern">@euwern</a></p>

tom: <p>I’m not sure if I’m missing the obvious, but how about subtracting 1 from the labels?</p>
<p>Best regards</p>
<p>Thomas</p>

m0nster: <p>Yes <a class="mention" href="/u/tom">@tom</a>. It will work if we subtract 1 from labels. but my question is different.<br>
I have done another classification problem and in that the labels started from 0.<br>
Now I am doing another classification problem and in here the labels start from 1.<br>
Why is this happening? and how to prevent that?</p>

tom: <p>Well, in data preparation, you would map whatever classes you have to <code>0 ... number of classes-1</code>, whether that is what you start with or you have words as classes or some otherwise numbered classes. One example of how to do this in Python is given in Jeremy Howards fast.ai classes when he does language models.</p>