离线强化学习:旧日志能教会一个新策略吗?
Offline reinforcement learning
固定同一批数据,比较拟合Q、支持动作限制与保守正则,检查没见过的动作如何改变决策。
offline-rl日志记录了发生的事,不是所有可选的事
本篇原创教学任务只有两次决策。入口动作 0 直接退出,得到 0.4 分;动作 1 继续,暂时没有奖励。第二处决策中,动作 0 得 1 分,动作 1 得 −2 分,然后回合结束。折扣为 0.9 时,继续后选动作 0 的价值是 0.9。只复制入口处最常见的动作,却可能只得到 0.4。
假设旧策略经常退出,很少尝试第二处的动作 1。它的日志可能已有足够的片段,让学习器拼出更好的路线;也可能留下一个完全没有测过、看起来却很诱人的动作。对这个动作预测出较大的 Q 值,不等于观察过它成功。
离线强化学习从已经收集好的数据学习,训练时不增加环境交互。“离线”不是说计算机没有联网。普通离策略学习可以一边复用旧转移、一边继续收集新经验;固定离线数据却不能靠试一次建议动作,来纠正错误预测。问题定义与分布变化
Bellman目标可能问到了数据里没有的动作
记日志转移集合为 ,产生它们的行为策略为 。要学到的策略仍然应优化实际环境中的期望回报:
标记真正终止,不是人为时间限制。比日志更好的策略不必复制原来的动作频率,却也会带来不同的状态、动作分布。这里假设记录的状态足以描述这个有限马尔可夫任务,环境规律保持不变;仅靠数一数数据行,不能证明这两个假设。
拟合 Q 迭代先用上一轮 Q 函数构造目标,再在已经记录的状态—动作对上拟合。采用贪心备份时:
近似号允许数值优化没有完全收敛。损失只约束日志中的动作,最大值却会查询某个已记录后继状态下的所有候选动作。因此,一个没有数据支持的大值,可以进入更早、经常被观察到的转移目标。在零覆盖实验中,未见过的第二阶段动作一直保留初值 2,错误路线便显得有吸引力。这个机制比笼统说“网络过拟合了”更具体。未知动作的备份问题
一种办法是限制策略只选有支持的动作;另一种办法是改变价值拟合。离散 CQL(H) 目标在原损失上增加“动作软最大值”与“数据动作 Q 值”的对比:
这个式子使用有限离散动作集,并声明温度为 1。连续动作需要另行处理动作积分;参考代码会采样动作并修正密度。它的 Atari 实现在 QR-DQN 上增加离散正则,而本例只使用标量表。CQL 式 4 固定实现
令 、, 为已观测状态—动作对的固定目标均值。对表格目标求导得到:
这个写法只用于 的状态;若 ,应省略数据残差项,不要先计算一个不存在的均值。未见动作若占较大 softmax 份额,正则会给它正梯度,梯度下降因而降低该值。数据中的动作则可能相对其他动作被抬高。这个正则不是经过校准的不确定性区间。
对任意标量 ,把同一状态的所有动作值一起平移,其正则不变:
Bellman 损失才提供价值的定位依据。对于完全未见动作,反复惩罚可以继续降低那一格,却没有拟合任何该动作的已观测奖励;有限次更新后的数值不是其真实奖励的后验估计。
读到“下界”,要一起读条件。 CQL 论文区分了一个目标的逐点结果,与另一个目标更紧的策略平均结果;分析依赖目标分布、覆盖、估计误差与正则条件。有限次最大值备份优化之后再贪心推荐,不会自动继承普遍下界证书。下面默认运行中,alpha 为 1 的控制器预测最大值约为 0.61343,真实回报却是 0.4。这提醒我们不要把另一组条件下的定理套在本实现上,并不是推翻论文。CQL 第 3.1 节
更简单的对照法,是同时把备份和最终推荐限制在已观察动作上:
若备份需要的非终止后继状态没有任何受支持动作,程序明确报错。这个简单支持集只要求出现过一次;在有噪声的问题中,一次观察不够建立统计信心。限制也可能把一个真的很好、却从未记录的动作排除掉。
先固定数据,再拟合任何策略
行为策略在入口继续的概率为 0.3;第二处选择动作 1 的概率是参数 rare。每次实验收集 64 个完整回合,随后冻结数据。对照包括 alpha 为 0、0.1、1 的三个标量表拟合,一个限制支持动作的拟合,以及在每个状态选择最高频动作的行为克隆基线。
每个 alpha 都进行 24 轮外层目标重算;每轮以学习率 0.2 做 80 次全批梯度更新,期间保持目标不变。两个非终止 Q 行都从 2 开始,终止行固定为零。这意味着 1,920 次梯度更新,每次读取全部 条转移,另有 次目标条目计算。输出中的目标计数没有包括所有梯度工作。支持集方法做四轮“算目标、求均值”,克隆只统计动作频率;拟合过程都不收集新的真实转移。
状态数为 、动作数为 、外层轮数为 、内层步数为 时,表格全批工作量约为 ,存储为 。这是教学计算量,不是大型神经实现的耗时结论。real_value 只在拟合之后用已知模拟器作独立评价。
下面的 Python、NumPy 程序可以完整运行。实现为原创,没有执行上游训练代码。
"""Original fixed-data tabular FQI/CQL(H) teaching example; NumPy only.
No new interactions during fitting; not the paper's QR-DQN or SAC experiments.
"""
import json
import numpy as np
GAMMA = .9
def positive_int(n):
if isinstance(n, bool) or not isinstance(n, (int, np.integer)) or n < 1:
raise ValueError('Expected a positive integer')
return int(n)
def step(state, action, unknown_reward=-2.):
if state not in (0, 1) or action not in (0, 1): raise ValueError('Invalid nonterminal decision')
if state == 0: return (2, .4, True) if action == 0 else (1, 0., False)
return 2, (1. if action == 0 else float(unknown_reward)), True
def collect(seed, episodes=64, rare=.05):
if not np.isfinite(rare) or not 0 <= rare <= 1: raise ValueError('Invalid probability')
rng = np.random.default_rng(seed); rows=[]
for _ in range(positive_int(episodes)):
state=0
while state != 2:
probability = .3 if state == 0 else rare
action = int(rng.random() < probability)
nxt,reward,done = step(state,action)
rows.append((state,action,reward,nxt,done));state=nxt
return np.asarray(rows,dtype=float)
def validate(data):
d=np.asarray(data,dtype=float)
if d.ndim != 2 or d.shape[1] != 5 or len(d) == 0 or not np.isfinite(d).all():
raise ValueError('Nonempty finite transition table required')
if not np.isin(d[:,0],[0,1]).all() or not np.isin(d[:,1],[0,1]).all() or not np.isin(d[:,3],[1,2]).all():
raise ValueError('Invalid states or actions')
if not np.isin(d[:,4],[0,1]).all() or not np.array_equal(d[:,4] == 1,d[:,3] == 2):
raise ValueError('Explicit true terminal mask required')
expected=np.where((d[:,0]==0)&(d[:,1]==1),1,2)
if not np.array_equal(d[:,3],expected):raise ValueError('Transition violates the two-stage task')
return d
def statistics(data):
d=validate(data);counts=np.zeros((2,2),dtype=int)
np.add.at(counts,(d[:,0].astype(int),d[:,1].astype(int)),1)
return counts
def targets(data, q, supported=False):
d=validate(data);nxt=d[:,3].astype(int);done=d[:,4].astype(bool)
values=q.max(1).copy()
if supported:
counts=statistics(d)
for state in (0,1):
mask=counts[state]>0
if np.any((nxt==state)&~done) and not mask.any():
raise ValueError('No supported successor action for this backup')
values[state]=float(q[state,mask].max()) if mask.any() else 0.
values[2]=0.
return d[:,2]+GAMMA*np.where(done,0.,values[nxt])
def loss_gradient(q, data, target, alpha):
d=validate(data);target=np.asarray(target,dtype=float)
if q.shape != (3,2) or target.shape != (len(d),) or not np.isfinite(q).all() or not np.isfinite(target).all():
raise ValueError('Finite table and target required')
if not np.isfinite(alpha) or alpha<0: raise ValueError('Nonnegative alpha required')
counts=statistics(d);frequency=counts/len(d);state_frequency=frequency.sum(1)
s,a=d[:,0].astype(int),d[:,1].astype(int);residual=q[s,a]-target
gradient=np.zeros_like(q);np.add.at(gradient,(s,a),residual/len(d))
maximum=q[:2].max(1,keepdims=True);e=np.exp(q[:2]-maximum);prob=e/e.sum(1,keepdims=True)
logsum=maximum[:,0]+np.log(e.sum(1))
penalty=float(state_frequency@logsum-np.sum(frequency*q[:2]))
gradient[:2]+=alpha*(state_frequency[:,None]*prob-frequency)
return float(.5*np.mean(residual**2)+alpha*penalty),gradient
def fit(data, alpha=0., outer=24, inner=80, learning_rate=.2, initial=2.):
d=validate(data)
if not np.isfinite(learning_rate) or learning_rate<=0 or not np.isfinite(initial): raise ValueError('Invalid optimizer')
q=np.full((3,2),float(initial));q[2]=0.
for _ in range(positive_int(outer)):
y=targets(d,q) # Fixed target throughout the inner optimization.
for _ in range(positive_int(inner)):
_,gradient=loss_gradient(q,d,y,alpha);q-=learning_rate*gradient
return q
def supported_fqi(data, rounds=4):
d=validate(data);counts=statistics(d);q=np.zeros((3,2))
for _ in range(positive_int(rounds)):
y=targets(d,q,supported=True)
for state in (0,1):
for action in (0,1):
mask=(d[:,0]==state)&(d[:,1]==action)
if mask.any():q[state,action]=y[mask].mean()
policy=[]
for state in (0,1):
mask=counts[state]>0
policy.append(int(np.argmax(np.where(mask,q[state],-np.inf))) if mask.any() else None)
return q,policy
def real_value(policy, unknown_reward=-2.):
state=0;value=0.;discount=1.
while state!=2:
action=policy[state]
if action is None:raise ValueError('Policy abstains at a reached state')
state,reward,_=step(state,action,unknown_reward);value+=discount*reward;discount*=GAMMA
return value
def experiment(seed=0, rare=.05):
d=collect(seed,rare=rare);counts=statistics(d);methods=[]
for alpha in (0.,.1,1.):
q=fit(d,alpha);policy=q[:2].argmax(1).tolist()
methods.append(dict(method='fqi' if alpha==0 else 'cql',alpha=alpha,q=q[:2].tolist(),
policy=policy,predicted_start=float(q[0].max()),real_return=real_value(policy),
gradient_steps=24*80,transition_targets=24*len(d)))
q,policy=supported_fqi(d)
methods.append(dict(method='supported',q=q[:2].tolist(),policy=policy,real_return=real_value(policy)))
policy=counts.argmax(1).tolist()
methods.append(dict(method='behavior-cloning',policy=policy,real_return=real_value(policy)))
return dict(seed=seed,rare_probability=rare,episodes=64,real_transitions=len(d),counts=counts.tolist(),
methods=methods,optimal_real_return=max(real_value([a,b]) for a in (0,1) for b in (0,1)))
if __name__=='__main__':
print(json.dumps(experiment(),indent=2))
查看运行摘要
{
"seed": 0,
"rare_probability": 0.05,
"episodes": 64,
"real_transitions": 82,
"counts": [
[
46,
18
],
[
17,
1
]
],
"methods": [
{
"method": "fqi",
"alpha": 0.0,
"q": [
[
0.40000000000000024,
0.9000000000000037
],
[
1.0000000000000027,
-1.9632035040665075
]
],
"policy": [
1,
0
],
"predicted_start": 0.9000000000000037,
"real_return": 0.9,
"gradient_steps": 1920,
"transition_targets": 1968
},
{
"method": "cql",
"alpha": 0.1,
"q": [
[
0.44243618011938973,
0.7909615945150398
],
[
0.9993172095153531,
-1.9655070222322186
]
],
"policy": [
1,
0
],
"predicted_start": 0.7909615945150398,
"real_return": 0.9,
"gradient_steps": 1920,
"transition_targets": 1968
},
{
"method": "cql",
"alpha": 1.0,
"q": [
[
0.61342500592268,
0.350517920816353
],
[
0.99547638199504,
-1.9223159592142167
]
],
"policy": [
0,
0
],
"predicted_start": 0.61342500592268,
"real_return": 0.4,
"gradient_steps": 1920,
"transition_targets": 1968
},
{
"method": "supported",
"q": [
[
0.3999999999999998,
0.8999999999999999
],
[
1.0,
-2.0
]
],
"policy": [
1,
0
],
"real_return": 0.9
},
{
"method": "behavior-cloning",
"policy": [
0,
0
],
"real_return": 0.4
}
],
"optimal_real_return": 0.9
}每种覆盖条件都保留八个种子。下表是得到的确定性策略在教学环境中的精确真实值,不是各自 Q 表给出的估计。
| 罕见动作概率 | 种子 | 普通拟合,alpha 0 | CQL alpha 0.1 | CQL alpha 1 | 支持集拟合 | 克隆 |
|---|---|---|---|---|---|---|
| 0 | 0—7 | 全部−1.8 | 全部0.9 | 全部0.4 | 全部0.9 | 全部0.4 |
| 0.05 | 0—7 | 六次0.9;种子4、6为−1.8 | 全部0.9 | 全部0.4 | 全部0.9 | 全部0.4 |
| 0.5 | 0—7 | 全部0.9 | 全部0.9 | 全部0.4 | 全部0.9 | 全部0.4 |
概率为 0.05 时,八个种子的罕见动作计数依次是 1、1、1、1、0、2、0、2。默认种子 0 有 82 条真实转移,入口动作计数为 46/18,第二处为 17/1。普通拟合此时已经成功,因为它见过有害动作;alpha 为 1 的惩罚反而选择了频繁退出,放弃数据支持的 0.9 路线。更保守不自动等于更有用。
零覆盖时,不必讨论优化器也能看出问题。构造第二个环境,在所有有记录的状态—动作对上与原环境相同,只把未见奖励从 −2 改为 +2。同一个行为策略会在两个世界产生完全相同的数据,而它们的最优回报分别是 0.9 和 1.8。任何方法都不能只凭这份日志识别身处哪个世界;偏好受支持路线,是明确的保守选择。
覆盖不是文件大就有了
本例奖励确定、状态身份精确、图很短且已知,没有隐藏状态、学得的表示或数据污染。更大问题里的奖励噪声、状态信息不全和分布变化,都可能破坏这个表格中看起来清楚的判断。
离线强化学习不等于克隆,但要超过克隆,需要证据支持有用的偏离,数据总量本身说明不了这一点。即使留出 Bellman 损失很小,策略仍可能利用训练和验证两边都缺少的动作值。奖励尺度变化,也会改变平方拟合项与固定保守系数的相对作用。
最后,反复查看真实模拟器回报来选择 alpha,利用了严格离线实践者未必拥有的信息。本例公开比较事先列明的固定系数,是教学实验;实际策略选择需要明确的验证流程,以及有自身覆盖、不确定性限制的离策略评估。固定 CQL 仓库也提示了数据集版本变化与参数差异,旧 README 的分数不是当前基准保证。版本化实现说明
缺的那一行能告诉你什么?
-
某状态的全部记录都使用动作 0,终止奖励为 1。两个 Q 值初始都为零。alpha 为 1 时,两个梯度是什么?学习率 0.2 更新一步后呢?
答案: 数据残差对动作 0 贡献 −1,对动作 1 为零;softmax 项分别贡献 −0.5、+0.5,总梯度为 −1.5、+0.5。更新后得到 0.3、−0.1。降低未见动作的值,没有揭示它的真实奖励。
-
为什么本任务中支持集拟合能得 0.9,行为克隆却得 0.4?
答案: 克隆在入口选更频繁的退出。日志中也记录了继续、随后选择有奖励的第二阶段动作;支持集备份能把这些观察片段连成 0.9 路线,不必复制原有频率。
-
零覆盖日志既兼容未见奖励为 −2,也兼容它为 +2。不增加实验,怎样说明不能保证在两个世界都选中真实最优动作?
答案: 算法在两个世界收到相同数据,数据就无法决定哪个未见结果成立,而两边最优路线不同。在同一日志上多做梯度更新不能移除这种不确定性,需要新证据或额外假设。
-
alpha 为 1 的默认运行预测约 0.61343,贪心控制器却只得 0.4。这推翻了 CQL 定理吗?该怎样计算这次训练成本?
答案: 没有。本有限最大值备份、CQL(H)、贪心实现,不是满足所引下界全部条件的固定策略估计器。这个 alpha 的拟合用了 1,920 次全批梯度更新和 个目标条目,没有新增真实交互。其他系数和基线另有计算成本,评价也要分开记。
把数据、优化器和结论分开
所选教程解释了“复用数据”和“禁止新采样”为何是不同设置。CQL 提供的是一族保守目标,不是无条件承诺;固定源码也区分了离散 QR-DQN 与连续 SAC 路线。教程 CQL 论文 固定代码
对照Q-learning和经验回放理解在线学习背景,再读世界模型了解另一种使用学得预测的方法。保守价值拟合或逼真的模型,都不会让固定日志中没有支持的动作自动变得可识别。
先判断,再看解释
给离线Q学习加入更强的保守惩罚,真实策略回报一定更高吗?
学习目标
- 在不增加真实交互的前提下完成固定数据拟合,解释未知动作的值怎样进入Bellman目标。
- 计算离散CQL目标与梯度,区分经验效果、覆盖条件及条件性价值下界。
先修与延伸
查看知识关联图 →参考文献
- Offline Reinforcement Learning: Tutorial, Review, and Perspectives on Open Problems — arXiv v3
Sergey Levine; Aviral Kumar; George Tucker; Justin Fu · 2020 - Conservative Q-Learning for Offline Reinforcement Learning — scoped conference paper
Aviral Kumar; Aurick Zhou; George Tucker; Sergey Levine · 2020 - CQL author implementation — fixed discrete and continuous method reading
Aviral Kumar; CQL contributors · 2020
版本1 · 编写状态: 已完成记录中的技术复核
查看技术检查记录(AI)
Codex · 2026-09-23 · Single AI author. Scoped reading: Selected v3 dated2020-11-01, first submitted2020-05-04. Read pages7/9/10/18/19 of43 and650 identity characters on page1. Fixed data, distribution shifts, IS/WIS and unseen-action backups; neither the2020 sufficiency footnote nor unverified original imitation bounds are current universal conclusions. Not a full-paper audit. Official13-page NeurIPS33 PDF; read3–4 and650 identity characters on page1, viewed4. Pointwise versus policy-average bounds, sampling/coverage/alpha conditions and discrete CQL(H) Equation4. No full appendix-proof or benchmark audit; finite teaching optimization is not certified by those theorems. Fixed2020-09-14 commit; full54-line README, discrete141–174/219–243, continuous cql.py194–282. QR-DQN regularization differs from continuous sampling corrections; data Q mean is not the comment’s log likelihood. README notes D4RL/version changes. Atari Apache identity only; all21 D4RL MIT lines read. No copying/execution. 6 paired equations and four explained exercises. Fixed targets, terminal masks, full tabular CQL(H) gradients, regularizer shift invariance and supported backups independently checked.24 seed/coverage settings retain ordinary-fit failures, stronger-penalty opportunity cost and predicted/real value differences. Two indistinguishable logged worlds have different optimal values. No new interaction in fitting or unconditional lower-bound claim.
- 独立核固定targets、真终止、表格CQL(H)完整梯度、正则平移不变与支持集备份;24种子/覆盖设置保留普通拟合失败、强惩罚机会成本及预测/真实差距。两世界同日志但最优不同,拟合不增加交互,不作无条件下界承诺。
- 每题四张计算SVG,9数值/几何与12个当前响应式组合通过;六张当前选定图均直接实看,本组没有图形失败或捕获后资产修改,资产与稿件SHA绑定,完整页面验收另记。
核对的来源位置:
- Offline Reinforcement Learning: Tutorial, Review, and Perspectives on Open Problems — arXiv v3 · Selected v3 dated2020-11-01, first submitted2020-05-04. Read pages7/9/10/18/19 of43 and650 identity characters on page1. Fixed data, distribution shifts, IS/WIS and unseen-action backups; neither the2020 sufficiency footnote nor unverified original imitation bounds are current universal conclusions. Not a full-paper audit.
- Conservative Q-Learning for Offline Reinforcement Learning — scoped conference paper · Official13-page NeurIPS33 PDF; read3–4 and650 identity characters on page1, viewed4. Pointwise versus policy-average bounds, sampling/coverage/alpha conditions and discrete CQL(H) Equation4. No full appendix-proof or benchmark audit; finite teaching optimization is not certified by those theorems.
- CQL author implementation — fixed discrete and continuous method reading · Fixed2020-09-14 commit; full54-line README, discrete141–174/219–243, continuous cql.py194–282. QR-DQN regularization differs from continuous sampling corrections; data Q mean is not the comment’s log likelihood. README notes D4RL/version changes. Atari Apache identity only; all21 D4RL MIT lines read. No copying/execution.
相关主题