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

  • 31Unfamiliar
  • 0Learning
  • 0Familiar
  • 0Mastered
Topic: Tensor Fundamentals
  • spaceFlip card
  • KI knew it
  • DI didn't know it
  • ←Previous card
  • →Next card

What is a tensor in PyTorch and how does it relate to NumPy arrays?

Tap to flipClick to flipspace

A tensor is the fundamental building block in PyTorch, similar to a multi-dimensional array in NumPy, but with additional capabilities like automatic differentiation and GPU acceleration.

Or swipe the card

31 cards

  1. What is a tensor in PyTorch and how does it relate to NumPy arrays?

    A tensor is the fundamental building block in PyTorch, similar to a multi-dimensional array in NumPy, but with additional capabilities like automatic differentiation and GPU acceleration.

  2. What are the three common patterns for creating tensors in PyTorch?

    1. Direct creation from data using torch.tensor(). 2. Creation from a desired shape using functions like torch.ones(), torch.zeros(), torch.randn(). 3. Creation by mimicking another tensor using functions like torch.randn_like().
  3. What are the three critical attributes of every tensor?

    1. .shape (tuple of dimensions), 2. .dtype (data type, e.g., torch.float32), 3. .device (CPU or GPU).
  4. Why must model parameters (weights and biases) be of a float type like float32?

    Because learning requires tiny continuous adjustments (nudges), which are only possible with floating-point numbers. Integer types cannot represent fractional changes.

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

    Elementwise multiplication (*) multiplies matching positions, requiring tensors of the same shape. Matrix multiplication (@) follows linear algebra rules, requiring the number of columns in the first matrix to equal the number of rows in the second.

  6. What does the dim argument control in reduction operations like .mean()?

    dim specifies which dimension to collapse: dim=0 collapses rows (operates vertically), dim=1 collapses columns (operates horizontally). Without dim, the reduction applies over all elements.

  7. How do you find the index of the maximum value along a dimension using PyTorch?

    Use torch.argmax(input, dim). For example, torch.argmax(scores, dim=1) returns the index of the highest value for each row.

  8. What is the purpose of torch.gather and how does it work?

    torch.gather selects elements from a tensor according to a custom index tensor. For a 2D tensor, it picks values along one dimension based on the indices provided for each row.

  9. What is requires_grad and how do you activate it?

    requires_grad is a boolean attribute that, when set to True, tells PyTorch's autograd engine to track all operations on that tensor. It is activated by setting requires_grad=True when creating a tensor.

  10. What is a computation graph in PyTorch and how is it built?

    A computation graph is a directed acyclic graph that records every operation performed on tensors with requires_grad=True. It is built automatically by PyTorch as operations are executed, connecting tensors to the functions that produced them.

  11. What does grad_fn represent on a tensor?

    grad_fn is an attribute that points to the function that created the tensor. It is like a breadcrumb in the computation graph, tracing how the tensor was generated (e.g., AddBackward0, MulBackward0). For user-created tensors, grad_fn is None.

  12. Write the formula for the forward pass of a simple linear regression model.

    y^=X@W+b\hat{y} = X @ W + by^​=X@W+b

  13. What is the formula for Mean Squared Error (MSE) loss?

    L=1n∑i=1n(y^i−yi)2L = \frac{1}{n} \sum_{i=1}^n (\hat{y}_i - y_i)^2L=n1​∑i=1n​(y^​i​−yi​)2

  14. What does loss.backward() do?

    It computes the gradient of the loss with respect to all tensors that have requires_grad=True. PyTorch traverses the computation graph backward and populates the .grad attribute of each parameter with the partial derivative of the loss w.r.t. that parameter.

  15. What do the values in .grad represent?

    They represent the partial derivative of the loss with respect to that parameter. The gradient points in the direction of steepest increase of the loss, so to minimize the loss, parameters should be updated in the opposite direction.

  16. Write the gradient descent update rule for a parameter θ\thetaθ.

    θt+1=θt−η⋅∇L(θt)\theta_{t+1} = \theta_t - \eta \cdot \nabla L(\theta_t)θt+1​=θt​−η⋅∇L(θt​) where η\etaη is the learning rate and ∇L(θt)\nabla L(\theta_t)∇L(θt​) is the gradient of the loss with respect to θ\thetaθ.

  17. What are the five steps of the training loop from scratch?

    1. Forward pass: compute prediction. 2. Calculate loss. 3. Backward pass: compute gradients via loss.backward(). 4. Update parameters using gradient descent. 5. Zero gradients for the next iteration (.grad.zero_()).
  18. Why is it necessary to zero gradients before each training iteration?

    Gradients accumulate by default. Without zeroing, new gradients are added to old ones, causing incorrect updates and divergence. Zeroing ensures each iteration's gradients correspond only to the current batch.

  19. How do you define a neural network model using nn.Module?

    1. Create a class that inherits from nn.Module. 2. In __init__, call super().__init__() and define layers as attributes. 3. In forward, define the forward pass by applying layers to input x.
  20. What does nn.Linear do and how does it relate to the manual forward pass?

    nn.Linear(in_features, out_features) creates a linear layer that performs y=xWT+by = xW^T + by=xWT+b, packaging the weight and bias as Parameters. It replaces manual x @ W + b with a clean layer(x) call.

  21. What is the purpose of activation functions like ReLU and GELU?

    Activation functions introduce non-linearity between linear layers. Without them, stacking linear layers is equivalent to a single linear layer, limiting the model's capacity to learn complex patterns.

  22. What does nn.Softmax do and where is it commonly used?

    nn.Softmax converts raw logits into a probability distribution: outputs are between 0 and 1 and sum to 1 across the specified dimension. It is typically used on the final output layer for multi-class classification.

  23. What is the role of nn.Embedding?

    It is a learnable lookup table that maps integer indices (e.g., word IDs) to dense vectors. It is the first step in many language models.

  24. What does nn.LayerNorm do and why is it important?

    Layer normalization rescales activations to have a mean of 0 and standard deviation of 1 across features, stabilizing training and preventing exploding/vanishing gradients. It is essential for deep networks.

  25. How does nn.Dropout differ between training and evaluation modes?

    During training, dropout randomly zeroes a fraction of neurons (and scales the rest to maintain expected sum). During evaluation, it is deactivated and passes all inputs unchanged. Mode is controlled via model.train() and model.eval().

  26. How do you create an optimizer in PyTorch and what is its role?

    Create an optimizer (e.g., torch.optim.Adam) by passing model.parameters() and a learning rate. The optimizer automates parameter updates using gradients.

  27. What is the 'three-line mantra' in PyTorch training?

    1. optimizer.zero_grad() – reset gradients. 2. loss.backward() – compute gradients. 3. optimizer.step() – update parameters.
  28. Write the professional PyTorch training loop for one epoch.

    python for epoch in range(epochs): y_hat = model(x) loss = loss_fn(y_hat, y_true) optimizer.zero_grad() loss.backward() optimizer.step()

  29. What is the structure of a Transformer's Feed-Forward Network (FFN)?

    An FFN typically consists of two linear layers with a non-linear activation (e.g., GELU) in between: output = Layer2(Activation(Layer1(input))).

  30. How does the training process for a large language model (LLM) differ from a toy linear regression model?

    The fundamental process is identical: forward pass, loss calculation, backward pass, parameter update, and gradient zeroing. Only the scale (billions of parameters) and specific components (e.g., cross-entropy loss, multiple layers) differ.

  31. What is the key takeaway about deep learning after building from scratch?

    A model is just an nn.Module containing layers. A layer is a container for parameters performing a mathematical operation. Learning is updating those parameters with zero_grad(), backward(), and step(). The magic of deep learning is engineering.

Card 1 of 31
Card 1 of 31

Ask anything

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

FlashcardsQuizFill in the blanksWritten testLessonNotesPodcastContent