Skip to content

Phase 5 - NLP & Transformers

Text is not numbers, and every step from one to the other throws something away. This phase measures each step: which words to keep, how to split them, what “similar” means, and what attention buys over recurrence.

Two results frame everything else. A linear model over word counts beat every neural model here — 0.8632 against a transformer’s 0.8462, in 8.4 seconds against 460. And on a task that needs two composed operations, one attention block scored 0.3120 while two scored 0.9990. Neither is a slogan; both are measurements, and they point in opposite directions about when architecture matters.

#PageThe measured headline
441Text Preprocessinglowercasing this corpus changes 0 words — it was pre-processed; br is the 7th most frequent token
441.5Subword TokenizationBPE at 2,070 pieces reaches OOV 0.0000 against 0.0293 for 20,000 words
442Bag of Words & TF-IDFsublinear TF-IDF 0.8748 in 0.4 s; TF-IDF at 2,000 features beat counts at 30,000
443Word Embeddingssentiment-trained vectors collapse to cosine 1.000; skip-gram finds movie/film at 0.746
444Sentiment Analysisfive families: TF-IDF 0.8632 wins, transformer 0.8462 at 55× the cost
445Named Entity Recognitiontoken accuracy 0.8011, entity F1 0.4389 — and all-O scores 0.5653
445.5Attention from Scratchone block 0.3120, two blocks 0.9990; unscaled attention peaks at 0.9355
446The Transformer Architectureevery ablation helps at 1 block; removing layer norm costs 0.0612 at 4
447Sequence-to-Sequenceattention took exact match 0.6250 → 0.9770 for 768 parameters
447.5Evaluating Language Modelsneural 189.81 vs bigram 226.47; BLEU gives a correct reordering 0.0000
diagram Diagram mermaid
figure IMDB, 8,000 reviews, 6 epochs, matched width matplotlib
Two panels. Left: bars of best validation accuracy for four families, all between 0.8210 and 0.8465, annotated with parameters and training seconds. Right: per-epoch validation accuracy where the transformer starts at 0.8462 in epoch one and stays flat, while the bag of words climbs from 0.7303 and the recurrent models rise more slowly. Two panels. Left: bars of best validation accuracy for four families, all between 0.8210 and 0.8465, annotated with parameters and training seconds. Right: per-epoch validation accuracy where the transformer starts at 0.8462 in epoch one and stays flat, while the bag of words climbs from 0.7303 and the recurrent models rise more slowly.
The transformer's entire learning happens in epoch 1 — 0.8462, which is also its best score across all six epochs. Attention over 200 positions in parallel means every token pair is one gradient step apart, so there is no long credit-assignment chain to unroll. That is the real advantage on display here; it is not accuracy, since the bag of words matched it at 0.8465 in a tenth of the time.
figure 200 random query-key draws, 12 tokens matplotlib
Two panels over 200 random draws with 12 tokens. Left: mean largest attention weight against key dimension. Without scaling it rises 0.4442, 0.7189, 0.8577, 0.9355 as the dimension goes 4, 16, 64, 256; with the 1/sqrt(d_k) scale it stays between 0.2567 and 0.3024. A dashed line marks uniform attention at 0.0833. Right: the same measurement as entropy, falling from 1.6128 to 0.1668 nats unscaled and holding near 2.08 scaled, against log 12 = 2.4849 for uniform. Two panels over 200 random draws with 12 tokens. Left: mean largest attention weight against key dimension. Without scaling it rises 0.4442, 0.7189, 0.8577, 0.9355 as the dimension goes 4, 16, 64, 256; with the 1/sqrt(d_k) scale it stays between 0.2567 and 0.3024. A dashed line marks uniform attention at 0.0833. Right: the same measurement as entropy, falling from 1.6128 to 0.1668 nats unscaled and holding near 2.08 scaled, against log 12 = 2.4849 for uniform.
Without the scale, attention at d_k = 256 puts 0.9355 of its weight on a single token before any training — the softmax has saturated on noise, and its gradient with it. The scaled version holds near 0.28 at every dimension, which is the point: the operation should behave the same whether the head is 4-dimensional or 256-dimensional. The entropy panel says the same thing in nats, against a uniform maximum of 2.4849.
figure Every claim this phase set out to test matplotlib
Horizontal bars, one per page in the phase, each labelled with the claim it tested and coloured by the verdict: green where the standard story held, amber where it held at a price, red where the measurement contradicted it. 4 of 6 claims contradicted, 1 held at a price, 1 held. Horizontal bars, one per page in the phase, each labelled with the claim it tested and coloured by the verdict: green where the standard story held, amber where it held at a price, red where the measurement contradicted it. 4 of 6 claims contradicted, 1 held at a price, 1 held.
Collected from the runs behind each page's own figures rather than measured afresh, so every bar is traceable to the page it names. Bar length is the log of the effect size, because the effects span from 0.0014 to 5,376 — the number that matters is printed on each bar. Across all nine phases, 34 of 54 claims were contradicted outright, 11 held at a cost that was worth stating, and 9 held as advertised.

Four results that contradict the usual story

Section titled “Four results that contradict the usual story”
  1. The simplest model won. TF-IDF with logistic regression scored 0.8632 against an average embedding’s 0.8575, a convolution’s 0.8495, a transformer’s 0.8462 and an LSTM’s 0.8415 — with 9,768 parameters and 8.4 seconds. Sentiment is close to a keyword task, and 8,000 reviews is not much data.
  2. A transformer block’s components do not help a shallow transformer. At one block, removing the feed-forward network, the residuals or the layer norms all raised accuracy. Layer normalisation only earns its 128 parameters at depth, where removing it costs 0.0612.
  3. Sentiment-trained embeddings collapse. terrible, poor, waste and bad end up at cosine 1.000 — parallel vectors — because a one-dimensional loss needs exactly one direction. The same corpus trained on co-occurrence gives movie/film at 0.746.
  4. Attention’s win is convergence, not accuracy — until composition is needed. The transformer matched a bag of words (−0.0002) but reached its best score in epoch 1. On the induction task, where the model must match a cue and shift one position, one block cannot do it at all.

Four corpora that were too easy, and what fixing them showed

Section titled “Four corpora that were too easy, and what fixing them showed”

Three modules in this phase produced perfect or meaningless scores on the first attempt. All three are now rebuilt, and the fixes are the most transferable content here.

ExperimentFirst attemptThe flawAfter fixing
NERevery model 1.0000entity strings shared between train and test — the benchmark measured a word listtest pools disjoint, 38% unknown tokens → best F1 0.4389
seq2seqeverything 1.0000a bare date is trivially learnabledate buried in filler → attention worth +0.3520 exact match
skip-gramaccuracy 0.4585 (below chance)positives built first, so validation_split took only negativesshuffled → 0.6470, and neighbours became semantic
perplexityn-grams and neural in one tablescored on different test sets (231,210 tokens vs 30,000 windows)same windows → neural 189.81 beats bigram 226.47

A fifth was a metric that flattered rather than a corpus that was easy: reporting the final epoch’s perplexity instead of the best gave 4,062.44 where the minimum was 189.81.

sketch How often the standard story survived p5.js
Step through the phases. Each bar splits the claims that phase tested into contradicted, held at a price, and held as advertised - the totals are summed live.

Every page compares against something that costs nothing:

TaskThe do-nothing baselineWhat it exposed
vocabulary choicecoverage at each cap (0.7624 at 1,000 words)23.8% of the text discarded silently
classificationTF-IDF + logistic (0.8632)four neural families that never beat it
taggingpredict O everywhere (0.5653)a model at 0.5750 token accuracy finding almost nothing
language modellinguniform = vocabulary size (4,997.00)whether a perplexity is meaningful at all
generationgreedy exact match, not per-character0.9217 character accuracy = 0.6250 exact
sketch Accuracy against what it cost p5.js
Five model families on the same 8,000 IMDB reviews. Drag to weight training time; the ranking re-sorts and the winner changes.
Idea from this phaseWhere it comes back
attention over a set of tokensdiffusion U-Nets, every modern generative model
pre-norm blocks with residualsPhase 6’s architectures, Phase 8’s scaling
teacher forcing and exposure biasautoregressive image and audio generation
perplexity and its tokenizer dependencePhase 6’s text generation page
“measure against the do-nothing baseline”every remaining phase
pch.quizTag pch.quizDefaultTitle
  1. TF-IDF with logistic regression scored 0.8632 in 8.4 seconds against a transformer's 0.8462 in 460. What is the defensible conclusion?

    pch.quizShowAnswer

    B — On 8,000 reviews of a near-keyword task, the extra machinery has nothing to learn that counts do not already capture - which is a claim about this budget and this task, not about transformers

  2. One attention block scored 0.3120 on the induction task while two scored 0.9990. Why can one block not do it?

    pch.quizShowAnswer

    B — The task needs two composed operations - match a cue, then shift one position - and a single attention layer can only perform one round of look-up before the output is read

  3. Embeddings trained on the sentiment objective put `terrible`, `poor`, `waste` and `bad` at cosine 1.000 - exactly parallel. What caused that?

    pch.quizShowAnswer

    B — A one-dimensional loss needs exactly one direction, so every word useful for the task collapses onto that axis and all other structure is discarded

  4. NER token accuracy was 0.8011 while entity F1 was 0.4389, and labelling everything `O` already scores 0.5653 on tokens. What is the lesson?

    pch.quizShowAnswer

    B — Token accuracy on a task dominated by one class is close to a do-nothing baseline; the unit you evaluate has to be the unit you care about, which for NER is the whole span

  5. At one transformer block, removing the feed-forward network, the residuals or the layer norms all RAISED accuracy; at four blocks, removing layer norm cost 0.0612. What does that pattern say?

    pch.quizShowAnswer

    B — Those components solve problems that only appear with depth, so a shallow ablation measures their cost without ever exposing their benefit

pch.coffeeTagline

pch.coffeeCta

pch.feedbackHeading

pch.feedbackSubheading