20import importlib.machinery
27from typing
import Union, Optional
29from onelib.argumentparse
import ArgumentParser
31Support commands in the one-cmds.
41 'import':
'Convert given model to circle',
42 'optimize':
'Optimize circle model',
43 'quantize':
'Quantize circle model',
46 'pack':
'Package circle and metadata into nnpackage',
49 'codegen':
'Code generation tool',
50 'profile':
'Profile backend model file',
51 'infer':
'Infer backend model file'
57 return [cmd
for group, cmds
in ONE_CMD.items()
for cmd
in cmds.keys()]
62 parser.add_argument(
'-v',
65 help=
'show program\'s version number and exit')
68 parser.add_argument(
'-V',
71 help=
'output additional information to stdout or stderr')
74 parser.add_argument(
'-C',
'--config', type=str, help=
'run with configuation file')
76 parser.add_argument(
'-S',
'--section', type=str, help=argparse.SUPPRESS)
81 This adds -v -V args only (no -C nor -S)
84 parser.add_argument(
'-v',
87 help=
'show program\'s version number and exit')
90 parser.add_argument(
'-V',
93 help=
'output additional information to stdout or stderr')
97 if driver ==
"one-quantize":
99 "tensor_name",
"scale",
"zero_point",
"src_tensor_name",
"dst_tensor_name"
101 if arg
in accumulables:
108 return hasattr(args, attr)
and getattr(args, attr)
113 Initialize configparser and set default option
115 This funciton has been introduced for all the one-cmds tools having same parsing option.
117 parser = configparser.ConfigParser(inline_comment_prefixes=(
'#',
';'))
118 parser.optionxform = str
124 section_to_parse: str,
126 quiet: bool =
False):
128 parse configuration file and store the information to args
130 :param config_path: path to configuration file
131 :param section_to_parse: section name to parse
132 :param args: object to store the parsed information
133 :param quiet: raise no error when given section doesn't exist
135 if config_path
is None:
139 parser.read(config_path)
141 if not parser.has_section(section_to_parse)
and quiet:
144 if not parser.has_section(section_to_parse):
145 raise AssertionError(
'configuration file must have \'' + section_to_parse +
149 CFG_ENV_SECTION =
'Environment'
150 if parser.has_section(CFG_ENV_SECTION):
151 for key
in parser[CFG_ENV_SECTION]:
152 os.environ[key] = parser[CFG_ENV_SECTION][key]
154 for key
in parser[section_to_parse]:
157 setattr(args, key, [parser[section_to_parse][key]])
159 getattr(args, key).append(parser[section_to_parse][key])
161 if hasattr(args, key)
and getattr(args, key):
163 setattr(args, key, parser[section_to_parse][key])
167 """print version of the file located in the file_path"""
168 script_path = os.path.realpath(file_path)
169 dir_path = os.path.dirname(script_path)
170 script_name = os.path.splitext(os.path.basename(script_path))[0]
172 subprocess.call([os.path.join(dir_path,
'one-version'), script_name])
177 """execute given method and print with program name for all uncaught exceptions"""
180 except Exception
as e:
181 prog_name = os.path.basename(mainpath)
182 print(f
"{prog_name}: {type(e).__name__}: " + str(e), file=sys.stderr)
186def run_ret(cmd, *, one_cmd: str =
None, err_prefix=
None, logfile=
None):
187 """Execute command in subprocess
190 one_cmd: subtool name to execute with given `cmd`
191 cmd: command to be executed in subprocess
192 err_prefix: prefix to be put before every stderr lines
193 logfile: file stream to which both of stdout and stderr lines will be written
195 Process execution return code; 0 if success and others for error.
198 assert one_cmd
in one_cmd_list(), f
'Invalid ONE COMMAND: {one_cmd}'
199 dir_path = os.path.dirname(os.path.dirname(
200 os.path.realpath(__file__)))
201 driver_path = os.path.join(dir_path, f
'one-{one_cmd}')
202 cmd = [driver_path] + cmd
204 with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
as p:
206 inputs = set([p.stdout, p.stderr])
208 readable, _, _ = select.select(inputs, [], [])
219 line = f
"{err_prefix}: ".encode() + line
220 out.buffer.write(line)
228def run(cmd, *, one_cmd: str =
None, err_prefix=
None, logfile=
None):
229 """Execute command in subprocess
232 one_cmd: subtool name to execute with given `cmd`
233 cmd: command to be executed in subprocess
234 err_prefix: prefix to be put before every stderr lines
235 logfile: file stream to which both of stdout and stderr lines will be written
238 assert one_cmd
in one_cmd_list(), f
'Invalid ONE COMMAND: {one_cmd}'
239 dir_path = os.path.dirname(os.path.dirname(
240 os.path.realpath(__file__)))
241 driver_path = os.path.join(dir_path, f
'one-{one_cmd}')
242 cmd = [driver_path] + cmd
244 with subprocess.Popen(cmd, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
as p:
246 inputs = set([p.stdout, p.stderr])
248 readable, _, _ = select.select(inputs, [], [])
259 line = f
"{err_prefix}: ".encode() + line
260 out.buffer.write(line)
264 if p.returncode != 0:
265 sys.exit(p.returncode)
269 if str.startswith(prefix):
270 return str[len(prefix):]
275 if str.endswith(suffix):
276 return str[:-len(suffix)]
282 returns a list of optimization. If `get_name` is True,
283 only basename without extension is returned rather than full file path.
295 Optimization options must be placed in `optimization` folder
297 dir_path = os.path.dirname(os.path.realpath(__file__))
301 f
for f
in glob.glob(dir_path +
'/../../optimization/O*.cfg', recursive=
True)
304 files = [s
for s
in files
if not ' ' in s]
308 base = ntpath.basename(cand)
309 if os.path.isfile(cand)
and os.access(cand, os.R_OK):
310 opt_list.append(cand)
315 opt_list = [ntpath.basename(f)
for f
in opt_list]
323 returns a list of targets. If `get_name` is True,
324 only basename without extension is returned rather than full file path.
337 Target configuration files must be placed in `target` folder
339 dir_path = os.path.dirname(os.path.realpath(__file__))
342 files = [f
for f
in glob.glob(dir_path +
'/../../target/*.ini', recursive=
True)]
344 files = [s
for s
in files
if not ' ' in s]
348 if os.path.isfile(cand)
and os.access(cand, os.R_OK):
349 target_list.append(cand)
352 target_list = [ntpath.basename(f)
for f
in target_list]
353 target_list = [
remove_suffix(s,
'.ini')
for s
in target_list]
359 target: Optional[str]) -> Optional[ArgumentParser]:
363 dir_path = os.path.dirname(os.path.realpath(__file__))
365 command_schema_path = dir_path + f
'/../../backends/command/{backend}/{cmd}.py'
366 if not os.path.isfile(command_schema_path):
370 spec = importlib.util.spec_from_file_location(cmd, command_schema_path)
371 module = importlib.util.module_from_spec(spec)
372 sys.modules[cmd] = module
373 spec.loader.exec_module(module)
375 if not hasattr(module,
"command_schema"):
376 raise RuntimeError(
'You must implement "command_schema" function')
378 parser: ArgumentParser = module.command_schema()
379 parser.target = target
384 """Looks for import drivers in given directory
387 search_path: path to the directory where to search import drivers
390 dict: each entry is related to single detected driver,
391 key is a config section name, value is a driver name
394 import_drivers_dict = {}
395 for module_name
in os.listdir(search_path):
396 full_path = os.path.join(search_path, module_name)
397 if not os.path.isfile(full_path):
399 if module_name.find(
"one-import-") != 0:
401 module_loader = importlib.machinery.SourceFileLoader(module_name, full_path)
402 module_spec = importlib.util.spec_from_loader(module_name, module_loader)
403 module = importlib.util.module_from_spec(module_spec)
405 module_loader.exec_module(module)
406 if hasattr(module,
"get_driver_cfg_section"):
407 section = module.get_driver_cfg_section()
408 import_drivers_dict[section] = module_name
411 return import_drivers_dict
Optional[ArgumentParser] get_arg_parser(Optional[str] backend, str cmd, Optional[str] target)
add_default_arg_no_CS(parser)
remove_suffix(str, suffix)
configparser.ConfigParser get_config_parser()
get_target_list(get_name=False)
run_ret(cmd, *str one_cmd=None, err_prefix=None, logfile=None)
is_accumulated_arg(arg, driver)
get_optimization_list(get_name=False)
print_version_and_exit(file_path)
detect_one_import_drivers(search_path)
is_valid_attr(args, attr)
parse_cfg(Union[str, None] config_path, str section_to_parse, args, bool quiet=False)
remove_prefix(str, prefix)
run(cmd, *str one_cmd=None, err_prefix=None, logfile=None)