Tensors and PyTorch Basics
Scalar, vector, matrix, tensor
Scalar - a single number, a point with no direction (age, temperature, price). -> 0D tensor
- Vector - list of numbers with direction and magnitude. A 768-dimension embedding is one vector. -> 1D tensor
- Matrix - grid of numbers with rows and columns. Q, K, V and weight matrices. -> 2D tensor
- Tensor - the generalisation of all of these. 3D, 4D, 5D and beyond.
A scalar, a vector and a matrix are all tensors. It is just a way of saying how many dimensions a value has. Same maths works for any dimension.
Why tensors suit deep learning: shapes
| Step | Shape | Rank |
|---|---|---|
| One sentence (3 tokens) | (3, 768) | 2D |
| Batch of 8 sentences | (8, 3, 768) | 3D |
| Split into 12 heads | (8, 12, 3, 64) | 4D |
- Each head gets 768 / 12 = 64 dimensions.
- Batching - pass a few sentences per step instead of all at once. Optimisation trick so the GPU is not overloaded.
- Tensors let us reshape and multiply across batches and heads easily.
Track how the shape changes at every step. That is how you follow what the code does.
Matrix transformations and dot product
Matrices do more than store numbers. Multiplying by the right matrix transforms the data.
- Rotation matrix [[0,-1],[1,0]] times (1,0) gives (0,1). Rotates 90 degrees.
- Scaling matrix [[2,0],[0,2]] doubles the size. 3 or 4 on the diagonal scales 3x or 4x.
- Stretch/squeeze: scale one axis only, e.g. 0.5 shrinks horizontally.
- Reflection (flip) and shear matrices also exist.
- An image is a matrix of pixels (256 x 256), so the same matrices rotate or scale whole images.
Dot product tells direction similarity.
- Same direction -> high
- Perpendicular (90 degrees) -> 0
- Opposite -> negative
- Attention uses Q dot K^T for exactly this: how relevant is one token to another.
Matrix multiplication: inner dimensions must match and cancel. (3,3) x (3,3) gives (3,3). A (3,3) times (4,3) fails, but transposing to (3,4) works and gives (3,4).
Creating tensors in PyTorch
import torch
print(torch.cuda.is_available()) # GPU present?
age = torch.tensor(20.0) # 0D
vec = torch.tensor([1,2,3,4]) # 1D, shape (4,)
mat = torch.tensor([[1,2,3],[4,5,6]]) # 2D, shape (2,3)
print(age.dim(), vec.dim(), mat.dim(), mat.shape)
torch.zeros(3,4) # all zeros
torch.ones(2,5) # all ones
torch.randn(3,3) # random, normal distribution
torch.arange(0,10) # 0..9, end excluded
torch.linspace(0,1,5) # 5 equally spaced values- torch.tensor - wrap any value as a tensor so tensor operations work later.
- randn - the extra n means numbers come from a normal (bell curve) distribution. Model weights usually start as random matrices like this.
- arange - start and end, sequential values.
- linspace - start, end, and how many values you want, equally spaced (step 0.25 here).
permute and view
x.permute(...) - you tell PyTorch which original dimension to put at each position.
x = torch.randn(8,128,12,64) # batch, tokens, heads, head_dim
y = x.permute(0,2,1,3) # (8,12,128,64)
x2 = torch.randn(3,4)
z = x2.view(4,3) # same data, new shape- Position 0 keeps dimension 0 (8), position 1 takes dimension 2 (12), position 2 takes dimension 1 (128), position 3 keeps 64.
- Why: matrix multiplication needs matching inner dimensions. Moving dimensions around makes that possible without manual shuffling.
- view reshapes (3,4) to (4,3). The memory pointer stays the same, so no copy is made. Only metadata changes. (Saves memory and time)
Why PyTorch, not Python loops
| CPU | GPU | |
|---|---|---|
| Cores | 8, 16, 32 | 5000 to 10000 |
| Each core | Complex, sequential tasks | Simple maths: multiply, add, divide |
| Best for | General programs | Matrix multiplication in ML |
- Triple nested Python loop vs A @ B on 100x100 matrices: about 18 s vs 0.01 s (~1500x faster).
- PyTorch is written in optimised C and CUDA. We get that speed for free.
- CUDA - programming language for NVIDIA GPUs.
- x.to('cuda') moves a tensor to the GPU; otherwise it stays on CPU.
- On small matrices (100x100) CPU and GPU are similar. As size grows (500 and up), GPU is about 40x faster.
How a tensor works inside
- Values - the actual numbers.
- Metadata - shape, device (CPU or GPU), dimensions, stride, gradient function.
- PyTorch can check from metadata alone whether two tensors can be multiplied.
- Stride - memory jump to the next row or column. For shape (3,4) the stride is (4,1).
Autograd and gradients
Autograd - PyTorch's automatic differentiation engine. It records every operation on a tracked tensor, then goes backwards through that record.
x = torch.tensor(3.0, requires_grad=True)
y = x**2
y.backward()
print(x.grad) # tensor(6.) = 2x
y = x**2
y.backward()
print(x.grad) # tensor(12.) accumulated
x.grad.zero_() # reset before next backward- requires_grad=True - tells PyTorch to store the computation graph because a backward pass will be needed. Without it, backward() fails.
- Gradients accumulate by default: 6 + 6 = 12. Zero them out to get 6 each time.
- In training we zero gradients every step so old calculations do not affect current ones.
- Without autograd you must derive every gradient by hand across all layers.
nn.Module and the five-line training step
class SimpleNet(nn.Module):
def __init__(self):
super().__init__()
self.l1 = nn.Linear(784, 128)
self.relu = nn.ReLU()
self.l2 = nn.Linear(128, 10)
def forward(self, x):
return self.l2(self.relu(self.l1(x)))- init - define every layer and activation.
- forward - how data moves: layer 1 -> ReLU -> layer 2.
- nn.Linear(in, out) - weight matrix plus bias. Output = x W^T + b. Here 784 inputs -> 128 -> 10 outputs.
The training step used by every big model:
Glossary
- Tensor
- N-dimensional array of numbers; generalises scalar, vector and matrix.
- Batching
- Passing a few sentences at a time to the model so the hardware is not overloaded.
- permute
- PyTorch function that reorders a tensor's dimensions.
- view
- Reshapes a tensor by changing only metadata, with no copy.
- Autograd
- PyTorch's automatic differentiation engine.
- requires_grad
- Flag telling PyTorch to track operations for gradient calculation.
- CUDA
- NVIDIA's programming platform for GPUs.
- Gradient
- Rate of change; shows how much an input affects the final loss.