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

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

What are the three common patterns for creating a tensor in PyTorch?

28 questions

  1. 1

    What are the three common patterns for creating a tensor in PyTorch?

    Model answer

    Direct creation from data using torch.tensor, creation from a desired shape using functions like torch.randn or torch.zeros, and creation by mimicking another tensor using e.g., torch.randn_like.

    Explanation

    The three patterns cover the main ways to obtain tensors: from existing data, from a known shape (often for weight initialization), and from a template tensor to match shape and type.

  2. 2

    What are the three critical attributes of every tensor, and why is each important?

    Model answer

    Shape (dimensions), dtype (data type), and device (CPU or GPU). Shape is crucial for debugging shape mismatches (90% of errors), dtype determines numeric precision (float32 is default for learnable parameters), and device indicates where computation occurs.

    Explanation

    These attributes are essential for understanding tensor properties and debugging. Shape mismatches cause most PyTorch errors; dtype affects gradient computation (need floats for continuous updates); device management enables GPU acceleration.

  3. 3

    Why must model parameters (weights and biases) be of a float type rather than integer?

    Model answer

    Because gradient descent requires tiny continuous adjustments (nudges) to parameters, which is impossible with integer types. Float32 allows updates like 3.001, enabling the learning process.

    Explanation

    The entire learning process relies on small, continuous changes; integers cannot represent fractional updates, so float types are mandatory for learnable parameters.

  4. 4

    What does the requires_grad=True flag do, and why is it called the 'most important setting in PyTorch'?

    Model answer

    It tells PyTorch's autograd engine to track every operation on that tensor, enabling automatic gradient computation. It is essential for making a tensor a learnable parameter.

    Explanation

    Without requires_grad=True, a tensor is just data; with it, PyTorch builds a computation graph to calculate gradients later via backward().

  5. 5

    Explain the role of grad_fn in the computation graph. Give an example of what it stores.

    Model answer

    grad_fn is a breadcrumb attribute on tensors created by operations, pointing to the function that produced them. For example, a tensor created by addition has grad_fn = , while a user-created tensor has grad_fn = None.

    Explanation

    grad_fn records the operation that created the tensor, forming a map of the computation graph. During backward(), Autograd follows this trail to compute gradients.

  6. 6

    How does PyTorch build a computation graph when you perform operations on tensors with requires_grad=True?

    Model answer

    PyTorch records each operation as a new node, connecting input tensors to the output tensor via the operation. The graph tracks the sequence of operations (e.g., add, multiply) that produced the final output.

    Explanation

    The graph is built dynamically as operations are executed. Each operation creates a new tensor with a grad_fn linking back to the operation and its inputs, enabling automatic differentiation.

  7. 7

    What is the difference between elementwise multiplication (using *) and matrix multiplication (using @) in PyTorch?

    Model answer

    Elementwise multiplication (*) multiplies corresponding elements of tensors with the same shape. Matrix multiplication (@) follows linear algebra rules: the number of columns in the first tensor must equal the number of rows in the second, and the result has outer dimensions.

    Explanation

    * is for elementwise operations; @ is for true matrix multiplication used in neural network layers (e.g., y = x @ w + b). Confusing them is a common beginner mistake.

  8. 8

    Given a tensor scores of shape (2,3) representing 2 students' scores on 3 assignments, what does scores.mean(dim=0) compute, and what does scores.mean(dim=1) compute?

    Model answer

    dim=0 collapses rows (students), giving the average score per assignment (3 values). dim=1 collapses columns (assignments), giving the average score per student (2 values).

    Explanation

    dim specifies which dimension to reduce. For a 2D tensor, dim=0 operates vertically (across rows), dim=1 operates horizontally (across columns).

  9. 9

    How does torch.argmax work, and how is it used to obtain a model's prediction?

    Model answer

    torch.argmax returns the index of the maximum value along a specified dimension. For classification, it is used on the output scores (logits) to select the predicted class (e.g., argmax with dim=1 for batch of predictions).

    Explanation

    argmax converts model output probabilities or scores into a discrete prediction by picking the class with the highest value.

  10. 10

    What purpose does torch.gather serve, and when would you use it over standard indexing?

    Model answer

    torch.gather allows custom selection of elements from a tensor by specifying a different column index for each row. It is used when you need non-uniform indexing (e.g., selecting different columns per row), as opposed to standard indexing which selects uniform slices.

    Explanation

    gather is optimized for high-performance dynamic selection, essential in complex architectures like attention mechanisms.

  11. 11

    Write the mathematical formula for a simple linear regression forward pass and its corresponding PyTorch code using raw tensors.

    Model answer

    Formula: y^=Xā‹…w+b\hat{y} = X \cdot w + by^​=Xā‹…w+b. Code: y_hat = X @ w + b.

    Explanation

    The forward pass computes the model's prediction. X is input, w is weight, b is bias. The @ operator performs matrix multiplication.

  12. 12

    What is the mean squared error (MSE) loss function, and how is it computed in code?

    Model answer

    MSE = 1nāˆ‘i=1n(yiāˆ’y^i)2\frac{1}{n}\sum_{i=1}^{n}(y_i - \hat{y}_i)^2n1ā€‹āˆ‘i=1n​(yiā€‹āˆ’y^​i​)2. Code: loss = ((y_hat - y_true)**2).mean().

    Explanation

    MSE measures the average squared difference between predictions and true values. It is a standard loss for regression problems.

  13. 13

    What does loss.backward() do, and what information does it populate?

    Model answer

    loss.backward() computes the gradients of the loss with respect to all tensors that have requires_grad=True. It populates the .grad attribute of those tensors with the partial derivatives.

    Explanation

    This is the core of automatic differentiation. Autograd traverses the computation graph backward from the loss, calculating gradients for every parameter.

  14. 14

    Explain the gradient descent update rule for a parameter Īø\thetaĪø given learning rate Ī·\etaĪ· and gradient āˆ‡L\nabla Lāˆ‡L.

    Model answer

    Īønew=Īøoldāˆ’Ī·ā‹…āˆ‡L\theta_{\text{new}} = \theta_{\text{old}} - \eta \cdot \nabla LĪønew​=Īøoldā€‹āˆ’Ī·ā‹…āˆ‡L.

    Explanation

    The parameter is updated in the opposite direction of the gradient to minimize the loss. The learning rate controls the step size.

  15. 15

    Why is it necessary to zero gradients (e.g., optimizer.zero_grad()) at the beginning of each training iteration?

    Model answer

    Gradients accumulate by default. Without zeroing, new gradients from the current iteration would be added to the previous ones, causing incorrect updates.

    Explanation

    Each backward() call adds gradients to the existing .grad attribute. Zeroing resets them to zero before the next forward pass, ensuring the update uses only the current batch's gradients.

  16. 16

    Describe the five steps of the gradient descent training loop as implemented from scratch.

    Model answer
    1. Forward pass: compute prediction y_hat. 2. Compute loss. 3. Backward pass: loss.backward() to compute gradients. 4. Update parameters: subtract learning rate times gradient. 5. Zero gradients: set .grad to zero for next iteration.

    Explanation

    These steps form the core learning cycle. Step 4 and 5 are manual in the from-scratch version, but automated by optimizers in professional code.

  17. 17

    What is the 'three-line mantra' in professional PyTorch training, and what does each line do?

    Model answer
    1. optimizer.zero_grad(): resets gradients. 2. loss.backward(): computes gradients. 3. optimizer.step(): updates parameters using the gradients.

    Explanation

    This replaces manual gradient zeroing and weight updates. It is the standard pattern seen in 99% of PyTorch training loops.

  18. 18

    How do you define a custom model using nn.Module? Provide the key structural requirements.

    Model answer

    Inherit from nn.Module, define layers in __init__, call super().__init__(), and implement the forward method that passes input through the layers.

    Explanation

    nn.Module provides automatic parameter registration and a standardized interface. The forward method defines the computation graph.

  19. 19

    What does nn.Linear encapsulate, and how does it compare to the manual X @ w + b operation?

    Model answer

    nn.Linear encapsulates a weight matrix w and a bias vector b, performing output = input @ weight.T + bias. It automatically manages parameters (requires_grad=True) and provides a clean interface.

    Explanation

    Instead of loose tensors, nn.Linear packages both parameters and the operation into a single object, simplifying model construction.

  20. 20

    Compare ReLU and GELU activation functions. How do they differ in handling negative inputs?

    Model answer

    ReLU sets all negative inputs to zero (hard threshold). GELU gently squashes negative inputs toward zero in a smooth, differentiable manner.

    Explanation

    ReLU is simpler and widely used; GELU is smoother and often performs better in transformers (GPT, Llama).

  21. 21

    What is the purpose of nn.Softmax, and what properties do its outputs have?

    Model answer

    Softmax converts raw scores (logits) into a probability distribution: all outputs are between 0 and 1 and sum to 1. It is used on the final layer for classification.

    Explanation

    Softmax enables interpreting model outputs as probabilities. The dim argument specifies which dimension to normalize over.

  22. 22

    Explain how nn.Embedding works. What is the input and output shape?

    Model answer

    nn.Embedding is a learnable lookup table that maps integer indices (word IDs) to dense vectors. Input shape: (batch_size, seq_len). Output shape: (batch_size, seq_len, embedding_dim).

    Explanation

    Each word ID retrieves its corresponding vector from the embedding matrix. This is the first step in language models.

  23. 23

    What does nn.LayerNorm do, and why is it important for deep networks?

    Model answer

    LayerNorm normalizes the outputs of a layer to have mean 0 and standard deviation 1 across the feature dimension. It stabilizes training by preventing activations from exploding or vanishing.

    Explanation

    LayerNorm rescales data to a consistent range, enabling effective gradient flow in deep networks. It is essential in transformers.

  24. 24

    How does nn.Dropout behave during training versus evaluation mode?

    Model answer

    During training, Dropout randomly zeros a fraction of inputs (with scaling). During evaluation (model.eval()), it acts as an identity function, passing all inputs unchanged.

    Explanation

    Dropout prevents overfitting by forcing the network to be robust. The behavior switch is controlled by model.train() and model.eval().

  25. 25

    How do you create an optimizer in PyTorch, and what arguments are required?

    Model answer

    Create an optimizer by calling torch.optim.Adam(model.parameters(), lr=learning_rate). The first argument is the iterable of parameters to update; the second is the learning rate.

    Explanation

    The optimizer manages parameter updates. Adam is a common choice; it uses adaptive learning rates and momentum.

  26. 26

    Compare the from-scratch training loop to the professional PyTorch training loop. What replaces the manual weight update and gradient zeroing?

    Model answer

    The professional loop replaces manual updates with optimizer.step() and manual zeroing with optimizer.zero_grad(). The forward pass uses model(x) and loss uses loss_fn(y_hat, y_true).

    Explanation

    The professional loop is cleaner, scalable, and uses optimized implementations. The three-line mantra (zero_grad, backward, step) automates the core update process.

  27. 27

    Describe the structure of a Feed-Forward Network (FFN) inside a transformer block. What layers does it contain?

    Model answer

    An FFN consists of two nn.Linear layers with an activation function (e.g., GELU) in between: x = layer2(activation(layer1(x))).

    Explanation

    The FFN is a simple multi-layer perceptron that processes each token independently. Despite its simplicity, it is a key component of transformers.

  28. 28

    How does the training process for a toy linear regression model (2 parameters) scale to a large language model like Llama 38B?

    Model answer

    The exact same five-step process is used: forward pass, loss calculation, backward pass, optimizer step, and gradient zeroing. The difference is scale (billions of parameters, transformer architecture) but the core algorithm is identical.

    Explanation

    The universal pattern (model(x), loss_fn, zero_grad, backward, step) works for any size model. Autograd and optimizers handle the complexity automatically.

1 of 28
Question 1 of 28

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent