smartyfy.mrindigi.com

Python Master Course V2 — 156. Neural Text Models and Sequence Generation

Purpose and learning outcomes

A neural language model replaces a table of transitions with a trainable function. You will use a small gated recurrent unit, or GRU, to predict the next character from a running hidden state. The entire corpus is included below and the run is deliberately bounded. Generated fragments demonstrate sequence mechanics; they do not establish useful conversation, factual knowledge, or general language competence.

  • Create token vocabularies and shifted prediction targets
  • Train a tiny recurrent next-token model
  • Compare greedy and temperature-based sampling with length limits

Prerequisites

  • 147: recurrent networks
  • 151 and 155: tokenization and language modeling

Environment and execution

Use a project-specific virtual environment with a currently supported Python 3 release compatible with the packages below. Python 3.11 or 3.12 is a practical starting point. Run shell commands in a terminal, then run the Python blocks in order in one script or notebook kernel. They use only included data and local CPU computation. No account, API key, camera, or external dataset is required. Record the installed package versions with python -m pip freeze when you save your results; a random seed does not guarantee identical numerical behavior across library versions.

python -m venv .venv
# macOS/Linux: source .venv/bin/activate
# Windows PowerShell: .venv\Scripts\Activate.ps1
python -m pip install torch

Understand the model and its assumptions

An embedding converts each integer token ID into a learned vector. The GRU reads vectors in order and updates a hidden state, allowing its prediction to depend on more than the immediately previous character. A linear output layer converts each hidden state into one logit per vocabulary item. Logits are unnormalized scores; cross-entropy combines the normalization and target comparison during training.

Inputs and targets must be shifted by one position. For a passage beginning ab, the first input is BOS and its target is a; the next input is a and its target is b. If inputs and targets are identical, the network can learn copying rather than next-token prediction. Each passage gets its own boundary markers and hidden-state reset. Padding makes a rectangular batch, but padded targets must be ignored in the loss.

Teacher forcing supplies the actual previous character during training. At generation time the model consumes its own predictions, so a mistake can move it into unfamiliar contexts. Greedy decoding selects the largest next-token score. Temperature sampling divides logits by a positive temperature before softmax; lower values concentrate probability, while higher values spread it. Neither operation improves the model's factual reliability.

The vocabulary is a declared alphabet plus special tokens. We do not discover characters from validation or test passages. All tensors remain on CPU, the model is tiny, and the epoch count is fixed before evaluation. Reusing the short corpus many times mainly teaches its patterns and may cause memorization. Seeds make the experiment easier to repeat within one environment, but different numerical backends and versions can still change training trajectories.

Worked example: build it in stages

Build padded input-target pairs with a helper that rejects excessively long passages. Use batch_first=True so model tensors follow batch, time, features. Flatten only the batch and time axes for cross-entropy. Reset gradients every step and clip their norm to limit unusually large updates. Evaluation switches model behavior and disables gradient recording; these are separate responsibilities.

import string
import torch
from torch import nn
from torch.nn import functional as F

torch.manual_seed(7)
torch.set_num_threads(1)
characters = list(string.ascii_lowercase + " ")
vocabulary = ["<PAD>", "<BOS>", "<EOS>", "<UNK>"] + characters
stoi = {token: i for i, token in enumerate(vocabulary)}
PAD, BOS, EOS, UNK = range(4)
training = ["the lamp is warm", "the room is calm", "a bird rests", "a dog rests"]
validation = ["the bird is calm", "a lamp is warm"]
final_test = ["the dog is calm"]

def batch(passages):
    sequences = [[BOS] + [stoi.get(c, UNK) for c in text] + [EOS]
                 for text in passages]
    width = max(len(s)-1 for s in sequences)
    if width > 64:
        raise ValueError("passage exceeds the teaching context limit")
    x = torch.full((len(sequences), width), PAD, dtype=torch.long)
    y = x.clone()
    for i, seq in enumerate(sequences):
        x[i, :len(seq)-1] = torch.tensor(seq[:-1])
        y[i, :len(seq)-1] = torch.tensor(seq[1:])
    return x, y

class CharacterGRU(nn.Module):
    def __init__(self):
        super().__init__()
        self.embedding = nn.Embedding(len(vocabulary), 16, padding_idx=PAD)
        self.recurrent = nn.GRU(16, 32, batch_first=True)
        self.output = nn.Linear(32, len(vocabulary))
    def forward(self, x):
        states, _ = self.recurrent(self.embedding(x))
        return self.output(states)

model = CharacterGRU()
optimizer = torch.optim.Adam(model.parameters(), lr=0.02)
x, y = batch(training)
for epoch in range(80):
    model.train()
    optimizer.zero_grad()
    logits = model(x)
    loss = F.cross_entropy(logits.reshape(-1, len(vocabulary)),
                           y.reshape(-1), ignore_index=PAD)
    loss.backward()
    nn.utils.clip_grad_norm_(model.parameters(), 1.0)
    optimizer.step()

@torch.no_grad()
def evaluate(passages):
    model.eval()
    a, b = batch(passages)
    return F.cross_entropy(model(a).reshape(-1, len(vocabulary)),
                           b.reshape(-1), ignore_index=PAD).item()

@torch.no_grad()
def generate(temperature=1.0, greedy=False, max_tokens=50):
    if temperature <= 0 or not 1 <= max_tokens <= 60:
        raise ValueError("use positive temperature and 1..60 tokens")
    model.eval()
    token_ids, pieces = [BOS], []
    for _ in range(max_tokens):
        logits = model(torch.tensor([token_ids]))[0, -1].clone()
        logits[[PAD, BOS]] = -torch.inf
        if greedy:
            token = int(logits.argmax())
        else:
            token = int(torch.multinomial((logits / temperature).softmax(0), 1))
        if token == EOS:
            break
        token_ids.append(token)
        pieces.append(vocabulary[token])
    return "".join(pieces)

print("validation nats:", evaluate(validation))
print("test nats:", evaluate(final_test))
print("greedy:", generate(greedy=True))
print("sample:", generate(temperature=0.8))

What the output means

The program reports measured losses in nats per non-padding target and two generated strings. Exact losses, convergence speed, and samples are intentionally unspecified. A low training loss alongside worse held-out loss is compatible with memorization. The sampled output cannot contain PAD or BOS because generation masks them, although evaluation still includes their logits in the model's full predictive distribution.

Guided lab and acceptance checks

Before training, inspect one row of x and y and manually decode the shift. Check that the count of non-padding targets equals the sum of passage lengths plus one end token per passage. After the fixed run, compare greedy output with temperatures 0.5 and 1.5 without changing the trained weights.

Acceptance requires a finite loss, correct target shifting, a separate passage split, and a hard generation limit. Keep a record of the model configuration and alphabet. If you experiment with epoch counts, choose them using validation only and reserve a new final passage for an independent comparison.

Common mistakes and repairs

Passing probabilities into cross_entropy applies the wrong interface; supply logits. Forgetting zero_grad accumulates gradients across steps. Including padding in the loss rewards predicting blank batch filler. Carrying hidden states between unrelated passages invents context. Finally, a fluent memorized fragment is not evidence that the system can answer an unseen question correctly.

Questions and answers

Why does the GRU not require a causal attention mask?

A unidirectional GRU processes positions sequentially, so a state at a position depends on earlier inputs and that input, not later ones. A bidirectional recurrent model would see future context and would not be appropriate for this next-token setup without changing the task.

Why can padding after the end be ignored without packing here?

We use a unidirectional GRU and compute loss only on valid target positions. Later padded inputs cannot alter earlier states. Packing can improve efficiency, but this tiny batch prioritizes clarity. Bidirectional processing would require more care.

Does model.eval disable gradient computation?

No. It changes the behavior of modules such as dropout and batch normalization. The no_grad decorator disables gradient recording for the evaluation function. Using both makes intent clear and avoids unnecessary memory use.

Why mask PAD and BOS during generation?

Those symbols organize batches and starts; they are not valid continuation content. A decoder can restrict allowed outcomes, but this changes its sampling distribution. Document the restriction rather than assuming decoded probabilities are unchanged model probabilities.

Can a temperature of zero implement greedy decoding?

Direct division by zero is invalid. Use an explicit argmax branch for greedy decoding, as the example does. Positive temperatures support probabilistic sampling; greedy selection is a separate deterministic choice for fixed logits.

Exercises

1. Assert the expected number of supervised targets. 2. Verify output shape before training. 3. Explain why generation can diverge from training even with low loss.

Worked solutions and reasoning

Teacher forcing gives the model correct previous characters during fitting. Generated mistakes become future inputs, producing a different context distribution. For a minimal CPU installation, use the official selector's CPU option for your operating system if the default torch package is unsuitable.

x_check, y_check = batch(training)
assert int((y_check != PAD).sum()) == sum(len(s) + 1 for s in training)
with torch.no_grad():
    output = model(x_check)
assert output.shape == (*x_check.shape, len(vocabulary))
assert torch.isfinite(output).all()

Recap

A recurrent language model combines token IDs, learned embeddings, state updates, and a next-token loss. Correct shifting and evaluation matter more than attractive samples. This small experiment teaches the training loop and decoding tradeoffs while keeping its limited evidence visible.

Official references

Finish the exercises and mastery checkpoint before marking this lesson complete. Completion is stored on this browser.