プリンキピア

第11章注意機構とTransformer

11.2.2. Attention Pooling via Nadaraya–Watson Regression11.2.2 ナダラヤ・ワトソン回帰による注意プーリング

Now that we have data and kernels, all we need is a function that computes the kernel regression estimates. Note that we also want to obtain the relative kernel weights in order to perform some minor diagnostics. Hence we first compute the kernel between all training features (covariates) x_train and all validation features x_val. This yields a matrix, which we subsequently normalize. When multiplied with the training labels y_train we obtain the estimates.
英語のヒント
データとカーネルがそろったので、必要なのはカーネル回帰の推定値を計算する関数だけである。ちょっとした診断を行うために、相対的なカーネルの重みも得たいことに注意してほしい。そこで、まずすべての訓練の特徴量(共変量)x_trainとすべての検証の特徴量x_valのあいだのカーネルを計算する。これにより行列が得られ、続いてそれを正規化する。訓練のラベルy_trainを掛けると、推定値が得られる。
Recall attention pooling in (11.1.1). Let each validation feature be a query, and each training feature–label pair be a key–value pair. As a result, the normalized relative kernel weights (attention_w below) are the attention weights.
英語のヒント
(11.1.1)の注意プーリングを思い出そう。各検証の特徴量をクエリとし、各訓練の特徴量とラベルの組をキーとバリューの組とする。その結果、正規化した相対的なカーネルの重み(以下のattention_w)が注意の重みになる。
def nadaraya_watson(x_train, y_train, x_val, kernel):
    dists = x_train.reshape((-1, 1)) - x_val.reshape((1, -1))
    # Each column/row corresponds to each query/key
    k = kernel(dists).type(torch.float32)
    # Normalization over keys for each query
    attention_w = k / k.sum(0)
    y_hat = y_train@attention_w
    return y_hat, attention_w
Let’s have a look at the kind of estimates that the different kernels produce.
英語のヒント
異なるカーネルがどんな推定値を出すか見てみよう。
def plot(x_train, y_train, x_val, y_val, kernels, names, attention=False):
    fig, axes = d2l.plt.subplots(1, 4, sharey=True, figsize=(12, 3))
    for kernel, name, ax in zip(kernels, names, axes):
        y_hat, attention_w = nadaraya_watson(x_train, y_train, x_val, kernel)
        if attention:
            pcm = ax.imshow(attention_w.detach().numpy(), cmap='Reds')
        else:
            ax.plot(x_val, y_hat)
            ax.plot(x_val, y_val, 'm--')
            ax.plot(x_train, y_train, 'o', alpha=0.5);
        ax.set_xlabel(name)
        if not attention:
            ax.legend(['y_hat', 'y'])
    if attention:
        fig.colorbar(pcm, ax=axes, shrink=0.7)

plot(x_train, y_train, x_val, y_val, kernels, names)
The first thing that stands out is that all three nontrivial kernels (Gaussian, Boxcar, and Epanechikov) produce fairly workable estimates that are not too far from the true function. Only the constant kernel that leads to the trivial estimate f(x)=1n∑iyi produces a rather unrealistic result. Let’s inspect the attention weighting a bit more closely:
英語のヒント
まず目につくのは、自明でない三つのカーネル(ガウス、箱型、エパネチニコフ)がどれも、本当の関数からそれほど遠くない、かなり使える推定値を出すことである。自明な推定値f(x)=1n∑iyiにつながる定数カーネルだけが、かなり非現実的な結果を出す。注意の重みのつき方をもう少し詳しく調べてみよう。
plot(x_train, y_train, x_val, y_val, kernels, names, attention=True)
The visualization clearly shows why the estimates for Gaussian, Boxcar, and Epanechikov are very similar: after all, they are derived from very similar attention weights, despite the different functional form of the kernel. This raises the question as to whether this is always the case.
英語のヒント
この可視化は、ガウス、箱型、エパネチニコフの推定値がなぜとてもよく似ているのかをはっきり示している。結局のところ、カーネルの関数の形は違っても、それらはとてもよく似た注意の重みから導かれている。ここから、これがいつも成り立つのかという疑問が生じる。