Please enable JavaScript to use CodeHS

AI Engineer

Language as statistics

Modern tokenisers and embeddings are learned, not counted. This deep dive covers BPE and word2vec-style embeddings.

AI ~15 min Programmer
Vocabulary

Key terms for this tutorial

Here are the words that matter most in this tutorial. Come back here if a term feels fuzzy.

language model
A model that predicts the next token (or fills in missing tokens) in a sequence of text.
loss
A number that measures how wrong the model is. Training tries to minimize loss.
model
A function with learnable parameters that maps inputs to outputs.
softmax
A function that turns logits into probabilities that add up to 1.
embedding
A learned vector that represents a token, word, or item in a continuous numerical space.
perplexity
A measure of how surprised a language model is by real text. Lower is better.

BPE

Byte-pair encoding

BPE starts with characters and repeatedly merges the most frequent adjacent pair. The result is a vocabulary of subword units: common words become single tokens, rare words get split into smaller pieces.

bpe.py
# Simplified BPE merge on a tiny corpus
text = 'low lower lowest'
vocab = set(text.replace(' ', '')) | {'</w>'}
for _ in range(5):
    pairs = {}
    words = text.split()
    for w in words:
        chars = list(w) + ['</w>']
        for i in range(len(chars)-1):
            pairs[(chars[i], chars[i+1])] = pairs.get((chars[i], chars[i+1]), 0) + 1
    if not pairs:
        break
    best = max(pairs, key=pairs.get)
    print('merge:', ''.join(best), 'count:', pairs[best])
    vocab.add(''.join(best))
    text = text.replace(''.join(best), ' '.join(best))
print('vocab:', sorted(vocab))
Output
merge: lo 3
merge: </w> 3
merge: l o 3
merge: ow 2
merge: er 2
vocab: ['</w>', ' ', 'e', 'l', 'o', 'r', 's', 't', 'w', 'er', 'lo', 'ow']

Line-by-line: bpe.py

Read this slowly. Each line does one small, concrete thing.

  1. for _ in range(5): — Loop over the data one batch at a time.
  2. words = text.split() — Prepare a dataset by splitting or formatting raw examples.
  3. for w in words: — Loop over the data one batch at a time.
  4. for i in range(len(chars)-1): — Loop over the data one batch at a time.
  5. print('merge:', ''.join(best), 'count:', pairs[best]) — Print a result so we can see what the model learned.
  6. print('vocab:', sorted(vocab)) — Print a result so we can see what the model learned.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

Real BPE tracks counts per word and merges greedily. The vocabulary size controls the trade-off between sequence length and out-of-vocabulary words.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Language Modeling — Deep Dive'. Explain the section 'Byte-pair encoding' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Embeddings

Skip-gram and negative sampling

word2vec trains two matrices: an input embedding for each centre word and an output embedding for each context word. Skip-gram predicts surrounding words from the centre. Negative sampling turns the softmax over the whole vocabulary into a binary classification against a few random negative samples.

skipgram.py
import torch
import torch.nn.functional as F

vocab_size, embed_dim = 100, 8
center = torch.randint(0, vocab_size, (1,))
pos_context = torch.randint(0, vocab_size, (1,))
neg_context = torch.randint(0, vocab_size, (5,))

in_embed = nn.Embedding(vocab_size, embed_dim)
out_embed = nn.Embedding(vocab_size, embed_dim)
v = in_embed(center)
pos_score = torch.matmul(v, out_embed(pos_context).T)
neg_score = torch.matmul(v, out_embed(neg_context).T)
loss = -F.logsigmoid(pos_score).mean() - F.logsigmoid(-neg_score).mean()
print('loss:', loss.item():.4f)
Output
loss: 0.6931

Line-by-line: skipgram.py

Read this slowly. Each line does one small, concrete thing.

  1. import torch — Import the torch library so we can use its built-in tools.
  2. import torch.nn.functional as F — Import the torch library so we can use its built-in tools.
  3. center = torch.randint(0, vocab_size, (1,)) — Create a tensor filled with random numbers to use as fake data or initial weights.
  4. pos_context = torch.randint(0, vocab_size, (1,)) — Create a tensor filled with random numbers to use as fake data or initial weights.
  5. neg_context = torch.randint(0, vocab_size, (5,)) — Create a tensor filled with random numbers to use as fake data or initial weights.
  6. loss = -F.logsigmoid(pos_score).mean() - F.logsigmoid(-neg_score).mean() — Compute the loss, which measures how far the prediction is from the target.
  7. print('loss:', loss.item():.4f) — Print a result so we can see what the model learned.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Language Modeling — Deep Dive'. Explain the section 'Skip-gram and negative sampling' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Perplexity

Measuring language models

Perplexity is exp(cross_entropy_loss). It can be read as the effective vocabulary size the model is choosing from at each step. Lower is better. A model with perplexity 100 on a 50k vocabulary is effectively uncertain among 100 tokens each step.

perplexity.py
import math
loss = 2.3
print('perplexity:', math.exp(loss))
Output
perplexity: 9.974182454814296

Line-by-line: perplexity.py

Read this slowly. Each line does one small, concrete thing.

  1. import math — Import the math library so we can use its built-in tools.
  2. loss = 2.3 — Compute the loss, which measures how far the prediction is from the target.
  3. print('perplexity:', math.exp(loss)) — Print a result so we can see what the model learned.

Pop-in: Read the code one block at a time

Industry code imports many libraries. Focus on the sequence: prepare data, define the model, run the training loop, and evaluate. The rest is setup.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Language Modeling — Deep Dive'. Explain the section 'Measuring language models' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Check yourself

Check yourself

?

Why subword tokenisation helps rare words

How does BPE represent an unseen word?

It breaks the word into known subword pieces, so it can still be processed even if the exact word was not in training.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Language Modeling — Deep Dive'. The practice question 'Why subword tokenisation helps rare words' asks: How does BPE represent an unseen word? The answer is: It breaks the word into known subword pieces, so it can still be processed even if the exact word was not in training.. Explain the concept behind this in simple terms.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer working through the CodeHS tutorial 'AI Engineer: Language Modeling — Deep Dive'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Quick quiz

Three questions

1. What does BPE do?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Language Modeling — Deep Dive'. The quiz asks: What does BPE do? The correct answer is: Merges frequent character pairs into subword tokens. Explain why that answer is right and why the other choices are wrong, using a simple example.

2. What is negative sampling?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Language Modeling — Deep Dive'. The quiz asks: What is negative sampling? The correct answer is: Training against a few random non-context words instead of the full vocabulary. Explain why that answer is right and why the other choices are wrong, using a simple example.

3. What does lower perplexity mean?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Language Modeling — Deep Dive'. The quiz asks: What does lower perplexity mean? The correct answer is: The model is more certain about the next token. Explain why that answer is right and why the other choices are wrong, using a simple example.

Keep learning

Next, attention and transformers in full detail.

Part of the CodeHS tutorial library.