{ "cells": [ { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "# OpenVINO optimizations for Knowledge graphs\n", "\n", "The goal of this notebook is to showcase performance optimizations for the ConvE knowledge graph embeddings model using the Intel® Distribution of OpenVINO™ Toolkit.
\n", "The optimizations process contains the following steps:\n", "\n", "1. Export the trained model to a format suitable for OpenVINO optimizations and inference\n", "2. Report the inference performance speedup obtained with the optimized OpenVINO model\n", "\n", "The ConvE model is an implementation of the paper - \"Convolutional 2D Knowledge Graph Embeddings\" (https://arxiv.org/abs/1707.01476).
\n", "The sample dataset can be downloaded from: https://github.com/TimDettmers/ConvE/tree/master/countries/countries_S1\n", "\n", "#### Table of contents:\n", "\n", "- [Windows specific settings](#Windows-specific-settings)\n", "- [Import the packages needed for successful execution](#Import-the-packages-needed-for-successful-execution)\n", " - [Settings: Including path to the serialized model files and input data files](#Settings:-Including-path-to-the-serialized-model-files-and-input-data-files)\n", " - [Download Model Checkpoint](#Download-Model-Checkpoint)\n", " - [Defining the ConvE model class](#Defining-the-ConvE-model-class)\n", " - [Defining the dataloader](#Defining-the-dataloader)\n", " - [Evaluate the trained ConvE model](#Evaluate-the-trained-ConvE-model)\n", " - [Prediction on the Knowledge graph.](#Prediction-on-the-Knowledge-graph.)\n", " - [Convert the trained PyTorch model to IR format for OpenVINO inference](#Convert-the-trained-PyTorch-model-to-IR-format-for-OpenVINO-inference)\n", " - [Evaluate the model performance with OpenVINO](#Evaluate-the-model-performance-with-OpenVINO)\n", "- [Select inference device](#Select-inference-device)\n", " - [Determine the platform specific speedup obtained through OpenVINO graph optimizations](#Determine-the-platform-specific-speedup-obtained-through-OpenVINO-graph-optimizations)\n", " - [Benchmark the converted OpenVINO model using benchmark app](#Benchmark-the-converted-OpenVINO-model-using-benchmark-app)\n", " - [Conclusions](#Conclusions)\n", " - [References](#References)\n", "\n" ] }, { "cell_type": "code", "execution_count": 1, "metadata": {}, "outputs": [], "source": [ "%pip install -q \"openvino>=2023.1.0\" torch scikit-learn tqdm --extra-index-url https://download.pytorch.org/whl/cpu" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Windows specific settings\n", "[back to top ⬆️](#Table-of-contents:)\n" ] }, { "cell_type": "code", "execution_count": 2, "metadata": {}, "outputs": [], "source": [ "# On Windows, add the directory that contains cl.exe to the PATH\n", "# to enable PyTorch to find the required C++ tools.\n", "# This code assumes that Visual Studio 2019 is installed in the default directory.\n", "# If you have a different C++ compiler, please add the correct path\n", "# to os.environ[\"PATH\"] directly.\n", "# Note that the C++ Redistributable is not enough to run this notebook.\n", "\n", "# Adding the path to os.environ[\"LIB\"] is not always required\n", "# - it depends on the system's configuration\n", "\n", "import sys\n", "\n", "if sys.platform == \"win32\":\n", " import distutils.command.build_ext\n", " import os\n", " from pathlib import Path\n", "\n", " VS_INSTALL_DIR = r\"C:/Program Files (x86)/Microsoft Visual Studio\"\n", " cl_paths = sorted(list(Path(VS_INSTALL_DIR).glob(\"**/Hostx86/x64/cl.exe\")))\n", " if len(cl_paths) == 0:\n", " raise ValueError(\n", " \"Cannot find Visual Studio. This notebook requires a C++ compiler. If you installed \"\n", " \"a C++ compiler, please add the directory that contains\"\n", " \"cl.exe to `os.environ['PATH']`.\"\n", " )\n", " else:\n", " # If multiple versions of MSVC are installed, get the most recent version\n", " cl_path = cl_paths[-1]\n", " vs_dir = str(cl_path.parent)\n", " os.environ[\"PATH\"] += f\"{os.pathsep}{vs_dir}\"\n", " # Code for finding the library dirs from\n", " # https://stackoverflow.com/questions/47423246/get-pythons-lib-path\n", " d = distutils.core.Distribution()\n", " b = distutils.command.build_ext.build_ext(d)\n", " b.finalize_options()\n", " os.environ[\"LIB\"] = os.pathsep.join(b.library_dirs)\n", " print(f\"Added {vs_dir} to PATH\")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Import the packages needed for successful execution\n", "[back to top ⬆️](#Table-of-contents:)\n" ] }, { "cell_type": "code", "execution_count": 3, "metadata": {}, "outputs": [], "source": [ "import json\n", "from pathlib import Path\n", "import sys\n", "import time\n", "\n", "import numpy as np\n", "import torch\n", "from sklearn.metrics import accuracy_score\n", "from torch.nn import functional as F, Parameter\n", "from torch.nn.init import xavier_normal_\n", "\n", "import openvino as ov\n", "\n", "# Fetch `notebook_utils` module\n", "import requests\n", "\n", "r = requests.get(\n", " url=\"https://raw.githubusercontent.com/openvinotoolkit/openvino_notebooks/latest/utils/notebook_utils.py\",\n", ")\n", "\n", "open(\"notebook_utils.py\", \"w\").write(r.text)\n", "from notebook_utils import download_file" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Settings: Including path to the serialized model files and input data files\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n" ] }, { "cell_type": "code", "execution_count": 4, "metadata": {}, "outputs": [], "source": [ "# Path to the pretrained model checkpoint\n", "modelpath = Path(\"models/conve.pt\")\n", "\n", "# Entity and relation embedding dimensions\n", "EMB_DIM = 300\n", "\n", "# Top K vals to consider from the predictions\n", "TOP_K = 2\n", "\n", "# Required for OpenVINO conversion\n", "output_dir = Path(\"models\")\n", "base_model_name = \"conve\"\n", "\n", "output_dir.mkdir(exist_ok=True)\n", "\n", "# Paths where PyTorch and OpenVINO IR models will be stored\n", "ir_path = Path(output_dir / base_model_name).with_suffix(\".xml\")" ] }, { "cell_type": "code", "execution_count": 5, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "ddd42480f61647ffaaf292831a28cc35", "version_major": 2, "version_minor": 0 }, "text/plain": [ "data/kg_training_entids.txt: 0%| | 0.00/3.79k [00:00\n", "Here, we use a simple accuracy metric to evaluate the model performance on a test dataset. However, it is typical to use metrics such as Mean Reciprocal Rank, Hits@10 etc." ] }, { "cell_type": "code", "execution_count": 9, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Average time taken for inference: 0.8238554000854492 ms\n", "Mean accuracy of the model on the test dataset: 0.875\n" ] } ], "source": [ "data = DataLoader()\n", "num_entities = len(data.entity_ids)\n", "num_relations = len(data.rel_ids)\n", "\n", "model = ConvE(num_entities=num_entities, num_relations=num_relations, emb_dim=EMB_DIM)\n", "model.load_state_dict(torch.load(modelpath))\n", "model.eval()\n", "\n", "pt_inf_times = []\n", "\n", "triples_list = data.test_triples_list\n", "num_test_samples = len(triples_list)\n", "pt_acc = 0.0\n", "for i in range(num_test_samples):\n", " test_sample = triples_list[i]\n", " h, r, t = test_sample\n", " start_time = time.time()\n", " logits = model.forward(e1=torch.tensor(h), rel=torch.tensor(r))\n", " end_time = time.time()\n", " pt_inf_times.append(end_time - start_time)\n", " score, pred = torch.topk(logits, TOP_K, 1)\n", "\n", " gt = np.array(sorted(t))\n", " pred = np.array(sorted(pred[0].cpu().detach()))\n", " pt_acc += accuracy_score(gt, pred)\n", "\n", "avg_pt_time = np.mean(pt_inf_times) * 1000\n", "print(f\"Average time taken for inference: {avg_pt_time} ms\")\n", "print(f\"Mean accuracy of the model on the test dataset: {pt_acc/num_test_samples}\")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Prediction on the Knowledge graph.\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "Here, we perform the entity prediction on the knowledge graph, as a sample evaluation task.
\n", "We pass the source entity `san_marino` and relation `locatedIn` to the knowledge graph and obtain the target entity predictions.
\n", "Expected predictions are target entities that form a factual triple with the entity and relation passed as inputs to the knowledge graph." ] }, { "cell_type": "code", "execution_count": 10, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Source Entity: san_marino, Relation: locatedin, Target entity prediction: southern_europe\n", "Source Entity: san_marino, Relation: locatedin, Target entity prediction: europe\n" ] } ], "source": [ "entitynames_dict = data.ids2entities\n", "\n", "ent = \"san_marino\"\n", "rel = \"locatedin\"\n", "\n", "h_idx = data.entity_ids[ent]\n", "r_idx = data.rel_ids[rel]\n", "\n", "logits = model.forward(torch.tensor(h_idx), torch.tensor(r_idx))\n", "score, pred = torch.topk(logits, TOP_K, 1)\n", "\n", "for j, id in enumerate(pred[0].cpu().detach().numpy()):\n", " pred_entity = entitynames_dict[id]\n", " print(f\"Source Entity: {ent}, Relation: {rel}, Target entity prediction: {pred_entity}\")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Convert the trained PyTorch model to IR format for OpenVINO inference\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "To evaluate performance with OpenVINO, we can either convert the trained PyTorch model to an intermediate representation (IR) format. `ov.convert_model` function can be used for conversion PyTorch models to OpenVINO Model class instance, that is ready to load on device or can be saved on disk in OpenVINO Intermediate Representation (IR) format using `ov.save_model`." ] }, { "cell_type": "code", "execution_count": 11, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Converting the trained conve model to IR format\n" ] } ], "source": [ "print(\"Converting the trained conve model to IR format\")\n", "\n", "ov_model = ov.convert_model(model, example_input=(torch.tensor(1), torch.tensor(1)))\n", "ov.save_model(ov_model, ir_path)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Evaluate the model performance with OpenVINO\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "Now, we evaluate the model performance with the OpenVINO framework. In order to do so, make three main API calls:\n", "\n", "1. Initialize the Inference engine with `Core()`\n", "2. Load the model with `read_model()`\n", "3. Compile the model with `compile_model()`\n", "\n", "Then, the model can be inferred on by using the `create_infer_request()` API call." ] }, { "cell_type": "code", "execution_count": 12, "metadata": {}, "outputs": [], "source": [ "core = ov.Core()\n", "ov_model = core.read_model(model=ir_path)" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "## Select inference device\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "select device from dropdown list for running inference using OpenVINO" ] }, { "cell_type": "code", "execution_count": 13, "metadata": {}, "outputs": [ { "data": { "application/vnd.jupyter.widget-view+json": { "model_id": "8075bb64a0b5497d820ddeaf3c840bf7", "version_major": 2, "version_minor": 0 }, "text/plain": [ "Dropdown(description='Device:', options=('CPU', 'GPU.0', 'GPU.1', 'AUTO'), value='CPU')" ] }, "execution_count": 13, "metadata": {}, "output_type": "execute_result" } ], "source": [ "import ipywidgets as widgets\n", "\n", "device = widgets.Dropdown(\n", " options=core.available_devices + [\"AUTO\"],\n", " value=\"CPU\",\n", " description=\"Device:\",\n", " disabled=False,\n", ")\n", "\n", "device" ] }, { "cell_type": "code", "execution_count": 14, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Average time taken for inference: 0.7051527500152588 ms\n", "Mean accuracy of the model on the test dataset: 0.10416666666666667\n" ] } ], "source": [ "compiled_model = core.compile_model(model=ov_model, device_name=device.value)\n", "input_layer_source = compiled_model.inputs[0]\n", "input_layer_relation = compiled_model.inputs[1]\n", "output_layer = compiled_model.output(0)\n", "\n", "ov_acc = 0.0\n", "ov_inf_times = []\n", "for i in range(num_test_samples):\n", " test_sample = triples_list[i]\n", " source, relation, target = test_sample\n", " model_inputs = {\n", " input_layer_source: np.int64(source),\n", " input_layer_relation: np.int64(relation),\n", " }\n", " start_time = time.time()\n", " result = compiled_model(model_inputs)[output_layer]\n", " end_time = time.time()\n", " ov_inf_times.append(end_time - start_time)\n", " top_k_idxs = list(np.argpartition(result[0], -TOP_K)[-TOP_K:])\n", "\n", " gt = np.array(sorted(t))\n", " pred = np.array(sorted(top_k_idxs))\n", " ov_acc += accuracy_score(gt, pred)\n", "\n", "avg_ov_time = np.mean(ov_inf_times) * 1000\n", "print(f\"Average time taken for inference: {avg_ov_time} ms\")\n", "print(f\"Mean accuracy of the model on the test dataset: {ov_acc/num_test_samples}\")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Determine the platform specific speedup obtained through OpenVINO graph optimizations\n", "[back to top ⬆️](#Table-of-contents:)\n" ] }, { "cell_type": "code", "execution_count": 15, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Speedup with OpenVINO optimizations: 1.17 X\n" ] } ], "source": [ "# prevent division by zero\n", "delimiter = max(avg_ov_time, np.finfo(float).eps)\n", "\n", "print(f\"Speedup with OpenVINO optimizations: {round(float(avg_pt_time)/float(delimiter),2)} X\")" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Benchmark the converted OpenVINO model using benchmark app\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "The OpenVINO toolkit provides a benchmarking application to gauge the platform specific runtime performance that can be obtained under optimal configuration parameters for a given model. For more details refer to: https://docs.openvino.ai/2024/learn-openvino/openvino-samples/benchmark-tool.html\n", "\n", "Here, we use the benchmark application to obtain performance estimates under optimal configuration for the knowledge graph model inference.
\n", "We obtain the average (AVG), minimum (MIN) as well as maximum (MAX) latency as well as the throughput performance (in samples/s) observed while running the benchmark application.
\n", "The platform specific optimal configuration parameters determined by the benchmarking app for OpenVINO inference can also be obtained by looking at the benchmark app results. " ] }, { "cell_type": "code", "execution_count": 16, "metadata": {}, "outputs": [ { "name": "stdout", "output_type": "stream", "text": [ "Benchmark OpenVINO model using the benchmark app\n", "[Step 1/11] Parsing and validating input arguments\n", "[ INFO ] Parsing input parameters\n", "[Step 2/11] Loading OpenVINO Runtime\n", "[ INFO ] OpenVINO:\n", "[ INFO ] Build ................................. 2024.0.0-13770-9b52171d290\n", "[ INFO ] \n", "[ INFO ] Device info:\n", "[ INFO ] CPU\n", "[ INFO ] Build ................................. 2024.0.0-13770-9b52171d290\n", "[ INFO ] \n", "[ INFO ] \n", "[Step 3/11] Setting device configuration\n", "[ WARNING ] Performance hint was not explicitly specified in command line. Device(CPU) performance hint will be set to PerformanceMode.THROUGHPUT.\n", "[Step 4/11] Reading model files\n", "[ INFO ] Loading model files\n", "[ INFO ] Read model took 8.35 ms\n", "[ INFO ] Original model I/O parameters:\n", "[ INFO ] Model inputs:\n", "[ INFO ] e1 (node: e1) : i64 / [...] / []\n", "[ INFO ] rel (node: rel) : i64 / [...] / []\n", "[ INFO ] Model outputs:\n", "[ INFO ] ***NO_NAME*** (node: aten::softmax/Softmax) : f32 / [...] / [1,271]\n", "[Step 5/11] Resizing model to match image sizes and given batch\n", "[ INFO ] Model batch size: 1\n", "[Step 6/11] Configuring input of the model\n", "[ INFO ] Model inputs:\n", "[ INFO ] e1 (node: e1) : i64 / [...] / []\n", "[ INFO ] rel (node: rel) : i64 / [...] / []\n", "[ INFO ] Model outputs:\n", "[ INFO ] ***NO_NAME*** (node: aten::softmax/Softmax) : f32 / [...] / [1,271]\n", "[Step 7/11] Loading the model to the device\n", "[ INFO ] Compile model took 53.61 ms\n", "[Step 8/11] Querying optimal runtime parameters\n", "[ INFO ] Model:\n", "[ INFO ] NETWORK_NAME: Model0\n", "[ INFO ] OPTIMAL_NUMBER_OF_INFER_REQUESTS: 18\n", "[ INFO ] NUM_STREAMS: 18\n", "[ INFO ] AFFINITY: Affinity.CORE\n", "[ INFO ] INFERENCE_NUM_THREADS: 36\n", "[ INFO ] PERF_COUNT: NO\n", "[ INFO ] INFERENCE_PRECISION_HINT: \n", "[ INFO ] PERFORMANCE_HINT: THROUGHPUT\n", "[ INFO ] EXECUTION_MODE_HINT: ExecutionMode.PERFORMANCE\n", "[ INFO ] PERFORMANCE_HINT_NUM_REQUESTS: 0\n", "[ INFO ] ENABLE_CPU_PINNING: True\n", "[ INFO ] SCHEDULING_CORE_TYPE: SchedulingCoreType.ANY_CORE\n", "[ INFO ] ENABLE_HYPER_THREADING: True\n", "[ INFO ] EXECUTION_DEVICES: ['CPU']\n", "[ INFO ] CPU_DENORMALS_OPTIMIZATION: False\n", "[ INFO ] CPU_SPARSE_WEIGHTS_DECOMPRESSION_RATE: 1.0\n", "[Step 9/11] Creating infer requests and preparing input tensors\n", "[ WARNING ] No input files were given for input 'e1'!. This input will be filled with random values!\n", "[ WARNING ] No input files were given for input 'rel'!. This input will be filled with random values!\n", "[ INFO ] Fill input 'e1' with random values \n", "[ INFO ] Fill input 'rel' with random values \n", "[Step 10/11] Measuring performance (Start inference asynchronously, 18 inference requests, limits: 10000 ms duration)\n", "[ INFO ] Benchmarking in inference only mode (inputs filling are not included in measurement loop).\n", "[ INFO ] First inference took 4.97 ms\n", "[Step 11/11] Dumping statistics report\n", "[ INFO ] Execution Devices:['CPU']\n", "[ INFO ] Count: 142056 iterations\n", "[ INFO ] Duration: 10001.15 ms\n", "[ INFO ] Latency:\n", "[ INFO ] Median: 0.96 ms\n", "[ INFO ] Average: 1.01 ms\n", "[ INFO ] Min: 0.43 ms\n", "[ INFO ] Max: 24.61 ms\n", "[ INFO ] Throughput: 14203.97 FPS\n" ] } ], "source": [ "print(\"Benchmark OpenVINO model using the benchmark app\")\n", "! benchmark_app -m $ir_path -d $device.value -api async -t 10 -shape \"input.1[1],input.2[1]\"" ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### Conclusions\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "In this notebook, we convert the trained PyTorch knowledge graph embeddings model to the OpenVINO format.
\n", "We confirm that there are no accuracy differences post conversion. We also perform a sample evaluation on the knowledge graph.
\n", "Then, we determine the platform specific speedup in runtime performance that can be obtained through OpenVINO graph optimizations.
\n", "To learn more about the OpenVINO performance optimizations, refer to: https://docs.openvino.ai/2024/openvino-workflow/running-inference/optimize-inference.html " ] }, { "attachments": {}, "cell_type": "markdown", "metadata": {}, "source": [ "### References\n", "[back to top ⬆️](#Table-of-contents:)\n", "\n", "1. Convolutional 2D Knowledge Graph Embeddings, Tim Dettmers et al. (https://arxiv.org/abs/1707.01476)\n", "2. Model implementation: https://github.com/TimDettmers/ConvE \n", "\n", "The ConvE model implementation used in this notebook is licensed under the MIT License. The license is displayed below:
\n", "MIT License\n", "\n", "Copyright (c) 2017 Tim Dettmers\n", "\n", "Permission is hereby granted, free of charge, to any person obtaining a copy
\n", "of this software and associated documentation files (the \"Software\"), to deal
\n", "in the Software without restriction, including without limitation the rights
\n", "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
\n", "copies of the Software, and to permit persons to whom the Software is
\n", "furnished to do so, subject to the following conditions:\n", "\n", "The above copyright notice and this permission notice shall be included in all
\n", "copies or substantial portions of the Software.\n", "\n", "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
\n", "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
\n", "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
\n", "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
\n", "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
\n", "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
\n", "SOFTWARE." ] } ], "metadata": { "kernelspec": { "display_name": "Python 3 (ipykernel)", "language": "python", "name": "python3" }, "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.8.10" }, "openvino_notebooks": { "imageUrl": "https://user-images.githubusercontent.com/29454499/210564312-82cda081-b2ed-4027-8251-ca57a97b4666.png", "tags": { "categories": [ "Model Demos", "Optimize" ], "libraries": [], "other": [], "tasks": [ "Knowledge Representation" ] } }, "vscode": { "interpreter": { "hash": "e0404472fd7b5b63117a9fa5c50283296e2708c2449c6090d2cdf8903f95897f" } }, "widgets": { "application/vnd.jupyter.widget-state+json": { "state": {}, "version_major": 2, "version_minor": 0 } } }, "nbformat": 4, "nbformat_minor": 4 }