Skip to content

Commit a717110

Browse files
GeorgeARMFreddieLiardet
authored andcommitted
Generate an operator configuration file from a list of tflite models
Signed-off-by: Georgios Pinitas <georgios.pinitas@arm.com> Change-Id: I1b13da6558bd11d49747162d66c81255ccec1498 Reviewed-on: https://review.mlplatform.org/c/ml/ComputeLibrary/+/6166 Tested-by: Arm Jenkins <bsgcomp@arm.com> Reviewed-by: SiCong Li <sicong.li@arm.com> Reviewed-by: Sheri Zhang <sheri.zhang@arm.com> Comments-Addressed: Arm Jenkins <bsgcomp@arm.com>
1 parent 93d6cf0 commit a717110

8 files changed

Lines changed: 604 additions & 0 deletions

File tree

.mdl.rb

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
all
2+
rule 'MD013', :line_length => 120, :code_block_line_length => 120

.pre-commit-config.yaml

Lines changed: 53 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,53 @@
1+
fail_fast: false
2+
3+
files: ^python/
4+
repos:
5+
- repo: https://github.com/pre-commit/pre-commit-hooks
6+
rev: v4.0.1
7+
hooks:
8+
- id: check-yaml
9+
stages: [commit]
10+
- id: check-json
11+
stages: [commit]
12+
- id: end-of-file-fixer
13+
stages: [commit]
14+
exclude: \.cp?p?$
15+
- id: requirements-txt-fixer
16+
stages: [commit]
17+
- id: trailing-whitespace
18+
stages: [commit]
19+
- id: mixed-line-ending
20+
args: ['--fix=lf']
21+
description: Forces to replace line ending by the UNIX 'lf' character.
22+
- id: detect-private-key
23+
stages: [commit]
24+
- id: check-executables-have-shebangs
25+
stages: [commit]
26+
- id: check-added-large-files
27+
args: ['--maxkb=100']
28+
stages: [commit]
29+
- repo: https://github.com/asottile/reorder_python_imports
30+
rev: v2.6.0
31+
hooks:
32+
- id: reorder-python-imports
33+
args: [--py3-plus]
34+
pass_filenames: true
35+
- repo: https://github.com/psf/black
36+
rev: 21.7b0
37+
hooks:
38+
- id: black
39+
- repo: https://github.com/asottile/blacken-docs
40+
rev: v1.8.0
41+
hooks:
42+
- id: blacken-docs
43+
additional_dependencies: [black==21.7b0]
44+
- repo: https://github.com/asottile/pyupgrade
45+
rev: v2.7.2
46+
hooks:
47+
- id: pyupgrade
48+
args: [--py36-plus]
49+
- repo: https://github.com/markdownlint/markdownlint
50+
rev: v0.9.0
51+
hooks:
52+
- id: markdownlint
53+
args: ["--style", ".mdl.rb"]

python/pyproject.toml

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
[tool.black]
2+
line-length = 120
3+
exclude = '''
4+
(
5+
/(
6+
\.eggs # exclude a few common directories in the
7+
| \.git # root of the project
8+
| \.mypy_cache
9+
| \.venv
10+
| \.vscode
11+
| \.pytest_cache
12+
| build
13+
)
14+
)
15+
'''

python/requirements.txt

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
flatbuffers==2.0
2+
numpy==1.19.5
3+
tflite==2.4.0
Lines changed: 37 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,37 @@
1+
# Extract list of operators from a list of TfLite models
2+
3+
## Introduction
4+
5+
Purpose of this script is to inspect a list of user-provided TfLite models and report
6+
the list of operators that are used as well as the data-types that the models operate on.
7+
The script can subsequently generate a configuration file that can be provided to the
8+
Compute Library build system and generate a library that contains only the operators required
9+
by the given model(s) to run.
10+
11+
Utilizing this script, use-case tailored Compute Library dynamic libraries can be created,
12+
helping reduce the overall binary size requirements.
13+
14+
## Usage example
15+
16+
Assuming that the virtual environment is activated and the requirements are present,
17+
we can run the following command:
18+
19+
```bash
20+
./report_model_ops.py -m modelA.tfile modelB.tflite -c build_config.json
21+
```
22+
23+
## Input arguments
24+
25+
***models (required)*** :
26+
A list of comma separated model files.
27+
28+
Supported model formats are:
29+
30+
* TfLite
31+
32+
***config (optional)*** :
33+
The configuration file to be created on JSON format that can be provided to ComputeLibrary's
34+
build system and generate a library with the given list of operators and data-types
35+
36+
***debug (optional)*** :
37+
Flag that enables debug information
Lines changed: 188 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,188 @@
1+
#!/usr/bin/env python3
2+
# Copyright (c) 2021 Arm Limited.
3+
#
4+
# SPDX-License-Identifier: MIT
5+
#
6+
# Permission is hereby granted, free of charge, to any person obtaining a copy
7+
# of this software and associated documentation files (the "Software"), to
8+
# deal in the Software without restriction, including without limitation the
9+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
10+
# sell copies of the Software, and to permit persons to whom the Software is
11+
# furnished to do so, subject to the following conditions:
12+
#
13+
# The above copyright notice and this permission notice shall be included in all
14+
# copies or substantial portions of the Software.
15+
#
16+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
21+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
22+
# SOFTWARE.
23+
import json
24+
import logging
25+
import os
26+
import sys
27+
from argparse import ArgumentParser
28+
29+
import tflite
30+
31+
sys.path.append(os.path.dirname(os.path.abspath(__file__)) + "/../")
32+
33+
from utils.model_identification import identify_model_type
34+
from utils.tflite_helpers import tflite_op2acl, tflite_typecode2name
35+
36+
SUPPORTED_MODEL_TYPES = ["tflite"]
37+
logger = logging.getLogger("report_model_ops")
38+
39+
40+
def get_ops_from_tflite_graph(model):
41+
"""
42+
Helper function that extract operator related meta-data from a TfLite model
43+
44+
Parameters
45+
----------
46+
model: str
47+
Respective TfLite model to analyse
48+
49+
Returns
50+
----------
51+
supported_ops, unsupported_ops, data_types: tuple
52+
A tuple with the sets of unique operator types and data-types that are present in the model
53+
"""
54+
55+
logger.debug(f"Analysing TfLite mode '{model}'!")
56+
57+
with open(model, "rb") as f:
58+
buf = f.read()
59+
model = tflite.Model.GetRootAsModel(buf, 0)
60+
61+
# Extract unique operators
62+
nr_unique_ops = model.OperatorCodesLength()
63+
unique_ops = {tflite.opcode2name(model.OperatorCodes(op_id).BuiltinCode()) for op_id in range(0, nr_unique_ops)}
64+
65+
# Extract IO data-types
66+
data_types = set()
67+
for subgraph_id in range(0, model.SubgraphsLength()):
68+
subgraph = model.Subgraphs(subgraph_id)
69+
for tensor_id in range(0, subgraph.TensorsLength()):
70+
data_types.add(tflite_typecode2name(subgraph.Tensors(tensor_id).Type()))
71+
72+
# Perform mapping between TfLite ops to ComputeLibrary ones
73+
supported_ops = set()
74+
unsupported_ops = set()
75+
for top in unique_ops:
76+
try:
77+
supported_ops.add(tflite_op2acl(top))
78+
except:
79+
unsupported_ops.add(top)
80+
logger.warning(f"Operator {top} has not ComputeLibrary mapping")
81+
82+
return (supported_ops, unsupported_ops, data_types)
83+
84+
85+
def extract_model_meta(model, model_type):
86+
"""
87+
Function that calls the appropriate model parser to extract model related meta-data
88+
Supported parsers: TfLite
89+
90+
Parameters
91+
----------
92+
model: str
93+
Path to model that we want to analyze
94+
model_type:
95+
type of the model
96+
97+
Returns
98+
----------
99+
ops, data_types: (tuple)
100+
A tuple with the list of unique operator types and data-types that are present in the model
101+
"""
102+
103+
if model_type == "tflite":
104+
return get_ops_from_tflite_graph(model)
105+
else:
106+
logger.warning(f"Model type '{model_type}' is unsupported!")
107+
return ()
108+
109+
110+
def generate_build_config(ops, data_types):
111+
"""
112+
Function that generates a compatible ComputeLibrary operator-based build configuration
113+
114+
Parameters
115+
----------
116+
ops: set
117+
Set with the operators to add in the build configuration
118+
data_types:
119+
Set with the data types to add in the build configuration
120+
121+
Returns
122+
----------
123+
config_data: dict
124+
Dictionary compatible with ComputeLibrary
125+
"""
126+
config_data = {}
127+
config_data["operators"] = list(ops)
128+
config_data["data_types"] = list(data_types)
129+
130+
return config_data
131+
132+
133+
if __name__ == "__main__":
134+
parser = ArgumentParser(
135+
description="""Report map of operations in a list of models.
136+
The script consumes deep learning models and reports the type of operations and data-types used
137+
Supported model types: TfLite """
138+
)
139+
140+
parser.add_argument(
141+
"-m",
142+
"--models",
143+
nargs="+",
144+
required=True,
145+
type=str,
146+
help=f"List of models; supported model types: {SUPPORTED_MODEL_TYPES}",
147+
)
148+
parser.add_argument("-D", "--debug", action="store_true", help="Enable script debugging output")
149+
parser.add_argument(
150+
"-c",
151+
"--config",
152+
type=str,
153+
help="JSON configuration file used that can be used for custom ComputeLibrary builds",
154+
)
155+
args = parser.parse_args()
156+
157+
# Setup Logger
158+
logging_level = logging.INFO
159+
if args.debug:
160+
logging_level = logging.DEBUG
161+
logging.basicConfig(level=logging_level)
162+
163+
# Extract operator mapping
164+
final_supported_ops = set()
165+
final_unsupported_ops = set()
166+
final_dts = set()
167+
for model in args.models:
168+
logger.debug(f"Starting analyzing {model} model")
169+
170+
model_type = identify_model_type(model)
171+
supported_model_ops, unsupported_mode_ops, model_dts = extract_model_meta(model, model_type)
172+
final_supported_ops.update(supported_model_ops)
173+
final_unsupported_ops.update(unsupported_mode_ops)
174+
final_dts.update(model_dts)
175+
176+
logger.info("=== Supported Operators")
177+
logger.info(final_supported_ops)
178+
logger.info("=== Unsupported Operators")
179+
logger.info(final_unsupported_ops)
180+
logger.info("=== Data Types")
181+
logger.info(final_dts)
182+
183+
# Generate json file
184+
if args.config:
185+
logger.debug("Generating JSON build configuration file")
186+
config_data = generate_build_config(final_supported_ops, final_dts)
187+
with open(args.config, "w") as f:
188+
json.dump(config_data, f)
Lines changed: 76 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,76 @@
1+
# Copyright (c) 2021 Arm Limited.
2+
#
3+
# SPDX-License-Identifier: MIT
4+
#
5+
# Permission is hereby granted, free of charge, to any person obtaining a copy
6+
# of this software and associated documentation files (the "Software"), to
7+
# deal in the Software without restriction, including without limitation the
8+
# rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
9+
# sell copies of the Software, and to permit persons to whom the Software is
10+
# furnished to do so, subject to the following conditions:
11+
#
12+
# The above copyright notice and this permission notice shall be included in all
13+
# copies or substantial portions of the Software.
14+
#
15+
# THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16+
# IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17+
# FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18+
# AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19+
# LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20+
# OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21+
# SOFTWARE.
22+
import logging
23+
import os
24+
25+
26+
def is_tflite_model(model_path):
27+
"""Check if a model is of TfLite type
28+
29+
Parameters:
30+
----------
31+
model_path: str
32+
Path to model
33+
34+
Returns
35+
----------
36+
bool:
37+
True if given path is a valid TfLite model
38+
"""
39+
40+
try:
41+
with open(model_path, "rb") as f:
42+
hdr_bytes = f.read(8)
43+
hdr_str = hdr_bytes[4:].decode("utf-8")
44+
if hdr_str == "TFL3":
45+
return True
46+
else:
47+
return False
48+
except:
49+
return False
50+
51+
52+
def identify_model_type(model_path):
53+
"""Identify the type of a given deep learning model
54+
55+
Parameters:
56+
----------
57+
model_path: str
58+
Path to model
59+
60+
Returns
61+
----------
62+
model_type: str
63+
String representation of model type or 'None' if type could not be retrieved.
64+
"""
65+
66+
if not os.path.exists(model_path):
67+
logging.warn(f"Provided model {model_path} does not exist!")
68+
return None
69+
70+
if is_tflite_model(model_path):
71+
model_type = "tflite"
72+
else:
73+
logging.warn(logging.warn(f"Provided model {model_path} is not of supported type!"))
74+
model_type = None
75+
76+
return model_type

0 commit comments

Comments
 (0)