0
0
PyTorchml~5 mins

Tensor operations (add, mul, matmul) in PyTorch - Cheat Sheet & Quick Revision

Choose your learning style9 modes available
Recall & Review
beginner
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)
Which operation multiplies tensors element by element?
Amatmul
Badd
Cmul
Ddot
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)
What is the output of torch.add(torch.tensor([1,2]), torch.tensor([3,4]))?
Atensor([4, 6])
Btensor([3, 6])
Ctensor([1, 2, 3, 4])
DError
Which PyTorch function would you use to perform matrix multiplication?
Atorch.mul
Btorch.add
Ctorch.sum
Dtorch.matmul
Describe how add, mul, and matmul differ when working with tensors in PyTorch.
Think about how each operation combines tensor elements and their shape rules.
You got /4 concepts.
    Explain what broadcasting means in the context of tensor operations like add and mul in PyTorch.
    Imagine adding a small tensor to a bigger one without manually reshaping.
    You got /4 concepts.