From 98f771fc028979c53a9cd23db6823d6d7a23bd14 Mon Sep 17 00:00:00 2001
From: Idan Ben Ami <109598548+Idan-BenAmi@users.noreply.github.com>
Date: Wed, 8 May 2024 20:38:37 +0300
Subject: [PATCH] removing quickstart project from mct (#1054)
* Remove quickstart project from mct
---
README.md | 3 -
model_compression_toolkit/gptq/README.md | 2 +-
tutorials/notebooks/IMX500_notebooks.md | 68 +-
tutorials/notebooks/MCT_notebooks.md | 10 -
.../example_quick_start_torchvision.ipynb | 214 ------
tutorials/quick_start/README.md | 256 -------
tutorials/quick_start/__init__.py | 14 -
tutorials/quick_start/common/__init__.py | 14 -
tutorials/quick_start/common/constants.py | 42 --
.../quick_start/common/library_mapping.py | 55 --
tutorials/quick_start/common/model_lib.py | 122 ----
tutorials/quick_start/common/results.py | 159 -----
tutorials/quick_start/common/tpc_info.py | 53 --
tutorials/quick_start/common/utils.py | 106 ---
tutorials/quick_start/keras_fw/__init__.py | 14 -
.../keras_fw/keras_applications/LICENSE | 33 -
.../keras_fw/keras_applications/__init__.py | 14 -
.../keras_fw/keras_applications/model_lib.py | 141 ----
tutorials/quick_start/keras_fw/quant.py | 141 ----
tutorials/quick_start/keras_fw/utils.py | 122 ----
tutorials/quick_start/main.py | 168 -----
tutorials/quick_start/pytorch_fw/__init__.py | 14 -
tutorials/quick_start/pytorch_fw/quant.py | 149 ----
.../quick_start/pytorch_fw/timm_lib/LICENSE | 201 ------
.../pytorch_fw/timm_lib/__init__.py | 14 -
.../pytorch_fw/timm_lib/model_lib.py | 105 ---
.../pytorch_fw/torchvision_lib/LICENSE | 29 -
.../pytorch_fw/torchvision_lib/__init__.py | 14 -
.../pytorch_fw/torchvision_lib/model_lib.py | 105 ---
.../pytorch_fw/ultralytics_lib/LICENSE | 661 ------------------
.../pytorch_fw/ultralytics_lib/README.md | 51 --
.../pytorch_fw/ultralytics_lib/__init__.py | 14 -
.../ultralytics_lib/common_replacers.py | 167 -----
.../ultralytics_lib/detect_replacers.py | 155 ----
.../pytorch_fw/ultralytics_lib/model_lib.py | 124 ----
.../ultralytics_lib/pose_replacers.py | 97 ---
.../ultralytics_lib/replace_module.py | 25 -
.../ultralytics_lib/segment_replacers.py | 90 ---
tutorials/quick_start/pytorch_fw/utils.py | 64 --
.../results/model_quantization_results.csv | 15 -
40 files changed, 63 insertions(+), 3782 deletions(-)
delete mode 100644 tutorials/notebooks/pytorch/example_quick_start_torchvision.ipynb
delete mode 100644 tutorials/quick_start/README.md
delete mode 100644 tutorials/quick_start/__init__.py
delete mode 100644 tutorials/quick_start/common/__init__.py
delete mode 100644 tutorials/quick_start/common/constants.py
delete mode 100644 tutorials/quick_start/common/library_mapping.py
delete mode 100644 tutorials/quick_start/common/model_lib.py
delete mode 100644 tutorials/quick_start/common/results.py
delete mode 100644 tutorials/quick_start/common/tpc_info.py
delete mode 100644 tutorials/quick_start/common/utils.py
delete mode 100644 tutorials/quick_start/keras_fw/__init__.py
delete mode 100644 tutorials/quick_start/keras_fw/keras_applications/LICENSE
delete mode 100644 tutorials/quick_start/keras_fw/keras_applications/__init__.py
delete mode 100644 tutorials/quick_start/keras_fw/keras_applications/model_lib.py
delete mode 100644 tutorials/quick_start/keras_fw/quant.py
delete mode 100644 tutorials/quick_start/keras_fw/utils.py
delete mode 100644 tutorials/quick_start/main.py
delete mode 100644 tutorials/quick_start/pytorch_fw/__init__.py
delete mode 100644 tutorials/quick_start/pytorch_fw/quant.py
delete mode 100644 tutorials/quick_start/pytorch_fw/timm_lib/LICENSE
delete mode 100644 tutorials/quick_start/pytorch_fw/timm_lib/__init__.py
delete mode 100644 tutorials/quick_start/pytorch_fw/timm_lib/model_lib.py
delete mode 100644 tutorials/quick_start/pytorch_fw/torchvision_lib/LICENSE
delete mode 100644 tutorials/quick_start/pytorch_fw/torchvision_lib/__init__.py
delete mode 100644 tutorials/quick_start/pytorch_fw/torchvision_lib/model_lib.py
delete mode 100644 tutorials/quick_start/pytorch_fw/ultralytics_lib/LICENSE
delete mode 100644 tutorials/quick_start/pytorch_fw/ultralytics_lib/README.md
delete mode 100644 tutorials/quick_start/pytorch_fw/ultralytics_lib/__init__.py
delete mode 100644 tutorials/quick_start/pytorch_fw/ultralytics_lib/common_replacers.py
delete mode 100644 tutorials/quick_start/pytorch_fw/ultralytics_lib/detect_replacers.py
delete mode 100644 tutorials/quick_start/pytorch_fw/ultralytics_lib/model_lib.py
delete mode 100644 tutorials/quick_start/pytorch_fw/ultralytics_lib/pose_replacers.py
delete mode 100644 tutorials/quick_start/pytorch_fw/ultralytics_lib/replace_module.py
delete mode 100644 tutorials/quick_start/pytorch_fw/ultralytics_lib/segment_replacers.py
delete mode 100644 tutorials/quick_start/pytorch_fw/utils.py
delete mode 100644 tutorials/quick_start/results/model_quantization_results.csv
diff --git a/README.md b/README.md
index a5f1b8df0..7492a1e28 100644
--- a/README.md
+++ b/README.md
@@ -45,9 +45,6 @@ for hands-on learning. For example:
* [Post training quantization with PyTorch](tutorials/notebooks/pytorch/ptq/example_pytorch_quantization_mnist.ipynb)
* [Data Generation for ResNet18 with PyTorch](tutorials/notebooks/pytorch/data_generation/example_pytorch_data_generation.ipynb).
-Additionally, for quick quantization of a variety of models from well-known collections,
-visit the [quick-start page](tutorials/quick_start/README.md) and the
-[results CSV](tutorials/quick_start/results/model_quantization_results.csv).
### Supported Versions
diff --git a/model_compression_toolkit/gptq/README.md b/model_compression_toolkit/gptq/README.md
index 338014eda..8a60c7ff4 100644
--- a/model_compression_toolkit/gptq/README.md
+++ b/model_compression_toolkit/gptq/README.md
@@ -17,7 +17,7 @@ The Hessian information is approximated in a label-free manner, thus, does not r
## GPTQ Usage
-For detailed examples and tutorials on using GPTQ in MCT with TensorFlow or PyTorch across various models and tasks, please refer to the [tutorials package](../../tutorials). You will find comprehensive explanations, notebook examples, and a [quick-start guide](../../tutorials/quick_start/README.md) for straightforward execution.
+For detailed examples and tutorials on using GPTQ in MCT with TensorFlow or PyTorch across various models and tasks, please refer to the [tutorials package](../../tutorials). You will find comprehensive explanations and notebook examples for straightforward execution.
## References
diff --git a/tutorials/notebooks/IMX500_notebooks.md b/tutorials/notebooks/IMX500_notebooks.md
index ad914988c..57d3ac8ba 100644
--- a/tutorials/notebooks/IMX500_notebooks.md
+++ b/tutorials/notebooks/IMX500_notebooks.md
@@ -3,10 +3,66 @@
Here we provide examples on quantizing pre-trained models for deployment on Sony-IMX500 processing platform.
We will cover various tasks and demonstrate the necessary steps to achieve efficient quantization for optimal
deployment performance.
-
- | Task | Model | Source Repository | Notebook |
- |-----------------------------------------------------------------|----------------|---------------------------------------------------------------------|---------------------------------------------------------------------------------------------------------|
- | Classification | MobileNetV2 | [Keras Applications](https://keras.io/api/applications/) | [Keras notebook](keras/ptq/example_keras_imagenet.ipynb) |
- | Object Detection | YOLOv8n | [Ultralytics](https://github.com/ultralytics/ultralytics) | [Keras notebook](keras/ptq/keras_yolov8n_for_imx500.ipynb) |
- | Semantic Segmentation | DeepLabV3-Plus | [bonlime's repo](https://github.com/bonlime/keras-deeplab-v3-plus) | [Keras notebook](keras/ptq/keras_deeplabv3plus_for_imx500.ipynb) |
+
+
+
+ Task |
+ Model Name |
+ Framework |
+ Dataset Name |
+
+
+
+ Classification |
+ MobilenetV2 |
+ Keras |
+ ImageNet |
+
+
+ MobileVit |
+ PyTorch |
+ ImageNet |
+
+
+
+ Object Detection |
+ YOLOv8n |
+ Keras |
+ COCO |
+
+
+ YOLOv8n |
+ PyTorch |
+ COCO |
+
+
+ NanoDet-Plus-m-416 |
+ Keras |
+ COCO |
+
+
+ EfficientDet-lite0 |
+ Keras |
+ COCO |
+
+
+ Semantic Segmentation |
+ Deeplabv3plus |
+ Keras |
+ PASCAL VOC |
+
+
+ Instance Segmentation |
+ YOLOv8n-seg |
+ PyTorch |
+ COCO |
+
+
+ Pose Estimation |
+ YOLOv8n-pose |
+ PyTorch |
+ COCO |
+
+
+
diff --git a/tutorials/notebooks/MCT_notebooks.md b/tutorials/notebooks/MCT_notebooks.md
index 251194ad8..06350e446 100644
--- a/tutorials/notebooks/MCT_notebooks.md
+++ b/tutorials/notebooks/MCT_notebooks.md
@@ -69,16 +69,6 @@ These techniques are essential for further optimizing models and achieving super
### Pytorch Tutorials
-
- Quick-Start with Torchvision
-
- | Tutorial |
- |-----------------------------------------------------------------------------------------------------------------|
- | [Quick Start - Torchvision Pretrained Model](pytorch/example_quick_start_torchvision.ipynb) |
-
-
-
-
Post-Training Quantization (PTQ)
diff --git a/tutorials/notebooks/pytorch/example_quick_start_torchvision.ipynb b/tutorials/notebooks/pytorch/example_quick_start_torchvision.ipynb
deleted file mode 100644
index fb675d727..000000000
--- a/tutorials/notebooks/pytorch/example_quick_start_torchvision.ipynb
+++ /dev/null
@@ -1,214 +0,0 @@
-{
- "cells": [
- {
- "cell_type": "markdown",
- "id": "c9e7b10d2bfe67d4",
- "metadata": {
- "collapsed": false,
- "id": "c9e7b10d2bfe67d4"
- },
- "source": [
- "# Quick Start\n",
- "\n",
- "[Run this tutorial in Google Colab](https://colab.research.google.com/github/sony/model_optimization/blob/main/tutorials/notebooks/pytorch/example_quick_start_torchvision.ipynb)"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "9bc664bf",
- "metadata": {},
- "source": [
- "## Overview\n",
- "This tutorial shows how to use \"quick-start\" with a pre-trained model from the torchvision library.\n",
- "\n",
- "The following steps will be covered:\n",
- "\n",
- "* **Setup the environment**: install MCT and add tutorials to PYTHONPATH\n",
- "* **Download and organize the imagenet dataset**\n",
- "* **Run quick_start on your model**\n",
- "\n",
- "**Note**: The following code will run faster on a GPU."
- ]
- },
- {
- "cell_type": "markdown",
- "id": "d0e81b09e6d30873",
- "metadata": {
- "collapsed": false,
- "id": "d0e81b09e6d30873"
- },
- "source": [
- "## Setup\n",
- "\n",
- "Install and import relevant packages"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "eda6ab0d8f0b6b56",
- "metadata": {
- "collapsed": false,
- "id": "eda6ab0d8f0b6b56"
- },
- "source": [
- "In order to use quick-start you'll need the [MCT tutorial folder](https://github.com/sony/model_optimization/tree/main/tutorials), so we'll clone the MCT repository to a local folder and use that code.\n",
- "\n",
- " **It's important to note that we use the most up-to-date MCT code available.**"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "ca9a743c0e7ba067",
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "ca9a743c0e7ba067",
- "outputId": "10c7246b-8b31-4c44-9a45-04d4d3a2958b"
- },
- "outputs": [],
- "source": [
- "!git clone https://github.com/sony/model_optimization.git local_mct\n",
- "!pip install -r ./local_mct/requirements.txt"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "PfJ3_AyieBL0",
- "metadata": {
- "id": "PfJ3_AyieBL0"
- },
- "outputs": [],
- "source": [
- "import os\n",
- "os.environ['PYTHONPATH'] = './local_mct/'"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "ufTwrlH-eCyB",
- "metadata": {
- "id": "ufTwrlH-eCyB"
- },
- "source": [
- "## Dataset\n",
- "Download the imagenet validation dataset.\n",
- "\n",
- "Use torchvision.datasets.ImageNet to create the dataset in the correct structure.\n",
- "\n",
- "**Note**: We use validation for time convinience since the training split is too big. Typically, the validation samples should only be used for testing."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "cj6WQGrLvkvx",
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "cj6WQGrLvkvx",
- "outputId": "46efb6a0-abe3-48d9-ce89-6890a566e6de"
- },
- "outputs": [],
- "source": [
- "!mkdir imagenet\n",
- "!wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_devkit_t12.tar.gz\n",
- "!mv ILSVRC2012_devkit_t12.tar.gz imagenet/\n",
- "!wget https://image-net.org/data/ILSVRC/2012/ILSVRC2012_img_val.tar\n",
- "!mv ILSVRC2012_img_val.tar imagenet/"
- ]
- },
- {
- "cell_type": "code",
- "execution_count": 4,
- "id": "coxDAP4Av3ol",
- "metadata": {
- "id": "coxDAP4Av3ol"
- },
- "outputs": [],
- "source": [
- "import torchvision\n",
- "ds = torchvision.datasets.ImageNet(root='./imagenet', split='val')"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "gY2UsnzOfjtk",
- "metadata": {
- "id": "gY2UsnzOfjtk"
- },
- "source": [
- "## Run Quick Start script on our model of choice\n",
- "\n",
- "Here we set the model name, model library, validation dataset path, and representative datasets path.\n",
- " \n",
- "The remaining arguments are left with their default settings. Please verify that the dataset paths are configured correctly."
- ]
- },
- {
- "cell_type": "code",
- "execution_count": null,
- "id": "ZJ8CR1FQRwg2",
- "metadata": {
- "colab": {
- "base_uri": "https://localhost:8080/"
- },
- "id": "ZJ8CR1FQRwg2",
- "outputId": "607f95e7-8c80-408f-ebe8-ace70f999e3e"
- },
- "outputs": [],
- "source": [
- "!python ./local_mct/tutorials/quick_start/main.py --model_name mobilenet_v2 --model_library torchvision --validation_dataset_folder ./imagenet/val --representative_dataset_folder ./imagenet/val"
- ]
- },
- {
- "cell_type": "markdown",
- "id": "d5d80935",
- "metadata": {},
- "source": [
- "\n",
- "Copyright 2024 Sony Semiconductor Israel, Inc. All rights reserved.\n",
- "\n",
- "Licensed under the Apache License, Version 2.0 (the \"License\");\n",
- "you may not use this file except in compliance with the License.\n",
- "You may obtain a copy of the License at\n",
- "\n",
- " http://www.apache.org/licenses/LICENSE-2.0\n",
- "\n",
- "Unless required by applicable law or agreed to in writing, software\n",
- "distributed under the License is distributed on an \"AS IS\" BASIS,\n",
- "WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n",
- "See the License for the specific language governing permissions and\n",
- "limitations under the License.\n"
- ]
- }
- ],
- "metadata": {
- "accelerator": "GPU",
- "colab": {
- "gpuType": "T4",
- "provenance": []
- },
- "kernelspec": {
- "display_name": "Python 3",
- "name": "python3"
- },
- "language_info": {
- "codemirror_mode": {
- "name": "ipython",
- "version": 2
- },
- "file_extension": ".py",
- "mimetype": "text/x-python",
- "name": "python",
- "nbconvert_exporter": "python",
- "pygments_lexer": "ipython2",
- "version": "2.7.6"
- }
- },
- "nbformat": 4,
- "nbformat_minor": 5
-}
diff --git a/tutorials/quick_start/README.md b/tutorials/quick_start/README.md
deleted file mode 100644
index 067be655e..000000000
--- a/tutorials/quick_start/README.md
+++ /dev/null
@@ -1,256 +0,0 @@
-# MCT Quick Start
-
-This example project demonstrates the capabilities of MCT (Model Compression Toolkit) and illustrates its interface
-with various model collections libraries. By accessing a wide range of pre-trained models, this project allows users to
-generate a quantized version of their chosen model with a single click.
-
-Currently, the project supports a selection of models from each library. However, our ongoing goal is to continually
-expand the support, aiming to include more models
-in the future.
-
-## Supported Features
- - Quantize pretrained models from various model [libraries](#supported-libraries)
- - Evaluate the performance of the floating point model and the quantized model.
- - Use MCT's Post-Training Quantization (PTQ) scheme [example](#basic-model-quantization-example---post-training-quantization-ptq)
- - Use MCT's advanced quantization techniques (such as GPTQ and Mixed Precision) [example](#advanced-model-quantization-example)
-
-
-## Results
-
-
-
- Task |
- Model Source |
- Model Name |
- Dataset Name |
- Float |
- Quantized - W8A8 |
-
-
- Performance |
- Size [MB] |
- Performance |
- Size [MB] |
-
-
-
- Top-1 Accuracy |
-
-
- Classification |
- torchvision |
- mobilenet_v2 |
- ImageNet |
- 72.15% |
- 13.88 |
- 71.88% |
- 3.47 |
-
-
- regnet_y_400mf |
- ImageNet |
- 75.78% |
- 17.24 |
- 75.42% |
- 4.31 |
-
-
- shufflenet_v2_x0_5 |
- ImageNet |
- 60.55% |
- 5.44 |
- 59.7% |
- 1.36 |
-
-
- squeezenet1_0 |
- ImageNet |
- 58.1% |
- 4.96 |
- 57.67% |
- 1.24 |
-
-
- timm |
- regnetx_002 |
- ImageNet |
- 68.76% |
- 10.68 |
- 68.27% |
- 2.67 |
-
-
- regnety_008 |
- ImageNet |
- 76.32% |
- 24.92 |
- 75.98% |
- 6.23 |
-
-
- resnet10t |
- ImageNet |
- 66.56% |
- 21.72 |
- 66.43% |
- 5.43 |
-
-
- resnet18 |
- ImageNet |
- 69.76% |
- 46.72 |
- 69.61% |
- 11.68 |
-
-
- efficientnet_es |
- ImageNet |
- 78.08% |
- 21.56 |
- 77.74% |
- 5.39 |
-
-
- keras_applications |
- MobileNetV2 |
- ImageNet |
- 71.85% |
- 13.88 |
- 71.57% |
- 3.47 |
-
-
- EfficientNetV2B0 |
- ImageNet |
- 78.41% |
- 28.24 |
- 77.44% |
- 7.06 |
-
-
- ResNet50 |
- ImageNet |
- 74.22% |
- 102 |
- 74.08% |
- 25.5 |
-
-
-
- mAP |
-
-
- Object Detection |
- ultralytics |
- yolov8n |
- COCO |
- 37.04 |
- 12.6 |
- 36.17 |
- 3.15 |
-
-
- yolov8m |
- COCO |
- 49.99 |
- 103.6 |
- 49.4 |
- 25.9 |
-
-
- Instance Segmentation |
- yolov8n-seg |
- COCO |
- 30.51 |
- 13.6 |
- 30.18 |
- 3.4 |
-
-
- Pose Estimation |
- yolov8n-pose |
- COCO |
- 50.92 |
- 13.12 |
- 49.18 |
- 3.28 |
-
-
-
-## Supported libraries
-- torchvision: [https://pytorch.org/vision/stable/index.html](https://pytorch.org/vision/stable/index.html)
-- timm: [https://github.com/huggingface/pytorch-image-models/tree/main/timm](https://github.com/huggingface/pytorch-image-models/tree/main/timm)
-- ultralytics: [https://ultralytics.com](https://ultralytics.com)
-- keras-applications: [https://keras.io/api/applications](https://keras.io/api/applications/)
-
-
-## Getting Started
-### Installation
-Install one of the supported libraries above.
-
-
-### Usage Examples
-#### Basic model quantization example - Post training quantization (PTQ)
-In the following example, we are evaluating the MCT on pre-trained mobilenet_v2, taken from torchvision models library
-1. Install the required library using `pip`:
-```bash
-pip install torchvision
- ```
-2. Run main.py script:
-```python
-python main.py --model_name mobilenet_v2 --model_library torchvision --validation_dataset_folder --representative_dataset_folder
-```
-In this example, we are running the main.py script with the following parameters:
-- `--model_name`: Specifies the name of the model to be used (mobilenet_v2 in this case).
-- `--model_library`: Specifies the package of the pre-trained models from which the model name is taken (in this case, torchvision).
-- `--validation_dataset_folder`: Specifies the path to the local copy of the dataset to be used for evaluation.
-- `--representative_dataset_folder`: Specifies the path to the local copy of the dataset to be used for quantization.
-
-Please note that the above example assumes the command is run from the command line and that the [main.py](./main.py) script is in the current directory.
-
-Make sure to refer to the script itself to understand all available parameters and their usage.
-
-#### Advanced model quantization example
-##### Mixed-precision
-In this example, we use the MCT Mixed-Precision quantization workflow to further reduce the model's size, with minimal reduction in the quantized model accuracy.
-We use the same pre-trained mobilenet_v2 model as our baseline, with the goal of attaining a model size
-that is 1/5 of the original floating-point model weights size. This is equivalent to a size reduction factor of 5.
-In contrast, the basic PTQ example illustrated earlier only manages to decrease the model size by a factor of 4.
-
-You can execute the following Python script to compress the model:
-```python
-python main.py --model_name mobilenet_v2 --model_library torchvision --mp_weights_compression 5 --validation_dataset_folder --representative_dataset_folder
-```
-
-##### Gradient-based post training quantization
-The following example demontrates the use of MCT's Gradient-based Post-Training Quantization (GPTQ) workflow.
-This approach is superior to the basic PTQ method as it refines the quantized model weights in order to regain performance.
-The weights modification is done through a knowledge distillation technique sourced from the original floating-point model.
-
-To execute the model compression with this approach, run the following Python script:
-```python
-python main.py --model_name mobilenet_v2 --model_library torchvision --gptq --validation_dataset_folder --representative_dataset_folder
-```
-
-Please note that the Mixed-Precision and Gradient-based Post Training Quantization (GPTQ) strategies can be combined to achieve a more significant model compression while mitigating the impact on model performance.
-#### More examples
-More details and examples for using Ultrlytics models can be found in this [readme](./pytorch_fw/ultralytics_lib/README.md)
-
-## External Package Versions
-
-The following external packages were tested with this project:
-
-- torchvision: Version 0.14.0
-- timm: Version 0.6.13
-- ultralytics: Version 8.0.47
-- keras-applications: Version 2.9.0
-
-## License
-This project is licensed under [Apache License 2.0](../../LICENSE.md).
-However, please note that different external packages have their own licenses. When using this project, you have the option to choose one of the following external packages:
-
-- torchvision: [license link](https://github.com/UiPath/torchvision/blob/master/LICENSE), [license copy](./pytorch_fw/torchvision_lib/LICENSE)
-- timm: [license link](https://github.com/huggingface/pytorch-image-models/blob/main/LICENSE), [license copy](./pytorch_fw/timm_lib/LICENSE)
-- ultralytics: [license link](https://github.com/ultralytics/ultralytics/blob/main/LICENSE), [license copy](./pytorch_fw/ultralytics_lib/LICENSE)
-- keras-applications: [license link](https://github.com/keras-team/keras-applications/blob/master/LICENSE), [license copy](./keras_fw/keras_applications/LICENSE)
diff --git a/tutorials/quick_start/__init__.py b/tutorials/quick_start/__init__.py
deleted file mode 100644
index 2147ec284..000000000
--- a/tutorials/quick_start/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
diff --git a/tutorials/quick_start/common/__init__.py b/tutorials/quick_start/common/__init__.py
deleted file mode 100644
index 2147ec284..000000000
--- a/tutorials/quick_start/common/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
diff --git a/tutorials/quick_start/common/constants.py b/tutorials/quick_start/common/constants.py
deleted file mode 100644
index d0e44ac9a..000000000
--- a/tutorials/quick_start/common/constants.py
+++ /dev/null
@@ -1,42 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-
-MODEL_NAME = 'model_name'
-MODEL_LIBRARY = 'model_library'
-OUTPUT_RESULTS_FILE = 'output_results_file'
-NUM_REPRESENTATIVE_IMAGES = 'num_representative_images'
-BATCH_SIZE = 'batch_size'
-REPRESENTATIVE_DATASET_FOLDER = 'representative_dataset_folder'
-VALIDATION_DATASET_FOLDER = 'validation_dataset_folder'
-TARGET_PLATFORM_NAME = 'target_platform_name'
-TARGET_PLATFORM_VERSION = 'target_platform_version'
-VALIDATION_SET_LIMIT = 'validation_set_limit'
-MP_WEIGHTS_COMPRESSION = 'mp_weights_compression'
-EDGE_TPU = 'edgetpu'
-MODULE_REPLACER = 'module_replacer'
-VALIDATOR = 'validator'
-DETECT = 'detect'
-SEGMENT = 'segment'
-POSE = 'pose'
-RECT = 'rect'
-MODE = 'mode'
-DEVICE = 'device'
-VAL = 'val'
-COCO_POSE = "coco-pose.yaml"
-
-IMAGENET_DATASET = 'ImageNet'
-COCO_DATASET = 'COCO'
-
-BYTES_TO_FP32 = 4
\ No newline at end of file
diff --git a/tutorials/quick_start/common/library_mapping.py b/tutorials/quick_start/common/library_mapping.py
deleted file mode 100644
index 0bb1b721d..000000000
--- a/tutorials/quick_start/common/library_mapping.py
+++ /dev/null
@@ -1,55 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-from typing import Tuple
-import importlib
-
-
-# Dictionary mapping library names to folder names
-LIB2FOLDER_DICT = {
- 'torchvision': 'torchvision_lib', # TorchVision library folder
- 'timm': 'timm_lib', # TIMM library folder
- 'ultralytics': 'ultralytics_lib', # Ultralytics folder
- 'keras_applications': 'keras_applications' # Keras Applications library folder
-}
-
-
-def find_modules(lib: str) -> Tuple[str, str]:
- """
- Finds the relevant module paths for a given pre-trained models library.
-
- Args:
- lib (str): Name of the library.
-
- Returns:
- Tuple of model_lib_module and quant_module, representing the module paths needed to be imported
- for the given library.
-
- Raises:
- Error: If the specified library is not found.
- """
-
- # Search in PyTorch libraries
- folder_name = LIB2FOLDER_DICT[lib]
- if importlib.util.find_spec('pytorch_fw.' + folder_name) is not None:
- model_lib_module = 'pytorch_fw.' + folder_name + '.model_lib'
- quant_module = 'pytorch_fw.quant'
-
- # Search in Keras libraries
- elif importlib.util.find_spec('keras_fw.' + folder_name) is not None:
- model_lib_module = 'keras_fw.' + folder_name + '.model_lib'
- quant_module = 'keras_fw.quant'
- else:
- raise Exception(f'Error: model library {lib} is not supported')
- return model_lib_module, quant_module
diff --git a/tutorials/quick_start/common/model_lib.py b/tutorials/quick_start/common/model_lib.py
deleted file mode 100644
index 7ed0884fc..000000000
--- a/tutorials/quick_start/common/model_lib.py
+++ /dev/null
@@ -1,122 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-from abc import abstractmethod, ABC
-
-
-class BaseModelLib(ABC):
- """
- Abstract base class representing pre-trained model library.
-
- Args:
- args: Arguments required for initializing the model library and selecting the relevant model
-
- Attributes:
- args: The input arguments
- """
-
- def __init__(self, args):
- self.args = args
-
- @abstractmethod
- def get_model(self):
- """
- Abstract method to return the floating-point model for quantization.
-
- Returns:
- The floating-point model to be used for quantization.
- """
- raise NotImplementedError
-
- @abstractmethod
- def get_representative_dataset(self, representative_dataset_folder, n_iter, batch_size):
- """
- Abstract method to return the representative dataset required by MCT for quantization.
-
- Args:
- representative_dataset_folder: Path to the representative dataset folder.
- n_iter: Number of calibration iterations to perform for quantization. It uses for creating the representative dataset.
- batch_size: Batch size for processing the representative dataset.
-
- Returns:
- The representative dataset generator to be used for quantization.
- """
- raise NotImplementedError
-
- @abstractmethod
- def evaluate(self, model):
- """
- Abstract method to perform evaluation for a given model.
-
- Args:
- model: The model to be evaluated.
-
- Returns:
- The evaluation results of the model.
- """
- raise NotImplementedError
-
-
-class ModuleReplacer(ABC):
- """
- Abstract base class for replacing modules in a given model.
-
- """
-
- def __init__(self):
- """
- Initializes the ModuleReplacer object.
- """
- pass
-
- @abstractmethod
- def get_new_module(self, config):
- """
- Abstract method to implement and return the new module based on a given configuration.
-
- Args:
- config: Configuration for the new module.
-
- Returns:
- The new module based on the given configuration.
- """
- raise NotImplementedError
-
- @abstractmethod
- def get_config(self, old_module):
- """
- Abstract method to return the configuration of the old module.
-
- Args:
- old_module: The old module to retrieve the configuration from.
-
- Returns:
- The configuration of the old module.
- """
- raise NotImplementedError
-
- @abstractmethod
- def replace(self, model):
- """
- Abstract method to replace the old module with the new module in a given model.
-
- Args:
- model: The model in which the module replacement should be performed.
-
- Returns:
- The model with the replaced module.
- """
- raise NotImplementedError
-
-
diff --git a/tutorials/quick_start/common/results.py b/tutorials/quick_start/common/results.py
deleted file mode 100644
index 4f50550f8..000000000
--- a/tutorials/quick_start/common/results.py
+++ /dev/null
@@ -1,159 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-import csv
-import logging
-from os import path
-from typing import List, Union
-
-from model_compression_toolkit.core.common.user_info import UserInformation
-from common.constants import MODEL_NAME, MODEL_LIBRARY, VALIDATION_DATASET_FOLDER
-
-from model_compression_toolkit.target_platform_capabilities.target_platform import TargetPlatformCapabilities
-from tutorials.quick_start.common.tpc_info import TPCInfo
-
-
-class DatasetInfo:
- """
- Holds information about the evaluation dataset.
- """
- def __init__(self, dataset_name: str, n_images: int):
- """
- Initializes a new instance of the DatasetInfo class.
-
- Args:
- dataset_name (str): The name of the dataset.
- n_images (int): The number of images in the dataset.
- """
- self.dataset_name = dataset_name
- self.n_images = n_images
-
-
-class QuantInfo:
- """
- Holds information about the quantization process.
- """
- def __init__(self, user_info: UserInformation,
- tpc_info: TPCInfo,
- quantization_workflow: str,
- mp_weights_compression: float = None
- ):
- """
- Initializes a new instance of the QuantInfo class.
-
- Args:
- user_info (UserInformation): Quantization information returned from MCT
- tpc_info (TPCInfo): The target platform capabilities information which is provided to the MCT.
- quantization_workflow (str): String to describe the quantization workflow (PTQ, GPTQ etc.).
- mp_weights_compression (float): Weights compression factor for mixed precision Resource Utilization constraint.
- """
- self.user_info = user_info
- self.tpc_info = tpc_info
- self.quantization_workflow = quantization_workflow
- self.mp_weights_compression = mp_weights_compression
-
-
-def read_models_list(filename: str) -> csv.DictReader:
- """
- Reads a models list and parameters from a CSV file and returns csv.DictReader.
-
- Args:
- filename: Path to the CSV file containing the models list.
-
- Returns:
- A dictionary read from the CSV file.
-
- """
- return csv.DictReader(open(path.join(filename)))
-
-
-def write_results(filename: str, models_list: List[dict], fieldnames: List[str]):
- """
- Writes the results of a models list to a CSV file.
-
- Args:
- filename: Path to the CSV file to write the results.
- models_list: List of model results, where each result is represented by a dictionary.
- fieldnames: List of fieldnames to be written as headers in the CSV file.
-
- Returns:
- None
-
- """
- writer = csv.DictWriter(open(filename, 'w'), fieldnames=fieldnames)
- writer.writeheader()
- for item in models_list:
- writer.writerow(item)
-
-
-def parse_results(params: dict, float_acc: float, quant_acc: float, quant_info: QuantInfo, dataset_info: DatasetInfo) -> dict:
- """
- Parses the results of model evaluation and quantization into a dictionary format.
-
- Args:
- params: Dictionary of parameters containing information about the model, dataset, etc.
- float_acc: Floating-point accuracy of the model.
- quant_acc: Quantized accuracy of the model.
- quant_info: Quantization information object containing details of the quantized model.
-
- Returns:
- A dictionary containing the parsed results.
-
- """
- a_bits = quant_info.tpc_info.activation_nbits
- w_bits = quant_info.tpc_info.weights_nbits
- bit_config = f'W{w_bits}A{a_bits}'
- if quant_info.mp_weights_compression:
- bit_config = f'{bit_config},MP-x{quant_info.mp_weights_compression}'
-
- res = {}
- res['ModelName'] = params[MODEL_NAME]
- res['ModelLibrary'] = params[MODEL_LIBRARY]
- res['DatasetName'] = dataset_info.dataset_name
- res['TotalImages'] = dataset_info.n_images
- res['FloatAcc'] = round(float_acc, 4)
- res['QuantAcc'] = round(quant_acc, 4)
- res['Size[MB]'] = round(quant_info.user_info.final_resource_utilization.weights_memory / 1e6, 2)
- res['BitsConfig'] = bit_config
- res['QuantWorkflow'] = quant_info.quantization_workflow
- res['TPC'] = quant_info.tpc_info.tp_model_name + '-' + quant_info.tpc_info.version
-
- return res
-
-
-def plot_results(data: Union[dict, List[dict]], spacing=15):
- """
- Prints the given dictionary or list of dictionaries as a table to the screen.
-
- Args:
- data (Union[dict, List[dict]]): The dictionary or list of dictionaries to be printed as a table.
- """
- # Handle a single dictionary
- if isinstance(data, dict):
- data = [data]
-
- # Extract the keys as the table header
- header = list(data[0].keys())
-
- # Print the header
- header_title = [h + (spacing - len(h)) * " " for h in header]
- logging.info("\t".join(header_title))
-
- # Print the rows
- for item in data:
- values = [str(item.get(key, "")) for key in header]
- values = [v + (spacing - len(v)) * " " for v in values]
- logging.info("\t".join(values))
-
-
diff --git a/tutorials/quick_start/common/tpc_info.py b/tutorials/quick_start/common/tpc_info.py
deleted file mode 100644
index 4bdc9fa6f..000000000
--- a/tutorials/quick_start/common/tpc_info.py
+++ /dev/null
@@ -1,53 +0,0 @@
-# Copyright 2024 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-
-
-def get_tpc_info(tpc):
- # Retrieve the number of bits used for activation functions within the TPC's default operation.
- activation_nbits = tpc.get_default_op_qc().activation_n_bits
-
- # Retrieve the number of bits used for weights in the TPC's default weight configuration.
- weights_nbits = tpc.get_default_op_qc().default_weight_attr_config.weights_n_bits
-
- # Extract the name of the tp model associated with the TPC.
- tp_model_name = tpc.tp_model.name
-
- # Get the version of the TPC.
- version = tpc.version
-
- return TPCInfo(activation_nbits=activation_nbits,
- weights_nbits=weights_nbits,
- tp_model_name=tp_model_name,
- version=version)
-
-class TPCInfo:
- def __init__(self,
- activation_nbits: int,
- weights_nbits: int,
- tp_model_name: str,
- version: str):
- """
- Args:
- activation_nbits: Number of bits used for activation functions.
- weights_nbits: Number of bits used for weights.
- tp_model_name: TP model's name.
- version: TPC's version.
- """
- self.activation_nbits = activation_nbits
- self.weights_nbits = weights_nbits
- self.tp_model_name = tp_model_name
- self.version = version
-
-
diff --git a/tutorials/quick_start/common/utils.py b/tutorials/quick_start/common/utils.py
deleted file mode 100644
index 386f249c8..000000000
--- a/tutorials/quick_start/common/utils.py
+++ /dev/null
@@ -1,106 +0,0 @@
-# Copyright 2024 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-import os
-import numpy as np
-from PIL import Image
-
-from typing import List, Callable
-import logging
-
-FILETYPES = ['jpeg', 'jpg', 'bmp', 'png']
-
-
-class FolderImageLoader(object):
- """
-
- Class for images loading, processing and retrieving.
-
- """
-
- def __init__(self,
- folder: str,
- preprocessing: List[Callable],
- batch_size: int,
- file_types: List[str] = FILETYPES):
-
- """ Initialize a FolderImageLoader object.
-
- Args:
- folder: Path of folder with images to load. The path has to exist, and has to contain at
- least one image.
- preprocessing: List of functions to use when processing the images before retrieving them.
- batch_size: Number of images to retrieve each sample.
- file_types: Files types to scan in the folder. Default list is :data:`~model_compression_toolkit.core.common.data_loader.FILETYPES`
-
- Examples:
-
- Instantiate a FolderImageLoader using a directory of images, that returns 10 images randomly each time it is sampled:
-
- >>> image_data_loader = FolderImageLoader('path/to/images/directory', preprocessing=[], batch_size=10)
- >>> images = image_data_loader.sample()
-
- To preprocess the images before retrieving them, a list of preprocessing methods can be passed:
-
- >>> image_data_loader = FolderImageLoader('path/to/images/directory', preprocessing=[lambda x: (x-127.5)/127.5], batch_size=10)
-
- For the FolderImageLoader to scan only specific files extensions, a list of extensions can be passed:
-
- >>> image_data_loader = FolderImageLoader('path/to/images/directory', preprocessing=[], batch_size=10, file_types=['png'])
-
- """
-
- self.folder = folder
- self.image_list = []
- logging.info(f"Starting Scanning Disk: {self.folder}")
- for root, dirs, files in os.walk(self.folder):
- for file in files:
- file_type = file.split('.')[-1].lower()
- if file_type in file_types:
- self.image_list.append(os.path.join(root, file))
- self.n_files = len(self.image_list)
- if self.n_files == 0:
- logging.critical(
- f"Expected files of type {FILETYPES}. No files of type {FILETYPES} were found.") # pragma: no cover
- logging.info(f"Finished Disk Scanning: Found {self.n_files} files")
- self.preprocessing = preprocessing
- self.batch_size = batch_size
-
- def _sample(self):
- """
- Read batch_size random images from the image_list the FolderImageLoader holds.
- Process them using the preprocessing list that was passed at initialization, and
- prepare it for retrieving.
- """
-
- index = np.random.randint(0, self.n_files, self.batch_size)
- image_list = []
- for i in index:
- file = self.image_list[i]
- img = np.uint8(np.array(Image.open(file).convert('RGB')))
- for p in self.preprocessing: # preprocess images
- img = p(img)
- image_list.append(img)
- self.next_batch_data = np.stack(image_list, axis=0)
-
- def sample(self):
- """
-
- Returns: A sample of batch_size images from the folder the FolderImageLoader scanned.
-
- """
-
- self._sample()
- data = self.next_batch_data # get current data
- return data
diff --git a/tutorials/quick_start/keras_fw/__init__.py b/tutorials/quick_start/keras_fw/__init__.py
deleted file mode 100644
index 2147ec284..000000000
--- a/tutorials/quick_start/keras_fw/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
diff --git a/tutorials/quick_start/keras_fw/keras_applications/LICENSE b/tutorials/quick_start/keras_fw/keras_applications/LICENSE
deleted file mode 100644
index 77a89428b..000000000
--- a/tutorials/quick_start/keras_fw/keras_applications/LICENSE
+++ /dev/null
@@ -1,33 +0,0 @@
-COPYRIGHT
-
-Copyright (c) 2016 - 2018, the respective contributors.
-All rights reserved.
-
-Each contributor holds copyright over their respective contributions.
-The project versioning (Git) records all such contribution source information.
-The initial code of this repository came from https://github.com/keras-team/keras
-(the Keras repository), hence, for author information regarding commits
-that occured earlier than the first commit in the present repository,
-please see the original Keras repository.
-
-LICENSE
-
-The MIT License (MIT)
-
-Permission is hereby granted, free of charge, to any person obtaining a copy
-of this software and associated documentation files (the "Software"), to deal
-in the Software without restriction, including without limitation the rights
-to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
-copies of the Software, and to permit persons to whom the Software is
-furnished to do so, subject to the following conditions:
-
-The above copyright notice and this permission notice shall be included in all
-copies or substantial portions of the Software.
-
-THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
-IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
-FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
-AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
-LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
-OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
-SOFTWARE.
diff --git a/tutorials/quick_start/keras_fw/keras_applications/__init__.py b/tutorials/quick_start/keras_fw/keras_applications/__init__.py
deleted file mode 100644
index 2147ec284..000000000
--- a/tutorials/quick_start/keras_fw/keras_applications/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
diff --git a/tutorials/quick_start/keras_fw/keras_applications/model_lib.py b/tutorials/quick_start/keras_fw/keras_applications/model_lib.py
deleted file mode 100644
index 27688b704..000000000
--- a/tutorials/quick_start/keras_fw/keras_applications/model_lib.py
+++ /dev/null
@@ -1,141 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-
-from typing import Dict
-import tensorflow as tf
-import keras
-
-from tutorials.quick_start.common.model_lib import BaseModelLib
-from tutorials.quick_start.keras_fw.utils import classification_eval, get_representative_dataset, separate_preprocess_model
-from tutorials.quick_start.common.constants import MODEL_NAME, BATCH_SIZE, VALIDATION_SET_LIMIT, VALIDATION_DATASET_FOLDER, IMAGENET_DATASET
-
-from tutorials.quick_start.common.results import DatasetInfo
-
-
-class ModelLib(BaseModelLib):
- """
- A class for quantizing pre-trained models from the tensorflow.keras.applications library
- """
- def __init__(self, args: Dict):
- """
- Init the ModelLib with user arguments
- Args:
- args (dict): user arguments
- """
- model_fn, self.model_package = self.get_keras_apps_model(args[MODEL_NAME])
- # create model
- self.model = model_fn()
- self.preprocess = self.generate_preprocess()
- self.dataset_name = IMAGENET_DATASET
- # Extract image input size and verify it's not dynamic (equals None)
- self.input_size = self.model.layers[0].input_shape[0][1:3]
- if None in self.input_size:
- raise Exception(f'model {args[MODEL_NAME]} has a dynamic input size, which is not supported by the MCT')
- super().__init__(args)
-
- def get_keras_apps_model(self, model_name: str):
- """
- Extracts the model package and model name from the input string: .
- The model package class contains the 'preprocess_input' method for preprocessing input images
- One exception is the MobileNetV3 models that are located in the parent model (tf.keras.applications)
-
- Args:
- model_name (str): A string containing the model to quantize in the following format: . (e.g. mobilenet_v2.MobileNetV2)
-
- Returns:
- model package class
- model class
-
- """
- if hasattr(tf.keras.applications, model_name):
- model_class = getattr(tf.keras.applications, model_name)
- model_package = eval(model_class.__module__)
- else:
- raise Exception(f'Unknown Keras Applications model class {model_name}')
-
- return model_class, model_package
-
- @staticmethod
- def get_keras_apps_weights(model_name):
- return None
-
- def generate_preprocess(self, truncate_preprocess: bool = False):
- """
- Generates the preprocess function for evaluation and quantization (representative dataset)
- Some models in this library contain the normalization of the preprocess in the beginning of the model. They can be removed.
- Args:
- truncate_preprocess (bool): Removes Normalization & Rescaling layers from the beginning of the model
-
- Returns:
-
- """
- pp_model = None
- if truncate_preprocess:
- self.model, pp_model = separate_preprocess_model(self.model)
-
- def _preprocess(x, l):
- x = self.model_package.preprocess_input(x)
- if pp_model is not None:
- x = pp_model(x)
- return x, l
-
- return _preprocess
-
- def get_model(self):
- return self.model
-
- def get_representative_dataset(self, representative_dataset_folder: str, n_iter: int, batch_size: int):
- """
- Create a representative dataset generator
- Args:
- representative_dataset_folder: Dataset location folder, in the format: representative_dataset_folder//
- n_iter: number batches to run in the generator
- batch_size: number of images in each batch
-
- Returns:
- A generator for the representative dataset, as the MCT expects
-
- """
- dl = tf.keras.utils.image_dataset_from_directory(representative_dataset_folder,
- batch_size=batch_size,
- image_size=self.input_size,
- crop_to_aspect_ratio=True).map(self.preprocess)
-
- return get_representative_dataset(dl, n_iter)
-
- def evaluate(self, model):
- """
- Evaluate a model
- Args:
- model: A keras model to evaluate
-
- Returns:
- model accuracy
- dataset info (dataset name, number of images in dataset)
-
- """
- batch_size = int(self.args[BATCH_SIZE])
- validation_dataset_folder = self.args[VALIDATION_DATASET_FOLDER]
- testloader = tf.keras.utils.image_dataset_from_directory(validation_dataset_folder,
- batch_size=batch_size,
- image_size=self.input_size,
- shuffle=False,
- crop_to_aspect_ratio=True)
-
- testloader = testloader.map(self.preprocess)
-
- acc, total = classification_eval(model, testloader, self.args[VALIDATION_SET_LIMIT])
- dataset_info = DatasetInfo(self.dataset_name, total)
- return acc, dataset_info
diff --git a/tutorials/quick_start/keras_fw/quant.py b/tutorials/quick_start/keras_fw/quant.py
deleted file mode 100644
index fe6be8b9d..000000000
--- a/tutorials/quick_start/keras_fw/quant.py
+++ /dev/null
@@ -1,141 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-
-import math
-import tensorflow as tf
-from keras.optimizers import Adam
-
-import model_compression_toolkit as mct
-import logging
-from tutorials.quick_start.common.constants import NUM_REPRESENTATIVE_IMAGES, BATCH_SIZE, \
- REPRESENTATIVE_DATASET_FOLDER, TARGET_PLATFORM_NAME, TARGET_PLATFORM_VERSION, BYTES_TO_FP32, MP_WEIGHTS_COMPRESSION
-
-
-from model_compression_toolkit.core import MixedPrecisionQuantizationConfig, CoreConfig, ResourceUtilization
-from model_compression_toolkit.target_platform_capabilities.target_platform import TargetPlatformCapabilities
-from tutorials.quick_start.common.results import QuantInfo
-from tutorials.quick_start.common.tpc_info import get_tpc_info
-
-
-def get_tpc(target_platform_name: str, target_platform_version: str) -> TargetPlatformCapabilities:
- """
- Returns the target platform capabilities according to the given platform name and version.
-
- Args:
- target_platform_name: Name of the target platform
- target_platform_version: Version of the target platform
-
- Returns:
- The target platform capabilities.
-
- """
- return mct.get_target_platform_capabilities('tensorflow', target_platform_name, target_platform_version)
-
-
-def get_target_resource_utilization(model, weights_compression, representative_data_gen, core_config, tpc):
- """
- Calculates the model's required size according to the given weights compression rate, to provide as a constraint for mixed precision search.
-
- Args:
- model: The model to calculate the target resource utilization for.
- weights_compression: The required weights compression ratio.
- representative_data_gen: Callable function to generate the representative dataset.
- core_config (CoreConfig): CoreConfig containing parameters for quantization and mixed precision.
- tpc (TargetPlatformCapabilities): TargetPlatformCapabilities to optimize the TensorFlow model according to.
-
- Returns:
- A ResourceUtilization object computed from MCT and contains info about the target model size.
-
- """
- ru_data = mct.core.keras_resource_utilization_data(model, representative_data_gen, core_config=core_config,
- target_platform_capabilities=tpc)
- weights_ru = BYTES_TO_FP32 * ru_data.weights_memory / weights_compression # (4 bytes for fp32) * weights memory(in Bytes) / compression rate
- return ResourceUtilization(weights_memory=weights_ru)
-
-
-def quantize(model: tf.keras.Model,
- get_representative_dataset: callable,
- tpc: TargetPlatformCapabilities,
- args: dict):
- """
- Returns a quantized model and a quantization info from MCT for the given TensorFlow floating-point model.
-
- Args:
- model: TensorFlow floating-point model to be quantized.
- get_representative_dataset: Callable function to generate the representative dataset for quantization.
- tpc: Target platform capabilities.
- args: Dictionary containing the necessary configurations for quantization.
-
- Returns:
- Tuple containing the quantized model and quantization info.
-
- """
-
- # PTQ - general configurations
- n_iter = math.ceil(int(args[NUM_REPRESENTATIVE_IMAGES]) // int(args[BATCH_SIZE])) # Number of batches
- logging.info(f"Running MCT... number of representative images: {args[REPRESENTATIVE_DATASET_FOLDER]}, number of calibration iters: {n_iter}")
-
- representative_data_gen = get_representative_dataset(
- representative_dataset_folder=args[REPRESENTATIVE_DATASET_FOLDER],
- n_iter=n_iter,
- batch_size=int(args[BATCH_SIZE])
- )
-
- # Mixed-precision configurations
- mp_wcr = args.get(MP_WEIGHTS_COMPRESSION, None)
- if mp_wcr:
- mp_conf = MixedPrecisionQuantizationConfig()
- core_conf = CoreConfig(quantization_config=mct.core.QuantizationConfig(
- shift_negative_activation_correction=True),
- mixed_precision_config=mp_conf)
- target_resource_utilization = get_target_resource_utilization(model, mp_wcr, representative_data_gen, core_conf, tpc)
- else:
- core_conf = CoreConfig(quantization_config=mct.core.QuantizationConfig(
- shift_negative_activation_correction=True))
- target_resource_utilization = None
-
- # Quantize model
- if args.get('gptq', False):
-
- workflow = 'GPTQ'
- n_epochs = args.get('gptq_num_calibration_iter') // n_iter
- logging.info(
- f"MCT Gradient-based Post Training Quantization is enabled. Number of epochs: {n_epochs}")
-
- gptq_conf = mct.gptq.get_keras_gptq_config(n_epochs=n_epochs, optimizer=Adam(learning_rate=args['gptq_lr']))
-
- quantized_model, quantization_info = \
- mct.gptq.keras_gradient_post_training_quantization(model,
- representative_data_gen=representative_data_gen,
- target_resource_utilization=target_resource_utilization,
- core_config=core_conf,
- gptq_config=gptq_conf,
- gptq_representative_data_gen=representative_data_gen,
- target_platform_capabilities=tpc)
-
-
- else:
- workflow = 'PTQ'
- quantized_model, quantization_info = \
- mct.ptq.keras_post_training_quantization(model,
- representative_data_gen=representative_data_gen,
- target_resource_utilization=target_resource_utilization,
- core_config=core_conf,
- target_platform_capabilities=tpc)
-
- return quantized_model, QuantInfo(user_info=quantization_info,
- tpc_info=get_tpc_info(tpc=tpc),
- quantization_workflow=workflow,
- mp_weights_compression=mp_wcr)
\ No newline at end of file
diff --git a/tutorials/quick_start/keras_fw/utils.py b/tutorials/quick_start/keras_fw/utils.py
deleted file mode 100644
index b89813978..000000000
--- a/tutorials/quick_start/keras_fw/utils.py
+++ /dev/null
@@ -1,122 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-
-import tensorflow as tf
-import logging
-from tqdm import tqdm
-
-
-def classification_eval(model: tf.keras.Model, data_loader: tf.data.Dataset, limit=None):
- """
- Evaluate a classification model
-
- Args:
- model: a model to evaluate
- data_loader: tensorflow evaluation dataset
- limit (int): optionally evaluate the model over less images than in the dataset
-
- Returns:
- model accuracy
- total number of images evaluated
-
- """
- logging.info(f'Start classification evaluation')
- acc = tf.keras.metrics.Accuracy()
- total = 0
- for data in tqdm(data_loader, desc="Classification evaluation"):
- images, labels = data
- # calculate outputs by running images through the network
- outputs = model(images)
- # the class with the highest energy is what we choose as prediction
- predicted = tf.argmax(outputs, 1)
- acc.update_state(labels, predicted)
- total += labels.shape[0]
- if limit and total >= int(limit):
- break
-
- logging.info(f'Num of images: {total}, Accuracy: {round(100 * acc.result().numpy(), 2)} %')
-
- return acc.result().numpy(), total
-
-
-def get_representative_dataset(data_loader: tf.data.Dataset, n_iters: int, data_loader_key: int = 0, preprocess=None):
- """
- A function to generate a representative dataset generator. The class can iterate the rep. dataset over and
- over if it contains fewer images than required iterations.
- Args:
- data_loader (tf.data.Dataset): a tensorflow dataset
- n_iters (int): number of iterations
- data_loader_key (int): index of images in data_loader output (usually the output is a tuple: [image, label])
- preprocess (callable): a function to preprocess a batch of dataset outputs: tuple of (images, labels)
-
- Returns:
- A representative dataset generator
-
- """
-
- class RepresentativeDataset:
- def __init__(self, in_data_loader):
- self.dl = in_data_loader
- self.iter = iter(self.dl)
-
- def __call__(self):
- for _ in range(n_iters):
- try:
- x = next(self.iter)[data_loader_key]
- except StopIteration:
- self.iter = iter(self.dl)
- x = next(self.iter)[data_loader_key]
- if preprocess is not None:
- x = preprocess(x, None)[0]
- yield [x.numpy()]
-
- def __len__(self):
- return n_iters
-
- return RepresentativeDataset(data_loader)
-
-
-def separate_preprocess_model(model: tf.keras.Model):
- """
- Separate the first layers of a model if they are considered as preprocess layers.
- Args:
- model (tf.keras.Model): input model
-
- Returns:
- The model without preprocessing layers
- A model of the preprocessing layers to use in the preprocess of the representative dataset and evaluation
-
- """
- pp_model = None
-
- preprocess_layers = []
- layer, last_layer = None, None
- for layer in model.layers[1:]:
- if isinstance(layer, (tf.keras.layers.Normalization,
- tf.keras.layers.Rescaling)):
- # Collect layers predefined as preprocess (normalization & Rescaling) at the beginning of the model
- preprocess_layers.append(layer.__class__.from_config(layer.get_config()))
- else:
- break
- last_layer = layer
-
- if preprocess_layers and not isinstance(layer, tf.keras.Sequential):
- # Separate the model into 2 models: preprocess-model and model without preprocess
- pp_model = tf.keras.Model(inputs=model.input, outputs=last_layer.output)
- trunc_model = tf.keras.Model(inputs=layer.input, outputs=model.output)
- else:
- trunc_model = model
-
- return trunc_model, pp_model
diff --git a/tutorials/quick_start/main.py b/tutorials/quick_start/main.py
deleted file mode 100644
index 163425051..000000000
--- a/tutorials/quick_start/main.py
+++ /dev/null
@@ -1,168 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-import argparse
-import importlib
-import logging
-import sys
-from typing import Dict, Tuple
-
-from common.results import write_results, read_models_list, parse_results, QuantInfo, plot_results, DatasetInfo
-from common.library_mapping import find_modules
-from common.constants import MODEL_NAME, MODEL_LIBRARY, OUTPUT_RESULTS_FILE, TARGET_PLATFORM_NAME, \
- TARGET_PLATFORM_VERSION
-
-
-# Script to Evaluate and Compress Pre-trained Neural Network Model(s) using MCT (Model Compression Toolkit)
-
-def argument_handler():
- parser = argparse.ArgumentParser()
-
- parser.add_argument('--model_name', '-m', type=str, required=False,
- help='The name of the pre-trained model to run')
- parser.add_argument('--model_library', type=str, required=False,
- help='The library that contains the pre-trained model')
- parser.add_argument('--validation_dataset_folder', type=str, required=False,
- help='Path to the validation dataset')
- parser.add_argument('--representative_dataset_folder', type=str, required=False,
- help='Path to the representative dataset used for quantization')
- parser.add_argument('--num_representative_images', type=int, default=200,
- help='Number of images for representative dataset')
- parser.add_argument('--target_platform_name', type=str, default='default',
- help='Specifies the name of the target platform capabilities (TPC) to select from the available TPCs provided by MCT')
- parser.add_argument('--target_platform_version', type=str, default='latest',
- help='Specifies the version of the target platform capabilities (TPC) to select from the available TPCs provided by MCT')
- parser.add_argument('--batch_size', type=int, default=10,
- help='Batch size for accuracy evaluation')
- parser.add_argument('--models_list_csv', type=str, default=None,
- help='Run according to a list of models and parameters taken from a csv file')
- parser.add_argument('--output_results_file', type=str, default='model_quantization_results.csv',
- help='Run according to a list of models and parameters taken from a csv file')
- parser.add_argument('--validation_set_limit', type=int, default=None,
- help='Limits the number of images taken for evaluation')
- parser.add_argument('--export_model', action="store_true",
- help='Whether to export the model after quantization')
- parser.add_argument('--gptq', action="store_true",
- help='Enables Gradient-based Post Training Quantization (GPTQ)')
- parser.add_argument('--gptq_num_calibration_iter', type=int, default=5000,
- help='The number of iterations on the representative dataset')
- parser.add_argument('--gptq_lr', type=float, default=3e-2,
- help='The number of iterations on the representative dataset')
- parser.add_argument("--mp_weights_compression", type=float, default=None,
- help='Enables mixed-precision quantization for a given weights compression rate. '
- 'The compression rate is relative to 32 bits fp precision, i.e. For a given'
- ' compression-rate of C, the average bits per parameter = 32/C for the compressed model')
-
- args = parser.parse_args()
-
- if args.models_list_csv is None:
- # If models_list_csv is not provided, then the following arguments are required
- required_args = ['model_name', 'model_library', 'validation_dataset_folder', 'representative_dataset_folder']
- missing_args = [arg for arg in required_args if getattr(args, arg) is None]
-
- if missing_args:
- parser.error(f"Missing required arguments: {', '.join(missing_args)}")
- sys.exit(1)
- return args
-
-
-def quantization_flow(config: Dict) -> Tuple[float, float, QuantInfo, DatasetInfo]:
- """
- This function implements the typical workflow when using MCT.
- It begins by evaluating the performance of the floating-point model.
- Next, the model is compressed using MCT quantization techniques.
- Finally, the evaluation process is repeated on the compressed model to assess its performance.
-
- Args:
- config (Dict): Configurations dictionary that contains the settings for the quantization flow
-
- Returns:
- float_results (float): The accuracy of the floating point model
- quant_results (float): The accuracy of the quantized model
- quantization_info (QuantInfo): Information of the model optimization process from MCT
- dataset_info (DatasetInfo): Information about the evaluated dataset
- """
-
- # Find and import the required modules for the models collection library ("model_library")
- model_lib_module, quant_module = find_modules(config[MODEL_LIBRARY])
- model_lib = importlib.import_module(model_lib_module)
- quant = importlib.import_module(quant_module)
-
- # Create a ModelLibrary object that combines the selected pre-trained model with the corresponding performance
- # evaluation functionality
- ml = model_lib.ModelLib(config)
-
- # Get the floating point model
- float_model = ml.get_model()
-
- # Evaluate the float model
- float_results, _ = ml.evaluate(float_model)
-
- # Select the target platform capabilities (https://github.com/sony/model_optimization/blob/main/model_compression_toolkit/target_platform_capabilities/README.md)
- target_platform_cap = quant.get_tpc(config[TARGET_PLATFORM_NAME], config[TARGET_PLATFORM_VERSION])
-
- # Run model compression toolkit
- quantized_model, quantization_info = quant.quantize(float_model,
- ml.get_representative_dataset,
- target_platform_cap,
- config)
-
- # Evaluate quantized model
- quant_results, dataset_info = ml.evaluate(quantized_model)
-
- return float_results, quant_results, quantization_info, dataset_info
-
-
-if __name__ == '__main__':
-
- # Set arguments and parameters
- args = argument_handler()
-
- # Set logger level
- logging.getLogger().setLevel(logging.INFO)
-
- # Create configuration dictionary
- config = dict(args._get_kwargs())
-
- if args.models_list_csv is None:
-
- # Run quantization flow and add results to the table
- float_acc, quant_acc, quant_info, dataset_info = quantization_flow(config)
-
- # Parse the results and print to screen
- res = parse_results(config, float_acc, quant_acc, quant_info, dataset_info)
- plot_results(res)
-
- else:
- models_list = read_models_list(args.models_list_csv)
- results_table = []
- for p in models_list:
-
- # Get next model and parameters from the list
- logging.info(f"Testing model: {p[MODEL_NAME]} from library: {p[MODEL_LIBRARY]}")
- config.update(p)
-
- # Run quantization flow and add results to the table
- float_acc, quant_acc, quant_info, dataset_info = quantization_flow(config)
-
- # Add results to the table
- res = parse_results(config, float_acc, quant_acc, quant_info, dataset_info)
- results_table.append(res)
-
- # Store results table
- write_results(config[OUTPUT_RESULTS_FILE], results_table, res.keys())
-
- # Print results to screen
- plot_results(results_table)
-
diff --git a/tutorials/quick_start/pytorch_fw/__init__.py b/tutorials/quick_start/pytorch_fw/__init__.py
deleted file mode 100644
index 2147ec284..000000000
--- a/tutorials/quick_start/pytorch_fw/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
diff --git a/tutorials/quick_start/pytorch_fw/quant.py b/tutorials/quick_start/pytorch_fw/quant.py
deleted file mode 100644
index 53a9520d0..000000000
--- a/tutorials/quick_start/pytorch_fw/quant.py
+++ /dev/null
@@ -1,149 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-import math
-from torch import nn, Tensor
-from torch.optim import Adam
-
-import tempfile
-
-import model_compression_toolkit as mct
-import logging
-from common.constants import NUM_REPRESENTATIVE_IMAGES, BATCH_SIZE, REPRESENTATIVE_DATASET_FOLDER, \
- TARGET_PLATFORM_NAME, TARGET_PLATFORM_VERSION
-
-from model_compression_toolkit.core import MixedPrecisionQuantizationConfig, CoreConfig, ResourceUtilization
-from model_compression_toolkit.target_platform_capabilities.target_platform import TargetPlatformCapabilities
-from tutorials.quick_start.common.constants import BYTES_TO_FP32, MP_WEIGHTS_COMPRESSION
-from tutorials.quick_start.common.results import QuantInfo
-from tutorials.quick_start.common.tpc_info import get_tpc_info
-
-
-def get_tpc(target_platform_name: str, target_platform_version: str) -> TargetPlatformCapabilities:
- """
- Returns the target platform capabilities according to the given platform name and version.
-
- Args:
- target_platform_name: Name of the target platform
- target_platform_version: Version of the target platform
-
- Returns:
- The target platform capabilities.
-
- """
- return mct.get_target_platform_capabilities('pytorch', target_platform_name, target_platform_version)
-
-
-def get_target_resource_utilization(model, weights_compression, representative_data_gen, core_config, tpc):
- """
- Calculates the model's required size according to the given weights compression rate, to provide as a constraint for mixed precision search.
-
- Args:
- model: The model to calculate the required size.
- weights_compression: The required weights compression ratio.
- representative_data_gen: Callable function to generate the representative dataset.
- core_config (CoreConfig): CoreConfig containing parameters for quantization and mixed precision.
- tpc (TargetPlatformCapabilities): TargetPlatformCapabilities to optimize the PyTorch model according to.
-
- Returns:
- A ResourceUtilization object computed from MCT and contains info about the target model size.
-
- """
- ru_data = mct.core.pytorch_resource_utilization_data(model, representative_data_gen, core_config=core_config,
- target_platform_capabilities=tpc)
- weights_ru = BYTES_TO_FP32 * ru_data.weights_memory / weights_compression # (4 bytes for fp32) * weights memory(in Bytes) / compression rate
- return ResourceUtilization(weights_memory=weights_ru)
-
-
-def quantize(model: nn.Module,
- get_representative_dataset: callable,
- tpc: TargetPlatformCapabilities,
- args: dict):
- """
- Returns a quantized model and a quantization info from MCT for the given PyTorch floating-point model.
-
- Args:
- model: PyTorch floating-point model to be quantized.
- get_representative_dataset: Callable function to generate the representative dataset for quantization.
- tpc: Target platform capabilities.
- args: Dictionary containing the necessary configurations for quantization.
-
- Returns:
- Tuple containing the quantized model and quantization info.
-
- """
-
- # PTQ - general configurations
- n_iter = math.ceil(int(args[NUM_REPRESENTATIVE_IMAGES]) // int(args[BATCH_SIZE])) # Number of batches
- logging.info(f"Running MCT... number of representative images: {args[REPRESENTATIVE_DATASET_FOLDER]}, number of calibration iters: {n_iter}")
-
- representative_data_gen = get_representative_dataset(
- representative_dataset_folder=args[REPRESENTATIVE_DATASET_FOLDER],
- n_iter=n_iter,
- batch_size=int(args[BATCH_SIZE])
- )
-
- # Mixed-precision configurations
- mp_wcr = args.get(MP_WEIGHTS_COMPRESSION, None)
- if mp_wcr:
- mp_conf = MixedPrecisionQuantizationConfig()
- core_conf = CoreConfig(quantization_config=mct.core.QuantizationConfig(
- shift_negative_activation_correction=True),
- mixed_precision_config=mp_conf)
- target_resource_utilization = get_target_resource_utilization(model, mp_wcr, representative_data_gen, core_conf, tpc)
- else:
- core_conf = CoreConfig(quantization_config=mct.core.QuantizationConfig(
- shift_negative_activation_correction=True))
- target_resource_utilization = None
-
- # Quantize model
- if args.get('gptq', False):
-
- workflow = 'GPTQ'
- n_epochs = args.get('gptq_num_calibration_iter') // n_iter
- logging.info(
- f"MCT Gradient-based Post Training Quantization is enabled. Number of epochs: {n_epochs}")
-
- gptq_conf = mct.gptq.get_pytorch_gptq_config(n_epochs=n_epochs, optimizer=Adam([Tensor([])], lr=args['gptq_lr']))
-
- quantized_model, quantization_info = \
- mct.gptq.pytorch_gradient_post_training_quantization(model,
- representative_data_gen=representative_data_gen,
- target_resource_utilization=target_resource_utilization,
- core_config=core_conf,
- gptq_config=gptq_conf,
- gptq_representative_data_gen=representative_data_gen,
- target_platform_capabilities=tpc)
-
-
- else:
- workflow = 'PTQ'
- quantized_model, quantization_info = \
- mct.ptq.pytorch_post_training_quantization(model,
- representative_data_gen=representative_data_gen,
- core_config=core_conf,
- target_platform_capabilities=tpc)
-
-
- # Export quantized model to ONNX
- if args.get('export_model',False):
- _, onnx_file_path = tempfile.mkstemp('.onnx') # Path of exported model
- mct.exporter.pytorch_export_model(model=quantized_model,
- save_model_path=onnx_file_path,
- repr_dataset=representative_data_gen)
-
- return quantized_model, QuantInfo(user_info=quantization_info,
- tpc_info=get_tpc_info(tpc=tpc),
- quantization_workflow=workflow,
- mp_weights_compression=mp_wcr)
\ No newline at end of file
diff --git a/tutorials/quick_start/pytorch_fw/timm_lib/LICENSE b/tutorials/quick_start/pytorch_fw/timm_lib/LICENSE
deleted file mode 100644
index b4e9438bd..000000000
--- a/tutorials/quick_start/pytorch_fw/timm_lib/LICENSE
+++ /dev/null
@@ -1,201 +0,0 @@
- Apache License
- Version 2.0, January 2004
- http://www.apache.org/licenses/
-
- TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
-
- 1. Definitions.
-
- "License" shall mean the terms and conditions for use, reproduction,
- and distribution as defined by Sections 1 through 9 of this document.
-
- "Licensor" shall mean the copyright owner or entity authorized by
- the copyright owner that is granting the License.
-
- "Legal Entity" shall mean the union of the acting entity and all
- other entities that control, are controlled by, or are under common
- control with that entity. For the purposes of this definition,
- "control" means (i) the power, direct or indirect, to cause the
- direction or management of such entity, whether by contract or
- otherwise, or (ii) ownership of fifty percent (50%) or more of the
- outstanding shares, or (iii) beneficial ownership of such entity.
-
- "You" (or "Your") shall mean an individual or Legal Entity
- exercising permissions granted by this License.
-
- "Source" form shall mean the preferred form for making modifications,
- including but not limited to software source code, documentation
- source, and configuration files.
-
- "Object" form shall mean any form resulting from mechanical
- transformation or translation of a Source form, including but
- not limited to compiled object code, generated documentation,
- and conversions to other media types.
-
- "Work" shall mean the work of authorship, whether in Source or
- Object form, made available under the License, as indicated by a
- copyright notice that is included in or attached to the work
- (an example is provided in the Appendix below).
-
- "Derivative Works" shall mean any work, whether in Source or Object
- form, that is based on (or derived from) the Work and for which the
- editorial revisions, annotations, elaborations, or other modifications
- represent, as a whole, an original work of authorship. For the purposes
- of this License, Derivative Works shall not include works that remain
- separable from, or merely link (or bind by name) to the interfaces of,
- the Work and Derivative Works thereof.
-
- "Contribution" shall mean any work of authorship, including
- the original version of the Work and any modifications or additions
- to that Work or Derivative Works thereof, that is intentionally
- submitted to Licensor for inclusion in the Work by the copyright owner
- or by an individual or Legal Entity authorized to submit on behalf of
- the copyright owner. For the purposes of this definition, "submitted"
- means any form of electronic, verbal, or written communication sent
- to the Licensor or its representatives, including but not limited to
- communication on electronic mailing lists, source code control systems,
- and issue tracking systems that are managed by, or on behalf of, the
- Licensor for the purpose of discussing and improving the Work, but
- excluding communication that is conspicuously marked or otherwise
- designated in writing by the copyright owner as "Not a Contribution."
-
- "Contributor" shall mean Licensor and any individual or Legal Entity
- on behalf of whom a Contribution has been received by Licensor and
- subsequently incorporated within the Work.
-
- 2. Grant of Copyright License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- copyright license to reproduce, prepare Derivative Works of,
- publicly display, publicly perform, sublicense, and distribute the
- Work and such Derivative Works in Source or Object form.
-
- 3. Grant of Patent License. Subject to the terms and conditions of
- this License, each Contributor hereby grants to You a perpetual,
- worldwide, non-exclusive, no-charge, royalty-free, irrevocable
- (except as stated in this section) patent license to make, have made,
- use, offer to sell, sell, import, and otherwise transfer the Work,
- where such license applies only to those patent claims licensable
- by such Contributor that are necessarily infringed by their
- Contribution(s) alone or by combination of their Contribution(s)
- with the Work to which such Contribution(s) was submitted. If You
- institute patent litigation against any entity (including a
- cross-claim or counterclaim in a lawsuit) alleging that the Work
- or a Contribution incorporated within the Work constitutes direct
- or contributory patent infringement, then any patent licenses
- granted to You under this License for that Work shall terminate
- as of the date such litigation is filed.
-
- 4. Redistribution. You may reproduce and distribute copies of the
- Work or Derivative Works thereof in any medium, with or without
- modifications, and in Source or Object form, provided that You
- meet the following conditions:
-
- (a) You must give any other recipients of the Work or
- Derivative Works a copy of this License; and
-
- (b) You must cause any modified files to carry prominent notices
- stating that You changed the files; and
-
- (c) You must retain, in the Source form of any Derivative Works
- that You distribute, all copyright, patent, trademark, and
- attribution notices from the Source form of the Work,
- excluding those notices that do not pertain to any part of
- the Derivative Works; and
-
- (d) If the Work includes a "NOTICE" text file as part of its
- distribution, then any Derivative Works that You distribute must
- include a readable copy of the attribution notices contained
- within such NOTICE file, excluding those notices that do not
- pertain to any part of the Derivative Works, in at least one
- of the following places: within a NOTICE text file distributed
- as part of the Derivative Works; within the Source form or
- documentation, if provided along with the Derivative Works; or,
- within a display generated by the Derivative Works, if and
- wherever such third-party notices normally appear. The contents
- of the NOTICE file are for informational purposes only and
- do not modify the License. You may add Your own attribution
- notices within Derivative Works that You distribute, alongside
- or as an addendum to the NOTICE text from the Work, provided
- that such additional attribution notices cannot be construed
- as modifying the License.
-
- You may add Your own copyright statement to Your modifications and
- may provide additional or different license terms and conditions
- for use, reproduction, or distribution of Your modifications, or
- for any such Derivative Works as a whole, provided Your use,
- reproduction, and distribution of the Work otherwise complies with
- the conditions stated in this License.
-
- 5. Submission of Contributions. Unless You explicitly state otherwise,
- any Contribution intentionally submitted for inclusion in the Work
- by You to the Licensor shall be under the terms and conditions of
- this License, without any additional terms or conditions.
- Notwithstanding the above, nothing herein shall supersede or modify
- the terms of any separate license agreement you may have executed
- with Licensor regarding such Contributions.
-
- 6. Trademarks. This License does not grant permission to use the trade
- names, trademarks, service marks, or product names of the Licensor,
- except as required for reasonable and customary use in describing the
- origin of the Work and reproducing the content of the NOTICE file.
-
- 7. Disclaimer of Warranty. Unless required by applicable law or
- agreed to in writing, Licensor provides the Work (and each
- Contributor provides its Contributions) on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
- implied, including, without limitation, any warranties or conditions
- of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
- PARTICULAR PURPOSE. You are solely responsible for determining the
- appropriateness of using or redistributing the Work and assume any
- risks associated with Your exercise of permissions under this License.
-
- 8. Limitation of Liability. In no event and under no legal theory,
- whether in tort (including negligence), contract, or otherwise,
- unless required by applicable law (such as deliberate and grossly
- negligent acts) or agreed to in writing, shall any Contributor be
- liable to You for damages, including any direct, indirect, special,
- incidental, or consequential damages of any character arising as a
- result of this License or out of the use or inability to use the
- Work (including but not limited to damages for loss of goodwill,
- work stoppage, computer failure or malfunction, or any and all
- other commercial damages or losses), even if such Contributor
- has been advised of the possibility of such damages.
-
- 9. Accepting Warranty or Additional Liability. While redistributing
- the Work or Derivative Works thereof, You may choose to offer,
- and charge a fee for, acceptance of support, warranty, indemnity,
- or other liability obligations and/or rights consistent with this
- License. However, in accepting such obligations, You may act only
- on Your own behalf and on Your sole responsibility, not on behalf
- of any other Contributor, and only if You agree to indemnify,
- defend, and hold each Contributor harmless for any liability
- incurred by, or claims asserted against, such Contributor by reason
- of your accepting any such warranty or additional liability.
-
- END OF TERMS AND CONDITIONS
-
- APPENDIX: How to apply the Apache License to your work.
-
- To apply the Apache License to your work, attach the following
- boilerplate notice, with the fields enclosed by brackets "{}"
- replaced with your own identifying information. (Don't include
- the brackets!) The text should be enclosed in the appropriate
- comment syntax for the file format. We also recommend that a
- file or class name and description of purpose be included on the
- same "printed page" as the copyright notice for easier
- identification within third-party archives.
-
- Copyright 2019 Ross Wightman
-
- Licensed under the Apache License, Version 2.0 (the "License");
- you may not use this file except in compliance with the License.
- You may obtain a copy of the License at
-
- http://www.apache.org/licenses/LICENSE-2.0
-
- Unless required by applicable law or agreed to in writing, software
- distributed under the License is distributed on an "AS IS" BASIS,
- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- See the License for the specific language governing permissions and
- limitations under the License.
\ No newline at end of file
diff --git a/tutorials/quick_start/pytorch_fw/timm_lib/__init__.py b/tutorials/quick_start/pytorch_fw/timm_lib/__init__.py
deleted file mode 100644
index 2147ec284..000000000
--- a/tutorials/quick_start/pytorch_fw/timm_lib/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
diff --git a/tutorials/quick_start/pytorch_fw/timm_lib/model_lib.py b/tutorials/quick_start/pytorch_fw/timm_lib/model_lib.py
deleted file mode 100644
index a80f1bd4a..000000000
--- a/tutorials/quick_start/pytorch_fw/timm_lib/model_lib.py
+++ /dev/null
@@ -1,105 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-import timm
-from timm.data import create_dataset, create_loader, resolve_data_config
-
-from tutorials.quick_start.common.model_lib import BaseModelLib
-from tutorials.quick_start.pytorch_fw.utils import classification_eval, get_representative_dataset
-from tutorials.quick_start.common.constants import MODEL_NAME, BATCH_SIZE, VALIDATION_SET_LIMIT, \
- VALIDATION_DATASET_FOLDER, IMAGENET_DATASET
-from tutorials.quick_start.common.results import DatasetInfo
-
-
-class ModelLib(BaseModelLib):
- """
- A class representing timm model library (https://github.com/huggingface/pytorch-image-models/tree/main).
- """
-
- def __init__(self, args):
- """
- Init the ModelLib with user arguments
- Args:
- args (dict): user arguments
- """
- avialable_models = timm.list_models('')
- model_name = args[MODEL_NAME]
- if model_name in avialable_models:
- self.model = timm.create_model(args[MODEL_NAME], pretrained=True)
- self.data_config = resolve_data_config([], model=self.model) # include the pre-processing
- self.dataset_name = IMAGENET_DATASET
- super().__init__(args)
- else:
- raise Exception(f'Unknown timm model name {model_name}, Available models : {avialable_models}')
-
- def get_model(self):
- """
- Returns the model instance.
- """
- return self.model
-
- def get_representative_dataset(self, representative_dataset_folder, n_iter, batch_size):
- """
- Create a representative dataset generator
- Args:
- representative_dataset_folder: Dataset location folder, in the format: representative_dataset_folder//
- n_iter: number batches to run in the generator
- batch_size: number of images in each batch
-
- Returns:
- A generator for the representative dataset, as the MCT expects
-
- """
- train_dataset = create_dataset(name='', root=representative_dataset_folder,
- is_training=False, batch_size=batch_size)
- dl = create_loader(
- train_dataset,
- input_size=self.data_config['input_size'],
- batch_size=batch_size,
- interpolation=self.data_config['interpolation'],
- mean=self.data_config['mean'],
- std=self.data_config['std'],
- crop_pct=self.data_config['crop_pct'])
- return get_representative_dataset(dl, n_iter)
-
- def evaluate(self, model):
- """
- Evaluates the model's performance.
-
- Args:
- model: The model to evaluate.
-
- Returns:
- acc: The accuracy of the model.
- DatasetInfo: Information about the dataset used.
- """
- batch_size = int(self.args[BATCH_SIZE])
- validation_dataset_folder = self.args[VALIDATION_DATASET_FOLDER]
- val_dataset = create_dataset(name='', root=validation_dataset_folder, is_training=False,
- batch_size=batch_size)
- testloader = create_loader(
- val_dataset,
- input_size=self.data_config['input_size'],
- batch_size=batch_size,
- interpolation=self.data_config['interpolation'],
- mean=self.data_config['mean'],
- std=self.data_config['std'],
- crop_pct=self.data_config['crop_pct'])
-
- acc, total = classification_eval(model, testloader, self.args[VALIDATION_SET_LIMIT])
- dataset_info = DatasetInfo(self.dataset_name, total)
- return acc, dataset_info
-
-
-
diff --git a/tutorials/quick_start/pytorch_fw/torchvision_lib/LICENSE b/tutorials/quick_start/pytorch_fw/torchvision_lib/LICENSE
deleted file mode 100644
index a95ba5204..000000000
--- a/tutorials/quick_start/pytorch_fw/torchvision_lib/LICENSE
+++ /dev/null
@@ -1,29 +0,0 @@
-BSD 3-Clause License
-
-Copyright (c) Soumith Chintala 2016,
-All rights reserved.
-
-Redistribution and use in source and binary forms, with or without
-modification, are permitted provided that the following conditions are met:
-
-* Redistributions of source code must retain the above copyright notice, this
- list of conditions and the following disclaimer.
-
-* Redistributions in binary form must reproduce the above copyright notice,
- this list of conditions and the following disclaimer in the documentation
- and/or other materials provided with the distribution.
-
-* Neither the name of the copyright holder nor the names of its
- contributors may be used to endorse or promote products derived from
- this software without specific prior written permission.
-
-THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
-AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
-IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
-DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
-FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
-DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
-SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
-CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
-OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
-OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
\ No newline at end of file
diff --git a/tutorials/quick_start/pytorch_fw/torchvision_lib/__init__.py b/tutorials/quick_start/pytorch_fw/torchvision_lib/__init__.py
deleted file mode 100644
index 2147ec284..000000000
--- a/tutorials/quick_start/pytorch_fw/torchvision_lib/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
diff --git a/tutorials/quick_start/pytorch_fw/torchvision_lib/model_lib.py b/tutorials/quick_start/pytorch_fw/torchvision_lib/model_lib.py
deleted file mode 100644
index 85b623b33..000000000
--- a/tutorials/quick_start/pytorch_fw/torchvision_lib/model_lib.py
+++ /dev/null
@@ -1,105 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-import torch
-import torchvision
-from torchvision.models import list_models, get_model, get_model_weights, get_weight
-from torch.utils.data import Subset
-
-from tutorials.quick_start.common.model_lib import BaseModelLib
-from tutorials.quick_start.pytorch_fw.utils import classification_eval, get_representative_dataset
-from tutorials.quick_start.common.constants import MODEL_NAME, BATCH_SIZE, VALIDATION_SET_LIMIT, \
- VALIDATION_DATASET_FOLDER, IMAGENET_DATASET
-
-from tutorials.quick_start.common.results import DatasetInfo
-
-
-class ModelLib(BaseModelLib):
- """
- A class representing torchvision model library (https://pytorch.org/vision/stable/models.html)
- """
-
- @staticmethod
- def get_torchvision_model(model_name):
- """
- Retrieves a torchvision model by name.
- """
- all_models = list_models() # List all torchvision models
- if model_name in all_models:
- return get_model(model_name, weights="DEFAULT") # Best available weights ("DEFAULT")
- else:
- raise Exception(f'Unknown torchvision model name {model_name}, Please check available models in https://pytorch.org/vision/stable/models.html')
-
- @staticmethod
- def get_torchvision_weights(model_name):
- """
- Returns the best available weights for the specified model.
- """
- return get_model_weights(model_name).DEFAULT
-
- def __init__(self, args):
- """
- Init the ModelLib with user arguments
- Args:
- args (dict): user arguments
- """
- self.model = self.get_torchvision_model(args[MODEL_NAME])
- self.preprocess = self.get_torchvision_weights(args[MODEL_NAME]).transforms()
- self.dataset_name = IMAGENET_DATASET
- super().__init__(args)
-
- def get_model(self):
- """
- Returns the model instance.
- """
- return self.model
-
- def get_representative_dataset(self, representative_dataset_folder, n_iter, batch_size):
- """
- Create a representative dataset generator
- Args:
- representative_dataset_folder: Dataset location folder, in the format: representative_dataset_folder//
- n_iter: number batches to run in the generator
- batch_size: number of images in each batch
-
- Returns:
- A generator for the representative dataset, as the MCT expects
-
- """
- ds = torchvision.datasets.ImageFolder(representative_dataset_folder, transform=self.preprocess)
- dl = torch.utils.data.DataLoader(ds, batch_size, shuffle=True)
- return get_representative_dataset(dl, n_iter)
-
- def evaluate(self, model):
- """
- Evaluates the model's performance.
-
- Args:
- model: The model to evaluate.
-
- Returns:
- acc: The accuracy of the model.
- DatasetInfo: Information about the dataset used.
- """
- batch_size = int(self.args[BATCH_SIZE])
- validation_dataset_folder = self.args[VALIDATION_DATASET_FOLDER]
- testset = torchvision.datasets.ImageFolder(validation_dataset_folder, transform=self.preprocess)
- testloader = torch.utils.data.DataLoader(testset,
- batch_size=batch_size,
- shuffle=False)
- acc, total = classification_eval(model, testloader, self.args[VALIDATION_SET_LIMIT])
- dataset_info = DatasetInfo(self.dataset_name, total)
- return acc, dataset_info
-
-
diff --git a/tutorials/quick_start/pytorch_fw/ultralytics_lib/LICENSE b/tutorials/quick_start/pytorch_fw/ultralytics_lib/LICENSE
deleted file mode 100644
index bae94e189..000000000
--- a/tutorials/quick_start/pytorch_fw/ultralytics_lib/LICENSE
+++ /dev/null
@@ -1,661 +0,0 @@
- GNU AFFERO GENERAL PUBLIC LICENSE
- Version 3, 19 November 2007
-
- Copyright (C) 2007 Free Software Foundation, Inc.
- Everyone is permitted to copy and distribute verbatim copies
- of this license document, but changing it is not allowed.
-
- Preamble
-
- The GNU Affero General Public License is a free, copyleft license for
-software and other kinds of works, specifically designed to ensure
-cooperation with the community in the case of network server software.
-
- The licenses for most software and other practical works are designed
-to take away your freedom to share and change the works. By contrast,
-our General Public Licenses are intended to guarantee your freedom to
-share and change all versions of a program--to make sure it remains free
-software for all its users.
-
- When we speak of free software, we are referring to freedom, not
-price. Our General Public Licenses are designed to make sure that you
-have the freedom to distribute copies of free software (and charge for
-them if you wish), that you receive source code or can get it if you
-want it, that you can change the software or use pieces of it in new
-free programs, and that you know you can do these things.
-
- Developers that use our General Public Licenses protect your rights
-with two steps: (1) assert copyright on the software, and (2) offer
-you this License which gives you legal permission to copy, distribute
-and/or modify the software.
-
- A secondary benefit of defending all users' freedom is that
-improvements made in alternate versions of the program, if they
-receive widespread use, become available for other developers to
-incorporate. Many developers of free software are heartened and
-encouraged by the resulting cooperation. However, in the case of
-software used on network servers, this result may fail to come about.
-The GNU General Public License permits making a modified version and
-letting the public access it on a server without ever releasing its
-source code to the public.
-
- The GNU Affero General Public License is designed specifically to
-ensure that, in such cases, the modified source code becomes available
-to the community. It requires the operator of a network server to
-provide the source code of the modified version running there to the
-users of that server. Therefore, public use of a modified version, on
-a publicly accessible server, gives the public access to the source
-code of the modified version.
-
- An older license, called the Affero General Public License and
-published by Affero, was designed to accomplish similar goals. This is
-a different license, not a version of the Affero GPL, but Affero has
-released a new version of the Affero GPL which permits relicensing under
-this license.
-
- The precise terms and conditions for copying, distribution and
-modification follow.
-
- TERMS AND CONDITIONS
-
- 0. Definitions.
-
- "This License" refers to version 3 of the GNU Affero General Public License.
-
- "Copyright" also means copyright-like laws that apply to other kinds of
-works, such as semiconductor masks.
-
- "The Program" refers to any copyrightable work licensed under this
-License. Each licensee is addressed as "you". "Licensees" and
-"recipients" may be individuals or organizations.
-
- To "modify" a work means to copy from or adapt all or part of the work
-in a fashion requiring copyright permission, other than the making of an
-exact copy. The resulting work is called a "modified version" of the
-earlier work or a work "based on" the earlier work.
-
- A "covered work" means either the unmodified Program or a work based
-on the Program.
-
- To "propagate" a work means to do anything with it that, without
-permission, would make you directly or secondarily liable for
-infringement under applicable copyright law, except executing it on a
-computer or modifying a private copy. Propagation includes copying,
-distribution (with or without modification), making available to the
-public, and in some countries other activities as well.
-
- To "convey" a work means any kind of propagation that enables other
-parties to make or receive copies. Mere interaction with a user through
-a computer network, with no transfer of a copy, is not conveying.
-
- An interactive user interface displays "Appropriate Legal Notices"
-to the extent that it includes a convenient and prominently visible
-feature that (1) displays an appropriate copyright notice, and (2)
-tells the user that there is no warranty for the work (except to the
-extent that warranties are provided), that licensees may convey the
-work under this License, and how to view a copy of this License. If
-the interface presents a list of user commands or options, such as a
-menu, a prominent item in the list meets this criterion.
-
- 1. Source Code.
-
- The "source code" for a work means the preferred form of the work
-for making modifications to it. "Object code" means any non-source
-form of a work.
-
- A "Standard Interface" means an interface that either is an official
-standard defined by a recognized standards body, or, in the case of
-interfaces specified for a particular programming language, one that
-is widely used among developers working in that language.
-
- The "System Libraries" of an executable work include anything, other
-than the work as a whole, that (a) is included in the normal form of
-packaging a Major Component, but which is not part of that Major
-Component, and (b) serves only to enable use of the work with that
-Major Component, or to implement a Standard Interface for which an
-implementation is available to the public in source code form. A
-"Major Component", in this context, means a major essential component
-(kernel, window system, and so on) of the specific operating system
-(if any) on which the executable work runs, or a compiler used to
-produce the work, or an object code interpreter used to run it.
-
- The "Corresponding Source" for a work in object code form means all
-the source code needed to generate, install, and (for an executable
-work) run the object code and to modify the work, including scripts to
-control those activities. However, it does not include the work's
-System Libraries, or general-purpose tools or generally available free
-programs which are used unmodified in performing those activities but
-which are not part of the work. For example, Corresponding Source
-includes interface definition files associated with source files for
-the work, and the source code for shared libraries and dynamically
-linked subprograms that the work is specifically designed to require,
-such as by intimate data communication or control flow between those
-subprograms and other parts of the work.
-
- The Corresponding Source need not include anything that users
-can regenerate automatically from other parts of the Corresponding
-Source.
-
- The Corresponding Source for a work in source code form is that
-same work.
-
- 2. Basic Permissions.
-
- All rights granted under this License are granted for the term of
-copyright on the Program, and are irrevocable provided the stated
-conditions are met. This License explicitly affirms your unlimited
-permission to run the unmodified Program. The output from running a
-covered work is covered by this License only if the output, given its
-content, constitutes a covered work. This License acknowledges your
-rights of fair use or other equivalent, as provided by copyright law.
-
- You may make, run and propagate covered works that you do not
-convey, without conditions so long as your license otherwise remains
-in force. You may convey covered works to others for the sole purpose
-of having them make modifications exclusively for you, or provide you
-with facilities for running those works, provided that you comply with
-the terms of this License in conveying all material for which you do
-not control copyright. Those thus making or running the covered works
-for you must do so exclusively on your behalf, under your direction
-and control, on terms that prohibit them from making any copies of
-your copyrighted material outside their relationship with you.
-
- Conveying under any other circumstances is permitted solely under
-the conditions stated below. Sublicensing is not allowed; section 10
-makes it unnecessary.
-
- 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
-
- No covered work shall be deemed part of an effective technological
-measure under any applicable law fulfilling obligations under article
-11 of the WIPO copyright treaty adopted on 20 December 1996, or
-similar laws prohibiting or restricting circumvention of such
-measures.
-
- When you convey a covered work, you waive any legal power to forbid
-circumvention of technological measures to the extent such circumvention
-is effected by exercising rights under this License with respect to
-the covered work, and you disclaim any intention to limit operation or
-modification of the work as a means of enforcing, against the work's
-users, your or third parties' legal rights to forbid circumvention of
-technological measures.
-
- 4. Conveying Verbatim Copies.
-
- You may convey verbatim copies of the Program's source code as you
-receive it, in any medium, provided that you conspicuously and
-appropriately publish on each copy an appropriate copyright notice;
-keep intact all notices stating that this License and any
-non-permissive terms added in accord with section 7 apply to the code;
-keep intact all notices of the absence of any warranty; and give all
-recipients a copy of this License along with the Program.
-
- You may charge any price or no price for each copy that you convey,
-and you may offer support or warranty protection for a fee.
-
- 5. Conveying Modified Source Versions.
-
- You may convey a work based on the Program, or the modifications to
-produce it from the Program, in the form of source code under the
-terms of section 4, provided that you also meet all of these conditions:
-
- a) The work must carry prominent notices stating that you modified
- it, and giving a relevant date.
-
- b) The work must carry prominent notices stating that it is
- released under this License and any conditions added under section
- 7. This requirement modifies the requirement in section 4 to
- "keep intact all notices".
-
- c) You must license the entire work, as a whole, under this
- License to anyone who comes into possession of a copy. This
- License will therefore apply, along with any applicable section 7
- additional terms, to the whole of the work, and all its parts,
- regardless of how they are packaged. This License gives no
- permission to license the work in any other way, but it does not
- invalidate such permission if you have separately received it.
-
- d) If the work has interactive user interfaces, each must display
- Appropriate Legal Notices; however, if the Program has interactive
- interfaces that do not display Appropriate Legal Notices, your
- work need not make them do so.
-
- A compilation of a covered work with other separate and independent
-works, which are not by their nature extensions of the covered work,
-and which are not combined with it such as to form a larger program,
-in or on a volume of a storage or distribution medium, is called an
-"aggregate" if the compilation and its resulting copyright are not
-used to limit the access or legal rights of the compilation's users
-beyond what the individual works permit. Inclusion of a covered work
-in an aggregate does not cause this License to apply to the other
-parts of the aggregate.
-
- 6. Conveying Non-Source Forms.
-
- You may convey a covered work in object code form under the terms
-of sections 4 and 5, provided that you also convey the
-machine-readable Corresponding Source under the terms of this License,
-in one of these ways:
-
- a) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by the
- Corresponding Source fixed on a durable physical medium
- customarily used for software interchange.
-
- b) Convey the object code in, or embodied in, a physical product
- (including a physical distribution medium), accompanied by a
- written offer, valid for at least three years and valid for as
- long as you offer spare parts or customer support for that product
- model, to give anyone who possesses the object code either (1) a
- copy of the Corresponding Source for all the software in the
- product that is covered by this License, on a durable physical
- medium customarily used for software interchange, for a price no
- more than your reasonable cost of physically performing this
- conveying of source, or (2) access to copy the
- Corresponding Source from a network server at no charge.
-
- c) Convey individual copies of the object code with a copy of the
- written offer to provide the Corresponding Source. This
- alternative is allowed only occasionally and noncommercially, and
- only if you received the object code with such an offer, in accord
- with subsection 6b.
-
- d) Convey the object code by offering access from a designated
- place (gratis or for a charge), and offer equivalent access to the
- Corresponding Source in the same way through the same place at no
- further charge. You need not require recipients to copy the
- Corresponding Source along with the object code. If the place to
- copy the object code is a network server, the Corresponding Source
- may be on a different server (operated by you or a third party)
- that supports equivalent copying facilities, provided you maintain
- clear directions next to the object code saying where to find the
- Corresponding Source. Regardless of what server hosts the
- Corresponding Source, you remain obligated to ensure that it is
- available for as long as needed to satisfy these requirements.
-
- e) Convey the object code using peer-to-peer transmission, provided
- you inform other peers where the object code and Corresponding
- Source of the work are being offered to the general public at no
- charge under subsection 6d.
-
- A separable portion of the object code, whose source code is excluded
-from the Corresponding Source as a System Library, need not be
-included in conveying the object code work.
-
- A "User Product" is either (1) a "consumer product", which means any
-tangible personal property which is normally used for personal, family,
-or household purposes, or (2) anything designed or sold for incorporation
-into a dwelling. In determining whether a product is a consumer product,
-doubtful cases shall be resolved in favor of coverage. For a particular
-product received by a particular user, "normally used" refers to a
-typical or common use of that class of product, regardless of the status
-of the particular user or of the way in which the particular user
-actually uses, or expects or is expected to use, the product. A product
-is a consumer product regardless of whether the product has substantial
-commercial, industrial or non-consumer uses, unless such uses represent
-the only significant mode of use of the product.
-
- "Installation Information" for a User Product means any methods,
-procedures, authorization keys, or other information required to install
-and execute modified versions of a covered work in that User Product from
-a modified version of its Corresponding Source. The information must
-suffice to ensure that the continued functioning of the modified object
-code is in no case prevented or interfered with solely because
-modification has been made.
-
- If you convey an object code work under this section in, or with, or
-specifically for use in, a User Product, and the conveying occurs as
-part of a transaction in which the right of possession and use of the
-User Product is transferred to the recipient in perpetuity or for a
-fixed term (regardless of how the transaction is characterized), the
-Corresponding Source conveyed under this section must be accompanied
-by the Installation Information. But this requirement does not apply
-if neither you nor any third party retains the ability to install
-modified object code on the User Product (for example, the work has
-been installed in ROM).
-
- The requirement to provide Installation Information does not include a
-requirement to continue to provide support service, warranty, or updates
-for a work that has been modified or installed by the recipient, or for
-the User Product in which it has been modified or installed. Access to a
-network may be denied when the modification itself materially and
-adversely affects the operation of the network or violates the rules and
-protocols for communication across the network.
-
- Corresponding Source conveyed, and Installation Information provided,
-in accord with this section must be in a format that is publicly
-documented (and with an implementation available to the public in
-source code form), and must require no special password or key for
-unpacking, reading or copying.
-
- 7. Additional Terms.
-
- "Additional permissions" are terms that supplement the terms of this
-License by making exceptions from one or more of its conditions.
-Additional permissions that are applicable to the entire Program shall
-be treated as though they were included in this License, to the extent
-that they are valid under applicable law. If additional permissions
-apply only to part of the Program, that part may be used separately
-under those permissions, but the entire Program remains governed by
-this License without regard to the additional permissions.
-
- When you convey a copy of a covered work, you may at your option
-remove any additional permissions from that copy, or from any part of
-it. (Additional permissions may be written to require their own
-removal in certain cases when you modify the work.) You may place
-additional permissions on material, added by you to a covered work,
-for which you have or can give appropriate copyright permission.
-
- Notwithstanding any other provision of this License, for material you
-add to a covered work, you may (if authorized by the copyright holders of
-that material) supplement the terms of this License with terms:
-
- a) Disclaiming warranty or limiting liability differently from the
- terms of sections 15 and 16 of this License; or
-
- b) Requiring preservation of specified reasonable legal notices or
- author attributions in that material or in the Appropriate Legal
- Notices displayed by works containing it; or
-
- c) Prohibiting misrepresentation of the origin of that material, or
- requiring that modified versions of such material be marked in
- reasonable ways as different from the original version; or
-
- d) Limiting the use for publicity purposes of names of licensors or
- authors of the material; or
-
- e) Declining to grant rights under trademark law for use of some
- trade names, trademarks, or service marks; or
-
- f) Requiring indemnification of licensors and authors of that
- material by anyone who conveys the material (or modified versions of
- it) with contractual assumptions of liability to the recipient, for
- any liability that these contractual assumptions directly impose on
- those licensors and authors.
-
- All other non-permissive additional terms are considered "further
-restrictions" within the meaning of section 10. If the Program as you
-received it, or any part of it, contains a notice stating that it is
-governed by this License along with a term that is a further
-restriction, you may remove that term. If a license document contains
-a further restriction but permits relicensing or conveying under this
-License, you may add to a covered work material governed by the terms
-of that license document, provided that the further restriction does
-not survive such relicensing or conveying.
-
- If you add terms to a covered work in accord with this section, you
-must place, in the relevant source files, a statement of the
-additional terms that apply to those files, or a notice indicating
-where to find the applicable terms.
-
- Additional terms, permissive or non-permissive, may be stated in the
-form of a separately written license, or stated as exceptions;
-the above requirements apply either way.
-
- 8. Termination.
-
- You may not propagate or modify a covered work except as expressly
-provided under this License. Any attempt otherwise to propagate or
-modify it is void, and will automatically terminate your rights under
-this License (including any patent licenses granted under the third
-paragraph of section 11).
-
- However, if you cease all violation of this License, then your
-license from a particular copyright holder is reinstated (a)
-provisionally, unless and until the copyright holder explicitly and
-finally terminates your license, and (b) permanently, if the copyright
-holder fails to notify you of the violation by some reasonable means
-prior to 60 days after the cessation.
-
- Moreover, your license from a particular copyright holder is
-reinstated permanently if the copyright holder notifies you of the
-violation by some reasonable means, this is the first time you have
-received notice of violation of this License (for any work) from that
-copyright holder, and you cure the violation prior to 30 days after
-your receipt of the notice.
-
- Termination of your rights under this section does not terminate the
-licenses of parties who have received copies or rights from you under
-this License. If your rights have been terminated and not permanently
-reinstated, you do not qualify to receive new licenses for the same
-material under section 10.
-
- 9. Acceptance Not Required for Having Copies.
-
- You are not required to accept this License in order to receive or
-run a copy of the Program. Ancillary propagation of a covered work
-occurring solely as a consequence of using peer-to-peer transmission
-to receive a copy likewise does not require acceptance. However,
-nothing other than this License grants you permission to propagate or
-modify any covered work. These actions infringe copyright if you do
-not accept this License. Therefore, by modifying or propagating a
-covered work, you indicate your acceptance of this License to do so.
-
- 10. Automatic Licensing of Downstream Recipients.
-
- Each time you convey a covered work, the recipient automatically
-receives a license from the original licensors, to run, modify and
-propagate that work, subject to this License. You are not responsible
-for enforcing compliance by third parties with this License.
-
- An "entity transaction" is a transaction transferring control of an
-organization, or substantially all assets of one, or subdividing an
-organization, or merging organizations. If propagation of a covered
-work results from an entity transaction, each party to that
-transaction who receives a copy of the work also receives whatever
-licenses to the work the party's predecessor in interest had or could
-give under the previous paragraph, plus a right to possession of the
-Corresponding Source of the work from the predecessor in interest, if
-the predecessor has it or can get it with reasonable efforts.
-
- You may not impose any further restrictions on the exercise of the
-rights granted or affirmed under this License. For example, you may
-not impose a license fee, royalty, or other charge for exercise of
-rights granted under this License, and you may not initiate litigation
-(including a cross-claim or counterclaim in a lawsuit) alleging that
-any patent claim is infringed by making, using, selling, offering for
-sale, or importing the Program or any portion of it.
-
- 11. Patents.
-
- A "contributor" is a copyright holder who authorizes use under this
-License of the Program or a work on which the Program is based. The
-work thus licensed is called the contributor's "contributor version".
-
- A contributor's "essential patent claims" are all patent claims
-owned or controlled by the contributor, whether already acquired or
-hereafter acquired, that would be infringed by some manner, permitted
-by this License, of making, using, or selling its contributor version,
-but do not include claims that would be infringed only as a
-consequence of further modification of the contributor version. For
-purposes of this definition, "control" includes the right to grant
-patent sublicenses in a manner consistent with the requirements of
-this License.
-
- Each contributor grants you a non-exclusive, worldwide, royalty-free
-patent license under the contributor's essential patent claims, to
-make, use, sell, offer for sale, import and otherwise run, modify and
-propagate the contents of its contributor version.
-
- In the following three paragraphs, a "patent license" is any express
-agreement or commitment, however denominated, not to enforce a patent
-(such as an express permission to practice a patent or covenant not to
-sue for patent infringement). To "grant" such a patent license to a
-party means to make such an agreement or commitment not to enforce a
-patent against the party.
-
- If you convey a covered work, knowingly relying on a patent license,
-and the Corresponding Source of the work is not available for anyone
-to copy, free of charge and under the terms of this License, through a
-publicly available network server or other readily accessible means,
-then you must either (1) cause the Corresponding Source to be so
-available, or (2) arrange to deprive yourself of the benefit of the
-patent license for this particular work, or (3) arrange, in a manner
-consistent with the requirements of this License, to extend the patent
-license to downstream recipients. "Knowingly relying" means you have
-actual knowledge that, but for the patent license, your conveying the
-covered work in a country, or your recipient's use of the covered work
-in a country, would infringe one or more identifiable patents in that
-country that you have reason to believe are valid.
-
- If, pursuant to or in connection with a single transaction or
-arrangement, you convey, or propagate by procuring conveyance of, a
-covered work, and grant a patent license to some of the parties
-receiving the covered work authorizing them to use, propagate, modify
-or convey a specific copy of the covered work, then the patent license
-you grant is automatically extended to all recipients of the covered
-work and works based on it.
-
- A patent license is "discriminatory" if it does not include within
-the scope of its coverage, prohibits the exercise of, or is
-conditioned on the non-exercise of one or more of the rights that are
-specifically granted under this License. You may not convey a covered
-work if you are a party to an arrangement with a third party that is
-in the business of distributing software, under which you make payment
-to the third party based on the extent of your activity of conveying
-the work, and under which the third party grants, to any of the
-parties who would receive the covered work from you, a discriminatory
-patent license (a) in connection with copies of the covered work
-conveyed by you (or copies made from those copies), or (b) primarily
-for and in connection with specific products or compilations that
-contain the covered work, unless you entered into that arrangement,
-or that patent license was granted, prior to 28 March 2007.
-
- Nothing in this License shall be construed as excluding or limiting
-any implied license or other defenses to infringement that may
-otherwise be available to you under applicable patent law.
-
- 12. No Surrender of Others' Freedom.
-
- If conditions are imposed on you (whether by court order, agreement or
-otherwise) that contradict the conditions of this License, they do not
-excuse you from the conditions of this License. If you cannot convey a
-covered work so as to satisfy simultaneously your obligations under this
-License and any other pertinent obligations, then as a consequence you may
-not convey it at all. For example, if you agree to terms that obligate you
-to collect a royalty for further conveying from those to whom you convey
-the Program, the only way you could satisfy both those terms and this
-License would be to refrain entirely from conveying the Program.
-
- 13. Remote Network Interaction; Use with the GNU General Public License.
-
- Notwithstanding any other provision of this License, if you modify the
-Program, your modified version must prominently offer all users
-interacting with it remotely through a computer network (if your version
-supports such interaction) an opportunity to receive the Corresponding
-Source of your version by providing access to the Corresponding Source
-from a network server at no charge, through some standard or customary
-means of facilitating copying of software. This Corresponding Source
-shall include the Corresponding Source for any work covered by version 3
-of the GNU General Public License that is incorporated pursuant to the
-following paragraph.
-
- Notwithstanding any other provision of this License, you have
-permission to link or combine any covered work with a work licensed
-under version 3 of the GNU General Public License into a single
-combined work, and to convey the resulting work. The terms of this
-License will continue to apply to the part which is the covered work,
-but the work with which it is combined will remain governed by version
-3 of the GNU General Public License.
-
- 14. Revised Versions of this License.
-
- The Free Software Foundation may publish revised and/or new versions of
-the GNU Affero General Public License from time to time. Such new versions
-will be similar in spirit to the present version, but may differ in detail to
-address new problems or concerns.
-
- Each version is given a distinguishing version number. If the
-Program specifies that a certain numbered version of the GNU Affero General
-Public License "or any later version" applies to it, you have the
-option of following the terms and conditions either of that numbered
-version or of any later version published by the Free Software
-Foundation. If the Program does not specify a version number of the
-GNU Affero General Public License, you may choose any version ever published
-by the Free Software Foundation.
-
- If the Program specifies that a proxy can decide which future
-versions of the GNU Affero General Public License can be used, that proxy's
-public statement of acceptance of a version permanently authorizes you
-to choose that version for the Program.
-
- Later license versions may give you additional or different
-permissions. However, no additional obligations are imposed on any
-author or copyright holder as a result of your choosing to follow a
-later version.
-
- 15. Disclaimer of Warranty.
-
- THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
-APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
-HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
-OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
-THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
-PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
-IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
-ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
-
- 16. Limitation of Liability.
-
- IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
-WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
-THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
-GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
-USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
-DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
-PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
-EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
-SUCH DAMAGES.
-
- 17. Interpretation of Sections 15 and 16.
-
- If the disclaimer of warranty and limitation of liability provided
-above cannot be given local legal effect according to their terms,
-reviewing courts shall apply local law that most closely approximates
-an absolute waiver of all civil liability in connection with the
-Program, unless a warranty or assumption of liability accompanies a
-copy of the Program in return for a fee.
-
- END OF TERMS AND CONDITIONS
-
- How to Apply These Terms to Your New Programs
-
- If you develop a new program, and you want it to be of the greatest
-possible use to the public, the best way to achieve this is to make it
-free software which everyone can redistribute and change under these terms.
-
- To do so, attach the following notices to the program. It is safest
-to attach them to the start of each source file to most effectively
-state the exclusion of warranty; and each file should have at least
-the "copyright" line and a pointer to where the full notice is found.
-
-
- Copyright (C)
-
- This program is free software: you can redistribute it and/or modify
- it under the terms of the GNU Affero General Public License as published by
- the Free Software Foundation, either version 3 of the License, or
- (at your option) any later version.
-
- This program is distributed in the hope that it will be useful,
- but WITHOUT ANY WARRANTY; without even the implied warranty of
- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
- GNU Affero General Public License for more details.
-
- You should have received a copy of the GNU Affero General Public License
- along with this program. If not, see .
-
-Also add information on how to contact you by electronic and paper mail.
-
- If your software can interact with users remotely through a computer
-network, you should also make sure that it provides a way for users to
-get its source. For example, if your program is a web application, its
-interface could display a "Source" link that leads users to an archive
-of the code. There are many ways you could offer source, and different
-solutions will be better for different programs; see section 13 for the
-specific requirements.
-
- You should also get your employer (if you work as a programmer) or school,
-if any, to sign a "copyright disclaimer" for the program, if necessary.
-For more information on this, and how to apply and follow the GNU AGPL, see
-.
\ No newline at end of file
diff --git a/tutorials/quick_start/pytorch_fw/ultralytics_lib/README.md b/tutorials/quick_start/pytorch_fw/ultralytics_lib/README.md
deleted file mode 100644
index b074727b7..000000000
--- a/tutorials/quick_start/pytorch_fw/ultralytics_lib/README.md
+++ /dev/null
@@ -1,51 +0,0 @@
-# MCT Quick Start - Ultralytics Example
-
-This example demonstrates how to use MCT 'quick start' with Ultralytics object detection model.
-
-
-## Getting Started
-
-### Installation
-Install the required library using `pip`:
-```bash
-pip install ultralytics==8.0.232
- ```
-
-### Usage Examples
-
-In the following example, we are evaluating the MCT on pre-trained yolov8n, taken from the Ultralytics models library.
-
-Note that we assume the command is run from the command line and that the [main.py](../../main.py) script is located in the current directory.
-Additionally, it is expected that the [model_optimization](../../../../) folder is included in python path.
-```csh
-setenv PYTHONPATH /path/to/model_optimization/folder
-```
-
-```csh
-python main.py --model_name yolov8n --model_library ultralytics --representative_dataset_folder /datasets/coco/images/train2017 --num_representative_images 64 --batch_size 1
-```
-In this example, we are running the main.py script with the following parameters:
-- `--model_name`: Specifies the name of the model to be used out of Ultralytics models (yolov8n in this case).
-- `--model_library`: Specifies the package of the pre-trained models from which the model name is taken (in this case, ultralytics_lib).
-- `--representative_dataset_folder`: Specifies the path to the local copy of the dataset to be used for quantization. In this case, we use the 'train' split of the downloaded dataset provided by Ultralytics.
-- `--num_representative_images`: Specifies the number of representative images to be used for quantization.
-- `--batch_size`: Specifies the batch size to be used.
-
-Please note that during the first model evaluation, Ultralytics downloads the COCO dataset to the folder specified in [coco.yaml](https://github.com/ultralytics/ultralytics/blob/main/ultralytics/cfg/datasets/coco.yaml) file. Therefore, the 'validation_dataset_folder' value is not required in this case.
-
-For the representative dataset, it is expected to follow the same format as the downloaded COCO dataset. For instance, you can use the 'train' split of the COCO dataset as the representative dataset or create a new split with the same format.
-
-For more information on the dataset format please refer the [ultralytics docs](https://docs.ultralytics.com/datasets/)
-
-## Model Replacers
-During the process, we perform a few manipulations to achieve better quantization results:
-
-1. We replace certain modules with modules supported by `torch.fx`, which our project relies on. The `torch.fx` toolkit helps us acquire a static graph representation from PyTorch models, enabling model compression manipulations like batch norm folding.
-2. We remove the last part of the detection head, responsible for bounding box decoding, and include it as part of the postprocessing. You can find the additional postprocessing in the new definition of the `postprocess` method under [detect_replacer.py](./detect_replacers.py).
-3. In Segmentation and Pose-Estimation tasks, which use the detect head, we use the replaced detect head and also modify the postprocessing accordingly. You can find the additional postprocessing in the new definition of the `postprocess` method under [segment_replacers.py](./segment_replacers.py) and [pose_replacers.py](./pose_replacers.py).
-
-
-## License
-This project is licensed under [Apache License 2.0](../../../../LICENSE.md).
-Ultralytics has the following license requirements:
-- ultralytics: [license link](https://github.com/ultralytics/ultralytics/blob/main/LICENSE), [license copy](./LICENSE)
diff --git a/tutorials/quick_start/pytorch_fw/ultralytics_lib/__init__.py b/tutorials/quick_start/pytorch_fw/ultralytics_lib/__init__.py
deleted file mode 100644
index 2147ec284..000000000
--- a/tutorials/quick_start/pytorch_fw/ultralytics_lib/__init__.py
+++ /dev/null
@@ -1,14 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
diff --git a/tutorials/quick_start/pytorch_fw/ultralytics_lib/common_replacers.py b/tutorials/quick_start/pytorch_fw/ultralytics_lib/common_replacers.py
deleted file mode 100644
index 36f779f67..000000000
--- a/tutorials/quick_start/pytorch_fw/ultralytics_lib/common_replacers.py
+++ /dev/null
@@ -1,167 +0,0 @@
-# Copyright 2024 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-
-"""
- Parts of this file were copied from https://github.com/ultralytics/ultralytics and modified for this project needs.
-
- The Licence of the ultralytics project is shown in: https://github.com/ultralytics/ultralytics/blob/main/LICENSE
-"""
-from typing import Any
-
-import torch
-
-from common.model_lib import ModuleReplacer
-from ultralytics import YOLO
-from ultralytics.nn.modules import C2f
-from ultralytics.cfg import get_cfg
-from ultralytics.utils import DEFAULT_CFG
-from ultralytics.utils.checks import check_imgsz
-from pathlib import Path
-
-from model_compression_toolkit.core.pytorch.back2framework.pytorch_model_builder import PytorchModel
-from tutorials.quick_start.common.constants import MODULE_REPLACER, VALIDATOR, DETECT, SEGMENT, POSE, RECT, MODE, \
- DEVICE, VAL, COCO_POSE
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.detect_replacers import DetectionValidatorReplacer, \
- DetectModuleReplacer
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.pose_replacers import PoseValidatorReplacer, PoseModuleReplacer
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.replace_module import replace_2d_deg_module
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.segment_replacers import SegmentationValidatorReplacer, \
- SegmentModuleReplacer
-
-TASK_MAP = {
- DETECT: {
- MODULE_REPLACER: DetectModuleReplacer(),
- VALIDATOR: DetectionValidatorReplacer},
- SEGMENT: {
- MODULE_REPLACER: SegmentModuleReplacer(),
- VALIDATOR: SegmentationValidatorReplacer},
- POSE: {
- MODULE_REPLACER: PoseModuleReplacer(),
- VALIDATOR: PoseValidatorReplacer}
-}
-
-
-# In this section we slightly modify C2f module and replace the "list" function which is not supported by torch.fx
-class C2fReplacer(C2f):
- """
- A new C2f module definition supported by torch.fx
- """
-
- def forward(self, x):
- y1 = self.cv1(x).chunk(2, 1)
- y = [y1[0], y1[1]]
- y.extend(m(y[-1]) for m in self.m)
- return self.cv2(torch.cat(y, 1))
-
-
-class C2fModuleReplacer(ModuleReplacer):
- """
- A module replacer for C2f modules.
- """
-
- def get_new_module(self, config):
- return C2fReplacer(*config)
-
- def get_config(self, c):
- c1 = next(c.cv1.children()).in_channels
- c2 = next(c.cv1.children()).out_channels
- cc = c.c
- n = int(next(c.cv2.children()).in_channels / cc - 2)
- e = cc / c2
- g = next(next(next(c.m.children()).children()).children()).groups
- shortcut = next(c.m.children()).add
- return [c1, c2, n, shortcut, g, e]
-
- def replace(self, model):
- return replace_2d_deg_module(model, C2f, self.get_new_module, self.get_config)
-
-
-class YOLOReplacer(YOLO):
- """
- Replaces the YOLO class to include the modified DetectionValidator
- """
-
- def val(self, data=None, **kwargs):
- """
- Validate a model on a given dataset .
-
- Args:
- data (str): The dataset to validate on. Accepts all formats accepted by yolo
- **kwargs : Any other args accepted by the validators. To see all args check 'configuration' section in docs
- """
- overrides = self.overrides.copy()
- overrides[RECT] = False # rect batches as default
- overrides.update(kwargs)
- overrides[MODE] = VAL
- overrides[DEVICE] = torch.device("cuda" if torch.cuda.is_available() else "cpu")
- args = get_cfg(cfg=DEFAULT_CFG, overrides=overrides)
- args.data = data or args.data
- args.data = COCO_POSE if self.task == 'pose' else args.data
- if 'task' in overrides:
- self.task = args.task
- else:
- args.task = self.task
- if args.imgsz == DEFAULT_CFG.imgsz and not isinstance(self.model, (str, Path)):
- args.imgsz = self.model.args['imgsz'] # use trained imgsz unless custom value is passed
- args.imgsz = check_imgsz(args.imgsz, max_dim=1)
-
- validator = TASK_MAP[self.task][VALIDATOR](args=args)
- validator.model = self.model
- validator(model=self.model)
- self.metrics_data = validator.metrics
-
- return validator.metrics
-
-
-def prepare_model_for_ultralytics_val(ultralytics_model: YOLOReplacer, model: Any, quantized=False):
- """
- Prepares the model for Ultralytics validation by setting necessary attributes.
- Post quantization, MCT returns a PytorchModel instance, which does not have some of the arguments required by
- Ultralytics code. We replace the model with a custom model that has these attributes.
- Args:
- ultralytics_model: The Ultralytics model instance.
- model: The model to validate.
- quantized: Whether the model is quantized.
- """
-
- class CustomPytorchModel(PytorchModel):
- def __init__(self, graph, append2output, return_float_outputs, wrapper, get_activation_quantizer_holder_fn):
- super().__init__(graph, append2output, return_float_outputs, wrapper, get_activation_quantizer_holder_fn)
- self.args = ultralytics_model.model.args
- self.names = ultralytics_model.model.names
- self.stride = ultralytics_model.model.stride
- self.device = next(model.parameters()).device
-
- def forward(self, x, augment=False, visualize=False, embed=False):
- return super().forward(x)
-
- def fuse(self, verbose=True):
- return self
-
- if not hasattr(model, 'args'):
- setattr(model, 'args', ultralytics_model.model.args)
- setattr(model, 'names', ultralytics_model.model.names)
- setattr(model, 'stride', ultralytics_model.model.stride)
- setattr(model, "device", next(model.parameters()).device)
- if quantized: # cast to custom pytorch model that accepts augment, visualize and embed
- custom_model = CustomPytorchModel(graph=model.graph, append2output=model.append2output,
- return_float_outputs=model.return_float_outputs, wrapper=model.wrapper,
- get_activation_quantizer_holder_fn=model.get_activation_quantizer_holder)
- for attr_name, attr_value in vars(model).items():
- setattr(custom_model, attr_name, attr_value)
-
- setattr(ultralytics_model, 'model', custom_model if quantized else model)
-
- return ultralytics_model
diff --git a/tutorials/quick_start/pytorch_fw/ultralytics_lib/detect_replacers.py b/tutorials/quick_start/pytorch_fw/ultralytics_lib/detect_replacers.py
deleted file mode 100644
index 36a683ed1..000000000
--- a/tutorials/quick_start/pytorch_fw/ultralytics_lib/detect_replacers.py
+++ /dev/null
@@ -1,155 +0,0 @@
-# Copyright 2024 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-
-"""
- Parts of this file were copied from https://github.com/ultralytics/ultralytics and modified for this project needs.
-
- The Licence of the ultralytics project is shown in: https://github.com/ultralytics/ultralytics/blob/main/LICENSE
-"""
-from typing import Tuple
-
-import torch
-from torch import Tensor
-from ultralytics.models.yolo.detect import DetectionValidator
-from ultralytics.nn import DetectionModel
-from ultralytics.nn.modules import Detect
-from ultralytics.utils.tal import make_anchors, dist2bbox
-
-from tutorials.quick_start.common.constants import EDGE_TPU
-from tutorials.quick_start.common.model_lib import ModuleReplacer
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.replace_module import replace_2d_deg_module
-
-
-# In this section we modify Detect module to exclude dynamic condition which is not supported by torch.fx
-# In addition, we remove the last part of the detection head which is essential for improving the quantization
-# This missing part will be added to the postprocessing implementation
-class DetectReplacer(Detect):
- """
- Replaces the Detect module with modifications to support torch.fx and removes the last part of the detection head.
- Specifically, we remove the concatenation of the outputs and the dynamic condition
- """
-
- def forward(self, x: Tensor) -> Tuple[Tensor, Tensor]:
- shape = x[0].shape # BCHW
- for i in range(self.nl):
- x[i] = torch.cat((self.cv2[i](x[i]), self.cv3[i](x[i])), 1)
-
- if self.export and self.format == EDGE_TPU: # FlexSplitV ops issue
- x_cat = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2)
- box = x_cat[:, :self.reg_max * 4]
- cls = x_cat[:, self.reg_max * 4:]
- else:
- box, cls = torch.cat([xi.view(shape[0], self.no, -1) for xi in x], 2).split(
- (self.reg_max * 4, self.nc), 1)
-
- y_cls = cls.sigmoid()
- y_bb = self.dfl(box)
- return y_bb, y_cls
-
-
-class DetectModuleReplacer(ModuleReplacer):
- """
- A module replacer for Detect modules.
- """
-
- def get_new_module(self, config: list) -> DetectReplacer:
- return DetectReplacer(*config)
-
- def get_config(self, c: torch.nn.Module) -> list[int, tuple]:
- nc = c.nc
- ch = [next(next(x.children()).children()).in_channels for x in c.cv2.children()]
- return [nc, ch]
-
- def replace(self, model: torch.nn.Module) -> torch.nn.Module:
- return replace_2d_deg_module(model, Detect, self.get_new_module, self.get_config)
-
-
-# In this section we modify the DetectionModel to exclude dynamic condition which is not supported by torch.fx
-class DetectionModelReplacer(DetectionModel):
- """
- Replaces the DetectionModel to exclude dynamic condition not supported by torch.fx.
- """
-
- # Original forward functions uses *args and **kwargs and these are not supported by torch.fx and therefore
- # we need to overload the forward function
- def forward(self, x, profile=False, visualize=False, augment=False, embed=False):
- return self.predict(x, profile=False, visualize=False, augment=False, embed=False)
-
- # Original predict uses a dynamic condition (if augment) which is not supported by torch.fx and we remove it
- def predict(self, x, profile=False, visualize=False, augment=False, embed=False):
- return self._predict_once(x, profile, visualize) # single-scale inference, train
-
- # Original _predict_once uses a dynamic condition (if profile, if visualize, if embed) which are not supported by
- # torch.fx and we remove them
- def _predict_once(self, x, profile=False, visualize=False, embed=False):
- y, dt, embeddings = [], [], [] # outputs
- for m in self.model:
- if m.f != -1: # if not from previous layer
- x = y[m.f] if isinstance(m.f, int) else [x if j == -1 else y[j] for j in
- m.f] # from earlier layers
-
- x = m(x) # run
- y.append(x if m.i in self.save else None) # save output
-
- return x
-
-
-class DetectionModelModuleReplacer(ModuleReplacer):
- """
- A module replacer for DetectionModel modules.
- """
-
- def get_config(self, c: torch.nn.Module) -> list:
- return [c.yaml]
-
- def get_new_module(self, config: list) -> DetectionModelReplacer:
- return DetectionModelReplacer(*config)
-
- def replace(self, model: torch.nn.Module) -> torch.nn.Module:
- return self.get_new_module(self.get_config(model))
-
-
-# In this section we modify the DetectionValidator (not part of the model) to include the missing functionality
-# that was removed from the Detect module
-class DetectionValidatorReplacer(DetectionValidator):
- """
- Replaces the DetectionValidator to include missing functionality from the Detect module.
- """
-
- # Code modified from make_anchors function in /ultralytics/utils/tal.py since we remove this part from the forward
- # function in the replaced Detect module
- def create_anchors_strides(self):
- # Post-processing additional part - exported from Detect module
- strides = [8, 16, 32]
- stride = torch.tensor(strides, dtype=torch.float32)
- grid = (self.args.imgsz / stride).numpy().astype(int)
- in_ch = 64 + self.nc # 144
- x_dummy = [torch.ones(1, in_ch, grid[0], grid[0]), torch.ones(1, in_ch, grid[1], grid[1]),
- torch.ones(1, in_ch, grid[2], grid[2])]
- anchors, strides = (x.transpose(0, 1) for x in make_anchors(x_dummy, stride, 0.5))
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
- a = anchors.to(device)
- s = strides.to(device)
- return a, s
-
- def postprocess(self, preds: tuple[Tensor, Tensor]) -> list[Tensor]:
- a, s = self.create_anchors_strides()
- dbox = dist2bbox(preds[0], a.unsqueeze(0), xywh=True, dim=1) * s
- preds = torch.cat((dbox, preds[1]), 1)
-
- # Original post-processing part
- preds = super().postprocess(preds)
-
- return preds
diff --git a/tutorials/quick_start/pytorch_fw/ultralytics_lib/model_lib.py b/tutorials/quick_start/pytorch_fw/ultralytics_lib/model_lib.py
deleted file mode 100644
index ed4cd4963..000000000
--- a/tutorials/quick_start/pytorch_fw/ultralytics_lib/model_lib.py
+++ /dev/null
@@ -1,124 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-
-"""
- Parts of this file were copied from https://github.com/ultralytics/ultralytics and modified for this project needs.
-
- The Licence of the ultralytics project is shown in: https://github.com/ultralytics/ultralytics/blob/main/LICENSE
-"""
-import logging
-
-import torch
-from ultralytics.utils.torch_utils import initialize_weights
-
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.common_replacers import C2fModuleReplacer, \
- YOLOReplacer, TASK_MAP
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.detect_replacers import DetectionModelModuleReplacer
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.common_replacers import prepare_model_for_ultralytics_val
-from tutorials.quick_start.common.model_lib import BaseModelLib
-from tutorials.quick_start.common.constants import MODEL_NAME, BATCH_SIZE, COCO_DATASET, VALIDATION_DATASET_FOLDER, \
- MODULE_REPLACER
-from tutorials.quick_start.common.results import DatasetInfo
-from tutorials.mct_model_garden.models_keras.yolov8.yolov8_preprocess import yolov8_preprocess_chw_transpose
-from tutorials.quick_start.common.utils import FolderImageLoader
-from model_compression_toolkit.core.pytorch.back2framework.pytorch_model_builder import PytorchModel
-
-
-class ModelLib(BaseModelLib):
- """
- A class representing ultralytics model library (https://github.com/ultralytics/ultralytics).
- """
-
- def __init__(self, args):
- """
- Init the ModelLib with user arguments
- Args:
- args (dict): user arguments
- """
- # Load model from ultralytics
- self.ultralytics_model = YOLOReplacer(args[MODEL_NAME])
- self.dataset_name = COCO_DATASET
- self.preprocess = yolov8_preprocess_chw_transpose
- model_weights = self.ultralytics_model.model.state_dict()
-
- # Replace few modules with quantization-friendly modules
- self.model = self.ultralytics_model.model
- self.model = DetectionModelModuleReplacer().replace(self.model)
- self.model = C2fModuleReplacer().replace(self.model)
- self.model = TASK_MAP[self.ultralytics_model.task][MODULE_REPLACER].replace(self.model)
-
- # load pre-trained weights
- initialize_weights(self.model)
- self.model.load_state_dict(model_weights) # load weights
- super().__init__(args)
-
- def get_model(self):
- """
- Returns the model instance.
- """
- return self.model
-
- def get_representative_dataset(self, representative_dataset_folder, n_iter, batch_size):
- """
- Create a representative dataset generator
- Args:
- representative_dataset_folder: Dataset location folder, in YOLO format (see ultralytics docs), for example: //coco/images/train2017
- n_iter: number batches to run in the generator
- batch_size: number of images in each batch
-
- Returns:
- A generator for the representative dataset, as the MCT expects
-
- """
- image_data_loader = FolderImageLoader(representative_dataset_folder,
- preprocessing=[self.preprocess],
- batch_size=batch_size)
- def representative_data_gen() -> list:
- for _ in range(n_iter):
- yield [image_data_loader.sample()]
-
- return representative_data_gen
-
- def evaluate(self, model):
- """
- Evaluates the model's performance.
-
- Args:
- model: The model to evaluate.
-
- Returns:
- acc: The accuracy of the model.
- DatasetInfo: Information about the dataset used.
- """
- # Use Cuda device if available
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
- model.to(device)
-
- # Some attributes are required for the evaluation of the quantized model
- self.ultralytics_model = prepare_model_for_ultralytics_val(self.ultralytics_model, model, quantized=isinstance(model, PytorchModel))
-
- # Evaluation using ultralytics interface
- if self.args[VALIDATION_DATASET_FOLDER] is not None:
- logging.warning('The provided value for "validation_dataset_folder" is ignored. '
- 'Ultralytics utilizes the dataset path specified in the coco.yaml file. '
- 'By default, the dataset path is taken from "/home/user/.config/Ultralytics/settings.yaml", depends on your operating system.')
-
- results = self.ultralytics_model.val(batch=int(self.args[BATCH_SIZE])) # evaluate model performance on the validation set
- map_res = results.mean_results()[-1]
- dataset_info = DatasetInfo(self.dataset_name, 5000)
- return map_res, dataset_info
-
-
-
diff --git a/tutorials/quick_start/pytorch_fw/ultralytics_lib/pose_replacers.py b/tutorials/quick_start/pytorch_fw/ultralytics_lib/pose_replacers.py
deleted file mode 100644
index 158dcbc2f..000000000
--- a/tutorials/quick_start/pytorch_fw/ultralytics_lib/pose_replacers.py
+++ /dev/null
@@ -1,97 +0,0 @@
-# Copyright 2024 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-
-"""
- Parts of this file were copied from https://github.com/ultralytics/ultralytics and modified for this project needs.
-
- The Licence of the ultralytics project is shown in: https://github.com/ultralytics/ultralytics/blob/main/LICENSE
-"""
-from typing import Tuple
-
-import torch
-from torch import Tensor
-from ultralytics.models.yolo.pose import PoseValidator
-from ultralytics.nn.modules import Pose
-from ultralytics.utils.tal import make_anchors, dist2bbox
-
-from tutorials.quick_start.common.model_lib import ModuleReplacer
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.detect_replacers import DetectReplacer, DetectionValidatorReplacer
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.replace_module import replace_2d_deg_module
-
-
-class PoseReplacer(Pose):
- """
- Replaces the Pose module to use the replaced Detect forward function.
- To improve quantization (due to different data types), we removes the output concatenation.
- This will be added back in post_process.
- Also removes the key points decoding part, which will be added back in post_process.
- """
-
- def __init__(self, nc=80, kpt_shape=(17, 3), ch=()):
- super().__init__(nc, kpt_shape, ch)
- self.detect = DetectReplacer.forward
-
- def forward(self, x: Tensor) -> Tuple[Tensor, Tensor, Tensor]:
- """Perform forward pass through YOLO model and return predictions."""
- bs = x[0].shape[0] # batch size
- kpt = torch.cat([self.cv4[i](x[i]).view(bs, self.nk, -1) for i in range(self.nl)], -1) # (bs, 17*3, h*w)
- y_bb, y_cls = self.detect(self, x)
- return y_bb, y_cls, kpt
-
-
-class PoseModuleReplacer(ModuleReplacer):
- """
- A module replacer for Segment modules.
- """
-
- def get_new_module(self, config: list) -> PoseReplacer:
- return PoseReplacer(*config)
-
- def get_config(self, c: torch.nn.Module) -> list:
- nc = c.nc
- kpt_shape = c.kpt_shape
- ch = [next(next(x.children()).children()).in_channels for x in c.cv2.children()]
- return [nc, kpt_shape, ch]
-
- def replace(self, model: torch.nn.Module) -> torch.nn.Module:
- return replace_2d_deg_module(model, Pose, self.get_new_module, self.get_config)
-
-
-class PoseValidatorReplacer(PoseValidator, DetectionValidatorReplacer):
- """
- Replaces the PoseValidator to include missing functionality from the Pose module.
- Uses the post process function from the DetectionValidatorReplacer, and adds the keypoint post-processing.
- """
- def postprocess(self, preds: Tuple[Tensor, Tensor, Tensor]) -> list[Tensor]:
- kpt_shape = (17, 3)
- a, s = self.create_anchors_strides()
-
- y_bb, y_cls, kpts = preds
- dbox = dist2bbox(y_bb, a.unsqueeze(0), xywh=True, dim=1) * s
- detect_out = torch.cat((dbox, y_cls), 1)
- # additional part for pose estimation
- ndim = kpt_shape[1]
- pred_kpt = kpts.clone()
- if ndim == 3:
- pred_kpt[:, 2::3] = pred_kpt[:, 2::3].sigmoid() # sigmoid (WARNING: inplace .sigmoid_() Apple MPS bug)
- pred_kpt[:, 0::ndim] = (pred_kpt[:, 0::ndim] * 2.0 + (a[0] - 0.5)) * s
- pred_kpt[:, 1::ndim] = (pred_kpt[:, 1::ndim] * 2.0 + (a[1] - 0.5)) * s
- preds = (torch.cat([detect_out, pred_kpt], 1), (y_cls, kpts))
-
- # Original post-processing part
- preds = super().postprocess(preds)
-
- return preds
-
\ No newline at end of file
diff --git a/tutorials/quick_start/pytorch_fw/ultralytics_lib/replace_module.py b/tutorials/quick_start/pytorch_fw/ultralytics_lib/replace_module.py
deleted file mode 100644
index dd0f4cf4b..000000000
--- a/tutorials/quick_start/pytorch_fw/ultralytics_lib/replace_module.py
+++ /dev/null
@@ -1,25 +0,0 @@
-import torch.nn
-
-
-def replace_2d_deg_module(model: torch.nn.Module, old_module: type, new_module: callable, get_config: callable):
- """
- Replaces a 2nd degree submodule in the given ultralytics model with a new module.
-
- Args:
- model (torch.nn.Module): The model to modify.
- old_module (type): The old module type to replace.
- new_module (callable): A function or callable that creates the new module.
- get_config (callable): A function or callable that retrieves the configuration for creating the new module.
-
- Returns:
- torch.nn.Module: The modified model.
- """
- for n, m in model.named_children():
- for name, c in m.named_children():
- if isinstance(c, old_module):
- l = new_module(get_config(c))
- setattr(l, 'f', c.f)
- setattr(l, 'i', c.i)
- setattr(l, 'type', c.type)
- setattr(m, name, l)
- return model
\ No newline at end of file
diff --git a/tutorials/quick_start/pytorch_fw/ultralytics_lib/segment_replacers.py b/tutorials/quick_start/pytorch_fw/ultralytics_lib/segment_replacers.py
deleted file mode 100644
index 0baebf778..000000000
--- a/tutorials/quick_start/pytorch_fw/ultralytics_lib/segment_replacers.py
+++ /dev/null
@@ -1,90 +0,0 @@
-# Copyright 2024 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-
-"""
- Parts of this file were copied from https://github.com/ultralytics/ultralytics and modified for this project needs.
-
- The Licence of the ultralytics project is shown in: https://github.com/ultralytics/ultralytics/blob/main/LICENSE
-"""
-from typing import Tuple, Any
-
-import torch
-from torch import Tensor
-from ultralytics.models.yolo.segment import SegmentationValidator
-from ultralytics.nn.modules import Segment
-from ultralytics.utils.tal import make_anchors, dist2bbox
-
-from tutorials.quick_start.common.model_lib import ModuleReplacer
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.detect_replacers import DetectReplacer, DetectionValidatorReplacer
-from tutorials.quick_start.pytorch_fw.ultralytics_lib.replace_module import replace_2d_deg_module
-
-
-class SegmentReplacer(Segment):
- """
- Replaces the Segment module to use the replaced Detect forward function.
- To improve quantization (due to different data types), we removes the output concatenation.
- This will be added back in post_process.
- """
-
- def __init__(self, nc=80, nm=32, npr=256, ch=()):
- super().__init__(nc, nm, npr, ch)
- self.detect = DetectReplacer.forward
-
- def forward(self, x: Tensor) -> Tuple[Tensor, Tensor, Tensor, Any]:
- p = self.proto(x[0]) # mask protos
- bs = p.shape[0] # batch size
-
- mc = torch.cat([self.cv4[i](x[i]).view(bs, self.nm, -1) for i in range(self.nl)], 2) # mask coefficients
- y_bb, y_cls = self.detect(self, x)
-
- return y_bb, y_cls, mc, p
-
-
-class SegmentModuleReplacer(ModuleReplacer):
- """
- A module replacer for Segment modules.
- """
-
- def get_new_module(self, config: list) -> SegmentReplacer:
- return SegmentReplacer(*config)
-
- def get_config(self, c: torch.nn.Module) -> list[int, int, int, tuple]:
- nc = c.nc
- nm = c.nm
- npr = c.npr
- ch = [next(next(x.children()).children()).in_channels for x in c.cv2.children()]
- return [nc, nm, npr, ch]
-
- def replace(self, model: torch.nn.Module) -> torch.nn.Module:
- return replace_2d_deg_module(model, Segment, self.get_new_module, self.get_config)
-
-
-class SegmentationValidatorReplacer(SegmentationValidator, DetectionValidatorReplacer):
- """
- Replaces the SegmentationValidator to include missing functionality from the Segment module.
- Uses the post process function from the DetectionValidatorReplacer, and adds the segmentation post-processing.
- """
- def postprocess(self, preds: Tuple[Tensor, Tensor, Tensor, Any]) -> Tuple[list[Tensor], Tensor]:
- a, s = self.create_anchors_strides()
- y_bb, y_cls, masks_coeffs, proto = preds
- dbox = dist2bbox(y_bb, a.unsqueeze(0), xywh=True, dim=1) * s
- y = torch.cat((dbox, y_cls), 1)
- # additional part for segmentation
- preds = (torch.cat([y, masks_coeffs], 1), (y_cls, masks_coeffs, proto))
-
- # Original post-processing part
- preds = super().postprocess(preds)
-
- return preds
\ No newline at end of file
diff --git a/tutorials/quick_start/pytorch_fw/utils.py b/tutorials/quick_start/pytorch_fw/utils.py
deleted file mode 100644
index 923c8d7d8..000000000
--- a/tutorials/quick_start/pytorch_fw/utils.py
+++ /dev/null
@@ -1,64 +0,0 @@
-# Copyright 2023 Sony Semiconductor Israel, Inc. All rights reserved.
-#
-# Licensed under the Apache License, Version 2.0 (the "License");
-# you may not use this file except in compliance with the License.
-# You may obtain a copy of the License at
-#
-# http://www.apache.org/licenses/LICENSE-2.0
-#
-# Unless required by applicable law or agreed to in writing, software
-# distributed under the License is distributed on an "AS IS" BASIS,
-# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-# See the License for the specific language governing permissions and
-# limitations under the License.
-# ==============================================================================
-import torch
-import logging
-from tqdm import tqdm
-
-
-def classification_eval(model, data_loader, limit=None, num_images_to_display=1000):
- logging.info(f'Start classification evaluation')
- correct = 0
- total = 0
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
- model.to(device)
- model.eval()
- # since we're not training, we don't need to calculate the gradients for our outputs
- with torch.no_grad():
- for data in tqdm(data_loader, desc="Classification evaluation"):
- images, labels = data
- # calculate outputs by running images through the network
- outputs = model(images.to(device))
- # the class with the highest energy is what we choose as prediction
- _, predicted = torch.max(outputs.data, 1)
- total += labels.size(0)
- correct += (predicted == labels.to(device)).sum().item()
- if total % num_images_to_display == 0:
- print(f'Num of images: {total}, Accuracy: {round(100 * correct / total, 2)} %')
- if limit and total >= int(limit):
- break
-
- logging.info(f'Num of images: {total}, Accuracy: {round(100 * correct / total, 2)} %')
-
- return correct / total, total
-
-
-def get_representative_dataset(data_loader, n_iters, data_loader_key=0, transforms=None):
- class RepresentativeDataset(object):
- def __init__(self, in_data_loader):
- self.dl = in_data_loader
- self.iter = iter(self.dl)
-
- def __call__(self):
- for _ in range(n_iters):
- try:
- x = next(self.iter)[data_loader_key]
- except StopIteration:
- self.iter = iter(self.dl)
- x = next(self.iter)[data_loader_key]
- if transforms is not None:
- x = transforms(x.float())
- yield [x.cpu().numpy()]
-
- return RepresentativeDataset(data_loader)
diff --git a/tutorials/quick_start/results/model_quantization_results.csv b/tutorials/quick_start/results/model_quantization_results.csv
deleted file mode 100644
index 60d3060db..000000000
--- a/tutorials/quick_start/results/model_quantization_results.csv
+++ /dev/null
@@ -1,15 +0,0 @@
-ModelName,ModelLibrary,DatasetName,TotalImages,FloatAcc,QuantAcc,Size[MB],BitsConfig,QuantTechnique,TPC
-mobilenet_v2,torchvision,ImageNet,50000,0.7215,0.7188,3.47,W8A8,PTQ,default_pytorch_tpc-v4
-regnet_y_400mf,torchvision,ImageNet,50000,0.7578,0.7542,4.31,W8A8,PTQ,default_pytorch_tpc-v4
-shufflenet_v2_x0_5,torchvision,ImageNet,50000,0.6055,0.597,1.36,W8A8,PTQ,default_pytorch_tpc-v4
-squeezenet1_0,torchvision,ImageNet,50000,0.581,0.5767,1.24,W8A8,PTQ,default_pytorch_tpc-v4
-regnetx_002,timm,ImageNet,50000,0.6876,0.6827,2.67,W8A8,PTQ,default_pytorch_tpc-v4
-regnety_008,timm,ImageNet,50000,0.7632,0.7598,6.23,W8A8,PTQ,default_pytorch_tpc-v4
-resnet10t,timm,ImageNet,50000,0.6656,0.6643,5.43,W8A8,PTQ,default_pytorch_tpc-v4
-resnet18,timm,ImageNet,50000,0.6976,0.6961,11.68,W8A8,PTQ,default_pytorch_tpc-v4
-efficientnet_es,timm,ImageNet,50000,0.7808,0.7774,5.39,W8A8,PTQ,default_pytorch_tpc-v4
-yolov8n,ultralytics,COCO,5000,0.3704,0.3617,3.15,W8A8,PTQ,default_pytorch_tpc-v4
-yolov8m,ultralytics,COCO,5000,0.4999,0.494,25.9,W8A8,PTQ,default_pytorch_tpc-v4
-MobileNetV2,keras_applications,ImageNet,50000,0.7185,0.7157,3.47,W8A8,PTQ,default_keras_tpc-v4
-EfficientNetV2B0,keras_applications,ImageNet,50000,0.7841,0.7744,7.06,W8A8,PTQ,default_keras_tpc-v4
-ResNet50,keras_applications,ImageNet,50000,0.7422,0.7408,25.5,W8A8,PTQ,default_keras_tpc-v4