AI Wiki中文/EN

MuZero: plan inside learned latent states

MuZero

Trace representation, dynamics and prediction, checking reward indexing, unrolled training and model-induced wrong routes.

On this pageIntuitionMathematics & methodImplementationLimitationsExercisesResearch connections

Must planning first draw the next image?

Consider an original two-step game. First choose a route, then a finishing action. The two best complete routes give discounted returns 0.9 and 0.82. To choose between them, a model might retain what rewards remain and which actions deserve attention, without reconstructing a complete image.

MuZero brings this idea to model-based reinforcement learning: encode real observations internally, predict how actions change that representation, then predict rewards, values and policies. Search uses this learned model. The original paper requires neither latent states equal to real states nor a pixel-reconstruction loss. That does not prove model accuracy or mean arbitrary compression preserves good decisions. Prediction and planning objectives

The key interface difference from AlphaZero is internal expansion. AlphaZero calls known rules for exact successor positions; MuZero uses learned dynamics. The real environment still supplies training experience and actual rewards. Its board-game pseudocode also receives current legal actions at the root. Avoiding a true dynamics simulator inside search does not eliminate all task interfaces. AlphaZero rules Root and internal interfaces

The learned model reverses the ranking of two action sequences for seed 1. All-seed real returns and separate interaction, search and update budgets retain this failure. Tables show three significant digits.
The learned model reverses the ranking of two action sequences for seed 1. All-seed real returns and separate interaction, search and update budgets retain this failure. Tables show three significant digits.

Three functions and two time coordinates

Let tt index real time and kk count imagined steps from the current root. Real observations are oto_t, real rewards are utu_t and latent states are stks_t^k. Real action at+1a_{t+1} leads to the next observation and reward ut+1u_{t+1}. The three learned functions are:

st0=hθ(o≤t),(rtk,stk)=gθ(stk−1,at+k),(ptk,vtk)=fθ(stk).s_t^0=h_\theta(o_{\le t}),\qquad (r_t^k,s_t^k)=g_\theta(s_t^{k-1},a_{t+k}),\qquad (p_t^k,v_t^k)=f_\theta(s_t^k).

Here hh is representation, gg is dynamics and ff is prediction. Reward rtkr_t^k predicts the just-completed kkth action’s reward, whereas vtkv_t^k predicts return after it. The same immediate reward must not be counted twice. Policy ptkp_t^k supplies priors for the next action. Real observations may require history; our discrete teaching observation is already Markov, so hh reads only the current observation. Functions and indices

We consistently define an edge’s QQ as the mean full return including that edge’s immediate reward. For a simulation reaching depth LL with leaf value vtLv_t^L, backup is:

GL=vtL,Gk−1=rtk+γGk,Q(sk−1,ak)←N(sk−1,ak)Q(sk−1,ak)+Gk−1N(sk−1,ak)+1.G^L=v_t^L,\qquad G^{k-1}=r_t^k+\gamma G^k,\qquad Q(s^{k-1},a^k)\leftarrow\frac{N(s^{k-1},a^k)Q(s^{k-1},a^k)+G^{k-1}}{N(s^{k-1},a^k)+1}.

The edge count then increases by one. With rewards 2 and 3, discount 0.9 and leaf value 4, root return is 2+0.9×3+0.92×4=7.942+0.9\times3+0.9^2\times4=7.94. Storing the second node’s continuation value 6.6 as the first edge’s full return loses a reward and a discount.

Another implementation can store node continuation and incoming-edge reward separately, combining them during selection. MuZero v2’s ancillary pseudocode has these fields. We choose full edge returns so each statistic has one interpretation. Reading paper edge notation beside code node fields requires tracking indices, not replacing quantities merely because both are called value. Our program is single-agent and does not apply two-player zero-sum sign alternation. Pseudocode selection and backup

Training value targets come from real trajectories. Long tasks can use nn real rewards followed by a future search-root value ν\nu:

zt=∑i=1nγi−1ut+i+γnνt+n.z_t=\sum_{i=1}^{n}\gamma^{i-1}u_{t+i}+\gamma^n\nu_{t+n}.

Imagined model rewards are not substituted as real labels. Genuine termination leaves no future continuation. Our two-step example uses complete real-episode Monte Carlo returns without that future bootstrap term. Policy targets are search visit distributions π\pi at corresponding real positions, and reward targets are observed uu. Multistep targets

Training selects a real observation from replay and feeds subsequent actually executed actions through KK recurrent steps. Our program explicitly uses the following normalization, with mt+km_{t+k} indicating whether policy supervision is required:

ℓ=1K+1∑k=0K[(vtk−zt+k)2−mt+kπt+kTlog⁡ptk]+1K∑k=1K(rtk−ut+k)2+λ∥θ∥22.\ell=\frac{1}{K+1}\sum_{k=0}^{K}\left[(v_t^k-z_{t+k})^2-m_{t+k}\pi_{t+k}^{\mathsf T}\log p_t^k\right] +\frac{1}{K}\sum_{k=1}^{K}(r_t^k-u_{t+k})^2+\lambda\|\theta\|_2^2.

Index each term carefully. The root has policy/value supervision but no newly executed imagined action, so our program does not separately fit its previous reward. The first reward prediction belongs to the first unrolled action. For interface simplicity, the original v2 pseudocode also predicts the known most recent reward during initial inference; our interface differs. The paper also uses task-dependent scalar losses and training details. This equation is our explicit teaching choice, not a single loss shared by every MuZero version. Joint training Target construction and simplification

Search compares values and priors. Our program normalizes full edge returns before adding a prior exploration term:

Q‾={(Q−qmin⁡)/(qmax⁡−qmin⁡),qmax⁡>qmin⁡,0,qmax⁡=qmin⁡,S(a)=Q‾(s,a)+c p(a∣s)N(s)+11+N(s,a).\overline Q=\begin{cases}(Q-q_{\min})/(q_{\max}-q_{\min}),&q_{\max}>q_{\min},\\0,&q_{\max}=q_{\min},\end{cases} \qquad S(a)=\overline Q(s,a)+c\,p(a\mid s)\frac{\sqrt{N(s)+1}}{1+N(s,a)}.

The range starts at zero and expands to include observed edge means. We fix c=1.5c=1.5 and reset statistics for each root search. This normalizes the complete r+γVr+\gamma V. The v2 pseudocode instead writes r+γnormalize⁡(V)r+\gamma\operatorname{normalize}(V), which is not algebraically interchangeable. For range 0–10, r=2,V=4,γ=0.9r=2,V=4,\gamma=0.9, the two calculations give 0.56 and 2.36. We specify our teaching convention without claiming an independently established paper erratum. Search statistics and normalization Actual v2 expression

Representation and dynamics must receive future prediction errors, rather than only fitting current heads. In our program, reward is also predicted from the current unrolled latent state. Write local head losses as ℓk\ell^k and the state component of dynamics as gsg_s. Backpropagation includes:

∂ℓ∂sk=∂ℓk∂sk+(∂gs(sk,ak+1)∂sk)T∂ℓ∂sk+1,0≤k<K.\frac{\partial\ell}{\partial s^k} =\frac{\partial\ell^k}{\partial s^k} +\left(\frac{\partial g_s(s^k,a^{k+1})}{\partial s^k}\right)^{\mathsf T} \frac{\partial\ell}{\partial s^{k+1}},\qquad 0\le k<K.

Future errors travel through the unroll into root representation: this is joint training. Original pseudocode also uses scale_gradient to adjust backward magnitudes while retaining forward values. It does not simply multiply the forward hidden state by 0.5. Our program uses ordinary full BPTT, explicit loss averaging and gradient-norm clipping, not every engineering technique in the paper. Backward-scaling interface

Learn a model instead of secretly calling the rules

The program requires Python 3.12 or later and NumPy; our run used Python 3.12.4 and NumPy 1.26.4. Observations are labeled 0, 1, 2 and 3, the last being genuinely terminal. In state 0, action 0 pays zero and goes to 1; action 1 pays 0.1 and goes to 2. State 1’s two actions pay 1 and −1; state 2’s pay −1 and 0.8, all terminating. With discount 0.9, the four complete action sequences return 0.9, −0.9, −0.8 and 0.82.

Function hh learns an eight-dimensional observation embedding. Function gg selects a learned affine transform by action, applies tanh to obtain a next latent state, then predicts reward. Function ff outputs a two-action softmax and linear value. All 220 parameters receive multistep training. There is no true-successor reconstruction loss or requirement that g(h(o),a)g(h(o),a) equal the next real observation’s embedding.

Training starts with 32 random-action episodes and continues for 100 model-search episodes. Warm-up policy labels are uniform behavior distributions; subsequent labels come from search. This is an explicit teaching warm-up choice. Each episode has two real actions; each searched training move uses 16 simulations with depth capped at 3. Each episode performs eight batch-eight updates with unroll length 3, learning rate 0.05, L2 coefficient 10−410^{-4} and gradient-norm cap 5. Data, planning and batch random streams are separate; evaluation uses another fixed seed.

After an episode, absorbing targets can fill short training sequences, but cannot erase the final real reward. If genuine termination occurs at observation oTo_T:

zT+j=0(j≥0),uT+j=0(j≥1),mT+j=0(j≥0).z_{T+j}=0\quad(j\ge0),\qquad u_{T+j}=0\quad(j\ge1),\qquad m_{T+j}=0\quad(j\ge0).

The arriving reward uTu_T still needs prediction. Later rewards and future values are zero, and policy supervision is skipped. Absorbing padding does not count as new real interaction. Internal latent search does not call a true termination test; it relies on absorbing training and limited depth, and can still predict an incorrect terminal continuation.

"""Original latent planning learner in a two-step task; NumPy, no pixel benchmark."""
import json
import math
import numpy as np

GAMMA, HIDDEN = .9, 8


def environment(state, action):
    """Real task, called only by collection and diagnostics, never by search."""
    if action not in (0,1) or not isinstance(action,(int,np.integer)):
        raise ValueError('Action must be zero or one.')
    if state == 0:
        return (0., 1, False) if action == 0 else (.1, 2, False)
    if state == 1:
        return (1. if action == 0 else -1.), 3, True
    if state == 2:
        return (-1. if action == 0 else .8), 3, True
    if state == 3:
        return 0., 3, True
    raise ValueError('Unknown observation.')


def init(seed):
    rng = np.random.default_rng(seed)
    return dict(E=rng.normal(0, .25, (4,HIDDEN)),
                G=rng.normal(0, .2, (2,HIDDEN,HIDDEN)),
                A=rng.normal(0, .2, (2,HIDDEN)), bg=np.zeros(HIDDEN),
                wr=rng.normal(0, .2, HIDDEN), br=np.zeros(1),
                Wp=rng.normal(0, .2, (HIDDEN,2)), bp=np.zeros(2),
                wv=rng.normal(0, .2, HIDDEN), bv=np.zeros(1))


def representation(w, observation):
    if not isinstance(observation,(int,np.integer)) or not 0 <= observation < 4:
        raise ValueError('Observation must be an integer from zero to three.')
    return np.tanh(w['E'][observation])


def dynamics(w, latent, action):
    if action not in (0,1) or not isinstance(action,(int,np.integer)):
        raise ValueError('Action must be zero or one.')
    next_latent = np.tanh(latent @ w['G'][action] + w['A'][action] + w['bg'])
    reward = float(next_latent @ w['wr'] + w['br'][0])
    return reward, next_latent


def prediction(w, latent):
    logits = latent @ w['Wp'] + w['bp']
    exp = np.exp(logits-max(logits))
    return exp/exp.sum(), float(latent @ w['wv'] + w['bv'][0])


def loss_grad(w, sample, decay=1e-4):
    """Joint backprop through representation, recurrent dynamics and all heads."""
    obs, actions, rewards, values, policies = sample
    kmax = len(actions)
    if kmax < 1 or len(rewards) != kmax or len(values) != kmax+1 or len(policies) != kmax+1:
        raise ValueError('Unroll and target lengths must agree.')
    if decay < 0 or not math.isfinite(decay) or not np.isfinite(rewards+values).all():
        raise ValueError('Finite targets and nonnegative finite regularization required.')
    states = [representation(w,obs)]
    predicted_rewards = []
    for action in actions:
        reward, latent = dynamics(w,states[-1],action)
        states.append(latent)
        predicted_rewards.append(reward)
    gradients = {key:np.zeros_like(v) for key,v in w.items()}
    dz = [np.zeros(HIDDEN) for _ in states]
    loss = 0.
    for k,latent in enumerate(states):
        probs, value = prediction(w,latent)
        dv = 2*(value-values[k])/(kmax+1)
        loss += (value-values[k])**2/(kmax+1)
        gradients['wv'] += latent*dv
        gradients['bv'][0] += dv
        dz[k] += w['wv']*dv
        if policies[k] is not None:  # no policy target beyond genuine termination
            target = np.asarray(policies[k])
            if target.shape != (2,) or np.any(target < 0) or not np.isclose(target.sum(),1):
                raise ValueError('Policy target must be a probability distribution.')
            dl = (probs-target)/(kmax+1)
            loss -= np.sum(target*np.log(probs))/(kmax+1)
            gradients['Wp'] += np.outer(latent,dl)
            gradients['bp'] += dl
            dz[k] += w['Wp'] @ dl
        if k:
            dr = 2*(predicted_rewards[k-1]-rewards[k-1])/kmax
            loss += (predicted_rewards[k-1]-rewards[k-1])**2/kmax
            gradients['wr'] += latent*dr
            gradients['br'][0] += dr
            dz[k] += w['wr']*dr
    for k in range(kmax,0,-1):
        dpre = dz[k]*(1-states[k]**2)
        gradients['G'][actions[k-1]] += np.outer(states[k-1],dpre)
        gradients['A'][actions[k-1]] += dpre
        gradients['bg'] += dpre
        dz[k-1] += w['G'][actions[k-1]] @ dpre
    gradients['E'][obs] += dz[0]*(1-states[0]**2)
    for key in w:
        loss += decay*np.sum(w[key]**2)
        gradients[key] += 2*decay*w[key]
    return float(loss), gradients


class Node:
    def __init__(self,w,latent):
        self.latent = latent
        self.prior, self.value = prediction(w,latent)
        self.visits = 0
        self.edges = {}  # action -> [reward, child, count, full-return sum]


def search(w, observation, budget, rng, noise=False, depth_limit=3):
    if not isinstance(budget,int) or budget < 1 or not isinstance(depth_limit,int) or depth_limit < 1:
        raise ValueError('Positive simulation and depth budgets required.')
    root = Node(w,representation(w,observation))
    if noise:
        root.prior = .75*root.prior+.25*rng.dirichlet([.3,.3])
    minimum, maximum, expansions = 0., 0., 0
    for _ in range(budget):
        node, path, depth = root, [], 0
        while depth < depth_limit:
            scores = []
            for a in (0,1):
                e = node.edges.get(a)
                count, q = (e[2],e[3]/e[2]) if e else (0,0.)
                # This teaching variant normalizes the complete edge return.
                normalized = (q-minimum)/(maximum-minimum) if maximum > minimum else 0.
                scores.append(normalized+1.5*node.prior[a]*math.sqrt(node.visits+1)/(1+count))
            best = max(scores)
            action = int(rng.choice([a for a,s in enumerate(scores) if s == best]))
            path.append((node,action))
            depth += 1
            if action not in node.edges:
                reward, latent = dynamics(w,node.latent,action)
                child = Node(w,latent)
                node.edges[action] = [reward,child,0,0.]
                expansions += 1
                node = child
                break
            node = node.edges[action][1]
        value = node.value
        for parent,action in reversed(path):
            edge = parent.edges[action]
            value = edge[0]+GAMMA*value
            edge[2] += 1
            edge[3] += value
            parent.visits += 1
            mean = edge[3]/edge[2]
            minimum,maximum = min(minimum,mean),max(maximum,mean)
    counts = np.array([root.edges[a][2] if a in root.edges else 0 for a in (0,1)])
    return counts/counts.sum(), dict(counts=counts.tolist(),root_visits=root.visits,
                                    model_expansions=expansions,simulations=budget,
                                    root_q=[root.edges[a][3]/root.edges[a][2] if a in root.edges else None for a in (0,1)])


def samples_from_episode(observations,actions,rewards,policies,rng,unroll=3):
    # Complete real episodes supply MC returns; beyond-end targets are absorbing padding.
    if (not isinstance(unroll,int) or unroll < 1 or len(observations) != len(actions)+1
            or len(rewards) != len(actions) or len(policies) != len(actions)
            or observations[-1] != 3):
        raise ValueError('A complete episode and positive integer unroll are required.')
    values = [0.]*(len(rewards)+1)
    for i in range(len(rewards)-1,-1,-1):
        values[i] = rewards[i]+GAMMA*values[i+1]
    samples = []
    for t,obs in enumerate(observations):
        aa,rr,vv,pp = [],[],[],[]
        for k in range(unroll+1):
            index = t+k
            vv.append(values[index] if index < len(values) else 0.)
            pp.append(policies[index].copy() if index < len(policies) else None)
            if k < unroll:
                aa.append(actions[index] if index < len(actions) else int(rng.integers(2)))
                rr.append(rewards[index] if index < len(rewards) else 0.)
        samples.append((obs,aa,rr,vv,pp))
    return samples


def evaluate(w, budget=16):
    rng = np.random.default_rng(9900)
    actions,policies,searches = [],[],[]
    state,total,discount = 0,0.,1.
    while state != 3:
        policy,report = search(w,state,budget,rng)
        action = int(np.argmax(policy))
        reward,state,done = environment(state,action)
        total += discount*reward;discount *= GAMMA
        actions.append(action);policies.append(policy.tolist());searches.append(report)
    root_latent = representation(w,0)
    sequences = []
    for a in (0,1):
        for b in (0,1):
            r1,z1 = dynamics(w,root_latent,a)
            r2,z2 = dynamics(w,z1,b)
            _,v2 = prediction(w,z2)
            actual1,s1,_ = environment(0,a);actual2,_,_ = environment(s1,b)
            sequences.append(dict(actions=[a,b],predicted_rewards=[r1,r2],
                                  predicted_terminal_value=v2,
                                  predicted_return=r1+GAMMA*r2+GAMMA**2*v2,
                                  real_return=actual1+GAMMA*actual2))
    return dict(real_return=total,actions=actions,policies=policies,searches=searches,sequences=sequences)


def train(seed, episodes=100, warmup=32, updates_per_episode=8, budget=16):
    if (any(not isinstance(x,int) or x < 1 for x in (episodes,updates_per_episode,budget))
            or not isinstance(warmup,int) or warmup < 0):
        raise ValueError('Positive training/search budgets and nonnegative warm-up required.')
    w = init(seed)
    data_rng = np.random.default_rng(seed+1000)
    planning_rng = np.random.default_rng(seed+2000)
    batch_rng = np.random.default_rng(seed+3000)
    replay,checkpoints = [],[]
    before = evaluate(w)
    real_moves = simulations = updates = 0
    pair_counts = [[0,0] for _ in range(3)]
    for episode in range(warmup+episodes):
        state,obs,actions,rewards,policies = 0,[0],[],[],[]
        while state != 3:
            if episode < warmup:
                policy = np.array([.5,.5])  # explicit random-data warm-up
            else:
                policy,_ = search(w,state,budget,planning_rng,noise=True)
                simulations += budget
            action = int(data_rng.choice(2,p=policy))
            pair_counts[state][action] += 1
            reward,state,done = environment(state,action)
            actions.append(action);rewards.append(reward);policies.append(policy);obs.append(state)
            real_moves += 1
        replay.extend(samples_from_episode(obs,actions,rewards,policies,data_rng))
        replay = replay[-1200:]
        for _ in range(updates_per_episode):
            batch = [replay[i] for i in batch_rng.integers(len(replay),size=8)]
            gradient = {k:np.zeros_like(v) for k,v in w.items()};loss=0.
            for sample in batch:
                part,g = loss_grad(w,sample);loss += part/len(batch)
                for k in gradient:gradient[k] += g[k]/len(batch)
            norm = math.sqrt(sum(float(np.sum(g*g)) for g in gradient.values()))
            scale = min(1.,5/max(norm,1e-12))
            for k in w:w[k] -= .05*scale*gradient[k]
            updates += 1
        if (episode+1) % 32 == 0:
            checkpoints.append(dict(episode=episode+1,last_minibatch_loss=loss,**evaluate(w)))
    return dict(seed=seed,episodes=warmup+episodes,random_warmup_episodes=warmup,
                real_moves=real_moves,training_simulations=simulations,gradient_steps=updates,
                replay_samples=len(replay),real_pair_counts=pair_counts,before=before,after=evaluate(w),checkpoints=checkpoints,
                weights={k:v.tolist() for k,v in w.items()})


if __name__ == '__main__':
    print(json.dumps(train(0),indent=2))
Inspect the complete recorded output
{
  "seed": 0,
  "episodes": 132,
  "random_warmup_episodes": 32,
  "real_moves": 264,
  "training_simulations": 3200,
  "gradient_steps": 1056,
  "replay_samples": 396,
  "real_pair_counts": [
    [
      80,
      52
    ],
    [
      66,
      14
    ],
    [
      11,
      41
    ]
  ],
  "before": {
    "real_return": 0.9,
    "actions": [
      0,
      0
    ],
    "policies": [
      [
        0.75,
        0.25
      ],
      [
        0.6875,
        0.3125
      ]
    ],
    "searches": [
      {
        "counts": [
          12,
          4
        ],
        "root_visits": 16,
        "model_expansions": 10,
        "simulations": 16,
        "root_q": [
          -0.026041212330549235,
          -0.1844567929777039
        ]
      },
      {
        "counts": [
          11,
          5
        ],
        "root_visits": 16,
        "model_expansions": 12,
        "simulations": 16,
        "root_q": [
          -0.06927077721579054,
          -0.24481425148340663
        ]
      }
    ],
    "sequences": [
      {
        "actions": [
          0,
          0
        ],
        "predicted_rewards": [
          0.005798558041537286,
          -0.06392557270932717
        ],
        "predicted_terminal_value": 0.11589423268886745,
        "predicted_return": 0.04213987108112548,
        "real_return": 0.9
      },
      {
        "actions": [
          0,
          1
        ],
        "predicted_rewards": [
          0.005798558041537286,
          -0.12065151576084737
        ],
        "predicted_terminal_value": -0.04765000142782609,
        "predicted_return": -0.14138430729976448,
        "real_return": -0.9
      },
      {
        "actions": [
          1,
          0
        ],
        "predicted_rewards": [
          -0.11160012127619856,
          -0.07908368937095805
        ],
        "predicted_terminal_value": 0.01224328641708343,
        "predicted_return": -0.17285837971222326,
        "real_return": -0.8
      },
      {
        "actions": [
          1,
          1
        ],
        "predicted_rewards": [
          -0.11160012127619856,
          -0.1294226748439823
        ],
        "predicted_terminal_value": -0.049065694993986164,
        "predicted_return": -0.26782374158091143,
        "real_return": 0.8200000000000001
      }
    ]
  },
  "after": {
    "real_return": 0.9,
    "actions": [
      0,
      0
    ],
    "policies": [
      [
        0.6875,
        0.3125
      ],
      [
        0.9375,
        0.0625
      ]
    ],
    "searches": [
      {
        "counts": [
          11,
          5
        ],
        "root_visits": 16,
        "model_expansions": 8,
        "simulations": 16,
        "root_q": [
          0.8619774925916637,
          0.709429496308854
        ]
      },
      {
        "counts": [
          15,
          1
        ],
        "root_visits": 16,
        "model_expansions": 8,
        "simulations": 16,
        "root_q": [
          0.9733353439597489,
          -1.1288028034630353
        ]
      }
    ],
    "sequences": [
      {
        "actions": [
          0,
          0
        ],
        "predicted_rewards": [
          -0.0033763030277872627,
          1.0217654109442595
        ],
        "predicted_terminal_value": -0.0672141707878609,
        "predicted_return": 0.861769088483879,
        "real_return": 0.9
      },
      {
        "actions": [
          0,
          1
        ],
        "predicted_rewards": [
          -0.0033763030277872627,
          -0.9933865415559276
        ],
        "predicted_terminal_value": -0.15804283637953148,
        "predicted_return": -1.0254388878955427,
        "real_return": -0.9
      },
      {
        "actions": [
          1,
          0
        ],
        "predicted_rewards": [
          0.10289097679323758,
          -0.9363796864486441
        ],
        "predicted_terminal_value": 0.11085896963752778,
        "predicted_return": -0.6500549756041446,
        "real_return": -0.8
      },
      {
        "actions": [
          1,
          1
        ],
        "predicted_rewards": [
          0.10289097679323758,
          0.800618370028547
        ],
        "predicted_terminal_value": -0.03838078541252177,
        "predicted_return": 0.7923590736347873,
        "real_return": 0.8200000000000001
      }
    ]
  },
  "checkpoints": [
    {
      "episode": 32,
      "last_minibatch_loss": 0.42416191598963665,
      "real_return": 0.9,
      "actions": [
        0,
        0
      ],
      "policies": [
        [
          0.6875,
          0.3125
        ],
        [
          0.875,
          0.125
        ]
      ],
      "searches": [
        {
          "counts": [
            11,
            5
          ],
          "root_visits": 16,
          "model_expansions": 11,
          "simulations": 16,
          "root_q": [
            0.601135500508052,
            0.18399857921305213
          ]
        },
        {
          "counts": [
            14,
            2
          ],
          "root_visits": 16,
          "model_expansions": 9,
          "simulations": 16,
          "root_q": [
            0.8891773951147338,
            -0.5644548330824508
          ]
        }
      ],
      "sequences": [
        {
          "actions": [
            0,
            0
          ],
          "predicted_rewards": [
            0.1735961100520435,
            0.6032741334311401
          ],
          "predicted_terminal_value": 0.17376250083787126,
          "predicted_return": 0.8572904558187453,
          "real_return": 0.9
        },
        {
          "actions": [
            0,
            1
          ],
          "predicted_rewards": [
            0.1735961100520435,
            -0.29077925815737793
          ],
          "predicted_terminal_value": -0.1267998714124936,
          "predicted_return": -0.19081311813371649,
          "real_return": -0.9
        },
        {
          "actions": [
            1,
            0
          ],
          "predicted_rewards": [
            0.0899990634488382,
            -0.6410896915190724
          ],
          "predicted_terminal_value": -0.13242328306657497,
          "predicted_return": -0.5942445182022527,
          "real_return": -0.8
        },
        {
          "actions": [
            1,
            1
          ],
          "predicted_rewards": [
            0.0899990634488382,
            0.3811839527322044
          ],
          "predicted_terminal_value": 0.08542922787050722,
          "predicted_return": 0.502262295482933,
          "real_return": 0.8200000000000001
        }
      ]
    },
    {
      "episode": 64,
      "last_minibatch_loss": 0.3553386372518754,
      "real_return": 0.9,
      "actions": [
        0,
        0
      ],
      "policies": [
        [
          0.75,
          0.25
        ],
        [
          0.9375,
          0.0625
        ]
      ],
      "searches": [
        {
          "counts": [
            12,
            4
          ],
          "root_visits": 16,
          "model_expansions": 9,
          "simulations": 16,
          "root_q": [
            0.8115435629304911,
            0.27813301387458
          ]
        },
        {
          "counts": [
            15,
            1
          ],
          "root_visits": 16,
          "model_expansions": 8,
          "simulations": 16,
          "root_q": [
            1.034395437235802,
            -0.9000909993934612
          ]
        }
      ],
      "sequences": [
        {
          "actions": [
            0,
            0
          ],
          "predicted_rewards": [
            0.023454866861555623,
            1.032304712357938
          ],
          "predicted_terminal_value": 0.04419859674416218,
          "predicted_return": 0.9883299713464713,
          "real_return": 0.9
        },
        {
          "actions": [
            0,
            1
          ],
          "predicted_rewards": [
            0.023454866861555623,
            -0.815036415387806
          ],
          "predicted_terminal_value": -0.0473299627142888,
          "predicted_return": -0.7484151767860437,
          "real_return": -0.9
        },
        {
          "actions": [
            1,
            0
          ],
          "predicted_rewards": [
            0.10844153651943682,
            -0.9101684477738338
          ],
          "predicted_terminal_value": 0.08573739933662522,
          "predicted_return": -0.6412627730143472,
          "real_return": -0.8
        },
        {
          "actions": [
            1,
            1
          ],
          "predicted_rewards": [
            0.10844153651943682,
            0.7529186517064107
          ],
          "predicted_terminal_value": 0.1043757110271693,
          "predicted_return": 0.8706126489872136,
          "real_return": 0.8200000000000001
        }
      ]
    },
    {
      "episode": 96,
      "last_minibatch_loss": 0.15335364510097158,
      "real_return": 0.9,
      "actions": [
        0,
        0
      ],
      "policies": [
        [
          0.6875,
          0.3125
        ],
        [
          0.9375,
          0.0625
        ]
      ],
      "searches": [
        {
          "counts": [
            11,
            5
          ],
          "root_visits": 16,
          "model_expansions": 10,
          "simulations": 16,
          "root_q": [
            0.7697828668617324,
            0.41792947979524564
          ]
        },
        {
          "counts": [
            15,
            1
          ],
          "root_visits": 16,
          "model_expansions": 8,
          "simulations": 16,
          "root_q": [
            0.984724845402061,
            -1.0816521821430976
          ]
        }
      ],
      "sequences": [
        {
          "actions": [
            0,
            0
          ],
          "predicted_rewards": [
            0.007055578369837667,
            1.055153842267748
          ],
          "predicted_terminal_value": -0.019538408395589568,
          "predicted_return": 0.9408679256103835,
          "real_return": 0.9
        },
        {
          "actions": [
            0,
            1
          ],
          "predicted_rewards": [
            0.007055578369837667,
            -0.9528851958761811
          ],
          "predicted_terminal_value": -0.13625939612519916,
          "predicted_return": -0.9609112087801367,
          "real_return": -0.9
        },
        {
          "actions": [
            1,
            0
          ],
          "predicted_rewards": [
            0.09955012708621805,
            -0.9094810059183069
          ],
          "predicted_terminal_value": 0.12769741936341333,
          "predicted_return": -0.6155478685558935,
          "real_return": -0.8
        },
        {
          "actions": [
            1,
            1
          ],
          "predicted_rewards": [
            0.09955012708621805,
            0.8034749543914307
          ],
          "predicted_terminal_value": 0.01820414395441211,
          "predicted_return": 0.8374229426415795,
          "real_return": 0.8200000000000001
        }
      ]
    },
    {
      "episode": 128,
      "last_minibatch_loss": 0.25631259247208166,
      "real_return": 0.9,
      "actions": [
        0,
        0
      ],
      "policies": [
        [
          0.75,
          0.25
        ],
        [
          0.9375,
          0.0625
        ]
      ],
      "searches": [
        {
          "counts": [
            12,
            4
          ],
          "root_visits": 16,
          "model_expansions": 8,
          "simulations": 16,
          "root_q": [
            0.897042086252022,
            0.7012195385476048
          ]
        },
        {
          "counts": [
            15,
            1
          ],
          "root_visits": 16,
          "model_expansions": 8,
          "simulations": 16,
          "root_q": [
            0.9808116159395832,
            -1.1090282327618939
          ]
        }
      ],
      "sequences": [
        {
          "actions": [
            0,
            0
          ],
          "predicted_rewards": [
            0.0002548561512478384,
            1.020692415057889
          ],
          "predicted_terminal_value": -0.021154019656549505,
          "predicted_return": 0.901743273781543,
          "real_return": 0.9
        },
        {
          "actions": [
            0,
            1
          ],
          "predicted_rewards": [
            0.0002548561512478384,
            -0.9991263150146993
          ],
          "predicted_terminal_value": -0.1435152776108406,
          "predicted_return": -1.0152062022267625,
          "real_return": -0.9
        },
        {
          "actions": [
            1,
            0
          ],
          "predicted_rewards": [
            0.09524526583549735,
            -0.9521837169369239
          ],
          "predicted_terminal_value": 0.15604083686918052,
          "predicted_return": -0.635327001543698,
          "real_return": -0.8
        },
        {
          "actions": [
            1,
            1
          ],
          "predicted_rewards": [
            0.09524526583549735,
            0.8130197725912539
          ],
          "predicted_terminal_value": -0.013581173370502464,
          "predicted_return": 0.8159623107375189,
          "real_return": 0.8200000000000001
        }
      ]
    }
  ],
  "weights": {
    "E": [
      [
        0.09295505453914489,
        -0.4342036418486415,
        0.00577446181314749,
        -0.01205691886129273,
        0.35972385840409465,
        -0.2005502627508048,
        0.6810583437075682,
        0.41641822707046283
      ],
      [
        -0.31746158310768297,
        -0.3861085497308248,
        -0.31735398169222084,
        0.22759134758313998,
        -0.6473578127694892,
        -0.43717517245116133,
        -0.37586023503869515,
        -0.2631459996538611
      ],
      [
        -0.05595121080557309,
        0.047492771704115595,
        0.18103535310587093,
        0.06085559545100155,
        0.051016694472414525,
        0.8489375745841187,
        -0.10194722233182385,
        0.11480585560700589
      ],
      [
        0.2554153539422737,
        0.20735422145904375,
        -0.07895492257855619,
        -0.2649026007448664,
        -0.11518988031674438,
        -0.0022938177924376026,
        -0.35098684695543464,
        -0.14576679002919146
      ]
    ],
    "G": [
      [
        [
          -0.04366961653127482,
          0.08269538338397266,
          0.0410500086406309,
          0.07780934366630837,
          -0.19076955733985027,
          -0.02027129039701172,
          0.11884620818356605,
          0.26535843138108506
        ],
        [
          -0.12572201150111142,
          0.46989831926263653,
          0.28113064634997015,
          0.08983738356858671,
          0.1391043733690421,
          0.062313955083370016,
          0.2760045256403647,
          0.377069149991765
        ],
        [
          0.30057556863441154,
          0.06620238865413142,
          0.08247287765452953,
          -0.1429533241552041,
          -0.10067926438323895,
          0.13129868968717961,
          -0.2716698104910928,
          0.11146947436643322
        ],
        [
          0.08563870185195409,
          0.1206851463981271,
          -0.1670299868026177,
          -0.13828455648476692,
          -0.048708472917255795,
          -0.15841069415418538,
          0.3418786459888812,
          -0.11000730921588285
        ],
        [
          0.028184908245286418,
          -0.20162178502949143,
          0.41741149693658713,
          0.3199515533624802,
          -0.030912064790591224,
          -0.48080557294032367,
          -0.086882432643935,
          0.13520673270819777
        ],
        [
          0.37105424285455396,
          -0.1634408829677438,
          0.6892086806807223,
          -0.27535771447032853,
          -0.19645116048054576,
          0.21644347055565338,
          -0.12423637269888194,
          0.5234439918571295
        ],
        [
          -0.11296627836786648,
          -0.3902393610343053,
          -0.021039452553466283,
          -0.06688459867497905,
          -0.49123314788115696,
          -0.09142969000486846,
          0.0180536038688379,
          0.22135908415455238
        ],
        [
          -0.27477833360772086,
          0.04959315404167755,
          0.029396917035314437,
          0.42401165772747146,
          -0.24044554835683035,
          -0.19220100328498074,
          0.011431174229620507,
          0.2037305392554122
        ]
      ],
      [
        [
          0.04967528658586541,
          -0.1233641728741019,
          -0.2266279486232987,
          -0.26374904016627804,
          0.09812848907076516,
          0.15337608345792267,
          -0.03849918244822743,
          -0.17235431320065495
        ],
        [
          0.15478998207684372,
          -0.06810389703017472,
          -0.22444049623651927,
          0.08462526561112099,
          -0.40099424052410937,
          -0.07501392841265675,
          -0.14100475595036985,
          -0.0998940919034044
        ],
        [
          -0.14794621890774987,
          0.041881011489417475,
          -0.14407674268041817,
          -0.05598687808796284,
          0.17771275408269419,
          -0.07952942734958902,
          0.20999240887076556,
          0.13803799017207094
        ],
        [
          0.18856408827231877,
          0.06764409963330423,
          0.10125495095768924,
          -0.28806689266079916,
          -0.053493484793013996,
          -0.06192761604505021,
          -0.2715636044308826,
          0.11073003249799246
        ],
        [
          -0.23626155425368014,
          -0.10615168327995714,
          -0.41704889720900534,
          0.061574061634147366,
          0.12907045858540714,
          0.34605126473257575,
          0.09909533587174736,
          0.08399937549894097
        ],
        [
          0.08725596593066609,
          0.40306526738610965,
          -0.781732925197382,
          0.2516570378614611,
          0.021201913485864525,
          -0.07611473532704856,
          0.09366605994194238,
          -0.17743257235532323
        ],
        [
          0.06148521913205308,
          -0.17168954143821288,
          -0.31622787043525746,
          -0.04511070638097263,
          -0.06642579712582979,
          0.575003982640472,
          0.0659830318446988,
          0.08249137465405729
        ],
        [
          -0.17368862221694853,
          -0.2906584200401595,
          0.036225065199826836,
          -0.24836495157912283,
          0.026068798432996858,
          0.11032750623847623,
          -0.15805543123982116,
          -0.36908469110848885
        ]
      ]
    ],
    "A": [
      [
        0.16775174410819713,
        -0.05218587175456269,
        0.019579165838065994,
        -0.022921845287528535,
        0.15575715602936047,
        -0.18994325000553972,
        -0.19929950527390417,
        -0.3002569612913598
      ],
      [
        0.24233089620273593,
        0.25227222077287886,
        0.05010628376103403,
        -0.00215644260053351,
        0.10478474806481299,
        0.24663522951829306,
        0.11163435209964617,
        -0.05847647646234356
      ]
    ],
    "bg": [
      -0.01745683766925487,
      0.07740791522317722,
      -0.03657181331732759,
      0.012222110551342046,
      -0.28034221231128875,
      -0.006862498909939806,
      -0.22615659523317888,
      -0.03432420282765353
    ],
    "wr": [
      -0.45440212982872963,
      0.35181583943638733,
      -1.2248949296623015,
      0.20303384797899088,
      0.15996493570255066,
      -0.01628535376147625,
      0.3500309314197188,
      -0.3713166298633596
    ],
    "br": [
      0.04919747185512057
    ],
    "Wp": [
      [
        -0.12401726849557512,
        0.14043763089043926
      ],
      [
        -0.239455886370363,
        0.4200192117106884
      ],
      [
        -0.009045937878615521,
        -0.015271490264777835
      ],
      [
        -0.2696067009067857,
        -0.3739647744194986
      ],
      [
        0.04638262325478769,
        0.15868571418237906
      ],
      [
        -0.40124735234561426,
        0.6704151745882071
      ],
      [
        -0.2974505802725323,
        -0.07228570553294061
      ],
      [
        -0.11283412585301925,
        0.13534507046328295
      ]
    ],
    "bp": [
      0.09914908390255088,
      -0.09914908390255091
    ],
    "wv": [
      -0.2824769641048989,
      -0.5897769663815517,
      -0.09469508592064917,
      0.20881260765929568,
      -0.18420772767929927,
      0.08233464375064649,
      0.07299639566043385,
      0.13416155285169107
    ],
    "bv": [
      0.24770639943740452
    ]
  }
}

Tests replace the real environment function with one that raises an error, yet search still executes, verifying use of gg for internal expansion. Real environment calls in the program collect actual experience or provide independent diagnostics. After acting, a fresh real observation is encoded by hh for the next root; the previous tree’s imagined state is not passed off as an observed future.

Seeds 0–7 are retained. Each uses 264 real actions, 3,200 training simulations and 1,056 gradient updates. Final real returns are 0.9, 0.82, 0.9, 0.9, 0.9, 0.9, 0.9 and 0.9. The program prints seed 0 by default; changing the entry call to train(1) reproduces the suboptimal seed.

For seed 1, the best real route returns 0.9 and the alternative 0.82. The model’s two-step predictions are approximately 0.745893 and 0.887080, reversing their ranking. Sixteen root simulations split visits 1 versus 15 and choose the worse route. Every nonterminal state–action pair has at least ten real observations in each run, but nonempty coverage does not guarantee accurate fitting. Finite search does not automatically repair model bias either.

An earlier shared-dynamics-plus-action-bias model had 156 parameters. Its full parameter gradients passed finite differences, yet learning was inadequate; larger training budgets retained erroneous branches. The current action-conditioned matrices give 220 parameters, all checked with maximum finite-difference error approximately 2.80×10−102.80\times10^{-10}. Earlier code, failed seeds and long-budget results were retained rather than deleted for a better curve. The change still does not make every seed optimal and does not reproduce Atari or board-game MuZero results.

One simulation adds at most one latent node, calling gg and ff once for that expansion; existing paths use cached predictions. This program also caps path depth. Beyond root inference, BB simulations add at most BB model expansions, while tree selection still has depth and branching costs. Training time and stored activations grow with unroll length. Simulations, real interactions and gradient updates are separate budgets.

Dropping pixels must not drop relevant distinctions

Suppose two observations are forced into the same latent state while one action produces deterministic rewards +1 and −1 respectively. A reward head restricted to one prediction yy has best equally weighted squared error:

min⁡y(y−1)2+(y+1)22=1,y∗=0.\min_y\frac{(y-1)^2+(y+1)^2}{2}=1,\qquad y^*=0.

Irrelevant background detail may be discarded, but distinctions needed for rewards or future decisions cannot be merged arbitrarily. Omitting reconstruction is an objective choice, not proof that a representation is sufficient. Fitting finite real trajectories also does not guarantee accuracy for every sequence explored by search.

Original v2 dynamics are deterministic. Stochastic environments, hidden information and unstable long predictions need further treatment; this example does not implement every later stochastic MuZero variant. A latent model can assign fictitious high rewards outside its data, and search may pursue them, exploiting the model as in other model-based methods. Original model scope

Value normalization rescales search scores; it is neither a confidence interval nor a model-uncertainty estimate. Our single model has no ensemble or certified error bound. A falling loss, correct gradients and separation from the true-rule interface answer different questions. Together they still do not guarantee an optimal real policy.

Track which step owns the reward

  1. Understanding: A root comes from a real observation. Must expanding its next internal search step call the real environment for a successor observation?

    Answer: No. Function gg maps the current latent state and candidate action to a next latent state and predicted reward, then ff supplies policy and value. The real environment supplies observations after actual actions; model predictions can still be wrong.

  2. Calculation: Two predicted edge rewards are 2 and 3, leaf value is 4 and discount is 0.9. What is full root return? What is omitted by using 6.6 as the first edge’s full return?

    Answer: Root return is 2+0.9(3+0.9×4)=7.942+0.9(3+0.9\times4)=7.94. The 6.6 is continuation after the first step. Using it directly omits the first reward 2 and one factor of 0.9 on continuation.

  3. Boundary: The last real action earns 1 and terminates, but an unroll needs two more steps. May the arriving reward be changed to zero and a uniform terminal policy label invented?

    Answer: Do not erase the last real reward. Terminal future value and later padded rewards are zero; our program skips policy supervision at and beyond termination. A uniform policy was not observed at that actionless terminal state.

  4. Transfer: Two observations give +1 and −1 for the same action but share one forced latent representation. Can more search make a deterministic reward head predict both correctly?

    Answer: No. The common optimum under equally weighted squared loss is zero, with error 1. Retain relevant information, change representation or model uncertainty appropriately. Repeated search through contradictory predictions cannot restore a discarded distinction.

Version both equations and ancillary code

We read MuZero arXiv v2 (2020-02-21; first submission 2019-11-19), PDF pages 2–4 and 12–13 plus first-page identity, visually inspecting page 12. The Nature page was inaccessible, so the cached preprint is not labeled as verified final publisher bytes. This scope supports the h/g/f, joint-unroll and search-interface discussion, not a complete appendix audit or benchmark replication. Versioned paper

Ancillary pseudocode.py is also pinned to v2. Reading covered specified sections on targets, search, backup and training. Environment, player and scalar-loss interfaces contain placeholders; this is not a complete executable training library. Public access was not taken as permission for unrestricted copying. We did not execute or copy it; the numerical program is original teaching code. Ancillary pseudocode

The AlphaZero accepted manuscript provides the known-rule comparison, not independent replication of MuZero experiments. Rule comparison Continue to model-based RL and world models to compare prediction objectives, real-data coverage and planning error.

Make a prediction, then check

Where does the next latent state come from when MuZero expands a search branch?

Choose one answer

Learning objectives

  • Train h/g/f jointly and separate real sampling from search entirely within the latent model.
  • Check incoming rewards, continuation values, absorbing targets and model error; explain why avoiding pixel reconstruction does not make a model correct.

Prerequisites & connections

Explore related knowledge →

References

  1. Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model — arXiv v2
    Julian Schrittwieser; Ioannis Antonoglou; Thomas Hubert; Karen Simonyan; Laurent Sifre; Simon Schmitt; Arthur Guez; Edward Lockhart; Demis Hassabis; Thore Graepel; Timothy Lillicrap; David Silver · 2020
  2. MuZero arXiv v2 ancillary pseudocode — scoped interface reading
    Julian Schrittwieser and coauthors · 2020
  3. A general reinforcement learning algorithm that masters chess, shogi, and Go through self-play — accepted manuscript
    David Silver; Thomas Hubert; Julian Schrittwieser; Ioannis Antonoglou; Matthew Lai; Arthur Guez; Marc Lanctot; Laurent Sifre; Dharshan Kumaran; Thore Graepel; Timothy Lillicrap; Karen Simonyan; Demis Hassabis · 2018

Version1 · Editorial status: Recorded technical checks completed

View technical check record (AI)

Codex · 2026-09-23 · Single AI author. Scoped reading: First2019-11-19; selected v2 dated2020-02-21, not verified Nature final bytes. Read PDF2–4/12–13 and first-page identity, viewed12: h/g/f, joint unroll, reward/continuation and normalization interfaces. No full appendix or benchmark audit. Fixed v2 ancillary pseudocode; read1–40/173–235/273–307/419–540/563–610. Root legality, latent search, incoming reward/node continuation, absorbing targets and gradient scaling; placeholders make it incomplete runnable code. Reference only, no copying/execution or inferred reuse license. UCL identifies an accepted manuscript, not publisher layout. Read PDF2/3/16–19 and first-page identity/abstract, viewed17: rule knowledge, PUCT, targets, noise/evaluation and differences from AlphaGo Zero. Error cancellation is author speculation; no full match-table audit or playing-strength replication. 8 paired equations and four explained exercises. Representation, action-conditioned dynamics, reward/policy/value heads and220 parameter derivatives checked. Search cannot access the real environment; terminal-arrival reward and absorbing padding remain distinct. Eight runs retain one suboptimal seed despite coverage and correct gradients. Full-edge normalization, Monte Carlo targets and ordinary BPTT are explicit teaching differences from v2 ancillary pseudocode.

  • Representation, action-conditioned dynamics, reward/policy/value heads and220 parameter derivatives checked. Search cannot access the real environment; terminal-arrival reward and absorbing padding remain distinct. Eight runs retain one suboptimal seed despite coverage and correct gradients. Full-edge normalization, Monte Carlo targets and ordinary BPTT are explicit teaching differences from v2 ancillary pseudocode.
  • Four computed SVG variants per topic;9 numeric/geometry tests and18 current responsive cases passed. All nine selected current captures directly viewed; separated visit counts and signed values correct the retained initial color-scale failure. Actual assets and manuscripts are SHA bound. Full article acceptance recorded separately.

Source locations checked:

Related topics

No matches. Try a synonym or acronym.

0 results shown

Wrap the whole query in double quotes for a phrase match.