Demonstrates how to divide a DL model into multiple IR model files (division) and introduce a simplest way to implement a custom layer works with OpenVINO IR models.

Overview

Demonstration of OpenVINO techniques - Model-division and a simplest-way to support custom layers

Description:

Model Optimizer in Intel(r) OpenVINO(tm) toolkit supports model division function. User can specify the region in the model to convert by specifying entry point and exit point with --input and --output options respectively.
The expected usage of those options are:

  • Excluding unnecessary layers: Removing non-DL related layers (such as JPEG decode) and layers not required for inferencing (such as accuracy metrics calculation)
  • Load balancing: Divide a model into multiple parts and cascade them to get the final inferencing result. Each individual part can be run on different device or different timing.
  • Access to the intermediate result: Divide a model and get the intermediate feature data to check the model integrity or for the other purposes.
  • Exclude non-supported layers: Convert the model without OpenVINO non-supprted layers. Divide the model and skip non-supported layers to get the IR models. User needs to perform the equivalent processing for the excluded layers to get the correct inferencing result.

This project demonstrates how to divide a DL model, and fill the hole for skipped leyers.
The project includes Python and C++ implementations of naive 2D convolution layer to perform the Conv2D task which was supposed to have done by the skipped layer. This could be a good reference when you need to implement a custom layer function to your project but don't want to develop full-blown OpenVINO custom layers due to some restrictions such as development time.
In this project, we will use a simple CNN classification model trained with MNIST dataset and demonstrate the way to divide the model with skipping a layer (on purpose) and use a simple custom layer to cover the data processing for the skipped layer.

image

Prerequisites:

  • TensorFlow 2.x
  • OpenVINO 2021.4 (2021.x may work)

How to train the model and create a trained model

You can train the model by just kicking the training.py script. training.py will use keras.datasets.mnist as the training and validation dataset and train the model, and then save the trained model in SavedModel format.
training.py also generates weights.npy file that contains the weight and bias data of target_conv_layer layer. This weight and bias data will be used by the special made Conv2D layer.
Since the model we use is tiny, it will take just a couple of minutes to complete.

python3 training.py

How to convert a TF trained model into OpenVINO IR model format

Model Optimizer in OpenVINO converts TF (savedmodel) model into OpenVINO IR model.
Here's a set of script to convert the model for you.

script description
convert-normal.sh Convert entire model and generate single IR model file (no division)
convert-divide.sh Divide the input model and output 2 IR models. All layers are still contained (no skipped layers)
convert-divide-skip.sh Divide the input model and skip 'target_conv_layer'
  • The converted models can be found in ./models folder.

Tip to find the correct node name for Model Optimizer

Model optimizer requires MO internal networkx graph node name to specify --input and --output nodes. You can modify the model optimizer a bit to have it display the list of networkx node names. Add 3 lines on the very bottom of the code snnipet below and run the model optimizer.

mo/utils/class_registration.py

def apply_replacements_list(graph: Graph, replacers_order: list):
    """
    Apply all transformations from replacers_order
    """
    for i, replacer_cls in enumerate(replacers_order):
        apply_transform(
            graph=graph,
            replacer_cls=replacer_cls,
            curr_transform_num=i,
            num_transforms=len(replacers_order))
        # Display name of available nodes after the 'loader' stage
        if 'LoadFinish' in str(replacer_cls):
            for node in graph.nodes():
                print(node)

You'll see something like this. You need to use one of those node names for --input and --output options in MO.

conv2d_input
Func/StatefulPartitionedCall/input/_0
unknown
Func/StatefulPartitionedCall/input/_1
StatefulPartitionedCall/sequential/conv2d/Conv2D/ReadVariableOp
StatefulPartitionedCall/sequential/conv2d/Conv2D
   :   (truncated)   :
StatefulPartitionedCall/sequential/dense_1/BiasAdd/ReadVariableOp
StatefulPartitionedCall/sequential/dense_1/BiasAdd
StatefulPartitionedCall/sequential/dense_1/Softmax
StatefulPartitionedCall/Identity
Func/StatefulPartitionedCall/output/_11
Func/StatefulPartitionedCall/output_control_node/_12
Identity
Identity56

How to infer with the models on OpenVINO

Several versions of scripts are available for the inference testing.
Those test programs will do inference 10,000 times with the MNIST validation dataset. Test program displays '.' when inference result is correct and 'X' when it's wrong. Performance numbers are measured from the start of 10,000 inferences to the end of all inferences. So, it is including loop overhead, pre/post processing time and so on.

script description (reference execution time, Core i7-8665U)
inference.py Use simgle, monolithic IR model and run inference 3.3 sec
inference-div.py Take 2 divided IR models and run inference. 2 models will be cascaded. 5.3 sec(*1)
inference-skip-python.py Tak2 2 divided IR models which excluded the 'target_conv_layer'. Program is including a Python version of Conv2D and perform convolution for 'target_conv_layer'. VERY SLOW. 4338.6 sec
inference-skip-cpp.py Tak2 2 divided IR models which excluded the 'target_conv_layer'. Program imports a Python module written in C++ which includes a C++ version of Conv2D. Reasonably fast. Conv2D Python extension module is required. Please refer to the following section for details. 10.8 sec

Note 1: This model is quite tiny and light-weight. OpenVINO can run this model in <0.1msec on Core i7-8665U CPU. The inferencing overhead introduced by dividing the model is noticeable but when you use heavy model, this penalty might be negligible.

How to build the Conv2D C++ Python extnsion module

You can build the Conv2D C++ Python extension module by running build.sh or build.bat.
myLayers.so or myLayers.pyd will be generated and copied to the current directory after a successful build.

How to run draw-and-infer demo program

Here's a simple yet bit fun demo application for MNIST CNN. You can draw a number on the screen by mouse or finger-tip and you'll see the real-time inference result. Right-click will clear the screen for another try. Several versions are available.

script description
draw-and-infer.py Use the monolithic IR model
draw-and-infer-div.py Use divided IR models
draw-and-infer-skip-cpp.py Use divided IR models which excluded 'target_conv_layer'. Conv2D Python extension is requird.

draw-and-infer

Tested environment

  • Windows 10 + VS2019 + OpenVINO 2021.4
  • Ubuntu 20.04 + OpenVINO 2021.4
You might also like...
Utility tools for the
Utility tools for the "Divide and Remaster" dataset, introduced as part of the Cocktail Fork problem paper

Divide and Remaster Utility Tools Utility tools for the "Divide and Remaster" dataset, introduced as part of the Cocktail Fork problem paper The DnR d

This is the official repository for evaluation on the NoW Benchmark Dataset. The goal of the NoW benchmark is to introduce a standard evaluation metric to measure the accuracy and robustness of 3D face reconstruction methods from a single image under variations in viewing angle, lighting, and common occlusions. PyTorch implementation of
PyTorch implementation of "Contrast to Divide: self-supervised pre-training for learning with noisy labels"

Contrast to Divide: self-supervised pre-training for learning with noisy labels This is an official implementation of "Contrast to Divide: self-superv

The-Secret-Sharing-Schemes - This interactive script demonstrates the Secret Sharing Schemes algorithm
The-Secret-Sharing-Schemes - This interactive script demonstrates the Secret Sharing Schemes algorithm

The-Secret-Sharing-Schemes This interactive script demonstrates the Secret Shari

N-Person-Check-Checker-Splitter - A calculator app use to divide checks

N-Person-Check-Checker-Splitter This is my from-scratch programmed calculator ap

This Jupyter notebook shows one way to implement a simple first-order low-pass filter on sampled data in discrete time.

How to Implement a First-Order Low-Pass Filter in Discrete Time We often teach or learn about filters in continuous time, but then need to implement t

This is a repository for a No-Code object detection inference API using the OpenVINO. It's supported on both Windows and Linux Operating systems.
This is a repository for a No-Code object detection inference API using the OpenVINO. It's supported on both Windows and Linux Operating systems.

OpenVINO Inference API This is a repository for an object detection inference API using the OpenVINO. It's supported on both Windows and Linux Operati

πŸ“š A collection of Jupyter notebooks for learning and experimenting with OpenVINO πŸ‘“
πŸ“š A collection of Jupyter notebooks for learning and experimenting with OpenVINO πŸ‘“

A collection of ready-to-run Python* notebooks for learning and experimenting with OpenVINO developer tools. The notebooks are meant to provide an introduction to OpenVINO basics and teach developers how to leverage our APIs for optimized deep learning inference in their applications.

A high-performance anchor-free YOLO. Exceeding yolov3~v5 with ONNX, TensorRT, NCNN, and Openvino supported.
A high-performance anchor-free YOLO. Exceeding yolov3~v5 with ONNX, TensorRT, NCNN, and Openvino supported.

YOLOX is an anchor-free version of YOLO, with a simpler design but better performance! It aims to bridge the gap between research and industrial communities. For more details, please refer to our report on Arxiv.

Comments
  • Bump tensorflow from 2.4 to 2.4.2

    Bump tensorflow from 2.4 to 2.4.2

    Bumps tensorflow from 2.4 to 2.4.2.

    Release notes

    Sourced from tensorflow's releases.

    TensorFlow 2.4.2

    Release 2.4.2

    This release introduces several vulnerability fixes:

    ... (truncated)

    Changelog

    Sourced from tensorflow's changelog.

    Release 2.4.2

    This release introduces several vulnerability fixes:

    • Fixes a heap buffer overflow in RaggedBinCount (CVE-2021-29512)
    • Fixes a heap out of bounds write in RaggedBinCount (CVE-2021-29514)
    • Fixes a type confusion during tensor casts which leads to dereferencing null pointers (CVE-2021-29513)
    • Fixes a reference binding to null pointer in MatrixDiag* ops (CVE-2021-29515)
    • Fixes a null pointer dereference via invalid Ragged Tensors (CVE-2021-29516)
    • Fixes a division by zero in Conv3D (CVE-2021-29517)
    • Fixes vulnerabilities where session operations in eager mode lead to null pointer dereferences (CVE-2021-29518)
    • Fixes a CHECK-fail in SparseCross caused by type confusion (CVE-2021-29519)
    • Fixes a segfault in SparseCountSparseOutput (CVE-2021-29521)
    • Fixes a heap buffer overflow in Conv3DBackprop* (CVE-2021-29520)
    • Fixes a division by 0 in Conv3DBackprop* (CVE-2021-29522)
    • Fixes a CHECK-fail in AddManySparseToTensorsMap (CVE-2021-29523)
    • Fixes a division by 0 in Conv2DBackpropFilter (CVE-2021-29524)
    • Fixes a division by 0 in Conv2DBackpropInput (CVE-2021-29525)
    • Fixes a division by 0 in Conv2D (CVE-2021-29526)
    • Fixes a division by 0 in QuantizedConv2D (CVE-2021-29527)
    • Fixes a division by 0 in QuantizedMul (CVE-2021-29528)
    • Fixes vulnerabilities caused by invalid validation in SparseMatrixSparseCholesky (CVE-2021-29530)
    • Fixes a heap buffer overflow caused by rounding (CVE-2021-29529)
    • Fixes a CHECK-fail in tf.raw_ops.EncodePng (CVE-2021-29531)
    • Fixes a heap out of bounds read in RaggedCross (CVE-2021-29532)
    • Fixes a CHECK-fail in DrawBoundingBoxes

    ... (truncated)

    Commits
    • 1923123 Merge pull request #50210 from tensorflow/geetachavan1-patch-1
    • a0c8093 Update BUILD
    • f1c8200 Merge pull request #50203 from tensorflow/mihaimaruseac-patch-1
    • 7cf45b5 Update common.sh
    • 4aaac2b Merge pull request #50185 from geetachavan1/cherrypicks_U90C1
    • 65afa4b Fix the nightly nonpip builds for MacOS.
    • 46c1821 Merge pull request #50184 from tensorflow/mihaimaruseac-patch-1
    • cf8d667 Update common_win.bat
    • b2ef8a6 Merge pull request #50061 from tensorflow/geetachavan1-patch-2
    • f9a1ba8 Update sparse_fill_empty_rows_op.cc
    • Additional commits viewable in compare view

    Dependabot compatibility score

    Dependabot will resolve any conflicts with this PR as long as you don't alter it yourself. You can also trigger a rebase manually by commenting @dependabot rebase.


    Dependabot commands and options

    You can trigger Dependabot actions by commenting on this PR:

    • @dependabot rebase will rebase this PR
    • @dependabot recreate will recreate this PR, overwriting any edits that have been made to it
    • @dependabot merge will merge this PR after your CI passes on it
    • @dependabot squash and merge will squash and merge this PR after your CI passes on it
    • @dependabot cancel merge will cancel a previously requested merge and block automerging
    • @dependabot reopen will reopen this PR if it is closed
    • @dependabot close will close this PR and stop Dependabot recreating it. You can achieve the same result by closing it manually
    • @dependabot ignore this major version will close this PR and stop Dependabot creating any more for this major version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this minor version will close this PR and stop Dependabot creating any more for this minor version (unless you reopen the PR or upgrade to it yourself)
    • @dependabot ignore this dependency will close this PR and stop Dependabot creating any more for this dependency (unless you reopen the PR or upgrade to it yourself)
    • @dependabot use these labels will set the current labels as the default for future PRs for this repo and language
    • @dependabot use these reviewers will set the current reviewers as the default for future PRs for this repo and language
    • @dependabot use these assignees will set the current assignees as the default for future PRs for this repo and language
    • @dependabot use this milestone will set the current milestone as the default for future PRs for this repo and language

    You can disable automated security fix PRs for this repo from the Security Alerts page.

    dependencies 
    opened by dependabot[bot] 1
Owner
Yasunori Shimura
Yasunori Shimura
Automatic Attendance marker for LMS Practice School Division, BITS Pilani

LMS Attendance Marker Automatic script for lazy people to mark attendance on LMS for Practice School 1. Setup Add your LMS credentials and time slot t

Nihar Bansal 3 Jun 12, 2021
A modified version of DeepMind's Alphafold2 to divide CPU part (MSA and template searching) and GPU part (prediction model)

ParallelFold Author: Bozitao Zhong This is a modified version of DeepMind's Alphafold2 to divide CPU part (MSA and template searching) and GPU part (p

Bozitao Zhong 77 Dec 22, 2022
Running Google MoveNet Multipose Tracking models on OpenVINO.

MoveNet MultiPose Tracking on OpenVINO

null 60 Nov 17, 2022
Demonstrates iterative FGSM on Apple's NeuralHash model.

apple-neuralhash-attack Demonstrates iterative FGSM on Apple's NeuralHash model. TL;DR: It is possible to apply noise to CSAM images and make them loo

Lim Swee Kiat 11 Jun 23, 2022
Python wrapper class for OpenVINO Model Server. User can submit inference request to OVMS with just a few lines of code

Python wrapper class for OpenVINO Model Server. User can submit inference request to OVMS with just a few lines of code.

Yasunori Shimura 7 Jul 27, 2022
Provided is code that demonstrates the training and evaluation of the work presented in the paper: "On the Detection of Digital Face Manipulation" published in CVPR 2020.

FFD Source Code Provided is code that demonstrates the training and evaluation of the work presented in the paper: "On the Detection of Digital Face M

null 88 Nov 22, 2022
This project demonstrates the use of neural networks and computer vision to create a classifier that interprets the Brazilian Sign Language.

LIBRAS-Image-Classifier This project demonstrates the use of neural networks and computer vision to create a classifier that interprets the Brazilian

Aryclenio Xavier Barros 26 Oct 14, 2022
Dynamic Divide-and-Conquer Adversarial Training for Robust Semantic Segmentation (ICCV2021οΌ‰

Dynamic Divide-and-Conquer Adversarial Training for Robust Semantic Segmentation This is a pytorch project for the paper Dynamic Divide-and-Conquer Ad

DV Lab 29 Nov 21, 2022
Indoor Panorama Planar 3D Reconstruction via Divide and Conquer

HV-plane reconstruction from a single 360 image Code for our paper in CVPR 2021: Indoor Panorama Planar 3D Reconstruction via Divide and Conquer (pape

sunset 36 Jan 3, 2023