What a tensor is
In machine learning a tensor is an n-dimensional array of numbers. Inputs, weights, activations and outputs are all tensors. The rank is how many dimensions it has, and the shape is how long each one is.
Rank 0: scalar
shape ()
Rank 1: vector
shape (3,)
Rank 2: matrix
shape (3, 4)
Rank 3: stack
shape (3, 3, 3)
A framework tensor in PyTorch or TensorFlow does three things a plain array does not:
- It can live on a GPU, where operations like matrix multiplication run across thousands of cores at once.
- It supports autograd: the framework records each operation so it can compute gradients for backpropagation. That is how a model learns.
- It has one dtype for all its numbers, such as
float32,float16/bfloat16orint8.
Where tensors show up in an LLM
- Embeddings: 10 tokens, each a 4,096-number vector, make a
(10, 4096)tensor. A batch of 8 sentences is(8, 10, 4096). - Weights: a 7B model is about 7 billion numbers spread across its layers' weight tensors.
- Quantization: storing those weights as
int8orint4instead of 2-bytefloat16shrinks memory 2 to 4 times. - KV cache: roughly
(layers, 2, batch, heads, seq_len, head_dim), and it grows with every token in the sequence.
How long training takes on a laptop
Training costs roughly 6 × parameters × tokens floating-point operations. The Chinchilla rule of thumb is about 20 training tokens per parameter, so a 200M-parameter model wants about 4B tokens: 6 × 200M × 4B ≈ 4.8 × 1018 FLOPs.
The base M4 GPU peaks around 4 TFLOPS. PyTorch on Apple's MPS backend typically reaches a quarter to a third of that, call it 1.2 TFLOPS, or about 1,000 to 2,000 tokens a second. A fanless MacBook Air also slows itself down over a multi-day run.
- 100M tokens2 days
toy model, basic grammar: 1 to 2 days
- 500M tokens8 days
coherent simple stories (TinyStories): 5 to 8 days
- 1B tokens14 days
a usable small model: about 2 weeks
- 4B tokens56 days
Chinchilla-optimal: 6 to 8 weeks
Memory is not the problem. Weights, gradients and AdamW state come to about 3.2 GB in fp32, which fits in 24 GB with a modest batch and gradient accumulation. Compute is the bottleneck.
And GPT-2 Small?
GPT-2 Small has 124M parameters. The original recipe, as reproduced in Karpathy's llm.c, trains on about 10B tokens: 7.4 × 1018 FLOPs. That is roughly 70 to 90 days nonstop on the Air, against about 90 minutes on eight A100s.
The community nanoGPT speedrun reaches the same quality with under 1B tokens, using the Muon optimizer and other tricks. That brings it to about 1 to 2 weeks on the Air, though parts of that code are built for NVIDIA GPUs and would need porting to MPS or MLX.
Tiny model locally
10–30M params, nanoGPT, overnight
Real run in the cloud
one H100 for a few hours
Mac for the rest
inference and LoRA fine-tuning with MLX
The bigram model
The simplest language model there is, and the first step toward GPT-2. It predicts the next character from the current one only. Trained on a list of names, the whole recipe is five steps.
each pair adds 1 to N[current][next]
1. Data
names, wrapped in .
2. Pairs
2-character sliding window
3. Count
N[cur][next] += 1 in a 27 × 27 tensor
4. Normalize
P = (N + 1) / row sum
5. Sample
start at ., draw until .
The 27 × 27 count table covers 26 letters plus the dot, so the model is 729 numbers with no layers and no neurons. Here it is for about two hundred common first names.
Normalizing a row turns counts into probabilities for the next character. Adding 1 to every count first (smoothing) means no pair gets 0%, which would otherwise make the loss infinite for an unseen pair.
- . → a12.8%
- . → e9.7%
- . → j8.4%
- . → l7.9%
- . → c7.5%
- . → s7.0%
Scoring it
The model is scored by the average negative log-likelihood (NLL) of the pairs in the data. Lower is better. Guessing uniformly among 27 characters scores ln(27) ≈ 3.30, and a bigram model on names gets to about 2.45.
The same model as a neural net
You can learn the same table with gradient descent instead of counting. One-hot encode the current character and multiply by a 27 × 27 weight matrix W, which is the same as looking up a row. Softmax gives probabilities, and training minimizes cross-entropy. W ends up close to the log of the count table.
import torch, torch.nn.functional as F
# xs, ys: tensors of character indices for every (current, next) pair
W = torch.randn(27, 27, requires_grad=True)
for step in range(200):
logits = W[xs] # row lookup = one_hot(xs) @ W
loss = F.cross_entropy(logits, ys) # softmax + NLL in one call
W.grad = None
loss.backward()
W.data -= 50 * W.grad # plain gradient descentThat ties it back to tensors: W is a rank-2 tensor, and training nudges it until each row matches the data.
From bigram to GPT-2
Bigram
1 character of context
N-gram
2–3 characters, table grows as 27ⁿ
MLP
learned embeddings over several characters
Transformer
attention over every earlier token (GPT-2)