PyTorch Training Breakdown
- 25Unfamiliar
- 0Learning
- 0Familiar
- 0Mastered
Which of the following is the correct way to create a PyTorch tensor from a Python list?
Which of the following is the correct way to create a PyTorch tensor from a Python list?
25 questions
- 1
Which of the following is the correct way to create a PyTorch tensor from a Python list?
- A
torch.Tensor([1, 2, 3])
- B
torch.create([1, 2, 3])
- C
torch.tensor([1, 2, 3])
- D
torch.from_list([1, 2, 3])
Correct answer
Ctorch.tensor([1, 2, 3])
Explanation
The function
torch.tensoris used to create a tensor from existing data like a Python list.torch.Tensoris a class constructor that creates an empty tensor by default. - A
- 2
What are the three critical attributes of every PyTorch tensor?
- A
ndim, element_size, and is_cuda
- B
shape, dtype, and device
- C
size, type, and location
- D
dim, data, and grad
Correct answer
Bshape, dtype, and device
Explanation
Every PyTorch tensor has
shape(dimensions),dtype(data type), anddevice(CPU or GPU). These are fundamental for debugging and tensor management. - A
- 3
Why must model parameters (weights and biases) use a float data type like float32?
- A
Integer types cannot be stored in tensors
- B
Gradients require continuous values for tiny adjustments
- C
Only float32 supports automatic differentiation
- D
Float32 is faster on all hardware
Correct answer
BGradients 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.
- A
- 4
What does setting
requires_grad=Trueon a tensor do?- A
It initializes the tensor with random values
- B
It tells PyTorch to track every operation on this tensor for gradient computation
- C
It forces the tensor to be stored on the GPU
- D
It converts the tensor to a learnable parameter automatically
Correct answer
BIt tells PyTorch to track every operation on this tensor for gradient computation
Explanation
Setting
requires_grad=Trueactivates autograd tracking. PyTorch will record all operations on that tensor to later compute gradients via backpropagation. - A
- 5
What attribute provides evidence that a computation graph exists for a tensor created by an operation?
- A
requires_grad
- B
grad
- C
grad_fn
- D
is_leaf
Correct answer
Cgrad_fn
Explanation
Every tensor created by an operation has a
grad_fnattribute that points to the function that produced it (e.g.,AddBackward0). This is the breadcrumb of the computation graph. - A
- 6
What is the main difference between the * operator and the @ operator for tensors?
- A
There is no difference; they are interchangeable
- B
- always requires same shape; @ requires matching inner dimensions
- C
- performs elementwise multiplication; @ performs matrix multiplication
- 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). - A
- 7
For a 2D tensor, what does
dim=0represent in a reduction operation like.mean()?- A
Collapse all dimensions
- B
Collapse rows (operate vertically)
- C
Collapse columns (operate horizontally)
- D
Keep the dimension with size 0
Correct answer
BCollapse 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.
- A
- 8
Which function is used to find the index of the maximum value along a dimension?
- A
torch.topk
- B
torch.argmax
- C
torch.max
- D
torch.gather
Correct answer
Btorch.argmax
Explanation
torch.argmaxreturns the indices of the maximum values along a specified dimension. It is commonly used to get a model's predicted class from logits. - A
- 9
What is the purpose of
torch.gather?- A
To select elements from a tensor according to a custom index tensor
- B
To collect all tensors in a list into one tensor
- C
To gather statistics like mean and variance
- D
To compute the gradient of a tensor
Correct answer
ATo select elements from a tensor according to a custom index tensor
Explanation
torch.gatherallows 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. - A
- 10
What is the formula for the forward pass of a simple linear regression model?
- A
y^ā=1+eāXW1ā
- B
y^ā=XW+b
- C
y^ā=Xā W
- D
y^ā=Ļ(XW+b)
Correct answer
By^ā=XW+b
Explanation
Linear regression predicts using y^ā=XW+b, where X is input, W is weight, and b is bias. This is the foundation of linear layers.
- A
- 11
What does the Mean Squared Error (MSE) loss compute?
- A
The maximum difference between predictions and true values
- B
The sum of absolute differences between predictions and true values
- C
The average of squared differences between predictions and true values
- D
The square root of the variance of predictions
Correct answer
CThe average of squared differences between predictions and true values
Explanation
MSE is n1āāi=1nā(y^āiāāyiā)2. It measures the average squared error, penalizing larger errors more heavily.
- A
- 12
What does
loss.backward()compute?- A
The forward pass of the model
- B
Gradients of the loss with respect to all tensors that have
requires_grad=True - C
The loss value for the current batch
- D
The new parameters after gradient descent
Correct answer
BGradients of the loss with respect to all tensors that have
requires_grad=TrueExplanation
loss.backward()computes gradients (partial derivatives) of the loss with respect to every tensor in the computation graph that hasrequires_grad=True. These gradients are stored in the.gradattribute. - A
- 13
What is the gradient descent update rule for a parameter Īø?
- A
Īøt+1ā=Ī·ā ĪøtāāāĪøāL
- B
Īøt+1ā=Īøtāā āĪøāL
- C
Īøt+1ā=ĪøtāāĪ·ā āĪøāL
- D
Īøt+1ā=Īøtā+Ī·ā āĪøāL
Correct answer
CĪø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 Ī· scales the step size.
- A
- 14
Why must we call
optimizer.zero_grad()before each training iteration?- A
To initialize the optimizer's internal state
- B
To reset the accumulated gradients from the previous iteration
- C
To set the learning rate to zero
- D
To delete the computation graph
Correct answer
BTo 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. - A
- 15
When building a custom model in PyTorch, which methods must you define?
- A
forwardandtrain - B
__init__andforward - C
__init__andparameters - D
__init__andbackward
Correct answer
B__init__andforwardExplanation
To create a custom module, inherit from
nn.Module, define layers in__init__, and implement the forward computation inforward. The backward pass is handled automatically by autograd. - A
- 16
What does
nn.Linear(in_features, out_features)do?- A
Creates an activation function layer
- B
Creates a convolutional layer
- C
Creates a fully connected layer with learnable weight and bias
- D
Creates a dropout layer
Correct answer
CCreates a fully connected layer with learnable weight and bias
Explanation
nn.Linearapplies a linear transformation y=xWT+b, where W and b are learnable parameters (tensors withrequires_grad=True). - A
- 17
Which activation function sets all negative inputs to zero?
- A
ReLU
- B
Softmax
- C
Tanh
- D
GELU
Correct answer
AReLU
Explanation
ReLU (Rectified Linear Unit) returns max(0,x). It is simple and widely used, though it has the "dying ReLU" problem for negative values.
- A
- 18
What is the primary use of
nn.Softmax?- A
To convert raw scores (logits) into a probability distribution
- B
To normalize input across features
- C
To smooth the negative part of the input
- D
To prevent overfitting by randomly dropping neurons
Correct answer
ATo convert raw scores (logits) into a probability distribution
Explanation
nn.Softmaxoutputs values in [0,1] that sum to 1, making it ideal for multiclass classification where the model outputs probabilities for each class. - A
- 19
What is the shape of the output tensor from an
nn.Embeddinglayer if the input is a batch of 4 word IDs (indices) and the embedding dimension is 3?- A
[3, 4]
- B
[1, 4, 3]
- C
[4]
- D
[4, 3]
Correct answer
D[4, 3]
Explanation
nn.Embeddingacts 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]. - A
- 20
What does
nn.LayerNormdo to its input?- A
It randomly zeros out a fraction of the neurons
- B
It rescales the input to have mean near 0 and standard deviation near 1 across the features
- C
It applies a learned affine transformation only
- D
It normalizes the input across the batch dimension
Correct answer
BIt rescales the input to have mean near 0 and standard deviation near 1 across the features
Explanation
nn.LayerNormnormalizes along the feature dimension, making the mean close to 0 and standard deviation close to 1. This stabilizes training in deep networks like transformers. - A
- 21
How does a dropout layer behave differently during training versus evaluation?
- A
It is only used during evaluation
- B
During training it randomly drops neurons; during evaluation it passes all inputs unchanged
- C
It behaves the same in both modes
- D
During training it passes all inputs unchanged; during evaluation it drops neurons
Correct answer
BDuring 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.
- A
- 22
Which of the following is the correct "three-line mantra" for training in PyTorch?
- A
optimizer.step(); loss.backward(); optimizer.zero_grad()
- B
optimizer.zero_grad(); optimizer.step(); loss.backward()
- C
loss.backward(); optimizer.step(); optimizer.zero_grad()
- D
optimizer.zero_grad(); loss.backward(); optimizer.step()
Correct answer
Doptimizer.zero_grad(); loss.backward(); optimizer.step()
Explanation
The standard order is: zero gradients, compute gradients via
backward(), then update parameters viastep(). This ensures fresh gradients are used for each update. - A
- 23
When using an optimizer, what must be passed to it during initialization?
- A
The model class and the number of epochs
- B
The model's parameters (via
model.parameters()) and the learning rate - C
Only the learning rate
- D
The loss function and the training data
Correct answer
BThe model's parameters (via
model.parameters()) and the learning rateExplanation
An optimizer like Adam needs the list of learnable parameters to update, typically obtained via
model.parameters(), and hyperparameters like the learning rate. - A
- 24
What is the fundamental difference between a toy linear regression model and a large language model (LLM) like Llama?
- A
Toy models cannot be trained with backpropagation
- B
LLMs use the same five-step training process but with many more parameters and layers
- C
LLMs use a completely different learning algorithm
- D
LLMs do not use gradient descent
Correct answer
BLLMs 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.
- A
- 25
Which of the following layers are inside a Transformer's feed-forward network (FFN)?
- A
nn.Linear, activation (e.g., GELU), and another nn.Linear
- B
nn.LSTM and nn.Linear
- C
nn.Conv2d, nn.ReLU, and nn.MaxPool2d
- D
Only nn.Linear layers
Correct answer
Ann.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.
- A

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