{ "cells": [ { "cell_type": "markdown", "id": "efaabde6", "metadata": { "origin_pos": 1 }, "source": [ "# Attention Scoring Functions\n", ":label:`sec_attention-scoring-functions`\n", "\n", "\n", "In :numref:`sec_attention-pooling`,\n", "we used a number of different distance-based kernels, including a Gaussian kernel to model\n", "interactions between queries and keys. As it turns out, distance functions are slightly more expensive to compute than dot products. As such, \n", "with the softmax operation to ensure nonnegative attention weights,\n", "much of the work has gone into *attention scoring functions* $a$ in :eqref:`eq_softmax_attention` and :numref:`fig_attention_output` that are simpler to compute. \n", "\n", "![Computing the output of attention pooling as a weighted average of values, where weights are computed with the attention scoring function $\\mathit{a}$ and the softmax operation.](../img/attention-output.svg)\n", ":label:`fig_attention_output`\n" ] }, { "cell_type": "code", "execution_count": 1, "id": "8e33a108", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:45.433072Z", "iopub.status.busy": "2023-08-18T19:43:45.432523Z", "iopub.status.idle": "2023-08-18T19:43:48.504425Z", "shell.execute_reply": "2023-08-18T19:43:48.503548Z" }, "origin_pos": 3, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "import math\n", "import torch\n", "from torch import nn\n", "from d2l import torch as d2l" ] }, { "cell_type": "markdown", "id": "a8224956", "metadata": { "origin_pos": 6 }, "source": [ "## [**Dot Product Attention**]\n", "\n", "\n", "Let's review the attention function (without exponentiation) from the Gaussian kernel for a moment:\n", "\n", "$$\n", "a(\\mathbf{q}, \\mathbf{k}_i) = -\\frac{1}{2} \\|\\mathbf{q} - \\mathbf{k}_i\\|^2 = \\mathbf{q}^\\top \\mathbf{k}_i -\\frac{1}{2} \\|\\mathbf{k}_i\\|^2 -\\frac{1}{2} \\|\\mathbf{q}\\|^2.\n", "$$\n", "\n", "First, note that the final term depends on $\\mathbf{q}$ only. As such it is identical for all $(\\mathbf{q}, \\mathbf{k}_i)$ pairs. Normalizing the attention weights to $1$, as is done in :eqref:`eq_softmax_attention`, ensures that this term disappears entirely. Second, note that both batch and layer normalization (to be discussed later) lead to activations that have well-bounded, and often constant, norms $\\|\\mathbf{k}_i\\|$. This is the case, for instance, whenever the keys $\\mathbf{k}_i$ were generated by a layer norm. As such, we can drop it from the definition of $a$ without any major change in the outcome. \n", "\n", "Last, we need to keep the order of magnitude of the arguments in the exponential function under control. Assume that all the elements of the query $\\mathbf{q} \\in \\mathbb{R}^d$ and the key $\\mathbf{k}_i \\in \\mathbb{R}^d$ are independent and identically drawn random variables with zero mean and unit variance. The dot product between both vectors has zero mean and a variance of $d$. To ensure that the variance of the dot product still remains $1$ regardless of vector length, we use the *scaled dot product attention* scoring function. That is, we rescale the dot product by $1/\\sqrt{d}$. We thus arrive at the first commonly used attention function that is used, e.g., in Transformers :cite:`Vaswani.Shazeer.Parmar.ea.2017`:\n", "\n", "$$ a(\\mathbf{q}, \\mathbf{k}_i) = \\mathbf{q}^\\top \\mathbf{k}_i / \\sqrt{d}.$$\n", ":eqlabel:`eq_dot_product_attention`\n", "\n", "Note that attention weights $\\alpha$ still need normalizing. We can simplify this further via :eqref:`eq_softmax_attention` by using the softmax operation:\n", "\n", "$$\\alpha(\\mathbf{q}, \\mathbf{k}_i) = \\mathrm{softmax}(a(\\mathbf{q}, \\mathbf{k}_i)) = \\frac{\\exp(\\mathbf{q}^\\top \\mathbf{k}_i / \\sqrt{d})}{\\sum_{j=1} \\exp(\\mathbf{q}^\\top \\mathbf{k}_j / \\sqrt{d})}.$$\n", ":eqlabel:`eq_attn-scoring-alpha`\n", "\n", "As it turns out, all popular attention mechanisms use the softmax, hence we will limit ourselves to that in the remainder of this chapter.\n", "\n", "## Convenience Functions\n", "\n", "We need a few functions to make the attention mechanism efficient to deploy. This includes tools for dealing with strings of variable lengths (common for natural language processing) and tools for efficient evaluation on minibatches (batch matrix multiplication). \n", "\n", "\n", "### [**Masked Softmax Operation**]\n", "\n", "One of the most popular applications of the attention mechanism is to sequence models. Hence we need to be able to deal with sequences of different lengths. In some cases, such sequences may end up in the same minibatch, necessitating padding with dummy tokens for shorter sequences (see :numref:`sec_machine_translation` for an example). These special tokens do not carry meaning. For instance, assume that we have the following three sentences:\n", "\n", "```\n", "Dive into Deep Learning \n", "Learn to code \n", "Hello world \n", "```\n", "\n", "Since we do not want blanks in our attention model we simply need to limit $\\sum_{i=1}^n \\alpha(\\mathbf{q}, \\mathbf{k}_i) \\mathbf{v}_i$ to $\\sum_{i=1}^l \\alpha(\\mathbf{q}, \\mathbf{k}_i) \\mathbf{v}_i$ for however long, $l \\leq n$, the actual sentence is. Since it is such a common problem, it has a name: the *masked softmax operation*. \n", "\n", "Let's implement it. Actually, the implementation cheats ever so slightly by setting the values of $\\mathbf{v}_i$, for $i > l$, to zero. Moreover, it sets the attention weights to a large negative number, such as $-10^{6}$, in order to make their contribution to gradients and values vanish in practice. This is done since linear algebra kernels and operators are heavily optimized for GPUs and it is faster to be slightly wasteful in computation rather than to have code with conditional (if then else) statements.\n" ] }, { "cell_type": "code", "execution_count": 2, "id": "080c4919", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:48.508521Z", "iopub.status.busy": "2023-08-18T19:43:48.507880Z", "iopub.status.idle": "2023-08-18T19:43:48.515032Z", "shell.execute_reply": "2023-08-18T19:43:48.514260Z" }, "origin_pos": 8, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "def masked_softmax(X, valid_lens): #@save\n", " \"\"\"Perform softmax operation by masking elements on the last axis.\"\"\"\n", " # X: 3D tensor, valid_lens: 1D or 2D tensor\n", " def _sequence_mask(X, valid_len, value=0):\n", " maxlen = X.size(1)\n", " mask = torch.arange((maxlen), dtype=torch.float32,\n", " device=X.device)[None, :] < valid_len[:, None]\n", " X[~mask] = value\n", " return X\n", "\n", " if valid_lens is None:\n", " return nn.functional.softmax(X, dim=-1)\n", " else:\n", " shape = X.shape\n", " if valid_lens.dim() == 1:\n", " valid_lens = torch.repeat_interleave(valid_lens, shape[1])\n", " else:\n", " valid_lens = valid_lens.reshape(-1)\n", " # On the last axis, replace masked elements with a very large negative\n", " # value, whose exponentiation outputs 0\n", " X = _sequence_mask(X.reshape(-1, shape[-1]), valid_lens, value=-1e6)\n", " return nn.functional.softmax(X.reshape(shape), dim=-1)" ] }, { "cell_type": "markdown", "id": "ac9441c0", "metadata": { "origin_pos": 11 }, "source": [ "To [**illustrate how this function works**],\n", "consider a minibatch of two examples of size $2 \\times 4$,\n", "where their valid lengths are $2$ and $3$, respectively. \n", "As a result of the masked softmax operation,\n", "values beyond the valid lengths for each pair of vectors are all masked as zero.\n" ] }, { "cell_type": "code", "execution_count": 3, "id": "b0fb493b", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:48.518456Z", "iopub.status.busy": "2023-08-18T19:43:48.517778Z", "iopub.status.idle": "2023-08-18T19:43:48.554108Z", "shell.execute_reply": "2023-08-18T19:43:48.553283Z" }, "origin_pos": 13, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([[[0.4448, 0.5552, 0.0000, 0.0000],\n", " [0.4032, 0.5968, 0.0000, 0.0000]],\n", "\n", " [[0.2795, 0.2805, 0.4400, 0.0000],\n", " [0.2798, 0.3092, 0.4110, 0.0000]]])" ] }, "execution_count": 3, "metadata": {}, "output_type": "execute_result" } ], "source": [ "masked_softmax(torch.rand(2, 2, 4), torch.tensor([2, 3]))" ] }, { "cell_type": "markdown", "id": "390fd5a8", "metadata": { "origin_pos": 16 }, "source": [ "If we need more fine-grained control to specify the valid length for each of the two vectors of every example, we simply use a two-dimensional tensor of valid lengths. This yields:\n" ] }, { "cell_type": "code", "execution_count": 4, "id": "0eff10c9", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:48.557828Z", "iopub.status.busy": "2023-08-18T19:43:48.557262Z", "iopub.status.idle": "2023-08-18T19:43:48.564098Z", "shell.execute_reply": "2023-08-18T19:43:48.563239Z" }, "origin_pos": 18, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "text/plain": [ "tensor([[[1.0000, 0.0000, 0.0000, 0.0000],\n", " [0.4109, 0.2794, 0.3097, 0.0000]],\n", "\n", " [[0.3960, 0.6040, 0.0000, 0.0000],\n", " [0.2557, 0.1833, 0.2420, 0.3190]]])" ] }, "execution_count": 4, "metadata": {}, "output_type": "execute_result" } ], "source": [ "masked_softmax(torch.rand(2, 2, 4), torch.tensor([[1, 3], [2, 4]]))" ] }, { "cell_type": "markdown", "id": "a03f10da", "metadata": { "origin_pos": 21 }, "source": [ "### Batch Matrix Multiplication\n", ":label:`subsec_batch_dot`\n", "\n", "Another commonly used operation is to multiply batches of matrices by one another. This comes in handy when we have minibatches of queries, keys, and values. More specifically, assume that \n", "\n", "$$\\mathbf{Q} = [\\mathbf{Q}_1, \\mathbf{Q}_2, \\ldots, \\mathbf{Q}_n] \\in \\mathbb{R}^{n \\times a \\times b}, \\\\\n", " \\mathbf{K} = [\\mathbf{K}_1, \\mathbf{K}_2, \\ldots, \\mathbf{K}_n] \\in \\mathbb{R}^{n \\times b \\times c}.\n", "$$\n", "\n", "Then the batch matrix multiplication (BMM) computes the elementwise product\n", "\n", "$$\\textrm{BMM}(\\mathbf{Q}, \\mathbf{K}) = [\\mathbf{Q}_1 \\mathbf{K}_1, \\mathbf{Q}_2 \\mathbf{K}_2, \\ldots, \\mathbf{Q}_n \\mathbf{K}_n] \\in \\mathbb{R}^{n \\times a \\times c}.$$\n", ":eqlabel:`eq_batch-matrix-mul`\n", "\n", "Let's see this in action in a deep learning framework.\n" ] }, { "cell_type": "code", "execution_count": 5, "id": "1d592456", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:48.567605Z", "iopub.status.busy": "2023-08-18T19:43:48.567037Z", "iopub.status.idle": "2023-08-18T19:43:48.572146Z", "shell.execute_reply": "2023-08-18T19:43:48.571131Z" }, "origin_pos": 23, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "Q = torch.ones((2, 3, 4))\n", "K = torch.ones((2, 4, 6))\n", "d2l.check_shape(torch.bmm(Q, K), (2, 3, 6))" ] }, { "cell_type": "markdown", "id": "4aef7274", "metadata": { "origin_pos": 26 }, "source": [ "## [**Scaled Dot Product Attention**]\n", "\n", "Let's return to the dot product attention introduced in :eqref:`eq_dot_product_attention`. \n", "In general, it requires that both the query and the key\n", "have the same vector length, say $d$, even though this can be addressed easily by replacing \n", "$\\mathbf{q}^\\top \\mathbf{k}$ with $\\mathbf{q}^\\top \\mathbf{M} \\mathbf{k}$ where $\\mathbf{M}$ is a matrix suitably chosen for translating between both spaces. For now assume that the dimensions match. \n", "\n", "In practice, we often think of minibatches for efficiency,\n", "such as computing attention for $n$ queries and $m$ key-value pairs,\n", "where queries and keys are of length $d$\n", "and values are of length $v$. The scaled dot product attention \n", "of queries $\\mathbf Q\\in\\mathbb R^{n\\times d}$,\n", "keys $\\mathbf K\\in\\mathbb R^{m\\times d}$,\n", "and values $\\mathbf V\\in\\mathbb R^{m\\times v}$\n", "thus can be written as \n", "\n", "$$ \\mathrm{softmax}\\left(\\frac{\\mathbf Q \\mathbf K^\\top }{\\sqrt{d}}\\right) \\mathbf V \\in \\mathbb{R}^{n\\times v}.$$\n", ":eqlabel:`eq_softmax_QK_V`\n", "\n", "Note that when applying this to a minibatch, we need the batch matrix multiplication introduced in :eqref:`eq_batch-matrix-mul`. In the following implementation of the scaled dot product attention,\n", "we use dropout for model regularization.\n" ] }, { "cell_type": "code", "execution_count": 6, "id": "33207d5f", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:48.575743Z", "iopub.status.busy": "2023-08-18T19:43:48.575036Z", "iopub.status.idle": "2023-08-18T19:43:48.581055Z", "shell.execute_reply": "2023-08-18T19:43:48.580209Z" }, "origin_pos": 28, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "class DotProductAttention(nn.Module): #@save\n", " \"\"\"Scaled dot product attention.\"\"\"\n", " def __init__(self, dropout):\n", " super().__init__()\n", " self.dropout = nn.Dropout(dropout)\n", "\n", " # Shape of queries: (batch_size, no. of queries, d)\n", " # Shape of keys: (batch_size, no. of key-value pairs, d)\n", " # Shape of values: (batch_size, no. of key-value pairs, value dimension)\n", " # Shape of valid_lens: (batch_size,) or (batch_size, no. of queries)\n", " def forward(self, queries, keys, values, valid_lens=None):\n", " d = queries.shape[-1]\n", " # Swap the last two dimensions of keys with keys.transpose(1, 2)\n", " scores = torch.bmm(queries, keys.transpose(1, 2)) / math.sqrt(d)\n", " self.attention_weights = masked_softmax(scores, valid_lens)\n", " return torch.bmm(self.dropout(self.attention_weights), values)" ] }, { "cell_type": "markdown", "id": "dbb8df37", "metadata": { "origin_pos": 31 }, "source": [ "To [**illustrate how the `DotProductAttention` class works**],\n", "we use the same keys, values, and valid lengths from the earlier toy example for additive attention. For the purpose of our example we assume that we have a minibatch size of $2$, a total of $10$ keys and values, and that the dimensionality of the values is $4$. Lastly, we assume that the valid length per observation is $2$ and $6$ respectively. Given that, we expect the output to be a $2 \\times 1 \\times 4$ tensor, i.e., one row per example of the minibatch.\n" ] }, { "cell_type": "code", "execution_count": 7, "id": "2f449209", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:48.584794Z", "iopub.status.busy": "2023-08-18T19:43:48.584072Z", "iopub.status.idle": "2023-08-18T19:43:48.590854Z", "shell.execute_reply": "2023-08-18T19:43:48.589996Z" }, "origin_pos": 33, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "queries = torch.normal(0, 1, (2, 1, 2))\n", "keys = torch.normal(0, 1, (2, 10, 2))\n", "values = torch.normal(0, 1, (2, 10, 4))\n", "valid_lens = torch.tensor([2, 6])\n", "\n", "attention = DotProductAttention(dropout=0.5)\n", "attention.eval()\n", "d2l.check_shape(attention(queries, keys, values, valid_lens), (2, 1, 4))" ] }, { "cell_type": "markdown", "id": "00e17255", "metadata": { "origin_pos": 36 }, "source": [ "Let's check whether the attention weights actually vanish for anything beyond the second and sixth column respectively (because of setting the valid length to $2$ and $6$).\n" ] }, { "cell_type": "code", "execution_count": 8, "id": "f40e370d", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:48.594461Z", "iopub.status.busy": "2023-08-18T19:43:48.593898Z", "iopub.status.idle": "2023-08-18T19:43:48.969221Z", "shell.execute_reply": "2023-08-18T19:43:48.968308Z" }, "origin_pos": 37, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "image/svg+xml": [ "\n", "\n", "\n", " \n", " \n", " \n", " \n", " 2023-08-18T19:43:48.906167\n", " image/svg+xml\n", " \n", " \n", " Matplotlib v3.7.2, https://matplotlib.org/\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "\n" ], "text/plain": [ "
" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),\n", " xlabel='Keys', ylabel='Queries')" ] }, { "cell_type": "markdown", "id": "583e7b8d", "metadata": { "origin_pos": 39 }, "source": [ "## [**Additive Attention**]\n", ":label:`subsec_additive-attention`\n", "\n", "When queries $\\mathbf{q}$ and keys $\\mathbf{k}$ are vectors of different dimension,\n", "we can either use a matrix to address the mismatch via $\\mathbf{q}^\\top \\mathbf{M} \\mathbf{k}$, or we can use additive attention \n", "as the scoring function. Another benefit is that, as its name indicates, the attention is additive. This can lead to some minor computational savings. \n", "Given a query $\\mathbf{q} \\in \\mathbb{R}^q$\n", "and a key $\\mathbf{k} \\in \\mathbb{R}^k$,\n", "the *additive attention* scoring function :cite:`Bahdanau.Cho.Bengio.2014` is given by \n", "\n", "$$a(\\mathbf q, \\mathbf k) = \\mathbf w_v^\\top \\textrm{tanh}(\\mathbf W_q\\mathbf q + \\mathbf W_k \\mathbf k) \\in \\mathbb{R},$$\n", ":eqlabel:`eq_additive-attn`\n", "\n", "where $\\mathbf W_q\\in\\mathbb R^{h\\times q}$, $\\mathbf W_k\\in\\mathbb R^{h\\times k}$, \n", "and $\\mathbf w_v\\in\\mathbb R^{h}$ are the learnable parameters. This term is then fed into a softmax to ensure both nonnegativity and normalization. \n", "An equivalent interpretation of :eqref:`eq_additive-attn` is that the query and key are concatenated\n", "and fed into an MLP with a single hidden layer. \n", "Using $\\tanh$ as the activation function and disabling bias terms, \n", "we implement additive attention as follows:\n" ] }, { "cell_type": "code", "execution_count": 9, "id": "3a2e6dee", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:48.973108Z", "iopub.status.busy": "2023-08-18T19:43:48.972388Z", "iopub.status.idle": "2023-08-18T19:43:48.979819Z", "shell.execute_reply": "2023-08-18T19:43:48.978914Z" }, "origin_pos": 41, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "class AdditiveAttention(nn.Module): #@save\n", " \"\"\"Additive attention.\"\"\"\n", " def __init__(self, num_hiddens, dropout, **kwargs):\n", " super(AdditiveAttention, self).__init__(**kwargs)\n", " self.W_k = nn.LazyLinear(num_hiddens, bias=False)\n", " self.W_q = nn.LazyLinear(num_hiddens, bias=False)\n", " self.w_v = nn.LazyLinear(1, bias=False)\n", " self.dropout = nn.Dropout(dropout)\n", "\n", " def forward(self, queries, keys, values, valid_lens):\n", " queries, keys = self.W_q(queries), self.W_k(keys)\n", " # After dimension expansion, shape of queries: (batch_size, no. of\n", " # queries, 1, num_hiddens) and shape of keys: (batch_size, 1, no. of\n", " # key-value pairs, num_hiddens). Sum them up with broadcasting\n", " features = queries.unsqueeze(2) + keys.unsqueeze(1)\n", " features = torch.tanh(features)\n", " # There is only one output of self.w_v, so we remove the last\n", " # one-dimensional entry from the shape. Shape of scores: (batch_size,\n", " # no. of queries, no. of key-value pairs)\n", " scores = self.w_v(features).squeeze(-1)\n", " self.attention_weights = masked_softmax(scores, valid_lens)\n", " # Shape of values: (batch_size, no. of key-value pairs, value\n", " # dimension)\n", " return torch.bmm(self.dropout(self.attention_weights), values)" ] }, { "cell_type": "markdown", "id": "4c313394", "metadata": { "origin_pos": 44 }, "source": [ "Let's [**see how `AdditiveAttention` works**]. In our toy example we pick queries, keys and values of size \n", "$(2, 1, 20)$, $(2, 10, 2)$ and $(2, 10, 4)$, respectively. This is identical to our choice for `DotProductAttention`, except that now the queries are $20$-dimensional. Likewise, we pick $(2, 6)$ as the valid lengths for the sequences in the minibatch.\n" ] }, { "cell_type": "code", "execution_count": 10, "id": "c1e66c95", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:48.983249Z", "iopub.status.busy": "2023-08-18T19:43:48.982715Z", "iopub.status.idle": "2023-08-18T19:43:48.993364Z", "shell.execute_reply": "2023-08-18T19:43:48.992407Z" }, "origin_pos": 46, "tab": [ "pytorch" ] }, "outputs": [], "source": [ "queries = torch.normal(0, 1, (2, 1, 20))\n", "\n", "attention = AdditiveAttention(num_hiddens=8, dropout=0.1)\n", "attention.eval()\n", "d2l.check_shape(attention(queries, keys, values, valid_lens), (2, 1, 4))" ] }, { "cell_type": "markdown", "id": "d0f37c23", "metadata": { "origin_pos": 49 }, "source": [ "When reviewing the attention function we see a behavior that is qualitatively quite similar to that of `DotProductAttention`. That is, only terms within the chosen valid length $(2, 6)$ are nonzero.\n" ] }, { "cell_type": "code", "execution_count": 11, "id": "bf7a330b", "metadata": { "execution": { "iopub.execute_input": "2023-08-18T19:43:48.996815Z", "iopub.status.busy": "2023-08-18T19:43:48.996248Z", "iopub.status.idle": "2023-08-18T19:43:49.212301Z", "shell.execute_reply": "2023-08-18T19:43:49.211395Z" }, "origin_pos": 50, "tab": [ "pytorch" ] }, "outputs": [ { "data": { "image/svg+xml": [ "\n", "\n", "\n", " \n", " \n", " \n", " \n", " 2023-08-18T19:43:49.170875\n", " image/svg+xml\n", " \n", " \n", " Matplotlib v3.7.2, https://matplotlib.org/\n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", " \n", "\n" ], "text/plain": [ "
" ] }, "metadata": {}, "output_type": "display_data" } ], "source": [ "d2l.show_heatmaps(attention.attention_weights.reshape((1, 1, 2, 10)),\n", " xlabel='Keys', ylabel='Queries')" ] }, { "cell_type": "markdown", "id": "62fe2877", "metadata": { "origin_pos": 52 }, "source": [ "## Summary\n", "\n", "In this section we introduced the two key attention scoring functions: dot product and additive attention. They are effective tools for aggregating across sequences of variable length. In particular, the dot product attention is the mainstay of modern Transformer architectures. When queries and keys are vectors of different lengths,\n", "we can use the additive attention scoring function instead. Optimizing these layers is one of the key areas of advance in recent years. For instance, [NVIDIA's Transformer Library](https://docs.nvidia.com/deeplearning/transformer-engine/user-guide/index.html) and Megatron :cite:`shoeybi2019megatron` crucially rely on efficient variants of the attention mechanism. We will dive into this in quite a bit more detail as we review Transformers in later sections. \n", "\n", "## Exercises\n", "\n", "1. Implement distance-based attention by modifying the `DotProductAttention` code. Note that you only need the squared norms of the keys $\\|\\mathbf{k}_i\\|^2$ for an efficient implementation. \n", "1. Modify the dot product attention to allow for queries and keys of different dimensionalities by employing a matrix to adjust dimensions. \n", "1. How does the computational cost scale with the dimensionality of the keys, queries, values, and their number? What about the memory bandwidth requirements?\n" ] }, { "cell_type": "markdown", "id": "37239f57", "metadata": { "origin_pos": 54, "tab": [ "pytorch" ] }, "source": [ "[Discussions](https://discuss.d2l.ai/t/1064)\n" ] } ], "metadata": { "language_info": { "name": "python" }, "required_libs": [] }, "nbformat": 4, "nbformat_minor": 5 }