PyTorch interview questions
10 questions with answers. 453 open jobs in India ask for PyTorch.
What's the difference between `reshape()` and `view()` in PyTorch?
torch.viewhas existed for a long time. It will return a tensor with the new shape. The returned tensor will share the underling data with the original tensor. See the documentation here.On the other hand, it seems that
torch.reshapehas been introduced recently in version 0.4. According to the document, this method willReturns a tensor with the same data and number of elements as input, but with the specified shape. When possible, the returned tensor will be a view of input. Otherwise, it will be a copy. Contiguous inputs and inputs with compatible strides can be reshaped without copying, but you should not depend on the copying vs. viewing behavior.
It means that
torch.reshapemay return a copy or a view of the original tensor. You can not count on that to return a view or a copy. According to the developer:if you need a copy use clone() if you need the same storage use view(). The semantics of reshape() are that it may or may not share the storage and you don't know beforehand.
Another difference is that
reshape()can operate on both contiguous and non-contiguous tensor whileview()can only operate on contiguous tensor. Also see here about the meaning ofcontiguous.From Stack Overflow: asked by Lifu Huang, answered by jdhao (CC BY-SA 4.0)
What does .contiguous() do in PyTorch?
There are a few operations on Tensors in PyTorch that do not change the contents of a tensor, but change the way the data is organized. These operations include:
narrow(),view(),expand()andtranspose()For example: when you call
transpose(), PyTorch doesn't generate a new tensor with a new layout, it just modifies meta information in the Tensor object so that the offset and stride describe the desired new shape. In this example, the transposed tensor and original tensor share the same memory:x = torch.randn(3,2) y = torch.transpose(x, 0, 1) x[0, 0] = 42 print(y[0,0]) # prints 42This is where the concept of contiguous comes in. In the example above,
xis contiguous butyis not because its memory layout is different to that of a tensor of same shape made from scratch. Note that the word "contiguous" is a bit misleading because it's not that the content of the tensor is spread out around disconnected blocks of memory. Here bytes are still allocated in one block of memory but the order of the elements is different!When you call
contiguous(), it actually makes a copy of the tensor such that the order of its elements in memory is the same as if it had been created from scratch with the same data.Normally you don't need to worry about this. You're generally safe to assume everything will work, and wait until you get a
RuntimeError: input is not contiguouswhere PyTorch expects a contiguous tensor to add a call tocontiguous().From Stack Overflow: asked by MBT, answered by Shital Shah (CC BY-SA 4.0)
What does `gather()` do in PyTorch in layman terms?
torch.gathercreates a new tensor from the input tensor by taking the values from each row along the input dimensiondim. The values intorch.LongTensor, passed asindex, specify which value to take from each 'row'. The dimension of the output tensor is same as the dimension of index tensor. Following illustration from the official docs explains it more clearly:(Note: In the illustration, indexing starts from 1 and not 0).
In first example, the dimension given is along rows (top to bottom), so for (1,1) position of
result, it takes row value from theindexfor thesrcthat is1. At (1,1) in source value is1so, outputs1at (1,1) inresult. Similarly for (2,2) the row value from the index forsrcis3. At (3,2) the value insrcis8and hence outputs8and so on.Similarly for second example, indexing is along columns, and hence at (2,2) position of the
result, the column value from the index forsrcis3, so at (2,3) fromsrc,6is taken and outputs toresultat (2,2)From Stack Overflow: asked by amitection, answered by Ritesh (CC BY-SA 4.0)
Understanding `torch.nn.Parameter()`
I will break it down for you. Tensors, as you might know, are multi dimensional matrices. Parameter, in its raw form, is a tensor i.e. a multi dimensional matrix. It sub-classes the Variable class.
The difference between a Variable and a Parameter comes in when associated with a module. When a Parameter is associated with a module as a model attribute, it gets added to the parameter list automatically and can be accessed using the 'parameters' iterator.
Initially in Torch, a Variable (which could for example be an intermediate state) would also get added as a parameter of the model upon assignment. Later on there were use cases identified where a need to cache the variables instead of having them added to the parameter list was identified.
One such case, as mentioned in the documentation is that of RNN, where in you need to save the last hidden state so you don't have to pass it again and again. The need to cache a Variable instead of having it automatically register as a parameter to the model is why we have an explicit way of registering parameters to our model i.e. nn.Parameter class.
For instance, run the following code -
import torch import torch.nn as nn from torch.optim import Adam class NN_Network(nn.Module): def __init__(self,in_dim,hid,out_dim): super(NN_Network, self).__init__() self.linear1 = nn.Linear(in_dim,hid) self.linear2 = nn.Linear(hid,out_dim) self.linear1.weight = torch.nn.Parameter(torch.zeros(in_dim,hid)) self.linear1.bias = torch.nn.Parameter(torch.ones(hid)) self.linear2.weight = torch.nn.Parameter(torch.zeros(in_dim,hid)) self.linear2.bias = torch.nn.Parameter(torch.ones(hid)) def forward(self, input_array): h = self.linear1(input_array) y_pred = self.linear2(h) return y_pred in_d = 5 hidn = 2 out_d = 3 net = NN_Network(in_d, hidn, out_d)Now, check the parameter list associated with this model -
for param in net.parameters(): print(type(param.data), param.size()) """ Output <class 'torch.FloatTensor'> torch.Size([5, 2]) <class 'torch.FloatTensor'> torch.Size([2]) <class 'torch.FloatTensor'> torch.Size([5, 2]) <class 'torch.FloatTensor'> torch.Size([2]) """Or try,
list(net.parameters())This can easily be fed to your optimizer -
opt = Adam(net.parameters(), learning_rate=0.001)Also, note that Parameters have require_grad set by default.
From Stack Overflow: asked by Vineet Pandey, answered by Astha Sharma (CC BY-SA 4.0)
Difference between "detach()" and "with torch.nograd()" in PyTorch?
tensor.detach()creates a tensor that shares storage with tensor that does not require grad. It detaches the output from the computational graph. So no gradient will be backpropagated along this variable.The wrapper
with torch.no_grad()temporarily set all therequires_gradflag to false.torch.no_gradsays that no operation should build the graph.The difference is that one refers to only a given variable on which it is called. The other affects all operations taking place within the
withstatement. Also,torch.no_gradwill use less memory because it knows from the beginning that no gradients are needed so it doesn’t need to keep intermediary results.Learn more about the differences between these along with examples from here.
From Stack Overflow: asked by user637140, answered by Anubhav Singh (CC BY-SA 4.0)
Why Pytorch officially use mean=[0.485, 0.456, 0.406] and std=[0.229, 0.224, 0.225] to normalize images?
Using the mean and std of Imagenet is a common practice. They are calculated based on millions of images. If you want to train from scratch on your own dataset, you can calculate the new mean and std. Otherwise, using the Imagenet pretrianed model with its own mean and std is recommended.
From Stack Overflow: asked by laridzhang, answered by zihaozhihao (CC BY-SA 4.0)
What does the parameter retain_graph mean in the Variable's backward() method?
@cleros is pretty on the point about the use of
retain_graph=True. In essence, it will retain any necessary information to calculate a certain variable, so that we can do backward pass on it.An illustrative example
Suppose that we have a computation graph shown above. The variable
dandeis the output, andais the input. For example,import torch from torch.autograd import Variable a = Variable(torch.rand(1, 4), requires_grad=True) b = a**2 c = b*2 d = c.mean() e = c.sum()when we do
d.backward(), that is fine. After this computation, the parts of the graph that calculatedwill be freed by default to save memory. So if we doe.backward(), the error message will pop up. In order to doe.backward(), we have to set the parameterretain_graphtoTrueind.backward(), i.e.,d.backward(retain_graph=True)As long as you use
retain_graph=Truein your backward method, you can do backward any time you want:d.backward(retain_graph=True) # fine e.backward(retain_graph=True) # fine d.backward() # also fine e.backward() # error will occur!More useful discussion can be found here.
A real use case
Right now, a real use case is multi-task learning where you have multiple losses that maybe be at different layers. Suppose that you have 2 losses:
loss1andloss2and they reside in different layers. In order to backprop the gradient ofloss1andloss2w.r.t to the learnable weight of your network independently. You have to useretain_graph=Trueinbackward()method in the first back-propagated loss.# suppose you first back-propagate loss1, then loss2 (you can also do the reverse) loss1.backward(retain_graph=True) loss2.backward() # now the graph is freed, and next process of batch gradient descent is ready optimizer.step() # update the network parametersFrom Stack Overflow: asked by jvans, answered by jdhao (CC BY-SA 4.0)
Evaluating pytorch models: `with torch.no_grad` vs `model.eval()`
TL;DR:
Use both. They do different things, and have different scopes.
with torch.no_grad- disables tracking of gradients inautograd.model.eval()changes theforward()behaviour of the module it is called upon- eg, it disables dropout and has batch norm use the entire population statistics
with torch.no_gradThe
torch.autograd.no_graddocumentation says:Context-manager that disabled [sic] gradient calculation.
Disabling gradient calculation is useful for inference, when you are sure that you will not call
Tensor.backward(). It will reduce memory consumption for computations that would otherwise haverequires_grad=True. In this mode, the result of every computation will haverequires_grad=False, even when the inputs haverequires_grad=True.model.eval()The
nn.Module.evaldocumentation says:Sets the module in evaluation mode.
This has any effect only on certain modules. See documentations of particular modules for details of their behaviors in training/evaluation mode, if they are affected, e.g.
Dropout,BatchNorm, etc.The creator of pytorch said the documentation should be updated to suggest the usage of both, and I raised the pull request.
From Stack Overflow: asked by Tom Hale, answered by Tom Hale (CC BY-SA 4.0)
Why do we call .detach() before calling .numpy() on a Pytorch Tensor?
I think the most crucial point to understand here is the difference between a
torch.tensorandnp.ndarray:
While both objects are used to store n-dimensional matrices (aka "Tensors"),torch.tensorshas an additional "layer" - which is storing the computational graph leading to the associated n-dimensional matrix.So, if you are only interested in efficient and easy way to perform mathematical operations on matrices
np.ndarrayortorch.tensorcan be used interchangeably.However,
torch.tensors are designed to be used in the context of gradient descent optimization, and therefore they hold not only a tensor with numeric values, but (and more importantly) the computational graph leading to these values. This computational graph is then used (using the chain rule of derivatives) to compute the derivative of the loss function w.r.t each of the independent variables used to compute the loss.As mentioned before,
np.ndarrayobject does not have this extra "computational graph" layer and therefore, when converting atorch.tensortonp.ndarrayyou must explicitly remove the computational graph of the tensor using thedetach()command.Computational Graph
From your comments it seems like this concept is a bit vague. I'll try and illustrate it with a simple example.
Consider a simple function of two (vector) variables,xandw:x = torch.rand(4, requires_grad=True) w = torch.rand(4, requires_grad=True) y = x @ w # inner-product of x and w z = y ** 2 # square the inner productIf we are only interested in the value of
z, we need not worry about any graphs, we simply moving forward from the inputs,xandw, to computeyand thenz.However, what would happen if we do not care so much about the value of
z, but rather want to ask the question "what iswthat minimizeszfor a givenx"?
To answer that question, we need to compute the derivative ofzw.r.tw.
How can we do that?
Using the chain rule we know thatdz/dw = dz/dy * dy/dw. That is, to compute the gradient ofzw.r.twwe need to move backward fromzback towcomputing the gradient of the operation at each step as we trace back our steps fromztow. This "path" we trace back is the computational graph ofzand it tells us how to compute the derivative ofzw.r.t the inputs leading toz:z.backward() # ask pytorch to trace back the computation of zWe can now inspect the gradient of
zw.r.tw:w.grad # the resulting gradient of z w.r.t w tensor([0.8010, 1.9746, 1.5904, 1.0408])Note that this is exactly equals to
2*y*x tensor([0.8010, 1.9746, 1.5904, 1.0408], grad_fn=<MulBackward0>)since
dz/dy = 2*yanddy/dw = x.Each tensor along the path stores its "contribution" to the computation:
z tensor(1.4061, grad_fn=<PowBackward0>)Read the rest at the sourceFrom Stack Overflow: asked by Josiah Yoder, answered by Shai (CC BY-SA 4.0)
How do I check if PyTorch is using the GPU?
These functions should help:
>>> import torch >>> torch.cuda.is_available() True >>> torch.cuda.device_count() 1 >>> torch.cuda.current_device() 0 >>> torch.cuda.device(0) <torch.cuda.device at 0x7efce0b03be0> >>> torch.cuda.get_device_name(0) 'GeForce GTX 950M'This tells us:
- CUDA is available and can be used by one device.
Device 0refers to the GPUGeForce GTX 950M, and it is currently chosen by PyTorch.
From Stack Overflow: asked by vvvvv, answered by vvvvv (CC BY-SA 4.0)
Related topics
Where these questions come from
Open-source collections on GitHub, official documentation, a government careers service and the Stack Exchange sites, each used under its own licence. The answers are the authors' own words: we only tidy the layout, leave out pictures, and cut a long answer with a link to the rest. Stack Exchange answers stay under CC BY-SA and name who asked and who answered.
- Stack Overflowby its contributors, named on each answerCC BY-SA10 questions