Table of Contents


Objectives

  • no pretrained weights, no internet, no libraries beyond torch
  • the only knowledge comes from a local text file (ditados_populares.txt)
  • the core new idea is attention: every character decides which previous characters matter to predict the next one

This is the follow-up to LM20-neural-net-intro: same task, same corpus — but the RNN is replaced by a GPT-style attention model.

Configuration

ParameterValueMeaning
BLOCK_SIZE64context: how many characters the model can look back at
BATCH_SIZE4sequences per training step
N_EMBD64embedding dimension
N_HEAD4attention heads
N_LAYER2transformer blocks
NUM_EPOCHS3000training iterations
LR0.001learning rate

Everything is deliberately small — a laptop trains it in minutes — yet the architecture is exactly the recipe used by GPT-style models, just scaled down.

import torch
import torch.nn as nn
import torch.nn.functional as F
import math
import random
BLOCK_SIZE = 16      # context: how many characters the model can look back at
BATCH_SIZE = 4       # sequences per training step
N_EMBD = 64          # embedding dimension
N_HEAD = 4           # attention heads
N_LAYER = 2          # transformer blocks
NUM_EPOCHS = 3000
LR = 0.001
 
torch.manual_seed(50)
random.seed(50)

Load the knowledge base

The model’s entire “world knowledge” is this single text file of Portuguese proverbs. Newlines become spaces so the model sees one long stream of text.

with open("ditados_populares.txt", "r", encoding="utf-8") as f:
    text = f.read().replace('\n', ' ').lower()
print(f"characters in text: {len(text)}")
text[:50]

Vocabulary

Character-level model: every unique character is a token. The two lambdas convert between text and integer ids; decoding encode("hello") straight back is a quick roundtrip sanity check:

chars = sorted(list(set(text)))
char2idx = {ch: i for i, ch in enumerate(chars)}
idx2char = {i: ch for ch, i in char2idx.items()}
vocab_size = len(chars)
 
encode = lambda s: [char2idx[c] for c in s]
decode = lambda l: ''.join(idx2char[i] for i in l)
 
print(f"vocab_size: {vocab_size}")
print(decode(encode("hello")))

Train / validation split

90% for training, 10% held out for validation. The validation loss is the honest measure: if it stops falling while the training loss keeps dropping, the model is memorising rather than generalising.

data = torch.tensor(encode(text), dtype=torch.long)
n = int(0.9 * len(data))
train_data = data[:n]
val_data = data[n:]
len(train_data), len(val_data)

Batches — predict the next character

Each sequence x is paired with y, the same text shifted one character to the left: at every position the model must predict the next character. A batch is a stack of BATCH_SIZE random windows of BLOCK_SIZE characters — shapes for both x and y. Since every position contributes one prediction, a single batch yields training examples.

def get_batch(split='train'):
    source = train_data if split == 'train' else val_data
    ix = torch.randint(len(source) - BLOCK_SIZE - 1, (BATCH_SIZE,))
    x = torch.stack([source[i:i + BLOCK_SIZE] for i in ix])
    y = torch.stack([source[i + 1:i + BLOCK_SIZE + 1] for i in ix])
    return x, y
 
x, y = get_batch()
print('x:', decode(x[0].tolist()))
print('y:', decode(y[0].tolist()))

Self-attention — the core idea

decoder-self-attention-causal-masking.png
Masked self-attention: queries and keys produce the alignments (attention weights), which blend the values into a context vector. Image: dvgodoy / dl-visuals, CC BY 4.0.

The mechanism comes from the paper Attention Is All You Need (Vaswani et al., NeurIPS 2017), which introduced the Transformer architecture.

For each character three vectors are computed:

  • Query — “what am I looking for?”
  • Key — “what do I contain?”
  • Value — “what do I communicate?”

The attention weights are : how relevant every earlier character is to the current one. Dividing by (the head size) keeps the dot products from growing too large — without it, the softmax saturates and the weights go nearly one-hot. The causal mask (lower-triangular) hides future characters, so predictions stay honest.

Compare with the RNN in LM20 (03_llm.ipynb): an RNN squeezes the whole past into one hidden state, while attention gives every position direct access to all previous positions.

class SelfAttentionHead(nn.Module):
    def __init__(self, head_size):
        super().__init__()
        self.key = nn.Linear(N_EMBD, head_size, bias=False)
        self.query = nn.Linear(N_EMBD, head_size, bias=False)
        self.value = nn.Linear(N_EMBD, head_size, bias=False)
        self.register_buffer('tril', 
          torch.tril(torch.ones(BLOCK_SIZE, BLOCK_SIZE)))
 
    def forward(self, x):
        B, T, C = x.shape
        k = self.key(x)          # (B, T, head_size)
        q = self.query(x)        # (B, T, head_size)
        
        # scaled dot product
        wei = q @ k.transpose(-2, -1) / math.sqrt(k.size(-1)) 
        
        # causal mask
        wei = wei.masked_fill(self.tril[:T, :T] == 0, float('-inf')) 
        wei = F.softmax(wei, dim=-1)  # (B, T, T)
        v = self.value(x)             # (B, T, head_size)
        return wei @ v                # weighted sum of values

Multi-head attention

Several attention heads run in parallel, each learning its own pattern (spaces, word starts, rhymes…). Each head works in a smaller subspace — 64 embedding dims ÷ 4 heads = 16 dims per head — and their outputs are concatenated and projected back to the embedding size.

class MultiHeadAttention(nn.Module):
    def __init__(self, num_heads, head_size):
        super().__init__()
        self.heads = nn.ModuleList([SelfAttentionHead(head_size) for _ in range(num_heads)])
        self.proj = nn.Linear(N_EMBD, N_EMBD)
 
    def forward(self, x):
        out = torch.cat([h(x) for h in self.heads], dim=-1)
        return self.proj(out)

Feed-forward network

After characters exchange information through attention, each position “thinks” on its own through a small two-layer network: expand to 4× the embedding size, ReLU, project back. It is applied identically and independently to every position.

class FeedForward(nn.Module):
    def __init__(self, n_embd):
        super().__init__()
        self.net = nn.Sequential(
            nn.Linear(n_embd, 4 * n_embd),
            nn.ReLU(),
            nn.Linear(4 * n_embd, n_embd),
        )
 
    def forward(self, x):
        return self.net(x)

Transformer block

Attention lets characters communicate, the feed-forward network processes each position. The residual connections (x + ...) give every sublayer a shortcut path, which keeps gradients healthy so deep stacks stay trainable, and the layer norms before each sublayer stabilise training — the pre-norm arrangement used by GPT-2.

class Block(nn.Module):
    def __init__(self, n_embd, num_heads):
        super().__init__()
        head_size = n_embd // num_heads
        self.sa = MultiHeadAttention(num_heads, head_size)
        self.ffwd = FeedForward(n_embd)
        self.ln1 = nn.LayerNorm(n_embd)
        self.ln2 = nn.LayerNorm(n_embd)
 
    def forward(self, x):
        x = x + self.sa(self.ln1(x))
        x = x + self.ffwd(self.ln2(x))
        return x

The full model

Token embeddings plus positional embeddings — attention by itself is order-agnostic, so without positions "ab" and "ba" would look identical to the model. On top: a stack of transformer blocks, a final layer norm, and a linear head that scores every character in the vocabulary.

class MiniLLM(nn.Module):
    def __init__(self):
        super().__init__()
        self.token_embedding = nn.Embedding(vocab_size, N_EMBD)
        self.position_embedding = nn.Embedding(BLOCK_SIZE, N_EMBD)
        self.blocks = nn.Sequential(*[Block(N_EMBD, N_HEAD) for _ in range(N_LAYER)])
        self.ln_f = nn.LayerNorm(N_EMBD)
        self.head = nn.Linear(N_EMBD, vocab_size)
 
    def forward(self, idx, targets=None):
        B, T = idx.shape
        x = self.token_embedding(idx) + self.position_embedding(torch.arange(T))
        x = self.blocks(x)
        x = self.ln_f(x)
        logits = self.head(x)
        loss = None
        if targets is not None:
            loss = F.cross_entropy(logits.reshape(B * T, vocab_size), targets.reshape(B * T))
        return logits, loss
 
    def generate(self, idx, max_new_tokens):
        for _ in range(max_new_tokens):
            idx_cond = idx[:, -BLOCK_SIZE:]              # keep the last BLOCK_SIZE characters
            logits, _ = self(idx_cond)
            logits = logits[:, -1, :]                    # score for the next character
            probs = F.softmax(logits, dim=-1)
            next_idx = torch.multinomial(probs, num_samples=1)
            idx = torch.cat([idx, next_idx], dim=1)
            if idx2char[next_idx.item()] == '.':  # '.' ends the sentence
                break
        return idx
 
model = MiniLLM()
optimizer = torch.optim.Adam(model.parameters(), lr=LR)
print(f"parameters: {sum(p.numel() for p in model.parameters()):,}")

Training

The model completes a prompt one character at a time: keep only the last BLOCK_SIZE characters, sample the next character from the predicted probabilities, append it and repeat. Generation stops as soon as a '.' closes the sentence.

print("Training...")
for epoch in range(NUM_EPOCHS):
    model.train()
    x, y = get_batch('train')
    logits, loss = model(x, y)
 
    optimizer.zero_grad()
    loss.backward()
    optimizer.step()
 
    if (epoch + 1) % 200 == 0:
        model.eval()
        with torch.no_grad():
            xv, yv = get_batch('val')
            _, val_loss = model(xv, yv)
        print(f"Epoch {epoch+1}/{NUM_EPOCHS}, Train loss: {loss.item():.4f}, Val loss: {val_loss.item():.4f}")

Ask questions

def generate_answer(prompt, max_len=72):
    model.eval()
    with torch.no_grad():
        idx = torch.tensor([encode(prompt.lower())], dtype=torch.long)
        idx = model.generate(idx, max_len)
        return decode(idx[0].tolist())
 

Same prompts as 03_llm.ipynb — compare the attention model with the RNN.

question = 'aguas'
print(generate_answer(question))
question = 'Completa o ditado amigo nao'
print(generate_answer(question))

From RNN to attention

03_llm (RNN)this notebook (attention)
Memory of the pastone hidden statedirect access to all previous characters
Processingsequential, character by characterparallel within a block
Architecturenn.RNN + linear layerself-attention + feed-forward blocks
Samplinggreedy (argmax)probabilistic (multinomial)

This stack — embeddings, masked self-attention, feed-forward, residual connections — is the decoder of a GPT-style Transformer, built from scratch. Scaling the same recipe up in data, context length and parameters leads to modern LLMs; the full blueprint is the Attention Is All You Need paper.