C++ seeming memory deallocation of a temporary variable

serhii: <p>Hello!</p>
<p>By implementing some c++ extensions I noticed that if I transfer GPU tensor to CPU using one-liner (<code>auto my_tensor_ptr = my_tensor.cpu().data_ptr&lt;float&gt;();</code>), usually what happens is that this pointer becomes some kind of a dangling pointer and data indexed via brackets operator <code>[]</code> is not valid anymore. It can be easily fixed by introducing a temporary variable:</p>
<pre><code class="lang-cpp">auto my_tensor_cpu = my_tensor.cpu();
auto my_tensor_ptr = my_tensor_cpu.data_ptr&lt;float&gt;();
</code></pre>
<p>Nevertheless, I sill don’t understand why does this deallocation occurs.<br>
Any explanation will be highly appreciated.</p>

albanD: <p>Hi,</p>
<p>This is because the data returned by <code>data_ptr&lt;&gt;()</code> is only valid as long as the original Tensor exists.<br>
But here the CPU tensor goes out of scope so the the data_ptr becomes invalid. This is expected.</p>

serhii: <p>Hi,</p>
<p>Yes, this is clear.<br>
But why does it cease to exist? Does it go out of its scope? What is its scope? By all means, I am not a c++ expert, but the PyTorch code is so entangled I can’t even find where the <code>cpu</code> method is implemented (maybe <a href="https://github.com/pytorch/pytorch/blob/791347642b637ca5769998f5d95f597cb8f81d18/aten/src/ATen/core/TensorMethods.h#L32" rel="nofollow noopener">here</a>) to check how this tensor is created.</p>

albanD: <p>This would actually be the same in python. If you create an object in the middle of the line. It will be gone by the end of it if you don’t reference it.<br>
Here you create a Tensor when doing <code>my_tensor.cpu()</code> (let’s call it foo). Then this object is used to call <code>.data_ptr&lt;float&gt;()</code> on it. The the result of that new function (a float* ) is saved into your variable <code>my_tensor_ptr</code>. At this point, nothing references foo anymore. So foo is de-allocated.</p>

serhii: <p>I think it is not exactly as in Python, because in Python it may be gced or may be not but it looks like in c++ it is <a href="https://en.cppreference.com/w/cpp/language/lifetime" rel="nofollow noopener">guaranteed</a><code>(All temporary objects are destroyed as the last step in evaluating the full-expression that (lexically) contains the point where they were created)</code> to be destroyed. So, is the object returned by <code>cpu()</code> method allocated in the stack? I assume if it was dynamically created, some sort of memory leak would have occurred.<br>
Still, it feels like created cpu tensor should contain a week reference to the created pointer to prevent it from deallocation and this would allow that one-liner.</p>

albanD: <p>This is not possible to do. <code>data_ptr&lt;float&gt;()</code> returns just a raw pointer to float. We cannot attach any reference or anything to it.<br>
It is the same as if you get a raw pointer to an object in cpp and then delete the object. The raw pointer never keeps the object alive.</p>
<p>Note that in cpython, the life of objects is refcounted and so (unless you create refcycle which are very rare), they are destroyed as soon as they are not referenced anymore.</p>

zzsunshine: <p>Hello!<br>
If I want to access each element in a cuda float tensor,  C++ code " tensors[0].data_ptr();" will return the first address, we expected *(tensors[0].data_ptr()) will return the data in the first address, but segmentation fault happens.<br>
Any explanation will be appreciated.</p>

albanD: <p>Hi,</p>
<p>The GPU data can only be accessed from a GPU function. Regular c++ code can only access data in RAM.<br>
You will need to write a GPU kernel to work with GPU data.</p>

zzsunshine: <p>Thanks for your quick help!  And could I move the GPU data to CPU using .cpu and then access each element in the tensor? I tried tensor[0].cpu().data but it failed with "tensors.c10::ArrayRef::operator[]<a>at::Tensor</a>(0ul).at::Tensor::cpu’ does not have class type "</p>

albanD: <p>You will need to use the same <code>data_ptr&lt;float&gt;()</code> call for this to work.</p>

zzsunshine: <p>I tried this as well, failed with similar error.</p>

albanD: <p>I’m not sure you can do <code>[0]</code> on a c++ tensor directly. I think you have to use <code>.index()</code>.<br>
Doing the same thing without the indexing should work no?</p>

zzsunshine: <p>Thanks. I am going to use kernel to implement and appreciate your help.</p>