14.5  从示教中学习

基础篇中的所有模型都是从带标签样本中学习的:一张图像及其类别,一句话及其下一个词。上一节展示了当无人提供标签、智能体只能通过尝试糟糕的动作来寻找好动作时,会付出多大的代价。而在许多场景中,有人可以直接为我们示范。假设我们记录了一位熟练驾驶员的所见与所为——每个时刻的摄像头图像以及相应选择的方向盘转角。我们能否像在 Fashion-MNIST 上训练分类器那样,以图像为输入、方向盘转角为标签,从这些样本对中训练出一个驾驶策略?

Dean Pomerleau 在 20 世纪 80 年代末于卡内基梅隆大学构建了这样一个网络。他的网络 ALVINN 仅含一个隐藏层,将道路图像映射为转向方向,成功驾驶一辆厢式货车沿道路行驶 (Pomerleau 1989年);后来的版本只需观察人类驾驶几分钟就能学会开车 (Pomerleau 1991年)。这种方法如今称为行为克隆(behavior cloning)。它既不需要环境模型,也不需要奖励信号,只需要一位可以记录其选择的专家;这也是当今从专家处学习最常用的方法:在精选回复上微调语言模型就是行为克隆,其中已生成的文本是状态,下一个词元是动作。

Pomerleau 也看到了它的弱点。人类驾驶员始终让车辆保持在车道中央,因此记录的数据中既没有路边的画面,也没有从路边修正回来的示例。一旦网络发生偏离,它就会看到从未见过的图像;为此,他不得不合成偏移后的道路视角,并标注能将车辆拉回车道的转向动作。分类器是在与训练数据同分布的输入上接受测试的,而策略却决定了自己接下来会看到什么输入。本节将在冰湖环境中量化这种差异的代价,展示该代价如何随任务长度增长,并通过改变数据收集方式,让专家对学习者自己到达的状态进行标注。

# Deterministic XLA kernels. On an accelerator XLA otherwise picks each
# matrix product's kernel by timing candidates, and kernels that add in
# different orders differ in the last bits; training runs at large step
# sizes can turn such differences into different outcomes. JAX reads
# XLA_FLAGS once, when it starts, so this cell runs before the imports.
import os
os.environ['XLA_FLAGS'] = (os.environ.get('XLA_FLAGS', '') +
                           ' --xla_gpu_deterministic_ops=true').strip()
import gymnasium as gym
import gymnasium as gym

14.5.1 行为克隆

示教(demonstration)是从专家处记录下的一条轨迹。行为克隆只保留专家访问过的状态以及在这些状态下采取的动作,既不使用奖励,也不使用转移模型。在冰湖上,专家就是 14.2 节 中价值迭代求出的最优策略 \(\pi^*\),因此本节用 \(\pi^*\) 同时表示最优策略和专家。我们采用平静冰面,每个指令都会让智能体沿预期方向移动。于是专家在每个回合中都会从起点走到终点,走完完全相同的 6 步路径,其访问的状态在冰湖上形成一条狭窄的管道,就像 Pomerleau 记录数据中的车道中央一样。由于冰湖模型已知,我们可以精确计算每一个成功率,在没有采样噪声的情况下将学习者与专家进行对比。

14.5.1.1 归约为分类问题

下面的代码单元将平静冰湖构建为 TabularMDP(即 14.1 节 中的数组 \(P\)、\(r\) 以及折扣因子 \(\gamma\)),用 d2l.value_iteration 求解它,并通过对 mdp.backup(作用于 \(V^*\) 的贝尔曼算子)在每个状态取最优动作来读取专家策略。demonstrations 在环境中运行专家策略,并仅记录其观测到的状态与采取的动作:

gamma = 0.95
env = gym.make('FrozenLake-v1', is_slippery=False)
mdp = d2l.TabularMDP.from_gym(env, gamma)
V_star = d2l.value_iteration(mdp, num_iters=1000)[-1]
pi_star = mdp.backup(V_star).argmax(axis=1)

def demonstrations(env, expert, num_episodes):
    """Roll the expert; record only what it saw and what it did."""
    states, actions = [], []
    for _ in range(num_episodes):
        s, done = env.reset()[0], False
        while not done:
            states.append(s)
            actions.append(int(expert[s]))
            s, _, terminated, truncated, _ = env.step(actions[-1])
            done = terminated or truncated
    return np.array(states), np.array(actions)

demo_s, demo_a = demonstrations(env, pi_star, 3)
print(f'{demo_s.size} state-action pairs from 3 expert episodes, '
      f'covering states {np.unique(demo_s)}')
18 state-action pairs from 3 expert episodes, covering states [ 0  4  8  9 13 14]
gamma = 0.95
env = gym.make('FrozenLake-v1', is_slippery=False)
mdp = d2l.TabularMDP.from_gym(env, gamma)
V_star = d2l.value_iteration(mdp, num_iters=1000)[-1]
pi_star = mdp.backup(V_star).argmax(axis=1)

def demonstrations(env, expert, num_episodes):
    """Roll the expert; record only what it saw and what it did."""
    states, actions = [], []
    for _ in range(num_episodes):
        s, done = env.reset()[0], False
        while not done:
            states.append(s)
            actions.append(int(expert[s]))
            s, _, terminated, truncated, _ = env.step(actions[-1])
            done = terminated or truncated
    return np.array(states), np.array(actions)

demo_s, demo_a = demonstrations(env, pi_star, 3)
print(f'{demo_s.size} state-action pairs from 3 expert episodes, '
      f'covering states {np.unique(demo_s)}')
18 state-action pairs from 3 expert episodes, covering states [ 0  4  8  9 13 14]

3 个回合给出了 18 个带标签样本对——实际上是相同的 6 个样本对重复了 3 次,因为在平静冰面上,专家的每个回合都完全相同:下、下、右、下、右、右。在状态 0 和状态 9 处,下与右路径同样短,平局时选择下。专家从未访问过冰冻格子 1、2、3、6 和 10。

行为克隆处理这些样本对的方式,与 3.1 节 处理图像和标签的方式完全相同:状态是输入,专家动作是类别,我们通过最大化对数似然 \(\sum_i \log \pi_\theta(a_i \mid s_i)\)(即最小化交叉熵)来拟合带参数 \(\theta\) 的条件分布 \(\pi_\theta(a \mid s)\)。我们所需的只是一个带参数的策略,以及对其进行梯度更新的方法。

14.5.1.2 策略容器

Policy 封装了一个将状态映射为各动作分数的网络 policy——使得 \(\pi_\theta(\cdot \mid s)\) 为状态 \(s\) 处分数的 softmax——以及用于更新其参数的 Adam 优化器 opt_pi。log_prob 返回一批状态及其所选动作对应的 \(\log \pi_\theta(a \mid s)\),这正是行为克隆要最大化的量:

class seeded:
    """In a `with seeded(seed):` block, PyTorch's CPU generator starts from
    seed; on exit it resumes its previous state, so the seed affects only
    the draws inside the block. seed=None draws from the global stream."""
    def __init__(self, seed):
        self.seed = seed

    def __enter__(self):
        if self.seed is not None:
            self.state = torch.get_rng_state()
            torch.default_generator.manual_seed(self.seed)

    def __exit__(self, *exc):
        if self.seed is not None:
            torch.set_rng_state(self.state)

class Policy(nn.Module):
    """A policy network and its optimizer; pi(.|s) is the softmax of the
    network's outputs at s."""
    def __init__(self, policy, lr=1e-2):
        super().__init__()
        self.policy = policy
        self.opt_pi = torch.optim.Adam(policy.parameters(), lr=lr)

    def log_prob(self, obs, act):
        """log pi(a|s) for a batch of states and the actions taken there."""
        return torch.log_softmax(self.policy(obs), dim=-1) \
                    .gather(-1, act[:, None]).squeeze(-1)

    @classmethod
    def tabular(cls, num_states, num_actions, lr=0.1, seed=None):
        """One preference theta_{s,a} per state-action pair: an embedding."""
        with seeded(seed):
            policy = nn.Embedding(num_states, num_actions)
        nn.init.zeros_(policy.weight)
        return cls(policy, lr)
class Policy(nnx.Module):
    """A policy network and its optimizer; pi(.|s) is the softmax of the
    network's outputs at s."""
    def __init__(self, policy, lr=1e-2):
        self.policy = policy
        self.opt_pi = nnx.Optimizer(policy, d2l.shared_adam(lr),
                                    wrt=nnx.Param)

    def log_prob(self, obs, act, policy=None):
        """log pi(a|s). Gradients flow w.r.t. the module you differentiate;
        the update functions pass that module back in as `policy`."""
        policy = self.policy if policy is None else policy
        logp = jax.nn.log_softmax(policy(obs), axis=-1)
        return jnp.take_along_axis(logp, act[:, None], axis=-1).squeeze(-1)

    @classmethod
    def tabular(cls, num_states, num_actions, lr=0.1, seed=None):
        """One preference theta_{s,a} per state-action pair: an embedding."""
        rngs = nnx.Rngs(d2l.get_key() if seed is None else seed)
        return cls(d2l.Embed(num_states, num_actions, rngs=rngs,
                             embedding_init=nnx.initializers.zeros_init()),
                   lr)

tabular 构造函数实现的是一个 softmax 回归模型:嵌入表为每个状态–动作对保存一个偏好值 \(\theta_{s,a}\),整数状态索引对应的行,再经 softmax 生成 \(\pi_\theta(\cdot\mid s)\)。全零初始化使初始策略为均匀分布。

参数 seed 固定了此构造函数及后续构造函数所建网络的随机初始化。seeded 在 with 语句块内从 seed 启动 PyTorch 的 CPU 随机数生成器,并在退出后恢复生成器状态,因此该种子不会影响构造函数之外的任何随机抽样。

该嵌入表是 d2l.Embed(39.9.6.1 节),它是一个用单次矩阵乘法代替加速器上原子加法的 nnx.Embed。对同一行的原子加法到达顺序会发生变化,导致单步更新的最低有效位——进而在较大步长下经过多步后的整个训练过程——在两次运行之间出现差异。

环境交互使用 NumPy 整数和数组,因此我们在边界处提供三个转换方法。act 使用调用方传入的 NumPy 随机数生成器从 \(\pi_\theta(\cdot \mid s)\) 中采样动作,从而让进入环境的所有随机性都来自同一个显式来源。它遵循 14.2 节 中 d2l.evaluate 的动作协议,后者用于对采样回合的回报求平均。act_greedy 返回概率最大的动作,log_prob_np 以 NumPy 数组形式返回对数概率:

@d2l.add_to_class(Policy)
def act(self, obs, rng):
    """Sample an action; numpy in, int out, the acting protocol of evaluate."""
    with torch.inference_mode():
        probs = torch.softmax(self.policy(torch.as_tensor(obs)), -1).numpy()
    return int(rng.choice(len(probs), p=probs))

@d2l.add_to_class(Policy)
def act_greedy(self, obs, rng=None):
    """The most probable action; the same protocol as act."""
    with torch.inference_mode():
        return int(self.policy(torch.as_tensor(obs)).argmax())

@d2l.add_to_class(Policy)
def log_prob_np(self, obs, act):
    """log pi(a|s) for numpy batches of states and actions, as numpy."""
    with torch.inference_mode():
        return self.log_prob(torch.as_tensor(obs),
                             torch.as_tensor(act)).numpy()
@d2l.add_to_class(Policy)
def act(self, obs, rng):
    """Sample an action; numpy in, int out, the acting protocol of evaluate."""
    logits = d2l.forward_np(self.policy, obs)
    probs = np.exp(logits - logits.max())
    return int(rng.choice(len(probs), p=probs / probs.sum()))

@d2l.add_to_class(Policy)
def act_greedy(self, obs, rng=None):
    """The most probable action; the same protocol as act."""
    return int(d2l.forward_np(self.policy, obs).argmax())

@d2l.add_to_class(Policy)
def log_prob_np(self, obs, act):
    """log pi(a|s) for numpy batches of states and actions, as numpy. The
    batch is padded to a bucket length, so that each operation compiles
    once per bucket rather than once per batch length."""
    obs_p, act_p, _ = d2l.padded(obs, act)
    return np.asarray(self.log_prob(jnp.asarray(obs_p),
                                    jnp.asarray(act_p)))[:len(act)]

这三个方法都在 torch.inference_mode 下运行,因为它们的计算都不需要求导。

act 和 act_greedy 通过 d2l.forward_np 运行网络;log_prob_np 以及下面的 policy_step 使用 d2l.padded 将批次填充到分桶长度,以便在不同批次大小之间复用编译后的代码;d2l.shared_adam 为具有相同学习率的所有智能体共享同一个优化器,从而复用编译后的更新函数。这些辅助工具均位于 39.9 节。log_prob 接受一个可选的 policy 参数,因为 nnx.value_and_grad 对传入的模块求导,更新函数会将该模块传回;JAX 只在这样的变换内部计算梯度。

对于状态数较少的策略,probs 直接从学习者中读取整张 \(\pi_\theta(a \mid s)\) 数组表,以便进行本节的精确计算:

@d2l.add_to_class(Policy)
def probs(self, num_states, num_actions):
    """pi(a|s) for every pair, as a (num_states, num_actions) numpy array."""
    s, a = np.divmod(np.arange(num_states * num_actions), num_actions)
    return np.exp(self.log_prob_np(s, a)).reshape(num_states, num_actions)
@d2l.add_to_class(Policy)
def probs(self, num_states, num_actions):
    """pi(a|s) for every pair, as a (num_states, num_actions) numpy array."""
    s, a = np.divmod(np.arange(num_states * num_actions), num_actions)
    return np.exp(self.log_prob_np(s, a)).reshape(num_states, num_actions)

14.5.1.3 拟合克隆策略

拟合克隆策略就是在权重 \(w_i\) 全为 1 的目标函数 \(\frac{1}{n}\sum_i w_i \log \pi_\theta(a_i \mid s_i)\) 上执行梯度上升。policy_step 针对一批状态、动作和权重在该目标上执行一步优化器更新:

def policy_step(ac, obs, act, weight):
    """One ascent step on (1/n) sum_t w_t log pi(a_t|s_t) over a batch of
    n states and actions; the weights w arrive as numpy, that is, as data."""
    w = torch.as_tensor(weight)
    loss = -(w * ac.log_prob(torch.as_tensor(obs),
                             torch.as_tensor(act))).mean()
    ac.opt_pi.zero_grad()
    loss.backward()
    ac.opt_pi.step()
    return loss.item()
@nnx.jit
def _policy_pass(ac, obs, act, w, mask):
    """One step on -(1/n) sum_t w_t log pi(a_t|s_t) over the n real rows."""
    loss, grads = nnx.value_and_grad(lambda policy: -(
        mask * w * ac.log_prob(obs, act, policy)).sum() / mask.sum())(ac.policy)
    ac.opt_pi.update(ac.policy, grads)
    return loss

def policy_step(ac, obs, act, weight):
    """One ascent step on (1/n) sum_t w_t log pi(a_t|s_t) over a batch of
    n states and actions; the weights w arrive as numpy, that is, as data.
    The batch is padded to a bucket length, so the compiled pass is reused."""
    return float(_policy_pass(ac, *d2l.padded(obs, act, np.float32(weight))))

权重以 NumPy 数组(即普通数据)的形式传入,不会有梯度流入其中。在行为克隆中,这些权重全部为 1。

拟合应当运行多久?如果训练到完全收敛,每状态一行的查表模型就会把这 6 个示教动作背得一字不差,克隆策略在平静冰面上每次都会沿着专家路径走。而现实中的分类器并非精确无误:相似的输入、有限的模型容量以及含噪标签都会在训练分布上留下一定误差。为了给克隆策略引入这样的误差,clone 以单位权重反复调用 policy_step,直到 \(\pi_\theta\) 在示教样本对上的平均动作不一致概率不超过 \(\varepsilon = 0.2\)。该停止准则固定了 \(\varepsilon\),因此本节的所有对比都将拟合误差保持为常数:

def clone(mdp, states, actions, eps=0.2):
    """Behavior cloning: cross-entropy fit of pi(a|s) to the expert's
    choices (policy_step with every weight equal to one), stopped once pi
    disagrees with the demonstrated actions with probability at most eps."""
    learner = Policy.tabular(mdp.num_states, mdp.num_actions)
    weight = np.ones(len(states), np.float32)
    while 1 - np.exp(learner.log_prob_np(states, actions)).mean() > eps:
        policy_step(learner, states, actions, weight)
    return learner

bc = clone(mdp, demo_s, demo_a)
pi_bc = bc.probs(mdp.num_states, mdp.num_actions)
for s in (9, 10):
    print(f'clone pi(.|s={s}): {np.round(pi_bc[s], 3)}')
clone pi(.|s=9): [0.061 0.818 0.061 0.061]
clone pi(.|s=10): [0.25 0.25 0.25 0.25]
def clone(mdp, states, actions, eps=0.2):
    """Behavior cloning: cross-entropy fit of pi(a|s) to the expert's
    choices (policy_step with every weight equal to one), stopped once pi
    disagrees with the demonstrated actions with probability at most eps."""
    learner = Policy.tabular(mdp.num_states, mdp.num_actions)
    weight = np.ones(len(states), np.float32)
    while 1 - np.exp(learner.log_prob_np(states, actions)).mean() > eps:
        policy_step(learner, states, actions, weight)
    return learner

bc = clone(mdp, demo_s, demo_a)
pi_bc = bc.probs(mdp.num_states, mdp.num_actions)
for s in (9, 10):
    print(f'clone pi(.|s={s}): {np.round(pi_bc[s], 3)}')
clone pi(.|s=9): [0.061 0.818 0.061 0.061]
clone pi(.|s=10): [0.25 0.25 0.25 0.25]

14 步 Adam 更新将不一致率降至 0.182。每个示教状态出现次数相同、收到的梯度也相同,因此 6 个示教行最终在专家动作上的概率都是 0.818,在其余三个动作上各为 0.061,正如状态 9 那一行所示。状态 10 从未被示教,它对应的行没有收到任何梯度,保持均匀分布,因此克隆策略在该处有四分之三的概率与专家不一致。重复数据不会改变拟合结果:3 份 6 对样本的平均损失与 1 份的平均损失完全相同,所以用 1 个专家回合克隆出的表与用 100 个专家回合克隆出的表一模一样。

14.5.2 分布偏移

14.5.2.1 训练与部署

分类器的性能保证只针对其训练数据所属的分布。行为克隆在专家访问的状态上训练,却在自身动作所产生的状态上部署。我们以两种方式部署克隆策略:贪心部署,即选取概率最大的动作;以及使用 act 从 \(\pi_\theta\) 中采样,就像语言模型采样下一个词元那样。

由于冰湖模型已知,策略的状态分布可以直接计算,而不必采样估计。记 \(d^\pi_t(s)\) 为策略 \(\pi\) 在经过 \(t\) 步后处于状态 \(s\) 的概率。初始时全部概率质量都集中在起点状态,每走一步,概率质量便经由策略与转移核向前传播:

\[d^\pi_{t+1}(s') = \sum_{s} d^\pi_t(s) \sum_a \pi(a \mid s)\, P(s' \mid s, a). \tag{14.5.1}\]

下一步落在 \(s'\) 的概率质量,等于各个状态在策略所选动作下流向该处的质量之和。visitation 在冰湖的 100 步时间限制内执行这一递推;终点和冰洞会结束回合且保留其概率质量,因此 100 步后终点的概率质量就是成功概率。用 d2l.evaluate 做一次蒙特卡洛模拟,可以校验采样克隆策略的精确数值:

def visitation(mdp, pi, absorbing=None, T=100):
    """d_0, ..., d_T: the state distributions of the policy pi[s, a] from the
    start state, propagated exactly through P for FrozenLake's 100-step
    limit. Mass that enters an `absorbing` state stays there."""
    P_pi = np.einsum('sa,sat->st', pi, mdp.P)
    if absorbing is not None:
        P_pi[absorbing] = np.eye(mdp.num_states)[absorbing]
    d = [np.eye(mdp.num_states)[0]]
    for _ in range(T):
        d.append(d[-1] @ P_pi)
    return np.array(d)

desc = env.unwrapped.desc.ravel()
goal, holes = desc == b'G', desc == b'H'
expert = np.eye(mdp.num_actions)[pi_star]                # one-hot rows
greedy = np.eye(mdp.num_actions)[pi_bc.argmax(axis=1)]
for name, pi in [('expert', expert), ('greedy clone', greedy),
                 ('sampling clone', pi_bc)]:
    d_T = visitation(mdp, pi)[-1]
    print(f'{name:>14}: reaches the goal {d_T[goal].sum():.3f}, '
          f'falls into a hole {d_T[holes].sum():.3f}')
rate = d2l.evaluate(env, bc.act, num_episodes=1000,
                    rng=np.random.default_rng(0))
print(f'sampling clone, 1000 episodes of bc.act: reaches the goal {rate:.3f}')
        expert: reaches the goal 1.000, falls into a hole 0.000
  greedy clone: reaches the goal 1.000, falls into a hole 0.000
sampling clone: reaches the goal 0.660, falls into a hole 0.340
sampling clone, 1000 episodes of bc.act: reaches the goal 0.656
def visitation(mdp, pi, absorbing=None, T=100):
    """d_0, ..., d_T: the state distributions of the policy pi[s, a] from the
    start state, propagated exactly through P for FrozenLake's 100-step
    limit. Mass that enters an `absorbing` state stays there."""
    P_pi = np.einsum('sa,sat->st', pi, mdp.P)
    if absorbing is not None:
        P_pi[absorbing] = np.eye(mdp.num_states)[absorbing]
    d = [np.eye(mdp.num_states)[0]]
    for _ in range(T):
        d.append(d[-1] @ P_pi)
    return np.array(d)

desc = env.unwrapped.desc.ravel()
goal, holes = desc == b'G', desc == b'H'
expert = np.eye(mdp.num_actions)[pi_star]                # one-hot rows
greedy = np.eye(mdp.num_actions)[pi_bc.argmax(axis=1)]
for name, pi in [('expert', expert), ('greedy clone', greedy),
                 ('sampling clone', pi_bc)]:
    d_T = visitation(mdp, pi)[-1]
    print(f'{name:>14}: reaches the goal {d_T[goal].sum():.3f}, '
          f'falls into a hole {d_T[holes].sum():.3f}')
rate = d2l.evaluate(env, bc.act, num_episodes=1000,
                    rng=np.random.default_rng(0))
print(f'sampling clone, 1000 episodes of bc.act: reaches the goal {rate:.3f}')
        expert: reaches the goal 1.000, falls into a hole 0.000
  greedy clone: reaches the goal 1.000, falls into a hole 0.000
sampling clone: reaches the goal 0.660, falls into a hole 0.340
sampling clone, 1000 episodes of bc.act: reaches the goal 0.656

专家每次都能到达终点,贪心克隆策略也一样:每个示教行中概率最大的动作就是专家动作,因此贪心克隆策略始终沿着专家路径前进。采样克隆策略在 66% 的回合中到达终点,其余回合掉入冰洞;1,000 次采样回合的统计结果在噪声范围内与之吻合。平静冰面上除了克隆策略自身的选择外没有任何随机性,因此它偏离路径的每一步都源于自身的错误动作。

这是分类器的错吗?下一个代码单元在三组状态上测量克隆策略与专家不一致的频率:训练样本对、100 个新专家回合的状态,以及克隆策略自己访问的状态(按访问频率加权)。随后它分别对 1、10 和 100 个专家回合进行克隆:

disagree = 1 - pi_bc[np.arange(mdp.num_states), pi_star]   # per state
fresh_s, _ = demonstrations(env, pi_star, 100)
occupancy = (visitation(mdp, pi_bc)[:-1] * ~(goal | holes)).sum(axis=0)
print('disagreement with the expert')
print(f'  on the training pairs:        {disagree[demo_s].mean():.3f}')
print(f'  on 100 fresh expert episodes: {disagree[fresh_s].mean():.3f}')
print(f"  on the clone's own states:    "
      f'{occupancy @ disagree / occupancy.sum():.3f}')
for n in [1, 10, 100]:
    pi_n = clone(mdp, *demonstrations(env, pi_star, n)).probs(
        mdp.num_states, mdp.num_actions)
    print(f'clone of {n:>3} expert episodes: reaches the goal '
          f'{visitation(mdp, pi_n)[-1][goal].sum():.3f}')
disagreement with the expert
  on the training pairs:        0.182
  on 100 fresh expert episodes: 0.182
  on the clone's own states:    0.216
clone of   1 expert episodes: reaches the goal 0.660
clone of  10 expert episodes: reaches the goal 0.660
clone of 100 expert episodes: reaches the goal 0.660
disagree = 1 - pi_bc[np.arange(mdp.num_states), pi_star]   # per state
fresh_s, _ = demonstrations(env, pi_star, 100)
occupancy = (visitation(mdp, pi_bc)[:-1] * ~(goal | holes)).sum(axis=0)
print('disagreement with the expert')
print(f'  on the training pairs:        {disagree[demo_s].mean():.3f}')
print(f'  on 100 fresh expert episodes: {disagree[fresh_s].mean():.3f}')
print(f"  on the clone's own states:    "
      f'{occupancy @ disagree / occupancy.sum():.3f}')
for n in [1, 10, 100]:
    pi_n = clone(mdp, *demonstrations(env, pi_star, n)).probs(
        mdp.num_states, mdp.num_actions)
    print(f'clone of {n:>3} expert episodes: reaches the goal '
          f'{visitation(mdp, pi_n)[-1][goal].sum():.3f}')
disagreement with the expert
  on the training pairs:        0.182
  on 100 fresh expert episodes: 0.182
  on the clone's own states:    0.216
clone of   1 expert episodes: reaches the goal 0.660
clone of  10 expert episodes: reaches the goal 0.660
clone of 100 expert episodes: reaches the goal 0.660

在新的专家回合上,克隆策略的出错率与训练样本对上相同,都是 18%,因此不存在泛化差距:示教数据已经覆盖了专家的分布。在这里,增加更多专家数据毫无帮助:它不会增添任何新状态,反复克隆这 6 对样本得到的都是同一张表,成功率始终为 66%。而在克隆策略自己访问的状态上,出错率升高到了 22%,因为其中包含一些它从未见过数据的格子,在那里它的不一致概率高达 \(3/4\)。策略接受测试的状态分布发生了移动,而且正是它自己的动作推动了这种移动。这就是分布偏移(distribution shift)。在 6 步任务上这种偏移还不大,14.5.3.2 节 将量化它究竟造成了多少性能损失。

14.5.2.2 覆盖缺失

覆盖缺失是另一种截然不同的失效模式。在湿滑冰面上,专家自己也会打滑,因此它访问的状态集合是随机的,少量回合可能会漏掉某个动作至关重要的状态。下面的代码单元构建湿滑冰湖及其最优策略,对每个 \(n\) 抽取 200 组包含 \(n\) 个专家回合的数据集,并精确评估每组数据集上的贪心克隆策略。该克隆策略在每个示教状态上采取专家动作;在其他所有状态上其对应行保持均匀分布,平局时选动作 0。代码直接写出这张表,而不必真的拟合 600 次克隆策略:

ice = gym.make('FrozenLake-v1', is_slippery=True)
mdp_ice = d2l.TabularMDP.from_gym(ice, gamma)
V_ice = d2l.value_iteration(mdp_ice, num_iters=1000)[-1]
pi_ice = mdp_ice.backup(V_ice).argmax(axis=1)
one_hot = np.eye(mdp_ice.num_actions)
expert_ice = visitation(mdp_ice, one_hot[pi_ice])[-1][goal].sum()
ice.reset(seed=5)
print(f'share of 200 datasets whose greedy clone is below half the expert '
      f'({expert_ice:.3f}):')
for n in [1, 3, 10]:
    rates = []
    for _ in range(200):
        seen = np.isin(np.arange(mdp_ice.num_states),
                       demonstrations(ice, pi_ice, n)[0])
        # the greedy clone: the expert's action where it has data; elsewhere
        # its row is untouched and uniform, and the tie goes to action 0
        tab = np.where(seen, pi_ice, 0)
        rates.append(visitation(mdp_ice, one_hot[tab])[-1][goal].sum())
    failed = np.mean(np.array(rates) < expert_ice / 2)
    print(f'  expert episodes per dataset {n:>2}: {failed:.1%}')
share of 200 datasets whose greedy clone is below half the expert (0.730):
  expert episodes per dataset  1: 32.0%
  expert episodes per dataset  3: 1.5%
  expert episodes per dataset 10: 0.0%
ice = gym.make('FrozenLake-v1', is_slippery=True)
mdp_ice = d2l.TabularMDP.from_gym(ice, gamma)
V_ice = d2l.value_iteration(mdp_ice, num_iters=1000)[-1]
pi_ice = mdp_ice.backup(V_ice).argmax(axis=1)
one_hot = np.eye(mdp_ice.num_actions)
expert_ice = visitation(mdp_ice, one_hot[pi_ice])[-1][goal].sum()
ice.reset(seed=5)
print(f'share of 200 datasets whose greedy clone is below half the expert '
      f'({expert_ice:.3f}):')
for n in [1, 3, 10]:
    rates = []
    for _ in range(200):
        seen = np.isin(np.arange(mdp_ice.num_states),
                       demonstrations(ice, pi_ice, n)[0])
        # the greedy clone: the expert's action where it has data; elsewhere
        # its row is untouched and uniform, and the tie goes to action 0
        tab = np.where(seen, pi_ice, 0)
        rates.append(visitation(mdp_ice, one_hot[tab])[-1][goal].sum())
    failed = np.mean(np.array(rates) < expert_ice / 2)
    print(f'  expert episodes per dataset {n:>2}: {failed:.1%}')
share of 200 datasets whose greedy clone is below half the expert (0.730):
  expert episodes per dataset  1: 32.0%
  expert episodes per dataset  3: 1.5%
  expert episodes per dataset 10: 0.0%

仅用 1 个回合时,约有三分之一的数据集得到的克隆策略成功率不到专家的一半;用 3 个回合时,每一百组中只有一两组如此;用 10 个回合时,200 组中无一例外全部过关。随着专家数据积累,覆盖缺失会逐渐消失;但分布偏移不会,因为克隆策略因自身失误而进入的状态,是专家永远不会访问的状态。

14.5.3 累积误差

14.5.3.1 二次与线性误差增长

冰湖上的专家路径只有 6 步长。当任务变得更长时,单步误差的代价会如何增长?监督学习只能界定单次决策出错的概率;而在序贯任务中,一次早期失误会改变此后所有的状态,甚至可能断送后续全部奖励。示教数据是从专家的状态分布 \(d^{\pi^*}_t\) 中采样的,因此行为克隆只在该分布上控制了克隆策略的错误率,而在分布之外鞭长莫及。

命题(累积误差)。 考虑一个长度为 \(T\) 步、每步奖励位于 \([0, 1]\) 内的回合制任务,以及一个策略 \(\hat\pi\):在每一步 \(t\),当状态从专家分布 \(d^{\pi^*}_t\) 中抽取时,该策略与专家不一致的概率不超过 \(\varepsilon\)。(i)\(\hat\pi\) 的期望回报比专家最多低 \(\varepsilon T(T+1)/2 \leq \varepsilon T^2\),且存在这样的任务,只要 \(\varepsilon T \leq 1\),其差距就达到这一量级。(ii)如果改为当状态从其自身分布 \(d^{\hat\pi}_t\) 中抽取时,\(\hat\pi\) 与专家不一致的概率不超过 \(\varepsilon\),且采取一次错误动作后改由专家接管最多损失 \(u\),那么回报差距最多为 \(u \varepsilon T\) (Ross 和 Bagnell 2010年)。

证明。 (i)让 \(\hat\pi\) 与专家从同一状态出发并共享相同的环境随机性,于是它们的轨迹完全重合,直到 \(\hat\pi\) 首次采取与专家不同的动作。专家在第 \(t\) 步的状态服从 \(d^{\pi^*}_t\),而首次不一致恰好发生在第 \(t\) 步的前提是 \(\hat\pi\) 在该状态下与专家不一致,其概率不超过 \(\varepsilon\)。从那一刻起,\(\hat\pi\) 最多损失第 \(t, \ldots, T\) 步共 \(T-t+1\) 步的奖励。对 \(t\) 求和,总差距不超过 \(\sum_{t=1}^{T} \varepsilon (T-t+1) = \varepsilon T(T+1)/2\)。(ii)令混合策略 \(\pi_k\) 在前 \(k\) 步遵循 \(\hat\pi\)、此后遵循专家,于是 \(\pi_0\) 为专家而 \(\pi_T\) 为 \(\hat\pi\)。相邻两个混合策略 \(\pi_{k-1}\) 与 \(\pi_k\) 仅在第 \(k\) 步的动作上不同,而该步的状态服从 \(d^{\hat\pi}_k\)。该动作与专家不一致的概率不超过 \(\varepsilon\),且一次不一致后由专家接管最多损失 \(u\)。专家与 \(\hat\pi\) 的回报之差等于这 \(T\) 对相邻混合策略之差的和,因此不超过 \(u \varepsilon T\)。\(\blacksquare\)

第二部分采用了 Kakade 和 Langford (2002年) 的裂项相消论证。即使 \(\varepsilon\) 是这 \(T\) 步错误率的平均值而非最大值,第(i)部分的求和仍然不超过 \(\varepsilon T^2\)。第(i)部分把后续所有损失都记在第一次失误头上,因为一旦偏离,策略便进入毫无误差控制的状态。第(ii)部分将 \(\varepsilon\) 的衡量转移到了策略自身访问的状态分布上,但只有在 \(u\) 较小时——即任务允许从单次错误动作中恢复时——这一界才有用。如果一次失误就是致命的,那么 \(u\) 就会大到与剩余视界相当,第(ii)部分又会退回到 \(\varepsilon T^2\) 量级。

冰湖的视界是固定的,因此我们改在一条 \(T\) 步的链上观察误差随 \(T\) 的增长。专家每步向右移动并获得 1 分奖励。两个模仿者在每一步独立地以概率 \(\varepsilon\) 与专家不一致。对于克隆模仿者,一次失误是永久性的:它会离开这条链进入从未见过的状态,此后不再获得任何奖励,因此它在第 \(t\) 步拿到奖励的概率是 \((1-\varepsilon)^t\)。可恢复模仿者在失误一步后就能回到链上,因此一次失误恰好损失 1 分奖励(对应第(ii)部分中 \(u = 1\)),它在第 \(t\) 步拿到奖励的概率为 \(1-\varepsilon\)。下面的代码单元在 \(\varepsilon = 0.01\)、\(T\) 最高取 64 时精确计算了两者的回报损失:

eps, T_max = 0.01, 64
T = np.arange(1, T_max + 1)
# probability of earning the reward of step t: the cloned imitator only if
# it has agreed at every step up to t, the recovering one if it agrees at t
earn_bc = np.cumprod(np.full(T_max, 1 - eps))
earn_rec = np.full(T_max, 1 - eps)
gap_bc, gap_rec = T - earn_bc.cumsum(), T - earn_rec.cumsum()
d2l.plot([T] * 3, [gap_bc, eps * T * (T + 1) / 2, gap_rec],
         xlabel='horizon T', ylabel='return lost to the expert',
         legend=['cloned', '$\\varepsilon T(T+1)/2$',
                 'recovering ($=\\varepsilon T$)'],
         xscale='log', yscale='log', figsize=(5, 3.5))
print(f'lost return at T={T_max}: cloned {gap_bc[-1]:.2f} '
      f'(eps T(T+1)/2 = {eps * T_max * (T_max + 1) / 2:.2f}), '
      f'recovering {gap_rec[-1]:.2f} (eps T = {eps * T_max:.2f})')
lost return at T=64: cloned 17.03 (eps T(T+1)/2 = 20.80), recovering 0.64 (eps T = 0.64)

eps, T_max = 0.01, 64
T = np.arange(1, T_max + 1)
# probability of earning the reward of step t: the cloned imitator only if
# it has agreed at every step up to t, the recovering one if it agrees at t
earn_bc = np.cumprod(np.full(T_max, 1 - eps))
earn_rec = np.full(T_max, 1 - eps)
gap_bc, gap_rec = T - earn_bc.cumsum(), T - earn_rec.cumsum()
d2l.plot([T] * 3, [gap_bc, eps * T * (T + 1) / 2, gap_rec],
         xlabel='horizon T', ylabel='return lost to the expert',
         legend=['cloned', '$\\varepsilon T(T+1)/2$',
                 'recovering ($=\\varepsilon T$)'],
         xscale='log', yscale='log', figsize=(5, 3.5))
print(f'lost return at T={T_max}: cloned {gap_bc[-1]:.2f} '
      f'(eps T(T+1)/2 = {eps * T_max * (T_max + 1) / 2:.2f}), '
      f'recovering {gap_rec[-1]:.2f} (eps T = {eps * T_max:.2f})')
lost return at T=64: cloned 17.03 (eps T(T+1)/2 = 20.80), recovering 0.64 (eps T = 0.64)

在对数坐标下,克隆模仿者紧贴二次参考曲线 \(\varepsilon T(T+1)/2\)(在 \(T = 10\) 处相差不到 3%,在 \(T = 30\) 处相差不到 10%),并随着 \(\varepsilon T\) 增大而逐渐落到参考线下方,因为首次失误最多只能发生一次:首次不一致落在第 \(t\) 步的概率是 \(\varepsilon(1-\varepsilon)^{t-1}\),小于上界所计的 \(\varepsilon\)。正如第(i)部分所要求,它从未越过参考线。可恢复模仿者恰好损失 \(\varepsilon T\)。在 \(T = 64\) 时,克隆模仿者损失约 17 分奖励,而可恢复模仿者仅损失 0.64 分,少了约 27 倍。1 将推导出这两条曲线的闭式解。

14.5.3.2 克隆策略损失的分解

回到冰湖上,克隆策略损失的 34 个百分点中,有多少来自分布偏移?克隆策略有两种失败方式:它可以直接从专家路径上因 6 个训练状态之一的误动作掉进冰洞——这是专家分布上的拟合误差 \(\varepsilon\),只有更好的拟合才能消除;或者它也可以离开路径进入没有数据的格子,再从那里失败——这就是分布偏移。下面的代码单元把路径之外的格子设为吸收态,让 visitation 测量克隆策略离开路径的频率,并比较留在路径上的回合与离开路径的回合各自的成功概率。最后一行评估了一个在路径内外每个格子上都具有与克隆策略相同 18% 误差的学习者:

path = np.isin(np.arange(mdp.num_states), demo_s)    # the expert's cells
off_path = ~path & ~(goal | holes)
d_T = visitation(mdp, pi_bc, absorbing=off_path)[-1]
left = d_T[off_path].sum()
stay_goal = d_T[goal].sum()
clone_goal = visitation(mdp, pi_bc)[-1][goal].sum()
print(f'the clone leaves the expert path in {left:.3f} of its episodes, '
      f'entering cells {np.flatnonzero(d_T * off_path)}')
print(f'it reaches the goal in {stay_goal / (1 - left):.3f} of the episodes '
      f'that stay on the path, {(clone_goal - stay_goal) / left:.3f} of '
      f'those that leave it')
# the clone's demonstrated rows, with their error, at every cell
p_agree = pi_bc[demo_s[0], demo_a[0]]
labeled = np.where(expert == 1, p_agree, (1 - p_agree) / 3)
print(f'a learner with the same error at every cell reaches the goal '
      f'{visitation(mdp, labeled)[-1][goal].sum():.3f}')
the clone leaves the expert path in 0.172 of its episodes, entering cells [ 1 10]
it reaches the goal in 0.715 of the episodes that stay on the path, 0.394 of those that leave it
a learner with the same error at every cell reaches the goal 0.735
path = np.isin(np.arange(mdp.num_states), demo_s)    # the expert's cells
off_path = ~path & ~(goal | holes)
d_T = visitation(mdp, pi_bc, absorbing=off_path)[-1]
left = d_T[off_path].sum()
stay_goal = d_T[goal].sum()
clone_goal = visitation(mdp, pi_bc)[-1][goal].sum()
print(f'the clone leaves the expert path in {left:.3f} of its episodes, '
      f'entering cells {np.flatnonzero(d_T * off_path)}')
print(f'it reaches the goal in {stay_goal / (1 - left):.3f} of the episodes '
      f'that stay on the path, {(clone_goal - stay_goal) / left:.3f} of '
      f'those that leave it')
# the clone's demonstrated rows, with their error, at every cell
p_agree = pi_bc[demo_s[0], demo_a[0]]
labeled = np.where(expert == 1, p_agree, (1 - p_agree) / 3)
print(f'a learner with the same error at every cell reaches the goal '
      f'{visitation(mdp, labeled)[-1][goal].sum():.3f}')
the clone leaves the expert path in 0.172 of its episodes, entering cells [ 1 10]
it reaches the goal in 0.715 of the episodes that stay on the path, 0.394 of those that leave it
a learner with the same error at every cell reaches the goal 0.735

克隆策略在 17% 的回合中会离开路径,且总是通过在状态 0 处误入格子 1,或在状态 9、14 处误入格子 10(图 14.5.1)。留在路径上的回合有 72% 到达终点,离开路径的回合只有 39% 到达终点。34 个百分点的损失随之分解为两部分:24 个百分点是直接从路径上掉入冰洞(\(0.828 \times 0.285\)),10 个百分点是离开路径后的失败(\(0.172 \times 0.606\))。如果在每个格子上都保持与克隆策略相同的误差,学习者的成功率将达到 73.5%,这意味着为路径外格子补充标签大约能挽回 34 个百分点中的 7.5 个百分点——少于 10 个百分点,因为即使有了标签,格子上仍有 18% 的出错率。在这个冰湖上,分布偏移约占克隆策略总损失的五分之一,其余部分则是路径内外固有的 18% 误差,单靠更换数据无法消除。在更长的路径上,克隆策略离开路径的频率会高得多;4 将在 \(8 \times 8\) 冰湖上考察这对两部分损失的影响。

图 14.5.1: 本节的克隆策略在平静冰湖上的去向。蓝色箭头标出专家的 6 步路径。每个格子显示部署后的克隆策略(采样动作,并在专家状态上以概率 \(\varepsilon = 0.18\) 与专家不一致)在 100 步时间限制内进入该格子的概率;颜色越深表示进入越频繁。虚线箭头表示克隆策略离开路径、进入无数据且均匀随机决策的格子的出口:从 0 到 1,以及从 9 或 14 到 10。克隆策略到达终点的概率为 \(0.66\);路径旁的冰洞 5 和 12 吞掉了其余大部分回合。

14.5.4 交互式数据收集

14.5.4.1 数据集聚合

增加更多示教无法解决分布偏移,因为专家永远不会访问克隆策略出错的那些格子。必须由学习者亲自去访问它们,再由专家为其标注。数据集聚合算法(DAgger,Dataset Aggregation)正是这样做的 (Ross 等 2011年):运行当前学习者,询问专家在学习者访问过的每个状态下应当采取哪个动作,将这些新样本对加入数据集,然后重新拟合(图 14.5.2)。模型、损失函数、优化器和停止准则都保持不变,改变的只有数据。

图 14.5.2: 一轮 DAgger 的流程。由学习者选择状态,由专家提供标签:运行学习者,专家指明在学习者访问的每个状态下自己会采取的动作,这些样本对并入数据集后重新拟合学习者。初始数据集是专家自己的示教。

relabel 用 act 像部署时那样采样运行学习者,并用专家的动作标注学习者访问到的状态:

def relabel(env, expert, learner, num_episodes, rng):
    """Roll the learner, sampling its actions; label its states with the
    expert's actions."""
    visited = []
    for _ in range(num_episodes):
        s, done = env.reset()[0], False
        while not done:
            visited.append(s)
            s, _, terminated, truncated, _ = env.step(learner.act(s, rng))
            done = terminated or truncated
    visited = np.array(visited)
    return visited, expert[visited]
def relabel(env, expert, learner, num_episodes, rng):
    """Roll the learner, sampling its actions; label its states with the
    expert's actions."""
    visited = []
    for _ in range(num_episodes):
        s, done = env.reset()[0], False
        while not done:
            visited.append(s)
            s, _, terminated, truncated, _ = env.step(learner.act(s, rng))
            done = terminated or truncated
    visited = np.array(visited)
    return visited, expert[visited]

dagger 从 3 个示教回合出发,运行 4 轮、每轮 10 个学习者回合,每轮结束后都用 clone 重新拟合,并精确评估每个学习者。39.9 节 中的 d2l.run_seeds 在 10 个随机种子上运行它并堆叠结果:

def dagger(seed, env, mdp, expert, demo_s, demo_a, num_rounds=4,
           num_episodes=10):
    """Yield (labels, distinct states, success) for behavior cloning and
    each DAgger round after it."""
    rng = np.random.default_rng(seed)
    goal = env.unwrapped.desc.ravel() == b'G'
    S, A = demo_s, demo_a                      # the aggregated dataset
    for k in range(num_rounds + 1):
        learner = clone(mdp, S, A)
        pi = learner.probs(mdp.num_states, mdp.num_actions)
        yield S.size, np.unique(S).size, visitation(mdp, pi)[-1][goal].sum()
        if k < num_rounds:            # the learner visits, the expert labels
            new_s, new_a = relabel(env, expert, learner, num_episodes, rng)
            S, A = np.concatenate([S, new_s]), np.concatenate([A, new_a])

runs = d2l.run_seeds(dagger, num_seeds=10, env=env, mdp=mdp, expert=pi_star,
                     demo_s=demo_s, demo_a=demo_a)   # (seed, round, quantity)
for k, (n, m, rate) in enumerate(np.median(runs, axis=0)):
    print(f'round {k}: {n:>3.0f} labels at {m:>2.0f} states, success '
          f'{rate:.3f} (seeds: {runs[:, k, 2].min():.3f} to '
          f'{runs[:, k, 2].max():.3f}; medians over 10 seeds)')
round 0:  18 labels at  6 states, success 0.660 (seeds: 0.660 to 0.660; medians over 10 seeds)
round 1:  84 labels at  8 states, success 0.710 (seeds: 0.649 to 0.735; medians over 10 seeds)
round 2: 152 labels at  9 states, success 0.717 (seeds: 0.652 to 0.735; medians over 10 seeds)
round 3: 218 labels at 11 states, success 0.735 (seeds: 0.710 to 0.735; medians over 10 seeds)
round 4: 283 labels at 11 states, success 0.735 (seeds: 0.717 to 0.735; medians over 10 seeds)
def dagger(seed, env, mdp, expert, demo_s, demo_a, num_rounds=4,
           num_episodes=10):
    """Yield (labels, distinct states, success) for behavior cloning and
    each DAgger round after it."""
    rng = np.random.default_rng(seed)
    goal = env.unwrapped.desc.ravel() == b'G'
    S, A = demo_s, demo_a                      # the aggregated dataset
    for k in range(num_rounds + 1):
        learner = clone(mdp, S, A)
        pi = learner.probs(mdp.num_states, mdp.num_actions)
        yield S.size, np.unique(S).size, visitation(mdp, pi)[-1][goal].sum()
        if k < num_rounds:            # the learner visits, the expert labels
            new_s, new_a = relabel(env, expert, learner, num_episodes, rng)
            S, A = np.concatenate([S, new_s]), np.concatenate([A, new_a])

runs = d2l.run_seeds(dagger, num_seeds=10, env=env, mdp=mdp, expert=pi_star,
                     demo_s=demo_s, demo_a=demo_a)   # (seed, round, quantity)
for k, (n, m, rate) in enumerate(np.median(runs, axis=0)):
    print(f'round {k}: {n:>3.0f} labels at {m:>2.0f} states, success '
          f'{rate:.3f} (seeds: {runs[:, k, 2].min():.3f} to '
          f'{runs[:, k, 2].max():.3f}; medians over 10 seeds)')
round 0:  18 labels at  6 states, success 0.660 (seeds: 0.660 to 0.660; medians over 10 seeds)
round 1:  84 labels at  8 states, success 0.710 (seeds: 0.649 to 0.735; medians over 10 seeds)
round 2: 152 labels at  9 states, success 0.717 (seeds: 0.652 to 0.735; medians over 10 seeds)
round 3: 218 labels at 11 states, success 0.735 (seeds: 0.710 to 0.735; medians over 10 seeds)
round 4: 283 labels at 11 states, success 0.735 (seeds: 0.717 to 0.735; medians over 10 seeds)

第 0 轮就是成功率为 0.66 的行为克隆。此后每轮大约新增 65 个标签,其中大多数仍在路径的 6 个状态上,偶尔会落到路径之外的格子里。不到 4 轮——只需几百个标签——10 个种子的中位数就达到 0.70 到 0.735(取决于具体选哪 10 个种子),达到或逼近“每个格子都有相同拟合误差”的学习者上限 0.735;且在每一个种子上,第 4 轮的学习者都优于行为克隆。相比之下,无论给多少专家标签,行为克隆都停留在 0.66。DAgger 挽回了源于路径外状态的那部分损失;而与专家之间剩余的差距来自拟合本身固有的 18% 误差,DAgger 并不触碰这部分。之所以有学习者能分毫不差地正好落在 0.735 上,是因为 Adam 会用每个参数自身梯度的大小去缩放该参数的步长,而任一已标注行的梯度都等于其标签数乘以一个对所有已标注行相同的因子,因此无论被标注过多少次,每个已标注行最终都会停在完全相同的 0.818 上。由此,学习者完全由“哪些格子带标签”唯一决定,一旦它能到达的每个格子都有了标签,它就是那个 0.735 的学习者。

各轮结果并不一定单调提升。在部分种子上,某一轮反而会使成功率略微下降(最差降至 0.649),5 将探究其原因。Ross 等 (2011年) 给出的理论保证针对的是整个序列中最好的学习者(或从中随机抽取的一个),而非最后一个。该保证假设进行多轮数据收集、在累积数据集上使用无遗憾学习者,且在原论文分析中收集数据时混合了专家与学习者的动作。它还要求专家随时待命,能够标注学习者到达的任何状态。保留此前各轮的全部数据,则能防止拟合出的策略只迎合最新一轮的轨迹。

14.5.4.2 作为行为克隆的监督微调

14.1 节 中的词元 MDP 使语言模型的监督微调成为行为克隆的一个特例。状态是上下文,即提示词加上迄今为止已生成的词元;动作是下一个词元;状态转移以概率 1 将该词元追加到末尾;精选回复就是专家示教。微调所用的交叉熵正是行为克隆的负对数似然,对每条回复中的所有词元求和。视界 \(T\) 是回复长度,\(u\) 则是写错一个词元后即使后续发挥良好仍要付出的代价:如果只是用词略显生僻但无伤大雅,该代价就很小;如果是在计算早期写错了一位数字而后续每一步都建立在它之上,该代价就会非常大。在部署时,模型采样自己的词元并以此为条件继续生成,因此随着回复变长,它的上下文会逐渐偏离精选回复的分布。

面向语言模型的 DAgger 需要一位专家为模型自己生成的前缀做标注:对学生模型生成的每个上下文,指出下一个词元应当是什么。人工无法为数百万条前缀完成这种标注,但更大的模型可以。同轨策略蒸馏(on-policy distillation)在学生模型自己采样的轨迹上训练学生,以教师模型的下一词元分布作为标签 (Agarwal 等 2024年);这正是以教师模型作为随叫随到专家的 DAgger。此外,在只有固定数据集可用的离线强化学习中,行为克隆也是标准的第一基线,15.7 节 会将各种离线方法与它进行对比。

行为克隆仅靠一个分类器就能将专家记录的选择转化为策略,而 DAgger 仅通过改变数据就消除了由学习者自身访问状态引发的那部分损失。两者都需要专家:一位提供示教,DAgger 还需要一位随时待命标注学习者所到之处。当没有专家可用时,还有两条路可走。如果环境规则已知且可微,就可以直接据此计算出好动作,14.6 节 将在连续状态与连续动作下做到这一点。如果连环境规则也未知,只要把克隆更新中的权重 \(w_i = 1\) 替换为一个衡量该动作结果好坏的数值,同一套更新依然适用。14.7 节 将从奖励中推导出这一权重。

14.5.5 小结

行为克隆像 softmax 回归一样,用交叉熵在专家的状态–动作对上拟合策略 \(\pi_\theta(a \mid s)\),既不需要转移模型也不需要奖励;每步拟合都是在单位权重下对对数概率执行一步梯度上升。拟合只控制了策略在专家状态分布上的误差,但部署后的策略访问的是自身动作产生的状态。专家状态上的单步误差 \(\varepsilon\) 在 \(T\) 步内最多可导致 \(\varepsilon T(T+1)/2\) 的回报损失,而策略自身状态上的同样误差在单次失误代价不超过 \(u\) 时最多损失 \(u \varepsilon T\)。在平静冰湖的 6 步路径上,增加更多专家数据无法改变克隆策略,偏离至专家从未访问状态的分布偏移约占其总损失的五分之一。DAgger 用专家动作标注学习者自己访问的状态,仅通过改变数据就挽回了这部分损失。

14.5.6 练习

  1. 链上损失的闭式解。在 14.5.3.1 节 的链实验中,模仿者在每一步 \(t = 1, \ldots, T\) 独立地以概率 \(\varepsilon\) 与专家不一致。克隆模仿者只有在第 \(t\) 步及之前每一步都与专家一致时才能拿到第 \(t\) 步的奖励;可恢复模仿者只要在第 \(t\) 步与专家一致就能拿到该步奖励。
    1. 推导出克隆模仿者相比专家所损失期望回报 \(G(T)\) 的闭式解,并证明可恢复模仿者损失 \(\varepsilon T\)。将两者与 \(\varepsilon = 0.01\)、\(T = 64\) 时打印出的数值进行对比。
    2. 将 \(G(T)\) 按 \(\varepsilon\) 展开至二阶。证明一阶项正是命题中的上界 \(\varepsilon T(T+1)/2\),并求出二阶项。二阶项的符号说明了克隆曲线相对于参考线的位置如何?对于 \(\varepsilon = 0.01\),一阶项在视界多大以内与 \(G(T)\) 的偏差不超过 10%?
    3. 当 \(\varepsilon T \gg 1\) 时,\(G(T)\) 如何增长?因此二次增长区间对 \(\varepsilon T\) 需要什么条件?计算曲线右端 \(\varepsilon = 0.01\)、\(T = 64\) 处两种损失的比值,并与两条参考线之比 \((T+1)/2\) 进行对比。
  2. 作为行为克隆的微调。14.5.4.2 节 将语言模型的监督微调等同于行为克隆:上下文是状态,下一个词元是动作,精选回复是示教。
    1. 14.5.3.1 节 中的命题假设每一步的出错率同为 \(\varepsilon\)。微调后的模型在精选回复上可能保持很小的常数出错率,但在自己生成的回复上,出错率却随位置增加而上升。解释原因,并说明此时命题的哪一部分描述了该模型。
    2. 除了工作量之外,为什么人类不适合作为语言模型 DAgger 的标注来源?同轨策略蒸馏用教师模型的整个下一词元分布(而非单个词元)来标注学生的每个前缀。写出相应的损失函数,并证明当教师模型把全部概率放在单个词元上时,该损失退化为行为克隆损失。
  3. [code] 实现覆盖所需的示教数。● 14.5.2 节 中的覆盖度代码单元构建了湿滑冰湖 mdp_ice 及其最优策略 pi_ice。确定性策略 pi 到达终点的概率即 visitation(mdp_ice, one_hot[pi]) 之后终点的概率质量。
    1. 对每个非终止状态 \(s\),计算“除在 \(s\) 处采取动作 0 外其余均遵循 pi_ice”的策略之成功概率。若该偏离使成功概率降到 pi_ice 的一半以下,则称 \(s\) 为关键状态。哪些状态是关键状态?
    2. 记 \(q_s\) 为单个专家回合访问状态 \(s\) 的概率。利用 visitation 的 absorbing 参数精确计算 \(q_s\):将 \(s\) 设为吸收态并读取 100 步后 \(s\) 处的概率质量。哪个非终止状态满足 \(q_s = 0\)?这对任意规模的专家数据意味着什么?3 个回合的数据集从未访问状态 13 的概率是多少?
    3. 将各关键状态近似视为相互独立,根据它们的 \(q_s\) 预测 \(n \in \{1, 3, 10\}\) 个专家回合漏掉至少一个关键状态的概率,并与代码单元打印的比率对比。该预测偏高还是偏低?这说明不同关键状态的访问之间存在什么关系?
  4. [code] 更长路径上的 DAgger。● 在 \(4 \times 4\) 平静冰湖上,分布偏移约占克隆策略损失的五分之一。在最优路径长达 14 步的 \(8 \times 8\) 平静冰湖 gym.make('FrozenLake-v1', map_name='8x8', is_slippery=False) 上重复本节实验:重建 env、mdp、pi_star、demo_s 和 demo_a,并重新运行本节代码单元。
    1. 计算采样克隆策略的成功概率、它离开专家路径的概率,以及在每个格子上都保持克隆策略误差的学习者之成功概率。克隆策略的损失中有多少比例发生在离开路径之后?又有多少比例能通过路径外标签挽回?为什么前者随路径变长而增大,而后者却不然?
    2. 在 10 个随机种子上运行 DAgger,绘制成功率随专家查询次数的变化曲线,并与使用至少同样多专家标签的行为克隆对比。
    3. 查表策略在每个状态上最多只需要一个标签。统计每轮 DAgger 结束后已标注的不同状态数,并估算如果只在尚无标签的状态上询问专家,需要多少次查询。
  5. DAgger 的理论保证。● 在 Ross 等 (2011年) 的分析中,第 \(i\) 轮的数据收集策略 \(\pi_i\) 在每一步以概率 \(\beta_i\) 采取专家动作,否则采取当前学习者 \(\hat\pi_i\) 的动作。下一轮学习者 \(\hat\pi_{i+1}\) 在第 \(1, \ldots, i\) 轮的聚合数据上最小化损失,正如用 clone 重新拟合一样。记 \(d_\pi = \frac{1}{T}\sum_{t=1}^T d^\pi_t\) 为策略 \(\pi\) 的平均状态分布,令 \(c(s, \pi) \in [0, c_{\max}]\) 为 \(\pi\) 在状态 \(s\) 处的分类损失(例如 \(\mathbf{1}(\pi(s) \neq \pi^*(s))\)),并设 \(c_i(\pi) = \mathbb{E}_{s \sim d_{\pi_i}}[c(s, \pi)]\)。
    1. 证明 \(\|d_{\pi_i} - d_{\hat\pi_i}\|_1 \leq 2\min(1, T\beta_i)\)。
    2. 记 \(\varepsilon_N = \min_\pi \frac{1}{N}\sum_{i=1}^N c_i(\pi)\) 为事后最优策略的损失,并假设学习者序列的平均遗憾不超过 \(\delta_N\): \[\frac{1}{N}\sum_{i=1}^N c_i(\hat\pi_i) - \varepsilon_N \leq \delta_N. \tag{14.5.2}\] 证明序列中必存在某个学习者 \(\hat\pi_j\) 满足 \[\mathbb{E}_{s \sim d_{\hat\pi_j}}[c(s, \hat\pi_j)] \leq \varepsilon_N + \delta_N + \frac{2c_{\max}}{N}\sum_{i=1}^N \min(1, T\beta_i). \tag{14.5.3}\] 原论文定理 4.1 的证明在对最后一项求和做进一步化简前,正是先推导出这一上界。
    3. 14.5.4.1 节 中的循环采用 \(\beta_1 = 1\) 且对 \(i \geq 2\) 取 \(\beta_i = 0\)。将上述上界特化到这一调度与 0-1 损失,并与 14.5.3.1 节 中命题的第(ii)部分结合。要使不含 \(\varepsilon_N\) 与 \(\delta_N\) 的那一项保持有界,\(N\) 必须随 \(T\) 如何增长?
    4. 在打印出的运行结果中,部分种子第一轮后的学习者反而劣于行为克隆。证明仅标注状态 1 会降低平静冰湖克隆策略的精确成功率,并结合专家在状态 1 的动作以及标注前后学习者在状态 1 和 2 上的行分布解释这一下降。要从序列中识别出最佳学习者需要什么条件?
  6. 示教背后的奖励。● 正文是从专家的动作中学习。逆向强化学习(inverse reinforcement learning)则是先推断出使示教成为最优的奖励函数,再利用该奖励进行规划。
    1. 根据 14.2.5 节 中的裂项相消论证,在终止状态满足 \(\Phi = 0\) 的对 \(r\) 的任意基于势能的奖励塑形 \(\tilde r(s, a, s') = r(s, a) + \gamma \Phi(s') - \Phi(s)\) 都保持专家最优。证明零奖励函数同样使专家最优。这两个事实对于从示教中恢复 \(r\) 意味着什么?
    2. 最大熵逆向强化学习 (Ziebart 等 2008年) 将固定起点的确定性回合制任务中的可行轨迹建模为 \(P_\theta(\tau) \propto \exp\big(\sum_t r_\theta(s_t, a_t)\big)\),并通过最大化示教的似然来拟合 \(\theta\)。为什么该准则会排除针对能到达终点的专家的零奖励解?假设每条可行轨迹都终结于终止状态,为什么该准则仍无法区分 \(r\) 与其 \(\gamma = 1\) 的势能塑形?如果轨迹是被时间限制截断的,你论证中的哪一步会失效?

讨论