Imported Upstream version 1.19.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     # optimization option from one-build
68     parser.add_argument('-O', type=str, help=argparse.SUPPRESS)
69
70     return parser
71
72
73 def _verify_arg(parser, args):
74     """verify given arguments"""
75     # check if required arguments is given
76     missing = []
77     if not _utils._is_valid_attr(args, 'input_path'):
78         missing.append('-i/--input_path')
79     if not _utils._is_valid_attr(args, 'output_path'):
80         missing.append('-o/--output_path')
81     if len(missing):
82         parser.error('the following arguments are required: ' + ' '.join(missing))
83
84
85 def _parse_arg(parser):
86     args = parser.parse_args()
87     # print version
88     if args.version:
89         _utils._print_version_and_exit(__file__)
90
91     return args
92
93
94 def _optimize(args):
95     # get file path to log
96     dir_path = os.path.dirname(os.path.realpath(__file__))
97     logfile_path = os.path.realpath(args.output_path) + '.log'
98
99     with open(logfile_path, 'wb') as f:
100         # make a command to optimize circle model
101         circle2circle_path = os.path.join(dir_path, 'circle2circle')
102         circle2circle_cmd = _utils._make_circle2circle_cmd(args, circle2circle_path,
103                                                            getattr(args, 'input_path'),
104                                                            getattr(args, 'output_path'))
105
106         # verbose
107         if _utils._is_valid_attr(args, 'verbose'):
108             circle2circle_cmd.append('--verbose')
109         if _utils._is_valid_attr(args, 'change_outputs'):
110             circle2circle_cmd.append('--change_outputs')
111             circle2circle_cmd.append(getattr(args, 'change_outputs'))
112
113         f.write((' '.join(circle2circle_cmd) + '\n').encode())
114
115         # optimize
116         _utils._run(circle2circle_cmd, err_prefix="circle2circle", logfile=f)
117
118
119 def _parse_opt(args):
120     if _utils._is_valid_attr(args, 'O'):
121         opt_name_path_dic = dict(
122             zip(_utils._get_optimization_list(get_name=True),
123                 _utils._get_optimization_list()))
124         config_path = opt_name_path_dic['O' + getattr(args, 'O')]
125         _utils._parse_cfg_and_overwrite(config_path, 'one-optimize', args)
126
127
128 def main():
129     # parse arguments
130     parser = _get_parser()
131     args = _parse_arg(parser)
132
133     # parse configuration file
134     _utils._parse_cfg(args, 'one-optimize')
135
136     # parse optimization file
137     # NOTE if there is a `one-optimize` section in above configuration file as well,
138     # it will be overwritten
139     _parse_opt(args)
140
141     # verify arguments
142     _verify_arg(parser, args)
143
144     # optimize
145     _optimize(args)
146
147
148 if __name__ == '__main__':
149     _utils._safemain(main, __file__)