Key terms for this tutorial
Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.
- attention
- A mechanism where each output position mixes input positions, weighted by how relevant they are.
- batch
- A small group of examples processed together. Batches let us estimate gradients quickly and use hardware efficiently.
- tensor
- A multi-dimensional array of numbers, the basic data type in deep learning.
- CUDA
- NVIDIA's parallel computing platform. `device = 'cuda'` tells PyTorch to run on a GPU.
- stride
- How far a convolution or window moves across an image or sequence.
Strides and views
A tensor is a data pointer plus a shape and a stride. The stride tells how many bytes to skip to move along each axis. A transpose is often just a stride swap, not a copy.
import torch
x = torch.arange(6).reshape(2, 3)
print('shape:', x.shape)
print('strides:', x.stride())
y = x.t()
print('transposed strides:', y.stride())
print('shares memory:', y.storage().data_ptr() == x.storage().data_ptr())
shape: torch.Size([2, 3]) strides: (3, 1) transposed strides: (1, 3) shares memory: True
Line-by-line: strides.py
Read this slowly. Each line does one small, concrete thing.
import torch— Import thetorchlibrary so we can use its built-in tools.print('shape:', x.shape)— Print a result so we can see what the model learned.print('strides:', x.stride())— Print a result so we can see what the model learned.print('transposed strides:', y.stride())— Print a result so we can see what the model learned.print('shares memory:', y.storage().data_ptr() == x.storage().data_ptr())— Print a result so we can see what the model learned.
Pop-in: RAG gives the model a textbook at test time
A language model only knows what it was trained on. RAG lets it look up relevant documents before answering, so it can use facts that were not in the training data.
Views save memory but can cause non-contiguous layouts. Before passing to a GPU kernel, you may need .contiguous().
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Tensors — Deep Dive'. Explain the section 'Strides and views' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
Einstein summation
einsum is a compact notation for matrix multiplication, batched operations, traces, and reductions. If you can write the index equation, you can avoid reshape gymnastics.
import torch
B, T, D = 2, 4, 3
Q = torch.randn(B, T, D)
K = torch.randn(B, T, D)
# batch matrix multiply Q @ K.T for each batch
scores = torch.einsum('btd,bTd->btT', Q, K)
print('scores shape:', scores.shape)
scores shape: torch.Size([2, 4, 4])
Line-by-line: einsum.py
Read this slowly. Each line does one small, concrete thing.
import torch— Import thetorchlibrary so we can use its built-in tools.Q = torch.randn(B, T, D)— Create a tensor filled with random numbers to use as fake data or initial weights.K = torch.randn(B, T, D)— Create a tensor filled with random numbers to use as fake data or initial weights.print('scores shape:', scores.shape)— Print a result so we can see what the model learned.
Pop-in: Read the code one block at a time
Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.
The string 'btd,bTd->btT' means: sum over the shared d dimension and keep batch b and the two time axes. This is exactly the attention score computation.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Tensors — Deep Dive'. Explain the section 'Einstein summation' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
GPU tensors and a peek at autograd
Moving a tensor to the GPU copies it to accelerator memory. Operations then run on CUDA kernels. PyTorch's autograd builds a directed graph of operations so backward() can propagate gradients.
import torch
x = torch.tensor([2.0, 3.0], requires_grad=True)
y = x ** 2
z = y.sum()
z.backward()
print('grad:', x.grad)
grad: tensor([4., 6.])
Line-by-line: gpu_autograd.py
Read this slowly. Each line does one small, concrete thing.
import torch— Import thetorchlibrary so we can use its built-in tools.x = torch.tensor([2.0, 3.0], requires_grad=True)— Create a PyTorch tensor from raw Python numbers.z.backward()— Compute gradients: how much each weight contributed to the loss.print('grad:', x.grad)— Print a result so we can see what the model learned.
Pop-in: Read the code one block at a time
Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.
When should you call .contiguous()?
You transposed a tensor and now a CUDA kernel complains. Why?
Transposes are stride views. Some kernels expect contiguous memory, so .contiguous() creates a fresh, row-major copy.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Tensors — Deep Dive'. The practice question 'When should you call .contiguous()?' asks: You transposed a tensor and now a CUDA kernel complains. Why? The answer is: Transposes are stride views. Some kernels expect contiguous memory, so .contiguous() creates a fresh, row-major copy.. Explain the concept behind this in simple terms.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Tensors — Deep Dive'. Explain the section 'GPU tensors and a peek at autograd' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.
Check yourself
Why does einsum help attention?
What does torch.einsum('btd,bTd->btT', Q, K) compute?
For each batch, it computes the dot product of every query vector with every key vector, producing a T-by-T score matrix.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Tensors — Deep Dive'. The practice question 'Why does einsum help attention?' asks: What does torch.einsum('btd,bTd->btT', Q, K) compute? The answer is: For each batch, it computes the dot product of every query vector with every key vector, producing a T-by-T score matrix.. Explain the concept behind this in simple terms.
Stuck or curious? Explain this to me on ChatGPT
Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Tensors — Deep Dive'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.
Three questions
1. What is a stride?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Tensors — Deep Dive'. The quiz asks: What is a stride? The correct answer is: The number of bytes to advance along each dimension. Explain why that answer is right and why the other choices are wrong, using a simple example.
2. What does einsum 'btd,bTd->btT' compute?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Tensors — Deep Dive'. The quiz asks: What does einsum 'btd,bTd->btT' compute? The correct answer is: Batch query-key dot products for attention. Explain why that answer is right and why the other choices are wrong, using a simple example.
3. Why does a transposed tensor sometimes need .contiguous()?
Stuck or curious? Explain this question to me on ChatGPT
Prompt: I am a beginner AI engineer studying 'AI Engineer: Tensors — Deep Dive'. The quiz asks: Why does a transposed tensor sometimes need .contiguous()? The correct answer is: Because the layout is non-contiguous and some kernels need compact memory. Explain why that answer is right and why the other choices are wrong, using a simple example.
Keep learning
With tensors mastered, see how optimizers really move on a loss surface.
Part of the CodeHS tutorial library.