← govind p lal
AI and ML Bootcamp · Lecture 6 · lecture notes

Tensors and PyTorch Basics

In short — What is a tensor, and why use PyTorch instead of plain Python loops or NumPy? Tensors generalise scalars, vectors and matrices, and give shape to batches and heads. PyTorch runs the maths fast on GPUs and computes gradients automatically.

Scalar, vector, matrix, tensor

builds on Lecture 2: Week 1 - AI and ML | Fast-tracking the course of AI | 18/01/2026, Lecture 5: Week 4 - AI&ML | Transformers: Part 2 | 07/02/2026

Scalar - a single number, a point with no direction (age, temperature, price). -> 0D tensor

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

builds on Lecture 5: Week 4 - AI&ML | Transformers: Part 2 | 07/02/2026, Lecture 4: Week 3 - AI and ML | Transformers- Part 1 | 31/01/2026
StepShapeRank
One sentence (3 tokens)(3, 768)2D
Batch of 8 sentences(8, 3, 768)3D
Split into 12 heads(8, 12, 3, 64)4D
!

Track how the shape changes at every step. That is how you follow what the code does.

Matrix transformations and dot product

builds on Lecture 5: Week 4 - AI&ML | Transformers: Part 2 | 07/02/2026

Matrices do more than store numbers. Multiplying by the right matrix transforms the data.

Dot product tells direction similarity.

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

builds on Lecture 4: Week 3 - AI and ML | Transformers- Part 1 | 31/01/2026
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

permute and view

builds on Lecture 5: Week 4 - AI&ML | Transformers: Part 2 | 07/02/2026

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

Why PyTorch, not Python loops

builds on Lecture 3: Week 2 - AI and ML | Neural Networks from Scratch | 24/01/2026
CPUGPU
Cores8, 16, 325000 to 10000
Each coreComplex, sequential tasksSimple maths: multiply, add, divide
Best forGeneral programsMatrix multiplication in ML

How a tensor works inside

Autograd and gradients

adds to earlier · How autograd tracks a computation graph, requires_grad, gradient accumulation and zero_grad. · builds on Lecture 3: Week 2 - AI and ML | Neural Networks from Scratch | 24/01/2026, Lecture 3: Week 2 - AI and ML | Neural Networks from Scratch | 24/01/2026

Autograd - PyTorch's automatic differentiation engine. It records every operation on a tracked tensor, then goes backwards through that record.

y.backward()xrequires_grad=Truex squaredplus 5yx.grad
Forward builds the graph; backward traverses it in reverse.
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

nn.Module and the five-line training step

adds to earlier · nn.Module structure, nn.Linear behaviour, and the zero_grad step in the loop. · builds on Lecture 3: Week 2 - AI and ML | Neural Networks from Scratch | 24/01/2026, Lecture 3: Week 2 - AI and ML | Neural Networks from Scratch | 24/01/2026
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)))

The training step used by every big model:

repeatForward passCompute losszero_gradloss.backward()Update weights
Five-step loop; the loss can be MSE, L1, L2, and so on.

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.