aboutsummaryrefslogtreecommitdiff
path: root/src/mlia/cli/commands.py
blob: 45c7c32396b977f25a4a007679eee200687b743b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
# SPDX-FileCopyrightText: Copyright 2022, Arm Limited and/or its affiliates.
# SPDX-License-Identifier: Apache-2.0
"""CLI commands module.

This module contains functions which implement main app
functionality.

Before running them from scripts 'logging' module should
be configured. Function 'setup_logging' from module
'mli.cli.logging' could be used for that, e.g.

>>> from mlia.api import ExecutionContext
>>> from mlia.cli.logging import setup_logging
>>> setup_logging(verbose=True)
>>> import mlia.cli.commands as mlia
>>> mlia.all_tests(ExecutionContext(working_dir="mlia_output"), "ethos-u55-256",
                   "path/to/model")
"""
import logging
from pathlib import Path
from typing import cast
from typing import List
from typing import Optional

from mlia.api import ExecutionContext
from mlia.api import get_advice
from mlia.api import PathOrFileLike
from mlia.cli.config import get_installation_manager
from mlia.cli.options import parse_optimization_parameters
from mlia.devices.ethosu.operators import generate_supported_operators_report
from mlia.utils.console import create_section_header
from mlia.utils.types import only_one_selected

logger = logging.getLogger(__name__)

CONFIG = create_section_header("ML Inference Advisor configuration")


def all_tests(
    ctx: ExecutionContext,
    target_profile: str,
    model: str,
    optimization_type: str = "pruning,clustering",
    optimization_target: str = "0.5,32",
    output: Optional[PathOrFileLike] = None,
    evaluate_on: Optional[List[str]] = None,
) -> None:
    """Generate a full report on the input model.

    This command runs a series of tests in order to generate a
    comprehensive report/advice:

        - converts the input Keras model into TFLite format
        - checks the model for operator compatibility on the specified device
        - applies optimizations to the model and estimates the resulting performance
          on both the original and the optimized models
        - generates a final report on the steps above
        - provides advice on how to (possibly) improve the inference performance

    :param ctx: execution context
    :param target_profile: target profile identifier. Will load appropriate parameters
            from the profile.json file based on this argument.
    :param model: path to the Keras model
    :param optimization_type: list of the optimization techniques separated
           by comma, e.g. 'pruning,clustering'
    :param optimization_target: list of the corresponding targets for
           the provided optimization techniques, e.g. '0.5,32'
    :param output: path to the file where the report will be saved
    :param evaluate_on: list of the backends to use for evaluation

    Example:
        Run command for the target profile ethos-u55-256 with two model optimizations
        and save report in json format locally in the file report.json

        >>> from mlia.api import ExecutionContext
        >>> from mlia.cli.logging import setup_logging
        >>> setup_logging()
        >>> from mlia.cli.commands import all_tests
        >>> all_tests(ExecutionContext(working_dir="mlia_output"), "ethos-u55-256",
                      "model.h5", "pruning,clustering", "0.5,32",
                       output="report.json")
    """
    opt_params = parse_optimization_parameters(
        optimization_type,
        optimization_target,
    )

    get_advice(
        target_profile,
        model,
        "all",
        optimization_targets=opt_params,
        output=output,
        context=ctx,
        backends=evaluate_on,
    )


def operators(
    ctx: ExecutionContext,
    target_profile: str,
    model: Optional[str] = None,
    output: Optional[PathOrFileLike] = None,
    supported_ops_report: bool = False,
) -> None:
    """Print the model's operator list.

    This command checks the operator compatibility of the input model with
    the specific target profile. Generates a report of the operator placement
    (NPU or CPU fallback) and advice on how to improve it (if necessary).

    :param ctx: execution context
    :param target_profile: target profile identifier. Will load appropriate parameters
            from the profile.json file based on this argument.
    :param model: path to the model, which can be TFLite or Keras
    :param output: path to the file where the report will be saved
    :param supported_ops_report: if True then generates supported operators
           report in current directory and exits

    Example:
        Run command for the target profile ethos-u55-256 and the provided
        TFLite model and print report on the standard output

        >>> from mlia.api import ExecutionContext
        >>> from mlia.cli.logging import setup_logging
        >>> setup_logging()
        >>> from mlia.cli.commands import operators
        >>> operators(ExecutionContext(working_dir="mlia_output"), "ethos-u55-256",
                      "model.tflite")
    """
    if supported_ops_report:
        generate_supported_operators_report()
        logger.info("Report saved into SUPPORTED_OPS.md")
        return

    if not model:
        raise Exception("Model is not provided")

    get_advice(
        target_profile,
        model,
        "operators",
        output=output,
        context=ctx,
    )


def performance(
    ctx: ExecutionContext,
    target_profile: str,
    model: str,
    output: Optional[PathOrFileLike] = None,
    evaluate_on: Optional[List[str]] = None,
) -> None:
    """Print the model's performance stats.

    This command estimates the inference performance of the input model
    on the specified target profile, and generates a report with advice on how
    to improve it.

    :param ctx: execution context
    :param target_profile: target profile identifier. Will load appropriate parameters
            from the profile.json file based on this argument.
    :param model: path to the model, which can be TFLite or Keras
    :param output: path to the file where the report will be saved
    :param evaluate_on: list of the backends to use for evaluation

    Example:
        Run command for the target profile ethos-u55-256 and
        the provided TFLite model and print report on the standard output

        >>> from mlia.api import ExecutionContext
        >>> from mlia.cli.logging import setup_logging
        >>> setup_logging()
        >>> from mlia.cli.commands import performance
        >>> performance(ExecutionContext(working_dir="mlia_output"), "ethos-u55-256",
                        "model.tflite")
    """
    get_advice(
        target_profile,
        model,
        "performance",
        output=output,
        context=ctx,
        backends=evaluate_on,
    )


def optimization(
    ctx: ExecutionContext,
    target_profile: str,
    model: str,
    optimization_type: str,
    optimization_target: str,
    layers_to_optimize: Optional[List[str]] = None,
    output: Optional[PathOrFileLike] = None,
    evaluate_on: Optional[List[str]] = None,
) -> None:
    """Show the performance improvements (if any) after applying the optimizations.

    This command applies the selected optimization techniques (up to the
    indicated targets) and generates a report with advice on how to improve
    the inference performance (if possible).

    :param ctx: execution context
    :param target: target profile identifier. Will load appropriate parameters
            from the profile.json file based on this argument.
    :param model: path to the TFLite model
    :param optimization_type: list of the optimization techniques separated
           by comma, e.g. 'pruning,clustering'
    :param optimization_target: list of the corresponding targets for
           the provided optimization techniques, e.g. '0.5,32'
    :param layers_to_optimize: list of the layers of the model which should be
           optimized, if None then all layers are used
    :param output: path to the file where the report will be saved
    :param evaluate_on: list of the backends to use for evaluation

    Example:
        Run command for the target profile ethos-u55-256 and
        the provided TFLite model and print report on the standard output

        >>> from mlia.cli.logging import setup_logging
        >>> setup_logging()
        >>> from mlia.cli.commands import optimization
        >>> optimization(ExecutionContext(working_dir="mlia_output"),
                         target="ethos-u55-256",
                         "model.tflite", "pruning", "0.5")
    """
    opt_params = parse_optimization_parameters(
        optimization_type,
        optimization_target,
        layers_to_optimize=layers_to_optimize,
    )

    get_advice(
        target_profile,
        model,
        "optimization",
        optimization_targets=opt_params,
        output=output,
        context=ctx,
        backends=evaluate_on,
    )


def backend(
    backend_action: str,
    path: Optional[Path] = None,
    download: bool = False,
    name: Optional[str] = None,
    i_agree_to_the_contained_eula: bool = False,
    noninteractive: bool = False,
) -> None:
    """Backends configuration."""
    logger.info(CONFIG)

    manager = get_installation_manager(noninteractive)

    if backend_action == "status":
        manager.show_env_details()

    if backend_action == "install":
        install_from_path = path is not None

        if not only_one_selected(install_from_path, download):
            raise Exception(
                "Please select only one action: download or "
                "provide path to the backend installation"
            )

        if install_from_path:
            manager.install_from(cast(Path, path), name)

        if download:
            eula_agreement = not i_agree_to_the_contained_eula
            manager.download_and_install(name, eula_agreement)