1. Home
  2. Explore
  3. Computer Science
  4. PyTorch Training Breakdown

Study methods

Flashcards
Quiz
Fill in the blanks
Written test
Lesson
Notes
Podcast
Content

PyTorch Training Breakdown

  • 25Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Tensor Basics

Which of the following is the correct way to create a PyTorch tensor from a Python list?

25 questions

  1. 1

    Which of the following is the correct way to create a PyTorch tensor from a Python list?

    1. A

      torch.Tensor([1, 2, 3])

    2. B

      torch.create([1, 2, 3])

    3. C

      torch.tensor([1, 2, 3])

    4. D

      torch.from_list([1, 2, 3])

    Correct answer
    C

    torch.tensor([1, 2, 3])

    Explanation

    The function torch.tensor is used to create a tensor from existing data like a Python list. torch.Tensor is a class constructor that creates an empty tensor by default.

  2. 2

    What are the three critical attributes of every PyTorch tensor?

    1. A

      ndim, element_size, and is_cuda

    2. B

      shape, dtype, and device

    3. C

      size, type, and location

    4. D

      dim, data, and grad

    Correct answer
    B

    shape, dtype, and device

    Explanation

    Every PyTorch tensor has shape (dimensions), dtype (data type), and device (CPU or GPU). These are fundamental for debugging and tensor management.

  3. 3

    Why must model parameters (weights and biases) use a float data type like float32?

    1. A

      Integer types cannot be stored in tensors

    2. B

      Gradients require continuous values for tiny adjustments

    3. C

      Only float32 supports automatic differentiation

    4. D

      Float32 is faster on all hardware

    Correct answer
    B

    Gradients require continuous values for tiny adjustments

    Explanation

    Deep learning relies on making tiny continuous adjustments (nudges) to parameters. Integer types cannot represent fractional changes, so float types are necessary for gradient-based learning.

  4. 4

    What does setting requires_grad=True on a tensor do?

    1. A

      It initializes the tensor with random values

    2. B

      It tells PyTorch to track every operation on this tensor for gradient computation

    3. C

      It forces the tensor to be stored on the GPU

    4. D

      It converts the tensor to a learnable parameter automatically

    Correct answer
    B

    It tells PyTorch to track every operation on this tensor for gradient computation

    Explanation

    Setting requires_grad=True activates autograd tracking. PyTorch will record all operations on that tensor to later compute gradients via backpropagation.

  5. 5

    What attribute provides evidence that a computation graph exists for a tensor created by an operation?

    1. A

      requires_grad

    2. B

      grad

    3. C

      grad_fn

    4. D

      is_leaf

    Correct answer
    C

    grad_fn

    Explanation

    Every tensor created by an operation has a grad_fn attribute that points to the function that produced it (e.g., AddBackward0). This is the breadcrumb of the computation graph.

  6. 6

    What is the main difference between the * operator and the @ operator for tensors?

    1. A

      There is no difference; they are interchangeable

    2. B
      • always requires same shape; @ requires matching inner dimensions
    3. C
      • performs elementwise multiplication; @ performs matrix multiplication
    4. D
      • performs matrix multiplication; @ performs elementwise multiplication
    Correct answer
    C
    • performs elementwise multiplication; @ performs matrix multiplication

    Explanation

    The * operator does elementwise multiplication (same shape tensors multiplied position-wise). The @ operator does matrix multiplication (dot product between rows and columns).

  7. 7

    For a 2D tensor, what does dim=0 represent in a reduction operation like .mean()?

    1. A

      Collapse all dimensions

    2. B

      Collapse rows (operate vertically)

    3. C

      Collapse columns (operate horizontally)

    4. D

      Keep the dimension with size 0

    Correct answer
    B

    Collapse rows (operate vertically)

    Explanation

    In a 2D tensor, dimension 0 is the row dimension. Reducing along dim=0 aggregates values across rows, giving one result per column.

  8. 8

    Which function is used to find the index of the maximum value along a dimension?

    1. A

      torch.topk

    2. B

      torch.argmax

    3. C

      torch.max

    4. D

      torch.gather

    Correct answer
    B

    torch.argmax

    Explanation

    torch.argmax returns the indices of the maximum values along a specified dimension. It is commonly used to get a model's predicted class from logits.

  9. 9

    What is the purpose of torch.gather?

    1. A

      To select elements from a tensor according to a custom index tensor

    2. B

      To collect all tensors in a list into one tensor

    3. C

      To gather statistics like mean and variance

    4. D

      To compute the gradient of a tensor

    Correct answer
    A

    To select elements from a tensor according to a custom index tensor

    Explanation

    torch.gather allows you to select elements from a tensor using an index tensor that specifies which element to pick from each row (or along a dimension). It is highly optimized and avoids slow for-loops.

  10. 10

    What is the formula for the forward pass of a simple linear regression model?

    1. A

      y^=11+eāˆ’XW\hat{y} = \frac{1}{1+e^{-XW}}y^​=1+eāˆ’XW1​

    2. B

      y^=XW+b\hat{y} = XW + by^​=XW+b

    3. C

      y^=Xā‹…W\hat{y} = X \cdot Wy^​=Xā‹…W

    4. D

      y^=σ(XW+b)\hat{y} = \sigma(XW + b)y^​=σ(XW+b)

    Correct answer
    B

    y^=XW+b\hat{y} = XW + by^​=XW+b

    Explanation

    Linear regression predicts using y^=XW+b\hat{y} = XW + by^​=XW+b, where XXX is input, WWW is weight, and bbb is bias. This is the foundation of linear layers.

  11. 11

    What does the Mean Squared Error (MSE) loss compute?

    1. A

      The maximum difference between predictions and true values

    2. B

      The sum of absolute differences between predictions and true values

    3. C

      The average of squared differences between predictions and true values

    4. D

      The square root of the variance of predictions

    Correct answer
    C

    The average of squared differences between predictions and true values

    Explanation

    MSE is 1nāˆ‘i=1n(y^iāˆ’yi)2\frac{1}{n}\sum_{i=1}^n (\hat{y}_i - y_i)^2n1ā€‹āˆ‘i=1n​(y^​iā€‹āˆ’yi​)2. It measures the average squared error, penalizing larger errors more heavily.

  12. 12

    What does loss.backward() compute?

    1. A

      The forward pass of the model

    2. B

      Gradients of the loss with respect to all tensors that have requires_grad=True

    3. C

      The loss value for the current batch

    4. D

      The new parameters after gradient descent

    Correct answer
    B

    Gradients of the loss with respect to all tensors that have requires_grad=True

    Explanation

    loss.backward() computes gradients (partial derivatives) of the loss with respect to every tensor in the computation graph that has requires_grad=True. These gradients are stored in the .grad attribute.

  13. 13

    What is the gradient descent update rule for a parameter Īø\thetaĪø?

    1. A

      Īøt+1=Ī·ā‹…Īøtāˆ’āˆ‡ĪøL\theta_{t+1} = \eta \cdot \theta_t - \nabla_\theta LĪøt+1​=Ī·ā‹…Īøtā€‹āˆ’āˆ‡Īøā€‹L

    2. B

      Īøt+1=Īøtā‹…āˆ‡ĪøL\theta_{t+1} = \theta_t \cdot \nabla_\theta LĪøt+1​=Īøtā€‹ā‹…āˆ‡Īøā€‹L

    3. C

      Īøt+1=Īøtāˆ’Ī·ā‹…āˆ‡ĪøL\theta_{t+1} = \theta_t - \eta \cdot \nabla_\theta LĪøt+1​=Īøtā€‹āˆ’Ī·ā‹…āˆ‡Īøā€‹L

    4. D

      Īøt+1=Īøt+Ī·ā‹…āˆ‡ĪøL\theta_{t+1} = \theta_t + \eta \cdot \nabla_\theta LĪøt+1​=Īøt​+Ī·ā‹…āˆ‡Īøā€‹L

    Correct answer
    C

    Īøt+1=Īøtāˆ’Ī·ā‹…āˆ‡ĪøL\theta_{t+1} = \theta_t - \eta \cdot \nabla_\theta LĪøt+1​=Īøtā€‹āˆ’Ī·ā‹…āˆ‡Īøā€‹L

    Explanation

    Gradient descent moves parameters in the opposite direction of the gradient (which points uphill) to minimize the loss. The learning rate Ī·\etaĪ· scales the step size.

  14. 14

    Why must we call optimizer.zero_grad() before each training iteration?

    1. A

      To initialize the optimizer's internal state

    2. B

      To reset the accumulated gradients from the previous iteration

    3. C

      To set the learning rate to zero

    4. D

      To delete the computation graph

    Correct answer
    B

    To reset the accumulated gradients from the previous iteration

    Explanation

    Gradients accumulate by default. If not zeroed, new gradients add to old ones, causing incorrect updates. zero_grad() clears them for the next batch.

  15. 15

    When building a custom model in PyTorch, which methods must you define?

    1. A

      forward and train

    2. B

      __init__ and forward

    3. C

      __init__ and parameters

    4. D

      __init__ and backward

    Correct answer
    B

    __init__ and forward

    Explanation

    To create a custom module, inherit from nn.Module, define layers in __init__, and implement the forward computation in forward. The backward pass is handled automatically by autograd.

  16. 16

    What does nn.Linear(in_features, out_features) do?

    1. A

      Creates an activation function layer

    2. B

      Creates a convolutional layer

    3. C

      Creates a fully connected layer with learnable weight and bias

    4. D

      Creates a dropout layer

    Correct answer
    C

    Creates a fully connected layer with learnable weight and bias

    Explanation

    nn.Linear applies a linear transformation y=xWT+by = xW^T + by=xWT+b, where WWW and bbb are learnable parameters (tensors with requires_grad=True).

  17. 17

    Which activation function sets all negative inputs to zero?

    1. A

      ReLU

    2. B

      Softmax

    3. C

      Tanh

    4. D

      GELU

    Correct answer
    A

    ReLU

    Explanation

    ReLU (Rectified Linear Unit) returns max⁔(0,x)\max(0, x)max(0,x). It is simple and widely used, though it has the "dying ReLU" problem for negative values.

  18. 18

    What is the primary use of nn.Softmax?

    1. A

      To convert raw scores (logits) into a probability distribution

    2. B

      To normalize input across features

    3. C

      To smooth the negative part of the input

    4. D

      To prevent overfitting by randomly dropping neurons

    Correct answer
    A

    To convert raw scores (logits) into a probability distribution

    Explanation

    nn.Softmax outputs values in [0,1] that sum to 1, making it ideal for multiclass classification where the model outputs probabilities for each class.

  19. 19

    What is the shape of the output tensor from an nn.Embedding layer if the input is a batch of 4 word IDs (indices) and the embedding dimension is 3?

    1. A

      [3, 4]

    2. B

      [1, 4, 3]

    3. C

      [4]

    4. D

      [4, 3]

    Correct answer
    D

    [4, 3]

    Explanation

    nn.Embedding acts as a lookup table. For each input ID, it returns the corresponding vector. The output shape is (batch_size, embedding_dim). So with 4 IDs and dim 3, shape is [4, 3].

  20. 20

    What does nn.LayerNorm do to its input?

    1. A

      It randomly zeros out a fraction of the neurons

    2. B

      It rescales the input to have mean near 0 and standard deviation near 1 across the features

    3. C

      It applies a learned affine transformation only

    4. D

      It normalizes the input across the batch dimension

    Correct answer
    B

    It rescales the input to have mean near 0 and standard deviation near 1 across the features

    Explanation

    nn.LayerNorm normalizes along the feature dimension, making the mean close to 0 and standard deviation close to 1. This stabilizes training in deep networks like transformers.

  21. 21

    How does a dropout layer behave differently during training versus evaluation?

    1. A

      It is only used during evaluation

    2. B

      During training it randomly drops neurons; during evaluation it passes all inputs unchanged

    3. C

      It behaves the same in both modes

    4. D

      During training it passes all inputs unchanged; during evaluation it drops neurons

    Correct answer
    B

    During training it randomly drops neurons; during evaluation it passes all inputs unchanged

    Explanation

    Dropout is a regularization technique. In training mode, it randomly zeros a fraction of neurons to prevent co-adaptation. In eval mode, it becomes an identity function, passing all inputs.

  22. 22

    Which of the following is the correct "three-line mantra" for training in PyTorch?

    1. A

      optimizer.step(); loss.backward(); optimizer.zero_grad()

    2. B

      optimizer.zero_grad(); optimizer.step(); loss.backward()

    3. C

      loss.backward(); optimizer.step(); optimizer.zero_grad()

    4. D

      optimizer.zero_grad(); loss.backward(); optimizer.step()

    Correct answer
    D

    optimizer.zero_grad(); loss.backward(); optimizer.step()

    Explanation

    The standard order is: zero gradients, compute gradients via backward(), then update parameters via step(). This ensures fresh gradients are used for each update.

  23. 23

    When using an optimizer, what must be passed to it during initialization?

    1. A

      The model class and the number of epochs

    2. B

      The model's parameters (via model.parameters()) and the learning rate

    3. C

      Only the learning rate

    4. D

      The loss function and the training data

    Correct answer
    B

    The model's parameters (via model.parameters()) and the learning rate

    Explanation

    An optimizer like Adam needs the list of learnable parameters to update, typically obtained via model.parameters(), and hyperparameters like the learning rate.

  24. 24

    What is the fundamental difference between a toy linear regression model and a large language model (LLM) like Llama?

    1. A

      Toy models cannot be trained with backpropagation

    2. B

      LLMs use the same five-step training process but with many more parameters and layers

    3. C

      LLMs use a completely different learning algorithm

    4. D

      LLMs do not use gradient descent

    Correct answer
    B

    LLMs use the same five-step training process but with many more parameters and layers

    Explanation

    Both models use the same core training loop (forward, loss, backward, update). The difference is scale: LLMs have billions of parameters and complex architectures like transformers, but the underlying process is identical.

  25. 25

    Which of the following layers are inside a Transformer's feed-forward network (FFN)?

    1. A

      nn.Linear, activation (e.g., GELU), and another nn.Linear

    2. B

      nn.LSTM and nn.Linear

    3. C

      nn.Conv2d, nn.ReLU, and nn.MaxPool2d

    4. D

      Only nn.Linear layers

    Correct answer
    A

    nn.Linear, activation (e.g., GELU), and another nn.Linear

    Explanation

    The FFN in a transformer block consists of two linear layers with a non-linear activation (like GELU) in between. This is a simple MLP that processes each token independently.

Question 1 of 25
Question 1 of 25

Ask anything

We've read this whole study set, so questions about it get the best answers.

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent