{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 0
   },
   "source": [
    "#  Sequence to Sequence Learning\n",
    ":label:`sec_seq2seq`\n",
    "\n",
    "As we have seen in :numref:`sec_machine_translation`,\n",
    "in machine translation\n",
    "both the input and output are a variable-length sequence.\n",
    "To address this type of problem,\n",
    "we have designed a general encoder-decoder architecture\n",
    "in :numref:`sec_encoder-decoder`.\n",
    "In this section,\n",
    "we will\n",
    "use two RNNs to design\n",
    "the encoder and the decoder of\n",
    "this architecture\n",
    "and apply it to *sequence to sequence* learning\n",
    "for machine translation\n",
    ":cite:`Sutskever.Vinyals.Le.2014,Cho.Van-Merrienboer.Gulcehre.ea.2014`.\n",
    "\n",
    "Following the design principle\n",
    "of the encoder-decoder architecture,\n",
    "the RNN encoder can\n",
    "take a variable-length sequence as the input and transforms it into a fixed-shape hidden state.\n",
    "In other words,\n",
    "information of the input (source) sequence\n",
    "is *encoded* in the hidden state of the RNN encoder.\n",
    "To generate the output sequence token by token,\n",
    "a separate RNN decoder\n",
    "can predict the next token based on\n",
    "what tokens have been seen (such as in language modeling) or generated,\n",
    "together with the encoded information of the input sequence.\n",
    ":numref:`fig_seq2seq` illustrates\n",
    "how to use two RNNs\n",
    "for sequence to sequence learning\n",
    "in machine translation.\n",
    "\n",
    "\n",
    "![Sequence to sequence learning with an RNN encoder and an RNN decoder.](../img/seq2seq.svg)\n",
    ":label:`fig_seq2seq`\n",
    "\n",
    "In :numref:`fig_seq2seq`,\n",
    "the special \"&lt;eos&gt;\" token\n",
    "marks the end of the sequence.\n",
    "The model can stop making predictions\n",
    "once this token is generated.\n",
    "At the initial time step of the RNN decoder,\n",
    "there are two special design decisions.\n",
    "First, the special beginning-of-sequence \"&lt;bos&gt;\" token is an input.\n",
    "Second,\n",
    "the final hidden state of the RNN encoder is used\n",
    "to initiate the hidden state of the decoder.\n",
    "In designs such as :cite:`Sutskever.Vinyals.Le.2014`,\n",
    "this is exactly\n",
    "how the encoded input sequence information\n",
    "is fed into the decoder for generating the output (target) sequence.\n",
    "In some other designs such as :cite:`Cho.Van-Merrienboer.Gulcehre.ea.2014`,\n",
    "the final hidden state of the encoder\n",
    "is also fed into the decoder as\n",
    "part of the inputs\n",
    "at every time step as shown in :numref:`fig_seq2seq`.\n",
    "Similar to the training of language models in\n",
    ":numref:`sec_language_model`,\n",
    "we can allow the labels to be the original output sequence,\n",
    "shifted by one token:\n",
    "\"&lt;bos&gt;\", \"Ils\", \"regardent\", \".\" $\\rightarrow$\n",
    "\"Ils\", \"regardent\", \".\", \"&lt;eos&gt;\".\n",
    "\n",
    "\n",
    "In the following,\n",
    "we will explain the design of :numref:`fig_seq2seq`\n",
    "in greater detail.\n",
    "We will train this model for machine translation\n",
    "on the English-French dataset as introduced in\n",
    ":numref:`sec_machine_translation`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {
    "origin_pos": 3,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [],
   "source": [
    "import collections\n",
    "import math\n",
    "import tensorflow as tf\n",
    "from d2l import tensorflow as d2l"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 4
   },
   "source": [
    "## Encoder\n",
    "\n",
    "Technically speaking,\n",
    "the encoder transforms an input sequence of variable length into a fixed-shape *context variable* $\\mathbf{c}$, and encodes the input sequence information in this context variable.\n",
    "As depicted in :numref:`fig_seq2seq`,\n",
    "we can use an RNN to design the encoder.\n",
    "\n",
    "Let us consider a sequence example (batch size: 1).\n",
    "Suppose that\n",
    "the input sequence is $x_1, \\ldots, x_T$, such that $x_t$ is the $t^{\\mathrm{th}}$ token in the input text sequence.\n",
    "At time step $t$, the RNN transforms\n",
    "the input feature vector $\\mathbf{x}_t$ for $x_t$\n",
    "and the hidden state $\\mathbf{h} _{t-1}$ from the previous time step\n",
    "into the current hidden state $\\mathbf{h}_t$.\n",
    "We can use a function $f$ to express the transformation of the RNN's recurrent layer:\n",
    "\n",
    "$$\\mathbf{h}_t = f(\\mathbf{x}_t, \\mathbf{h}_{t-1}). $$\n",
    "\n",
    "In general,\n",
    "the encoder transforms the hidden states at\n",
    "all the time steps\n",
    "into the context variable through a customized function $q$:\n",
    "\n",
    "$$\\mathbf{c} =  q(\\mathbf{h}_1, \\ldots, \\mathbf{h}_T).$$\n",
    "\n",
    "For example, when choosing $q(\\mathbf{h}_1, \\ldots, \\mathbf{h}_T) = \\mathbf{h}_T$ such as in :numref:`fig_seq2seq`,\n",
    "the context variable is just the hidden state $\\mathbf{h}_T$\n",
    "of the input sequence at the final time step.\n",
    "\n",
    "So far we have used a unidirectional RNN\n",
    "to design the encoder,\n",
    "where\n",
    "a hidden state only depends on\n",
    "the input subsequence at and before the time step of the hidden state.\n",
    "We can also construct encoders using bidirectional RNNs. In this case, a hidden state depends on\n",
    "the subsequence before and after the time step (including the input at the current time step), which encodes the information of the entire sequence.\n",
    "\n",
    "\n",
    "Now let us [**implement the RNN encoder**].\n",
    "Note that we use an *embedding layer*\n",
    "to obtain the feature vector for each token in the input sequence.\n",
    "The weight\n",
    "of an embedding layer\n",
    "is a matrix\n",
    "whose number of rows equals to the size of the input vocabulary (`vocab_size`)\n",
    "and number of columns equals to the feature vector's dimension (`embed_size`).\n",
    "For any input token index $i$,\n",
    "the embedding layer\n",
    "fetches the $i^{\\mathrm{th}}$ row (starting from 0) of the weight matrix\n",
    "to return its feature vector.\n",
    "Besides,\n",
    "here we choose a multilayer GRU to\n",
    "implement the encoder.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {
    "origin_pos": 7,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "class Seq2SeqEncoder(d2l.Encoder):\n",
    "    \"\"\"The RNN encoder for sequence to sequence learning.\"\"\"\n",
    "    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers, dropout=0, **kwargs):\n",
    "        super().__init__(*kwargs)\n",
    "        # Embedding layer\n",
    "        self.embedding = tf.keras.layers.Embedding(vocab_size, embed_size)\n",
    "        self.rnn = tf.keras.layers.RNN(tf.keras.layers.StackedRNNCells(\n",
    "            [tf.keras.layers.GRUCell(num_hiddens, dropout=dropout)\n",
    "             for _ in range(num_layers)]), return_sequences=True,\n",
    "                                       return_state=True)\n",
    "\n",
    "    def call(self, X, *args, **kwargs):\n",
    "        # The input `X` shape: (`batch_size`, `num_steps`)\n",
    "        # The output `X` shape: (`batch_size`, `num_steps`, `embed_size`)\n",
    "        X = self.embedding(X)\n",
    "        output = self.rnn(X, **kwargs)\n",
    "        state = output[1:]\n",
    "        return output[0], state"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 8
   },
   "source": [
    "The returned variables of recurrent layers\n",
    "have been explained in :numref:`sec_rnn-concise`.\n",
    "Let us still use a concrete example\n",
    "to [**illustrate the above encoder implementation.**]\n",
    "Below\n",
    "we instantiate a two-layer GRU encoder\n",
    "whose number of hidden units is 16.\n",
    "Given\n",
    "a minibatch of sequence inputs `X`\n",
    "(batch size: 4, number of time steps: 7),\n",
    "the hidden states of the last layer\n",
    "at all the time steps\n",
    "(`output` return by the encoder's recurrent layers)\n",
    "are a tensor\n",
    "of shape\n",
    "(number of time steps, batch size, number of hidden units).\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {
    "origin_pos": 11,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "TensorShape([4, 7, 16])"
      ]
     },
     "execution_count": 3,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "encoder = Seq2SeqEncoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2)\n",
    "X = tf.zeros((4, 7))\n",
    "output, state = encoder(X, training=False)\n",
    "output.shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 12
   },
   "source": [
    "Since a GRU is employed here,\n",
    "the shape of the multilayer hidden states\n",
    "at the final time step\n",
    "is\n",
    "(number of hidden layers, batch size, number of hidden units).\n",
    "If an LSTM is used,\n",
    "memory cell information will also be contained in `state`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {
    "origin_pos": 15,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(2, [TensorShape([4, 16]), TensorShape([4, 16])])"
      ]
     },
     "execution_count": 4,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "len(state), [element.shape for element in state]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 16
   },
   "source": [
    "## [**Decoder**]\n",
    ":label:`sec_seq2seq_decoder`\n",
    "\n",
    "As we just mentioned,\n",
    "the context variable $\\mathbf{c}$ of the encoder's output encodes the entire input sequence $x_1, \\ldots, x_T$. Given the output sequence $y_1, y_2, \\ldots, y_{T'}$ from the training dataset,\n",
    "for each time step $t'$\n",
    "(the symbol differs from the time step $t$ of input sequences or encoders),\n",
    "the probability of the decoder output $y_{t'}$\n",
    "is conditional\n",
    "on the previous output subsequence\n",
    "$y_1, \\ldots, y_{t'-1}$ and\n",
    "the context variable $\\mathbf{c}$, i.e., $P(y_{t'} \\mid y_1, \\ldots, y_{t'-1}, \\mathbf{c})$.\n",
    "\n",
    "To model this conditional probability on sequences,\n",
    "we can use another RNN as the decoder.\n",
    "At any time step $t^\\prime$ on the output sequence,\n",
    "the RNN takes the output $y_{t^\\prime-1}$ from the previous time step\n",
    "and the context variable $\\mathbf{c}$ as its input,\n",
    "then transforms\n",
    "them and\n",
    "the previous hidden state $\\mathbf{s}_{t^\\prime-1}$\n",
    "into the\n",
    "hidden state $\\mathbf{s}_{t^\\prime}$ at the current time step.\n",
    "As a result, we can use a function $g$ to express the transformation of the decoder's hidden layer:\n",
    "\n",
    "$$\\mathbf{s}_{t^\\prime} = g(y_{t^\\prime-1}, \\mathbf{c}, \\mathbf{s}_{t^\\prime-1}).$$\n",
    ":eqlabel:`eq_seq2seq_s_t`\n",
    "\n",
    "After obtaining the hidden state of the decoder,\n",
    "we can use an output layer and the softmax operation to compute the conditional probability distribution\n",
    "$P(y_{t^\\prime} \\mid y_1, \\ldots, y_{t^\\prime-1}, \\mathbf{c})$ for the output at time step $t^\\prime$.\n",
    "\n",
    "Following :numref:`fig_seq2seq`,\n",
    "when implementing the decoder as follows,\n",
    "we directly use the hidden state at the final time step\n",
    "of the encoder\n",
    "to initialize the hidden state of the decoder.\n",
    "This requires that the RNN encoder and the RNN decoder have the same number of layers and hidden units.\n",
    "To further incorporate the encoded input sequence information,\n",
    "the context variable is concatenated\n",
    "with the decoder input at all the time steps.\n",
    "To predict the probability distribution of the output token,\n",
    "a fully-connected layer is used to transform\n",
    "the hidden state at the final layer of the RNN decoder.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {
    "origin_pos": 19,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [],
   "source": [
    "class Seq2SeqDecoder(d2l.Decoder):\n",
    "    \"\"\"The RNN decoder for sequence to sequence learning.\"\"\"\n",
    "    def __init__(self, vocab_size, embed_size, num_hiddens, num_layers,\n",
    "                 dropout=0, **kwargs):\n",
    "        super().__init__(**kwargs)\n",
    "        self.embedding = tf.keras.layers.Embedding(vocab_size, embed_size)\n",
    "        self.rnn = tf.keras.layers.RNN(tf.keras.layers.StackedRNNCells(\n",
    "            [tf.keras.layers.GRUCell(num_hiddens, dropout=dropout)\n",
    "             for _ in range(num_layers)]), return_sequences=True,\n",
    "                                       return_state=True)\n",
    "        self.dense = tf.keras.layers.Dense(vocab_size)\n",
    "\n",
    "    def init_state(self, enc_outputs, *args):\n",
    "        return enc_outputs[1]\n",
    "\n",
    "    def call(self, X, state, **kwargs):\n",
    "        # The output `X` shape: (`batch_size`, `num_steps`, `embed_size`)\n",
    "        X = self.embedding(X)\n",
    "        # Broadcast `context` so it has the same `num_steps` as `X`\n",
    "        context = tf.repeat(tf.expand_dims(state[-1], axis=1), repeats=X.shape[1], axis=1)\n",
    "        X_and_context = tf.concat((X, context), axis=2)\n",
    "        rnn_output = self.rnn(X_and_context, state, **kwargs)\n",
    "        output = self.dense(rnn_output[0])\n",
    "        # `output` shape: (`batch_size`, `num_steps`, `vocab_size`)\n",
    "        # `state` is a list with `num_layers` entries. Each entry has shape:\n",
    "        # (`batch_size`, `num_hiddens`)\n",
    "        return output, rnn_output[1:]"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 20
   },
   "source": [
    "To [**illustrate the implemented decoder**],\n",
    "below we instantiate it with the same hyperparameters from the aforementioned encoder.\n",
    "As we can see, the output shape of the decoder becomes (batch size, number of time steps, vocabulary size),\n",
    "where the last dimension of the tensor stores the predicted token distribution.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {
    "origin_pos": 23,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "(TensorShape([4, 7, 10]), 2, TensorShape([4, 16]))"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "decoder = Seq2SeqDecoder(vocab_size=10, embed_size=8, num_hiddens=16, num_layers=2)\n",
    "state = decoder.init_state(encoder(X))\n",
    "output, state = decoder(X, state, training=False)\n",
    "output.shape, len(state), state[0].shape"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 24
   },
   "source": [
    "To summarize,\n",
    "the layers in the above RNN encoder-decoder model are illustrated in :numref:`fig_seq2seq_details`.\n",
    "\n",
    "![Layers in an RNN encoder-decoder model.](../img/seq2seq-details.svg)\n",
    ":label:`fig_seq2seq_details`\n",
    "\n",
    "## Loss Function\n",
    "\n",
    "At each time step, the decoder\n",
    "predicts a probability distribution for the output tokens.\n",
    "Similar to language modeling,\n",
    "we can apply softmax to obtain the distribution\n",
    "and calculate the cross-entropy loss for optimization.\n",
    "Recall :numref:`sec_machine_translation`\n",
    "that the special padding tokens\n",
    "are appended to the end of sequences\n",
    "so sequences of varying lengths\n",
    "can be efficiently loaded\n",
    "in minibatches of the same shape.\n",
    "However,\n",
    "prediction of padding tokens\n",
    "should be excluded from loss calculations.\n",
    "\n",
    "To this end,\n",
    "we can use the following\n",
    "`sequence_mask` function\n",
    "to [**mask irrelevant entries with zero values**]\n",
    "so later\n",
    "multiplication of any irrelevant prediction\n",
    "with zero equals to zero.\n",
    "For example,\n",
    "if the valid length of two sequences\n",
    "excluding padding tokens\n",
    "are one and two, respectively,\n",
    "the remaining entries after\n",
    "the first one\n",
    "and the first two entries are cleared to zeros.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {
    "origin_pos": 27,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(2, 3), dtype=int32, numpy=\n",
       "array([[1, 0, 0],\n",
       "       [4, 5, 0]], dtype=int32)>"
      ]
     },
     "execution_count": 7,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "#@save\n",
    "def sequence_mask(X, valid_len, value=0):\n",
    "    \"\"\"Mask irrelevant entries in sequences.\"\"\"\n",
    "    maxlen = X.shape[1]\n",
    "    mask = tf.range(start=0, limit=maxlen, dtype=tf.float32)[\n",
    "        None, :] < tf.cast(valid_len[:, None], dtype=tf.float32)\n",
    "\n",
    "    if len(X.shape) == 3:\n",
    "        return tf.where(tf.expand_dims(mask, axis=-1), X, value)\n",
    "    else:\n",
    "        return tf.where(mask, X, value)\n",
    "\n",
    "X = tf.constant([[1, 2, 3], [4, 5, 6]])\n",
    "sequence_mask(X, tf.constant([1, 2]))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 28
   },
   "source": [
    "(**We can also mask all the entries across the last\n",
    "few axes.**)\n",
    "If you like, you may even specify\n",
    "to replace such entries with a non-zero value.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {
    "origin_pos": 31,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<tf.Tensor: shape=(2, 3, 4), dtype=float32, numpy=\n",
       "array([[[ 1.,  1.,  1.,  1.],\n",
       "        [-1., -1., -1., -1.],\n",
       "        [-1., -1., -1., -1.]],\n",
       "\n",
       "       [[ 1.,  1.,  1.,  1.],\n",
       "        [ 1.,  1.,  1.,  1.],\n",
       "        [-1., -1., -1., -1.]]], dtype=float32)>"
      ]
     },
     "execution_count": 8,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "X = tf.ones((2,3,4))\n",
    "sequence_mask(X, tf.constant([1, 2]), value=-1)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 32
   },
   "source": [
    "Now we can [**extend the softmax cross-entropy loss\n",
    "to allow the masking of irrelevant predictions.**]\n",
    "Initially,\n",
    "masks for all the predicted tokens are set to one.\n",
    "Once the valid length is given,\n",
    "the mask corresponding to any padding token\n",
    "will be cleared to zero.\n",
    "In the end,\n",
    "the loss for all the tokens\n",
    "will be multipled by the mask to filter out\n",
    "irrelevant predictions of padding tokens in the loss.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {
    "origin_pos": 35,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "class MaskedSoftmaxCELoss(tf.keras.losses.Loss):\n",
    "    \"\"\"The softmax cross-entropy loss with masks.\"\"\"\n",
    "    def __init__(self, valid_len):\n",
    "        super().__init__(reduction='none')\n",
    "        self.valid_len = valid_len\n",
    "\n",
    "    # `pred` shape: (`batch_size`, `num_steps`, `vocab_size`)\n",
    "    # `label` shape: (`batch_size`, `num_steps`)\n",
    "    # `valid_len` shape: (`batch_size`,)\n",
    "    def call(self, label, pred):\n",
    "        weights = tf.ones_like(label, dtype=tf.float32)\n",
    "        weights = sequence_mask(weights, self.valid_len)\n",
    "        label_one_hot = tf.one_hot(label, depth=pred.shape[-1])\n",
    "        unweighted_loss = tf.keras.losses.CategoricalCrossentropy(\n",
    "            from_logits=True, reduction='none')(label_one_hot, pred)\n",
    "        weighted_loss = tf.reduce_mean((unweighted_loss*weights), axis=1)\n",
    "        return weighted_loss"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 36
   },
   "source": [
    "For [**a sanity check**], we can create three identical sequences.\n",
    "Then we can\n",
    "specify that the valid lengths of these sequences\n",
    "are 4, 2, and 0, respectively.\n",
    "As a result,\n",
    "the loss of the first sequence\n",
    "should be twice as large as that of the second sequence,\n",
    "while the third sequence should have a zero loss.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "origin_pos": 39,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "array([2.3025851, 1.1512926, 0.       ], dtype=float32)"
      ]
     },
     "execution_count": 10,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "loss = MaskedSoftmaxCELoss(tf.constant([4, 2, 0]))\n",
    "loss(tf.ones((3,4), dtype = tf.int32), tf.ones((3, 4, 10))).numpy()"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 40
   },
   "source": [
    "## [**Training**]\n",
    ":label:`sec_seq2seq_training`\n",
    "\n",
    "In the following training loop,\n",
    "we concatenate the special beginning-of-sequence token\n",
    "and the original output sequence excluding the final token as\n",
    "the input to the decoder, as shown in :numref:`fig_seq2seq`.\n",
    "This is called *teacher forcing* because\n",
    "the original output sequence (token labels) is fed into the decoder.\n",
    "Alternatively,\n",
    "we could also feed the *predicted* token\n",
    "from the previous time step\n",
    "as the current input to the decoder.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "origin_pos": 43,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "def train_seq2seq(net, data_iter, lr, num_epochs, tgt_vocab, device):\n",
    "    \"\"\"Train a model for sequence to sequence.\"\"\"\n",
    "    optimizer = tf.keras.optimizers.Adam(learning_rate=lr)\n",
    "    animator = d2l.Animator(xlabel=\"epoch\", ylabel=\"loss\",\n",
    "                            xlim=[10, num_epochs])\n",
    "    for epoch in range(num_epochs):\n",
    "        timer = d2l.Timer()\n",
    "        metric = d2l.Accumulator(2)  # Sum of training loss, no. of tokens\n",
    "        for batch in data_iter:\n",
    "            X, X_valid_len, Y, Y_valid_len = [x for x in batch]\n",
    "            bos = tf.reshape(tf.constant([tgt_vocab['<bos>']] * Y.shape[0]),\n",
    "                             shape=(-1, 1))\n",
    "            dec_input = tf.concat([bos, Y[:, :-1]], 1)  # Teacher forcing\n",
    "            with tf.GradientTape() as tape:\n",
    "                Y_hat, _ = net(X, dec_input, X_valid_len, training=True)\n",
    "                l = MaskedSoftmaxCELoss(Y_valid_len)(Y, Y_hat)\n",
    "            gradients = tape.gradient(l, net.trainable_variables)\n",
    "            gradients = d2l.grad_clipping(gradients, 1)\n",
    "            optimizer.apply_gradients(zip(gradients, net.trainable_variables))\n",
    "            num_tokens = tf.reduce_sum(Y_valid_len).numpy()\n",
    "            metric.add(tf.reduce_sum(l), num_tokens)\n",
    "        if (epoch + 1) % 10 == 0:\n",
    "            animator.add(epoch + 1, (metric[0] / metric[1],))\n",
    "    print(f'loss {metric[0] / metric[1]:.3f}, {metric[1] / timer.stop():.1f} '\n",
    "          f'tokens/sec on {str(device)}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 44
   },
   "source": [
    "Now we can [**create and train an RNN encoder-decoder model**]\n",
    "for sequence to sequence learning on the machine translation dataset.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {
    "origin_pos": 45,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "loss 0.033, 1009.5 tokens/sec on <tensorflow.python.eager.context._EagerDeviceContext object at 0x7f84411c74c0>\n"
     ]
    },
    {
     "data": {
      "image/svg+xml": [
       "<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"no\"?>\n",
       "<!DOCTYPE svg PUBLIC \"-//W3C//DTD SVG 1.1//EN\"\n",
       "  \"http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd\">\n",
       "<svg xmlns:xlink=\"http://www.w3.org/1999/xlink\" width=\"262.1875pt\" height=\"180.65625pt\" viewBox=\"0 0 262.1875 180.65625\" xmlns=\"http://www.w3.org/2000/svg\" version=\"1.1\">\n",
       " <metadata>\n",
       "  <rdf:RDF xmlns:dc=\"http://purl.org/dc/elements/1.1/\" xmlns:cc=\"http://creativecommons.org/ns#\" xmlns:rdf=\"http://www.w3.org/1999/02/22-rdf-syntax-ns#\">\n",
       "   <cc:Work>\n",
       "    <dc:type rdf:resource=\"http://purl.org/dc/dcmitype/StillImage\"/>\n",
       "    <dc:date>2022-03-24T13:00:18.745828</dc:date>\n",
       "    <dc:format>image/svg+xml</dc:format>\n",
       "    <dc:creator>\n",
       "     <cc:Agent>\n",
       "      <dc:title>Matplotlib v3.5.1, https://matplotlib.org/</dc:title>\n",
       "     </cc:Agent>\n",
       "    </dc:creator>\n",
       "   </cc:Work>\n",
       "  </rdf:RDF>\n",
       " </metadata>\n",
       " <defs>\n",
       "  <style type=\"text/css\">*{stroke-linejoin: round; stroke-linecap: butt}</style>\n",
       " </defs>\n",
       " <g id=\"figure_1\">\n",
       "  <g id=\"patch_1\">\n",
       "   <path d=\"M 0 180.65625 \n",
       "L 262.1875 180.65625 \n",
       "L 262.1875 0 \n",
       "L 0 0 \n",
       "L 0 180.65625 \n",
       "z\n",
       "\" style=\"fill: none\"/>\n",
       "  </g>\n",
       "  <g id=\"axes_1\">\n",
       "   <g id=\"patch_2\">\n",
       "    <path d=\"M 50.14375 143.1 \n",
       "L 245.44375 143.1 \n",
       "L 245.44375 7.2 \n",
       "L 50.14375 7.2 \n",
       "z\n",
       "\" style=\"fill: #ffffff\"/>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_1\">\n",
       "    <g id=\"xtick_1\">\n",
       "     <g id=\"line2d_1\">\n",
       "      <path d=\"M 77.081681 143.1 \n",
       "L 77.081681 7.2 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_2\">\n",
       "      <defs>\n",
       "       <path id=\"me51f1c825e\" d=\"M 0 0 \n",
       "L 0 3.5 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#me51f1c825e\" x=\"77.081681\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_1\">\n",
       "      <!-- 50 -->\n",
       "      <g transform=\"translate(70.719181 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-35\" d=\"M 691 4666 \n",
       "L 3169 4666 \n",
       "L 3169 4134 \n",
       "L 1269 4134 \n",
       "L 1269 2991 \n",
       "Q 1406 3038 1543 3061 \n",
       "Q 1681 3084 1819 3084 \n",
       "Q 2600 3084 3056 2656 \n",
       "Q 3513 2228 3513 1497 \n",
       "Q 3513 744 3044 326 \n",
       "Q 2575 -91 1722 -91 \n",
       "Q 1428 -91 1123 -41 \n",
       "Q 819 9 494 109 \n",
       "L 494 744 \n",
       "Q 775 591 1075 516 \n",
       "Q 1375 441 1709 441 \n",
       "Q 2250 441 2565 725 \n",
       "Q 2881 1009 2881 1497 \n",
       "Q 2881 1984 2565 2268 \n",
       "Q 2250 2553 1709 2553 \n",
       "Q 1456 2553 1204 2497 \n",
       "Q 953 2441 691 2322 \n",
       "L 691 4666 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "        <path id=\"DejaVuSans-30\" d=\"M 2034 4250 \n",
       "Q 1547 4250 1301 3770 \n",
       "Q 1056 3291 1056 2328 \n",
       "Q 1056 1369 1301 889 \n",
       "Q 1547 409 2034 409 \n",
       "Q 2525 409 2770 889 \n",
       "Q 3016 1369 3016 2328 \n",
       "Q 3016 3291 2770 3770 \n",
       "Q 2525 4250 2034 4250 \n",
       "z\n",
       "M 2034 4750 \n",
       "Q 2819 4750 3233 4129 \n",
       "Q 3647 3509 3647 2328 \n",
       "Q 3647 1150 3233 529 \n",
       "Q 2819 -91 2034 -91 \n",
       "Q 1250 -91 836 529 \n",
       "Q 422 1150 422 2328 \n",
       "Q 422 3509 836 4129 \n",
       "Q 1250 4750 2034 4750 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-35\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_2\">\n",
       "     <g id=\"line2d_3\">\n",
       "      <path d=\"M 110.754095 143.1 \n",
       "L 110.754095 7.2 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_4\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#me51f1c825e\" x=\"110.754095\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_2\">\n",
       "      <!-- 100 -->\n",
       "      <g transform=\"translate(101.210345 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-31\" d=\"M 794 531 \n",
       "L 1825 531 \n",
       "L 1825 4091 \n",
       "L 703 3866 \n",
       "L 703 4441 \n",
       "L 1819 4666 \n",
       "L 2450 4666 \n",
       "L 2450 531 \n",
       "L 3481 531 \n",
       "L 3481 0 \n",
       "L 794 0 \n",
       "L 794 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_3\">\n",
       "     <g id=\"line2d_5\">\n",
       "      <path d=\"M 144.426509 143.1 \n",
       "L 144.426509 7.2 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_6\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#me51f1c825e\" x=\"144.426509\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_3\">\n",
       "      <!-- 150 -->\n",
       "      <g transform=\"translate(134.882759 157.698438)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-31\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_4\">\n",
       "     <g id=\"line2d_7\">\n",
       "      <path d=\"M 178.098922 143.1 \n",
       "L 178.098922 7.2 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_8\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#me51f1c825e\" x=\"178.098922\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_4\">\n",
       "      <!-- 200 -->\n",
       "      <g transform=\"translate(168.555172 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-32\" d=\"M 1228 531 \n",
       "L 3431 531 \n",
       "L 3431 0 \n",
       "L 469 0 \n",
       "L 469 531 \n",
       "Q 828 903 1448 1529 \n",
       "Q 2069 2156 2228 2338 \n",
       "Q 2531 2678 2651 2914 \n",
       "Q 2772 3150 2772 3378 \n",
       "Q 2772 3750 2511 3984 \n",
       "Q 2250 4219 1831 4219 \n",
       "Q 1534 4219 1204 4116 \n",
       "Q 875 4013 500 3803 \n",
       "L 500 4441 \n",
       "Q 881 4594 1212 4672 \n",
       "Q 1544 4750 1819 4750 \n",
       "Q 2544 4750 2975 4387 \n",
       "Q 3406 4025 3406 3419 \n",
       "Q 3406 3131 3298 2873 \n",
       "Q 3191 2616 2906 2266 \n",
       "Q 2828 2175 2409 1742 \n",
       "Q 1991 1309 1228 531 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_5\">\n",
       "     <g id=\"line2d_9\">\n",
       "      <path d=\"M 211.771336 143.1 \n",
       "L 211.771336 7.2 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_10\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#me51f1c825e\" x=\"211.771336\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_5\">\n",
       "      <!-- 250 -->\n",
       "      <g transform=\"translate(202.227586 157.698438)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-32\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"xtick_6\">\n",
       "     <g id=\"line2d_11\">\n",
       "      <path d=\"M 245.44375 143.1 \n",
       "L 245.44375 7.2 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_12\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#me51f1c825e\" x=\"245.44375\" y=\"143.1\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_6\">\n",
       "      <!-- 300 -->\n",
       "      <g transform=\"translate(235.9 157.698438)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-33\" d=\"M 2597 2516 \n",
       "Q 3050 2419 3304 2112 \n",
       "Q 3559 1806 3559 1356 \n",
       "Q 3559 666 3084 287 \n",
       "Q 2609 -91 1734 -91 \n",
       "Q 1441 -91 1130 -33 \n",
       "Q 819 25 488 141 \n",
       "L 488 750 \n",
       "Q 750 597 1062 519 \n",
       "Q 1375 441 1716 441 \n",
       "Q 2309 441 2620 675 \n",
       "Q 2931 909 2931 1356 \n",
       "Q 2931 1769 2642 2001 \n",
       "Q 2353 2234 1838 2234 \n",
       "L 1294 2234 \n",
       "L 1294 2753 \n",
       "L 1863 2753 \n",
       "Q 2328 2753 2575 2939 \n",
       "Q 2822 3125 2822 3475 \n",
       "Q 2822 3834 2567 4026 \n",
       "Q 2313 4219 1838 4219 \n",
       "Q 1578 4219 1281 4162 \n",
       "Q 984 4106 628 3988 \n",
       "L 628 4550 \n",
       "Q 988 4650 1302 4700 \n",
       "Q 1616 4750 1894 4750 \n",
       "Q 2613 4750 3031 4423 \n",
       "Q 3450 4097 3450 3541 \n",
       "Q 3450 3153 3228 2886 \n",
       "Q 3006 2619 2597 2516 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-33\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"127.246094\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_7\">\n",
       "     <!-- epoch -->\n",
       "     <g transform=\"translate(132.565625 171.376563)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-65\" d=\"M 3597 1894 \n",
       "L 3597 1613 \n",
       "L 953 1613 \n",
       "Q 991 1019 1311 708 \n",
       "Q 1631 397 2203 397 \n",
       "Q 2534 397 2845 478 \n",
       "Q 3156 559 3463 722 \n",
       "L 3463 178 \n",
       "Q 3153 47 2828 -22 \n",
       "Q 2503 -91 2169 -91 \n",
       "Q 1331 -91 842 396 \n",
       "Q 353 884 353 1716 \n",
       "Q 353 2575 817 3079 \n",
       "Q 1281 3584 2069 3584 \n",
       "Q 2775 3584 3186 3129 \n",
       "Q 3597 2675 3597 1894 \n",
       "z\n",
       "M 3022 2063 \n",
       "Q 3016 2534 2758 2815 \n",
       "Q 2500 3097 2075 3097 \n",
       "Q 1594 3097 1305 2825 \n",
       "Q 1016 2553 972 2059 \n",
       "L 3022 2063 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-70\" d=\"M 1159 525 \n",
       "L 1159 -1331 \n",
       "L 581 -1331 \n",
       "L 581 3500 \n",
       "L 1159 3500 \n",
       "L 1159 2969 \n",
       "Q 1341 3281 1617 3432 \n",
       "Q 1894 3584 2278 3584 \n",
       "Q 2916 3584 3314 3078 \n",
       "Q 3713 2572 3713 1747 \n",
       "Q 3713 922 3314 415 \n",
       "Q 2916 -91 2278 -91 \n",
       "Q 1894 -91 1617 61 \n",
       "Q 1341 213 1159 525 \n",
       "z\n",
       "M 3116 1747 \n",
       "Q 3116 2381 2855 2742 \n",
       "Q 2594 3103 2138 3103 \n",
       "Q 1681 3103 1420 2742 \n",
       "Q 1159 2381 1159 1747 \n",
       "Q 1159 1113 1420 752 \n",
       "Q 1681 391 2138 391 \n",
       "Q 2594 391 2855 752 \n",
       "Q 3116 1113 3116 1747 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-6f\" d=\"M 1959 3097 \n",
       "Q 1497 3097 1228 2736 \n",
       "Q 959 2375 959 1747 \n",
       "Q 959 1119 1226 758 \n",
       "Q 1494 397 1959 397 \n",
       "Q 2419 397 2687 759 \n",
       "Q 2956 1122 2956 1747 \n",
       "Q 2956 2369 2687 2733 \n",
       "Q 2419 3097 1959 3097 \n",
       "z\n",
       "M 1959 3584 \n",
       "Q 2709 3584 3137 3096 \n",
       "Q 3566 2609 3566 1747 \n",
       "Q 3566 888 3137 398 \n",
       "Q 2709 -91 1959 -91 \n",
       "Q 1206 -91 779 398 \n",
       "Q 353 888 353 1747 \n",
       "Q 353 2609 779 3096 \n",
       "Q 1206 3584 1959 3584 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-63\" d=\"M 3122 3366 \n",
       "L 3122 2828 \n",
       "Q 2878 2963 2633 3030 \n",
       "Q 2388 3097 2138 3097 \n",
       "Q 1578 3097 1268 2742 \n",
       "Q 959 2388 959 1747 \n",
       "Q 959 1106 1268 751 \n",
       "Q 1578 397 2138 397 \n",
       "Q 2388 397 2633 464 \n",
       "Q 2878 531 3122 666 \n",
       "L 3122 134 \n",
       "Q 2881 22 2623 -34 \n",
       "Q 2366 -91 2075 -91 \n",
       "Q 1284 -91 818 406 \n",
       "Q 353 903 353 1747 \n",
       "Q 353 2603 823 3093 \n",
       "Q 1294 3584 2113 3584 \n",
       "Q 2378 3584 2631 3529 \n",
       "Q 2884 3475 3122 3366 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-68\" d=\"M 3513 2113 \n",
       "L 3513 0 \n",
       "L 2938 0 \n",
       "L 2938 2094 \n",
       "Q 2938 2591 2744 2837 \n",
       "Q 2550 3084 2163 3084 \n",
       "Q 1697 3084 1428 2787 \n",
       "Q 1159 2491 1159 1978 \n",
       "L 1159 0 \n",
       "L 581 0 \n",
       "L 581 4863 \n",
       "L 1159 4863 \n",
       "L 1159 2956 \n",
       "Q 1366 3272 1645 3428 \n",
       "Q 1925 3584 2291 3584 \n",
       "Q 2894 3584 3203 3211 \n",
       "Q 3513 2838 3513 2113 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-65\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-70\" x=\"61.523438\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\" x=\"125\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-63\" x=\"186.181641\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-68\" x=\"241.162109\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"matplotlib.axis_2\">\n",
       "    <g id=\"ytick_1\">\n",
       "     <g id=\"line2d_13\">\n",
       "      <path d=\"M 50.14375 125.571812 \n",
       "L 245.44375 125.571812 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_14\">\n",
       "      <defs>\n",
       "       <path id=\"m6faf25315f\" d=\"M 0 0 \n",
       "L -3.5 0 \n",
       "\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </defs>\n",
       "      <g>\n",
       "       <use xlink:href=\"#m6faf25315f\" x=\"50.14375\" y=\"125.571812\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_8\">\n",
       "      <!-- 0.05 -->\n",
       "      <g transform=\"translate(20.878125 129.371031)scale(0.1 -0.1)\">\n",
       "       <defs>\n",
       "        <path id=\"DejaVuSans-2e\" d=\"M 684 794 \n",
       "L 1344 794 \n",
       "L 1344 0 \n",
       "L 684 0 \n",
       "L 684 794 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       </defs>\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"95.410156\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_2\">\n",
       "     <g id=\"line2d_15\">\n",
       "      <path d=\"M 50.14375 93.20182 \n",
       "L 245.44375 93.20182 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_16\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m6faf25315f\" x=\"50.14375\" y=\"93.20182\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_9\">\n",
       "      <!-- 0.10 -->\n",
       "      <g transform=\"translate(20.878125 97.001039)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-31\" x=\"95.410156\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_3\">\n",
       "     <g id=\"line2d_17\">\n",
       "      <path d=\"M 50.14375 60.831829 \n",
       "L 245.44375 60.831829 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_18\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m6faf25315f\" x=\"50.14375\" y=\"60.831829\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_10\">\n",
       "      <!-- 0.15 -->\n",
       "      <g transform=\"translate(20.878125 64.631047)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-31\" x=\"95.410156\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-35\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"ytick_4\">\n",
       "     <g id=\"line2d_19\">\n",
       "      <path d=\"M 50.14375 28.461837 \n",
       "L 245.44375 28.461837 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #b0b0b0; stroke-width: 0.8; stroke-linecap: square\"/>\n",
       "     </g>\n",
       "     <g id=\"line2d_20\">\n",
       "      <g>\n",
       "       <use xlink:href=\"#m6faf25315f\" x=\"50.14375\" y=\"28.461837\" style=\"stroke: #000000; stroke-width: 0.8\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "     <g id=\"text_11\">\n",
       "      <!-- 0.20 -->\n",
       "      <g transform=\"translate(20.878125 32.261055)scale(0.1 -0.1)\">\n",
       "       <use xlink:href=\"#DejaVuSans-30\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-2e\" x=\"63.623047\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-32\" x=\"95.410156\"/>\n",
       "       <use xlink:href=\"#DejaVuSans-30\" x=\"159.033203\"/>\n",
       "      </g>\n",
       "     </g>\n",
       "    </g>\n",
       "    <g id=\"text_12\">\n",
       "     <!-- loss -->\n",
       "     <g transform=\"translate(14.798437 84.807812)rotate(-90)scale(0.1 -0.1)\">\n",
       "      <defs>\n",
       "       <path id=\"DejaVuSans-6c\" d=\"M 603 4863 \n",
       "L 1178 4863 \n",
       "L 1178 0 \n",
       "L 603 0 \n",
       "L 603 4863 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "       <path id=\"DejaVuSans-73\" d=\"M 2834 3397 \n",
       "L 2834 2853 \n",
       "Q 2591 2978 2328 3040 \n",
       "Q 2066 3103 1784 3103 \n",
       "Q 1356 3103 1142 2972 \n",
       "Q 928 2841 928 2578 \n",
       "Q 928 2378 1081 2264 \n",
       "Q 1234 2150 1697 2047 \n",
       "L 1894 2003 \n",
       "Q 2506 1872 2764 1633 \n",
       "Q 3022 1394 3022 966 \n",
       "Q 3022 478 2636 193 \n",
       "Q 2250 -91 1575 -91 \n",
       "Q 1294 -91 989 -36 \n",
       "Q 684 19 347 128 \n",
       "L 347 722 \n",
       "Q 666 556 975 473 \n",
       "Q 1284 391 1588 391 \n",
       "Q 1994 391 2212 530 \n",
       "Q 2431 669 2431 922 \n",
       "Q 2431 1156 2273 1281 \n",
       "Q 2116 1406 1581 1522 \n",
       "L 1381 1569 \n",
       "Q 847 1681 609 1914 \n",
       "Q 372 2147 372 2553 \n",
       "Q 372 3047 722 3315 \n",
       "Q 1072 3584 1716 3584 \n",
       "Q 2034 3584 2315 3537 \n",
       "Q 2597 3491 2834 3397 \n",
       "z\n",
       "\" transform=\"scale(0.015625)\"/>\n",
       "      </defs>\n",
       "      <use xlink:href=\"#DejaVuSans-6c\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-6f\" x=\"27.783203\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-73\" x=\"88.964844\"/>\n",
       "      <use xlink:href=\"#DejaVuSans-73\" x=\"141.064453\"/>\n",
       "     </g>\n",
       "    </g>\n",
       "   </g>\n",
       "   <g id=\"line2d_21\">\n",
       "    <path d=\"M 50.14375 13.377273 \n",
       "L 56.878233 38.57887 \n",
       "L 63.612716 54.18391 \n",
       "L 70.347198 66.667049 \n",
       "L 77.081681 76.178345 \n",
       "L 83.816164 85.36872 \n",
       "L 90.550647 92.254846 \n",
       "L 97.285129 97.51129 \n",
       "L 104.019612 103.025046 \n",
       "L 110.754095 107.565948 \n",
       "L 117.488578 110.572039 \n",
       "L 124.22306 113.114913 \n",
       "L 130.957543 116.024775 \n",
       "L 137.692026 119.190463 \n",
       "L 144.426509 120.694069 \n",
       "L 151.160991 122.946598 \n",
       "L 157.895474 125.302117 \n",
       "L 164.629957 126.297153 \n",
       "L 171.36444 128.327256 \n",
       "L 178.098922 129.941698 \n",
       "L 184.833405 130.735083 \n",
       "L 191.567888 131.873096 \n",
       "L 198.302371 132.441214 \n",
       "L 205.036853 133.785801 \n",
       "L 211.771336 134.647079 \n",
       "L 218.505819 134.729428 \n",
       "L 225.240302 135.662565 \n",
       "L 231.974784 136.282828 \n",
       "L 238.709267 136.922727 \n",
       "L 245.44375 136.894777 \n",
       "\" clip-path=\"url(#p791556e053)\" style=\"fill: none; stroke: #1f77b4; stroke-width: 1.5; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_3\">\n",
       "    <path d=\"M 50.14375 143.1 \n",
       "L 50.14375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_4\">\n",
       "    <path d=\"M 245.44375 143.1 \n",
       "L 245.44375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_5\">\n",
       "    <path d=\"M 50.14375 143.1 \n",
       "L 245.44375 143.1 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "   <g id=\"patch_6\">\n",
       "    <path d=\"M 50.14375 7.2 \n",
       "L 245.44375 7.2 \n",
       "\" style=\"fill: none; stroke: #000000; stroke-width: 0.8; stroke-linejoin: miter; stroke-linecap: square\"/>\n",
       "   </g>\n",
       "  </g>\n",
       " </g>\n",
       " <defs>\n",
       "  <clipPath id=\"p791556e053\">\n",
       "   <rect x=\"50.14375\" y=\"7.2\" width=\"195.3\" height=\"135.9\"/>\n",
       "  </clipPath>\n",
       " </defs>\n",
       "</svg>\n"
      ],
      "text/plain": [
       "<Figure size 252x180 with 1 Axes>"
      ]
     },
     "metadata": {
      "needs_background": "light"
     },
     "output_type": "display_data"
    }
   ],
   "source": [
    "embed_size, num_hiddens, num_layers, dropout = 32, 32, 2, 0.1\n",
    "batch_size, num_steps = 64, 10\n",
    "lr, num_epochs, device = 0.005, 300, d2l.try_gpu()\n",
    "\n",
    "train_iter, src_vocab, tgt_vocab = d2l.load_data_nmt(batch_size, num_steps)\n",
    "encoder = Seq2SeqEncoder(\n",
    "    len(src_vocab), embed_size, num_hiddens, num_layers, dropout)\n",
    "decoder = Seq2SeqDecoder(\n",
    "    len(tgt_vocab), embed_size, num_hiddens, num_layers, dropout)\n",
    "net = d2l.EncoderDecoder(encoder, decoder)\n",
    "train_seq2seq(net, train_iter, lr, num_epochs, tgt_vocab, device)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 46
   },
   "source": [
    "## [**Prediction**]\n",
    "\n",
    "To predict the output sequence\n",
    "token by token,\n",
    "at each decoder time step\n",
    "the predicted token from the previous\n",
    "time step is fed into the decoder as an input.\n",
    "Similar to training,\n",
    "at the initial time step\n",
    "the beginning-of-sequence (\"&lt;bos&gt;\") token\n",
    "is fed into the decoder.\n",
    "This prediction process\n",
    "is illustrated in :numref:`fig_seq2seq_predict`.\n",
    "When the end-of-sequence (\"&lt;eos&gt;\") token is predicted,\n",
    "the prediction of the output sequence is complete.\n",
    "\n",
    "\n",
    "![Predicting the output sequence token by token using an RNN encoder-decoder.](../img/seq2seq-predict.svg)\n",
    ":label:`fig_seq2seq_predict`\n",
    "\n",
    "We will introduce different\n",
    "strategies for sequence generation in\n",
    ":numref:`sec_beam-search`.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {
    "origin_pos": 49,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [],
   "source": [
    "#@save\n",
    "def predict_seq2seq(net, src_sentence, src_vocab, tgt_vocab, num_steps,\n",
    "                    save_attention_weights=False):\n",
    "    \"\"\"Predict for sequence to sequence.\"\"\"\n",
    "    src_tokens = src_vocab[src_sentence.lower().split(' ')] + [\n",
    "        src_vocab['<eos>']]\n",
    "    enc_valid_len = tf.constant([len(src_tokens)])\n",
    "    src_tokens = d2l.truncate_pad(src_tokens, num_steps, src_vocab['<pad>'])\n",
    "    # Add the batch axis\n",
    "    enc_X = tf.expand_dims(src_tokens, axis=0)\n",
    "    enc_outputs = net.encoder(enc_X, enc_valid_len, training=False)\n",
    "    dec_state = net.decoder.init_state(enc_outputs, enc_valid_len)\n",
    "    # Add the batch axis\n",
    "    dec_X = tf.expand_dims(tf.constant([tgt_vocab['<bos>']]), axis=0)\n",
    "    output_seq, attention_weight_seq = [], []\n",
    "    for _ in range(num_steps):\n",
    "        Y, dec_state = net.decoder(dec_X, dec_state, training=False)\n",
    "        # We use the token with the highest prediction likelihood as the input\n",
    "        # of the decoder at the next time step\n",
    "        dec_X = tf.argmax(Y, axis=2)\n",
    "        pred = tf.squeeze(dec_X, axis=0)\n",
    "        # Save attention weights\n",
    "        if save_attention_weights:\n",
    "            attention_weight_seq.append(net.decoder.attention_weights)\n",
    "        # Once the end-of-sequence token is predicted, the generation of the\n",
    "        # output sequence is complete\n",
    "        if pred == tgt_vocab['<eos>']:\n",
    "            break\n",
    "        output_seq.append(pred.numpy())\n",
    "    return ' '.join(tgt_vocab.to_tokens(tf.reshape(output_seq, shape = -1).numpy().tolist())), attention_weight_seq"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 50
   },
   "source": [
    "## Evaluation of Predicted Sequences\n",
    "\n",
    "We can evaluate a predicted sequence\n",
    "by comparing it with the\n",
    "label sequence (the ground-truth).\n",
    "BLEU (Bilingual Evaluation Understudy),\n",
    "though originally proposed for evaluating\n",
    "machine translation results :cite:`Papineni.Roukos.Ward.ea.2002`,\n",
    "has been extensively used in measuring\n",
    "the quality of output sequences for different applications.\n",
    "In principle, for any $n$-grams in the predicted sequence,\n",
    "BLEU evaluates whether this $n$-grams appears\n",
    "in the label sequence.\n",
    "\n",
    "Denote by $p_n$\n",
    "the precision of $n$-grams,\n",
    "which is\n",
    "the ratio of\n",
    "the number of matched $n$-grams in\n",
    "the predicted and label sequences\n",
    "to\n",
    "the number of $n$-grams in the predicted sequence.\n",
    "To explain,\n",
    "given a label sequence $A$, $B$, $C$, $D$, $E$, $F$,\n",
    "and a predicted sequence $A$, $B$, $B$, $C$, $D$,\n",
    "we have $p_1 = 4/5$,  $p_2 = 3/4$, $p_3 = 1/3$, and $p_4 = 0$.\n",
    "Besides,\n",
    "let $\\mathrm{len}_{\\text{label}}$ and $\\mathrm{len}_{\\text{pred}}$\n",
    "be\n",
    "the numbers of tokens in the label sequence and the predicted sequence, respectively.\n",
    "Then, BLEU is defined as\n",
    "\n",
    "$$ \\exp\\left(\\min\\left(0, 1 - \\frac{\\mathrm{len}_{\\text{label}}}{\\mathrm{len}_{\\text{pred}}}\\right)\\right) \\prod_{n=1}^k p_n^{1/2^n},$$\n",
    ":eqlabel:`eq_bleu`\n",
    "\n",
    "where $k$ is the longest $n$-grams for matching.\n",
    "\n",
    "Based on the definition of BLEU in :eqref:`eq_bleu`,\n",
    "whenever the predicted sequence is the same as the label sequence, BLEU is 1.\n",
    "Moreover,\n",
    "since matching longer $n$-grams is more difficult,\n",
    "BLEU assigns a greater weight\n",
    "to a longer $n$-gram precision.\n",
    "Specifically, when $p_n$ is fixed,\n",
    "$p_n^{1/2^n}$ increases as $n$ grows (the original paper uses $p_n^{1/n}$).\n",
    "Furthermore,\n",
    "since\n",
    "predicting shorter sequences\n",
    "tends to obtain a higher $p_n$ value,\n",
    "the coefficient before the multiplication term in :eqref:`eq_bleu`\n",
    "penalizes shorter predicted sequences.\n",
    "For example, when $k=2$,\n",
    "given the label sequence $A$, $B$, $C$, $D$, $E$, $F$ and the predicted sequence $A$, $B$,\n",
    "although $p_1 = p_2 = 1$, the penalty factor $\\exp(1-6/2) \\approx 0.14$ lowers the BLEU.\n",
    "\n",
    "We [**implement the BLEU measure**] as follows.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {
    "origin_pos": 51,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [],
   "source": [
    "def bleu(pred_seq, label_seq, k):  #@save\n",
    "    \"\"\"Compute the BLEU.\"\"\"\n",
    "    pred_tokens, label_tokens = pred_seq.split(' '), label_seq.split(' ')\n",
    "    len_pred, len_label = len(pred_tokens), len(label_tokens)\n",
    "    score = math.exp(min(0, 1 - len_label / len_pred))\n",
    "    for n in range(1, k + 1):\n",
    "        num_matches, label_subs = 0, collections.defaultdict(int)\n",
    "        for i in range(len_label - n + 1):\n",
    "            label_subs[' '.join(label_tokens[i: i + n])] += 1\n",
    "        for i in range(len_pred - n + 1):\n",
    "            if label_subs[' '.join(pred_tokens[i: i + n])] > 0:\n",
    "                num_matches += 1\n",
    "                label_subs[' '.join(pred_tokens[i: i + n])] -= 1\n",
    "        score *= math.pow(num_matches / (len_pred - n + 1), math.pow(0.5, n))\n",
    "    return score"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 52
   },
   "source": [
    "In the end,\n",
    "we use the trained RNN encoder-decoder\n",
    "to [**translate a few English sentences into French**]\n",
    "and compute the BLEU of the results.\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {
    "origin_pos": 54,
    "tab": [
     "tensorflow"
    ]
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "go . => va !, bleu 1.000\n",
      "i lost . => j'ai perdu ., bleu 1.000\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "he's calm . => j'ai <unk> un mouvement la la la la la <unk>, bleu 0.000\n",
      "i'm home . => je suis malade ., bleu 0.512\n"
     ]
    }
   ],
   "source": [
    "engs = ['go .', \"i lost .\", 'he\\'s calm .', 'i\\'m home .']\n",
    "fras = ['va !', 'j\\'ai perdu .', 'il est calme .', 'je suis chez moi .']\n",
    "for eng, fra in zip(engs, fras):\n",
    "    translation, attention_weight_seq = predict_seq2seq(\n",
    "        net, eng, src_vocab, tgt_vocab, num_steps)\n",
    "    print(f'{eng} => {translation}, bleu {bleu(translation, fra, k=2):.3f}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {
    "origin_pos": 55
   },
   "source": [
    "## Summary\n",
    "\n",
    "* Following the design of the encoder-decoder architecture, we can use two RNNs to design a model for sequence to sequence learning.\n",
    "* When implementing the encoder and the decoder, we can use multilayer RNNs.\n",
    "* We can use masks to filter out irrelevant computations, such as when calculating the loss.\n",
    "* In encoder-decoder training, the teacher forcing approach feeds original output sequences (in contrast to predictions) into the decoder.\n",
    "* BLEU is a popular measure for evaluating output sequences by matching $n$-grams between the predicted sequence and the label sequence.\n",
    "\n",
    "\n",
    "## Exercises\n",
    "\n",
    "1. Can you adjust the hyperparameters to improve the translation results?\n",
    "1. Rerun the experiment without using masks in the loss calculation. What results do you observe? Why?\n",
    "1. If the encoder and the decoder differ in the number of layers or the number of hidden units, how can we initialize the hidden state of the decoder?\n",
    "1. In training, replace teacher forcing with feeding the prediction at the previous time step into the decoder. How does this influence the performance?\n",
    "1. Rerun the experiment by replacing GRU with LSTM.\n",
    "1. Are there any other ways to design the output layer of the decoder?\n"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}