Skip to main content

Beginner-Friendly Topic

Take your time - it's perfectly normal to re-read this topic 2-3 times. Try the interactive code editor below to run code yourself. Use the Q&A section to check your understanding before moving on.You've got this!

Lesson 11 of 12

Module 3 Practice

Apply your understanding of how LLMs learn with a practical exercise that simulates the core concept.

15 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

Mini Project: Simulate Next-Token Prediction

Mini Project: Simulate Next-Token Prediction
# Mini Project: Build a simple next-token prediction simulator
# This shows the core concept LLMs use during training

def build_simple_language_model(training_texts):
    """
    Build a very simple bigram language model.
    This illustrates the core concept: learn which token follows which.
    A real LLM does this for billions of examples with billions of parameters.
    """
    from collections import defaultdict

    # Count how often each word follows each other word
    next_word_counts = defaultdict(lambda: defaultdict(int))

    for text in training_texts:
        words = text.lower().split()
        for i in range(len(words) - 1):
            current_word = words[i]
            next_word = words[i + 1]
            next_word_counts[current_word][next_word] += 1

    return next_word_counts

def predict_next_token(model, current_word, top_n=3):
    """Predict the top N most likely next tokens."""
    if current_word not in model:
        return []

    counts = model[current_word]
    total = sum(counts.values())

    # Calculate probabilities
    probabilities = {word: count / total for word, count in counts.items()}

    # Sort by probability
    sorted_predictions = sorted(
        probabilities.items(),
        key=lambda x: x[1],
        reverse=True
    )

    return sorted_predictions[:top_n]

# Training data (normally billions of sentences)
training_data = [
    "the cat sat on the mat",
    "the cat ran on the floor",
    "the dog sat on the sofa",
    "the dog ran in the park",
    "the cat played in the garden",
    "cats and dogs are animals",
]

# Train the model
model = build_simple_language_model(training_data)

# Make predictions
print("Simple Next-Token Prediction Model")
print("=" * 40)
print()

test_words = ["the", "cat", "sat", "dog"]
for word in test_words:
    predictions = predict_next_token(model, word)
    print(f"After '{word}', most likely next tokens:")
    for predicted_word, prob in predictions:
        bar = "█" * int(prob * 20)
        print(f"  '{predicted_word}': {prob:.2f} {bar}")
    print()
Diagram
Loading diagram…

Practice Diagram

Key Takeaways from Module 3

  • LLMs learn one thing: given a sequence of tokens, predict the most likely next token
  • This simple task teaches grammar, facts, reasoning, and coding patterns as side effects
  • Training data is vast (trillions of tokens) and diverse (web, books, code, academic papers)
  • Pretraining is the main learning phase — it happens once and costs millions of dollars
  • The training loop: predict → measure loss (error) → adjust parameters → repeat billions of times
  • During inference (when you use the model), no learning happens — parameters are fixed
  • Real-world LLMs like GPT-4 do this at a scale that makes the simple concept produce remarkable results

Key Takeaways

  • Apply your understanding of how LLMs learn with a practical exercise that simulates the core concept.
  • LLMs learn one thing: given a sequence of tokens, predict the most likely next token
  • This simple task teaches grammar, facts, reasoning, and coding patterns as side effects
  • Training data is vast (trillions of tokens) and diverse (web, books, code, academic papers)

Finished this lesson?

0 of 12 in Module 3
Sign in to save progress

Topics in This Module

0/12 done