How Machines Read Text · EN
Day 1

From neurons to tokens

The full foundation in one day: how a neural network learns, how tokenizers and encoders are trained, how tokens become vectors, and why Korean costs more tokens.

1

Foundations — how a network learns

A neuron, training a classifier, and one full backprop step.

PART 0 · HOW MACHINES LEARN

What is a neural network?

A neural network is just a big stack of adjustable knobs (called weights). Numbers go in, the network multiplies them by its knobs and adds them up, and an answer comes out. “Learning” means slowly turning the knobs until the answers are right.

Try one neuron

Drag the weights. The neuron multiplies each input by its weight, adds a bias, and squashes the result into an output between 0 and 1.

input 1 (x₁)0.80
input 2 (x₂)0.30
weight 1 (w₁)1.20
weight 2 (w₂)-0.80
bias (b)0.20

The squash: the sigmoid σ

w₁=1.20w₂=-0.800.80.3inputΣ0.92b=0.20σσ(0.9) = 0.720.72output
/Line thickness = weight strength · blue = positive, red = negative
weighted sum = (1.20)·(0.80) + (-0.80)·(0.30) + (0.20) = 0.92
output = σ(0.92) = 0.715
A real network stacks thousands of these neurons in layers. Training = automatically finding the knob settings that make the outputs correct — which is what you'll watch next.
WATCH IT LEARN

Training a network to classify

Below is a real neural network running in your browser, learning to separate two groups of dots. Press Play and watch the colored boundary bend until it sorts them correctly — and the loss (how wrong it is) fall toward zero.

Group 1Group 2decision linemargin (low-confidence band)
Dataset:
Epoch
0
Loss
0.000
Accuracy
0%
Random start — the boundary is meaningless.
Tip: switch to XOR — a straight line can never separate it, so the network must learn a curved boundary. That curve is what the hidden layer buys you.
WATCH ONE TRAINING STEP

Forward pass → backprop → weight update

Above you watched the boundary move. But HOW does a weight know which way to turn? Here is a tiny real network (2 inputs → 2 hidden → 1 output). Step through one full training iteration and watch the exact value of every weight change.

Iteration 0 · Setup · learning rate 1.5
A training example enters. The weights still hold their current values. We will compute the network ONE neuron at a time.
1x₀0x₁?h₀?h₁?ŷ1target y
Target
1
Prediction ŷ
—
Loss
—
weightvaluegradient ∇new value
W₁ x₀→h₀0.60——
W₁ x₁→h₀-0.50——
W₁ x₀→h₁-0.40——
W₁ x₁→h₁0.70——
b₁ h₀0.10——
b₁ h₁-0.20——
W₂ h₀→ŷ0.50——
W₂ h₁→ŷ-0.60——
b₂ ŷ0.15——
2

Tokenizer — text into pieces

First, text is split into subword tokens. The tokenizer is trained too.

HOW A TOKENIZER LEARNS

Training a tokenizer (BPE)

A subword tokenizer is also trained — but differently from the network above. It starts from single characters, then repeatedly glues together the most frequent neighboring pair. Press Step (or Play) to watch it build a vocabulary of reusable pieces from this little corpus.

Training set:
Every word starts as individual characters. Press Step.
Training corpus (word × frequency)
×7
low
×5
lower
×3
lowest
×4
slow
×3
slower
×6
new
×6
newer
×4
newest
×3
wide
×3
wider
×2
widest
Merges learned (in order) — Vocabulary size: 10
Merge budget: 0 / 10
—
slowest
7 pieces
Try “slowest” — built cleanly from learned pieces. Then type a Korean word: it was never in training, so it falls back to tiny character pieces. That is exactly why low-resource languages pay the token tax.
3

Encoder — learning meaning

A real BERT learns by filling in masked blanks (self-supervised).

HOW THE ENCODER TRAINS

Masked Language Modeling — fill in the blank

Once the tokenizer above has split text into pieces, the encoder learns what those pieces MEAN. This is how modern text encoders (BERT, RoBERTa, XLM-R) actually learn — with no human labels. Hide a word with [MASK] and the model must predict it from context. Repeat over billions of sentences and it absorbs grammar, facts, and meaning. Below is a REAL multilingual BERT predicting live in your browser.

Downloading the real BERT weights… (loads automatically — a moment)

4

Embeddings — tokens as vectors

How a token gets its vector, then real word maps in 2-D and 3-D.

FROM TEXT TO NUMBERS

Token labeling & the embedding table

Before any learning, two setup steps turn tokens into something a network can use. (1) Every distinct token from the corpus is given a number — its label/ID. (2) Each ID points to a row of N numbers — its vector. Those numbers begin random; training (next) makes them meaningful.

1 · Label every token (build the vocabulary)
A tiny corpus (sample):
kingqueenthronecrown
kingprincecrown
queenroyalcrown
princeroyalthrone
kingqueenroyal
Collect every unique token → give each an ID:
0 king1 queen2 throne3 crown4 prince5 royal6 dog7 cat8 pet9 puppy10 kitten11 animal12 apple13 banana14 fruit15 grape16 sweet17 juice18 one19 two20 three21 four22 number23 count
That number is the token's only “name” to the network — it has no meaning yet.
2 · Each ID → a row of N numbers (its embedding)
idtokend1d2d3d4d5d6…
0king-0.98-0.880.950.400.04-0.19…
1queen-0.07-0.520.110.46-0.48-0.69…
2throne0.530.04-0.61-0.26-0.410.07…
3crown-0.410.96-0.500.76-0.62-0.71…
4prince-0.69-0.420.100.52-0.850.83…
5royal0.110.240.360.930.250.84…
6dog0.66-0.92-0.65-0.29-0.15-0.96…
7cat-0.820.54-0.26-0.15-0.060.89…
⋮ (24 tokens total)
Here we show N = 6 columns and will train N = 2 (so it fits on a flat graph). Real encoders use N = 384, 768, or more dimensions per token.
This whole table is just numbers — and every number is a weight the network can adjust.
Right now these numbers are random noise. Next, watch training reshape them so tokens that mean similar things end up with similar rows.
HOW A TOKEN GETS ITS VECTOR

Learning an embedding from scratch

A network can't read letters — only numbers. So every token is handed a short list of numbers called its embedding (here just 2 numbers, so we can plot it). At the start these numbers are RANDOM. Watch the network learn better ones, live.

The rule it learns by: tokens that appear together in the text get PULLED closer; random unrelated tokens get PUSHED apart. Repeat over the whole corpus and every token drifts to a spot that reflects its meaning. (This is the idea behind word2vec.)
Token → ID → vector (a row in the embedding table)
king→ id #0→ vector[ 0.25, -0.99 ]
Click any dot or row to inspect its vector. Each token is just a row number into a big table of learnable numbers.
epoch 0 · model error (loss): 0.00
Everything starts as a random cloud — these numbers mean nothing yet. Press One step to see the math, or Train to run.
Each token's 2-number vector, plotted
kingqueenthronecrownprinceroyaldogcatpetpuppykittenanimalapplebananafruitgrapesweetjuiceonetwothreefournumbercount
predicted too far → pull togetherpredicted too close → push apart
Colors mark the hidden topics — the model is never told them; clusters EMERGE from training alone.
The embedding table (updates as it learns)
king0.25-0.99
queen0.050.96
throne0.94-0.44
crown0.230.44
prince-0.150.99
royal-0.09-0.02
dog-0.72-0.19
cat-0.50-0.69
pet-0.02-0.87
puppy-0.210.53
kitten-0.43-0.62
animal-0.91-0.15
apple0.180.60
banana-0.41-0.59
fruit0.320.09
grape0.52-0.61
sweet0.44-0.09
juice0.540.99
one-0.520.51
two-0.69-0.35
three-0.17-0.50
four-0.700.45
number0.15-0.75
count-0.47-0.90
king — closest tokens now: number, pet, grape
This is the classic word2vec idea — the simplest way to learn embeddings. Modern models (BERT, GPT) don't use word2vec itself: they learn an embedding table like this INSIDE the Transformer, trained by the masking/prediction task from the Encoder section. Same principle — tokens become learned vectors via prediction + backprop — just a much bigger network, and the vectors become context-aware.
FROM PICTURES TO WORDS

Turning words into numbers (embeddings)

Networks only understand numbers, so each word becomes a list of numbers — a vector. Through training, the network learns to place words with similar meaning near each other. Click a word to see its nearest neighbors.

This is a simplified 2-D map; real embeddings have hundreds of dimensions. Notice meanings cluster — and across languages too.

Now in 3D — add your own words

Same idea, but live and in 3D with a REAL model. It turns each word into a 384-number vector; we project that to 3D so you can see it. Drag to rotate, use +/− to zoom, click a word for its closest relatives. Add any word — even Korean — and watch where it lands.

Downloading the embedding model (~23 MB, once) & embedding words…

5

Tokenization & the token tax

Why Korean and low-resource languages cost more tokens.

START HERE · THE PUZZLE

Why does the same sentence cost more in Korean?

AI language models don't read words — they read tokens (chunks of text). Type the same meaning in English and Korean below, and watch how many tokens each one becomes. The counts come from GPT's real tokenizer, running right in your browser.

Type in either box and the other fills in automatically. No download — uses a free online translator, so it needs an internet connection.
8 tokens · 46 characters
Artificial␣intelligence␣is␣changing␣the␣world.
17 tokens · 19 characters
인공지능이␣세상을␣바꾸고␣있습니다.
Korean uses 2.1× more tokens than English
More tokens means: pay more (APIs bill per token), slower replies, and the model's memory fills up faster. We'll see exactly why by the end.
Try a preset:
THREE WAYS TO CUT TEXT

Tokenization: how machines slice up language

Type anything (try English and Korean!). The same text is split three ways. Notice how the counts and pieces differ.

Character (by letter)

15 pieces
학1교2에3서4␣5자6연7어8를9␣10공11부12해13요14.15

Tiny vocabulary, never “unknown”, handles typos & emoji. But sequences get very long and the model must learn what a word is from scratch.

Word (by spaces)

4 pieces
학교에서1자연어를2공부해요3.4

Intuitive and short. But the vocabulary explodes and any new/rare word becomes “unknown” (UNK). Korean is brutal here: 학교, 학교에서, 학교를 all look like different words.

Subword (GPT's real BPE)

16 pieces
1학23교4에서5␣자67연8어9를10␣11공12부13해14요15.16

The winner used by all modern LLMs: keep common words whole, split rare ones into reusable pieces. Below is GPT-4's actual tokenizer. ‘␣’ marks a space; the amber chips are partial-byte pieces — exactly how Korean often gets shattered.

Note: BERT uses a subword method called WordPiece (continuations marked with ‘##’), and multilingual models use SentencePiece (spaces marked with ‘▁’). Compare them all in the companion Colab notebook.

Trade-offs at a glance

CharacterWordSubword
Vocabulary sizetinyhugemedium
Unknown words?neverfrequentrare
Sequence lengthlongshortmedium
Used byrare todayold NLPBERT, GPT, all LLMs
REAL TOKENIZERS, LIVE

WordPiece vs SentencePiece vs BPE — the real models

The panel above uses GPT’s BPE. Here are three real tokenizers from actual models, running live in your browser. Watch the markers: BERT uses ## (glue to the previous piece), XLM-R uses ▁ (a space before a word).

Downloading tokenizers…

TIDYING TEXT FIRST

Normalization: when identical-looking text isn't equal

Before tokenizing, text is cleaned. The sneakiest case: two strings that look identical but are stored as different bytes — so the computer says they're NOT equal. This bites Korean especially (and is the cause of broken filenames between Mac and Windows).

2 code points · 6 bytes
6 code points · 18 bytes
Raw equal (===)?NO
Equal after normalization (NFC)?YES
Try these:

Unicode forms — “한글”

NFCU+D55C U+AE002 code points
NFDU+1112 U+1161 U+11AB U+1100 U+1173 U+11AF6 code points
NFKCU+D55C U+AE002 code points
NFKDU+1112 U+1161 U+11AB U+1100 U+1173 U+11AF6 code points
Same look, different bytes → search, login, and de-duplication can silently fail. Normalization (NFC/NFD) forces one canonical form so the computer treats them as equal. Lowercasing and trimming spaces are normalization too.
THE PAYOFF

The token tax: low-resource languages pay more

Every bar below is the SAME sentence — “Artificial intelligence is changing the world.” — in a different language, measured with GPT's real tokenizer. English is cheapest because the tokenizer saw the most English. Languages with less training data get shattered into more, smaller pieces.

English
8 tokens · 1.0× English
Spanish
10 tokens · 1.3× English
Chinese
12 tokens · 1.5× English
Swahili
13 tokens · 1.6× English
Japanese
15 tokens · 1.9× English
Korean
17 tokens · 2.1× English
Hindi
43 tokens · 5.4× English
Amharic
72 tokens · 9.0× English

Why this happens

A subword tokenizer is trained on data. It learns big reusable chunks for languages it saw a lot of (English), and only tiny byte-level pieces for languages it barely saw. Korean is agglutinative — particles & endings (조사/어미) attach to stems (학교+에서+는) — so even subwords need many pieces.

What the tax costs

  • Money — APIs charge per token
  • Speed — more tokens, slower replies
  • Memory — fills the context window sooner
  • Fairness — speakers of low-resource languages pay more for worse AI
How the field copes: multilingual models like XLM-RoBERTa train on 100 languages at once, enabling zero-shot cross-lingual transfer (learn a task in one language, use it in another). But it breaks down for languages too different or not seen in training — exactly the low-resource case.

Try it: the price of the tax

A rough estimate. Same app, same number of messages — Korean costs more simply because it becomes more tokens.

English total
$0.40
8 tokens / message
Korean total
$0.85
17 tokens / message
Extra paid just for using Korean
$0.45
2.1×
6

Reference

Vocabulary card for the key terms.

VOCABULARY CARD

Korean ↔ English glossary

Term한국어Plain meaning
NLP자연어처리Computers working with human language
LLM거대언어모델A huge model that predicts text
Token토큰A chunk the model reads (not always a word)
Tokenization토큰화Cutting text into tokens
Vocabulary어휘집The fixed list of tokens a model knows
OOV / UNK미등록 단어A word not in the vocabulary
Normalization정규화Standardizing text (case, spacing, Unicode)
Subword서브워드Pieces between a letter and a word
BPE / WordPiece / SentencePiece—Subword algorithms (GPT / BERT / multilingual)
Embedding임베딩Turning a token into numbers
Morpheme형태소Smallest meaning unit (key for Korean)
Agglutinative교착어Korean attaches particles/endings to stems
Low-resource language저자원 언어A language with little training data
Context window문맥 길이Max tokens a model reads at once
Pretraining / Fine-tuning사전학습 / 미세조정Train broadly / adapt to a task
Day 2

Attention & Transformers

How tokens look at each other: self-attention, the Transformer block, and the split between encoders (reading) and decoders (generating).

1

Attention — tokens look at each other

Each token decides which other tokens to focus on, and by how much.

ATTENTION

Self-attention — which tokens matter?

Each token builds a query and compares it against every other token's key. The softmax of those scores decides how much of each token's value to mix in — so a word can “look at” the words it depends on.

Click a word to see where it looks
The12%cat20%saton15%the12%mat20%
sat pays most attention to cat.
Attention weights from the chosen word (they add up to 100%)
The
12%
cat
20%
sat
22%
on
15%
the
12%
mat
20%
Full attention grid — row = from, column = to, darker = more attention
Thecatsatonthemat
The161718161617
cat122121131221
sat122022151220
on141620201416
the161718161617
mat122121141220
score = (query · key) ÷ √d → softmax → weights → weighted sum of values
No fixed window: every token can reach any other token in one step. That is the whole trick behind Transformers.
TRY IT YOURSELF

Guess where the word looks

The highlighted word is ambiguous. A person uses the rest of the sentence to figure out what it means — and so does attention. Which word do you think it points to?

The trophy didn't fit in the suitcase because it was too big.

What does “it” point to?
Score: 0 / 0
This is exactly what attention learns to do — connect a word to the other words that explain it, anywhere in the sentence.
2

The Transformer block

Attention + a feed-forward network, stacked with residual connections and normalization.

TRANSFORMER BLOCK

Putting a Transformer layer together

One block = multi-head attention → add & normalize → feed-forward network → add & normalize. Stack a few dozen of these and you have GPT or BERT.

Token + position embeddingsMulti-head attentiontokens look at each otherAdd & normalizeFeed-forward networkthink about each token on its ownAdd & normalizeOutput (to the next block)residual / skip connection
  • Multi-head attention — mixes tokens together
  • Feed-forward network — processes tokens separately
  • Add & normalize
  • residual / skip connection
This same block is stacked ×N (GPT-2: 12, GPT-3: 96).
BUILD IT YOURSELF

Build a Transformer block

You've seen the finished block — now assemble one yourself. Click the four pieces in the right order, bottom to top. Data flows up from the input embeddings to the output.

Your block
Output → next block
↑
stack your 4 pieces here
↑
Token + position embeddings (input)
0 / 4 pieces placed
Pieces — click to stack
Feed-forward network
Add & normalize
Multi-head attention
Add & normalize

Click a stacked piece to take it back.

3

Encoder & decoder

Reading (encoder) vs generating (decoder) — and how the two combine for translation.

ENCODER & DECODER

Reading vs generating

Same attention machinery, one difference: what each token is allowed to look at. Green means “can look”.

Encoder — reads

to →ThecatsatdownfromThecatsatdown

Every token sees every other token — full context, both directions. This is BERT.

Decoder — generates

to →ThecatsatdownfromThecatsatdown

Each token sees only itself and the words before it — it can't peek at the future. This is GPT.

Row = the token doing the looking · column = the token being looked at

Translation uses both: an encoder reads the whole source sentence, then a decoder writes the translation one word at a time.