39.9  实用函数与类

本节汇总本书使用的实用函数与类的具体实现。凡是标有 #@save 的代码单元都会被复制到 d2l 包中,使全书任意章节都能以 d2l.plot、d2l.set_figsize 等形式直接调用。

import collections
import inspect
from IPython import display
from matplotlib import ticker
from matplotlib_inline import backend_inline
import collections
import inspect
from IPython import display
from matplotlib import ticker
from matplotlib_inline import backend_inline
import collections
import inspect
from IPython import display
from matplotlib import ticker
from matplotlib_inline import backend_inline
import collections
import inspect
import random
import sys
from IPython import display
from matplotlib import ticker
from matplotlib_inline import backend_inline

39.9.1 超参数实用工具

@d2l.add_to_class(d2l.HyperParameters)
def save_hyperparameters(self, ignore=None):
    """Save function arguments into instance attributes."""
    ignore = [] if ignore is None else ignore
    frame = inspect.currentframe().f_back
    _, _, _, local_vars = inspect.getargvalues(frame)
    self.hparams = {k:v for k, v in local_vars.items()
                    if k not in set(ignore+['self']) and not k.startswith('_')}
    for k, v in self.hparams.items():
        setattr(self, k, v)

39.9.2 进度展示与绘图

本书大多数曲线图都由 d2l.plot 绘制,用于在同一坐标系中画出一条或多条曲线。第一个代码单元负责设置图像格式与尺寸(use_svg_display、set_figsize)以及坐标轴标签、范围与刻度(set_axes)。在对数坐标轴上,set_log_ticks 以统一格式标注所有主刻度。

def use_svg_display():
    """Use the svg format to display a plot in Jupyter."""
    backend_inline.set_matplotlib_formats('svg')

def set_figsize(figsize=(3.5, 2.5)):
    """Set the figure size for matplotlib."""
    use_svg_display()
    d2l.plt.rcParams['figure.figsize'] = figsize

def set_log_ticks(axis):
    """Label all major ticks of a log axis in one format."""
    lo, hi = axis.get_view_interval()
    if 0 < lo and hi < 100 * lo:  # Under two decades: ticks at 1, 2, 5
        axis.set_major_locator(ticker.LogLocator(subs=(1, 2, 5)))
    ticks = axis.get_major_locator().tick_values(lo, hi)
    plain = all(1e-4 <= t < 1e5 for t in ticks if lo <= t <= hi)

    def label(v, _):
        if plain:  # 0.001, 0.01, ..., 10000
            return f'{v:g}'
        m, k = f'{v:.3e}'.split('e')  # 2.500e-05 -> '2.500', '-05'
        m, power = f'{float(m):g}', f'10^{{{int(k)}}}'  # '2.5', '10^{-5}'
        return f'${power}$' if m == '1' else f'${m}\\times{power}$'

    axis.set_major_formatter(ticker.FuncFormatter(label))
    axis.set_minor_formatter(ticker.NullFormatter())


def set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend,
             legend_loc=None):
    """Set the axes for matplotlib. legend_loc is a matplotlib legend
    location, or 'outside' for beside the axes, clear of the curves."""
    axes.set_xlabel(xlabel), axes.set_ylabel(ylabel)
    axes.set_xscale(xscale), axes.set_yscale(yscale)
    axes.set_xlim(xlim),     axes.set_ylim(ylim)
    for axis, scale in ((axes.xaxis, xscale), (axes.yaxis, yscale)):
        if scale == 'log':
            set_log_ticks(axis)
    if legend and legend_loc == 'outside':
        axes.legend(legend, loc='center left', bbox_to_anchor=(1, 0.5))
    elif legend:
        axes.legend(legend, loc=legend_loc)  # None: matplotlib's best spot
    axes.grid()

plot 的大部分代码用于将不同形式的输入规范化为曲线列表。

def plot(X, Y=None, xlabel=None, ylabel=None, legend=None, xlim=None,
         ylim=None, xscale='linear', yscale='linear',
         fmts=('-', 'm--', 'g-.', 'r:'), figsize=(3.5, 2.5), axes=None,
         legend_loc=None):
    """Plot data points."""
    legend = [] if legend is None else legend

    def has_one_axis(X):  # True if X (tensor or list) has 1 axis
        return (hasattr(X, "ndim") and X.ndim == 1 or isinstance(X, list)
                and not hasattr(X[0], "__len__"))
    
    if has_one_axis(X): X = [X]
    if Y is None:
        X, Y = [[]] * len(X), X
    elif has_one_axis(Y):
        Y = [Y]
    if len(X) != len(Y):
        X = X * len(Y)
        
    set_figsize(figsize)
    if axes is None:
        axes = d2l.plt.gca()
    axes.cla()
    # Extend the formats with new colors so that no curve is dropped
    fmts = list(fmts) + [f'C{i % 10}' + ('-', '--', '-.', ':')[i % 4]
                         for i in range(len(fmts), len(Y))]
    for x, y, fmt in zip(X, Y, fmts):
        axes.plot(x, y, fmt) if len(x) else axes.plot(y, fmt)
    set_axes(axes, xlabel, ylabel, xlim, ylim, xscale, yscale, legend,
             legend_loc)

2.4 节 中的 ProgressBoard 在调用线程上绘图。show 将全部曲线渲染为新图,并在 notebook 输出中替换同一画板的上一帧。在无头模式构建全书时,仅最后一次调用会实际渲染,因此执行后的 notebook 每个画板只保留一张成图。损失曲线画在左轴,准确率画在右侧第二纵轴上;此时图例会自动移至图上方,以免遮挡任一组曲线。验证集数据点以及仅含单点的曲线都会以圆点标出,确保只跑一轮时依然清晰可见。

import os
from matplotlib.figure import Figure

@d2l.add_to_class(d2l.ProgressBoard)
def show(self, final=True):
    """Redraw all curves; the book build renders only the final call."""
    if not self.display or (
            not final and os.environ.get('D2L_NB_CAPTURE') == '1'):
        return
    d2l.use_svg_display()
    fig = Figure(figsize=self.figsize)
    self._plot(fig.add_subplot())
    if self.handle is None:
        self.handle = display.display(fig, display_id=True)
    else:
        self.handle.update(fig)

@d2l.add_to_class(d2l.ProgressBoard)
def _plot(self, ax):
    """Losses on the left axis, accuracies on a right one."""
    acc_ax = None
    for i, (label, (xs, ys)) in enumerate(self.data.items()):
        target = ax
        if label.endswith('acc'):
            acc_ax = acc_ax or ax.twinx()
            target = acc_ax
        # Mark validation points, and any curve that has a single point
        marked = label.startswith('val') or len(xs) == 1
        target.plot(xs, ys, ('-', '--', '-.', ':')[i % 4], color=f'C{i % 10}',
                    marker='o' if marked else None, markersize=3,
                    clip_on=not marked, label=label)
    ax.set_xlabel(self.xlabel), ax.set_ylabel(self.ylabel)
    ax.set_xscale(self.xscale), ax.set_yscale(self.yscale)
    if self.xlim: ax.set_xlim(self.xlim)
    if self.ylim: ax.set_ylim(self.ylim)
    if self.yscale == 'log': d2l.set_log_ticks(ax.yaxis)
    if acc_ax is not None: acc_ax.set_ylabel('accuracy')
    lines = list(ax.get_lines()) + list(acc_ax.get_lines() if acc_ax else [])
    labels = [line.get_label() for line in lines]
    if acc_ax is not None:  # Above the axes: no curve of either axis is hidden
        ax.legend(lines, labels, loc='lower center', ncol=len(lines),
                  bbox_to_anchor=(0.5, 1), frameon=False)
    elif lines:
        ax.legend(lines, labels)
    ax.grid()

show_trace_2d 在目标函数 f 的等高线图上绘制二维更新规则的迭代轨迹(由 9.1 节 的 d2l.train_2d 返回)。视窗覆盖起点 \((-5, -2)\) 与原点处的最小值,并随轨迹自动扩展。除非轨迹沿某一坐标轴发散,两轴始终共享同一比例尺。

show_trace_2d 在目标函数 f 的等高线图上绘制二维更新规则的迭代轨迹(由 9.1 节 的 d2l.train_2d 返回)。视窗覆盖起点 \((-5, -2)\) 与原点处的最小值,并随轨迹自动扩展。除非轨迹沿某一坐标轴发散,两轴始终共享同一比例尺。

def show_trace_2d(f, results):
    """Show the trace of 2D variables over the contours of f."""
    x1s, x2s = zip(*[(float(a), float(b)) for a, b in results])
    grids = []  # A window around start and minimum, widened to fit the trace
    for (lo, hi), xs in zip([(-5.5, 1.0), (-3.0, 3.0)], (x1s, x2s)):
        lo, hi = min(lo, min(xs) - 0.5), max(hi, max(xs) + 0.5)
        grids.append(d2l.arange(lo, hi, (hi - lo) / 100))
    x1, x2 = d2l.meshgrid(*grids, indexing='ij')
    width, height = (float(g[-1] - g[0]) for g in grids)
    equal = 0.25 < height / width < 4  # Equal scales unless the trace diverged
    d2l.set_figsize((3, 2.8) if equal else (3.5, 2.5))
    d2l.plt.contour(x1, x2, f(x1, x2), colors='0.6', linewidths=0.8)
    d2l.plt.plot(x1s, x2s, '-o', color='C1', markersize=4)
    d2l.plt.xlabel('$x_1$')
    d2l.plt.ylabel('$x_2$')
    if equal:
        d2l.plt.gca().set_aspect('equal')
def show_trace_2d(f, results):
    """Show the trace of 2D variables over the contours of f."""
    x1s, x2s = zip(*[(float(a), float(b)) for a, b in results])
    grids = []  # A window around start and minimum, widened to fit the trace
    for (lo, hi), xs in zip([(-5.5, 1.0), (-3.0, 3.0)], (x1s, x2s)):
        lo, hi = min(lo, min(xs) - 0.5), max(hi, max(xs) + 0.5)
        grids.append(d2l.arange(lo, hi, (hi - lo) / 100))
    x1, x2 = d2l.meshgrid(*grids, indexing='ij')
    width, height = (float(g[-1] - g[0]) for g in grids)
    equal = 0.25 < height / width < 4  # Equal scales unless the trace diverged
    d2l.set_figsize((3, 2.8) if equal else (3.5, 2.5))
    d2l.plt.contour(x1, x2, f(x1, x2), colors='0.6', linewidths=0.8)
    d2l.plt.plot(x1s, x2s, '-o', color='C1', markersize=4)
    d2l.plt.xlabel('$x_1$')
    d2l.plt.ylabel('$x_2$')
    if equal:
        d2l.plt.gca().set_aspect('equal')

plot_intervals 绘制带区间的估计值,例如带自助法误差棒的准确率。series 将标签映射到三条与 x 等长的序列:估计值以及区间的下界与上界;nan 会略过对应点。在 kind='errorbar' 模式下,每个估计值显示为带误差棒的标记,且同个 x 处的多条序列并排错开以免互相遮挡;在 kind='band' 模式下,每条序列显示为折线配半透明阴影带。x 可以存放数值或类别名。reference 绘制水平虚线(如随机基线或零线),xscale 接受 'linear'、'log' 或 'log2'。第 \(i\) 条序列使用颜色 Ci,函数返回坐标轴对象以便调用方叠加配套曲线。marks 用于向各序列叠加额外数据点(例如第二个估计量):它将名称映射到 matplotlib 格式(如 '--'、'D')以及各序列标签对应的点集 (xs, ys),按对应序列的颜色绘制并在图例中以黑色列出一次。

def plot_intervals(x, series, xlabel, ylabel, *, kind='errorbar',
                   reference=None, xscale='linear', axes=None, marks=None):
    """Estimates with intervals: `series` maps a label to (mean, lo, hi);
    `marks` maps a name to (fmt, {label: (xs, ys)})."""
    if kind not in ('errorbar', 'band') or xscale not in ('linear', 'log',
                                                          'log2'):
        raise ValueError(f'unknown kind {kind!r} or xscale {xscale!r}')
    x = np.asarray(x)
    categorical = not np.issubdtype(x.dtype, np.number)
    pos = np.arange(len(x), dtype=float) if categorical else x.astype(float)
    logx = xscale != 'linear' and not categorical
    # Side-by-side offsets, in the units in which the x-axis is even
    to_axis, from_axis = (np.log, np.exp) if logx else (np.asarray,) * 2
    gaps = np.diff(np.unique(to_axis(pos)))
    width = 0.6 * (gaps.min() if len(gaps) else 1.0) / len(series)
    if axes is None:
        d2l.set_figsize()
        axes = d2l.plt.gca()
    for i, (label, (mean, lo, hi)) in enumerate(series.items()):
        mean, lo, hi = (np.asarray(v, dtype=float) for v in (mean, lo, hi))
        if not mean.shape == lo.shape == hi.shape == pos.shape:
            raise ValueError(f'{label}: mean, lo and hi need {len(pos)} '
                             'values each')
        err = np.stack([mean - lo, hi - mean])
        if np.any(err < -1e-9):  # nan (a missing point) passes
            raise ValueError(f'{label}: an interval misses its estimate')
        color = f'C{i % 10}'
        if kind == 'band':
            axes.plot(pos, mean, '-', color=color, label=label)
            axes.fill_between(pos, lo, hi, color=color, alpha=0.2,
                              linewidth=0)
        else:
            at = from_axis(to_axis(pos) + (i - (len(series) - 1) / 2) * width)
            axes.errorbar(at, mean, yerr=np.clip(err, 0, None), fmt='o',
                          color=color, markersize=4, capsize=3, label=label)
    for name, (fmt, points) in (marks or {}).items():
        for i, label in enumerate(series):
            if label in points:
                axes.plot(*points[label], fmt, color=f'C{i % 10}')
        axes.plot([], [], fmt, color='black', label=name)  # legend only
    if reference is not None:
        axes.axhline(reference, linestyle='--', color='black', linewidth=0.8)
    if logx:
        axes.set_xscale('log', base=2 if xscale == 'log2' else 10)
    if categorical or logx:  # One tick per x value
        axes.set_xticks(pos, [str(v) if categorical else f'{v:g}' for v in x])
        axes.xaxis.set_minor_locator(ticker.NullLocator())
    if categorical and len(x) > 3:  # Slanted names do not collide
        axes.set_xticklabels(axes.get_xticklabels(), rotation=30, ha='right')
    axes.set_xlabel(xlabel), axes.set_ylabel(ylabel)
    if len(series) > 1 or marks:
        axes.legend()
    axes.grid(axis='y' if categorical else 'both')  # No line through a bar
    return axes

39.9.3 强化学习实用工具

def plot_curves(curves, xlabel, ylabel, smooth=1, reference=None,
                ylim=None, x=None, xscale='linear', yscale='linear',
                band='range'):
    """One panel per call. `curves` maps a label to an array of shape
    [seed, step] (or [step] for a single seed); plots the seed median and a
    shaded band over the seeds: min to max (`band='range'`) or the
    interquartile range (`band='iqr'`, the better summary from five seeds
    on). `smooth`, if greater than 1, replaces each point by the mean of the
    `smooth` steps that end there, before the seed statistics; the first
    `smooth - 1` steps lack a full window and are dropped. `x` gives the
    position of each step (default 0, 1, 2, ...). `reference`, if given,
    draws a dashed horizontal line; `ylim` fixes the y-axis range; `xscale`
    and `yscale` take matplotlib's scale names, e.g. 'log'."""
    set_figsize((6, 4))
    for name, values in curves.items():
        values = np.atleast_2d(values)
        xs = np.arange(values.shape[1]) if x is None else np.asarray(x)
        if smooth > 1:
            kernel = np.ones(smooth) / smooth
            values = np.stack([np.convolve(v, kernel, 'valid')
                               for v in values])
            xs = xs[smooth - 1:]      # each window sits at its last step
        line, = plt.plot(xs, np.median(values, axis=0), label=name)
        if values.shape[0] > 1:
            lo, hi = ((values.min(axis=0), values.max(axis=0))
                      if band == 'range' else
                      np.percentile(values, [25, 75], axis=0))
            plt.fill_between(xs, lo, hi, alpha=0.2, color=line.get_color())
    if reference is not None:
        plt.axhline(reference, linestyle='--', color='gray')
    if ylim is not None:
        plt.ylim(ylim)
    plt.xscale(xscale)
    plt.yscale(yscale)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.legend()

def plot_hist(samples, xlabel, ylabel, bins=60, vlines=()):
    """Overlaid histograms of `samples` (label -> values), dashed at `vlines`."""
    set_figsize((6, 4))
    for name, x in samples.items():
        plt.hist(x, bins=bins, alpha=0.5, label=name)
    for v in vlines:
        plt.axvline(v, linestyle='--', color='black')
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.legend()

def show_grid(desc, values, policy=None, titles=None,
              diverging=False, fmt='{:.2f}'):
    """A gridworld in the style of the chapter's figures. Each cell is
    shaded by `values` (white to blue, or with `diverging=True` red to blue
    around zero, for differences) and shows its state index (top left), its
    value (bottom left) and an arrow for the action of `policy`, if given.
    Holes are grey and the goal green; S, H and G sit at the bottom right.
    The grid shape is read from `desc` (e.g. `env.unwrapped.desc`).
    `values` and `policy` may each be a single frame, shape (num_states,),
    or a sequence of frames, shape (num_frames, num_states); `titles`, if
    given, labels each frame."""
    h, w = desc.shape
    values = np.atleast_2d(values).reshape(-1, h * w)
    if policy is not None:
        policy = np.atleast_2d(policy).reshape(-1, h * w)
    if diverging:
        top = max(np.abs(values).max(), 1e-12)
        cmap, norm = plt.get_cmap('RdBu'), plt.Normalize(-top, top)
    else:
        cmap = plt.get_cmap('Blues')
        norm = plt.Normalize(min(0.0, values.min()),
                             max(values.max(), 1e-12))
    move = {0: (-1, 0), 1: (0, 1), 2: (1, 0), 3: (0, -1)}   # (dx, dy)
    fig, axes = plt.subplots(1, len(values), squeeze=False,
                             figsize=(3.6 * len(values), 3.6))
    for k, ax in enumerate(axes[0]):
        for s in range(h * w):
            y, x = divmod(s, w)
            cell, v = desc[y, x].decode(), values[k, s]
            fill = {'H': ('#565D66', 0.55), 'G': ('#2CA02C', 0.35)}.get(
                cell, (cmap(norm(v)), 1.0))
            ax.add_patch(plt.Rectangle((x, y), 1, 1, fc=fill[0],
                                       alpha=fill[1], ec='black', lw=1.0))
            shade = np.abs(norm(v) - 0.5) * 2 if diverging else norm(v)
            ink = 'white' if cell == 'H' or (cell != 'G' and shade > 0.6) \
                else 'black'
            ax.text(x + 0.07, y + 0.07, str(s), ha='left', va='top',
                    fontsize=9, color=ink)
            if cell not in 'HG' or np.abs(v) > 1e-9:   # terminal: 0
                ax.text(x + 0.07, y + 0.93, fmt.format(v), ha='left',
                        va='bottom', fontsize=10, color=ink)
            if cell in 'SHG':
                ax.text(x + 0.82, y + 0.80, cell, ha='center', va='center',
                        fontsize=13, fontweight='bold', color=ink)
            if policy is not None and cell not in 'HG':
                dx, dy = move[int(policy[k, s])]
                ax.annotate('', xy=(x + 0.5 + 0.22 * dx, y + 0.45 + 0.22 * dy),
                            xytext=(x + 0.5 - 0.22 * dx,
                                    y + 0.45 - 0.22 * dy),
                            arrowprops=dict(arrowstyle='-|>', color=ink,
                                            lw=1.6, mutation_scale=14))
        ax.set_xlim(0, w)
        ax.set_ylim(h, 0)
        ax.set_aspect('equal')
        ax.axis('off')
        if titles is not None:
            ax.set_title(titles[k])
    fig.tight_layout()

def run_seeds(train, num_seeds, **kwargs):
    """Run train(seed, **kwargs), a generator of curve points, per seed."""
    return np.array([list(train(seed, **kwargs)) for seed in range(num_seeds)])

def on_grid(runs, grid, col, smooth=1):
    """Resample per-episode rows (env step, value, ...) onto an env-step
    grid. For each run, drop the rows whose column `col` is NaN, average
    the column over the last `smooth` episodes, and interpolate linearly at
    the grid points; returns [run, grid point], the input of plot_curves."""
    out = []
    for r in runs:
        r = np.asarray(r, dtype=float)
        r = r[~np.isnan(r[:, col])]
        v = np.convolve(r[:, col], np.ones(smooth) / smooth, 'valid')
        out.append(np.interp(grid, r[smooth - 1:, 0], v))
    return np.stack(out)

def plot_curves(curves, xlabel, ylabel, smooth=1, reference=None,
                ylim=None, x=None, xscale='linear', yscale='linear',
                band='range'):
    """One panel per call. `curves` maps a label to an array of shape
    [seed, step] (or [step] for a single seed); plots the seed median and a
    shaded band over the seeds: min to max (`band='range'`) or the
    interquartile range (`band='iqr'`, the better summary from five seeds
    on). `smooth`, if greater than 1, replaces each point by the mean of the
    `smooth` steps that end there, before the seed statistics; the first
    `smooth - 1` steps lack a full window and are dropped. `x` gives the
    position of each step (default 0, 1, 2, ...). `reference`, if given,
    draws a dashed horizontal line; `ylim` fixes the y-axis range; `xscale`
    and `yscale` take matplotlib's scale names, e.g. 'log'."""
    set_figsize((6, 4))
    for name, values in curves.items():
        values = np.atleast_2d(values)
        xs = np.arange(values.shape[1]) if x is None else np.asarray(x)
        if smooth > 1:
            kernel = np.ones(smooth) / smooth
            values = np.stack([np.convolve(v, kernel, 'valid')
                               for v in values])
            xs = xs[smooth - 1:]      # each window sits at its last step
        line, = plt.plot(xs, np.median(values, axis=0), label=name)
        if values.shape[0] > 1:
            lo, hi = ((values.min(axis=0), values.max(axis=0))
                      if band == 'range' else
                      np.percentile(values, [25, 75], axis=0))
            plt.fill_between(xs, lo, hi, alpha=0.2, color=line.get_color())
    if reference is not None:
        plt.axhline(reference, linestyle='--', color='gray')
    if ylim is not None:
        plt.ylim(ylim)
    plt.xscale(xscale)
    plt.yscale(yscale)
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.legend()

def plot_hist(samples, xlabel, ylabel, bins=60, vlines=()):
    """Overlaid histograms of `samples` (label -> values), dashed at `vlines`."""
    set_figsize((6, 4))
    for name, x in samples.items():
        plt.hist(x, bins=bins, alpha=0.5, label=name)
    for v in vlines:
        plt.axvline(v, linestyle='--', color='black')
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.legend()

def show_grid(desc, values, policy=None, titles=None,
              diverging=False, fmt='{:.2f}'):
    """A gridworld in the style of the chapter's figures. Each cell is
    shaded by `values` (white to blue, or with `diverging=True` red to blue
    around zero, for differences) and shows its state index (top left), its
    value (bottom left) and an arrow for the action of `policy`, if given.
    Holes are grey and the goal green; S, H and G sit at the bottom right.
    The grid shape is read from `desc` (e.g. `env.unwrapped.desc`).
    `values` and `policy` may each be a single frame, shape (num_states,),
    or a sequence of frames, shape (num_frames, num_states); `titles`, if
    given, labels each frame."""
    h, w = desc.shape
    values = np.atleast_2d(values).reshape(-1, h * w)
    if policy is not None:
        policy = np.atleast_2d(policy).reshape(-1, h * w)
    if diverging:
        top = max(np.abs(values).max(), 1e-12)
        cmap, norm = plt.get_cmap('RdBu'), plt.Normalize(-top, top)
    else:
        cmap = plt.get_cmap('Blues')
        norm = plt.Normalize(min(0.0, values.min()),
                             max(values.max(), 1e-12))
    move = {0: (-1, 0), 1: (0, 1), 2: (1, 0), 3: (0, -1)}   # (dx, dy)
    fig, axes = plt.subplots(1, len(values), squeeze=False,
                             figsize=(3.6 * len(values), 3.6))
    for k, ax in enumerate(axes[0]):
        for s in range(h * w):
            y, x = divmod(s, w)
            cell, v = desc[y, x].decode(), values[k, s]
            fill = {'H': ('#565D66', 0.55), 'G': ('#2CA02C', 0.35)}.get(
                cell, (cmap(norm(v)), 1.0))
            ax.add_patch(plt.Rectangle((x, y), 1, 1, fc=fill[0],
                                       alpha=fill[1], ec='black', lw=1.0))
            shade = np.abs(norm(v) - 0.5) * 2 if diverging else norm(v)
            ink = 'white' if cell == 'H' or (cell != 'G' and shade > 0.6) \
                else 'black'
            ax.text(x + 0.07, y + 0.07, str(s), ha='left', va='top',
                    fontsize=9, color=ink)
            if cell not in 'HG' or np.abs(v) > 1e-9:   # terminal: 0
                ax.text(x + 0.07, y + 0.93, fmt.format(v), ha='left',
                        va='bottom', fontsize=10, color=ink)
            if cell in 'SHG':
                ax.text(x + 0.82, y + 0.80, cell, ha='center', va='center',
                        fontsize=13, fontweight='bold', color=ink)
            if policy is not None and cell not in 'HG':
                dx, dy = move[int(policy[k, s])]
                ax.annotate('', xy=(x + 0.5 + 0.22 * dx, y + 0.45 + 0.22 * dy),
                            xytext=(x + 0.5 - 0.22 * dx,
                                    y + 0.45 - 0.22 * dy),
                            arrowprops=dict(arrowstyle='-|>', color=ink,
                                            lw=1.6, mutation_scale=14))
        ax.set_xlim(0, w)
        ax.set_ylim(h, 0)
        ax.set_aspect('equal')
        ax.axis('off')
        if titles is not None:
            ax.set_title(titles[k])
    fig.tight_layout()

def run_seeds(train, num_seeds, **kwargs):
    """Run train(seed, **kwargs), a generator of curve points, per seed."""
    return np.array([list(train(seed, **kwargs)) for seed in range(num_seeds)])

def on_grid(runs, grid, col, smooth=1):
    """Resample per-episode rows (env step, value, ...) onto an env-step
    grid. For each run, drop the rows whose column `col` is NaN, average
    the column over the last `smooth` episodes, and interpolate linearly at
    the grid points; returns [run, grid point], the input of plot_curves."""
    out = []
    for r in runs:
        r = np.asarray(r, dtype=float)
        r = r[~np.isnan(r[:, col])]
        v = np.convolve(r[:, col], np.ones(smooth) / smooth, 'valid')
        out.append(np.interp(grid, r[smooth - 1:, 0], v))
    return np.stack(out)

run_seeds 按每个随机种子运行一次训练生成器,并将产出的曲线堆叠为形状 (seed, step, …) 的单个数组,作为 plot_curves 的标准输入。离策略智能体每回合汇报一次,不同种子完成的回合数各不相同;on_grid 将这类按回合记录的数据插值到统一的环境步网格上,使其同样能够堆叠绘图。

run_seeds 按每个随机种子运行一次训练生成器,并将产出的曲线堆叠为形状 (seed, step, …) 的单个数组,作为 plot_curves 的标准输入。离策略智能体每回合汇报一次,不同种子完成的回合数各不相同;on_grid 将这类按回合记录的数据插值到统一的环境步网格上,使其同样能够堆叠绘图。

强化学习智能体的 JAX 实现每次只对单个状态采取动作,而在长度逐批变化的批量上执行更新。编译代码以网络结构、输入形状与优化器为键,因此我们用三个辅助工具将编译次数压到最低。forward_np 为每种网络结构只编译一次前向传播,每次调用读取网络当前参数,避免优化器更新触发重编译。_pad 与 _bucket 将批量填充到下一个 2 的幂(至少 64 行),使同一份编译更新可跨不同批量长度复用;padded 将同一批量的多个数组一起填充,并附带标记真实行的掩码,使更新在求均值时排除填充行。shared_adam 为每个学习率维护一个共享的 optax.adam,使相同学习率的智能体复用编译后的更新;plain_sgd 对部分实验用于替代 Adam 的朴素 SGD 做同样处理。

def plain_sgd(net, lr):
    """A plain SGD optimizer over the parameters of `net`."""
    return torch.optim.SGD(net.parameters(), lr=lr)

_forwards = {}                          # one compiled forward per net structure


import weakref
_splits = weakref.WeakKeyDictionary()  # per net: its forward and variables

def forward_np(net, x):
    """net(x) for numpy x, as numpy, through one compiled forward per net
    structure and input shape. The net is split once and its variables are
    kept, so each call reads their current values: optimizer steps show up
    without splitting again."""
    if net not in _splits:
        graph, state = nnx.split(net)
        tree = jax.tree.structure(state)
        if (graph, tree) not in _forwards:
            _forwards[graph, tree] = jax.jit(lambda leaves, x: nnx.merge(
                graph, jax.tree.unflatten(tree, leaves))(x))
        _splits[net] = _forwards[graph, tree], jax.tree.leaves(
            state, is_leaf=lambda v: isinstance(v, nnx.Variable))
    forward, variables = _splits[net]
    leaves = [v.get_raw_value() for v in variables]
    return jax.tree.map(np.asarray, forward(leaves, x))

def _pad(x, size):
    """Zero-pad axis 0 of an array to `size` rows."""
    x = np.asarray(x)
    return np.pad(x, ((0, size - len(x)),) + ((0, 0),) * (x.ndim - 1))

def _bucket(n):
    """Padded batch length: the next power of two, at least 64, so that a
    compiled pass is reused across batches of different lengths."""
    return 1 << max(6, (n - 1).bit_length())

def padded(*arrays):
    """The arrays zero-padded along axis 0 to a shared bucket length, plus a
    0/1 mask of the real rows, so that one compiled pass serves every batch
    length."""
    n = len(arrays[0])
    size = _bucket(n)
    mask = (np.arange(size) < n).astype(np.float32)
    return (*(_pad(x, size) for x in arrays), mask)


_adams = {}

def shared_adam(lr):
    """One optax.adam per learning rate, shared by all agents: compiled
    updates are keyed on the optimizer, so a new agent reuses the compiled
    code instead of compiling it again."""
    return _adams.setdefault(lr, optax.adam(lr))


_sgds = {}

def plain_sgd(net, lr):
    """A plain SGD optimizer over `net`, one optax.sgd per learning rate."""
    return nnx.Optimizer(net, _sgds.setdefault(lr, optax.sgd(lr)),
                         wrt=nnx.Param)

39.9.4 用于图像评分的特征网络

生成模型章节借助一个小型 CIFAR-10 分类器的特征为生成图像打分(16.5 节)。load_cifar10_arrays 返回缩放到 \([-1, 1]\) 的 CIFAR-10 训练集、测试集图像及其标签。FeatureCNN 是一个包含三个卷积块的分类器(每块含批量规范化、ReLU 与 \(2 \times 2\) 最大汇聚),后接全局平均汇聚与线性输出头;其 features 方法返回汇聚后的特征,resolution 参数设定输入先缩放到的目标尺寸(缩小时自动做低通滤波)。train_feature_cnn 在随机水平翻转与可选随机平移增强下,使用 Adam 配合单周期学习率调度对其进行训练。

生成模型章节借助一个小型 CIFAR-10 分类器的特征为生成图像打分(16.5 节)。load_cifar10_arrays 返回缩放到 \([-1, 1]\) 的 CIFAR-10 训练集、测试集图像及其标签。FeatureCNN 是一个包含三个卷积块的分类器(每块含批量规范化、ReLU 与 \(2 \times 2\) 最大汇聚),后接全局平均汇聚与线性输出头;其 features 方法返回汇聚后的特征,resolution 参数设定输入先缩放到的目标尺寸(缩小时自动做低通滤波)。train_feature_cnn 在随机水平翻转与可选随机平移增强下,使用 Adam 配合单周期学习率调度对其进行训练。

def load_cifar10_arrays():
    """CIFAR-10 on the GPU if there is one, pixel values scaled to [-1, 1].
    Returns train_X, train_y, test_X, test_y."""
    import pickle, warnings  # not in the d2l library preamble
    d2l.DATA_HUB['cifar10'] = (
        'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',
        '874905e36347c8536514d0a26261acf3bff89bc7')
    cifar_dir = d2l.download_extract('cifar10', 'cifar-10-batches-py')
    def load_batch(name):
        with open(f'{cifar_dir}/{name}', 'rb') as f, warnings.catch_warnings():
            warnings.simplefilter('ignore')   # legacy NumPy pickle format
            batch = pickle.load(f, encoding='bytes')
        X = torch.tensor(batch[b'data'], dtype=torch.float32)
        return X.reshape(-1, 3, 32, 32) / 127.5 - 1, torch.tensor(
            batch[b'labels'])
    Xs, ys = zip(*[load_batch(f'data_batch_{i}') for i in range(1, 6)])
    test_X, test_y = load_batch('test_batch')
    device = d2l.try_gpu()
    return (torch.cat(Xs).to(device), torch.cat(ys).to(device),
            test_X.to(device), test_y.to(device))


class FeatureCNN(nn.Module):
    """Three conv blocks, global average pooling, and a linear head. Inputs
    are first resized bilinearly to resolution x resolution."""
    def __init__(self, feature_dim=128, resolution=32):
        super().__init__()
        self.resolution = resolution
        widths = [3, 32, 64, feature_dim]
        self.blocks = nn.ModuleList(
            [nn.Sequential(nn.Conv2d(c_in, c_out, 3, padding=1),
                           nn.BatchNorm2d(c_out), nn.ReLU(),
                           nn.MaxPool2d(2))
             for c_in, c_out in zip(widths[:-1], widths[1:])])
        self.head = nn.Linear(feature_dim, 10)

    def features(self, x):
        if x.shape[-1] != self.resolution:
            x = F.interpolate(x, size=(self.resolution, self.resolution),
                              mode='bilinear', antialias=True)
        for block in self.blocks:
            x = block(x)
        return x.mean(dim=(2, 3))

    def forward(self, x):
        return self.head(self.features(x))


def train_feature_cnn(cnn, X, y, num_epochs=15, max_lr=0.003,
                      batch_size=256, shift=0, seed=0):
    """Train on random horizontal flips, plus random shifts of up to `shift`
    pixels, with a one-cycle learning rate; end in evaluation mode."""
    gen = torch.Generator(X.device).manual_seed(seed)  # local random streams
    gen_shift = torch.Generator().manual_seed(seed)
    opt = torch.optim.Adam(cnn.parameters())
    sched = torch.optim.lr_scheduler.OneCycleLR(
        opt, max_lr, total_steps=num_epochs * (len(X) // batch_size),
        cycle_momentum=False)
    h, w = X.shape[2:]
    cnn.train()
    for epoch in range(num_epochs):
        order = torch.randperm(len(X), device=X.device, generator=gen)
        for i in range(0, len(order) - batch_size + 1, batch_size):
            Xb, yb = X[order[i:i + batch_size]], y[order[i:i + batch_size]]
            flip = torch.rand(len(Xb), 1, 1, 1, device=X.device,
                              generator=gen) < 0.5
            Xb = torch.where(flip, Xb.flip(-1), Xb)
            a, b = torch.randint(0, 2 * shift + 1, (2,),
                                 generator=gen_shift).tolist()
            Xb = F.pad(Xb, (shift,) * 4, mode='reflect')[..., a:a + h, b:b + w]
            loss = F.cross_entropy(cnn(Xb), yb)
            opt.zero_grad(), loss.backward(), opt.step(), sched.step()
    cnn.eval()

def load_cifar10_arrays():
    """CIFAR-10 on the default device, pixel values scaled to [-1, 1].
    Returns train_X, train_y, test_X, test_y."""
    import pickle, warnings  # not in the d2l library preamble
    d2l.DATA_HUB['cifar10'] = (
        'https://www.cs.toronto.edu/~kriz/cifar-10-python.tar.gz',
        '874905e36347c8536514d0a26261acf3bff89bc7')
    cifar_dir = d2l.download_extract('cifar10', 'cifar-10-batches-py')
    def load_batch(name):
        with open(f'{cifar_dir}/{name}', 'rb') as f, warnings.catch_warnings():
            warnings.simplefilter('ignore')   # legacy NumPy pickle format
            batch = pickle.load(f, encoding='bytes')
        X = batch[b'data'].reshape(-1, 3, 32, 32).transpose(0, 2, 3, 1)
        return (jnp.asarray(X, dtype=jnp.float32) / 127.5 - 1,
                jnp.asarray(batch[b'labels']))
    Xs, ys = zip(*[load_batch(f'data_batch_{i}') for i in range(1, 6)])
    test_X, test_y = load_batch('test_batch')
    return jnp.concatenate(Xs), jnp.concatenate(ys), test_X, test_y


class FeatureCNN(nnx.Module):
    """Three conv blocks, global average pooling, and a linear head. Inputs
    are first resized bilinearly to resolution x resolution."""
    def __init__(self, feature_dim=128, resolution=32, rngs=None):
        rngs = nnx.Rngs(d2l.get_key()) if rngs is None else rngs
        self.resolution = resolution
        widths = [3, 32, 64, feature_dim]
        # Weights and biases from U(+-1/sqrt(fan_in)); with Flax's default
        # initialization the same images score FDs about 15% lower
        self.convs = nnx.List(
            [d2l.Conv(c_in, c_out, (3, 3), padding='SAME', rngs=rngs)
             for c_in, c_out in zip(widths[:-1], widths[1:])])
        # Running averages decay 0.9; the variance is computed in two passes
        self.norms = nnx.List([nnx.BatchNorm(c, momentum=0.9,
                                             use_fast_variance=False,
                                             rngs=rngs)
                               for c in widths[1:]])
        self.head = d2l.Linear(feature_dim, 10, rngs=rngs)

    def features(self, x):
        if x.shape[1] != self.resolution:
            x = jax.image.resize(
                x, (x.shape[0], self.resolution, self.resolution, x.shape[3]),
                method='bilinear')
        for conv, norm in zip(self.convs, self.norms):
            x = nnx.max_pool(nnx.relu(norm(conv(x))),
                             window_shape=(2, 2), strides=(2, 2))
        return x.mean(axis=(1, 2))

    def __call__(self, x):
        return self.head(self.features(x))


def train_feature_cnn(cnn, X, y, num_epochs=15, max_lr=0.003,
                      batch_size=256, shift=0, seed=0):
    """Train on random horizontal flips, plus random shifts of up to `shift`
    pixels, with a one-cycle learning rate; end in evaluation mode."""
    schedule = optax.cosine_onecycle_schedule(
        num_epochs * (len(X) // batch_size), max_lr)
    opt = nnx.Optimizer(cnn, optax.adam(schedule), wrt=nnx.Param)
    h, w = X.shape[1:3]

    @nnx.jit
    def step(cnn, opt, Xb, yb, key):
        k1, k2 = jax.random.split(key)
        flip = jax.random.bernoulli(k1, 0.5, (len(Xb), 1, 1, 1))
        Xb = jnp.where(flip, Xb[:, :, ::-1], Xb)
        a, b = jax.random.randint(k2, (2,), 0, 2 * shift + 1)
        Xb = jnp.pad(Xb, ((0, 0), (shift, shift), (shift, shift), (0, 0)),
                     mode='reflect')
        Xb = jax.lax.dynamic_slice(Xb, (0, a, b, 0), (len(Xb), h, w, 3))
        def loss_fn(cnn):
            return optax.softmax_cross_entropy_with_integer_labels(
                cnn(Xb), yb).mean()
        opt.update(cnn, nnx.grad(loss_fn)(cnn))

    cnn.train()
    key = jax.random.key(seed)
    for epoch in range(num_epochs):
        key, kp = jax.random.split(key)
        order = jax.random.permutation(kp, len(X))
        for i in range(0, len(order) - batch_size + 1, batch_size):
            key, ka = jax.random.split(key)
            idx = order[i:i + batch_size]
            step(cnn, opt, X[idx], y[idx], ka)
    cnn.eval()

39.9.5 训练实用工具

以下旧版辅助函数为保持向后兼容而保留:

def load_array(data_arrays, batch_size, is_train=True):
    """Construct a PyTorch data iterator."""
    dataset = torch.utils.data.TensorDataset(*data_arrays)
    return torch.utils.data.DataLoader(dataset, batch_size, shuffle=is_train)

def sgd(params, lr, batch_size):
    """Minibatch stochastic gradient descent."""
    with torch.no_grad():
        for param in params:
            param -= lr * param.grad / batch_size
            param.grad.zero_()

def get_dataloader_workers():
    """Use 4 processes to read the data."""
    return 4

def load_data_fashion_mnist(batch_size, resize=None):
    """Download the Fashion-MNIST dataset and then load it into memory."""
    trans = [transforms.ToTensor()]
    if resize:
        trans.insert(0, transforms.Resize(resize))
    trans = transforms.Compose(trans)
    mnist_train = torchvision.datasets.FashionMNIST(
        root="../data", train=True, transform=trans, download=True)
    mnist_test = torchvision.datasets.FashionMNIST(
        root="../data", train=False, transform=trans, download=True)
    return (torch.utils.data.DataLoader(mnist_train, batch_size, shuffle=True,
                                        num_workers=get_dataloader_workers()),
            torch.utils.data.DataLoader(mnist_test, batch_size, shuffle=False,
                                        num_workers=get_dataloader_workers()))

def evaluate_accuracy_gpu(net, data_iter, device=None):
    """Compute the accuracy for a model on a dataset using a GPU."""
    if isinstance(net, nn.Module):
        net.eval()  # Set the model to evaluation mode
        if not device:
            device = next(iter(net.parameters())).device
    # No. of correct predictions, no. of predictions
    metric = d2l.Accumulator(2)

    with torch.no_grad():
        for X, y in data_iter:
            if isinstance(X, list):
                # Required for BERT Fine-tuning (to be covered later)
                X = [x.to(device) for x in X]
            else:
                X = X.to(device)
            y = y.to(device)
            metric.add(d2l.accuracy(net(X), y), d2l.size(y))
    return metric[0] / metric[1]


def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
    """Train a model with a GPU (defined in Chapter 6)."""
    def init_weights(m):
        if type(m) == nn.Linear or type(m) == nn.Conv2d:
            nn.init.xavier_uniform_(m.weight)
    net.apply(init_weights)
    print('training on', device)
    net.to(device)
    optimizer = torch.optim.SGD(net.parameters(), lr=lr)
    loss = nn.CrossEntropyLoss()
    animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
                            legend=['train loss', 'train acc', 'test acc'])
    timer, num_batches = d2l.Timer(), len(train_iter)
    for epoch in range(num_epochs):
        # Sum of training loss, sum of training accuracy, no. of examples
        metric = d2l.Accumulator(3)
        net.train()
        for i, (X, y) in enumerate(train_iter):
            timer.start()
            optimizer.zero_grad()
            X, y = X.to(device), y.to(device)
            y_hat = net(X)
            l = loss(y_hat, y)
            l.backward()
            optimizer.step()
            with torch.no_grad():
                metric.add(l * X.shape[0], d2l.accuracy(y_hat, y), X.shape[0])
            timer.stop()
            train_l = metric[0] / metric[2]
            train_acc = metric[1] / metric[2]
            if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
                animator.add(epoch + (i + 1) / num_batches,
                             (train_l, train_acc, None))
        test_acc = evaluate_accuracy_gpu(net, test_iter)
        animator.add(epoch + 1, (None, None, test_acc))
    print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
          f'test acc {test_acc:.3f}')
    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
          f'on {str(device)}')

def load_array(data_arrays, batch_size, is_train=True):
    """Construct a TensorFlow data iterator."""
    dataset = tf.data.Dataset.from_tensor_slices(data_arrays)
    if is_train:
        dataset = dataset.shuffle(buffer_size=1000)
    dataset = dataset.batch(batch_size)
    return dataset


def sgd(params, grads, lr, batch_size):
    """Minibatch stochastic gradient descent."""
    for param, grad in zip(params, grads):
        param.assign_sub(lr * grad / batch_size)

def load_data_fashion_mnist(batch_size, resize=None):
    """Download the Fashion-MNIST dataset and then load it into memory."""
    mnist_train, mnist_test = tf.keras.datasets.fashion_mnist.load_data()
    # Divide all numbers by 255 so that all pixel values are between
    # 0 and 1, add a batch dimension at the last. And cast label to int32
    process = lambda X, y: (tf.expand_dims(X, axis=3) / 255,
                            tf.cast(y, dtype='int32'))
    resize_fn = lambda X, y: (
        tf.image.resize_with_pad(X, resize, resize) if resize else X, y)
    return (
        tf.data.Dataset.from_tensor_slices(process(*mnist_train)).batch(
            batch_size).shuffle(len(mnist_train[0])).map(resize_fn),
        tf.data.Dataset.from_tensor_slices(process(*mnist_test)).batch(
            batch_size).map(resize_fn))

class TrainCallback(tf.keras.callbacks.Callback):
    """A callback to visualize the training progress."""
    def __init__(self, net, train_iter, test_iter, num_epochs, device_name):
        self.timer = d2l.Timer()
        self.animator = d2l.Animator(
            xlabel='epoch', xlim=[1, num_epochs], legend=[
                'train loss', 'train acc', 'test acc'])
        self.net = net
        self.train_iter = train_iter
        self.test_iter = test_iter
        self.num_epochs = num_epochs
        self.device_name = device_name
    def on_epoch_begin(self, epoch, logs=None):
        self.timer.start()
    def on_epoch_end(self, epoch, logs):
        self.timer.stop()
        test_acc = self.net.evaluate(
            self.test_iter, verbose=0, return_dict=True)['accuracy']
        metrics = (logs['loss'], logs['accuracy'], test_acc)
        self.animator.add(epoch + 1, metrics)
        if epoch == self.num_epochs - 1:
            batch_size = next(iter(self.train_iter))[0].shape[0]
            num_examples = batch_size * tf.data.experimental.cardinality(
                self.train_iter).numpy()
            print(f'loss {metrics[0]:.3f}, train acc {metrics[1]:.3f}, '
                  f'test acc {metrics[2]:.3f}')
            print(f'{num_examples / self.timer.avg():.1f} examples/sec on '
                  f'{str(self.device_name)}')


def train_ch6(net_fn, train_iter, test_iter, num_epochs, lr, device):
    """Train a model with a GPU (defined in Chapter 6)."""
    device_name = device._device_name
    strategy = tf.distribute.OneDeviceStrategy(device_name)
    with strategy.scope():
        optimizer = tf.keras.optimizers.SGD(learning_rate=lr)
        loss = tf.keras.losses.SparseCategoricalCrossentropy(from_logits=True)
        net = net_fn()
        net.compile(optimizer=optimizer, loss=loss, metrics=['accuracy'])
    callback = TrainCallback(net, train_iter, test_iter, num_epochs,
                             device_name)
    net.fit(train_iter, epochs=num_epochs, verbose=0, callbacks=[callback])
    return net

def linreg(X, w, b):
    """The linear regression model."""
    return d2l.matmul(X, w) + b

def squared_loss(y_hat, y):
    """Squared loss."""
    return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2

class ArrayDataLoader(d2l.ArrayLoader):
    """`d2l.ArrayLoader` that yields JAX arrays and also accepts a dataset.

    Pass the arrays as positional arguments, or one dataset object with
    `__len__` and `__getitem__` whose items are tuples of fields. Like
    `d2l.ArrayLoader`, it keeps the last, partial minibatch unless
    `drop_last=True`."""
    def __init__(self, *args, batch_size=32, shuffle=False, drop_last=False):
        if len(args) == 1 and not hasattr(args[0], 'shape'):  # A dataset
            items = [args[0][i] for i in range(len(args[0]))]
            if isinstance(items[0], (tuple, list)):
                args = tuple(np.array([item[j] for item in items])
                             for j in range(len(items[0])))
            else:
                args = (np.array(items),)
        super().__init__(args, batch_size, shuffle=shuffle,
                         drop_last=drop_last)

    def __iter__(self):
        for batch in super().__iter__():
            yield tuple(jnp.asarray(a) for a in batch)

def load_array(data_arrays, batch_size, is_train=True):
    """Minibatches of JAX arrays, reshuffled each pass if is_train."""
    return d2l.ArrayDataLoader(*data_arrays, batch_size=batch_size,
                               shuffle=is_train)

class Animator:
    """For plotting data in animation."""
    def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
                 ylim=None, xscale='linear', yscale='linear',
                 fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
                 figsize=(3.5, 2.5)):
        if legend is None:
            legend = []
        d2l.use_svg_display()
        self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
        if nrows * ncols == 1:
            self.axes = [self.axes, ]
        self.config_axes = lambda: d2l.set_axes(
            self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
        self.X, self.Y, self.fmts = None, None, fmts

    def add(self, x, y):
        if not hasattr(y, "__len__"):
            y = [y]
        n = len(y)
        if not hasattr(x, "__len__"):
            x = [x] * n
        if not self.X:
            self.X = [[] for _ in range(n)]
        if not self.Y:
            self.Y = [[] for _ in range(n)]
        for i, (a, b) in enumerate(zip(x, y)):
            if a is not None and b is not None:
                self.X[i].append(a)
                self.Y[i].append(b)
        self.axes[0].cla()
        for x, y, fmt in zip(self.X, self.Y, self.fmts):
            self.axes[0].plot(x, y, fmt)
        self.config_axes()
        display.display(self.fig)
        display.clear_output(wait=True)

class Accumulator:
    """For accumulating sums over `n` variables."""
    def __init__(self, n):
        self.data = [0.0] * n

    def add(self, *args):
        self.data = [a + float(b) for a, b in zip(self.data, args)]

    def reset(self):
        self.data = [0.0] * len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]

def tokenize(lines, token='word'):
    """Split text lines into word or character tokens."""
    assert token in ('word', 'char'), 'Unknown token type: ' + token
    return [line.split() if token == 'word' else list(line) for line in lines]

def truncate_pad(line, num_steps, padding_token):
    """Truncate or pad sequences."""
    if len(line) > num_steps:
        return line[:num_steps]
    return line + [padding_token] * (num_steps - len(line))

def download_extract(name, folder=None):
    """Download and extract a zip/tar file."""
    fname = download(name)
    base_dir = os.path.dirname(fname)
    data_dir, ext = os.path.splitext(fname)
    target = os.path.join(base_dir, folder) if folder else data_dir
    marker = fname + '.extracted'
    if os.path.exists(marker):
        return target
    if ext == '.zip':
        fp = zipfile.ZipFile(fname, 'r')
    elif ext in ('.tar', '.gz'):
        fp = tarfile.open(fname, 'r')
    else:
        assert False, 'Only zip/tar files can be extracted.'
    fp.extractall(base_dir)
    open(marker, 'w').close()
    return target

def evaluate_loss(net, data_iter, loss):
    """Evaluate the loss of a model on the given dataset."""
    metric = d2l.Accumulator(2)
    for X, y in data_iter:
        out = net(X)
        y = d2l.reshape(y, out.shape)
        l = loss(out, y)
        metric.add(d2l.reduce_sum(l), d2l.size(l))
    return metric[0] / metric[1]
def load_array(data_arrays, batch_size, is_train=True):
    """Construct a Gluon data iterator."""
    dataset = gluon.data.ArrayDataset(*data_arrays)
    return gluon.data.DataLoader(dataset, batch_size, shuffle=is_train)

def sgd(params, lr, batch_size):
    """Minibatch stochastic gradient descent."""
    for param in params:
        param[:] = param - lr * param.grad / batch_size

def get_dataloader_workers():
    """Use 4 processes to read the data except for Windows."""
    return 0 if sys.platform.startswith('win') else 4

def load_data_fashion_mnist(batch_size, resize=None):
    """Download the Fashion-MNIST dataset and then load it into memory."""
    dataset = gluon.data.vision
    trans = [dataset.transforms.ToTensor()]
    if resize:
        trans.insert(0, dataset.transforms.Resize(resize))
    trans = dataset.transforms.Compose(trans)
    mnist_train = dataset.FashionMNIST(train=True).transform_first(trans)
    mnist_test = dataset.FashionMNIST(train=False).transform_first(trans)
    return (gluon.data.DataLoader(mnist_train, batch_size, shuffle=True,
                                  num_workers=get_dataloader_workers()),
            gluon.data.DataLoader(mnist_test, batch_size, shuffle=False,
                                  num_workers=get_dataloader_workers()))

def evaluate_accuracy_gpu(net, data_iter, device=None):
    """Compute the accuracy for a model on a dataset using a GPU."""
    if not device:  # Query the first device where the first parameter is on
        device = list(net.collect_params().values())[0].list_device()[0]
    # No. of correct predictions, no. of predictions
    metric = d2l.Accumulator(2)
    for X, y in data_iter:
        X, y = X.to_device(device), y.to_device(device)
        metric.add(d2l.accuracy(net(X), y), d2l.size(y))
    return metric[0] / metric[1]


def train_ch6(net, train_iter, test_iter, num_epochs, lr, device):
    """Train a model with a GPU (defined in Chapter 6)."""
    net.initialize(force_reinit=True, device=device, init=init.Xavier())
    loss = gluon.loss.SoftmaxCrossEntropyLoss()
    trainer = gluon.Trainer(net.collect_params(),
                            'sgd', {'learning_rate': lr})
    animator = d2l.Animator(xlabel='epoch', xlim=[1, num_epochs],
                            legend=['train loss', 'train acc', 'test acc'])
    timer, num_batches = d2l.Timer(), len(train_iter)
    for epoch in range(num_epochs):
        # Sum of training loss, sum of training accuracy, no. of examples
        metric = d2l.Accumulator(3)
        for i, (X, y) in enumerate(train_iter):
            timer.start()
            # Here is the major difference from `d2l.train_epoch_ch3`
            X, y = X.to_device(device), y.to_device(device)
            with autograd.record():
                y_hat = net(X)
                l = loss(y_hat, y)
            l.backward()
            trainer.step(X.shape[0])
            metric.add(l.sum(), d2l.accuracy(y_hat, y), X.shape[0])
            timer.stop()
            train_l = metric[0] / metric[2]
            train_acc = metric[1] / metric[2]
            if (i + 1) % (num_batches // 5) == 0 or i == num_batches - 1:
                animator.add(epoch + (i + 1) / num_batches,
                             (train_l, train_acc, None))
        test_acc = evaluate_accuracy_gpu(net, test_iter)
        animator.add(epoch + 1, (None, None, test_acc))
    print(f'loss {train_l:.3f}, train acc {train_acc:.3f}, '
          f'test acc {test_acc:.3f}')
    print(f'{metric[2] * num_epochs / timer.sum():.1f} examples/sec '
          f'on {str(device)}')
    
def grad_clipping(net, theta):
    """Clip the gradient."""
    if isinstance(net, gluon.Block):
        params = [p.data() for p in net.collect_params().values()]
    else:
        params = net.params
    norm = math.sqrt(sum((p.grad ** 2).sum() for p in params))
    if norm > theta:
        for param in params:
            param.grad[:] *= theta / norm
def evaluate_accuracy(net, data_iter):
    """Compute the accuracy for a model on a dataset."""
    metric = Accumulator(2)  # No. of correct predictions, no. of predictions
    for X, y in data_iter:
        metric.add(accuracy(net(X), y), d2l.size(y))
    return metric[0] / metric[1]
def evaluate_accuracy(net, data_iter):
    """Compute the accuracy for a model on a dataset."""
    metric = Accumulator(2)  # No. of correct predictions, no. of predictions
    for X, y in data_iter:
        metric.add(accuracy(net(X), y), d2l.size(y))
    return metric[0] / metric[1]
def show_images(imgs, num_rows, num_cols, titles=None, scale=1.5,
                cmap=None, vmin=None, vmax=None):
    """Plot a list of images (cmap colors single-channel images, on the
    color scale from vmin to vmax if given)."""
    figsize = (num_cols * scale, num_rows * scale)
    _, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize)
    axes = axes.flatten()
    for i, (ax, img) in enumerate(zip(axes, imgs)):
        try:
            img = d2l.numpy(img)
        except:
            pass
        ax.imshow(img, cmap=cmap, vmin=vmin, vmax=vmax)
        ax.axes.get_xaxis().set_visible(False)
        ax.axes.get_yaxis().set_visible(False)
        if titles:
            ax.set_title(titles[i])
    return axes

show_heatmaps 将矩阵绘制为彩色网格,每个矩阵占一个子图。其参数形状为(子图行数、子图列数、高度、宽度)。默认情况下所有子图共享同一色标与颜色条;cbar='each' 为每个子图配备独立色标与颜色条,cbar=False 则不画颜色条。刻度标注整数行列索引,xticklabels 与 yticklabels 可为其命名(例如按词元)。它用于展示 3.3 节 的混淆矩阵以及 第 10 章 的注意力权重。

def show_heatmaps(matrices, xlabel, ylabel, titles=None,
                  figsize=(2.5, 2.5), cmap='Reds', cbar=True,
                  xticklabels=None, yticklabels=None):
    """Show heatmaps of matrices; cbar is True (shared), 'each' or False."""
    d2l.use_svg_display()
    matrices = d2l.numpy(matrices)
    num_rows, num_cols, height, width = matrices.shape
    fig, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize,
                                 sharex=True, sharey=True, squeeze=False)
    # All panels share one color scale (one norm) unless each gets its own
    lims = {} if cbar == 'each' else dict(norm=d2l.plt.Normalize(
        matrices.min(), matrices.max()))
    for i, (row_axes, row_matrices) in enumerate(zip(axes, matrices)):
        for j, (ax, matrix) in enumerate(zip(row_axes, row_matrices)):
            pcm = ax.imshow(matrix, cmap=cmap, **lims)
            if cbar == 'each':
                fig.colorbar(pcm, ax=ax, shrink=0.6)
            if i == num_rows - 1:
                ax.set_xlabel(xlabel)
            if j == 0:
                ax.set_ylabel(ylabel)
            if titles:
                ax.set_title(titles[j])
    # Shared axes: setting the ticks of one panel sets them for all
    for axis, n, labels in ((ax.xaxis, width, xticklabels),
                            (ax.yaxis, height, yticklabels)):
        if labels is None:
            axis.set_major_locator(d2l.plt.MaxNLocator(
                'auto', integer=True, steps=[1, 2, 2.5, 5, 10]))
        else:  # Named ticks; names along the x-axis read vertically
            axis.set_ticks(range(n), labels,
                           rotation=90 if axis is ax.xaxis else 0)
    if cbar is True:
        fig.colorbar(pcm, ax=axes, shrink=0.6);
def linreg(X, w, b):
    """The linear regression model."""
    return d2l.matmul(X, w) + b

def squared_loss(y_hat, y):
    """Squared loss."""
    return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2

def get_fashion_mnist_labels(labels):
    """Return text labels for the Fashion-MNIST dataset."""
    text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
                   'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
    return [text_labels[int(i)] for i in labels]

#@tab pytorch, mxnet, tensorflow
class Animator:
    """For plotting data in animation."""
    def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
                 ylim=None, xscale='linear', yscale='linear',
                 fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
                 figsize=(3.5, 2.5)):
        # Incrementally plot multiple lines
        if legend is None:
            legend = []
        d2l.use_svg_display()
        self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
        if nrows * ncols == 1:
            self.axes = [self.axes, ]
        # Use a lambda function to capture arguments
        self.config_axes = lambda: d2l.set_axes(
            self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
        self.X, self.Y, self.fmts = None, None, fmts

    def add(self, x, y):
        # Add multiple data points into the figure
        if not hasattr(y, "__len__"):
            y = [y]
        n = len(y)
        if not hasattr(x, "__len__"):
            x = [x] * n
        if not self.X:
            self.X = [[] for _ in range(n)]
        if not self.Y:
            self.Y = [[] for _ in range(n)]
        for i, (a, b) in enumerate(zip(x, y)):
            if a is not None and b is not None:
                self.X[i].append(a)
                self.Y[i].append(b)
        self.axes[0].cla()
        for x, y, fmt in zip(self.X, self.Y, self.fmts):
            self.axes[0].plot(x, y, fmt)
        self.config_axes()
        display.display(self.fig)
        display.clear_output(wait=True)

#@tab pytorch, mxnet, tensorflow
class Accumulator:
    """For accumulating sums over `n` variables."""
    def __init__(self, n):
        self.data = [0.0] * n

    def add(self, *args):
        self.data = [a + float(b) for a, b in zip(self.data, args)]

    def reset(self):
        self.data = [0.0] * len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]


#@tab pytorch, mxnet, tensorflow
def accuracy(y_hat, y):
    """Compute the number of correct predictions."""
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
        y_hat = d2l.argmax(y_hat, axis=1)
    elif (len(y_hat.shape) > 1 and y_hat.shape[-1] == 1) or y_hat.dtype != y.dtype:
        # Binary classification with float scores (logits or probabilities):
        # threshold at 0 (logits) to get class labels, then reshape to match y.
        y_hat = d2l.astype(y_hat > 0, y.dtype).reshape(y.shape)
    cmp = d2l.astype(y_hat, y.dtype) == y
    return float(d2l.reduce_sum(d2l.astype(cmp, y.dtype)))

def linreg(X, w, b):
    """The linear regression model."""
    return d2l.matmul(X, w) + b

def squared_loss(y_hat, y):
    """Squared loss."""
    return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2

def get_fashion_mnist_labels(labels):
    """Return text labels for the Fashion-MNIST dataset."""
    text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
                   'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
    return [text_labels[int(i)] for i in labels]

#@tab pytorch, mxnet, tensorflow
class Animator:
    """For plotting data in animation."""
    def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
                 ylim=None, xscale='linear', yscale='linear',
                 fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
                 figsize=(3.5, 2.5)):
        # Incrementally plot multiple lines
        if legend is None:
            legend = []
        d2l.use_svg_display()
        self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
        if nrows * ncols == 1:
            self.axes = [self.axes, ]
        # Use a lambda function to capture arguments
        self.config_axes = lambda: d2l.set_axes(
            self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
        self.X, self.Y, self.fmts = None, None, fmts

    def add(self, x, y):
        # Add multiple data points into the figure
        if not hasattr(y, "__len__"):
            y = [y]
        n = len(y)
        if not hasattr(x, "__len__"):
            x = [x] * n
        if not self.X:
            self.X = [[] for _ in range(n)]
        if not self.Y:
            self.Y = [[] for _ in range(n)]
        for i, (a, b) in enumerate(zip(x, y)):
            if a is not None and b is not None:
                self.X[i].append(a)
                self.Y[i].append(b)
        self.axes[0].cla()
        for x, y, fmt in zip(self.X, self.Y, self.fmts):
            self.axes[0].plot(x, y, fmt)
        self.config_axes()
        display.display(self.fig)
        display.clear_output(wait=True)

#@tab pytorch, mxnet, tensorflow
class Accumulator:
    """For accumulating sums over `n` variables."""
    def __init__(self, n):
        self.data = [0.0] * n

    def add(self, *args):
        self.data = [a + float(b) for a, b in zip(self.data, args)]

    def reset(self):
        self.data = [0.0] * len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]


#@tab pytorch, mxnet, tensorflow
def accuracy(y_hat, y):
    """Compute the number of correct predictions."""
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
        y_hat = d2l.argmax(y_hat, axis=1)
    elif (len(y_hat.shape) > 1 and y_hat.shape[-1] == 1) or y_hat.dtype != y.dtype:
        # Binary classification with float scores (logits or probabilities):
        # threshold at 0 (logits) to get class labels, then reshape to match y.
        y_hat = d2l.astype(y_hat > 0, y.dtype).reshape(y.shape)
    cmp = d2l.astype(y_hat, y.dtype) == y
    return float(d2l.reduce_sum(d2l.astype(cmp, y.dtype)))

def linreg(X, w, b):
    """The linear regression model."""
    return d2l.matmul(X, w) + b

def squared_loss(y_hat, y):
    """Squared loss."""
    return (y_hat - d2l.reshape(y, y_hat.shape)) ** 2 / 2

def get_fashion_mnist_labels(labels):
    """Return text labels for the Fashion-MNIST dataset."""
    text_labels = ['t-shirt', 'trouser', 'pullover', 'dress', 'coat',
                   'sandal', 'shirt', 'sneaker', 'bag', 'ankle boot']
    return [text_labels[int(i)] for i in labels]

#@tab pytorch, mxnet, tensorflow
class Animator:
    """For plotting data in animation."""
    def __init__(self, xlabel=None, ylabel=None, legend=None, xlim=None,
                 ylim=None, xscale='linear', yscale='linear',
                 fmts=('-', 'm--', 'g-.', 'r:'), nrows=1, ncols=1,
                 figsize=(3.5, 2.5)):
        # Incrementally plot multiple lines
        if legend is None:
            legend = []
        d2l.use_svg_display()
        self.fig, self.axes = d2l.plt.subplots(nrows, ncols, figsize=figsize)
        if nrows * ncols == 1:
            self.axes = [self.axes, ]
        # Use a lambda function to capture arguments
        self.config_axes = lambda: d2l.set_axes(
            self.axes[0], xlabel, ylabel, xlim, ylim, xscale, yscale, legend)
        self.X, self.Y, self.fmts = None, None, fmts

    def add(self, x, y):
        # Add multiple data points into the figure
        if not hasattr(y, "__len__"):
            y = [y]
        n = len(y)
        if not hasattr(x, "__len__"):
            x = [x] * n
        if not self.X:
            self.X = [[] for _ in range(n)]
        if not self.Y:
            self.Y = [[] for _ in range(n)]
        for i, (a, b) in enumerate(zip(x, y)):
            if a is not None and b is not None:
                self.X[i].append(a)
                self.Y[i].append(b)
        self.axes[0].cla()
        for x, y, fmt in zip(self.X, self.Y, self.fmts):
            self.axes[0].plot(x, y, fmt)
        self.config_axes()
        display.display(self.fig)
        display.clear_output(wait=True)

#@tab pytorch, mxnet, tensorflow
class Accumulator:
    """For accumulating sums over `n` variables."""
    def __init__(self, n):
        self.data = [0.0] * n

    def add(self, *args):
        self.data = [a + float(b) for a, b in zip(self.data, args)]

    def reset(self):
        self.data = [0.0] * len(self.data)

    def __getitem__(self, idx):
        return self.data[idx]


#@tab pytorch, mxnet, tensorflow
def accuracy(y_hat, y):
    """Compute the number of correct predictions."""
    if len(y_hat.shape) > 1 and y_hat.shape[1] > 1:
        y_hat = d2l.argmax(y_hat, axis=1)
    elif (len(y_hat.shape) > 1 and y_hat.shape[-1] == 1) or y_hat.dtype != y.dtype:
        # Binary classification with float scores (logits or probabilities):
        # threshold at 0 (logits) to get class labels, then reshape to match y.
        y_hat = d2l.astype(y_hat > 0, y.dtype).reshape(y.shape)
    cmp = d2l.astype(y_hat, y.dtype) == y
    return float(d2l.reduce_sum(d2l.astype(cmp, y.dtype)))
import os
import requests
import zipfile
import tarfile
import hashlib

def download(url, folder='../data', sha1_hash=None):
    """Download a file to folder and return the local filepath."""
    if not url.startswith('http'):
        # For back compatibility
        url, sha1_hash = DATA_HUB[url]
    os.makedirs(folder, exist_ok=True)
    fname = os.path.join(folder, url.split('/')[-1])
    # Check if hit cache
    if os.path.exists(fname) and sha1_hash:
        sha1 = hashlib.sha1()
        with open(fname, 'rb') as f:
            while True:
                data = f.read(1048576)
                if not data:
                    break
                sha1.update(data)
        if sha1.hexdigest() == sha1_hash:
            return fname
    # Download
    import tempfile
    print(f'Downloading {fname} from {url}...')
    r = requests.get(url, stream=True, verify=True)
    fd, tmp = tempfile.mkstemp(dir=folder)
    try:
        with os.fdopen(fd, 'wb') as f:
            f.write(r.content)
        os.replace(tmp, fname)
    except BaseException:
        os.unlink(tmp)
        raise
    return fname

def extract(filename, folder=None):
    """Extract a zip/tar file into folder."""
    import tempfile, shutil
    base_dir = os.path.dirname(filename)
    _, ext = os.path.splitext(filename)
    assert ext in ('.zip', '.tar', '.gz'), 'Only support zip/tar files.'
    opener = zipfile.ZipFile if ext == '.zip' else tarfile.open
    if folder is None:
        folder = base_dir
    tmp = tempfile.mkdtemp(dir=folder)
    try:
        with opener(filename, 'r') as fp:
            fp.extractall(tmp)
        for name in os.listdir(tmp):
            src = os.path.join(tmp, name)
            dst = os.path.join(folder, name)
            if os.path.isdir(dst):
                shutil.rmtree(dst)
            os.rename(src, dst)
    finally:
        shutil.rmtree(tmp, ignore_errors=True)
def download_extract(name, folder=None):
    """Download and extract a zip/tar file."""
    fname = download(name)
    base_dir = os.path.dirname(fname)
    data_dir, ext = os.path.splitext(fname)
    target = os.path.join(base_dir, folder) if folder else data_dir
    # Skip re-extraction if a completion marker exists (extracting many small
    # files is slow and unnecessary when the archive is already unpacked).
    marker = fname + '.extracted'
    if os.path.exists(marker):
        return target
    if ext == '.zip':
        fp = zipfile.ZipFile(fname, 'r')
    elif ext in ('.tar', '.gz'):
        fp = tarfile.open(fname, 'r')
    else:
        assert False, 'Only zip/tar files can be extracted.'
    fp.extractall(base_dir)
    open(marker, 'w').close()
    return target


def tokenize(lines, token='word'):
    """Split text lines into word or character tokens."""
    assert token in ('word', 'char'), 'Unknown token type: ' + token
    return [line.split() if token == 'word' else list(line) for line in lines]

def download_extract(name, folder=None):
    """Download and extract a zip/tar file."""
    fname = download(name)
    base_dir = os.path.dirname(fname)
    data_dir, ext = os.path.splitext(fname)
    target = os.path.join(base_dir, folder) if folder else data_dir
    # Skip re-extraction if a completion marker exists (extracting many small
    # files is slow and unnecessary when the archive is already unpacked).
    marker = fname + '.extracted'
    if os.path.exists(marker):
        return target
    if ext == '.zip':
        fp = zipfile.ZipFile(fname, 'r')
    elif ext in ('.tar', '.gz'):
        fp = tarfile.open(fname, 'r')
    else:
        assert False, 'Only zip/tar files can be extracted.'
    fp.extractall(base_dir)
    open(marker, 'w').close()
    return target


def tokenize(lines, token='word'):
    """Split text lines into word or character tokens."""
    assert token in ('word', 'char'), 'Unknown token type: ' + token
    return [line.split() if token == 'word' else list(line) for line in lines]

def download_extract(name, folder=None):
    """Download and extract a zip/tar file."""
    fname = download(name)
    base_dir = os.path.dirname(fname)
    data_dir, ext = os.path.splitext(fname)
    target = os.path.join(base_dir, folder) if folder else data_dir
    # Skip re-extraction if a completion marker exists (extracting many small
    # files is slow and unnecessary when the archive is already unpacked).
    marker = fname + '.extracted'
    if os.path.exists(marker):
        return target
    if ext == '.zip':
        fp = zipfile.ZipFile(fname, 'r')
    elif ext in ('.tar', '.gz'):
        fp = tarfile.open(fname, 'r')
    else:
        assert False, 'Only zip/tar files can be extracted.'
    fp.extractall(base_dir)
    open(marker, 'w').close()
    return target


def tokenize(lines, token='word'):
    """Split text lines into word or character tokens."""
    assert token in ('word', 'char'), 'Unknown token type: ' + token
    return [line.split() if token == 'word' else list(line) for line in lines]
def evaluate_loss(net, data_iter, loss):
    """Evaluate the loss of a model on the given dataset."""
    metric = d2l.Accumulator(2)  # Sum of losses, no. of examples
    for X, y in data_iter:
        out = net(X)
        y = d2l.reshape(y, out.shape)
        l = loss(out, y)
        metric.add(d2l.reduce_sum(l), d2l.size(l))
    return metric[0] / metric[1]
def evaluate_loss(net, data_iter, loss):
    """Evaluate the loss of a model on the given dataset."""
    metric = d2l.Accumulator(2)  # Sum of losses, no. of examples
    for X, y in data_iter:
        l = loss(net(X), y)
        metric.add(d2l.reduce_sum(l), d2l.size(l))
    return metric[0] / metric[1]
def evaluate_loss(net, data_iter, loss):
    """Evaluate the loss of a model on the given dataset."""
    metric = d2l.Accumulator(2)  # Sum of losses, no. of examples
    for X, y in data_iter:
        l = loss(net(X), y)
        metric.add(d2l.reduce_sum(l), d2l.size(l))
    return metric[0] / metric[1]
def grad_clipping(net, theta):
    """Clip the gradient."""
    if isinstance(net, nn.Module):
        params = [p for p in net.parameters() if p.requires_grad]
    else:
        params = net.params
    norm = torch.sqrt(sum(torch.sum((p.grad ** 2)) for p in params))
    if norm > theta:
        for param in params:
            param.grad[:] *= theta / norm
def grad_clipping(grads, theta):
    """Clip the gradient."""
    theta = tf.constant(theta, dtype=tf.float32)
    new_grad = []
    for grad in grads:
        if isinstance(grad, tf.IndexedSlices):
            new_grad.append(tf.convert_to_tensor(grad))
        else:
            new_grad.append(grad)
    norm = tf.math.sqrt(sum((tf.reduce_sum(grad ** 2)).numpy()
                        for grad in new_grad))
    norm = tf.cast(norm, tf.float32)
    if tf.greater(norm, theta):
        for i, grad in enumerate(new_grad):
            new_grad[i] = grad * theta / norm
    else:
        new_grad = new_grad
    return new_grad

39.9.6 序列与注意力实用工具

d2l.DATA_HUB['fra-eng'] = (d2l.DATA_URL + 'fra-eng.zip',
                           '94646ad1522d915e7b0f9296181140edcf86a4f5')


def read_data_nmt():
    """Load the English-French dataset."""
    data_dir = d2l.download_extract('fra-eng')
    with open(os.path.join(data_dir, 'fra.txt'), 'r', encoding='utf-8') as f:
        return f.read()


def preprocess_nmt(text):
    """Preprocess the English-French dataset."""
    def no_space(char, prev_char):
        return char in set(',.!?') and prev_char != ' '

    # Replace non-breaking space with space, and convert uppercase letters to
    # lowercase ones
    text = text.replace('\u202f', ' ').replace('\xa0', ' ').lower()
    # Insert space between words and punctuation marks
    out = [' ' + char if i > 0 and no_space(char, text[i - 1]) else char
           for i, char in enumerate(text)]
    return ''.join(out)


def tokenize_nmt(text, num_examples=None):
    """Tokenize the English-French dataset."""
    source, target = [], []
    for i, line in enumerate(text.split('\n')):
        if num_examples and i > num_examples:
            break
        parts = line.split('\t')
        if len(parts) == 2:
            source.append(parts[0].split(' '))
            target.append(parts[1].split(' '))
    return source, target

    

def truncate_pad(line, num_steps, padding_token):
    """Truncate or pad sequences."""
    if len(line) > num_steps:
        return line[:num_steps]  # Truncate
    return line + [padding_token] * (num_steps - len(line))  # Pad


def build_array_nmt(lines, vocab, num_steps):
    """Transform text sequences of machine translation into minibatches."""
    lines = [vocab[l] for l in lines]
    lines = [l + [vocab['<eos>']] for l in lines]
    array = d2l.tensor([truncate_pad(
        l, num_steps, vocab['<pad>']) for l in lines])
    valid_len = d2l.reduce_sum(
        d2l.astype(array != vocab['<pad>'], d2l.int32), 1)
    return array, valid_len


def load_data_nmt(batch_size, num_steps, num_examples=600):
    """Return the iterator and the vocabularies of the translation dataset."""
    text = preprocess_nmt(read_data_nmt())
    source, target = tokenize_nmt(text, num_examples)
    src_vocab = d2l.Vocab(source, min_freq=2,
                          reserved_tokens=['<pad>', '<bos>', '<eos>'])
    tgt_vocab = d2l.Vocab(target, min_freq=2,
                          reserved_tokens=['<pad>', '<bos>', '<eos>'])
    src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)
    tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)
    data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)
    data_iter = d2l.load_array(data_arrays, batch_size)
    return data_iter, src_vocab, tgt_vocab

d2l.DATA_HUB['fra-eng'] = (d2l.DATA_URL + 'fra-eng.zip',
                           '94646ad1522d915e7b0f9296181140edcf86a4f5')


def read_data_nmt():
    """Load the English-French dataset."""
    data_dir = d2l.download_extract('fra-eng')
    with open(os.path.join(data_dir, 'fra.txt'), 'r', encoding='utf-8') as f:
        return f.read()


def preprocess_nmt(text):
    """Preprocess the English-French dataset."""
    def no_space(char, prev_char):
        return char in set(',.!?') and prev_char != ' '

    # Replace non-breaking space with space, and convert uppercase letters to
    # lowercase ones
    text = text.replace('\u202f', ' ').replace('\xa0', ' ').lower()
    # Insert space between words and punctuation marks
    out = [' ' + char if i > 0 and no_space(char, text[i - 1]) else char
           for i, char in enumerate(text)]
    return ''.join(out)


def tokenize_nmt(text, num_examples=None):
    """Tokenize the English-French dataset."""
    source, target = [], []
    for i, line in enumerate(text.split('\n')):
        if num_examples and i > num_examples:
            break
        parts = line.split('\t')
        if len(parts) == 2:
            source.append(parts[0].split(' '))
            target.append(parts[1].split(' '))
    return source, target

    

def truncate_pad(line, num_steps, padding_token):
    """Truncate or pad sequences."""
    if len(line) > num_steps:
        return line[:num_steps]  # Truncate
    return line + [padding_token] * (num_steps - len(line))  # Pad


def build_array_nmt(lines, vocab, num_steps):
    """Transform text sequences of machine translation into minibatches."""
    lines = [vocab[l] for l in lines]
    lines = [l + [vocab['<eos>']] for l in lines]
    array = d2l.tensor([truncate_pad(
        l, num_steps, vocab['<pad>']) for l in lines])
    valid_len = d2l.reduce_sum(
        d2l.astype(array != vocab['<pad>'], d2l.int32), 1)
    return array, valid_len


def load_data_nmt(batch_size, num_steps, num_examples=600):
    """Return the iterator and the vocabularies of the translation dataset."""
    text = preprocess_nmt(read_data_nmt())
    source, target = tokenize_nmt(text, num_examples)
    src_vocab = d2l.Vocab(source, min_freq=2,
                          reserved_tokens=['<pad>', '<bos>', '<eos>'])
    tgt_vocab = d2l.Vocab(target, min_freq=2,
                          reserved_tokens=['<pad>', '<bos>', '<eos>'])
    src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)
    tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)
    data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)
    data_iter = d2l.load_array(data_arrays, batch_size)
    return data_iter, src_vocab, tgt_vocab

d2l.DATA_HUB['fra-eng'] = (d2l.DATA_URL + 'fra-eng.zip',
                           '94646ad1522d915e7b0f9296181140edcf86a4f5')


def read_data_nmt():
    """Load the English-French dataset."""
    data_dir = d2l.download_extract('fra-eng')
    with open(os.path.join(data_dir, 'fra.txt'), 'r', encoding='utf-8') as f:
        return f.read()


def preprocess_nmt(text):
    """Preprocess the English-French dataset."""
    def no_space(char, prev_char):
        return char in set(',.!?') and prev_char != ' '

    # Replace non-breaking space with space, and convert uppercase letters to
    # lowercase ones
    text = text.replace('\u202f', ' ').replace('\xa0', ' ').lower()
    # Insert space between words and punctuation marks
    out = [' ' + char if i > 0 and no_space(char, text[i - 1]) else char
           for i, char in enumerate(text)]
    return ''.join(out)


def tokenize_nmt(text, num_examples=None):
    """Tokenize the English-French dataset."""
    source, target = [], []
    for i, line in enumerate(text.split('\n')):
        if num_examples and i > num_examples:
            break
        parts = line.split('\t')
        if len(parts) == 2:
            source.append(parts[0].split(' '))
            target.append(parts[1].split(' '))
    return source, target

    

def truncate_pad(line, num_steps, padding_token):
    """Truncate or pad sequences."""
    if len(line) > num_steps:
        return line[:num_steps]  # Truncate
    return line + [padding_token] * (num_steps - len(line))  # Pad


def build_array_nmt(lines, vocab, num_steps):
    """Transform text sequences of machine translation into minibatches."""
    lines = [vocab[l] for l in lines]
    lines = [l + [vocab['<eos>']] for l in lines]
    array = d2l.tensor([truncate_pad(
        l, num_steps, vocab['<pad>']) for l in lines])
    valid_len = d2l.reduce_sum(
        d2l.astype(array != vocab['<pad>'], d2l.int32), 1)
    return array, valid_len


def load_data_nmt(batch_size, num_steps, num_examples=600):
    """Return the iterator and the vocabularies of the translation dataset."""
    text = preprocess_nmt(read_data_nmt())
    source, target = tokenize_nmt(text, num_examples)
    src_vocab = d2l.Vocab(source, min_freq=2,
                          reserved_tokens=['<pad>', '<bos>', '<eos>'])
    tgt_vocab = d2l.Vocab(target, min_freq=2,
                          reserved_tokens=['<pad>', '<bos>', '<eos>'])
    src_array, src_valid_len = build_array_nmt(source, src_vocab, num_steps)
    tgt_array, tgt_valid_len = build_array_nmt(target, tgt_vocab, num_steps)
    data_arrays = (src_array, src_valid_len, tgt_array, tgt_valid_len)
    data_iter = d2l.load_array(data_arrays, batch_size)
    return data_iter, src_vocab, tgt_vocab
def sequence_mask(X, valid_len, value=0):
    """Mask irrelevant entries in sequences."""
    maxlen = X.size(1)
    mask = torch.arange((maxlen), dtype=torch.float32,
                        device=X.device)[None, :] < valid_len[:, None]
    X[~mask] = value
    return X

    

class MaskedSoftmaxCELoss(nn.CrossEntropyLoss):
    """The softmax cross-entropy loss with masks."""
    # `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)
    # `label` shape: (`batch_size`, `num_steps`)
    # `valid_len` shape: (`batch_size`,)
    def __init__(self):
        super().__init__(reduction='none')

    def forward(self, pred, label, valid_len):
        weights = torch.ones_like(label)
        weights = sequence_mask(weights, valid_len)
        unweighted_loss = super().forward(pred.permute(0, 2, 1), label)
        weighted_loss = (unweighted_loss * weights).mean(dim=1)
        return weighted_loss
    

def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):
    """Train a model for sequence to sequence."""
    def xavier_init_weights(m):
        if type(m) == nn.Linear:
            nn.init.xavier_uniform_(m.weight)
        if type(m) == nn.GRU:
            for param in m._flat_weights_names:
                if "weight" in param:
                    nn.init.xavier_uniform_(m._parameters[param])
    net.apply(xavier_init_weights)
    net.to(device)
    optimizer = torch.optim.Adam(net.parameters(), lr=lr)
    loss = MaskedSoftmaxCELoss()
    net.train()
    animator = d2l.Animator(xlabel='epoch', ylabel='loss',
                            xlim=[10, num_epochs])
    for epoch in range(num_epochs):
        timer = d2l.Timer()
        metric = d2l.Accumulator(2)  # Sum of training loss, no. of tokens
        for batch in data_iter:
            optimizer.zero_grad()
            X, X_valid_len, Y, Y_valid_len = [x.to(device) for x in batch]
            bos = torch.tensor([tgt_vocab['<bos>']] * Y.shape[0],
                               device=device).reshape(-1, 1)
            dec_input = d2l.concat([bos, Y[:, :-1]], 1)  # Teacher forcing
            Y_hat, _ = net(X, dec_input, X_valid_len)
            l = loss(Y_hat, Y, Y_valid_len)
            l.sum().backward()  # Make the loss scalar for `backward`
            d2l.grad_clipping(net, 1)
            num_tokens = Y_valid_len.sum()
            optimizer.step()
            with torch.no_grad():
                metric.add(l.sum(), num_tokens)
        if (epoch + 1) % 10 == 0:
            animator.add(epoch + 1, (metric[0] / metric[1],))
    print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '
          f'tokens/sec on {str(device)}')
    


def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,
                    device, save_attention_weights=False):
    """Predict for sequence to sequence."""
    # Set `net` to eval mode for inference
    net.eval()
    src_tokens = src_vocab[src_sentence.lower().split(' ')] + [
        src_vocab['<eos>']]
    enc_valid_len = torch.tensor([len(src_tokens)], device=device)
    src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])
    # Add the batch axis
    enc_X = torch.unsqueeze(
        torch.tensor(src_tokens, dtype=torch.long, device=device), dim=0)
    enc_outputs = net.encoder(enc_X, enc_valid_len)
    dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)
    # Add the batch axis
    dec_X = torch.unsqueeze(torch.tensor(
        [tgt_vocab['<bos>']], dtype=torch.long, device=device), dim=0)
    output_seq, attention_weight_seq = [], []
    for _ in range(num_steps):
        Y, dec_state = net.decoder(dec_X, dec_state)
        # We use the token with the highest prediction likelihood as input
        # of the decoder at the next time step
        dec_X = Y.argmax(dim=2)
        pred = dec_X.squeeze(dim=0).type(torch.int32).item()
        # Save attention weights (to be covered later)
        if save_attention_weights:
            attention_weight_seq.append(net.decoder.attention_weights)
        # Once the end-of-sequence token is predicted, the generation of the
        # output sequence is complete
        if pred == tgt_vocab['<eos>']:
            break
        output_seq.append(pred)
    return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq

def sequence_mask(X, valid_len, value=0):
    """Mask irrelevant entries in sequences."""
    maxlen = X.shape[1]
    mask = tf.range(start=0, limit=maxlen, dtype=tf.float32)[
        None, :] < tf.cast(valid_len[:, None], dtype=tf.float32)
    
    if len(X.shape) == 3:
        return tf.where(tf.expand_dims(mask, axis=-1), X, value)
    else:
        return tf.where(mask, X, value)

    

class MaskedSoftmaxCELoss(tf.keras.losses.Loss):
    """The softmax cross-entropy loss with masks."""
    def __init__(self, valid_len):
        super().__init__(reduction='none')
        self.valid_len = valid_len
    
    # `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)
    # `label` shape: (`batch_size`, `num_steps`)
    # `valid_len` shape: (`batch_size`,)
    def call(self, label, pred):
        weights = tf.ones_like(label, dtype=tf.float32)
        weights = sequence_mask(weights, self.valid_len)
        label_one_hot = tf.one_hot(label, depth=pred.shape[-1])
        unweighted_loss = tf.keras.losses.CategoricalCrossentropy(
            from_logits=True, reduction='none')(label_one_hot, pred)
        weighted_loss = tf.reduce_mean((unweighted_loss*weights), axis=1)
        return weighted_loss
    

def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):
    """Train a model for sequence to sequence."""
    optimizer = tf.keras.optimizers.Adam(learning_rate=lr)
    animator = d2l.Animator(xlabel="epoch", ylabel="loss",
                            xlim=[10, num_epochs])
    for epoch in range(num_epochs):
        timer = d2l.Timer()
        metric = d2l.Accumulator(2)  # Sum of training loss, no. of tokens
        for batch in data_iter:
            X, X_valid_len, Y, Y_valid_len = [x for x in batch]
            bos = tf.reshape(tf.constant([tgt_vocab['<bos>']] * Y.shape[0]),
                             shape=(-1, 1))
            dec_input = tf.concat([bos, Y[:, :-1]], 1)  # Teacher forcing
            with tf.GradientTape() as tape:
                Y_hat, _ = net(X, dec_input, X_valid_len, training=True)
                l = MaskedSoftmaxCELoss(Y_valid_len)(Y, Y_hat)
            gradients = tape.gradient(l, net.trainable_variables)
            gradients = d2l.grad_clipping(gradients, 1)
            optimizer.apply_gradients(zip(gradients, net.trainable_variables))
            num_tokens = tf.reduce_sum(Y_valid_len).numpy()
            metric.add(tf.reduce_sum(l), num_tokens)
        if (epoch + 1) % 10 == 0:
            animator.add(epoch + 1, (metric[0] / metric[1],))
    print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '
          f'tokens/sec on {str(device._device_name)}')
    

def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,
                    save_attention_weights=False):
    """Predict for sequence to sequence."""
    src_tokens = src_vocab[src_sentence.lower().split(' ')] + [
        src_vocab['<eos>']]
    enc_valid_len = tf.constant([len(src_tokens)])
    src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])
    # Add the batch axis
    enc_X = tf.expand_dims(src_tokens, axis=0)
    enc_outputs = net.encoder(enc_X, enc_valid_len, training=False)
    dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)
    # Add the batch axis
    dec_X = tf.expand_dims(tf.constant([tgt_vocab['<bos>']]), axis=0)
    output_seq, attention_weight_seq = [], []
    for _ in range(num_steps):
        Y, dec_state = net.decoder(dec_X, dec_state, training=False)
        # We use the token with the highest prediction likelihood as input
        # of the decoder at the next time step
        dec_X = tf.argmax(Y, axis=2)
        pred = tf.squeeze(dec_X, axis=0)
        # Save attention weights
        if save_attention_weights:
            attention_weight_seq.append(net.decoder.attention_weights)
        # Once the end-of-sequence token is predicted, the generation of the
        # output sequence is complete
        if pred == tgt_vocab['<eos>']:
            break
        output_seq.append(pred.numpy())
    return ' '.join(tgt_vocab.to_tokens(tf.reshape(output_seq, shape = -1).numpy().tolist())), attention_weight_seq
    

class MaskedSoftmaxCELoss(gluon.loss.SoftmaxCELoss):
    """The softmax cross-entropy loss with masks."""
    # `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)
    # `label` shape: (`batch_size`, `num_steps`)
    # `valid_len` shape: (`batch_size`,)
    def forward(self, pred, label, valid_len):
        # `weights` shape: (`batch_size`, `num_steps`, 1)
        weights = mnp.expand_dims(mnp.ones_like(label), axis=-1)
        weights = npx.sequence_mask(weights, valid_len, True, axis=1)
        return super(MaskedSoftmaxCELoss, self).forward(pred, label, weights)


def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):
    """Train a model for sequence to sequence."""
    net.initialize(init.Xavier(), force_reinit=True, device=device)
    trainer = gluon.Trainer(net.collect_params(), 'adam',
                            {'learning_rate': lr})
    loss = MaskedSoftmaxCELoss()
    animator = d2l.Animator(xlabel='epoch', ylabel='loss',
                            xlim=[10, num_epochs])
    for epoch in range(num_epochs):
        timer = d2l.Timer()
        metric = d2l.Accumulator(2)  # Sum of training loss, no. of tokens
        for batch in data_iter:
            X, X_valid_len, Y, Y_valid_len = [
                x.to_device(device) for x in batch]
            bos = mnp.array([tgt_vocab['<bos>']] * Y.shape[0],
                            device=device).reshape(-1, 1)
            dec_input = d2l.concat([bos, Y[:, :-1]], 1)  # Teacher forcing
            with autograd.record():
                Y_hat, _ = net(X, dec_input, X_valid_len)
                l = loss(Y_hat, Y, Y_valid_len)
            l.backward()
            d2l.grad_clipping(net, 1)
            num_tokens = Y_valid_len.sum()
            trainer.step(num_tokens)
            metric.add(l.sum(), num_tokens)
        if (epoch + 1) % 10 == 0:
            animator.add(epoch + 1, (metric[0] / metric[1],))
    print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '
          f'tokens/sec on {str(device)}')


def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,
                    device, save_attention_weights=False):
    """Predict for sequence to sequence."""
    src_tokens = src_vocab[src_sentence.lower().split(' ')] + [
        src_vocab['<eos>']]
    enc_valid_len = mnp.array([len(src_tokens)], device=device)
    src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])
    # Add the batch axis
    enc_X = mnp.expand_dims(mnp.array(src_tokens, device=device), axis=0)
    enc_outputs = net.encoder(enc_X, enc_valid_len)
    dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)
    # Add the batch axis
    dec_X = mnp.expand_dims(
        mnp.array([tgt_vocab['<bos>']], device=device), axis=0)
    output_seq, attention_weight_seq = [], []
    for _ in range(num_steps):
        Y, dec_state = net.decoder(dec_X, dec_state)
        # We use the token with the highest prediction likelihood as input
        # of the decoder at the next time step
        dec_X = Y.argmax(axis=2)
        pred = dec_X.squeeze(axis=0).astype('int32').item()
        # Save attention weights (to be covered later)
        if save_attention_weights:
            attention_weight_seq.append(net.decoder.attention_weights)
        # Once the end-of-sequence token is predicted, the generation of the
        # output sequence is complete
        if pred == tgt_vocab['<eos>']:
            break
        output_seq.append(pred)
    return ' '.join(tgt_vocab.to_tokens(output_seq)), attention_weight_seq

39.9.6.1 小词表的嵌入梯度

嵌入查表的梯度会把每个位置的梯度累加到对应词元的那一行,而 XLA 通过原子操作完成这些累加。在文本小批量中,成千上万个位置对应少数高频词元(例如空格或字母 e 的字节)。它们对同一行的累加彼此排队等待,在 GPU 上求和耗时可能比随机词元慢几十倍。对于词表不超过 1,024 个词元的情形,Embed 将同一求和改写为词元独热行与梯度的一次矩阵乘法;在其他方面它与 nnx.Embed 完全一致,本书的 JAX 模型均用它作为词元嵌入表。

@jax.custom_vjp
def embedding_rows(table, X):
    """The rows X of table."""
    return table[X]

def _embedding_rows_fwd(table, X):
    return table[X], (table, X)

def _embedding_rows_bwd(residuals, grad):
    """Gradient of the table: the one-hot rows of X times the gradients."""
    table, X = residuals
    one_hot = jax.nn.one_hot(X, len(table), dtype=grad.dtype)
    return jnp.einsum('...v,...d->vd', one_hot, grad,
                      precision='highest').astype(table.dtype), None


embedding_rows.defvjp(_embedding_rows_fwd, _embedding_rows_bwd)

class Embed(nnx.Embed):
    """nnx.Embed whose gradient is a matrix product for small vocabularies."""
    def __call__(self, X):
        table = self.embedding[...]
        if len(table) > 1024:  # A one-hot row would cost too much
            return super().__call__(X)
        return embedding_rows(table, X).astype(self.dtype or table.dtype)

39.9.7 框架覆盖说明

本节中的旧版辅助函数(train_ch6、train_seq2seq、predict_seq2seq、MaskedSoftmaxCELoss)仅为与原版 D2L 实现保持兼容而保留——它们早于本版引入的统一 d2l.Trainer 类,因此不提供 JAX 版本。如果你正在阅读 JAX 标签页,对应章节均端到端使用 d2l.Trainer.fit(model, data),相应的逐批量逻辑实现在 Trainer.fit_epoch 及配套的 @d2l.add_to_class 扩展中。evaluate_accuracy 在全部四个框架中均有提供:PyTorch 与 JAX 在 9.3 节 中定义了 evaluate_accuracy(model, batches),而 MXNet 与 TensorFlow 标签页则保留上文的旧版 evaluate_accuracy(net, data_iter)。

讨论