{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "Tce3stUlHN0L"
      },
      "source": [
        "##### Copyright 2021 The TensorFlow Authors."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "cellView": "form",
        "id": "tuOe1ymfHZPu"
      },
      "outputs": [],
      "source": [
        "#@title Licensed under the Apache License, Version 2.0 (the \"License\");\n",
        "# you may not use this file except in compliance with the License.\n",
        "# You may obtain a copy of the License at\n",
        "#\n",
        "# https://www.apache.org/licenses/LICENSE-2.0\n",
        "#\n",
        "# Unless required by applicable law or agreed to in writing, software\n",
        "# distributed under the License is distributed on an \"AS IS\" BASIS,\n",
        "# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
        "# See the License for the specific language governing permissions and\n",
        "# limitations under the License."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "qFdPvlXBOdUN"
      },
      "source": [
        "# Decoding API"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MfBg1C5NB3X0"
      },
      "source": [
        "\u003ctable class=\"tfo-notebook-buttons\" align=\"left\"\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://www.tensorflow.org/text/guide/decoding_api\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/tf_logo_32px.png\" /\u003eView on TensorFlow.org\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://colab.research.google.com/github/tensorflow/text/blob/master/docs/guide/decoding_api.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/colab_logo_32px.png\" /\u003eRun in Google Colab\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca target=\"_blank\" href=\"https://github.com/tensorflow/text/blob/master/docs/guide/decoding_api.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/GitHub-Mark-32px.png\" /\u003eView on GitHub\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "  \u003ctd\u003e\n",
        "    \u003ca href=\"https://storage.googleapis.com/tensorflow_docs/text/docs/guide/decoding_api.ipynb\"\u003e\u003cimg src=\"https://www.tensorflow.org/images/download_logo_32px.png\" /\u003eDownload notebook\u003c/a\u003e\n",
        "  \u003c/td\u003e\n",
        "\u003c/table\u003e"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xHxb-dlhMIzW"
      },
      "source": [
        "## Overview\n",
        "In the recent past, there has been a lot of research in language generation with auto-regressive models. In auto-regressive language generation, the probability distribution of token at time step *K* is dependent on the model's token-predictions till step *K-1*. For these models, decoding strategies such as Beam search, Greedy, Top-p, and Top-k are critical components of the model and largely influence the style/nature of the generated output token at a given time step *K*. \n",
        "\n",
        "For example, **Beam search** reduces the risk of missing hidden high probability tokens by\n",
        "keeping the most likely num_beams of hypotheses at each time step and eventually\n",
        "choosing the hypothesis that has the overall highest probability.\n",
        "[Murray et al. (2018)](https://arxiv.org/abs/1808.10006) and\n",
        "[Yang et al. (2018)](https://arxiv.org/abs/1808.09582) show that beam search\n",
        "works well in Machine Translation tasks.\n",
        "Both **Beam search** \u0026 **Greedy** strategies have a possibility of generating\n",
        "repeating tokens.\n",
        "\n",
        "[Fan et. al (2018)](https://arxiv.org/pdf/1805.04833.pdf) introduced **Top-K\n",
        "sampling**, in which the K most likely tokens are filtered and the probability mass\n",
        "is redistributed among only those K tokens.\n",
        "\n",
        "[Ari Holtzman et. al (2019)](https://arxiv.org/pdf/1904.09751.pdf) introduced\n",
        "**Top-p sampling**, which chooses from the smallest possible set of tokens with\n",
        "cumulative probability that adds upto the probability *p*. The probability mass is then\n",
        "redistributed among this set. This way, the size of the set of tokens can\n",
        "dynamically increase and decrease.\n",
        "**Top-p, Top-k** are generally used in tasks such as story-generation.\n",
        "\n",
        "The Decoding API provides an interface to experiment with different decoding strategies on auto-regressive models.\n",
        "\n",
        "1. The following sampling strategies are provided in sampling_module.py, which inherits from the base Decoding class:\n",
        "  *   [top_p](https://arxiv.org/abs/1904.09751) : [github](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/ops/sampling_module.py#L65) \n",
        "\n",
        "  *   [top_k](https://arxiv.org/pdf/1805.04833.pdf) : [github](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/ops/sampling_module.py#L48)\n",
        "\n",
        "  *   Greedy : [github](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/ops/sampling_module.py#L26)\n",
        "\n",
        "2. Beam search is provided in beam_search.py. [github](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/ops/beam_search.py)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "MUXex9ctTuDB"
      },
      "source": [
        "## Setup"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "60_D9NLa9KhJ"
      },
      "outputs": [],
      "source": [
        "!pip install -q -U tensorflow-text"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "FJV1ttb8dZyQ"
      },
      "outputs": [],
      "source": [
        "!pip install -q tf-models-nightly"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "IqR2PQG4ZaZ0"
      },
      "outputs": [],
      "source": [
        "import numpy as np\n",
        "import matplotlib.pyplot as plt\n",
        "\n",
        "import tensorflow as tf\n",
        "\n",
        "from official import nlp\n",
        "from official.nlp.modeling.ops import sampling_module\n",
        "from official.nlp.modeling.ops import beam_search"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "j9r8-Q_CekYK"
      },
      "source": [
        "## Initialize Sampling Module in TF-NLP.\n",
        "\n",
        "\n",
        "* **symbols_to_logits_fn** : Use this closure to call the model to predict the logits for the `index+1` step. Inputs and outputs for this closure are as follows:  \n",
        "```\n",
        "Args:\n",
        "  1] ids : Current decoded sequences. int tensor with shape (batch_size, index + 1 or 1 if padded_decode is True)],\n",
        "  2] index [scalar] : current decoded step,\n",
        "  3] cache [nested dictionary of tensors] : Only used for faster decoding to store pre-computed attention hidden states for keys and values. More explanation in the cell below.\n",
        "Returns:\n",
        "  1] tensor for next-step logits [batch_size, vocab]\n",
        "  2] the updated_cache [nested dictionary of tensors].\n",
        "```\n",
        "The cache is used for faster decoding.\n",
        "Here is a [reference](https://github.com/tensorflow/models/blob/master/official/nlp/modeling/ops/beam_search_test.py#L88) implementation for the above closure.\n",
        "\n",
        "\n",
        "* **length_normalization_fn** : Use this closure for returning length normalization parameter.\n",
        "```\n",
        "Args: \n",
        "  1] length : scalar for decoded step index.\n",
        "  2] dtype : data-type of output tensor\n",
        "Returns:\n",
        "  1] value of length normalization factor.\n",
        "```\n",
        "\n",
        "* **vocab_size** : Output vocabulary size.\n",
        "\n",
        "* **max_decode_length** : Scalar for total number of decoding steps.\n",
        "\n",
        "* **eos_id** : Decoding will stop if all output decoded ids in the batch have this eos_id.\n",
        "\n",
        "* **padded_decode** : Set this to True if running on TPU. Tensors are padded to max_decoding_length if this is True.\n",
        "\n",
        "* **top_k** : top_k is enabled if this value is \u003e 1.\n",
        "\n",
        "* **top_p** : top_p is enabled if this value is \u003e 0 and \u003c 1.0\n",
        "\n",
        "* **sampling_temperature** : This is used to re-estimate the softmax output. Temperature skews the distribution towards high probability tokens and lowers the mass in tail distribution. Value has to be positive. Low temperature is equivalent to greedy and makes the distribution sharper, while high temperature makes it more flat.\n",
        "\n",
        "* **enable_greedy** : By default, this is True and greedy decoding is enabled. To experiment with other strategies, please set this to False."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "xqpGECmAeu7Q"
      },
      "source": [
        "## Initialize the Model hyperparameters"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "KtylpxOmceaC"
      },
      "outputs": [],
      "source": [
        "params = {}\n",
        "params['num_heads'] = 2\n",
        "params['num_layers'] = 2\n",
        "params['batch_size'] = 2\n",
        "params['n_dims'] = 256\n",
        "params['max_decode_length'] = 4"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pwdM2pl3RSPb"
      },
      "source": [
        "In auto-regressive architectures like Transformer based [Encoder-Decoder](https://arxiv.org/abs/1706.03762) models, \n",
        "Cache is used for fast sequential decoding.\n",
        "It is a nested dictionary storing pre-computed hidden-states (key and values in the self-attention blocks and in the cross-attention blocks) for every layer."
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "A_xX-fbze8_S"
      },
      "source": [
        "## Initialize cache. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "mMOeXVmbdilM"
      },
      "outputs": [],
      "source": [
        "cache = {\n",
        "    'layer_%d' % layer: {\n",
        "        'k': tf.zeros([params['batch_size'], params['max_decode_length'], params['num_heads'], int(params['n_dims']/params['num_heads'])], dtype=tf.float32),\n",
        "        'v': tf.zeros([params['batch_size'], params['max_decode_length'], params['num_heads'], int(params['n_dims']/params['num_heads'])], dtype=tf.float32)\n",
        "        } for layer in range(params['num_layers'])\n",
        "    }\n",
        "print(\"cache key shape for layer 1 :\", cache['layer_1']['k'].shape)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "-9BGL3gOe-2K"
      },
      "source": [
        "## Define closure for length normalization if needed.\n",
        "This is used for normalizing the final scores of generated sequences and is optional\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "U82B_tH2d294"
      },
      "outputs": [],
      "source": [
        "def length_norm(length, dtype):\n",
        "  \"\"\"Return length normalization factor.\"\"\"\n",
        "  return tf.pow(((5. + tf.cast(length, dtype)) / 6.), 0.0)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "TJdqBNBbS78n"
      },
      "source": [
        "## Create model_fn\n",
        "  In practice, this will be replaced by an actual model implementation such as [here](https://github.com/tensorflow/models/blob/master/official/nlp/transformer/transformer.py#L236)\n",
        "```\n",
        "Args:\n",
        "i : Step that is being decoded.\n",
        "Returns:\n",
        "  logit probabilities of size [batch_size, 1, vocab_size]\n",
        "```"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "xVeis7YZfaQM"
      },
      "outputs": [],
      "source": [
        "probabilities = tf.constant([[[0.3, 0.4, 0.3], [0.3, 0.3, 0.4],\n",
        "                              [0.1, 0.1, 0.8], [0.1, 0.1, 0.8]],\n",
        "                            [[0.2, 0.5, 0.3], [0.2, 0.7, 0.1],\n",
        "                              [0.1, 0.1, 0.8], [0.1, 0.1, 0.8]]])\n",
        "def model_fn(i):\n",
        "  return probabilities[:, i, :]"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "_G2rkaCPfcka"
      },
      "source": [
        "## Initialize symbols_to_logits_fn\n"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "1B6T3629fdKJ"
      },
      "outputs": [],
      "source": [
        "def _symbols_to_logits_fn():\n",
        "  \"\"\"Calculates logits of the next tokens.\"\"\"\n",
        "  def symbols_to_logits_fn(ids, i, temp_cache):\n",
        "    del ids\n",
        "    logits = tf.cast(tf.math.log(model_fn(i)), tf.float32)\n",
        "    return logits, temp_cache\n",
        "  return symbols_to_logits_fn"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "rhosGmvZffke"
      },
      "source": [
        "## Greedy \n",
        "Greedy decoding selects the token id with the highest probability as its next id: $id_t = argmax_{w}P(id | id_{1:t-1})$ at each timestep $t$. The following sketch shows greedy decoding. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "JZ-p0JdbfyJ7"
      },
      "outputs": [],
      "source": [
        "greedy_obj = sampling_module.SamplingModule(\n",
        "    length_normalization_fn=None,\n",
        "    dtype=tf.float32,\n",
        "    symbols_to_logits_fn=_symbols_to_logits_fn(),\n",
        "    vocab_size=3,\n",
        "    max_decode_length=params['max_decode_length'],\n",
        "    eos_id=10,\n",
        "    padded_decode=False)\n",
        "ids, _ = greedy_obj.generate(\n",
        "    initial_ids=tf.constant([9, 1]), initial_cache=cache)\n",
        "print(\"Greedy Decoded Ids:\", ids)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "pOmG0IE6ff40"
      },
      "source": [
        "## top_k sampling\n",
        "In *Top-K* sampling, the *K* most likely next token ids are filtered and the probability mass is redistributed among only those *K* ids. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "qkIDv7VZfuzr"
      },
      "outputs": [],
      "source": [
        "top_k_obj = sampling_module.SamplingModule(\n",
        "    length_normalization_fn=length_norm,\n",
        "    dtype=tf.float32,\n",
        "    symbols_to_logits_fn=_symbols_to_logits_fn(),\n",
        "    vocab_size=3,\n",
        "    max_decode_length=params['max_decode_length'],\n",
        "    eos_id=10,\n",
        "    sample_temperature=tf.constant(1.0),\n",
        "    top_k=tf.constant(3),\n",
        "    padded_decode=False,\n",
        "    enable_greedy=False)\n",
        "ids, _ = top_k_obj.generate(\n",
        "    initial_ids=tf.constant([9, 1]), initial_cache=cache)\n",
        "print(\"top-k sampled Ids:\", ids)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "PaEv2c_cflsE"
      },
      "source": [
        "## top_p sampling\n",
        "Instead of sampling only from the most likely *K* token ids, in *Top-p* sampling chooses from the smallest possible set of ids whose cumulative probability exceeds the probability *p*."
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "WzHslibyfs6K"
      },
      "outputs": [],
      "source": [
        "top_p_obj = sampling_module.SamplingModule(\n",
        "    length_normalization_fn=length_norm,\n",
        "    dtype=tf.float32,\n",
        "    symbols_to_logits_fn=_symbols_to_logits_fn(),\n",
        "    vocab_size=3,\n",
        "    max_decode_length=params['max_decode_length'],\n",
        "    eos_id=10,\n",
        "    sample_temperature=tf.constant(1.0),\n",
        "    top_p=tf.constant(0.9),\n",
        "    padded_decode=False,\n",
        "    enable_greedy=False)\n",
        "ids, _ = top_p_obj.generate(\n",
        "    initial_ids=tf.constant([9, 1]), initial_cache=cache)\n",
        "print(\"top-p sampled Ids:\", ids)"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {
        "id": "hTSdHdTjfoPV"
      },
      "source": [
        "## Beam search decoding\n",
        "Beam search reduces the risk of missing hidden high probability token ids by keeping the most likely num_beams of hypotheses at each time step and eventually choosing the hypothesis that has the overall highest probability. "
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {
        "id": "U1jIPF_qfqcO"
      },
      "outputs": [],
      "source": [
        "beam_size = 2\n",
        "params['batch_size'] = 1\n",
        "beam_cache = {\n",
        "    'layer_%d' % layer: {\n",
        "        'k': tf.zeros([params['batch_size'], params['max_decode_length'], params['num_heads'], params['n_dims']], dtype=tf.float32),\n",
        "        'v': tf.zeros([params['batch_size'], params['max_decode_length'], params['num_heads'], params['n_dims']], dtype=tf.float32)\n",
        "        } for layer in range(params['num_layers'])\n",
        "    }\n",
        "print(\"cache key shape for layer 1 :\", beam_cache['layer_1']['k'].shape)\n",
        "ids, _ = beam_search.sequence_beam_search(\n",
        "    symbols_to_logits_fn=_symbols_to_logits_fn(),\n",
        "    initial_ids=tf.constant([9], tf.int32),\n",
        "    initial_cache=beam_cache,\n",
        "    vocab_size=3,\n",
        "    beam_size=beam_size,\n",
        "    alpha=0.6,\n",
        "    max_decode_length=params['max_decode_length'],\n",
        "    eos_id=10,\n",
        "    padded_decode=False,\n",
        "    dtype=tf.float32)\n",
        "print(\"Beam search ids:\", ids)"
      ]
    }
  ],
  "metadata": {
    "colab": {
      "collapsed_sections": [],
      "name": "decoding_api.ipynb",
      "provenance": [],
      "toc_visible": true
    },
    "kernelspec": {
      "display_name": "Python 3",
      "name": "python3"
    }
  },
  "nbformat": 4,
  "nbformat_minor": 0
}