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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
{
 "cells": [
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "c5f666768988bb7e",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "# Classification with ConvNeXt and OpenVINO\n",
    "The [`torchvision.models`](https://pytorch.org/vision/stable/models.html) subpackage contains definitions of models for addressing different tasks, including: image classification, pixelwise semantic segmentation, object detection, instance segmentation, person keypoint detection, video classification, and optical flow. Throughout this notebook we will show how to use one of them.\n",
    "\n",
    "The ConvNeXt model is based on the [A ConvNet for the 2020s](https://arxiv.org/abs/2201.03545) paper. The outcome of this exploration is a family of pure ConvNet models dubbed ConvNeXt. Constructed entirely from standard ConvNet modules, ConvNeXts compete favorably with Transformers in terms of accuracy and scalability, achieving 87.8% ImageNet top-1 accuracy and outperforming Swin Transformers on COCO detection and ADE20K segmentation, while maintaining the simplicity and efficiency of standard ConvNets.\n",
    "The `torchvision.models` subpackage [contains](https://pytorch.org/vision/main/models/convnext.html) several pretrained ConvNeXt model. In this tutorial we will use ConvNeXt Tiny model.\n",
    "\n",
    "\n",
    "#### Table of contents:\n",
    "\n",
    "- [Prerequisites](#Prerequisites)\n",
    "- [Get a test image](#Get-a-test-image)\n",
    "- [Get a pretrained model](#Get-a-pretrained-model)\n",
    "- [Define a preprocessing and prepare an input data](#Define-a-preprocessing-and-prepare-an-input-data)\n",
    "- [Use the original model to run an inference](#Use-the-original-model-to-run-an-inference)\n",
    "- [Convert the model to OpenVINO Intermediate representation format](#Convert-the-model-to-OpenVINO-Intermediate-representation-format)\n",
    "- [Use the OpenVINO IR model to run an inference](#Use-the-OpenVINO-IR-model-to-run-an-inference)\n",
    "\n"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "1c2d1a64285edce7",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Prerequisites\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "3fa963993b1a5e68",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "%pip install -q --extra-index-url https://download.pytorch.org/whl/cpu torch torchvision\n",
    "%pip install -q  \"openvino>=2023.1.0\""
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "5043e3dd3be9ad6a",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Get a test image\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "First of all lets get a test image from an open dataset. "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7aaf480dc5faad52",
   "metadata": {
    "collapsed": false,
    "is_executing": true,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import requests\n",
    "\n",
    "from torchvision.io import read_image\n",
    "import torchvision.transforms as transforms\n",
    "\n",
    "\n",
    "img_path = \"cats_image.jpeg\"\n",
    "r = requests.get(\"https://huggingface.co/datasets/huggingface/cats-image/resolve/main/cats_image.jpeg\")\n",
    "\n",
    "with open(img_path, \"wb\") as f:\n",
    "    f.write(r.content)\n",
    "image = read_image(img_path)\n",
    "display(transforms.ToPILImage()(image))"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "bc57f34a2836b2f7",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Get a pretrained model\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "Torchvision provides a mechanism of [listing and retrieving available models](https://pytorch.org/vision/stable/models.html#listing-and-retrieving-available-models). "
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "ad1a577e49d0cb79",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import torchvision.models as models\n",
    "\n",
    "# List available models\n",
    "all_models = models.list_models()\n",
    "# List of models by type. Classification models are in the parent module.\n",
    "classification_models = models.list_models(module=models)\n",
    "\n",
    "print(classification_models)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "12887cf8f1f5bdfc",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "We will use `convnext_tiny`. To get a pretrained model just use `models.get_model(\"convnext_tiny\", weights='DEFAULT')` or a specific method of `torchvision.models` for this model using [default weights](https://pytorch.org/vision/stable/models/generated/torchvision.models.convnext_tiny.html#torchvision.models.ConvNeXt_Tiny_Weights) that is equivalent to `ConvNeXt_Tiny_Weights.IMAGENET1K_V1`. If you don't specify `weight` or specify `weights=None` it will be a random initialization. To get all available weights for the model you can call `weights_enum = models.get_model_weights(\"convnext_tiny\")`, but there is only one for this model. You can find more information how to initialize pre-trained models [here](https://pytorch.org/vision/stable/models.html#initializing-pre-trained-models)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4ff104177ab55761",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "model = models.convnext_tiny(weights=models.ConvNeXt_Tiny_Weights.DEFAULT)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "b591169d664ba0a3",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Define a preprocessing and prepare an input data\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "You can use `torchvision.transforms` to make a preprocessing or use[preprocessing transforms from the model wight](https://pytorch.org/vision/stable/models.html#using-the-pre-trained-models)."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "7c5ba4260cb1e66",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import torch\n",
    "\n",
    "\n",
    "preprocess = models.ConvNeXt_Tiny_Weights.DEFAULT.transforms()\n",
    "\n",
    "input_data = preprocess(image)\n",
    "input_data = torch.stack([input_data], dim=0)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "203262ff4538e315",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Use the original model to run an inference\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "221e6a6140c9a9c9",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "outputs = model(input_data)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "76c099a1da7e44d4",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "And print results"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "dc09c6ee2c791ed0",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "# download class number to class label mapping\n",
    "imagenet_classes_file_path = \"imagenet_2012.txt\"\n",
    "r = requests.get(\n",
    "    url=\"https://storage.openvinotoolkit.org/repositories/openvino_notebooks/data/data/datasets/imagenet/imagenet_2012.txt\",\n",
    ")\n",
    "\n",
    "with open(imagenet_classes_file_path, \"w\") as f:\n",
    "    f.write(r.text)\n",
    "\n",
    "imagenet_classes = open(imagenet_classes_file_path).read().splitlines()\n",
    "\n",
    "\n",
    "def print_results(outputs: torch.Tensor):\n",
    "    _, predicted_class = outputs.max(1)\n",
    "    predicted_probability = torch.softmax(outputs, dim=1)[0, predicted_class].item()\n",
    "\n",
    "    print(f\"Predicted Class: {predicted_class.item()}\")\n",
    "    print(f\"Predicted Label: {imagenet_classes[predicted_class.item()]}\")\n",
    "    print(f\"Predicted Probability: {predicted_probability}\")"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "757fcd966112c54",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "print_results(outputs)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "36af21a44d028ebe",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Convert the model to OpenVINO Intermediate representation format\n",
    "[back to top ⬆️](#Table-of-contents:)\n",
    "\n",
    "OpenVINO supports PyTorch through conversion to OpenVINO Intermediate Representation (IR) format. To take the advantage of OpenVINO optimization tools and features, the model should be converted using the OpenVINO Converter tool (OVC). The `openvino.convert_model` function provides Python API for OVC usage. The function returns the instance of the OpenVINO Model class, which is ready for use in the Python interface. However, it can also be saved on disk using `openvino.save_model` for future execution."
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "459eda7435de45d8",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "from pathlib import Path\n",
    "\n",
    "import openvino as ov\n",
    "\n",
    "\n",
    "ov_model_xml_path = Path(\"models/ov_convnext_model.xml\")\n",
    "\n",
    "if not ov_model_xml_path.exists():\n",
    "    ov_model_xml_path.parent.mkdir(parents=True, exist_ok=True)\n",
    "    converted_model = ov.convert_model(model, example_input=torch.randn(1, 3, 224, 224))\n",
    "    # add transform to OpenVINO preprocessing converting\n",
    "    ov.save_model(converted_model, ov_model_xml_path)\n",
    "else:\n",
    "    print(f\"IR model {ov_model_xml_path} already exists.\")"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "314101e94e7a7f7d",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "When the `openvino.save_model` function is used, an OpenVINO model is serialized in the file system as two files with `.xml` and `.bin` extensions. This pair of files is called OpenVINO Intermediate Representation format (OpenVINO IR, or just IR) and useful for efficient model deployment. OpenVINO IR can be loaded into another application for inference using the `openvino.Core.read_model` function. "
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "990b1af0c54941c6",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "Select device from dropdown list for running inference using OpenVINO"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "2496704b7dda49c8",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "import ipywidgets as widgets\n",
    "\n",
    "core = ov.Core()\n",
    "device = widgets.Dropdown(\n",
    "    options=core.available_devices + [\"AUTO\"],\n",
    "    value=\"AUTO\",\n",
    "    description=\"Device:\",\n",
    "    disabled=False,\n",
    ")\n",
    "\n",
    "device"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "68430816abf7f5b3",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "core = ov.Core()\n",
    "\n",
    "compiled_model = core.compile_model(ov_model_xml_path, device_name=device.value)"
   ]
  },
  {
   "attachments": {},
   "cell_type": "markdown",
   "id": "d84cf4a8e4b24011",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "source": [
    "## Use the OpenVINO IR model to run an inference\n",
    "[back to top ⬆️](#Table-of-contents:)\n"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "4b7f7686f8220bfc",
   "metadata": {
    "collapsed": false,
    "jupyter": {
     "outputs_hidden": false
    }
   },
   "outputs": [],
   "source": [
    "outputs = compiled_model(input_data)[0]\n",
    "print_results(torch.from_numpy(outputs))"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "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.11.5"
  },
  "openvino_notebooks": {
   "imageUrl": "",
   "tags": {
    "categories": [
     "Convert"
    ],
    "libraries": [],
    "other": [],
    "tasks": [
     "Image Classification"
    ]
   }
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}