All topics

PyTorch interview questions

10 questions with answers. 453 open jobs in India ask for PyTorch.

  1. What's the difference between `reshape()` and `view()` in PyTorch?

    torch.view has 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.reshape has been introduced recently in version 0.4. According to the document, this method will

    Returns 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.reshape may 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 while view() can only operate on contiguous tensor. Also see here about the meaning of contiguous.

    From Stack Overflow: asked by Lifu Huang, answered by jdhao (CC BY-SA 4.0)

  2. 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() and transpose()

    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 42
    

    This is where the concept of contiguous comes in. In the example above, x is contiguous but y is 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 contiguous where PyTorch expects a contiguous tensor to add a call to contiguous().

    From Stack Overflow: asked by MBT, answered by Shital Shah (CC BY-SA 4.0)

  3. What does `gather()` do in PyTorch in layman terms?

    torch.gather creates a new tensor from the input tensor by taking the values from each row along the input dimension dim. The values in torch.LongTensor, passed as index, 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 the index for the src that is 1. At (1,1) in source value is 1 so, outputs 1 at (1,1) in result. Similarly for (2,2) the row value from the index for src is 3. At (3,2) the value in src is 8 and hence outputs 8 and 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 for src is 3, so at (2,3) from src ,6 is taken and outputs to result at (2,2)

    From Stack Overflow: asked by amitection, answered by Ritesh (CC BY-SA 4.0)

  4. 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)

  5. 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 the requires_grad flag to false. torch.no_grad says 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 with statement. Also, torch.no_grad will 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)

  6. 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)

  7. 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 d and e is the output, and a is 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 calculate d will be freed by default to save memory. So if we do e.backward(), the error message will pop up. In order to do e.backward(), we have to set the parameter retain_graph to True in d.backward(), i.e.,

    d.backward(retain_graph=True)
    

    As long as you use retain_graph=True in 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: loss1 and loss2 and they reside in different layers. In order to backprop the gradient of loss1 and loss2 w.r.t to the learnable weight of your network independently. You have to use retain_graph=True in backward() 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 parameters
    

    From Stack Overflow: asked by jvans, answered by jdhao (CC BY-SA 4.0)

  8. 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 in autograd.
    • model.eval() changes the forward() behaviour of the module it is called upon
    • eg, it disables dropout and has batch norm use the entire population statistics

    with torch.no_grad

    The torch.autograd.no_grad documentation 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 have requires_grad=True. In this mode, the result of every computation will have requires_grad=False, even when the inputs have requires_grad=True.

    model.eval()

    The nn.Module.eval documentation 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)

  9. 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.tensor and np.ndarray:
    While both objects are used to store n-dimensional matrices (aka "Tensors"), torch.tensors has 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.ndarray or torch.tensor can 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.ndarray object does not have this extra "computational graph" layer and therefore, when converting a torch.tensor to np.ndarray you must explicitly remove the computational graph of the tensor using the detach() 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, x and w:

    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 product
    

    If we are only interested in the value of z, we need not worry about any graphs, we simply moving forward from the inputs, x and w, to compute y and then z.

    However, what would happen if we do not care so much about the value of z, but rather want to ask the question "what is w that minimizes z for a given x"?
    To answer that question, we need to compute the derivative of z w.r.t w.
    How can we do that?
    Using the chain rule we know that dz/dw = dz/dy * dy/dw. That is, to compute the gradient of z w.r.t w we need to move backward from z back to w computing the gradient of the operation at each step as we trace back our steps from z to w. This "path" we trace back is the computational graph of z and it tells us how to compute the derivative of z w.r.t the inputs leading to z:

    z.backward()  # ask pytorch to trace back the computation of z
    

    We can now inspect the gradient of z w.r.t w:

    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*y and dy/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)

  10. 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 0 refers to the GPU GeForce 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.