m2m模型翻译
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

72 lines
2.5 KiB

6 months ago
  1. #!/usr/bin/env python3
  2. # Copyright (c) Microsoft Corporation. All rights reserved.
  3. # Licensed under the MIT License.
  4. import argparse
  5. import os
  6. import pathlib
  7. import sys
  8. import onnx
  9. from .onnx_model_utils import fix_output_shapes, make_dim_param_fixed, make_input_shape_fixed
  10. def make_dynamic_shape_fixed_helper():
  11. parser = argparse.ArgumentParser(
  12. f"{os.path.basename(__file__)}:{make_dynamic_shape_fixed_helper.__name__}",
  13. description="""
  14. Assign a fixed value to a dim_param or input shape
  15. Provide either dim_param and dim_value or input_name and input_shape.""",
  16. )
  17. parser.add_argument(
  18. "--dim_param", type=str, required=False, help="Symbolic parameter name. Provide dim_value if specified."
  19. )
  20. parser.add_argument(
  21. "--dim_value", type=int, required=False, help="Value to replace dim_param with in the model. Must be > 0."
  22. )
  23. parser.add_argument(
  24. "--input_name",
  25. type=str,
  26. required=False,
  27. help="Model input name to replace shape of. Provide input_shape if specified.",
  28. )
  29. parser.add_argument(
  30. "--input_shape",
  31. type=lambda x: [int(i) for i in x.split(",")],
  32. required=False,
  33. help="Shape to use for input_shape. Provide comma separated list for the shape. "
  34. "All values must be > 0. e.g. --input_shape 1,3,256,256",
  35. )
  36. parser.add_argument("input_model", type=pathlib.Path, help="Provide path to ONNX model to update.")
  37. parser.add_argument("output_model", type=pathlib.Path, help="Provide path to write updated ONNX model to.")
  38. args = parser.parse_args()
  39. if (
  40. (args.dim_param and args.input_name)
  41. or (not args.dim_param and not args.input_name)
  42. or (args.dim_param and (not args.dim_value or args.dim_value < 1))
  43. or (args.input_name and (not args.input_shape or any([value < 1 for value in args.input_shape])))
  44. ):
  45. print("Invalid usage.")
  46. parser.print_help()
  47. sys.exit(-1)
  48. model = onnx.load(str(args.input_model.resolve(strict=True)))
  49. if args.dim_param:
  50. make_dim_param_fixed(model.graph, args.dim_param, args.dim_value)
  51. else:
  52. make_input_shape_fixed(model.graph, args.input_name, args.input_shape)
  53. # update the output shapes to make them fixed if possible.
  54. fix_output_shapes(model)
  55. onnx.save(model, str(args.output_model.resolve()))
  56. if __name__ == "__main__":
  57. make_dynamic_shape_fixed_helper()