PyTorch Training Breakdown
- 31Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
- 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?
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
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.
What are the three common patterns for creating tensors in PyTorch?
- Direct creation from data using
torch.tensor(). 2. Creation from a desired shape using functions liketorch.ones(),torch.zeros(),torch.randn(). 3. Creation by mimicking another tensor using functions liketorch.randn_like().
- Direct creation from data using
What are the three critical attributes of every tensor?
.shape(tuple of dimensions), 2..dtype(data type, e.g.,torch.float32), 3..device(CPU or GPU).
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.
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.What does the
dimargument control in reduction operations like.mean()?dimspecifies which dimension to collapse:dim=0collapses rows (operates vertically),dim=1collapses columns (operates horizontally). Withoutdim, the reduction applies over all elements.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.What is the purpose of
torch.gatherand how does it work?torch.gatherselects 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.What is
requires_gradand how do you activate it?requires_gradis a boolean attribute that, when set toTrue, tells PyTorch's autograd engine to track all operations on that tensor. It is activated by settingrequires_grad=Truewhen creating a tensor.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.What does
grad_fnrepresent on a tensor?grad_fnis 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_fnisNone.Write the formula for the forward pass of a simple linear regression model.
y^=X@W+b
What is the formula for Mean Squared Error (MSE) loss?
L=n1∑i=1n(y^i−yi)2
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.gradattribute of each parameter with the partial derivative of the loss w.r.t. that parameter.What do the values in
.gradrepresent?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.
Write the gradient descent update rule for a parameter θ.
θt+1=θt−η⋅∇L(θt) where η is the learning rate and ∇L(θt) is the gradient of the loss with respect to θ.
What are the five steps of the training loop from scratch?
- 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_()).
- Forward pass: compute prediction. 2. Calculate loss. 3. Backward pass: compute gradients via
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.
How do you define a neural network model using
nn.Module?- Create a class that inherits from
nn.Module. 2. In__init__, callsuper().__init__()and define layers as attributes. 3. Inforward, define the forward pass by applying layers to inputx.
- Create a class that inherits from
What does
nn.Lineardo and how does it relate to the manual forward pass?nn.Linear(in_features, out_features)creates a linear layer that performs y=xWT+b, packaging the weight and bias as Parameters. It replaces manualx @ W + bwith a cleanlayer(x)call.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.
What does
nn.Softmaxdo and where is it commonly used?nn.Softmaxconverts 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.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.
What does
nn.LayerNormdo 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.
How does
nn.Dropoutdiffer 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()andmodel.eval().How do you create an optimizer in PyTorch and what is its role?
Create an optimizer (e.g.,
torch.optim.Adam) by passingmodel.parameters()and a learning rate. The optimizer automates parameter updates using gradients.What is the 'three-line mantra' in PyTorch training?
optimizer.zero_grad()– reset gradients. 2.loss.backward()– compute gradients. 3.optimizer.step()– update parameters.
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()
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))).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.
What is the key takeaway about deep learning after building from scratch?
A model is just an
nn.Modulecontaining layers. A layer is a container for parameters performing a mathematical operation. Learning is updating those parameters withzero_grad(),backward(), andstep(). The magic of deep learning is engineering.

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