Skip to content
Advertisement

How to understand creating leaf tensors in PyTorch?

From PyTorch documentation:

JavaScript

But why are e and f leaf Tensors, when they both were also cast from a CPU Tensor, into a Cuda Tensor (an operation)?

Is it because Tensor e was cast into Cuda before the in-place operation requires_grad_()?

And because f was cast by assignment device="cuda" rather than by method .cuda()?

Advertisement

Answer

When a tensor is first created, it becomes a leaf node.

Basically, all inputs and weights of a neural network are leaf nodes of the computational graph.

When any operation is performed on a tensor, it is not a leaf node anymore.

JavaScript

requires_grad_() is not an operation in the same way as cuda() or others are.
It creates a new tensor, because tensor which requires gradient (trainable weight) cannot depend on anything else.

JavaScript

Also, detach() operation creates a new tensor which does not require gradient:

JavaScript

In the last example we create a new tensor which is already on a cuda device.
We do not need any operation to cast it.

JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement