Paul Jialiang Wu agentic-portfolio 中文 Español 한국어 日本語✉️ Free list
← Back to portfolio

AI-NATIVE SERIES · WORLD MODELS FROM CS229, EPISODE 1 OF 1 · AGE 20

World Models Start in Six Lines of CS229: Learn the Wolf, Guard the Flock (for Age 20)

By Paul Jialiang Wu · agentic-portfolio-lovat.vercel.app · 2026-10-16 · 18 min read

Cover: World models start in six lines of CS229, for age 20. Three cards: who it is for (engineers who want to do world-model research, not just read about it), what you leave with (a world model you can run in a browser, and the road to Dreamer and Genie), the one finding (for three of the four wolf habits, learning lifts the shepherd from turning away 17 to 37 percent of wolves to 87 to 100 percent, with seed 1).
World Models from CS229, episode 1 of 1: age 20.

1-minute takeaway

What this is. An essay and a live demo for engineers of about twenty. CS229 section 19.3 contains a complete world model small enough to read in one sitting: count transitions to learn how the world moves, plan with value iteration on what you learned, act, repeat. The demo is a shepherd learning a wolf's habits; the essay maps which parts of the same loop later work keeps in Kalman filtering, Dyna, World Models, Dreamer, MuZero and Genie.

Why it matters. Many labs are betting that robotics, games and physical AI will run on world models, and most explanations start at the 11-billion-parameter end. Starting at six lines you can run lets you see what each later paper actually added, and which claims about world models are still open.

What you can do after reading. Play the shepherd demo and beat the never-learning baseline, change one assumption (the wolf's habit, the discount, the amount of experience) and report what broke, then run the family drill with a child and post what the shepherd learned.

World Models from CS229 — the series spine

▶ See it running: open the live demo public · no sign-in

  1. World models start in CS229 §19.3 this episode

The one question: What is a world model small enough to build, run and understand, and how does it lead to Dreamer, MuZero and Genie?

This piece does NOT teach the whole CS229 course or train a neural world model; it builds the tabular one in section 19.3 and maps the road up. The family drill it hands to children belongs to Shepherd's Academy of War, part 5.

What this essay is about: world models, starting from six lines

This is an essay about world models: a machine's small, learned copy of how its world behaves, used to plan before it acts. It is written for engineers of about twenty who want to do research on world models, not just read about them. You need a browser, Python, and about half an hour.

Many labs are betting that robotics, games and physical AI will run on world models. NVIDIA's Cosmos platform puts the case plainly: a physical AI system needs "a digital twin of the world, the world model" (NVIDIA (2025), Cosmos World Foundation Model Platform for Physical AI, arXiv 2501.03575). Most explanations start at the big end, with 11-billion-parameter video models. This one starts at the small end, with six lines in the Stanford CS229 lecture notes by Tengyu Ma and Andrew Ng (Ma & Ng, CS229 Lecture Notes (Stanford, Spring 2026)). In section 19.3, "Learning a model for an MDP", those six lines contain a complete world model: watch, count, plan, act, repeat.

The essay was built with playbook-math, from a hand-picked slice of a 278-page set of notes: about 30 pages. Each was scored on three things: how strongly it pulls an engineer toward research, how much it matters for world models, and whether a family could play it.

CS229 section (printed pages)Why it made the cut
19.1–19.3: MDPs, value iteration, learning a model (228–234)The whole world-model loop in a few lines; the demo runs it
19.4.2: using a model or simulator (237–241)Learning s(t+1) from s(t) and a(t) from data: the first learned simulator
20.4: LQG, the Kalman filter with LQR (254–257)Acting on a belief when you cannot see the state
11.5: variational inference and the VAE (162–166)The compression engine inside neural world models
8.2: double descent (123–127)The clearest story in the notes of measurement overturning theory

The running thing it was built on is the Shepherd's World Model, a free page where a shepherd learns a wolf's secret habits in order to guard two flocks. The picture comes from Shepherd's Academy of War, a family academy where children learn how an attack works so that they can protect. The wolf is an animal, and no person is the enemy.

Before you read on. You will end by running the shepherd demo with a child of 7 to 11 and asking them to predict the wolf. Read as someone who will have to explain the loop simply. In a meta-analysis of 39 studies, teaching after studying with that expectation scored g = 0.48 (a subgroup result), while teaching without it showed no measurable benefit (g = −0.02) (Kobayashi (2024), Educational Psychology Review (ERIC EJ1414484)).

Activity 1 · Invent the shepherd's method first

Sketch an 8-by-8 field on paper. Put a flock in each bottom corner and a shepherd between them. A wolf enters from the top row and moves two cells for every one the shepherd moves, with a habit the shepherd has never been told.

Before reading on, write down how a shepherd who knows nothing should become good at this. What should it record each night? How should it choose where to stand?

Most people invent the same thing: keep a tally of where the wolf went from each spot, and stand where the tally says the wolf is heading. That is exactly the CS229 method. The tally is the world model. Standing where it points is the plan. Kenneth Craik guessed in 1943 that minds work this way: an organism that carries a "small-scale model" of reality can try out alternatives before acting (Craik (1943), The Nature of Explanation, quoted by Quanta Magazine (2025)). His was an idea, not an algorithm. CS229 section 19.3 writes the algorithm down.

The six lines

CS229 section 19.3 starts from a Markov decision process (MDP): states, actions, rewards, and transition probabilities that say where each action tends to lead. Usually you are not given those probabilities. You must estimate them from experience, and the notes give the estimate as a ratio (eq. 19.5). Each transition probability, the chance of landing in s′ after taking action a in state s, is the number of times that happened, divided by the "#times we took action a in state s" (Ma & Ng, CS229 Lecture Notes, eq. 19.5 (p. 233)). A pair never tried gets a uniform guess.

Then the notes put learning and planning together in a loop of a few lines:

  1. Start with any policy.
  2. Repeat: - (a) run it for some trials; - (b) update the transition counts; - (c) run value iteration on the estimated model; - (d) switch to the greedy policy for the new values.

Step (c) is the planning half, so here it is plainly. The value V(s) of a state is how much reward you can expect from there on. Value iteration repeats one update until the numbers stop changing (§19.2): V(s) ← R(s) + γ · max over actions a of Σ over next states s′ of P̂_sa(s′) · V(s′). Here γ (0.95 in the demo) discounts the future. A policy is a rule for which action to take in each state, and the greedy policy simply takes the action with the best value. On night 1, the shepherd that knows nothing believes every wolf move is equally likely, so it guards every cell equally, which means it guards none.

That is the whole world model. A world model is a small copy of how the world behaves, learned from what you saw and used to plan before you act. This one has a memory of what happened (the counts), a model built from that memory (the ratios), and a planner that uses the model before acting (value iteration).

Four boxes in a loop: WATCH (see the wolf move) to COUNT (P-hat equals count divided by visits, equation 19.5) to PLAN (value iteration on P-hat, section 19.2) to ACT (greedy move on V), and back to WATCH. A dashed blue line without an arrow joins PLAN and WATCH through the middle, labelled DREAM: plan inside the learned model (Ha and Schmidhuber; Dreamer).
The CS229 section 19.3 loop: watch, count, plan, act, repeat. The dashed path is a dream: planning inside the learned model.

Activity 2 · Watch the shepherd learn

Open the Shepherd's World Model with seed 1. Pick the river sneak and press "Learn 30 nights" twice, noting the score after each press. Then switch to engineer mode and compare the learned table with the true one for the cell the wolf is in.

Now pick the wanderer and do the same. Write down which habit the shepherd learned the most from, and guess why before reading on.

The demo runs the CS229 loop with two named simplifications. Only the wolf's moves are learned: the rewards and the shepherd's own moves are given. And a cell the wolf has never visited gets an even guess over the wolf's legal moves, not over all 64 cells, because a wolf cannot teleport. It counts every wolf step it sees, runs value iteration over every pair of shepherd and wolf positions (64 × 64 = 4,096 states), and moves greedily. The wolf moves two cells per turn, so chasing it fails. The shepherd has to be where the wolf is going, which only a model can tell it.

With seed 1, the shepherd that never learns plans forever with "every move is equally likely". Here is how it compares with the learning shepherd, over its last 30 of 60 nights. That is the second press: the score after 60 nights minus the score after 30, divided by 30. (Computed; open the page with seed 1 to reproduce.)

The wolf's habitNever learnsLearns
River sneak (left flank)22% turned away100%
Ridge runner (right flank)17%87%
Straight runner (nearest flock)37%93%
Wanderer (mostly random)88%93%

The last row is the lesson inside the lesson. A wanderer has almost no habit to learn, so the world model has almost nothing to add. Against it, a shepherd that learns does about as well as one that assumes every wolf move is equally likely and never updates (93% against 88%). Learning cannot add a pattern the wolf does not have. A world model is only as useful as the structure in the world it models. That sentence is worth a research career. In my view, much of the argument about whether large models "have world models" is really an argument about how much structure their training data forced them to capture. That is an opinion, not a finding.

The road up: from six lines to world foundation models

Later work keeps some lines of this loop and changes others. Kalman's filter assumes the model is given and learns nothing. Genie learns a simulator but does not plan. MuZero learns only the parts planning needs. The table says which part each one keeps, and the caveat each still carries.

A table from 1943 to 2025 saying which part of the loop each work keeps: Craik, the idea of planning on a model; Kalman filter, the model as a belief, given not learned; Dyna, count and plan interleaved; World Models by Ha and Schmidhuber, learn and dream, a dream not the world; MuZero, plan on what matters; Genie, learn a simulator with no planner, consistent for minutes in Genie 3; DreamerV3 in Nature, learn, dream and act. Each row has a caveat column.
The lineage, with the caveat each step still carries.

Belief instead of position.

Learn, then plan, interleaved.

Dream inside the model.

Learn only what planning needs.

One recipe for many domains.

Foundation world models.

The CS229 notes also hold the two engines inside these big models:

They are the next rungs, not this one.

Activity 3 · Write the counting half yourself, then finish it

Write a learner for a 7-cell corridor where a wolf walks toward the sheep with a habit you hide from it. Count transitions (eq. 19.5), print the learned probabilities, then use the learned model to estimate how many steps the shepherd has before the wolf arrives. Compare with the version below.

import random
random.seed(1)
N, SHEEP = 7, 6                       # a corridor of 7 cells; the sheep are in the last one
def wolf_step(w):                     # the TRUE habit, hidden from the shepherd
    return min(w + 1, SHEEP) if random.random() > 0.2 else max(w - 1, 0)
counts = [[0] * N for _ in range(N)]  # counts[w][w2]: how often the wolf went from w to w2
visits = [0] * N
def p_hat(w, w2):                     # CS229 eq. 19.5; never seen -> uniform over the wolf's moves
    if visits[w] == 0:
        return 0.5 if abs(w2 - w) == 1 or (w in (0, SHEEP) and w2 == w) else 0.0
    return counts[w][w2] / visits[w]
for night in range(200):              # watch the wolf and count
    w = 0
    while w != SHEEP:
        w2 = wolf_step(w)
        counts[w][w2] += 1
        visits[w] += 1
        w = w2
for w in range(SHEEP):
    print(w, "-> forward", round(p_hat(w, w + 1), 2), " back", round(p_hat(w, max(w - 1, 0)), 2))
E = [0.0] * N                         # plan: how many steps until the wolf reaches the sheep? (the shepherd's deadline)
for _ in range(500):                  # value iteration on expected steps-to-sheep under P-hat
    E = [0.0 if w == SHEEP else 1 + sum(p_hat(w, w2) * E[w2] for w2 in range(N)) for w in range(N)]
print("expected steps for the wolf to reach the sheep from cell 0:", round(E[0], 2))

It prints learned forward probabilities between 0.77 and 0.84 for a true value of 0.8, and an expected 9.32 steps from the first cell (computed with seed 1). Be clear about what it is. The counting is CS229's eq. 19.5. The last loop evaluates the learned chain, which is the planning step with no choice in it. Give the shepherd actions (stay, step toward the wolf) and take the best one each round, and it becomes value iteration: that is your exercise, and it is the demo's engine. Then break it on purpose:

Each change is a real research question in miniature. How much data does a world model need? What happens when the world drifts? What does planning on a wrong model cost?

Why this is where research starts

The most inspiring pages in CS229 for a would-be researcher are not about world models at all. They are section 8.2, on double descent. For decades the textbook picture said that past a point, bigger models overfit and test error rises. Then measurements showed the opposite past a further point. Belkin and colleagues reported that "increasing model capacity beyond the point of interpolation results in improved performance" (Belkin, Hsu, Ma & Mandal (2019), Reconciling modern machine-learning practice and the classical bias-variance trade-off, PNAS 116 (arXiv 1812.11118)). Nakkiran and colleagues titled their follow-up Deep Double Descent: Where Bigger Models and More Data Hurt (Nakkiran et al. (2019), Deep Double Descent, arXiv 1912.02292), because more data could even make things worse for a while.

That is the research move in its plainest form: run the thing, measure, be surprised, rebuild the theory. The shepherd demo is small enough to do it tonight. The wanderer row above is already a surprise worth explaining.

Same story, five exits

You are a…The decision this changesOne action this week
StudentWhether world models are a topic you can start on nowRun the counting half in Python, finish it, then change one assumption and write down what broke
EngineerWhether your system needs a learned model or more dataAsk whether your agent's world has structure a model could capture (the wanderer test)
FounderWhether "world model" in a pitch means a planner, a simulator or a video generatorAsk which line of the CS229 loop the product actually runs
ExecutiveWhether a world-model claim has a measurement behind itAsk for the baseline that never learns, and the gap
InvestorWhether a world-model company's moat is the model or the dataAsk how the model is corrected when the world drifts

Truth, love and beauty in this essay

One lens is my own, and I label it as mine. Shepherd's Academy of War takes its picture from David's report to Saul: "Your servant was keeping his father’s sheep; and when a lion or a bear came, and took a lamb out of the flock, I went out after him, and struck him, and rescued it out of his mouth…" (1 Samuel 17:34–35, WEB). A shepherd who learns the predator's habits in order to protect the flock is, in my faith, a picture of love that does its homework. The checklist above stands without that belief.

Mistakes that are half right

Now teach it

Your teach-back. Sit with a child of 7 to 11 and open the Shepherd's World Model in kid mode. Let the child pick the wolf's secret habit without telling you, then press "Watch one night" a few times together. Before each night, ask the child where the wolf will go and where the shepherd should stand. After ten nights, ask what the shepherd has learned. This is the drill format from Shepherd's Academy of War, part 5.

Outcome: the child predicts the wolf's next move before the shepherd moves, and can say in one sentence what the shepherd learned (for example "the wolf sneaks down the river"). Post the child's age and that sentence as a comment on this article. It is counted in Shepherd's Academy of War's signal ledger as a shepherd-demo drill, separate from SAW's weekly car-ride drill.

Why it matters: five whys

The problem: an engineer wants to work on world models and does not know where to start, because most headline papers start at billions of parameters.

  1. Why do the headline papers start big? The headline results are at scale: Genie's 11B parameters (Bruce et al. (2024), Genie, arXiv 2402.15391), and DreamerV3 in Nature (Hafner et al. (2025), Mastering diverse control tasks through world models, Nature 640).
  2. Why does starting big block understanding? At scale you cannot see which part does the work: the model, the planner, or the data.
  3. Why not? Because the parts are entangled in one network. In the CS229 loop they are separate lines you can switch off one at a time (Ma & Ng, CS229 Lecture Notes, eq. 19.5 (p. 233)).
  4. Why does switching parts off matter? It is how you find what matters. The never-learning baseline and the wanderer row are exactly that kind of experiment, and Dyna names the honest caveat: learned models are "ofttimes incorrect" (Sutton (1991), Dyna, ACM SIGART Bulletin 2).
  5. Root cause: world models are taught top-down. The fix is to build a small complete one, measure it against a baseline, break it on purpose, and then climb the lineage knowing what each step added.

Operate: run it this week

  1. Read the teach-ahead line.
  2. Sketch the shepherd's method on paper (Activity 1, 5 minutes).
  3. Run the Shepherd's World Model on all four habits and fill in your own copy of the table (10 minutes).
  4. Run the counting half in Python, finish it with the shepherd's actions, then break it on purpose (15 minutes).
  5. Run the family drill with a child and post the outcome.

Feedback: how you know it worked

Simulation-based learning has strong evidence in higher education: g = 0.85 across 145 studies (Chernikova et al. (2020), Simulation-based learning in higher education, Review of Educational Research 90). That is for students using simulations, not for children, and not for building one, so treat the family drill as a test, not a promise. Studies suggest young children build causal maps of their world: "2- to 4-year-old children construct new causal maps" (Gopnik et al. (2004), A theory of causal learning in children, Psychological Review 111). The drill asks whether that shows up when they predict a wolf.

Feedforward: tripwires, decided now

The 5S self-score

SClaimEvidence
SimpleThe prose reads at a grade-13 level or easier.Flesch–Kincaid grade of the prose: 7.3 (band ≤ 13), recomputed by node scripts/check-numbers-four-ages.mjs --series world-models-cs229
SolidEvery quoted claim comes from a fetched source with its hedge; every demo number reproduces with seed 1.DreamerV3 "to our knowledge" (Nature); seeded demo
SharpA world model is only as useful as the structure in the world it models; six lines contain the whole loop.the wanderer row · the six lines
SMARTThis week: four habits, one broken assumption, one family drill.Operate
SurpriseThe near-random wolf is the one the shepherd learns least from, and that is the lesson.Activity 2
Truth · Love · BeautySeeded truth, a child to teach, six lines that scale.Truth, love and beauty

Sources

  1. Ma, T. & Ng, A. CS229 Lecture Notes, Stanford, Spring 2026 (section 19.3, pp. 232–234; 20.4; 11.5; 14; 8.2). cs229.stanford.edu
  2. Craik, K. (1943). The Nature of Explanation, as quoted in Quanta Magazine (2025). quantamagazine.org
  3. Kalman, R. E. (1960). A New Approach to Linear Filtering and Prediction Problems. J. Basic Eng. 82. Crossref
  4. Sutton, R. S. (1991). Dyna. ACM SIGART Bulletin 2. OpenAlex
  5. Ha, D. & Schmidhuber, J. (2018). World Models. arXiv:1803.10122
  6. Schrittwieser, J. et al. (2020). MuZero. Nature 588. nature.com
  7. Hafner, D. et al. (2025). Mastering diverse control tasks through world models. Nature 640. nature.com
  8. Bruce, J. et al. (2024). Genie: Generative Interactive Environments. arXiv:2402.15391
  9. Google DeepMind (2025). Genie 3. deepmind.google
  10. NVIDIA (2025). Cosmos World Foundation Model Platform for Physical AI. arXiv:2501.03575
  11. OpenAI (2024). Video generation models as world simulators (abstract via MIT CSAIL). csail.mit.edu
  12. Kingma, D. P. & Welling, M. (2013). Auto-Encoding Variational Bayes. arXiv:1312.6114
  13. Ho, J., Jain, A. & Abbeel, P. (2020). Denoising Diffusion Probabilistic Models. arXiv:2006.11239
  14. Belkin, M., Hsu, D., Ma, S. & Mandal, S. (2019). Reconciling modern machine-learning practice and the classical bias–variance trade-off. arXiv:1812.11118
  15. Nakkiran, P. et al. (2019). Deep Double Descent. arXiv:1912.02292
  16. Chernikova, O. et al. (2020). Simulation-based learning in higher education. Review of Educational Research 90. doi:10.3102/0034654320933544
  17. Gopnik, A. et al. (2004). A theory of causal learning in children. Psychological Review 111. PubMed
  18. Kobayashi, K. (2024). Interactive learning effects of preparing to teach and teaching. Educational Psychology Review. ERIC EJ1414484
  19. 1 Samuel 17:34–36, World English Bible. bible-api.com

Related

Written by Paul Jialiang Wu · agentic-portfolio · 2026-10-16. The core loop is section 19.3 of the CS229 Lecture Notes by Tengyu Ma and Andrew Ng (Stanford); the notes are linked, not reproduced. Built with playbook-math: one idea, four ages, every number from a checked source. Views are my own, not my employer's.