Nelze vybrat více než 25 témat Téma musí začínat písmenem nebo číslem, může obsahovat pomlčky („-“) a může být dlouhé až 35 znaků.

486 lines
22KB

  1. # YOLOv5 🚀 by Ultralytics, GPL-3.0 license
  2. """
  3. Export a YOLOv5 PyTorch model to other formats. TensorFlow exports authored by https://github.com/zldrobit
  4. Format | Example | `--include ...` argument
  5. --- | --- | ---
  6. PyTorch | yolov5s.pt | -
  7. TorchScript | yolov5s.torchscript | `torchscript`
  8. ONNX | yolov5s.onnx | `onnx`
  9. CoreML | yolov5s.mlmodel | `coreml`
  10. OpenVINO | yolov5s_openvino_model/ | `openvino`
  11. TensorFlow SavedModel | yolov5s_saved_model/ | `saved_model`
  12. TensorFlow GraphDef | yolov5s.pb | `pb`
  13. TensorFlow Lite | yolov5s.tflite | `tflite`
  14. TensorFlow.js | yolov5s_web_model/ | `tfjs`
  15. TensorRT | yolov5s.engine | `engine`
  16. Usage:
  17. $ python path/to/export.py --weights yolov5s.pt --include torchscript onnx coreml openvino saved_model tflite tfjs
  18. Inference:
  19. $ python path/to/detect.py --weights yolov5s.pt
  20. yolov5s.torchscript
  21. yolov5s.onnx
  22. yolov5s.mlmodel (under development)
  23. yolov5s_openvino_model (under development)
  24. yolov5s_saved_model
  25. yolov5s.pb
  26. yolov5s.tflite
  27. yolov5s.engine
  28. TensorFlow.js:
  29. $ cd .. && git clone https://github.com/zldrobit/tfjs-yolov5-example.git && cd tfjs-yolov5-example
  30. $ npm install
  31. $ ln -s ../../yolov5/yolov5s_web_model public/yolov5s_web_model
  32. $ npm start
  33. """
  34. import argparse
  35. import json
  36. import os
  37. import subprocess
  38. import sys
  39. import time
  40. from pathlib import Path
  41. import torch
  42. import torch.nn as nn
  43. from torch.utils.mobile_optimizer import optimize_for_mobile
  44. FILE = Path(__file__).resolve()
  45. ROOT = FILE.parents[0] # YOLOv5 root directory
  46. if str(ROOT) not in sys.path:
  47. sys.path.append(str(ROOT)) # add ROOT to PATH
  48. ROOT = Path(os.path.relpath(ROOT, Path.cwd())) # relative
  49. from models.common import Conv
  50. from models.experimental import attempt_load
  51. from models.yolo import Detect
  52. from utils.activations import SiLU
  53. from utils.datasets import LoadImages
  54. from utils.general import (LOGGER, check_dataset, check_img_size, check_requirements, colorstr, file_size, print_args,
  55. url2file)
  56. from utils.torch_utils import select_device
  57. def export_torchscript(model, im, file, optimize, prefix=colorstr('TorchScript:')):
  58. # YOLOv5 TorchScript model export
  59. try:
  60. LOGGER.info(f'\n{prefix} starting export with torch {torch.__version__}...')
  61. f = file.with_suffix('.torchscript')
  62. ts = torch.jit.trace(model, im, strict=False)
  63. d = {"shape": im.shape, "stride": int(max(model.stride)), "names": model.names}
  64. extra_files = {'config.txt': json.dumps(d)} # torch._C.ExtraFilesMap()
  65. (optimize_for_mobile(ts) if optimize else ts).save(str(f), _extra_files=extra_files)
  66. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  67. except Exception as e:
  68. LOGGER.info(f'{prefix} export failure: {e}')
  69. def export_onnx(model, im, file, opset, train, dynamic, simplify, prefix=colorstr('ONNX:')):
  70. # YOLOv5 ONNX export
  71. try:
  72. check_requirements(('onnx',))
  73. import onnx
  74. LOGGER.info(f'\n{prefix} starting export with onnx {onnx.__version__}...')
  75. f = file.with_suffix('.onnx')
  76. torch.onnx.export(model, im, f, verbose=False, opset_version=opset,
  77. training=torch.onnx.TrainingMode.TRAINING if train else torch.onnx.TrainingMode.EVAL,
  78. do_constant_folding=not train,
  79. input_names=['images'],
  80. output_names=['output'],
  81. dynamic_axes={'images': {0: 'batch', 2: 'height', 3: 'width'}, # shape(1,3,640,640)
  82. 'output': {0: 'batch', 1: 'anchors'} # shape(1,25200,85)
  83. } if dynamic else None)
  84. # Checks
  85. model_onnx = onnx.load(f) # load onnx model
  86. onnx.checker.check_model(model_onnx) # check onnx model
  87. # LOGGER.info(onnx.helper.printable_graph(model_onnx.graph)) # print
  88. # Simplify
  89. if simplify:
  90. try:
  91. check_requirements(('onnx-simplifier',))
  92. import onnxsim
  93. LOGGER.info(f'{prefix} simplifying with onnx-simplifier {onnxsim.__version__}...')
  94. model_onnx, check = onnxsim.simplify(
  95. model_onnx,
  96. dynamic_input_shape=dynamic,
  97. input_shapes={'images': list(im.shape)} if dynamic else None)
  98. assert check, 'assert check failed'
  99. onnx.save(model_onnx, f)
  100. except Exception as e:
  101. LOGGER.info(f'{prefix} simplifier failure: {e}')
  102. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  103. LOGGER.info(f"{prefix} run --dynamic ONNX model inference with: 'python detect.py --weights {f}'")
  104. except Exception as e:
  105. LOGGER.info(f'{prefix} export failure: {e}')
  106. def export_coreml(model, im, file, prefix=colorstr('CoreML:')):
  107. # YOLOv5 CoreML export
  108. ct_model = None
  109. try:
  110. check_requirements(('coremltools',))
  111. import coremltools as ct
  112. LOGGER.info(f'\n{prefix} starting export with coremltools {ct.__version__}...')
  113. f = file.with_suffix('.mlmodel')
  114. model.train() # CoreML exports should be placed in model.train() mode
  115. ts = torch.jit.trace(model, im, strict=False) # TorchScript model
  116. ct_model = ct.convert(ts, inputs=[ct.ImageType('image', shape=im.shape, scale=1 / 255, bias=[0, 0, 0])])
  117. ct_model.save(f)
  118. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  119. except Exception as e:
  120. LOGGER.info(f'\n{prefix} export failure: {e}')
  121. return ct_model
  122. def export_openvino(model, im, file, prefix=colorstr('OpenVINO:')):
  123. # YOLOv5 OpenVINO export
  124. try:
  125. check_requirements(('openvino-dev',)) # requires openvino-dev: https://pypi.org/project/openvino-dev/
  126. import openvino.inference_engine as ie
  127. LOGGER.info(f'\n{prefix} starting export with openvino {ie.__version__}...')
  128. f = str(file).replace('.pt', '_openvino_model' + os.sep)
  129. cmd = f"mo --input_model {file.with_suffix('.onnx')} --output_dir {f}"
  130. subprocess.check_output(cmd, shell=True)
  131. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  132. except Exception as e:
  133. LOGGER.info(f'\n{prefix} export failure: {e}')
  134. def export_saved_model(model, im, file, dynamic,
  135. tf_nms=False, agnostic_nms=False, topk_per_class=100, topk_all=100, iou_thres=0.45,
  136. conf_thres=0.25, prefix=colorstr('TensorFlow saved_model:')):
  137. # YOLOv5 TensorFlow saved_model export
  138. keras_model = None
  139. try:
  140. import tensorflow as tf
  141. from tensorflow import keras
  142. from models.tf import TFDetect, TFModel
  143. LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
  144. f = str(file).replace('.pt', '_saved_model')
  145. batch_size, ch, *imgsz = list(im.shape) # BCHW
  146. tf_model = TFModel(cfg=model.yaml, model=model, nc=model.nc, imgsz=imgsz)
  147. im = tf.zeros((batch_size, *imgsz, 3)) # BHWC order for TensorFlow
  148. y = tf_model.predict(im, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
  149. inputs = keras.Input(shape=(*imgsz, 3), batch_size=None if dynamic else batch_size)
  150. outputs = tf_model.predict(inputs, tf_nms, agnostic_nms, topk_per_class, topk_all, iou_thres, conf_thres)
  151. keras_model = keras.Model(inputs=inputs, outputs=outputs)
  152. keras_model.trainable = False
  153. keras_model.summary()
  154. keras_model.save(f, save_format='tf')
  155. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  156. except Exception as e:
  157. LOGGER.info(f'\n{prefix} export failure: {e}')
  158. return keras_model
  159. def export_pb(keras_model, im, file, prefix=colorstr('TensorFlow GraphDef:')):
  160. # YOLOv5 TensorFlow GraphDef *.pb export https://github.com/leimao/Frozen_Graph_TensorFlow
  161. try:
  162. import tensorflow as tf
  163. from tensorflow.python.framework.convert_to_constants import convert_variables_to_constants_v2
  164. LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
  165. f = file.with_suffix('.pb')
  166. m = tf.function(lambda x: keras_model(x)) # full model
  167. m = m.get_concrete_function(tf.TensorSpec(keras_model.inputs[0].shape, keras_model.inputs[0].dtype))
  168. frozen_func = convert_variables_to_constants_v2(m)
  169. frozen_func.graph.as_graph_def()
  170. tf.io.write_graph(graph_or_graph_def=frozen_func.graph, logdir=str(f.parent), name=f.name, as_text=False)
  171. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  172. except Exception as e:
  173. LOGGER.info(f'\n{prefix} export failure: {e}')
  174. def export_tflite(keras_model, im, file, int8, data, ncalib, prefix=colorstr('TensorFlow Lite:')):
  175. # YOLOv5 TensorFlow Lite export
  176. try:
  177. import tensorflow as tf
  178. from models.tf import representative_dataset_gen
  179. LOGGER.info(f'\n{prefix} starting export with tensorflow {tf.__version__}...')
  180. batch_size, ch, *imgsz = list(im.shape) # BCHW
  181. f = str(file).replace('.pt', '-fp16.tflite')
  182. converter = tf.lite.TFLiteConverter.from_keras_model(keras_model)
  183. converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS]
  184. converter.target_spec.supported_types = [tf.float16]
  185. converter.optimizations = [tf.lite.Optimize.DEFAULT]
  186. if int8:
  187. dataset = LoadImages(check_dataset(data)['train'], img_size=imgsz, auto=False) # representative data
  188. converter.representative_dataset = lambda: representative_dataset_gen(dataset, ncalib)
  189. converter.target_spec.supported_ops = [tf.lite.OpsSet.TFLITE_BUILTINS_INT8]
  190. converter.target_spec.supported_types = []
  191. converter.inference_input_type = tf.uint8 # or tf.int8
  192. converter.inference_output_type = tf.uint8 # or tf.int8
  193. converter.experimental_new_quantizer = False
  194. f = str(file).replace('.pt', '-int8.tflite')
  195. tflite_model = converter.convert()
  196. open(f, "wb").write(tflite_model)
  197. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  198. except Exception as e:
  199. LOGGER.info(f'\n{prefix} export failure: {e}')
  200. def export_edgetpu(keras_model, im, file, prefix=colorstr('Edge TPU:')):
  201. # YOLOv5 Edge TPU export https://coral.ai/docs/edgetpu/models-intro/
  202. try:
  203. cmd = 'edgetpu_compiler --version'
  204. out = subprocess.run(cmd, shell=True, capture_output=True, check=True)
  205. ver = out.stdout.decode().split()[-1]
  206. LOGGER.info(f'\n{prefix} starting export with Edge TPU compiler {ver}...')
  207. f = str(file).replace('.pt', '-int8_edgetpu.tflite')
  208. f_tfl = str(file).replace('.pt', '-int8.tflite') # TFLite model
  209. cmd = f"edgetpu_compiler -s {f_tfl}"
  210. subprocess.run(cmd, shell=True, check=True)
  211. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  212. except Exception as e:
  213. LOGGER.info(f'\n{prefix} export failure: {e}')
  214. def export_tfjs(keras_model, im, file, prefix=colorstr('TensorFlow.js:')):
  215. # YOLOv5 TensorFlow.js export
  216. try:
  217. check_requirements(('tensorflowjs',))
  218. import re
  219. import tensorflowjs as tfjs
  220. LOGGER.info(f'\n{prefix} starting export with tensorflowjs {tfjs.__version__}...')
  221. f = str(file).replace('.pt', '_web_model') # js dir
  222. f_pb = file.with_suffix('.pb') # *.pb path
  223. f_json = f + '/model.json' # *.json path
  224. cmd = f"tensorflowjs_converter --input_format=tf_frozen_model " \
  225. f"--output_node_names='Identity,Identity_1,Identity_2,Identity_3' {f_pb} {f}"
  226. subprocess.run(cmd, shell=True)
  227. json = open(f_json).read()
  228. with open(f_json, 'w') as j: # sort JSON Identity_* in ascending order
  229. subst = re.sub(
  230. r'{"outputs": {"Identity.?.?": {"name": "Identity.?.?"}, '
  231. r'"Identity.?.?": {"name": "Identity.?.?"}, '
  232. r'"Identity.?.?": {"name": "Identity.?.?"}, '
  233. r'"Identity.?.?": {"name": "Identity.?.?"}}}',
  234. r'{"outputs": {"Identity": {"name": "Identity"}, '
  235. r'"Identity_1": {"name": "Identity_1"}, '
  236. r'"Identity_2": {"name": "Identity_2"}, '
  237. r'"Identity_3": {"name": "Identity_3"}}}',
  238. json)
  239. j.write(subst)
  240. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  241. except Exception as e:
  242. LOGGER.info(f'\n{prefix} export failure: {e}')
  243. def export_engine(model, im, file, train, half, simplify, workspace=4, verbose=False, prefix=colorstr('TensorRT:')):
  244. # YOLOv5 TensorRT export https://developer.nvidia.com/tensorrt
  245. try:
  246. check_requirements(('tensorrt',))
  247. import tensorrt as trt
  248. opset = (12, 13)[trt.__version__[0] == '8'] # test on TensorRT 7.x and 8.x
  249. export_onnx(model, im, file, opset, train, False, simplify)
  250. onnx = file.with_suffix('.onnx')
  251. assert onnx.exists(), f'failed to export ONNX file: {onnx}'
  252. LOGGER.info(f'\n{prefix} starting export with TensorRT {trt.__version__}...')
  253. f = file.with_suffix('.engine') # TensorRT engine file
  254. logger = trt.Logger(trt.Logger.INFO)
  255. if verbose:
  256. logger.min_severity = trt.Logger.Severity.VERBOSE
  257. builder = trt.Builder(logger)
  258. config = builder.create_builder_config()
  259. config.max_workspace_size = workspace * 1 << 30
  260. flag = (1 << int(trt.NetworkDefinitionCreationFlag.EXPLICIT_BATCH))
  261. network = builder.create_network(flag)
  262. parser = trt.OnnxParser(network, logger)
  263. if not parser.parse_from_file(str(onnx)):
  264. raise RuntimeError(f'failed to load ONNX file: {onnx}')
  265. inputs = [network.get_input(i) for i in range(network.num_inputs)]
  266. outputs = [network.get_output(i) for i in range(network.num_outputs)]
  267. LOGGER.info(f'{prefix} Network Description:')
  268. for inp in inputs:
  269. LOGGER.info(f'{prefix}\tinput "{inp.name}" with shape {inp.shape} and dtype {inp.dtype}')
  270. for out in outputs:
  271. LOGGER.info(f'{prefix}\toutput "{out.name}" with shape {out.shape} and dtype {out.dtype}')
  272. half &= builder.platform_has_fast_fp16
  273. LOGGER.info(f'{prefix} building FP{16 if half else 32} engine in {f}')
  274. if half:
  275. config.set_flag(trt.BuilderFlag.FP16)
  276. with builder.build_engine(network, config) as engine, open(f, 'wb') as t:
  277. t.write(engine.serialize())
  278. LOGGER.info(f'{prefix} export success, saved as {f} ({file_size(f):.1f} MB)')
  279. except Exception as e:
  280. LOGGER.info(f'\n{prefix} export failure: {e}')
  281. @torch.no_grad()
  282. def run(data=ROOT / 'data/coco128.yaml', # 'dataset.yaml path'
  283. weights=ROOT / 'yolov5s.pt', # weights path
  284. imgsz=(640, 640), # image (height, width)
  285. batch_size=1, # batch size
  286. device='cpu', # cuda device, i.e. 0 or 0,1,2,3 or cpu
  287. include=('torchscript', 'onnx'), # include formats
  288. half=False, # FP16 half-precision export
  289. inplace=False, # set YOLOv5 Detect() inplace=True
  290. train=False, # model.train() mode
  291. optimize=False, # TorchScript: optimize for mobile
  292. int8=False, # CoreML/TF INT8 quantization
  293. dynamic=False, # ONNX/TF: dynamic axes
  294. simplify=False, # ONNX: simplify model
  295. opset=12, # ONNX: opset version
  296. verbose=False, # TensorRT: verbose log
  297. workspace=4, # TensorRT: workspace size (GB)
  298. nms=False, # TF: add NMS to model
  299. agnostic_nms=False, # TF: add agnostic NMS to model
  300. topk_per_class=100, # TF.js NMS: topk per class to keep
  301. topk_all=100, # TF.js NMS: topk for all classes to keep
  302. iou_thres=0.45, # TF.js NMS: IoU threshold
  303. conf_thres=0.25 # TF.js NMS: confidence threshold
  304. ):
  305. t = time.time()
  306. include = [x.lower() for x in include]
  307. tf_exports = list(x in include for x in ('saved_model', 'pb', 'tflite', 'edgetpu', 'tfjs')) # TensorFlow exports
  308. file = Path(url2file(weights) if str(weights).startswith(('http:/', 'https:/')) else weights)
  309. # Checks
  310. imgsz *= 2 if len(imgsz) == 1 else 1 # expand
  311. opset = 12 if ('openvino' in include) else opset # OpenVINO requires opset <= 12
  312. # Load PyTorch model
  313. device = select_device(device)
  314. assert not (device.type == 'cpu' and half), '--half only compatible with GPU export, i.e. use --device 0'
  315. model = attempt_load(weights, map_location=device, inplace=True, fuse=True) # load FP32 model
  316. nc, names = model.nc, model.names # number of classes, class names
  317. # Input
  318. gs = int(max(model.stride)) # grid size (max stride)
  319. imgsz = [check_img_size(x, gs) for x in imgsz] # verify img_size are gs-multiples
  320. im = torch.zeros(batch_size, 3, *imgsz).to(device) # image size(1,3,320,192) BCHW iDetection
  321. # Update model
  322. if half:
  323. im, model = im.half(), model.half() # to FP16
  324. model.train() if train else model.eval() # training mode = no Detect() layer grid construction
  325. for k, m in model.named_modules():
  326. if isinstance(m, Conv): # assign export-friendly activations
  327. if isinstance(m.act, nn.SiLU):
  328. m.act = SiLU()
  329. elif isinstance(m, Detect):
  330. m.inplace = inplace
  331. m.onnx_dynamic = dynamic
  332. # m.forward = m.forward_export # assign forward (optional)
  333. for _ in range(2):
  334. y = model(im) # dry runs
  335. LOGGER.info(f"\n{colorstr('PyTorch:')} starting from {file} ({file_size(file):.1f} MB)")
  336. # Exports
  337. if 'torchscript' in include:
  338. export_torchscript(model, im, file, optimize)
  339. if ('onnx' in include) or ('openvino' in include): # OpenVINO requires ONNX
  340. export_onnx(model, im, file, opset, train, dynamic, simplify)
  341. if 'engine' in include:
  342. export_engine(model, im, file, train, half, simplify, workspace, verbose)
  343. if 'coreml' in include:
  344. export_coreml(model, im, file)
  345. if 'openvino' in include:
  346. export_openvino(model, im, file)
  347. # TensorFlow Exports
  348. if any(tf_exports):
  349. pb, tflite, edgetpu, tfjs = tf_exports[1:]
  350. assert not (tflite and tfjs), 'TFLite and TF.js models must be exported separately, please pass only one type.'
  351. model = export_saved_model(model, im, file, dynamic, tf_nms=nms or agnostic_nms or tfjs,
  352. agnostic_nms=agnostic_nms or tfjs, topk_per_class=topk_per_class, topk_all=topk_all,
  353. conf_thres=conf_thres, iou_thres=iou_thres) # keras model
  354. if pb or tfjs: # pb prerequisite to tfjs
  355. export_pb(model, im, file)
  356. if tflite or edgetpu:
  357. export_tflite(model, im, file, int8=int8 or edgetpu, data=data, ncalib=100)
  358. if edgetpu:
  359. export_edgetpu(model, im, file)
  360. if tfjs:
  361. export_tfjs(model, im, file)
  362. # Finish
  363. LOGGER.info(f'\nExport complete ({time.time() - t:.2f}s)'
  364. f"\nResults saved to {colorstr('bold', file.parent.resolve())}"
  365. f'\nVisualize with https://netron.app')
  366. def parse_opt():
  367. parser = argparse.ArgumentParser()
  368. parser.add_argument('--data', type=str, default=ROOT / 'data/coco128.yaml', help='dataset.yaml path')
  369. parser.add_argument('--weights', nargs='+', type=str, default=ROOT / 'yolov5s.pt', help='model.pt path(s)')
  370. parser.add_argument('--imgsz', '--img', '--img-size', nargs='+', type=int, default=[640, 640], help='image (h, w)')
  371. parser.add_argument('--batch-size', type=int, default=1, help='batch size')
  372. parser.add_argument('--device', default='cpu', help='cuda device, i.e. 0 or 0,1,2,3 or cpu')
  373. parser.add_argument('--half', action='store_true', help='FP16 half-precision export')
  374. parser.add_argument('--inplace', action='store_true', help='set YOLOv5 Detect() inplace=True')
  375. parser.add_argument('--train', action='store_true', help='model.train() mode')
  376. parser.add_argument('--optimize', action='store_true', help='TorchScript: optimize for mobile')
  377. parser.add_argument('--int8', action='store_true', help='CoreML/TF INT8 quantization')
  378. parser.add_argument('--dynamic', action='store_true', help='ONNX/TF: dynamic axes')
  379. parser.add_argument('--simplify', action='store_true', help='ONNX: simplify model')
  380. parser.add_argument('--opset', type=int, default=12, help='ONNX: opset version')
  381. parser.add_argument('--verbose', action='store_true', help='TensorRT: verbose log')
  382. parser.add_argument('--workspace', type=int, default=4, help='TensorRT: workspace size (GB)')
  383. parser.add_argument('--nms', action='store_true', help='TF: add NMS to model')
  384. parser.add_argument('--agnostic-nms', action='store_true', help='TF: add agnostic NMS to model')
  385. parser.add_argument('--topk-per-class', type=int, default=100, help='TF.js NMS: topk per class to keep')
  386. parser.add_argument('--topk-all', type=int, default=100, help='TF.js NMS: topk for all classes to keep')
  387. parser.add_argument('--iou-thres', type=float, default=0.45, help='TF.js NMS: IoU threshold')
  388. parser.add_argument('--conf-thres', type=float, default=0.25, help='TF.js NMS: confidence threshold')
  389. parser.add_argument('--include', nargs='+',
  390. default=['torchscript', 'onnx'],
  391. help='available formats are (torchscript, onnx, engine, coreml, saved_model, pb, tflite, tfjs)')
  392. opt = parser.parse_args()
  393. print_args(FILE.stem, opt)
  394. return opt
  395. def main(opt):
  396. for opt.weights in (opt.weights if isinstance(opt.weights, list) else [opt.weights]):
  397. run(**vars(opt))
  398. if __name__ == "__main__":
  399. opt = parse_opt()
  400. main(opt)