Please enable JavaScript to use CodeHS

AI Engineer

Turning language into numbers

Language models do not read words; they read numbers. In this tutorial you will tokenize text, count n-grams, and see why dense embeddings beat one-hot vectors when the vocabulary is large.

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.

attention
A mechanism where each output position mixes input positions, weighted by how relevant they are.
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.
tensor
A multi-dimensional array of numbers, the basic data type in deep learning.
token
A unit of text (word, sub-word, or character) that a language model processes.
embedding
A learned vector that represents a token, word, or item in a continuous numerical space.

Tokens

Tokenization: breaking text into pieces

The first step in any language model is to split text into tokens. Tokens can be words, characters, or sub-word pieces. GPT-style models use byte-pair encoding (BPE), which keeps common words whole and splits rare words into smaller units.

After tokenization, every token becomes an integer ID. From the model's perspective, language is a sequence of integers.

Core idea: the model never sees 'hello'; it sees an integer like 15496. Every token ID gets mapped to a vector, and that vector is what the network actually processes.

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'. Explain the section 'Tokenization: breaking text into pieces' in plain English. Include simple analogies, vocabulary definitions, and a short example.


N-grams

A simple next-word model: counting n-grams

An n-gram model predicts the next token based on the previous n-1 tokens. Train it by counting what follows each context in a corpus.

bigram.py
from collections import defaultdict, Counter

text = "the cat sat on the mat and the cat looked at the rat"
words = text.split()

# Count every bigram context -> next word
bigrams = defaultdict(Counter)
for w1, w2 in zip(words, words[1:]):
    bigrams[w1][w2] += 1

context = "the"
next_counter = bigrams[context]
total = sum(next_counter.values())
for word, count in next_counter.items():
    print(f"P({word} | {context}) = {count/total:.2f}")
Output
P(cat | the) = 0.50
P(mat | the) = 0.25
P(rat | the) = 0.25

Line-by-line: bigram.py

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

  1. from collections import defaultdict, Counter — Import tools from the collections package.
  2. words = text.split() — Prepare a dataset by splitting or formatting raw examples.
  3. for w1, w2 in zip(words, words[1:]): — Loop over the data one batch at a time.
  4. for word, count in next_counter.items(): — Loop over the data one batch at a time.
  5. print(f"P({word} | {context}) = {count/total:.2f}") — 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.

Bigrams capture local patterns, but they cannot use distant context and they fail when a sequence has never appeared in training. Modern models solve both problems with embeddings and attention.

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'. Explain the section 'A simple next-word model: counting n-grams' 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

From one-hot vectors to embeddings

If your vocabulary has 50,000 tokens, a one-hot vector is 50,000 long. That is wasteful and gives the model no notion of similarity. An embedding is a short, dense vector learned for each token.

Similar tokens end up with similar vectors. The vector for 'king' minus 'man' plus 'woman' lands near 'queen' because the embedding geometry captures meaning.

embedding_lookup.py
import torch
import torch.nn as nn

vocab_size = 50_000
embed_dim = 128

# Each of the 50,000 tokens gets a 128-dimensional vector
embedding = nn.Embedding(vocab_size, embed_dim)

token_ids = torch.tensor([0, 5, 12])  # "the", "cat", "sat"
vectors = embedding(token_ids)
print("shape:", vectors.shape)       # (3, 128)
print("vector[0] first 5:", vectors[0, :5].detach().numpy())
Output
shape: torch.Size([3, 128])
vector[0] first 5: [-0.023  0.041 -0.012  0.008 -0.035]

Line-by-line: embedding_lookup.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 as nn — Import the torch library so we can use its built-in tools.
  3. embedding = nn.Embedding(vocab_size, embed_dim) — Convert text or items into dense vectors that capture meaning.
  4. token_ids = torch.tensor([0, 5, 12]) # "the", "cat", "sat" — Create a PyTorch tensor from raw Python numbers.
  5. vectors = embedding(token_ids) — Convert text or items into dense vectors that capture meaning.
  6. print("shape:", vectors.shape) # (3, 128) — Print a result so we can see what the model learned.
  7. print("vector[0] first 5:", vectors[0, :5].detach().numpy()) — Print a result so we can see what the model learned.

Pop-in: RAG gives the model a textbook at test time

A language model only knows what it was trained on. RAG lets it look up relevant documents before answering, so it can use facts that were not in the training data.

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'. Explain the section 'From one-hot vectors to embeddings' in plain English. Include simple analogies, vocabulary definitions, and a short example. Also walk through the code example in this section step by step.


Objective

The language-modeling objective

A language model is trained to predict the next token given the previous tokens. The loss is cross-entropy: it penalizes the model for assigning low probability to the token that actually comes next.

This is powerful because the training data is free: any text is a supervision signal. Every word in a book is the 'correct next token' for the words before it.

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'. Explain the section 'The language-modeling objective' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Check yourself

Check yourself

?

Why are embeddings better than one-hot vectors?

Compare memory, similarity, and the information each gives to the model.

One-hot vectors are huge, sparse, and treat every token as unrelated. Embeddings are small, dense, and place similar words near each other in vector space, giving the model a head start on meaning.

Stuck or curious? Explain this to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Language Modeling'. The practice question 'Why are embeddings better than one-hot vectors?' asks: Compare memory, similarity, and the information each gives to the model. The answer is: One-hot vectors are huge, sparse, and treat every token as unrelated. Embeddings are small, dense, and place similar words near each other in vector space, giving the model a head start on meaning.. 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'. Explain the section 'Check yourself' in plain English. Include simple analogies, vocabulary definitions, and a short example.


Quick quiz

Three questions

1. What is a token in a language model?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Language Modeling'. The quiz asks: What is a token in a language model? The correct answer is: A unit of text represented by an integer ID. Explain why that answer is right and why the other choices are wrong, using a simple example.

2. What does a bigram model predict?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Language Modeling'. The quiz asks: What does a bigram model predict? The correct answer is: The next word from the previous one word. Explain why that answer is right and why the other choices are wrong, using a simple example.

3. What is the supervision signal for language modeling?

Stuck or curious? Explain this question to me on ChatGPT

Prompt: I am a beginner AI engineer studying 'AI Engineer: Language Modeling'. The quiz asks: What is the supervision signal for language modeling? The correct answer is: The next token in any text. Explain why that answer is right and why the other choices are wrong, using a simple example.

Keep learning

Explore BPE, word2vec skip-gram, negative sampling, and perplexity in depth.

Part of the CodeHS tutorial library.