File size: 34,258 Bytes
db5855f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
{
 "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. <br>\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). <br>\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<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "1c15838dc58a435ca86fe960150c3a92",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "data/kg_training_relids.txt:   0%|          | 0.00/62.0 [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    },
    {
     "data": {
      "application/vnd.jupyter.widget-view+json": {
       "model_id": "b431e3af943c4540b6611d9a0a621b92",
       "version_major": 2,
       "version_minor": 0
      },
      "text/plain": [
       "data/e1rel_to_e2_ranking_test.json:   0%|          | 0.00/19.1k [00:00<?, ?B/s]"
      ]
     },
     "metadata": {},
     "output_type": "display_data"
    }
   ],
   "source": [
    "data_folder = \"data\"\n",
    "\n",
    "# Download the file containing the entities and entity IDs\n",
    "entdatapath = download_file(\n",
    "    \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/text/countries_S1/kg_training_entids.txt\",\n",
    "    directory=data_folder,\n",
    ")\n",
    "\n",
    "# Download the file containing the relations and relation IDs\n",
    "reldatapath = download_file(\n",
    "    \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/text/countries_S1/kg_training_relids.txt\",\n",
    "    directory=data_folder,\n",
    ")\n",
    "\n",
    "# Download the test data file\n",
    "testdatapath = download_file(\n",
    "    \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/json/countries_S1/e1rel_to_e2_ranking_test.json\",\n",
    "    directory=data_folder,\n",
    ")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Download Model Checkpoint\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 6,
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "'models/conve.pt' already exists.\n"
     ]
    },
    {
     "data": {
      "text/plain": [
       "PosixPath('/home/ea/work/openvino_notebooks/notebooks/knowledge-graphs-conve/models/conve.pt')"
      ]
     },
     "execution_count": 6,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "model_url = \"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/models/knowledge-graph-embeddings/conve.pt\"\n",
    "\n",
    "download_file(model_url, filename=modelpath.name, directory=modelpath.parent)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Defining the ConvE model class\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 7,
   "metadata": {},
   "outputs": [],
   "source": [
    "# Model implementation reference: https://github.com/TimDettmers/ConvE\n",
    "class ConvE(torch.nn.Module):\n",
    "    def __init__(self, num_entities, num_relations, emb_dim):\n",
    "        super(ConvE, self).__init__()\n",
    "        # Embedding tables for entity and relations with num_uniq_ent in y-dim, emb_dim in x-dim\n",
    "        self.emb_e = torch.nn.Embedding(num_entities, emb_dim, padding_idx=0)\n",
    "        self.ent_weights_matrix = torch.ones([num_entities, emb_dim], dtype=torch.float64)\n",
    "        self.emb_rel = torch.nn.Embedding(num_relations, emb_dim, padding_idx=0)\n",
    "        self.ne = num_entities\n",
    "        self.nr = num_relations\n",
    "        self.inp_drop = torch.nn.Dropout(0.2)\n",
    "        self.hidden_drop = torch.nn.Dropout(0.3)\n",
    "        self.feature_map_drop = torch.nn.Dropout2d(0.2)\n",
    "        self.loss = torch.nn.BCELoss()\n",
    "        self.conv1 = torch.nn.Conv2d(1, 32, (3, 3), 1, 0, bias=True)\n",
    "        self.bn0 = torch.nn.BatchNorm2d(1)\n",
    "        self.bn1 = torch.nn.BatchNorm2d(32)\n",
    "        self.ln0 = torch.nn.LayerNorm(emb_dim)\n",
    "        self.register_parameter(\"b\", Parameter(torch.zeros(num_entities)))\n",
    "        self.fc = torch.nn.Linear(16128, emb_dim)\n",
    "\n",
    "    def init(self):\n",
    "        \"\"\"Initializes the model\"\"\"\n",
    "        # Xavier initialization\n",
    "        xavier_normal_(self.emb_e.weight.data)\n",
    "        xavier_normal_(self.emb_rel.weight.data)\n",
    "\n",
    "    def forward(self, e1, rel):\n",
    "        \"\"\"Forward pass on the model.\n",
    "        :param e1: source entity\n",
    "        :param rel: relation between the source and target entities\n",
    "        Returns the model predictions for the target entities\n",
    "        \"\"\"\n",
    "        e1_embedded = self.emb_e(e1).view(-1, 1, 10, 30)\n",
    "        rel_embedded = self.emb_rel(rel).view(-1, 1, 10, 30)\n",
    "        stacked_inputs = torch.cat([e1_embedded, rel_embedded], 2)\n",
    "        stacked_inputs = self.bn0(stacked_inputs)\n",
    "        x = self.inp_drop(stacked_inputs)\n",
    "        x = self.conv1(x)\n",
    "        x = self.bn1(x)\n",
    "        x = F.relu(x)\n",
    "        x = self.feature_map_drop(x)\n",
    "        x = x.view(1, -1)\n",
    "        x = self.fc(x)\n",
    "        x = self.hidden_drop(x)\n",
    "        x = self.ln0(x)\n",
    "        x = F.relu(x)\n",
    "        x = torch.mm(x, self.emb_e.weight.transpose(1, 0))\n",
    "        x = self.hidden_drop(x)\n",
    "        x += self.b.expand_as(x)\n",
    "        pred = torch.nn.functional.softmax(x, dim=1)\n",
    "        return pred"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Defining the dataloader\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 8,
   "metadata": {},
   "outputs": [],
   "source": [
    "class DataLoader:\n",
    "    def __init__(self):\n",
    "        super(DataLoader, self).__init__()\n",
    "\n",
    "        self.ent_path = entdatapath\n",
    "        self.rel_path = reldatapath\n",
    "        self.test_file = testdatapath\n",
    "        self.entity_ids, self.ids2entities = self.load_data(data_path=self.ent_path)\n",
    "        self.rel_ids, self.ids2rel = self.load_data(data_path=self.rel_path)\n",
    "        self.test_triples_list = self.convert_triples(data_path=self.test_file)\n",
    "\n",
    "    def load_data(self, data_path):\n",
    "        \"\"\"Creates a dictionary of data items with corresponding ids\"\"\"\n",
    "        item_dict, ids_dict = {}, {}\n",
    "        fp = open(data_path, \"r\")\n",
    "        lines = fp.readlines()\n",
    "        for line in lines:\n",
    "            name, id = line.strip().split(\"\\t\")\n",
    "            item_dict[name] = int(id)\n",
    "            ids_dict[int(id)] = name\n",
    "        fp.close()\n",
    "        return item_dict, ids_dict\n",
    "\n",
    "    def convert_triples(self, data_path):\n",
    "        \"\"\"Creates a triple of source entity, relation and target entities\"\"\"\n",
    "        triples_list = []\n",
    "        dp = open(data_path, \"r\")\n",
    "        lines = dp.readlines()\n",
    "        for line in lines:\n",
    "            item_dict = json.loads(line.strip())\n",
    "            h = item_dict[\"e1\"]\n",
    "            r = item_dict[\"rel\"]\n",
    "            t = item_dict[\"e2_multi1\"].split(\"\\t\")\n",
    "            hrt_list = []\n",
    "            hrt_list.append(self.entity_ids[h])\n",
    "            hrt_list.append(self.rel_ids[r])\n",
    "            t_ents = []\n",
    "            for t_idx in t:\n",
    "                t_ents.append(self.entity_ids[t_idx])\n",
    "            hrt_list.append(t_ents)\n",
    "            triples_list.append(hrt_list)\n",
    "        dp.close()\n",
    "        return triples_list"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "### Evaluate the trained ConvE model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "First, we will evaluate the model performance using PyTorch. The goal is to make sure there are no accuracy differences between the original model inference and the model converted to OpenVINO intermediate representation inference results. <br>\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. <br>\n",
    "We pass the source entity `san_marino` and relation `locatedIn` to the knowledge graph and obtain the target entity predictions. <br>\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. <br> \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. <br> \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: <Type: 'float32'>\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. <br>\n",
    "We confirm that there are no accuracy differences post conversion. We also perform a sample evaluation on the knowledge graph.<br> \n",
    "Then, we determine the platform specific speedup in runtime performance that can be obtained through OpenVINO graph optimizations. <br>\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: <br>\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<br>\n",
    "of this software and associated documentation files (the \"Software\"), to deal<br>\n",
    "in the Software without restriction, including without limitation the rights<br>\n",
    "to use, copy, modify, merge, publish, distribute, sublicense, and/or sell<br>\n",
    "copies of the Software, and to permit persons to whom the Software is<br>\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<br>\n",
    "copies or substantial portions of the Software.\n",
    "\n",
    "THE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR<br>\n",
    "IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,<br>\n",
    "FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE<br>\n",
    "AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER<br>\n",
    "LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,<br>\n",
    "OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE<br>\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
}