MuZero:在学得的潜状态里规划
MuZero
追踪表示、动力学与预测三个接口,检查奖励下标、多步训练及模型导致的错误路线。
muzero规划一定要先画出下一张画面吗?
设想一个原创的两步小游戏。第一步选路线,第二步选收尾动作;最好的两条完整路线分别给出折扣回报 0.9 和 0.82。要判断先走哪条,模型也许只需保留“之后还能拿到多少奖励、哪些动作值得试”等信息,不必重建一张完整画面。
MuZero 把这个想法用于模型式强化学习:从真实观察建立内部表示,在该表示中预测动作后的变化,再预测奖励、价值和策略。搜索使用这个学得的模型。原论文没有要求潜状态等于真实状态,也没有像素重构损失;这不等于已经证明模型足够准确,或任意压缩都能保留正确决策。预测与规划的目标
它与 AlphaZero 的关键接口差别是内部展开:AlphaZero 可以调用已知规则得到准确后继局面,MuZero 使用学得的动力学。真实环境仍负责产生训练经验和实际奖励。在棋类伪代码中,根还接收当前合法动作;“不调用真实动力学模拟器做内部搜索”不能扩写成完全没有任务接口。AlphaZero 的规则 MuZero 的根与内部接口
三个函数,两个时间坐标
用 表示真实时间, 表示从当前根往前想象了几步。真实观察为 ,真实奖励为 ,潜状态为 ;真实动作 使环境到达下一观察并产生 。三个可学习函数为:
是表示函数, 是动力学函数, 是预测函数。 预测刚刚完成第 个动作的奖励, 预测此后还会得到的回报;两者不能把同一份即时奖励重复计算。策略 为潜状态中的下一动作提供先验。真实观察可能需要历史;本教学任务的离散观察本身是马尔可夫状态,所以 只读当前观察。三个函数与下标
本篇统一把搜索边的 定义为包含这条边即时奖励的完整回报均值。若一条模拟走到深度 ,叶值为 ,反向递推为:
然后将该边次数加一。两条边奖励为 2、3,折扣 0.9、叶值 4 时,根回报是 。如果误把第二个节点的续值 6.6 直接存成第一条边的完整回报,就漏了奖励与折扣。
另一种实现可以分别保存节点续值和入边奖励,选择时再组合。MuZero v2 随文伪代码就有这两个字段。本文采用完整边回报,是为了让每个统计量只有一个解释;读原文的边记号与伪代码的节点字段时必须跟踪下标,不能只看到都叫 value 就直接替换。本程序是单智能体,不使用双人零和的逐层取负号。伪代码的选择与回传
训练价值的目标来自真实轨迹。长任务可以用 步奖励加上未来搜索根值 :
它不是把模型自己想象的奖励当成真实标签。遇到真实终止后没有未来续值;本例只有两步,直接使用完整真实回合的 Monte Carlo 回报,不使用这个未来自举项。策略目标是对应真实位置搜索得到的访问分布 ,奖励目标是实际观察到的 。多步目标
训练从回放里选一个真实观察,把随后真实执行的动作输入模型,连续展开 步。本文程序的损失明确采用以下归一方式,其中 指示该位置是否还需要策略监督:
每一项都要解释位置:根有策略/价值监督,但没有新执行的想象动作,所以本程序不另拟合根的“上一步奖励”;第一个奖励预测对应第一个展开动作。原 v2 伪代码为简化接口,也让 initial inference 预测已知的最近奖励,这与本文的接口不同。论文还按任务采用不同的标量损失与训练细节;上式是本篇小实现的明确选择,不是所有 MuZero 版本通用的唯一损失。联合训练与简化接口 目标构造
搜索需要比较价值与先验。为处理数值范围,本文对完整边回报归一,然后加先验探索项:
程序以零初始化范围,随后扩大到搜索中见过的边均值;固定 、每次根搜索重置统计。这里归一的是完整的 。v2 伪代码中的表达式则为 ,这两个式子不能字面互换。例如范围 0 到 10、 时,两种计算分别是 0.56 与 2.36。此处明确教学约定,不把约定差异写成已经独立验证的论文勘误。搜索统计与归一化 v2 的实际表达式
表示和动力学必须收到未来预测误差,而不只是拟合当前头部。在本程序中,奖励也由当前展开潜状态预测;把各头部的局部损失记为 ,动力学的状态分量记为 ,反向传播包含:
未来状态的误差沿展开链回到根表示,这是联合训练的含义。原伪代码还用 scale_gradient 调整后向倍率而保持前向数值不变;不能把它误写成前向隐藏状态直接乘 0.5。本程序使用普通完整 BPTT、明确的损失平均与梯度范数裁剪,未实现原文全部工程技巧。后向缩放的接口
模型真正在学,而不是偷偷调用规则
程序使用 Python 3.12 以上与 NumPy;实际环境为 Python 3.12.4、NumPy 1.26.4。四种观察编号为 0、1、2、3,最后一个是真实终止。状态 0 的动作 0 给奖励 0 并到 1;动作 1 给 0.1 并到 2。在状态 1,两动作分别给 1、−1;在状态 2,分别给 −1、0.8,随后都终止。折扣 0.9,所以四种完整动作序列回报依次为 0.9、−0.9、−0.8、0.82。
学一个八维观察嵌入; 按动作选一套可学习仿射变换,经 tanh 得下一潜状态,再预测奖励; 输出两动作 softmax 与线性价值。总共 220 参数,都由多步损失更新。没有真实后继状态重构损失,也没有要求 等于下一真实观察的嵌入。
每次训练先用 32 个随机动作回合收集经验,再用 100 个模型搜索回合继续学习。预热的策略标签是均匀行为分布,后面的标签才来自搜索;这是明确的教学预热安排。每回合两个真实动作,每动作训练搜索 16 次,树深上限 3;每回合进行 8 次 batch8 梯度更新,展开 3 步,学习率 0.05、L2 系数 、梯度范数上限 5。数据、规划与批次随机流分开,评价另用固定种子。
回合结束后,训练序列可以用吸收目标补齐,但不能抹掉最后一步的真实奖励。设真实终止发生在观察 ,则:
到达终点的奖励 仍要预测;之后的奖励与未来价值为零,策略监督跳过。吸收补齐不算新增真实交互。内部潜树没有调用真实终止判定,而是依赖吸收训练与有限深度,模型仍可能预测错误的终点续值。
"""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))
查看完整运行结果
{
"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
]
}
}测试把真实 environment 函数替换为抛错函数后,search 仍能执行,核实内部展开使用的是 。程序中的真实环境调用只用于采集真实经验和独立诊断。实际行动后会拿到新的真实观察,再用 建立下一次根,不沿着上一棵树的想象状态假装已经观察到未来。
保存了种子 0—7。每个种子有 264 次真实动作、3,200 次训练模拟和 1,056 次梯度更新。最终真实回报依次为 0.9、0.82、0.9、0.9、0.9、0.9、0.9、0.9。正文默认输出种子 0;把入口改为 train(1) 可以复查次优种子。
种子 1 中,最优真实路线给 0.9,另一条给 0.82;模型对它们的两步预测约为 0.745893、0.887080,排反了。根 16 次搜索把访问分成 1 与 15,最终走次优路线。各次运行每个非终止状态动作对至少被真实观察 10 次,但覆盖不为空并不能保证拟合准确;有限搜索也不会自动修正模型偏差。
初版共享动力学加动作偏置只有 156 参数,已通过全参数梯度差分,却学习不足;增加训练预算也保留了错误分支。当前版本改为动作条件矩阵,共 220 参数,全部梯度差分最大误差约 。早期程序、失败种子与长预算结果保留,未为了漂亮曲线删除。这个小改动也没有使所有种子最优,更不能宣称复现了 MuZero 在 Atari 或棋类上的成绩。
一次模拟至多增加一个潜节点,展开调用一次 和一次 ;已有路径使用缓存预测。本程序还限制每条路径深度,除根推理外, 次模拟的新增模型计算至多 次,但树内选择仍有深度与分支成本。训练 BPTT 的时间和保存激活量随展开长度增长;模拟预算、真实交互和梯度更新是三种不同成本。
不重构像素,仍要保留决策需要的区别
假设两个观察被强制映射成同一个潜状态,同一动作在其中分别产生确定奖励 +1、−1。若奖励头只能给出一个预测 ,等权均方误差的最佳结果是:
因此可以丢掉不影响目标的背景细节,却不能随意合并奖励或未来决策所需的差别。没有重构要求是一种目标选择,不是表示天然充分的证明。只在有限真实轨迹上拟合,也不能保证所有被搜索访问的动作序列都准确。
原 v2 的动力学表示是确定性的;随机环境、隐藏信息以及不稳定的长期预测需要额外讨论,不能由本例推广成全部后续随机 MuZero 变体已经实现。潜模型可能在数据外给出虚假的高奖励,搜索会主动追逐这些预测,形成类似其他模型式方法的模型利用问题。原版模型范围
值归一化只改变搜索分数的尺度,不是置信区间或模型不确定性估计。本例的单一模型没有集成,也没有误差证书。训练曲线下降、梯度正确和规则接口隔离各自回答不同问题;它们合起来仍不保证真实策略最优。
先追踪奖励属于哪一步
-
理解: 根由真实观察产生,内部搜索展开下一步时是否还需要调用真实环境拿后继观察?
答案: 不需要; 从当前潜状态与候选动作产生下一潜状态和奖励预测, 再给策略与价值。真实环境在实际行动时提供新观察,模型预测仍可能错误。
-
手算: 两条预测边奖励为 2、3,叶值 4、折扣 0.9。根完整回报是多少?如果直接把 6.6 当第一边的完整回报,少算了什么?
答案: 根是 。6.6 是第一步之后的续值,直接使用会漏掉第一步奖励 2,也漏掉对续值施加一次 0.9 折扣。
-
边界: 最后一个真实动作得 1 分并终止,展开序列还缺两步。能否把到达终点的奖励也改为零,并给终点生成一个均匀策略标签?
答案: 不能抹掉真实最后奖励。终点未来价值为零,之后补齐的奖励为零;本程序跳过终点及之后的策略监督。均匀策略不是从该无动作终止状态观测到的真实标签。
-
迁移: 两个观察对同一动作的奖励是 +1、−1,却被合并成同一潜状态。增加搜索次数能让一个确定奖励头同时预测对吗?
答案: 不能。等权平方损失的共同最优预测是 0,仍有误差 1。需要保留相关信息、改变表示或适当建模不确定性;重复搜索同一个矛盾预测不会补回已丢失的区别。
论文公式和随文伪代码都要注明版本
本篇核读 MuZero arXiv v2(2020-02-21;初稿为 2019-11-19)的 PDF 第 2—4、12—13 页及首页身份,实际查看第 12 页。Nature 页面访问受阻,因此没有把该缓存写成核过的 Nature 最终排版字节。原文支持 、联合展开与搜索接口的说明,未完成全部附录或基准复现。固定版本论文
随文 pseudocode.py 同样固定为 v2,实际核读目标构造、搜索、回传与训练等指定段。它含环境、玩家、标量损失等占位,不能当成可直接运行的完整训练库;公开可访问也没有被当成任意复制的许可。本项目没有执行或复制它,数值程序为原创教学实现。随文伪代码
AlphaZero 的接受稿用于对照已知规则搜索,并非 MuZero 实验的独立复现证据。规则对照 继续读 基于模型的强化学习 与 世界模型,可进一步比较模型预测目标、真实数据覆盖和规划误差。
先判断,再看解释
MuZero内部展开一个新搜索分支时,下一潜状态来自哪里?
学习目标
- 实现h/g/f联合训练,区分真实采样与完全在潜模型内的搜索。
- 核对入边奖励、续值、吸收目标和模型误差,解释不重构像素不等于模型正确。
先修与延伸
查看知识关联图 →参考文献
- 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 - MuZero arXiv v2 ancillary pseudocode — scoped interface reading
Julian Schrittwieser and coauthors · 2020 - 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
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(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.
- 核表示、动作条件动力学、reward/policy/value头与220参数导数;搜索不访问真实环境,保留到终点reward及吸收padding区别。八种子有一次次优,覆盖与梯度正确不等于最优。完整边归一、MC目标、普通BPTT与v2随文伪代码的教学差异明确。
- 每题四张计算SVG,9数值/几何与18个当前响应式组合通过;九张当前选定图均直接实看,访问数与有符号价值分开后修正保留的初次色标错误,资产与稿件SHA绑定,完整页面验收另记。
核对的来源位置:
- Mastering Atari, Go, Chess and Shogi by Planning with a Learned Model — arXiv v2 · 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.
- MuZero arXiv v2 ancillary pseudocode — scoped interface reading · 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.
- A general reinforcement learning algorithm that masters chess, shogi, and Go through self-play — accepted manuscript · 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.
相关主题