Python / PyTorch Fundamentals Interview Questions
What are the most important tensor operations in PyTorch?
PyTorch provides a rich set of tensor operations covering arithmetic, shape manipulation, reduction, and linear algebra. Most have both a functional form (torch.add) and a method form (tensor.add), plus in-place variants with a trailing underscore (tensor.add_).
import torch a = torch.tensor([[1.,2.,3.],[4.,5.,6.]]) b = torch.tensor([[7.,8.,9.],[10.,11.,12.]]) # ââ Arithmetic print(a + b) # element-wise add print(a * b) # element-wise multiply (Hadamard) print(torch.matmul(a, b.T)) # matrix multiply (2Ã3) @ (3Ã2) â (2Ã2) print(a @ b.T) # same with @ operator # ââ Shape manipulation print(a.shape) # torch.Size([2, 3]) print(a.reshape(3, 2)) # (3, 2) â new view if possible print(a.view(6)) # (6,) â must be contiguous print(a.unsqueeze(0).shape) # (1, 2, 3) â add dim print(a.squeeze(0).shape) # removes dim of size 1 print(torch.cat([a, b], dim=0)) # (4, 3) â concatenate rows print(torch.stack([a, b], dim=0)) # (2, 2, 3) â new dim print(a.permute(1, 0)) # (3, 2) â transpose # ââ Reduction print(a.sum()) # scalar sum print(a.sum(dim=1)) # sum along rows â (2,) print(a.mean(dim=0)) # mean along columns â (3,) print(a.max(), a.min()) print(a.argmax()) # index of max (flattened) # ââ In-place (modifies tensor, avoids memory allocation) a.add_(1) # a += 1 a.mul_(2) # a *= 2 # Warning: in-place ops on tensors requiring grad can cause issues!
Key distinction: reshape returns a view when possible (no copy) and falls back to a copy if the tensor is not contiguous. view always requires a contiguous tensor and always returns a view. Use contiguous().view() or just reshape() to be safe.
More Related questions...