{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Copyright (c) Microsoft Corporation. All rights reserved.  \n",
    "Licensed under the MIT License."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "# Inference PyTorch Bert Model with ONNX Runtime on GPU"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "In this tutorial, you'll learn how to load a Bert model from PyTorch, convert it to ONNX, and inference it for high performance using ONNX Runtime and NVIDIA GPU. In the following sections, we are going to use the Bert model trained with Stanford Question Answering Dataset (SQuAD) dataset as an example. Bert SQuAD model is used in question answering scenarios, where the answer to every question is a segment of text from the corresponding reading passage, or the question might be unanswerable.\n",
    "\n",
    "This notebook is for GPU inference. For CPU inference, please look at another notebook [Inference PyTorch Bert Model with ONNX Runtime on CPU](PyTorch_Bert-Squad_OnnxRuntime_CPU.ipynb)."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 0. Prerequisites ##\n",
    "It requires your machine to have a GPU, and a python environment with [PyTorch](https://pytorch.org/) installed before running this notebook.\n",
    "\n",
    "#### GPU Environment Setup using AnaConda\n",
    "\n",
    "First, we install [AnaConda](https://www.anaconda.com/distribution/) in a target machine and open an AnaConda prompt window when it is done. Then run the following commands to create a conda environment. This notebook is tested with PyTorch 2.0.1 and OnnxRuntime 1.16.0.\n",
    "\n",
    "```console\n",
    "conda create -n gpu_env python=3.10\n",
    "conda activate gpu_env\n",
    "pip install jupyterlab\n",
    "conda install ipykernel\n",
    "conda install -c conda-forge ipywidgets\n",
    "ipython kernel install --user --name gpu_env\n",
    "jupyter-lab\n",
    "```\n",
    "Finally, launch Jupyter Notebook and you can choose gpu_env as kernel to run this notebook.\n",
    "\n",
    "Onnxruntime-gpu need specified version of CUDA and cuDNN. You can find the Requirements [here](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#requirements). Remember to add the directories to PATH environment variable (See [CUDA and cuDNN Path](#CUDA-and-cuDNN-Path) below)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 1,
   "metadata": {},
   "outputs": [],
   "source": [
    "import sys\n",
    "\n",
    "if sys.platform in ['linux', 'win32']: # Linux or Windows\n",
    "    !{sys.executable} -m pip install torch --index-url https://download.pytorch.org/whl/cu118 -q\n",
    "    !{sys.executable} -m pip install onnxruntime-gpu onnx transformers psutil pandas py-cpuinfo py3nvml wget netron sympy protobuf==3.20.3 -q\n",
    "else: # Mac\n",
    "    print(\"CUDA is not available on MacOS\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### CUDA and cuDNN Path\n",
    "onnxruntime-gpu has dependency on [CUDA](https://developer.nvidia.com/cuda-downloads) and [cuDNN](https://developer.nvidia.com/cudnn). Required CUDA version can be found [here](https://onnxruntime.ai/docs/execution-providers/CUDA-ExecutionProvider.html#requirements) If you import torch before onnxruntime, onnxruntime might use the CUDA and cuDNN DLLs that loaded by PyTorch."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "pytorch: 2.0.1+cu118\n",
      "onnxruntime: 1.16.0\n",
      "onnx: 1.14.1\n",
      "transformers: 4.33.1\n"
     ]
    }
   ],
   "source": [
    "import torch\n",
    "import onnx\n",
    "import onnxruntime\n",
    "import transformers\n",
    "print(\"pytorch:\", torch.__version__)\n",
    "print(\"onnxruntime:\", onnxruntime.__version__)\n",
    "print(\"onnx:\", onnx.__version__)\n",
    "print(\"transformers:\", transformers.__version__)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 1. Load Pretrained Bert model ##"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We begin by downloading the SQuAD data file and store them in the specified location. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [],
   "source": [
    "import os\n",
    "\n",
    "cache_dir = \"./squad\"\n",
    "if not os.path.exists(cache_dir):\n",
    "    os.makedirs(cache_dir)\n",
    "\n",
    "predict_file_url = \"https://rajpurkar.github.io/SQuAD-explorer/dataset/dev-v1.1.json\"\n",
    "predict_file = os.path.join(cache_dir, \"dev-v1.1.json\")\n",
    "if not os.path.exists(predict_file):\n",
    "    import wget\n",
    "    print(\"Start downloading predict file.\")\n",
    "    wget.download(predict_file_url, predict_file)\n",
    "    print(\"Predict file downloaded.\")"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's first define some constant variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Whether allow overwriting existing ONNX model and download the latest script from GitHub\n",
    "enable_overwrite = True\n",
    "\n",
    "# Total samples to inference, so that we can get average latency\n",
    "total_samples = 1000\n",
    "\n",
    "# ONNX opset version\n",
    "opset_version=11"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Specify some model configuration variables."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "metadata": {},
   "outputs": [],
   "source": [
    "# fine-tuned model from https://huggingface.co/models?search=squad\n",
    "model_name_or_path = \"bert-large-uncased-whole-word-masking-finetuned-squad\"\n",
    "max_seq_length = 128\n",
    "doc_stride = 128\n",
    "max_query_length = 64"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Start to load model from pretrained. This step could take a few minutes. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "Some weights of the model checkpoint at bert-large-uncased-whole-word-masking-finetuned-squad were not used when initializing BertForQuestionAnswering: ['bert.pooler.dense.bias', 'bert.pooler.dense.weight']\n",
      "- This IS expected if you are initializing BertForQuestionAnswering from the checkpoint of a model trained on another task or with another architecture (e.g. initializing a BertForSequenceClassification model from a BertForPreTraining model).\n",
      "- This IS NOT expected if you are initializing BertForQuestionAnswering from the checkpoint of a model that you expect to be exactly identical (initializing a BertForSequenceClassification model from a BertForSequenceClassification model).\n",
      "100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 48/48 [00:02<00:00, 16.27it/s]\n",
      "convert squad examples to features: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1000/1000 [00:03<00:00, 256.11it/s]\n",
      "add example index and unique id: 100%|\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588\u2588| 1000/1000 [00:00<?, ?it/s]\n"
     ]
    }
   ],
   "source": [
    "# The following code is adapted from HuggingFace transformers\n",
    "# https://github.com/huggingface/transformers/blob/master/examples/run_squad.py\n",
    "\n",
    "from transformers import (BertConfig, BertForQuestionAnswering, BertTokenizer)\n",
    "\n",
    "# Load pretrained model and tokenizer\n",
    "config_class, model_class, tokenizer_class = (BertConfig, BertForQuestionAnswering, BertTokenizer)\n",
    "config = config_class.from_pretrained(model_name_or_path, cache_dir=cache_dir)\n",
    "tokenizer = tokenizer_class.from_pretrained(model_name_or_path, do_lower_case=True, cache_dir=cache_dir)\n",
    "model = model_class.from_pretrained(model_name_or_path,\n",
    "                                    from_tf=False,\n",
    "                                    config=config,\n",
    "                                    cache_dir=cache_dir)\n",
    "# load some examples\n",
    "from transformers.data.processors.squad import SquadV1Processor\n",
    "\n",
    "processor = SquadV1Processor()\n",
    "examples = processor.get_dev_examples(None, filename=predict_file)\n",
    "\n",
    "from transformers import squad_convert_examples_to_features\n",
    "features, dataset = squad_convert_examples_to_features( \n",
    "            examples=examples[:total_samples], # convert enough examples for this notebook\n",
    "            tokenizer=tokenizer,\n",
    "            max_seq_length=max_seq_length,\n",
    "            doc_stride=doc_stride,\n",
    "            max_query_length=max_query_length,\n",
    "            is_training=False,\n",
    "            return_dataset='pt'\n",
    "        )"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 2. Export the loaded model ##\n",
    "Once the model is loaded, we can export the loaded PyTorch model to ONNX."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "============= Diagnostic Run torch.onnx.export version 2.0.1+cu118 =============\n",
      "verbose: False, log level: Level.ERROR\n",
      "======================= 0 NONE 0 NOTE 0 WARNING 0 ERROR ========================\n",
      "\n",
      "Model exported at  .\\onnx_models\\bert-base-cased-squad_opset11.onnx\n"
     ]
    }
   ],
   "source": [
    "output_dir = os.path.join(\".\", \"onnx_models\")\n",
    "if not os.path.exists(output_dir):\n",
    "    os.makedirs(output_dir)   \n",
    "export_model_path = os.path.join(output_dir, 'bert-base-cased-squad_opset{}.onnx'.format(opset_version))\n",
    "\n",
    "import torch\n",
    "use_gpu = torch.cuda.is_available()\n",
    "device = torch.device(\"cuda\" if use_gpu else \"cpu\")\n",
    "\n",
    "# Get the first example data to run the model and export it to ONNX\n",
    "data = dataset[0]\n",
    "inputs = {\n",
    "    'input_ids':      data[0].to(device).reshape(1, max_seq_length),\n",
    "    'attention_mask': data[1].to(device).reshape(1, max_seq_length),\n",
    "    'token_type_ids': data[2].to(device).reshape(1, max_seq_length)\n",
    "}\n",
    "\n",
    "# Set model to inference mode, which is required before exporting the model because some operators behave differently in \n",
    "# inference and training mode.\n",
    "model.eval()\n",
    "model.to(device)\n",
    "\n",
    "if enable_overwrite or not os.path.exists(export_model_path):\n",
    "    with torch.no_grad():\n",
    "        symbolic_names = {0: 'batch_size', 1: 'max_seq_len'}\n",
    "        torch.onnx.export(model,                                            # model being run\n",
    "                          args=tuple(inputs.values()),                      # model input (or a tuple for multiple inputs)\n",
    "                          f=export_model_path,                              # where to save the model (can be a file or file-like object)\n",
    "                          opset_version=opset_version,                      # the ONNX version to export the model to\n",
    "                          do_constant_folding=True,                         # whether to execute constant folding for optimization\n",
    "                          input_names=['input_ids',                         # the model's input names\n",
    "                                       'input_mask', \n",
    "                                       'segment_ids'],\n",
    "                          output_names=['start', 'end'],                    # the model's output names\n",
    "                          dynamic_axes={'input_ids': symbolic_names,        # variable length axes\n",
    "                                        'input_mask' : symbolic_names,\n",
    "                                        'segment_ids' : symbolic_names,\n",
    "                                        'start' : symbolic_names,\n",
    "                                        'end' : symbolic_names})\n",
    "        print(\"Model exported at \", export_model_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 3. PyTorch Inference ##\n",
    "Use PyTorch to evaluate an example input for comparison purpose."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "PyTorch cuda Inference time = 19.32 ms\n"
     ]
    }
   ],
   "source": [
    "import time\n",
    "\n",
    "# Measure the latency. It is not accurate using Jupyter Notebook, it is recommended to use standalone python script.\n",
    "latency = []\n",
    "with torch.no_grad():\n",
    "    for i in range(total_samples):\n",
    "        data = dataset[i]\n",
    "        inputs = {\n",
    "            'input_ids':      data[0].to(device).reshape(1, max_seq_length),\n",
    "            'attention_mask': data[1].to(device).reshape(1, max_seq_length),\n",
    "            'token_type_ids': data[2].to(device).reshape(1, max_seq_length)\n",
    "        }\n",
    "        start = time.time()\n",
    "        outputs = model(**inputs)\n",
    "        latency.append(time.time() - start)\n",
    "print(\"PyTorch {} Inference time = {} ms\".format(device.type, format(sum(latency) * 1000 / len(latency), '.2f')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 4. Inference ONNX Model with ONNX Runtime ##"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Now we are ready to inference the model with ONNX Runtime."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "OnnxRuntime gpu Inference time = 6.91 ms\n"
     ]
    }
   ],
   "source": [
    "import psutil\n",
    "import onnxruntime\n",
    "import numpy\n",
    "\n",
    "assert 'CUDAExecutionProvider' in onnxruntime.get_available_providers()\n",
    "device_name = 'gpu'\n",
    "\n",
    "sess_options = onnxruntime.SessionOptions()\n",
    "\n",
    "# Optional: store the optimized graph and view it using Netron to verify that model is fully optimized.\n",
    "# Note that this will increase session creation time so enable it for debugging only.\n",
    "sess_options.optimized_model_filepath = os.path.join(output_dir, \"optimized_model_{}.onnx\".format(device_name))\n",
    "\n",
    "# Please change the value according to best setting in Performance Test Tool result.\n",
    "sess_options.intra_op_num_threads=psutil.cpu_count(logical=True)\n",
    "\n",
    "session = onnxruntime.InferenceSession(export_model_path, sess_options, providers=[\"CUDAExecutionProvider\", \"CPUExecutionProvider\"])\n",
    "\n",
    "latency = []\n",
    "for i in range(total_samples):\n",
    "    data = dataset[i]\n",
    "    ort_inputs = {\n",
    "        'input_ids':  data[0].cpu().reshape(1, max_seq_length).numpy(),\n",
    "        'input_mask': data[1].cpu().reshape(1, max_seq_length).numpy(),\n",
    "        'segment_ids': data[2].cpu().reshape(1, max_seq_length).numpy()\n",
    "    }\n",
    "    start = time.time()\n",
    "    ort_outputs = session.run(None, ort_inputs)\n",
    "    latency.append(time.time() - start)\n",
    "    \n",
    "print(\"OnnxRuntime {} Inference time = {} ms\".format(device_name, format(sum(latency) * 1000 / len(latency), '.2f')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "We can compare the output of PyTorch and ONNX Runtime. We can see some results are not close. It is because ONNX Runtime uses some approximation in CUDA optimization. Based on our evaluation on SQuAD data set, F1 score is on par for models before and after optimization."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 10,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "***** Verifying correctness *****\n",
      "PyTorch and ONNX Runtime output 0 are close: True\n",
      "maximum_diff=0.002086162567138672 average_diff=0.00040457770228385925\n",
      "PyTorch and ONNX Runtime output 1 are close: True\n",
      "maximum_diff=0.0033638477325439453 average_diff=0.00045418128138408065\n"
     ]
    }
   ],
   "source": [
    "print(\"***** Verifying correctness *****\")\n",
    "for i in range(2):    \n",
    "    print('PyTorch and ONNX Runtime output {} are close:'.format(i), numpy.allclose(ort_outputs[i], outputs[i].cpu(), rtol=1e-02, atol=1e-02))\n",
    "    diff = ort_outputs[i] - outputs[i].cpu().numpy()\n",
    "    max_diff = numpy.max(numpy.abs(diff))\n",
    "    avg_diff = numpy.average(numpy.abs(diff))\n",
    "    print(f'maximum_diff={max_diff} average_diff={avg_diff}')"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Inference with Actual Sequence Length\n",
    "Note that ONNX model is exported using dynamic length axis. It is recommended to use actual sequence input without padding instead of fixed length input for best performance. Let's see how it can be applied to this model.\n",
    "\n",
    "From an example input below, we can see zero padding at the end of each sequence."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 11,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "data": {
      "text/plain": [
       "{'input_ids': tensor([[  101,  2054,  2329,  2694,  2897,  2097,  4287,  1996,  3565,  4605,\n",
       "           1029,   102,  1999,  1996,  2142,  2983,  1010,  4035,  2557,  1019,\n",
       "           2444,  1998,  1019,  2444,  2998,  4469,  2097,  4287,  1996,  5049,\n",
       "           1012,  1996,  4035,  2097,  4287,  2049,  2219,  2329,  2394,  3743,\n",
       "           1010,  2007,  6754, 10184,  1010, 12270, 10589,  1998,  6857,  8945,\n",
       "          18505,  2006,  8570,  1012,   102,     0,     0,     0,     0,     0,\n",
       "              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
       "              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
       "              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
       "              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
       "              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
       "              0,     0,     0,     0,     0,     0,     0,     0,     0,     0,\n",
       "              0,     0,     0,     0,     0,     0,     0,     0]],\n",
       "        device='cuda:0'),\n",
       " 'attention_mask': tensor([[1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 0, 0, 0, 0, 0]], device='cuda:0'),\n",
       " 'token_type_ids': tensor([[0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,\n",
       "          1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,\n",
       "          0, 0, 0, 0, 0, 0, 0, 0]], device='cuda:0')}"
      ]
     },
     "execution_count": 11,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# An example input (we can see padding). From attention_mask, we can deduce the actual length.\n",
    "inputs"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "The original sequence length is 128. After removing paddings, the sequence length is reduced. Input with smaller sequence length need less computation, thus we can see there is improvement on inference latency. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 12,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Average length 94\n",
      "OnnxRuntime gpu Inference time with actual sequence length = 6.47 ms\n"
     ]
    }
   ],
   "source": [
    "import statistics\n",
    "\n",
    "latency = []\n",
    "lengths = []\n",
    "for i in range(total_samples):\n",
    "    data = dataset[i]\n",
    "    # Instead of using fixed length (128), we can use actual sequence length (less than 128), which helps to get better performance.\n",
    "    actual_sequence_length = sum(data[1].numpy())\n",
    "    lengths.append(actual_sequence_length)\n",
    "    opt_inputs = {\n",
    "        'input_ids':  data[0].numpy()[:actual_sequence_length].reshape(1, actual_sequence_length),\n",
    "        'input_mask': data[1].numpy()[:actual_sequence_length].reshape(1, actual_sequence_length),\n",
    "        'segment_ids': data[2].numpy()[:actual_sequence_length].reshape(1, actual_sequence_length)\n",
    "    }\n",
    "    start = time.time()\n",
    "    opt_outputs = session.run(None, opt_inputs)\n",
    "    latency.append(time.time() - start)\n",
    "print(\"Average length\", statistics.mean(lengths))\n",
    "print(\"OnnxRuntime {} Inference time with actual sequence length = {} ms\".format(device_name, format(sum(latency) * 1000 / len(latency), '.2f')))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's compare the output and see whether the results are close.\n",
    "\n",
    "**Note**: Need end-to-end evaluation on performance and accuracy if you use this strategy."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 13,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "***** Comparing results with/without paddings *****\n",
      "Output 0 are close: False\n",
      "Output 1 are close: False\n"
     ]
    }
   ],
   "source": [
    "print(\"***** Comparing results with/without paddings *****\")\n",
    "for i in range(2):\n",
    "    print('Output {} are close:'.format(i), numpy.allclose(opt_outputs[i], ort_outputs[i][:,:len(opt_outputs[i][0])], rtol=1e-03, atol=1e-03))"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 5. Offline Optimization and Test Tools\n",
    "\n",
    "It is recommended to try [OnnxRuntime Transformer Model Optimization Tool](https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/transformers) on the exported ONNX models. It could help verify whether the model can be fully optimized, and get performance test results."
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Transformer Optimizer\n",
    "\n",
    "Although OnnxRuntime could optimize Bert model exported by PyTorch. Sometime, model cannot be fully optimized due to different reasons:\n",
    "* A new subgraph pattern is generated by new version of export tool, and the pattern is not covered by older version of OnnxRuntime. \n",
    "* The exported model uses dynamic axis and this makes it harder for shape inference of the graph. That blocks some optimization to be applied.\n",
    "* Some optimization is better to be done offline. Like change input tensor type from int64 to int32 to avoid extra Cast nodes, or convert model to float16 to achieve better performance in V100 or T4 GPU.\n",
    "\n",
    "We have python script **optimizer.py**, which is more flexible in graph pattern matching and model conversion (like float32 to float16). You can also use it to verify whether a Bert model is fully optimized.\n",
    "\n",
    "In this example, we can see that it introduces optimization that is not provided by onnxruntime: SkipLayerNormalization and bias fusion, which is not fused in OnnxRuntime due to shape inference as mentioned.\n",
    "\n",
    "It will also tell whether the model is fully optimized or not. If not, that means you might need change the script to fuse some new pattern of subgraph.\n",
    "\n",
    "Example Usage:\n",
    "```\n",
    "from onnxruntime.transformers import optimizer\n",
    "optimized_model = optimizer.optimize_model(export_model_path, model_type='bert', num_heads=12, hidden_size=768)\n",
    "optimized_model.save_model_to_file(optimized_model_path)\n",
    "```\n",
    "\n",
    "You can also use command line like the following:"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Float32 Model\n",
    "Let us optimize the ONNX model using the script. The first example will output model with float32 to store weights. This is the choice for most GPUs without Tensor Core.\n",
    "\n",
    "If your GPU (like V100 or T4) has Tensor Core, jump to [Float16 Model](#6.-Model-Optimization-with-Float16) section since that will give you better performance than Float32 model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 14,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "               apply: Fused LayerNormalization: 49\n",
      "               apply: Fused Gelu: 24\n",
      "               apply: Fused SkipLayerNormalization: 48\n",
      "               apply: Fused Attention: 24\n",
      "         prune_graph: Removed 5 nodes\n",
      "               apply: Fused EmbedLayerNormalization(with mask): 1\n",
      "         prune_graph: Removed 10 nodes\n",
      "               apply: Fused BiasGelu: 24\n",
      "               apply: Fused SkipLayerNormalization(add bias): 48\n",
      "            optimize: opset version: 11\n",
      "get_fused_operator_statistics: Optimized operators:{'EmbedLayerNormalization': 1, 'Attention': 24, 'MultiHeadAttention': 0, 'Gelu': 0, 'FastGelu': 0, 'BiasGelu': 24, 'GemmFastGelu': 0, 'LayerNormalization': 0, 'SkipLayerNormalization': 48, 'QOrderedAttention': 0, 'QOrderedGelu': 0, 'QOrderedLayerNormalization': 0, 'QOrderedMatMul': 0}\n",
      "                main: The model has been fully optimized.\n",
      "  save_model_to_file: Sort graphs in topological order\n",
      "  save_model_to_file: Model saved to ./onnx/bert-base-cased-squad_opt_gpu_fp32.onnx\n"
     ]
    }
   ],
   "source": [
    "optimized_fp32_model_path = './onnx/bert-base-cased-squad_opt_{}_fp32.onnx'.format('gpu' if use_gpu else 'cpu')\n",
    "\n",
    "!{sys.executable} -m onnxruntime.transformers.optimizer --input $export_model_path --output $optimized_fp32_model_path"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "#### Optimized Graph\n",
    "We can open the optimized model using [Netron](https://github.com/lutzroeder/netron) to visualize.\n",
    "\n",
    "The graph is like the following:\n",
    "<img src='images/optimized_bert_gpu.png'>\n",
    "\n",
    "Sometime, optimized graph is slightly different. For example, FastGelu is replaced by BiasGelu for CPU inference; When the option --input_int32 is used, Cast nodes for inputs are removed."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 15,
   "metadata": {},
   "outputs": [],
   "source": [
    "import netron\n",
    "\n",
    "# change it to True if want to view the optimized model in browser\n",
    "enable_netron = False\n",
    "if enable_netron:\n",
    "    # If you encounter error \"access a socket in a way forbidden by its access permissions\", install Netron as standalone application instead.\n",
    "    netron.start(optimized_fp32_model_path)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Performance Test Tool\n",
    "\n",
    "The following will create 1000 random inputs of batch_size 1 and sequence length 128, then measure the average latency and throughput numbers.\n",
    "\n",
    "Note that the test uses fixed sequence length. If you use [dynamic sequence length](#Inference-with-Actual-Sequence-Length), actual performance depends on the distribution of sequence length.\n",
    "\n",
    "**Attention**: Latency numbers from Jupyter Notebook are not accurate. See [Attional Info](#7.-Additional-Info) for more info."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 16,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=32,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.21 ms, Throughput = 311.15 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=24,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.21 ms, Throughput = 311.73 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=15,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.20 ms, Throughput = 312.51 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=14,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.20 ms, Throughput = 312.49 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=13,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.20 ms, Throughput = 312.24 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=12,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.20 ms, Throughput = 312.20 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=11,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.23 ms, Throughput = 310.02 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=10,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.22 ms, Throughput = 310.93 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=9,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.21 ms, Throughput = 311.57 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.20 ms, Throughput = 312.80 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=7,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.23 ms, Throughput = 309.53 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=6,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.23 ms, Throughput = 309.27 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=5,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.21 ms, Throughput = 311.10 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=4,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.23 ms, Throughput = 310.02 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=3,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.22 ms, Throughput = 310.30 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=2,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.21 ms, Throughput = 311.10 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp32.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=1,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.19 ms, Throughput = 313.24 QPS\n",
      "test setting TestSetting(batch_size=1, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=None, seed=3, verbose=False, log_severity=2, average_sequence_length=128, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=1 sequence_length=128\n",
      "Test summary is saved to onnx\\perf_results_GPU_B1_S128_20230912-125746.txt\n"
     ]
    }
   ],
   "source": [
    "GPU_OPTION = '--use_gpu --use_io_binding' if use_gpu else ''\n",
    "\n",
    "!{sys.executable} -m onnxruntime.transformers.bert_perf_test --model $optimized_fp32_model_path --batch_size 1 --sequence_length 128 --samples 1000 --test_times 1 $GPU_OPTION"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "Let's load the summary file and take a look."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 17,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Perf results from ./onnx\\perf_results_GPU_B1_S128_20230912-125746.txt\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Latency(ms)</th>\n",
       "      <th>Latency_P50</th>\n",
       "      <th>Latency_P75</th>\n",
       "      <th>Latency_P90</th>\n",
       "      <th>Latency_P95</th>\n",
       "      <th>Latency_P99</th>\n",
       "      <th>Throughput(QPS)</th>\n",
       "      <th>intra_op_num_threads</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>3.19</td>\n",
       "      <td>3.16</td>\n",
       "      <td>3.21</td>\n",
       "      <td>3.27</td>\n",
       "      <td>3.35</td>\n",
       "      <td>3.52</td>\n",
       "      <td>313.24</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>3.20</td>\n",
       "      <td>3.17</td>\n",
       "      <td>3.22</td>\n",
       "      <td>3.25</td>\n",
       "      <td>3.34</td>\n",
       "      <td>3.50</td>\n",
       "      <td>312.80</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.20</td>\n",
       "      <td>3.15</td>\n",
       "      <td>3.25</td>\n",
       "      <td>3.29</td>\n",
       "      <td>3.36</td>\n",
       "      <td>3.58</td>\n",
       "      <td>312.51</td>\n",
       "      <td>15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>3.20</td>\n",
       "      <td>3.18</td>\n",
       "      <td>3.21</td>\n",
       "      <td>3.26</td>\n",
       "      <td>3.35</td>\n",
       "      <td>3.53</td>\n",
       "      <td>312.49</td>\n",
       "      <td>14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3.20</td>\n",
       "      <td>3.16</td>\n",
       "      <td>3.25</td>\n",
       "      <td>3.29</td>\n",
       "      <td>3.40</td>\n",
       "      <td>3.56</td>\n",
       "      <td>312.24</td>\n",
       "      <td>13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>3.20</td>\n",
       "      <td>3.19</td>\n",
       "      <td>3.22</td>\n",
       "      <td>3.27</td>\n",
       "      <td>3.35</td>\n",
       "      <td>3.48</td>\n",
       "      <td>312.20</td>\n",
       "      <td>12</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>3.21</td>\n",
       "      <td>3.18</td>\n",
       "      <td>3.23</td>\n",
       "      <td>3.28</td>\n",
       "      <td>3.37</td>\n",
       "      <td>3.51</td>\n",
       "      <td>311.73</td>\n",
       "      <td>24</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>3.21</td>\n",
       "      <td>3.19</td>\n",
       "      <td>3.23</td>\n",
       "      <td>3.27</td>\n",
       "      <td>3.34</td>\n",
       "      <td>3.52</td>\n",
       "      <td>311.57</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>3.21</td>\n",
       "      <td>3.18</td>\n",
       "      <td>3.26</td>\n",
       "      <td>3.31</td>\n",
       "      <td>3.36</td>\n",
       "      <td>3.54</td>\n",
       "      <td>311.15</td>\n",
       "      <td>32</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>3.21</td>\n",
       "      <td>3.17</td>\n",
       "      <td>3.24</td>\n",
       "      <td>3.28</td>\n",
       "      <td>3.34</td>\n",
       "      <td>3.52</td>\n",
       "      <td>311.10</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>3.21</td>\n",
       "      <td>3.19</td>\n",
       "      <td>3.25</td>\n",
       "      <td>3.29</td>\n",
       "      <td>3.33</td>\n",
       "      <td>3.54</td>\n",
       "      <td>311.10</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>3.22</td>\n",
       "      <td>3.19</td>\n",
       "      <td>3.25</td>\n",
       "      <td>3.29</td>\n",
       "      <td>3.36</td>\n",
       "      <td>3.51</td>\n",
       "      <td>310.93</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>3.22</td>\n",
       "      <td>3.19</td>\n",
       "      <td>3.26</td>\n",
       "      <td>3.29</td>\n",
       "      <td>3.40</td>\n",
       "      <td>3.55</td>\n",
       "      <td>310.30</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>3.23</td>\n",
       "      <td>3.19</td>\n",
       "      <td>3.26</td>\n",
       "      <td>3.32</td>\n",
       "      <td>3.42</td>\n",
       "      <td>3.58</td>\n",
       "      <td>310.02</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>3.23</td>\n",
       "      <td>3.19</td>\n",
       "      <td>3.26</td>\n",
       "      <td>3.30</td>\n",
       "      <td>3.36</td>\n",
       "      <td>3.54</td>\n",
       "      <td>310.02</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>3.23</td>\n",
       "      <td>3.20</td>\n",
       "      <td>3.23</td>\n",
       "      <td>3.27</td>\n",
       "      <td>3.35</td>\n",
       "      <td>3.60</td>\n",
       "      <td>309.53</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>3.23</td>\n",
       "      <td>3.19</td>\n",
       "      <td>3.22</td>\n",
       "      <td>3.26</td>\n",
       "      <td>3.33</td>\n",
       "      <td>3.68</td>\n",
       "      <td>309.27</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    Latency(ms)  Latency_P50  Latency_P75  Latency_P90  Latency_P95  \\\n",
       "0          3.19         3.16         3.21         3.27         3.35   \n",
       "1          3.20         3.17         3.22         3.25         3.34   \n",
       "2          3.20         3.15         3.25         3.29         3.36   \n",
       "3          3.20         3.18         3.21         3.26         3.35   \n",
       "4          3.20         3.16         3.25         3.29         3.40   \n",
       "5          3.20         3.19         3.22         3.27         3.35   \n",
       "6          3.21         3.18         3.23         3.28         3.37   \n",
       "7          3.21         3.19         3.23         3.27         3.34   \n",
       "8          3.21         3.18         3.26         3.31         3.36   \n",
       "9          3.21         3.17         3.24         3.28         3.34   \n",
       "10         3.21         3.19         3.25         3.29         3.33   \n",
       "11         3.22         3.19         3.25         3.29         3.36   \n",
       "12         3.22         3.19         3.26         3.29         3.40   \n",
       "13         3.23         3.19         3.26         3.32         3.42   \n",
       "14         3.23         3.19         3.26         3.30         3.36   \n",
       "15         3.23         3.20         3.23         3.27         3.35   \n",
       "16         3.23         3.19         3.22         3.26         3.33   \n",
       "\n",
       "    Latency_P99  Throughput(QPS)  intra_op_num_threads  \n",
       "0          3.52           313.24                     1  \n",
       "1          3.50           312.80                     8  \n",
       "2          3.58           312.51                    15  \n",
       "3          3.53           312.49                    14  \n",
       "4          3.56           312.24                    13  \n",
       "5          3.48           312.20                    12  \n",
       "6          3.51           311.73                    24  \n",
       "7          3.52           311.57                     9  \n",
       "8          3.54           311.15                    32  \n",
       "9          3.52           311.10                     5  \n",
       "10         3.54           311.10                     2  \n",
       "11         3.51           310.93                    10  \n",
       "12         3.55           310.30                     3  \n",
       "13         3.58           310.02                    11  \n",
       "14         3.54           310.02                     4  \n",
       "15         3.60           309.53                     7  \n",
       "16         3.68           309.27                     6  "
      ]
     },
     "execution_count": 17,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "def load_last_perf_test_result():\n",
    "    import os\n",
    "    import glob     \n",
    "    import pandas\n",
    "    latest_result_file = max(glob.glob(\"./onnx/perf_results_*.txt\"), key=os.path.getmtime)\n",
    "    result_data = pandas.read_table(latest_result_file)\n",
    "    print(\"Perf results from\", latest_result_file)\n",
    "    # Do not show columns that have same values for all rows.\n",
    "    columns_to_remove = ['model', 'graph_optimization_level', 'batch_size', 'sequence_length', 'test_cases', 'test_times', 'use_gpu', 'use_io_binding', 'average_sequence_length', 'random_sequence_length']\n",
    "    result_data.drop(columns_to_remove, axis=1, inplace=True)\n",
    "    return result_data\n",
    "    \n",
    "thread_results = load_last_perf_test_result()\n",
    "thread_results"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "From above result, we can see that latency is very close for different settings of intra_op_num_threads.\n",
    "\n",
    "### Model Results Comparison Tool\n",
    "\n",
    "When a BERT model is optimized, some approximation is used in calculation. If your BERT model has three inputs, a script compare_bert_results.py can be used to do a quick verification. The tool will generate some fake input data, and compare the inference outputs of the original and optimized models. If outputs are all close, it is safe to use the optimized model.\n",
    "\n",
    "For GPU inference, the absolute or relative difference is larger than those numbers of CPU inference. Note that slight difference in output will not impact final result. We did end-to-end evaluation using SQuAD data set using a fine-tuned squad model, and F1 score is almost the same before/after optimization."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 18,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "100% passed for 100 random inputs given thresholds (rtol=0.01, atol=0.01).\n",
      "maximum absolute difference=0.05149984359741211\n"
     ]
    }
   ],
   "source": [
    "USE_GPU = '--use_gpu' if use_gpu else ''\n",
    "!{sys.executable} -m onnxruntime.transformers.compare_bert_results --baseline_model $export_model_path --optimized_model $optimized_fp32_model_path --batch_size 1 --sequence_length 128 --samples 100 --rtol 0.01 --atol 0.01 $USE_GPU"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 6. Model Optimization with Float16\n",
    "\n",
    "The optimizer.py script have an option **--float16** to convert model to use float16 to store weights. After the conversion, it could be faster to run in GPU with tensor cores like V100 or T4.\n",
    "\n",
    "Let's run tools to measure the performance on Nvidia RTX 4090. The results show significant performance improvement: latency is about 3.2 ms for float32 model, and about 1.8 ms for float16 model."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 19,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "\u001b\u0000[\u00000\u0000;\u00009\u00003\u0000m\u00002\u00000\u00002\u00003\u0000-\u00000\u00009\u0000-\u00001\u00002\u0000 \u00001\u00002\u0000:\u00005\u00007\u0000:\u00005\u00004\u0000.\u00005\u00005\u00000\u00008\u00002\u00002\u00008\u0000 \u0000[\u0000W\u0000:\u0000o\u0000n\u0000n\u0000x\u0000r\u0000u\u0000n\u0000t\u0000i\u0000m\u0000e\u0000:\u0000,\u0000 \u0000s\u0000e\u0000s\u0000s\u0000i\u0000o\u0000n\u0000_\u0000s\u0000t\u0000a\u0000t\u0000e\u0000.\u0000c\u0000c\u0000:\u00001\u00001\u00006\u00002\u0000 \u0000o\u0000n\u0000n\u0000x\u0000r\u0000u\u0000n\u0000t\u0000i\u0000m\u0000e\u0000:\u0000:\u0000V\u0000e\u0000r\u0000i\u0000f\u0000y\u0000E\u0000a\u0000c\u0000h\u0000N\u0000o\u0000d\u0000e\u0000I\u0000s\u0000A\u0000s\u0000s\u0000i\u0000g\u0000n\u0000e\u0000d\u0000T\u0000o\u0000A\u0000n\u0000E\u0000p\u0000]\u0000 \u0000S\u0000o\u0000m\u0000e\u0000 \u0000n\u0000o\u0000d\u0000e\u0000s\u0000 \u0000w\u0000e\u0000r\u0000e\u0000 \u0000n\u0000o\u0000t\u0000 \u0000a\u0000s\u0000s\u0000i\u0000g\u0000n\u0000e\u0000d\u0000 \u0000t\u0000o\u0000 \u0000t\u0000h\u0000e\u0000 \u0000p\u0000r\u0000e\u0000f\u0000e\u0000r\u0000r\u0000e\u0000d\u0000 \u0000e\u0000x\u0000e\u0000c\u0000u\u0000t\u0000i\u0000o\u0000n\u0000 \u0000p\u0000r\u0000o\u0000v\u0000i\u0000d\u0000e\u0000r\u0000s\u0000 \u0000w\u0000h\u0000i\u0000c\u0000h\u0000 \u0000m\u0000a\u0000y\u0000 \u0000o\u0000r\u0000 \u0000m\u0000a\u0000y\u0000 \u0000n\u0000o\u0000t\u0000 \u0000h\u0000a\u0000v\u0000e\u0000 \u0000a\u0000n\u0000 \u0000n\u0000e\u0000g\u0000a\u0000t\u0000i\u0000v\u0000e\u0000 \u0000i\u0000m\u0000p\u0000a\u0000c\u0000t\u0000 \u0000o\u0000n\u0000 \u0000p\u0000e\u0000r\u0000f\u0000o\u0000r\u0000m\u0000a\u0000n\u0000c\u0000e\u0000.\u0000 \u0000e\u0000.\u0000g\u0000.\u0000 \u0000O\u0000R\u0000T\u0000 \u0000e\u0000x\u0000p\u0000l\u0000i\u0000c\u0000i\u0000t\u0000l\u0000y\u0000 \u0000a\u0000s\u0000s\u0000i\u0000g\u0000n\u0000s\u0000 \u0000s\u0000h\u0000a\u0000p\u0000e\u0000 \u0000r\u0000e\u0000l\u0000a\u0000t\u0000e\u0000d\u0000 \u0000o\u0000p\u0000s\u0000 \u0000t\u0000o\u0000 \u0000C\u0000P\u0000U\u0000 \u0000t\u0000o\u0000 \u0000i\u0000m\u0000p\u0000r\u0000o\u0000v\u0000e\u0000 \u0000p\u0000e\u0000r\u0000f\u0000.\u0000\u001b\u0000[\u0000m\u0000\n",
      "\u0000\u001b\u0000[\u00000\u0000;\u00009\u00003\u0000m\u00002\u00000\u00002\u00003\u0000-\u00000\u00009\u0000-\u00001\u00002\u0000 \u00001\u00002\u0000:\u00005\u00007\u0000:\u00005\u00004\u0000.\u00005\u00005\u00001\u00001\u00000\u00000\u00008\u0000 \u0000[\u0000W\u0000:\u0000o\u0000n\u0000n\u0000x\u0000r\u0000u\u0000n\u0000t\u0000i\u0000m\u0000e\u0000:\u0000,\u0000 \u0000s\u0000e\u0000s\u0000s\u0000i\u0000o\u0000n\u0000_\u0000s\u0000t\u0000a\u0000t\u0000e\u0000.\u0000c\u0000c\u0000:\u00001\u00001\u00006\u00004\u0000 \u0000o\u0000n\u0000n\u0000x\u0000r\u0000u\u0000n\u0000t\u0000i\u0000m\u0000e\u0000:\u0000:\u0000V\u0000e\u0000r\u0000i\u0000f\u0000y\u0000E\u0000a\u0000c\u0000h\u0000N\u0000o\u0000d\u0000e\u0000I\u0000s\u0000A\u0000s\u0000s\u0000i\u0000g\u0000n\u0000e\u0000d\u0000T\u0000o\u0000A\u0000n\u0000E\u0000p\u0000]\u0000 \u0000R\u0000e\u0000r\u0000u\u0000n\u0000n\u0000i\u0000n\u0000g\u0000 \u0000w\u0000i\u0000t\u0000h\u0000 \u0000v\u0000e\u0000r\u0000b\u0000o\u0000s\u0000e\u0000 \u0000o\u0000u\u0000t\u0000p\u0000u\u0000t\u0000 \u0000o\u0000n\u0000 \u0000a\u0000 \u0000n\u0000o\u0000n\u0000-\u0000m\u0000i\u0000n\u0000i\u0000m\u0000a\u0000l\u0000 \u0000b\u0000u\u0000i\u0000l\u0000d\u0000 \u0000w\u0000i\u0000l\u0000l\u0000 \u0000s\u0000h\u0000o\u0000w\u0000 \u0000n\u0000o\u0000d\u0000e\u0000 \u0000a\u0000s\u0000s\u0000i\u0000g\u0000n\u0000m\u0000e\u0000n\u0000t\u0000s\u0000.\u0000\u001b\u0000[\u0000m\u0000\n",
      "\u0000               apply: Fused LayerNormalization: 49\n",
      "               apply: Fused Gelu: 24\n",
      "               apply: Fused SkipLayerNormalization: 48\n",
      "               apply: Fused Attention: 24\n",
      "         prune_graph: Removed 5 nodes\n",
      "               apply: Fused EmbedLayerNormalization(with mask): 1\n",
      "         prune_graph: Removed 10 nodes\n",
      "               apply: Fused BiasGelu: 24\n",
      "               apply: Fused SkipLayerNormalization(add bias): 48\n",
      "            optimize: opset version: 11\n",
      "get_fused_operator_statistics: Optimized operators:{'EmbedLayerNormalization': 1, 'Attention': 24, 'MultiHeadAttention': 0, 'Gelu': 0, 'FastGelu': 0, 'BiasGelu': 24, 'GemmFastGelu': 0, 'LayerNormalization': 0, 'SkipLayerNormalization': 48, 'QOrderedAttention': 0, 'QOrderedGelu': 0, 'QOrderedLayerNormalization': 0, 'QOrderedMatMul': 0}\n",
      "                main: The model has been fully optimized.\n",
      "  save_model_to_file: Sort graphs in topological order\n",
      "  save_model_to_file: Model saved to ./onnx/bert-base-cased-squad_opt_gpu_fp16.onnx\n"
     ]
    }
   ],
   "source": [
    "optimized_fp16_model_path = './onnx/bert-base-cased-squad_opt_{}_fp16.onnx'.format('gpu' if use_gpu else 'cpu')\n",
    "!{sys.executable} -m onnxruntime.transformers.optimizer --input $export_model_path --output $optimized_fp16_model_path --float16 $USE_GPU"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 20,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=32,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.77 ms, Throughput = 566.45 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=24,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.74 ms, Throughput = 574.96 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=15,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.74 ms, Throughput = 574.28 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=14,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.74 ms, Throughput = 575.17 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=13,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.76 ms, Throughput = 569.77 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=12,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.79 ms, Throughput = 559.84 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=11,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.77 ms, Throughput = 566.09 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=10,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.77 ms, Throughput = 563.97 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=9,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.77 ms, Throughput = 565.70 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.77 ms, Throughput = 565.50 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=7,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.77 ms, Throughput = 566.38 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=6,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.75 ms, Throughput = 572.89 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=5,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.76 ms, Throughput = 568.67 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=4,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.78 ms, Throughput = 561.98 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=3,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.77 ms, Throughput = 566.14 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=2,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.78 ms, Throughput = 563.25 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=1,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.77 ms, Throughput = 565.09 QPS\n",
      "test setting TestSetting(batch_size=1, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=None, seed=3, verbose=False, log_severity=2, average_sequence_length=128, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=1 sequence_length=128\n",
      "Test summary is saved to onnx\\perf_results_GPU_B1_S128_20230912-130021.txt\n"
     ]
    }
   ],
   "source": [
    "GPU_OPTION = '--use_gpu --use_io_binding' if use_gpu else ''\n",
    "!python -m onnxruntime.transformers.bert_perf_test --model $optimized_fp16_model_path --batch_size 1 --sequence_length 128 --samples 1000 --test_times 1 $GPU_OPTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 21,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Perf results from ./onnx\\perf_results_GPU_B1_S128_20230912-130021.txt\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Latency(ms)</th>\n",
       "      <th>Latency_P50</th>\n",
       "      <th>Latency_P75</th>\n",
       "      <th>Latency_P90</th>\n",
       "      <th>Latency_P95</th>\n",
       "      <th>Latency_P99</th>\n",
       "      <th>Throughput(QPS)</th>\n",
       "      <th>intra_op_num_threads</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1.74</td>\n",
       "      <td>1.72</td>\n",
       "      <td>1.72</td>\n",
       "      <td>1.75</td>\n",
       "      <td>1.80</td>\n",
       "      <td>2.17</td>\n",
       "      <td>575.17</td>\n",
       "      <td>14</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1.74</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.75</td>\n",
       "      <td>1.76</td>\n",
       "      <td>2.14</td>\n",
       "      <td>574.96</td>\n",
       "      <td>24</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1.74</td>\n",
       "      <td>1.72</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.76</td>\n",
       "      <td>1.79</td>\n",
       "      <td>2.16</td>\n",
       "      <td>574.28</td>\n",
       "      <td>15</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>1.75</td>\n",
       "      <td>1.72</td>\n",
       "      <td>1.72</td>\n",
       "      <td>1.76</td>\n",
       "      <td>2.02</td>\n",
       "      <td>2.15</td>\n",
       "      <td>572.89</td>\n",
       "      <td>6</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>1.76</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.76</td>\n",
       "      <td>1.81</td>\n",
       "      <td>2.14</td>\n",
       "      <td>569.77</td>\n",
       "      <td>13</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>1.76</td>\n",
       "      <td>1.72</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.80</td>\n",
       "      <td>2.08</td>\n",
       "      <td>2.15</td>\n",
       "      <td>568.67</td>\n",
       "      <td>5</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>6</th>\n",
       "      <td>1.77</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.81</td>\n",
       "      <td>2.12</td>\n",
       "      <td>2.19</td>\n",
       "      <td>566.45</td>\n",
       "      <td>32</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>7</th>\n",
       "      <td>1.77</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.77</td>\n",
       "      <td>2.06</td>\n",
       "      <td>2.17</td>\n",
       "      <td>566.38</td>\n",
       "      <td>7</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>8</th>\n",
       "      <td>1.77</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.81</td>\n",
       "      <td>2.10</td>\n",
       "      <td>2.18</td>\n",
       "      <td>566.14</td>\n",
       "      <td>3</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>9</th>\n",
       "      <td>1.77</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.82</td>\n",
       "      <td>2.07</td>\n",
       "      <td>2.17</td>\n",
       "      <td>566.09</td>\n",
       "      <td>11</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>10</th>\n",
       "      <td>1.77</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.75</td>\n",
       "      <td>1.78</td>\n",
       "      <td>2.02</td>\n",
       "      <td>2.13</td>\n",
       "      <td>565.70</td>\n",
       "      <td>9</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>11</th>\n",
       "      <td>1.77</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.93</td>\n",
       "      <td>2.06</td>\n",
       "      <td>2.16</td>\n",
       "      <td>565.50</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>12</th>\n",
       "      <td>1.77</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.81</td>\n",
       "      <td>2.11</td>\n",
       "      <td>2.20</td>\n",
       "      <td>565.09</td>\n",
       "      <td>1</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>13</th>\n",
       "      <td>1.77</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.75</td>\n",
       "      <td>1.85</td>\n",
       "      <td>2.06</td>\n",
       "      <td>2.15</td>\n",
       "      <td>563.97</td>\n",
       "      <td>10</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>14</th>\n",
       "      <td>1.78</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.93</td>\n",
       "      <td>2.13</td>\n",
       "      <td>2.19</td>\n",
       "      <td>563.25</td>\n",
       "      <td>2</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>15</th>\n",
       "      <td>1.78</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.75</td>\n",
       "      <td>1.88</td>\n",
       "      <td>2.10</td>\n",
       "      <td>2.19</td>\n",
       "      <td>561.98</td>\n",
       "      <td>4</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>16</th>\n",
       "      <td>1.79</td>\n",
       "      <td>1.75</td>\n",
       "      <td>1.76</td>\n",
       "      <td>1.99</td>\n",
       "      <td>2.08</td>\n",
       "      <td>2.16</td>\n",
       "      <td>559.84</td>\n",
       "      <td>12</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "    Latency(ms)  Latency_P50  Latency_P75  Latency_P90  Latency_P95  \\\n",
       "0          1.74         1.72         1.72         1.75         1.80   \n",
       "1          1.74         1.73         1.73         1.75         1.76   \n",
       "2          1.74         1.72         1.73         1.76         1.79   \n",
       "3          1.75         1.72         1.72         1.76         2.02   \n",
       "4          1.76         1.74         1.74         1.76         1.81   \n",
       "5          1.76         1.72         1.73         1.80         2.08   \n",
       "6          1.77         1.73         1.74         1.81         2.12   \n",
       "7          1.77         1.74         1.74         1.77         2.06   \n",
       "8          1.77         1.73         1.74         1.81         2.10   \n",
       "9          1.77         1.73         1.74         1.82         2.07   \n",
       "10         1.77         1.74         1.75         1.78         2.02   \n",
       "11         1.77         1.73         1.74         1.93         2.06   \n",
       "12         1.77         1.73         1.74         1.81         2.11   \n",
       "13         1.77         1.74         1.75         1.85         2.06   \n",
       "14         1.78         1.73         1.74         1.93         2.13   \n",
       "15         1.78         1.74         1.75         1.88         2.10   \n",
       "16         1.79         1.75         1.76         1.99         2.08   \n",
       "\n",
       "    Latency_P99  Throughput(QPS)  intra_op_num_threads  \n",
       "0          2.17           575.17                    14  \n",
       "1          2.14           574.96                    24  \n",
       "2          2.16           574.28                    15  \n",
       "3          2.15           572.89                     6  \n",
       "4          2.14           569.77                    13  \n",
       "5          2.15           568.67                     5  \n",
       "6          2.19           566.45                    32  \n",
       "7          2.17           566.38                     7  \n",
       "8          2.18           566.14                     3  \n",
       "9          2.17           566.09                    11  \n",
       "10         2.13           565.70                     9  \n",
       "11         2.16           565.50                     8  \n",
       "12         2.20           565.09                     1  \n",
       "13         2.15           563.97                    10  \n",
       "14         2.19           563.25                     2  \n",
       "15         2.19           561.98                     4  \n",
       "16         2.16           559.84                    12  "
      ]
     },
     "execution_count": 21,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fp32_result = load_last_perf_test_result()\n",
    "fp32_result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Throughput Tuning\n",
    "\n",
    "Some application need best throughput under some constraint on latency. This can be done by testing performance of different batch sizes. The tool could help on this.\n",
    "\n",
    "Here is an example that check the performance of multiple batch sizes (1, 2, 4, 8, 16, 32 and 64) using default settings."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 22,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=32,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 20.41 ms, Throughput = 1567.65 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 1.73 ms, Throughput = 576.74 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=2,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 2.18 ms, Throughput = 917.92 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=4,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 3.25 ms, Throughput = 1229.91 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=8,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 5.38 ms, Throughput = 1486.89 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=16,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=128,random_sequence_length=False\n",
      "Average latency = 9.90 ms, Throughput = 1616.79 QPS\n",
      "test setting TestSetting(batch_size=32, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=128, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=32 sequence_length=128\n",
      "test setting TestSetting(batch_size=1, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=128, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=1 sequence_length=128\n",
      "test setting TestSetting(batch_size=2, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=128, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=2 sequence_length=128\n",
      "test setting TestSetting(batch_size=4, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=128, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=4 sequence_length=128\n",
      "test setting TestSetting(batch_size=8, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=128, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=8 sequence_length=128\n",
      "test setting TestSetting(batch_size=16, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=128, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=16 sequence_length=128\n",
      "Test summary is saved to onnx\\perf_results_GPU_B1-2-4-8-16-32_S128_20230912-130248.txt\n"
     ]
    }
   ],
   "source": [
    "THREAD_SETTING = '--intra_op_num_threads 8'\n",
    "!{sys.executable} -m onnxruntime.transformers.bert_perf_test --model $optimized_fp16_model_path --batch_size 1 2 4 8 16 32 --sequence_length 128 --samples 1000 --test_times 1 $THREAD_SETTING $GPU_OPTION"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 23,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Perf results from ./onnx\\perf_results_GPU_B1-2-4-8-16-32_S128_20230912-130248.txt\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Latency(ms)</th>\n",
       "      <th>Latency_P50</th>\n",
       "      <th>Latency_P75</th>\n",
       "      <th>Latency_P90</th>\n",
       "      <th>Latency_P95</th>\n",
       "      <th>Latency_P99</th>\n",
       "      <th>Throughput(QPS)</th>\n",
       "      <th>intra_op_num_threads</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1.73</td>\n",
       "      <td>1.72</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.79</td>\n",
       "      <td>2.04</td>\n",
       "      <td>576.74</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>2.18</td>\n",
       "      <td>2.16</td>\n",
       "      <td>2.16</td>\n",
       "      <td>2.18</td>\n",
       "      <td>2.29</td>\n",
       "      <td>2.76</td>\n",
       "      <td>917.92</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>3.25</td>\n",
       "      <td>3.25</td>\n",
       "      <td>3.26</td>\n",
       "      <td>3.28</td>\n",
       "      <td>3.29</td>\n",
       "      <td>3.43</td>\n",
       "      <td>1229.91</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>5.38</td>\n",
       "      <td>5.38</td>\n",
       "      <td>5.39</td>\n",
       "      <td>5.42</td>\n",
       "      <td>5.44</td>\n",
       "      <td>5.60</td>\n",
       "      <td>1486.89</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>9.90</td>\n",
       "      <td>9.89</td>\n",
       "      <td>9.94</td>\n",
       "      <td>9.97</td>\n",
       "      <td>10.00</td>\n",
       "      <td>10.06</td>\n",
       "      <td>1616.79</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>20.41</td>\n",
       "      <td>20.41</td>\n",
       "      <td>20.47</td>\n",
       "      <td>20.52</td>\n",
       "      <td>20.55</td>\n",
       "      <td>20.68</td>\n",
       "      <td>1567.65</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Latency(ms)  Latency_P50  Latency_P75  Latency_P90  Latency_P95  \\\n",
       "0         1.73         1.72         1.73         1.73         1.79   \n",
       "1         2.18         2.16         2.16         2.18         2.29   \n",
       "2         3.25         3.25         3.26         3.28         3.29   \n",
       "3         5.38         5.38         5.39         5.42         5.44   \n",
       "4         9.90         9.89         9.94         9.97        10.00   \n",
       "5        20.41        20.41        20.47        20.52        20.55   \n",
       "\n",
       "   Latency_P99  Throughput(QPS)  intra_op_num_threads  \n",
       "0         2.04           576.74                     8  \n",
       "1         2.76           917.92                     8  \n",
       "2         3.43          1229.91                     8  \n",
       "3         5.60          1486.89                     8  \n",
       "4        10.06          1616.79                     8  \n",
       "5        20.68          1567.65                     8  "
      ]
     },
     "execution_count": 23,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "fp16_result = load_last_perf_test_result()\n",
    "fp16_result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Packing Mode (Effective Transformer)\n",
    "\n",
    "When padding ratio is high, it is helpful to use packing mode, also known as [effective transformer](https://github.com/bytedance/effective_transformer).\n",
    "This feature requires onnxruntime-gpu version 1.16 or later. \n",
    "\n",
    "In below example, average sequence length after removing paddings is 32, the sequence length with paddings is 128. We can see 3x throughput with packing mode (QPS increased from 1617 to 5652)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 24,
   "metadata": {},
   "outputs": [
    {
     "name": "stderr",
     "output_type": "stream",
     "text": [
      "_replace_attention_with_packing_attention: Converted 24 Attention nodes to PackedAttention.\n",
      "  save_model_to_file: Sort graphs in topological order\n",
      "                save: Delete the existing onnx file: ./onnx/bert-base-cased-squad_opt_gpu_fp16_packed.onnx\n",
      "                save: Delete the existing external data file: ./onnx/bert-base-cased-squad_opt_gpu_fp16_packed.onnx.data\n",
      "  save_model_to_file: Model saved to ./onnx/bert-base-cased-squad_opt_gpu_fp16_packed.onnx\n"
     ]
    },
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16_packed.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=32,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=32,random_sequence_length=False\n",
      "Average latency = 5.66 ms, Throughput = 5652.40 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16_packed.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=1,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=32,random_sequence_length=False\n",
      "Average latency = 1.70 ms, Throughput = 586.97 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16_packed.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=2,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=32,random_sequence_length=False\n",
      "Average latency = 1.79 ms, Throughput = 1114.37 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16_packed.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=4,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=32,random_sequence_length=False\n",
      "Average latency = 1.77 ms, Throughput = 2262.31 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16_packed.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=8,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=32,random_sequence_length=False\n",
      "Average latency = 2.18 ms, Throughput = 3666.45 QPS\n",
      "Running test: model=bert-base-cased-squad_opt_gpu_fp16_packed.onnx,graph_optimization_level=ENABLE_ALL,intra_op_num_threads=8,batch_size=16,sequence_length=128,test_cases=1000,test_times=1,use_gpu=True,use_io_binding=True,average_sequence_length=32,random_sequence_length=False\n",
      "Average latency = 3.31 ms, Throughput = 4829.58 QPS\n",
      "test setting TestSetting(batch_size=32, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=32, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=32 sequence_length=128\n",
      "test setting TestSetting(batch_size=1, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=32, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=1 sequence_length=128\n",
      "test setting TestSetting(batch_size=2, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=32, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=2 sequence_length=128\n",
      "test setting TestSetting(batch_size=4, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=32, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=4 sequence_length=128\n",
      "test setting TestSetting(batch_size=8, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=32, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=8 sequence_length=128\n",
      "test setting TestSetting(batch_size=16, sequence_length=128, test_cases=1000, test_times=1, use_gpu=True, use_io_binding=True, provider=None, intra_op_num_threads=8, seed=3, verbose=False, log_severity=2, average_sequence_length=32, random_sequence_length=False)\n",
      "Generating 1000 samples for batch_size=16 sequence_length=128\n",
      "Test summary is saved to onnx\\perf_results_GPU_B1-2-4-8-16-32_S128_20230912-130354.txt\n"
     ]
    }
   ],
   "source": [
    "assert use_gpu, \"Require GPU for packing mode\"\n",
    "packed_fp16_model_path = './onnx/bert-base-cased-squad_opt_gpu_fp16_packed.onnx'\n",
    "!{sys.executable} -m onnxruntime.transformers.convert_to_packing_mode --input $optimized_fp16_model_path --output $packed_fp16_model_path --use_external_data_format\n",
    "!{sys.executable} -m onnxruntime.transformers.bert_perf_test --model $packed_fp16_model_path --batch_size 1 2 4 8 16 32 --sequence_length 128 --average_sequence_length 32 --samples 1000 --test_times 1 $THREAD_SETTING $GPU_OPTION    "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 25,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "Perf results from ./onnx\\perf_results_GPU_B1-2-4-8-16-32_S128_20230912-130354.txt\n"
     ]
    },
    {
     "data": {
      "text/html": [
       "<div>\n",
       "<style scoped>\n",
       "    .dataframe tbody tr th:only-of-type {\n",
       "        vertical-align: middle;\n",
       "    }\n",
       "\n",
       "    .dataframe tbody tr th {\n",
       "        vertical-align: top;\n",
       "    }\n",
       "\n",
       "    .dataframe thead th {\n",
       "        text-align: right;\n",
       "    }\n",
       "</style>\n",
       "<table border=\"1\" class=\"dataframe\">\n",
       "  <thead>\n",
       "    <tr style=\"text-align: right;\">\n",
       "      <th></th>\n",
       "      <th>Latency(ms)</th>\n",
       "      <th>Latency_P50</th>\n",
       "      <th>Latency_P75</th>\n",
       "      <th>Latency_P90</th>\n",
       "      <th>Latency_P95</th>\n",
       "      <th>Latency_P99</th>\n",
       "      <th>Throughput(QPS)</th>\n",
       "      <th>intra_op_num_threads</th>\n",
       "    </tr>\n",
       "  </thead>\n",
       "  <tbody>\n",
       "    <tr>\n",
       "      <th>0</th>\n",
       "      <td>1.70</td>\n",
       "      <td>1.63</td>\n",
       "      <td>1.65</td>\n",
       "      <td>2.13</td>\n",
       "      <td>2.20</td>\n",
       "      <td>2.32</td>\n",
       "      <td>586.97</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>1</th>\n",
       "      <td>1.77</td>\n",
       "      <td>1.74</td>\n",
       "      <td>1.76</td>\n",
       "      <td>1.82</td>\n",
       "      <td>1.93</td>\n",
       "      <td>2.17</td>\n",
       "      <td>2262.31</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>2</th>\n",
       "      <td>1.79</td>\n",
       "      <td>1.73</td>\n",
       "      <td>1.74</td>\n",
       "      <td>2.12</td>\n",
       "      <td>2.18</td>\n",
       "      <td>2.32</td>\n",
       "      <td>1114.37</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>3</th>\n",
       "      <td>2.18</td>\n",
       "      <td>2.16</td>\n",
       "      <td>2.17</td>\n",
       "      <td>2.22</td>\n",
       "      <td>2.30</td>\n",
       "      <td>2.64</td>\n",
       "      <td>3666.45</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>4</th>\n",
       "      <td>3.31</td>\n",
       "      <td>3.31</td>\n",
       "      <td>3.32</td>\n",
       "      <td>3.35</td>\n",
       "      <td>3.39</td>\n",
       "      <td>3.51</td>\n",
       "      <td>4829.58</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "    <tr>\n",
       "      <th>5</th>\n",
       "      <td>5.66</td>\n",
       "      <td>5.66</td>\n",
       "      <td>5.68</td>\n",
       "      <td>5.71</td>\n",
       "      <td>5.74</td>\n",
       "      <td>5.91</td>\n",
       "      <td>5652.40</td>\n",
       "      <td>8</td>\n",
       "    </tr>\n",
       "  </tbody>\n",
       "</table>\n",
       "</div>"
      ],
      "text/plain": [
       "   Latency(ms)  Latency_P50  Latency_P75  Latency_P90  Latency_P95  \\\n",
       "0         1.70         1.63         1.65         2.13         2.20   \n",
       "1         1.77         1.74         1.76         1.82         1.93   \n",
       "2         1.79         1.73         1.74         2.12         2.18   \n",
       "3         2.18         2.16         2.17         2.22         2.30   \n",
       "4         3.31         3.31         3.32         3.35         3.39   \n",
       "5         5.66         5.66         5.68         5.71         5.74   \n",
       "\n",
       "   Latency_P99  Throughput(QPS)  intra_op_num_threads  \n",
       "0         2.32           586.97                     8  \n",
       "1         2.17          2262.31                     8  \n",
       "2         2.32          1114.37                     8  \n",
       "3         2.64          3666.45                     8  \n",
       "4         3.51          4829.58                     8  \n",
       "5         5.91          5652.40                     8  "
      ]
     },
     "execution_count": 25,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "packing_result = load_last_perf_test_result()\n",
    "packing_result"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "## 7. Additional Info\n",
    "\n",
    "Note that running Jupyter Notebook has significant impact on performance result. You can close Jupyter Notebook and other applications, then run the performance test in a console to get more accurate performance numbers.\n",
    "\n",
    "We have a [benchmark script](https://github.com/microsoft/onnxruntime/blob/main/onnxruntime/python/tools/transformers/run_benchmark.sh). It is recommended to use it measure inference speed of OnnxRuntime.\n",
    "\n",
    "[OnnxRuntime C API](https://github.com/microsoft/onnxruntime/blob/main/docs/C_API.md) could get slightly better performance than python API. If you use C API in inference, you can use OnnxRuntime_Perf_Test.exe built from source to measure performance instead.\n",
    "\n",
    "Here is the machine configuration that generated the above results. You might get slower or faster result according to your hardware."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 26,
   "metadata": {
    "scrolled": true
   },
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "{\n",
      "  \"gpu\": {\n",
      "    \"driver_version\": \"537.13\",\n",
      "    \"devices\": [\n",
      "      {\n",
      "        \"memory_total\": 25757220864,\n",
      "        \"memory_available\": 18009264128,\n",
      "        \"name\": \"NVIDIA GeForce RTX 4090\"\n",
      "      }\n",
      "    ]\n",
      "  },\n",
      "  \"cpu\": {\n",
      "    \"brand\": \"13th Gen Intel(R) Core(TM) i9-13900\",\n",
      "    \"cores\": 24,\n",
      "    \"logical_cores\": 32,\n",
      "    \"hz\": \"2000000000,0\",\n",
      "    \"l2_cache\": 33554432,\n",
      "    \"flags\": \"3dnow,3dnowprefetch,abm,acpi,adx,aes,apic,avx,avx2,bmi1,bmi2,clflush,clflushopt,clwb,cmov,cx16,cx8,de,dts,erms,est,f16c,fma,fpu,fxsr,gfni,ht,hypervisor,ia64,intel_pt,invpcid,lahf_lm,mca,mce,mmx,monitor,movbe,msr,mtrr,osxsave,pae,pat,pbe,pcid,pclmulqdq,pdcm,pge,pni,popcnt,pse,pse36,rdpid,rdrnd,rdseed,sep,serial,sha,smap,smep,ss,sse,sse2,sse4_1,sse4_2,ssse3,tm,tm2,tsc,tscdeadline,umip,vaes,vme,vpclmulqdq,x2apic,xsave,xtpr\",\n",
      "    \"processor\": \"Intel64 Family 6 Model 183 Stepping 1, GenuineIntel\"\n",
      "  },\n",
      "  \"memory\": {\n",
      "    \"total\": 33992912896,\n",
      "    \"available\": 17272422400\n",
      "  },\n",
      "  \"os\": \"Windows-10-10.0.22621-SP0\",\n",
      "  \"python\": \"3.10.13.final.0 (64 bit)\",\n",
      "  \"packages\": {\n",
      "    \"flatbuffers\": \"23.5.26\",\n",
      "    \"numpy\": \"1.25.2\",\n",
      "    \"onnx\": \"1.14.1\",\n",
      "    \"onnxruntime-gpu\": \"1.16.0\",\n",
      "    \"protobuf\": \"3.20.3\",\n",
      "    \"sympy\": \"1.12\",\n",
      "    \"torch\": \"2.0.1+cu118\",\n",
      "    \"transformers\": \"4.33.1\"\n",
      "  },\n",
      "  \"onnxruntime\": {\n",
      "    \"version\": \"1.16.0\",\n",
      "    \"support_gpu\": true\n",
      "  },\n",
      "  \"pytorch\": {\n",
      "    \"version\": \"2.0.1+cu118\",\n",
      "    \"support_gpu\": true,\n",
      "    \"cuda\": \"11.8\"\n",
      "  },\n",
      "  \"tensorflow\": null\n",
      "}\n"
     ]
    }
   ],
   "source": [
    "!{sys.executable} -m onnxruntime.transformers.machine_info --silent"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "gpu_env",
   "language": "python",
   "name": "gpu_env"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.13"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 4
}