Imported Upstream version 1.18.0
[platform/core/ml/nnfw.git] / compiler / one-cmds / one-optimize
1 #!/usr/bin/env bash
2 ''''export SCRIPT_PATH="$(cd "$(dirname "$(readlink -f "${BASH_SOURCE[0]}")")" && pwd)" # '''
3 ''''export PY_PATH=${SCRIPT_PATH}/venv/bin/python                                       # '''
4 ''''test -f ${PY_PATH} && exec ${PY_PATH} "$0" "$@"                                     # '''
5 ''''echo "Error: Virtual environment not found. Please run 'one-prepare-venv' command." # '''
6 ''''exit 255                                                                            # '''
7
8 # Copyright (c) 2020 Samsung Electronics Co., Ltd. All Rights Reserved
9 #
10 # Licensed under the Apache License, Version 2.0 (the "License");
11 # you may not use this file except in compliance with the License.
12 # You may obtain a copy of the License at
13 #
14 #    http://www.apache.org/licenses/LICENSE-2.0
15 #
16 # Unless required by applicable law or agreed to in writing, software
17 # distributed under the License is distributed on an "AS IS" BASIS,
18 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19 # See the License for the specific language governing permissions and
20 # limitations under the License.
21
22 import argparse
23 import os
24 import subprocess
25 import sys
26
27 import utils as _utils
28
29 # TODO Find better way to suppress trackback on error
30 sys.tracebacklimit = 0
31
32
33 def _get_parser():
34     parser = argparse.ArgumentParser(
35         description='command line tool to optimize circle model')
36
37     _utils._add_default_arg(parser)
38
39     ## utility arguments
40     utility_group = parser.add_argument_group('arguments for utility')
41
42     utility_group.add_argument(
43         '-p',
44         '--generate_profile_data',
45         action='store_true',
46         help='generate profiling data')
47
48     utility_group.add_argument(
49         '--change_outputs',
50         type=str,
51         help='Experimental: Change first subgraph output nodes to CSV names')
52
53     ## circle2circle arguments
54     circle2circle_group = parser.add_argument_group('arguments for optimization')
55
56     # input and output path.
57     circle2circle_group.add_argument(
58         '-i', '--input_path', type=str, help='full filepath of the input file')
59     circle2circle_group.add_argument(
60         '-o', '--output_path', type=str, help='full filepath of the output file')
61
62     # optimization pass
63     for opt in _utils._CONSTANT.OPTIMIZATION_OPTS:
64         # opt = (option_name, help_message)
65         circle2circle_group.add_argument('--' + opt[0], action='store_true', help=opt[1])
66
67     return parser
68
69
70 def _verify_arg(parser, args):
71     """verify given arguments"""
72     # check if required arguments is given
73     missing = []
74     if not _utils._is_valid_attr(args, 'input_path'):
75         missing.append('-i/--input_path')
76     if not _utils._is_valid_attr(args, 'output_path'):
77         missing.append('-o/--output_path')
78     if len(missing):
79         parser.error('the following arguments are required: ' + ' '.join(missing))
80
81
82 def _parse_arg(parser):
83     args = parser.parse_args()
84     # print version
85     if args.version:
86         _utils._print_version_and_exit(__file__)
87
88     return args
89
90
91 def _optimize(args):
92     # get file path to log
93     dir_path = os.path.dirname(os.path.realpath(__file__))
94     logfile_path = os.path.realpath(args.output_path) + '.log'
95
96     with open(logfile_path, 'wb') as f:
97         # make a command to optimize circle model
98         circle2circle_path = os.path.join(dir_path, 'circle2circle')
99         circle2circle_cmd = _utils._make_circle2circle_cmd(args, circle2circle_path,
100                                                            getattr(args, 'input_path'),
101                                                            getattr(args, 'output_path'))
102
103         # verbose
104         if _utils._is_valid_attr(args, 'verbose'):
105             circle2circle_cmd.append('--verbose')
106         if _utils._is_valid_attr(args, 'change_outputs'):
107             circle2circle_cmd.append('--change_outputs')
108             circle2circle_cmd.append(getattr(args, 'change_outputs'))
109
110         f.write((' '.join(circle2circle_cmd) + '\n').encode())
111
112         # optimize
113         _utils._run(circle2circle_cmd, err_prefix="circle2circle", logfile=f)
114
115
116 def main():
117     # parse arguments
118     parser = _get_parser()
119     args = _parse_arg(parser)
120
121     # parse configuration file
122     _utils._parse_cfg(args, 'one-optimize')
123
124     # verify arguments
125     _verify_arg(parser, args)
126
127     # optimize
128     _optimize(args)
129
130
131 if __name__ == '__main__':
132     _utils._safemain(main, __file__)