What does the add operation do on tensors in PyTorch?
The add operation adds corresponding elements of two tensors of the same shape, producing a new tensor with the summed values.
Click to reveal answer
intermediate
Explain the difference between mul and matmul in PyTorch tensor operations.
mul performs element-wise multiplication between two tensors of the same shape, multiplying each element individually. matmul performs matrix multiplication, combining rows and columns according to linear algebra rules.
Click to reveal answer
intermediate
What shape requirements must tensors meet to use matmul in PyTorch?
For matmul, the inner dimensions must match: if tensor A is shape (m, n), tensor B must be shape (n, p). The result will have shape (m, p).
Click to reveal answer
advanced
How does broadcasting work with add or mul in PyTorch?
Broadcasting lets PyTorch automatically expand smaller tensors to match the shape of larger tensors when performing add or mul, as long as their shapes are compatible.
Click to reveal answer
beginner
Write a PyTorch code snippet to multiply two tensors element-wise and then add another tensor.
import torch
x = torch.tensor([1, 2, 3])
y = torch.tensor([4, 5, 6])
z = torch.tensor([7, 8, 9])
result = x.mul(y).add(z) # element-wise multiply x and y, then add z
print(result) # tensor([11, 18, 27])
Click to reveal answer
What does torch.matmul(A, B) compute if A is (2, 3) and B is (3, 4)?
AMatrix multiplication resulting in shape (2, 4)
BElement-wise multiplication resulting in shape (2, 3)
CElement-wise addition resulting in shape (2, 3)
DMatrix multiplication resulting in shape (3, 3)
✗ Incorrect
matmul multiplies matrices where inner dimensions match. Here, 3 matches 3, so output shape is (2, 4).
Which operation multiplies tensors element by element?
Amatmul
Badd
Cmul
Ddot
✗ Incorrect
mul performs element-wise multiplication between tensors.
If tensor A is shape (5,) and tensor B is shape (1,), what happens when you do A + B in PyTorch?
AError due to shape mismatch
BBroadcasting adds B to each element of A
CResult is shape (1,)
DResult is shape (5, 1)
✗ Incorrect
PyTorch broadcasts the smaller tensor B to match A's shape and adds element-wise.
What is the output of torch.add(torch.tensor([1,2]), torch.tensor([3,4]))?
Hint: Check tensor shapes before matmul to avoid mismatch [OK]
Common Mistakes:
Assuming 1D and 2D tensors always multiply
Ignoring shape rules for matmul
Thinking matmul works like element-wise multiply
5. Given two tensors a = torch.tensor([[1, 2], [3, 4]]) and b = torch.tensor([[2, 0], [1, 2]]), which code correctly computes the element-wise product and then adds the matrix product of a and b?