プリンキピア

第11章注意機構とTransformer

11.1.1. Visualization11.1.1 可視化

One of the benefits of the attention mechanism is that it can be quite intuitive, particularly when the weights are nonnegative and sum to 1. In this case we might interpret large weights as a way for the model to select components of relevance. While this is a good intuition, it is important to remember that it is just that, an intuition. Regardless, we may want to visualize its effect on the given set of keys when applying a variety of different queries. This function will come in handy later.
英語のヒント
注意機構の利点の一つは、特に重みが非負で和が1になるとき、かなり直観的でありうることである。この場合、大きな重みを、モデルが関連のある部品を選ぶ方法と解釈できるかもしれない。これはよい直観だが、それがただの直観にすぎないことを覚えておくのは大切である。いずれにせよ、さまざまなクエリを当てはめたときに、与えられたキーの集合への効果を可視化したいことがある。この関数は後で役に立つ。
We thus define the show_heatmaps function. Note that it does not take a matrix (of attention weights) as its input but rather a tensor with four axes, allowing for an array of different queries and weights. Consequently the input matrices has the shape (number of rows for display, number of columns for display, number of queries, number of keys). This will come in handy later on when we want to visualize the workings that are to design Transformers.
英語のヒント
そこで、show_heatmaps関数を定義する。これは(注意の重みの)行列を入力にとるのではなく、4つの軸をもつテンソルをとることに注意してほしい。これにより、さまざまなクエリと重みの配列を扱える。そのため、入力matricesは(表示する行の数、表示する列の数、クエリの数、キーの数)という形状をもつ。これは、後でTransformerを設計する仕組みを可視化したいときに役に立つ。
#@save
def show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5),
                  cmap='Reds'):
    """Show heatmaps of matrices."""
    d2l.use_svg_display()
    num_rows, num_cols, _, _ = matrices.shape
    fig, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize,
                                 sharex=True, sharey=True, squeeze=False)
    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.detach().numpy(), cmap=cmap)
            if i == num_rows - 1:
                ax.set_xlabel(xlabel)
            if j == 0:
                ax.set_ylabel(ylabel)
            if titles:
                ax.set_title(titles[j])
    fig.colorbar(pcm, ax=axes, shrink=0.6);
As a quick sanity check let’s visualize the identity matrix, representing a case where the attention weight is 1 only when the query and the key are the same.
英語のヒント
手早い健全性の確認として、単位行列を可視化しよう。これは、クエリとキーが同じときだけ注意の重みが1になる場合を表す。
attention_weights = torch.eye(10).reshape((1, 1, 10, 10))
show_heatmaps(attention_weights, xlabel='Keys', ylabel='Queries')