Games and Learned Game Engines › Agents Trained Inside Generated Games

Michael BrenndoerferJuly 25, 20267 min read
World Models HandbookAll chapters
Part 10 of 12Application Domains
Chapter 55Games and Learned Game Engines › Agents Trained Inside Generated Games
Reading section 6 of 10 · Agents Trained Inside Generated Games · 7 minSection 6 of 10 · 7 min

Book contents

Section 6 of 10 · 7 min read

Games and Learned Game Engines › Agents Trained Inside Generated GamesOne section · Sections in this chapter6 / 10 ↓
Reading tools Definitions & inline links

Choose your expertise level to adjust how many terms are explained. Beginners see more tooltips, experts see fewer to maintain reading flow. Hover over underlined terms for instant definitions.

Article links

Make inline references clickable

A learned model can supply imagined trajectories for policy updates or candidate-action search, but the model itself first needs data. Dreamer continues to collect environment experience while learning from imagined trajectories; MuZero learns dynamics useful for search; Ha and Schmidhuber tested a dream-trained controller in VizDoom. GameNGen's DOOM generation is primarily a playable-model demonstration, not evidence that an agent trained in it transferred to the reference game. Computational and data advantages depend on the environment, hardware, model, and evaluation protocol.

A model used for decisions needs at least three properties under the intended task distribution.

  1. Decision sufficiency. It should retain information needed to rank actions for the objective, even when visual reconstruction is not required.
  2. Rollout stability over the planning horizon. The drift we just measured must be small enough that short plans remain accurate.
  3. Reward realism. The predicted reward must be aligned with the true reward on states the planner tends to visit.

These conditions differ from visual playability, rather than forming a guaranteed sufficient test. A model can be useful for one planner while looking poor, and a rendered world can look persuasive while giving wrong rewards. Even when the three conditions appear to hold on a test set, distribution shift under optimization can expose further errors.

Two Ways to Train an Agent with a Model

The literature separates two styles of use.

  • Policy learning in imagination. The agent updates an actor and critic from modeled trajectories, as Dreamer does. The learned policy can exploit errors in the world model; actual training also needs environment data for that model.
  • Planning in the model. A planner evaluates candidate futures and chooses an action, as in MuZero's MCTS or the simple MPC below. Replanning from a new observation limits the length of the executed open-loop plan but does not make the first decision immune to errors in simulated futures.

Both styles can exploit errors. An imagined policy is trained against model predictions; a planner can choose a bad first action because an inaccurate later reward made its candidate sequence look attractive. Receding-horizon search then observes the new real state before choosing again, while an actor does not necessarily search anew at each decision. Search also has a per-decision cost that depends on its budget. The example below demonstrates random-shooting MPC, not a general superiority claim for planning.

Model Exploitation Is the Central Risk

Optimization can favor model-predicted outcomes that do not occur in the reference environment. For the grid world, separate the true reward rule from the network's reward-head prediction. The environment returns

rt=−∥st+1−g∥1,r_t=-\lVert s_{t+1}-g\rVert_1,

Here st+1s_{t+1} is the true post-action agent coordinate, gg is the true goal coordinate, and ∥⋅∥1\lVert\cdot\rVert_1 is Manhattan distance. The learned model instead predicts

r^t=Rθ(ot,at),\hat r_t=R_\theta(o_t,a_t),

where RθR_\theta is the separate scalar reward head after the MLP trunk. It is not computed by decoding the predicted next observation or measuring its distance to a decoded goal. In particular, a one-cell observation-prediction error does not imply a one-unit error in r^t\hat r_t. The planner below sums these direct reward-head outputs. Model exploitation remains possible if a candidate action sequence receives optimistic reward predictions, but this code does not demonstrate that it occurs.

The distinction between the two heads matters diagnostically: observation drift and reward error need separate measurements. A visually wrong rollout might still rank actions well, while a visually plausible one might misrank them. Repeated optimization can search for optimistic predictions, but whether that happens here must be measured against true returns.

Common responses to this risk change the model, planner, or objective:

  • Ensembles and uncertainty penalties. Model disagreement can signal poorly supported actions, although disagreement is not a perfect error estimate. PILCO, PETS, Ensembles, and MBPO compares related approaches.
  • Short imagination horizons. Dreamer imagines finite rollouts and uses a value model to estimate returns beyond them. Shorter rollouts limit how far the learned dynamics are applied directly, although accumulated model error is not the paper's stated reason for this design.
  • Real-data correction. New reference-environment transitions can reveal and repair model errors in visited regions, at an interaction cost.
  • Conservatism. MOPO subtracts a model-uncertainty penalty from imagined rewards; MOReL routes unsupported state-actions to a pessimistic unknown state. Part VIII's planned chapter on offline and conservative model-based RL covers this family.

Each mitigation changes what the agent is allowed to optimize or what evidence it receives. None guarantees transfer for an arbitrary learned model. Evaluate the chosen policy in the reference environment, not solely against its training model.

Demonstrating Planning Inside the Learned Engine

At each environment step, random-shooting MPC samples action sequences of length HH, rolls them out inside the learned model, and selects the sequence with the highest sum of predicted reward-head outputs. It executes only that sequence's first action, observes the real next state, and plans again. Re-anchoring prevents errors in an unexecuted trajectory from becoming the next observed state, but errors at any simulated depth can still affect which first action wins the search.

In[22]:
Code
def mpc_plan(model, obs_flat, horizon=5, n_samples=64, rng=None):
    """Random-shooting MPC. Returns the best first action."""
    if rng is None:
        rng = np.random.default_rng()
    best_total = -np.inf
    best_a0 = 0
    with torch.no_grad():
        for _ in range(n_samples):
            seq = rng.integers(0, N_ACTIONS, size=horizon)
            cur = obs_flat.unsqueeze(0)
            total = 0.0
            for a in seq:
                a_t = torch.tensor([int(a)])
                next_obs, r = model(cur, a_t)
                total += float(r.item())
                cur = next_obs
            if total > best_total:
                best_total = total
                best_a0 = int(seq[0])
    return best_a0

We evaluate the planner in the reference grid world with a seed separate from data collection. This closed-loop test checks whether actions selected using the model reach the real goal; it complements, rather than replaces, transition and reward-error measurements.

In[23]:
Code
def evaluate_mpc(model, horizon=5, n_episodes=30, seed=1234, n_samples=64):
    env = GridWorld(seed=seed)
    rng = np.random.default_rng(seed)
    wins = 0
    for _ in range(n_episodes):
        obs = env.reset()
        done = False
        while not done:
            obs_flat = torch.from_numpy(obs.reshape(-1))
            a = mpc_plan(
                model, obs_flat, horizon=horizon, n_samples=n_samples, rng=rng
            )
            obs, _, done = env.step(a)
        if np.array_equal(env.agent, env.goal):
            wins += 1
    return wins / n_episodes


results = {}
for h in [1, 2, 5, 10]:
    results[h] = evaluate_mpc(W_model, horizon=h)
Out[24]:
Console
Horizon  1: success rate 1.00
Horizon  2: success rate 1.00
Horizon  5: success rate 1.00
Horizon 10: success rate 1.00
Out[25]:
Visualization
Bar chart of MPC success rate at horizons one, two, five, and ten.
Real-environment success rates for random-shooting MPC using the learned grid-world model at four planning horizons. All tested horizons achieve 100% success on the thirty seeded episodes each, so this experiment cannot demonstrate an improvement with horizon or a later drift-induced decline.

All four tested horizons reach the goal on every one of the thirty seeded evaluation episodes for that horizon. Each evaluation call starts its environment and planner generators from the same seed; different horizon lengths group and consume the planner draws differently, so this is not a paired comparison of identical candidate sequences. These saturated results show that the learned model supports this planner on these small test cases despite observation rollout error. They do not show a benefit from increasing the horizon, a drift-induced decline, an optimal horizon, or guaranteed improvement from more samples. On a harder task, those effects would need a broader paired evaluation.

Pixel-level rollout error and decision usefulness answer different questions. Here the planner reaches the goal on the tested episodes despite substantial observation error; thirty trials per horizon are too narrow to establish reliability elsewhere. Evaluate both model predictions and closed-loop outcomes on held-out starts and, where possible, new tasks, reporting uncertainty when comparing methods.