{ "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 }