{
"cells": [
{
"cell_type": "markdown",
"id": "f21c7eb3",
"metadata": {
"origin_pos": 0
},
"source": [
"# 自然语言推断:使用注意力\n",
":label:`sec_natural-language-inference-attention`\n",
"\n",
"我们在 :numref:`sec_natural-language-inference-and-dataset`中介绍了自然语言推断任务和SNLI数据集。鉴于许多模型都是基于复杂而深度的架构,Parikh等人提出用注意力机制解决自然语言推断问题,并称之为“可分解注意力模型” :cite:`Parikh.Tackstrom.Das.ea.2016`。这使得模型没有循环层或卷积层,在SNLI数据集上以更少的参数实现了当时的最佳结果。本节将描述并实现这种基于注意力的自然语言推断方法(使用MLP),如 :numref:`fig_nlp-map-nli-attention`中所述。\n",
"\n",
"\n",
":label:`fig_nlp-map-nli-attention`\n",
"\n",
"## 模型\n",
"\n",
"与保留前提和假设中词元的顺序相比,我们可以将一个文本序列中的词元与另一个文本序列中的每个词元对齐,然后比较和聚合这些信息,以预测前提和假设之间的逻辑关系。与机器翻译中源句和目标句之间的词元对齐类似,前提和假设之间的词元对齐可以通过注意力机制灵活地完成。\n",
"\n",
"\n",
":label:`fig_nli_attention`\n",
"\n",
" :numref:`fig_nli_attention`描述了使用注意力机制的自然语言推断方法。从高层次上讲,它由三个联合训练的步骤组成:对齐、比较和汇总。我们将在下面一步一步地对它们进行说明。\n"
]
},
{
"cell_type": "code",
"execution_count": 1,
"id": "012b50e0",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:26.279483Z",
"iopub.status.busy": "2023-08-18T06:58:26.278712Z",
"iopub.status.idle": "2023-08-18T06:58:29.526584Z",
"shell.execute_reply": "2023-08-18T06:58:29.525381Z"
},
"origin_pos": 2,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"import torch\n",
"from torch import nn\n",
"from torch.nn import functional as F\n",
"from d2l import torch as d2l"
]
},
{
"cell_type": "markdown",
"id": "8daac4ce",
"metadata": {
"origin_pos": 4
},
"source": [
"### 注意(Attending)\n",
"\n",
"第一步是将一个文本序列中的词元与另一个序列中的每个词元对齐。假设前提是“我确实需要睡眠”,假设是“我累了”。由于语义上的相似性,我们不妨将假设中的“我”与前提中的“我”对齐,将假设中的“累”与前提中的“睡眠”对齐。同样,我们可能希望将前提中的“我”与假设中的“我”对齐,将前提中的“需要”和“睡眠”与假设中的“累”对齐。请注意,这种对齐是使用加权平均的“软”对齐,其中理想情况下较大的权重与要对齐的词元相关联。为了便于演示, :numref:`fig_nli_attention`以“硬”对齐的方式显示了这种对齐方式。\n",
"\n",
"现在,我们更详细地描述使用注意力机制的软对齐。用$\\mathbf{A} = (\\mathbf{a}_1, \\ldots, \\mathbf{a}_m)$和$\\mathbf{B} = (\\mathbf{b}_1, \\ldots, \\mathbf{b}_n)$表示前提和假设,其词元数量分别为$m$和$n$,其中$\\mathbf{a}_i, \\mathbf{b}_j \\in \\mathbb{R}^{d}$($i = 1, \\ldots, m, j = 1, \\ldots, n$)是$d$维的词向量。对于软对齐,我们将注意力权重$e_{ij} \\in \\mathbb{R}$计算为:\n",
"\n",
"$$e_{ij} = f(\\mathbf{a}_i)^\\top f(\\mathbf{b}_j),$$\n",
":eqlabel:`eq_nli_e`\n",
"\n",
"其中函数$f$是在下面的`mlp`函数中定义的多层感知机。输出维度$f$由`mlp`的`num_hiddens`参数指定。\n"
]
},
{
"cell_type": "code",
"execution_count": 2,
"id": "03198966",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:29.532436Z",
"iopub.status.busy": "2023-08-18T06:58:29.531669Z",
"iopub.status.idle": "2023-08-18T06:58:29.540551Z",
"shell.execute_reply": "2023-08-18T06:58:29.539443Z"
},
"origin_pos": 6,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"def mlp(num_inputs, num_hiddens, flatten):\n",
" net = []\n",
" net.append(nn.Dropout(0.2))\n",
" net.append(nn.Linear(num_inputs, num_hiddens))\n",
" net.append(nn.ReLU())\n",
" if flatten:\n",
" net.append(nn.Flatten(start_dim=1))\n",
" net.append(nn.Dropout(0.2))\n",
" net.append(nn.Linear(num_hiddens, num_hiddens))\n",
" net.append(nn.ReLU())\n",
" if flatten:\n",
" net.append(nn.Flatten(start_dim=1))\n",
" return nn.Sequential(*net)"
]
},
{
"cell_type": "markdown",
"id": "fe5a88db",
"metadata": {
"origin_pos": 8
},
"source": [
"值得注意的是,在 :eqref:`eq_nli_e`中,$f$分别输入$\\mathbf{a}_i$和$\\mathbf{b}_j$,而不是将它们一对放在一起作为输入。这种*分解*技巧导致$f$只有$m + n$个次计算(线性复杂度),而不是$mn$次计算(二次复杂度)\n",
"\n",
"对 :eqref:`eq_nli_e`中的注意力权重进行规范化,我们计算假设中所有词元向量的加权平均值,以获得假设的表示,该假设与前提中索引$i$的词元进行软对齐:\n",
"\n",
"$$\n",
"\\boldsymbol{\\beta}_i = \\sum_{j=1}^{n}\\frac{\\exp(e_{ij})}{ \\sum_{k=1}^{n} \\exp(e_{ik})} \\mathbf{b}_j.\n",
"$$\n",
"\n",
"同样,我们计算假设中索引为$j$的每个词元与前提词元的软对齐:\n",
"\n",
"$$\n",
"\\boldsymbol{\\alpha}_j = \\sum_{i=1}^{m}\\frac{\\exp(e_{ij})}{ \\sum_{k=1}^{m} \\exp(e_{kj})} \\mathbf{a}_i.\n",
"$$\n",
"\n",
"下面,我们定义`Attend`类来计算假设(`beta`)与输入前提`A`的软对齐以及前提(`alpha`)与输入假设`B`的软对齐。\n"
]
},
{
"cell_type": "code",
"execution_count": 3,
"id": "d57da2e1",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:29.545456Z",
"iopub.status.busy": "2023-08-18T06:58:29.544693Z",
"iopub.status.idle": "2023-08-18T06:58:29.554270Z",
"shell.execute_reply": "2023-08-18T06:58:29.553173Z"
},
"origin_pos": 10,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"class Attend(nn.Module):\n",
" def __init__(self, num_inputs, num_hiddens, **kwargs):\n",
" super(Attend, self).__init__(**kwargs)\n",
" self.f = mlp(num_inputs, num_hiddens, flatten=False)\n",
"\n",
" def forward(self, A, B):\n",
" # A/B的形状:(批量大小,序列A/B的词元数,embed_size)\n",
" # f_A/f_B的形状:(批量大小,序列A/B的词元数,num_hiddens)\n",
" f_A = self.f(A)\n",
" f_B = self.f(B)\n",
" # e的形状:(批量大小,序列A的词元数,序列B的词元数)\n",
" e = torch.bmm(f_A, f_B.permute(0, 2, 1))\n",
" # beta的形状:(批量大小,序列A的词元数,embed_size),\n",
" # 意味着序列B被软对齐到序列A的每个词元(beta的第1个维度)\n",
" beta = torch.bmm(F.softmax(e, dim=-1), B)\n",
" # beta的形状:(批量大小,序列B的词元数,embed_size),\n",
" # 意味着序列A被软对齐到序列B的每个词元(alpha的第1个维度)\n",
" alpha = torch.bmm(F.softmax(e.permute(0, 2, 1), dim=-1), A)\n",
" return beta, alpha"
]
},
{
"cell_type": "markdown",
"id": "17ead0f5",
"metadata": {
"origin_pos": 12
},
"source": [
"### 比较\n",
"\n",
"在下一步中,我们将一个序列中的词元与与该词元软对齐的另一个序列进行比较。请注意,在软对齐中,一个序列中的所有词元(尽管可能具有不同的注意力权重)将与另一个序列中的词元进行比较。为便于演示, :numref:`fig_nli_attention`对词元以*硬*的方式对齐。例如,上述的*注意*(attending)步骤确定前提中的“need”和“sleep”都与假设中的“tired”对齐,则将对“疲倦-需要睡眠”进行比较。\n",
"\n",
"在比较步骤中,我们将来自一个序列的词元的连结(运算符$[\\cdot, \\cdot]$)和来自另一序列的对齐的词元送入函数$g$(一个多层感知机):\n",
"\n",
"$$\\mathbf{v}_{A,i} = g([\\mathbf{a}_i, \\boldsymbol{\\beta}_i]), i = 1, \\ldots, m\\\\ \\mathbf{v}_{B,j} = g([\\mathbf{b}_j, \\boldsymbol{\\alpha}_j]), j = 1, \\ldots, n.$$\n",
"\n",
":eqlabel:`eq_nli_v_ab`\n",
"\n",
"在 :eqref:`eq_nli_v_ab`中,$\\mathbf{v}_{A,i}$是指,所有假设中的词元与前提中词元$i$软对齐,再与词元$i$的比较;而$\\mathbf{v}_{B,j}$是指,所有前提中的词元与假设中词元$i$软对齐,再与词元$i$的比较。下面的`Compare`个类定义了比较步骤。\n"
]
},
{
"cell_type": "code",
"execution_count": 4,
"id": "3587e2bc",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:29.559109Z",
"iopub.status.busy": "2023-08-18T06:58:29.558368Z",
"iopub.status.idle": "2023-08-18T06:58:29.566400Z",
"shell.execute_reply": "2023-08-18T06:58:29.565225Z"
},
"origin_pos": 14,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"class Compare(nn.Module):\n",
" def __init__(self, num_inputs, num_hiddens, **kwargs):\n",
" super(Compare, self).__init__(**kwargs)\n",
" self.g = mlp(num_inputs, num_hiddens, flatten=False)\n",
"\n",
" def forward(self, A, B, beta, alpha):\n",
" V_A = self.g(torch.cat([A, beta], dim=2))\n",
" V_B = self.g(torch.cat([B, alpha], dim=2))\n",
" return V_A, V_B"
]
},
{
"cell_type": "markdown",
"id": "60dd10dd",
"metadata": {
"origin_pos": 16
},
"source": [
"### 聚合\n",
"\n",
"现在我们有两组比较向量$\\mathbf{v}_{A,i}$($i = 1, \\ldots, m$)和$\\mathbf{v}_{B,j}$($j = 1, \\ldots, n$)。在最后一步中,我们将聚合这些信息以推断逻辑关系。我们首先求和这两组比较向量:\n",
"\n",
"$$\n",
"\\mathbf{v}_A = \\sum_{i=1}^{m} \\mathbf{v}_{A,i}, \\quad \\mathbf{v}_B = \\sum_{j=1}^{n}\\mathbf{v}_{B,j}.\n",
"$$\n",
"\n",
"接下来,我们将两个求和结果的连结提供给函数$h$(一个多层感知机),以获得逻辑关系的分类结果:\n",
"\n",
"$$\n",
"\\hat{\\mathbf{y}} = h([\\mathbf{v}_A, \\mathbf{v}_B]).\n",
"$$\n",
"\n",
"聚合步骤在以下`Aggregate`类中定义。\n"
]
},
{
"cell_type": "code",
"execution_count": 5,
"id": "24cd9b3d",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:29.571174Z",
"iopub.status.busy": "2023-08-18T06:58:29.570475Z",
"iopub.status.idle": "2023-08-18T06:58:29.578900Z",
"shell.execute_reply": "2023-08-18T06:58:29.577743Z"
},
"origin_pos": 18,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"class Aggregate(nn.Module):\n",
" def __init__(self, num_inputs, num_hiddens, num_outputs, **kwargs):\n",
" super(Aggregate, self).__init__(**kwargs)\n",
" self.h = mlp(num_inputs, num_hiddens, flatten=True)\n",
" self.linear = nn.Linear(num_hiddens, num_outputs)\n",
"\n",
" def forward(self, V_A, V_B):\n",
" # 对两组比较向量分别求和\n",
" V_A = V_A.sum(dim=1)\n",
" V_B = V_B.sum(dim=1)\n",
" # 将两个求和结果的连结送到多层感知机中\n",
" Y_hat = self.linear(self.h(torch.cat([V_A, V_B], dim=1)))\n",
" return Y_hat"
]
},
{
"cell_type": "markdown",
"id": "9f9b14fe",
"metadata": {
"origin_pos": 20
},
"source": [
"### 整合代码\n",
"\n",
"通过将注意步骤、比较步骤和聚合步骤组合在一起,我们定义了可分解注意力模型来联合训练这三个步骤。\n"
]
},
{
"cell_type": "code",
"execution_count": 6,
"id": "6b99cb6a",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:29.583787Z",
"iopub.status.busy": "2023-08-18T06:58:29.583094Z",
"iopub.status.idle": "2023-08-18T06:58:29.593524Z",
"shell.execute_reply": "2023-08-18T06:58:29.592256Z"
},
"origin_pos": 22,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"class DecomposableAttention(nn.Module):\n",
" def __init__(self, vocab, embed_size, num_hiddens, num_inputs_attend=100,\n",
" num_inputs_compare=200, num_inputs_agg=400, **kwargs):\n",
" super(DecomposableAttention, self).__init__(**kwargs)\n",
" self.embedding = nn.Embedding(len(vocab), embed_size)\n",
" self.attend = Attend(num_inputs_attend, num_hiddens)\n",
" self.compare = Compare(num_inputs_compare, num_hiddens)\n",
" # 有3种可能的输出:蕴涵、矛盾和中性\n",
" self.aggregate = Aggregate(num_inputs_agg, num_hiddens, num_outputs=3)\n",
"\n",
" def forward(self, X):\n",
" premises, hypotheses = X\n",
" A = self.embedding(premises)\n",
" B = self.embedding(hypotheses)\n",
" beta, alpha = self.attend(A, B)\n",
" V_A, V_B = self.compare(A, B, beta, alpha)\n",
" Y_hat = self.aggregate(V_A, V_B)\n",
" return Y_hat"
]
},
{
"cell_type": "markdown",
"id": "e6989df0",
"metadata": {
"origin_pos": 24
},
"source": [
"## 训练和评估模型\n",
"\n",
"现在,我们将在SNLI数据集上对定义好的可分解注意力模型进行训练和评估。我们从读取数据集开始。\n",
"\n",
"### 读取数据集\n",
"\n",
"我们使用 :numref:`sec_natural-language-inference-and-dataset`中定义的函数下载并读取SNLI数据集。批量大小和序列长度分别设置为$256$和$50$。\n"
]
},
{
"cell_type": "code",
"execution_count": 7,
"id": "b2b87351",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:58:29.598451Z",
"iopub.status.busy": "2023-08-18T06:58:29.597744Z",
"iopub.status.idle": "2023-08-18T06:59:16.165261Z",
"shell.execute_reply": "2023-08-18T06:59:16.164059Z"
},
"origin_pos": 25,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"Downloading ../data/snli_1.0.zip from https://nlp.stanford.edu/projects/snli/snli_1.0.zip...\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"read 549367 examples\n"
]
},
{
"name": "stdout",
"output_type": "stream",
"text": [
"read 9824 examples\n"
]
}
],
"source": [
"batch_size, num_steps = 256, 50\n",
"train_iter, test_iter, vocab = d2l.load_data_snli(batch_size, num_steps)"
]
},
{
"cell_type": "markdown",
"id": "effd33ee",
"metadata": {
"origin_pos": 27
},
"source": [
"### 创建模型\n",
"\n",
"我们使用预训练好的100维GloVe嵌入来表示输入词元。我们将向量$\\mathbf{a}_i$和$\\mathbf{b}_j$在 :eqref:`eq_nli_e`中的维数预定义为100。 :eqref:`eq_nli_e`中的函数$f$和 :eqref:`eq_nli_v_ab`中的函数$g$的输出维度被设置为200.然后我们创建一个模型实例,初始化它的参数,并加载GloVe嵌入来初始化输入词元的向量。\n"
]
},
{
"cell_type": "code",
"execution_count": 8,
"id": "5587af56",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:59:16.169126Z",
"iopub.status.busy": "2023-08-18T06:59:16.168798Z",
"iopub.status.idle": "2023-08-18T06:59:44.672054Z",
"shell.execute_reply": "2023-08-18T06:59:44.670793Z"
},
"origin_pos": 29,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"embed_size, num_hiddens, devices = 100, 200, d2l.try_all_gpus()\n",
"net = DecomposableAttention(vocab, embed_size, num_hiddens)\n",
"glove_embedding = d2l.TokenEmbedding('glove.6b.100d')\n",
"embeds = glove_embedding[vocab.idx_to_token]\n",
"net.embedding.weight.data.copy_(embeds);"
]
},
{
"cell_type": "markdown",
"id": "bccfd50d",
"metadata": {
"origin_pos": 31
},
"source": [
"### 训练和评估模型\n",
"\n",
"与 :numref:`sec_multi_gpu`中接受单一输入(如文本序列或图像)的`split_batch`函数不同,我们定义了一个`split_batch_multi_inputs`函数以小批量接受多个输入,如前提和假设。\n"
]
},
{
"cell_type": "markdown",
"id": "526be438",
"metadata": {
"origin_pos": 33
},
"source": [
"现在我们可以在SNLI数据集上训练和评估模型。\n"
]
},
{
"cell_type": "code",
"execution_count": 9,
"id": "ad101b85",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T06:59:44.678227Z",
"iopub.status.busy": "2023-08-18T06:59:44.677721Z",
"iopub.status.idle": "2023-08-18T07:02:56.417387Z",
"shell.execute_reply": "2023-08-18T07:02:56.416024Z"
},
"origin_pos": 35,
"tab": [
"pytorch"
]
},
"outputs": [
{
"name": "stdout",
"output_type": "stream",
"text": [
"loss 0.497, train acc 0.805, test acc 0.824\n",
"14163.6 examples/sec on [device(type='cuda', index=0), device(type='cuda', index=1)]\n"
]
},
{
"data": {
"image/svg+xml": [
"\n",
"\n",
"\n"
],
"text/plain": [
""
]
},
"metadata": {
"needs_background": "light"
},
"output_type": "display_data"
}
],
"source": [
"lr, num_epochs = 0.001, 4\n",
"trainer = torch.optim.Adam(net.parameters(), lr=lr)\n",
"loss = nn.CrossEntropyLoss(reduction=\"none\")\n",
"d2l.train_ch13(net, train_iter, test_iter, loss, trainer, num_epochs,\n",
" devices)"
]
},
{
"cell_type": "markdown",
"id": "d6855e87",
"metadata": {
"origin_pos": 37
},
"source": [
"### 使用模型\n",
"\n",
"最后,定义预测函数,输出一对前提和假设之间的逻辑关系。\n"
]
},
{
"cell_type": "code",
"execution_count": 10,
"id": "4bea7172",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:02:56.422878Z",
"iopub.status.busy": "2023-08-18T07:02:56.422048Z",
"iopub.status.idle": "2023-08-18T07:02:56.431275Z",
"shell.execute_reply": "2023-08-18T07:02:56.430126Z"
},
"origin_pos": 39,
"tab": [
"pytorch"
]
},
"outputs": [],
"source": [
"#@save\n",
"def predict_snli(net, vocab, premise, hypothesis):\n",
" \"\"\"预测前提和假设之间的逻辑关系\"\"\"\n",
" net.eval()\n",
" premise = torch.tensor(vocab[premise], device=d2l.try_gpu())\n",
" hypothesis = torch.tensor(vocab[hypothesis], device=d2l.try_gpu())\n",
" label = torch.argmax(net([premise.reshape((1, -1)),\n",
" hypothesis.reshape((1, -1))]), dim=1)\n",
" return 'entailment' if label == 0 else 'contradiction' if label == 1 \\\n",
" else 'neutral'"
]
},
{
"cell_type": "markdown",
"id": "e586a5a5",
"metadata": {
"origin_pos": 41
},
"source": [
"我们可以使用训练好的模型来获得对示例句子的自然语言推断结果。\n"
]
},
{
"cell_type": "code",
"execution_count": 11,
"id": "9830eae7",
"metadata": {
"execution": {
"iopub.execute_input": "2023-08-18T07:02:56.436285Z",
"iopub.status.busy": "2023-08-18T07:02:56.435278Z",
"iopub.status.idle": "2023-08-18T07:02:56.447228Z",
"shell.execute_reply": "2023-08-18T07:02:56.446040Z"
},
"origin_pos": 42,
"tab": [
"pytorch"
]
},
"outputs": [
{
"data": {
"text/plain": [
"'contradiction'"
]
},
"execution_count": 11,
"metadata": {},
"output_type": "execute_result"
}
],
"source": [
"predict_snli(net, vocab, ['he', 'is', 'good', '.'], ['he', 'is', 'bad', '.'])"
]
},
{
"cell_type": "markdown",
"id": "e5ddb189",
"metadata": {
"origin_pos": 43
},
"source": [
"## 小结\n",
"\n",
"* 可分解注意模型包括三个步骤来预测前提和假设之间的逻辑关系:注意、比较和聚合。\n",
"* 通过注意力机制,我们可以将一个文本序列中的词元与另一个文本序列中的每个词元对齐,反之亦然。这种对齐是使用加权平均的软对齐,其中理想情况下较大的权重与要对齐的词元相关联。\n",
"* 在计算注意力权重时,分解技巧会带来比二次复杂度更理想的线性复杂度。\n",
"* 我们可以使用预训练好的词向量作为下游自然语言处理任务(如自然语言推断)的输入表示。\n",
"\n",
"## 练习\n",
"\n",
"1. 使用其他超参数组合训练模型,能在测试集上获得更高的准确度吗?\n",
"1. 自然语言推断的可分解注意模型的主要缺点是什么?\n",
"1. 假设我们想要获得任何一对句子的语义相似级别(例如,0~1之间的连续值)。我们应该如何收集和标注数据集?请尝试设计一个有注意力机制的模型。\n"
]
},
{
"cell_type": "markdown",
"id": "e98a7edc",
"metadata": {
"origin_pos": 45,
"tab": [
"pytorch"
]
},
"source": [
"[Discussions](https://discuss.d2l.ai/t/5728)\n"
]
}
],
"metadata": {
"language_info": {
"name": "python"
},
"required_libs": []
},
"nbformat": 4,
"nbformat_minor": 5
}