0
0
PyTorchml~20 mins

Tensor operations (add, mul, matmul) in PyTorch - Practice Problems & Coding Challenges

Choose your learning style9 modes available
Challenge - 5 Problems
🎖️
Tensor Mastery Badge
Get all challenges correct to earn this badge!
Test your skills under time pressure!
Predict Output
intermediate
2:00remaining
Output of element-wise addition and multiplication
What is the output of the following PyTorch code?
PyTorch
import torch

a = torch.tensor([1, 2, 3])
b = torch.tensor([4, 5, 6])
add_result = a + b
mul_result = a * b
print(add_result.tolist(), mul_result.tolist())
A[5, 7, 9] [5, 7, 9]
B[4, 7, 9] [4, 10, 18]
C[5, 7, 9] [4, 10, 18]
D[5, 7, 9] [1, 2, 3]
Attempts:
2 left
💡 Hint
Remember that + and * between tensors perform element-wise operations.
Model Choice
intermediate
1:30remaining
Choosing the correct operation for matrix multiplication
Which PyTorch operation correctly performs matrix multiplication between two 2D tensors?
Atorch.matmul(a, b)
Btorch.mul(a, b)
Ctorch.add(a, b)
Da + b
Attempts:
2 left
💡 Hint
Matrix multiplication is not element-wise addition or multiplication.
🔧 Debug
advanced
2:00remaining
Identify the error in tensor multiplication
What error will the following code raise?
PyTorch
import torch

a = torch.tensor([1, 2, 3])
b = torch.tensor([[4, 5, 6], [7, 8, 9]])
result = a * b
print(result)
AValueError: operands could not be broadcast together with shapes (3,) (2,3)
BNo error, outputs element-wise multiplication
CTypeError: unsupported operand type(s) for *: 'list' and 'Tensor'
DRuntimeError: The size of tensor a (3) must match the size of tensor b (2) at non-singleton dimension 0
Attempts:
2 left
💡 Hint
Check if the shapes of the tensors are compatible for element-wise multiplication.
Metrics
advanced
1:30remaining
Calculate output shape after matrix multiplication
Given two tensors a and b with shapes (4, 3) and (3, 5), what is the shape of torch.matmul(a, b)?
A(4, 5)
B(3, 3)
C(5, 4)
D(4, 3)
Attempts:
2 left
💡 Hint
Matrix multiplication shape rule: (m, n) x (n, p) = (m, p).
🧠 Conceptual
expert
2:30remaining
Difference between torch.mul and torch.matmul
Which statement correctly describes the difference between torch.mul and torch.matmul?
Atorch.mul performs matrix multiplication; torch.matmul performs element-wise multiplication.
BBoth perform element-wise multiplication but torch.matmul supports broadcasting.
CBoth perform matrix multiplication but torch.mul is faster.
Dtorch.mul performs element-wise multiplication; torch.matmul performs matrix multiplication following linear algebra rules.
Attempts:
2 left
💡 Hint
Think about how each function treats tensor dimensions and multiplication rules.