mobile_optimizer.py 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134
  1. """
  2. This module contains utility method for mobile model optimization and lint.
  3. """
  4. import torch
  5. from enum import Enum
  6. from torch._C import _MobileOptimizerType as MobileOptimizerType
  7. from typing import Optional, Set, List, AnyStr
  8. class LintCode(Enum):
  9. BUNDLED_INPUT = 1
  10. REQUIRES_GRAD = 2
  11. DROPOUT = 3
  12. BATCHNORM = 4
  13. def optimize_for_mobile(
  14. script_module: torch.jit.ScriptModule,
  15. optimization_blocklist: Optional[Set[MobileOptimizerType]] = None,
  16. preserved_methods: Optional[List[AnyStr]] = None,
  17. backend: str = 'CPU') -> torch.jit.RecursiveScriptModule:
  18. """
  19. Args:
  20. script_module: An instance of torch script module with type of ScriptModule.
  21. optimization_blocklist: A set with type of MobileOptimizerType. When set is not passed,
  22. optimization method will run all the optimizer pass; otherwise, optimizer
  23. method will run the optimization pass that is not included inside optimization_blocklist.
  24. preserved_methods: A list of methods that needed to be preserved when freeze_module pass is invoked
  25. backend: Device type to use for running the result model ('CPU'(default), 'Vulkan' or 'Metal').
  26. Returns:
  27. A new optimized torch script module
  28. """
  29. if not isinstance(script_module, torch.jit.ScriptModule):
  30. raise TypeError(
  31. 'Got {}, but ScriptModule is expected.'.format(type(script_module)))
  32. if optimization_blocklist is None:
  33. optimization_blocklist = set()
  34. if preserved_methods is None:
  35. preserved_methods = []
  36. # Convert potential byte arrays into strings (if there is any) to pass type checking
  37. # Here we use a new name as assigning it back to preserved_methods will invoke
  38. # mypy errors (i.e. List[AnyStr] = List[str])
  39. preserved_methods_str: List[str] = [str(method) for method in preserved_methods]
  40. bundled_inputs_attributes = _get_bundled_inputs_preserved_attributes(script_module, preserved_methods_str)
  41. if all([hasattr(script_module, method) for method in bundled_inputs_attributes]):
  42. preserved_methods_str = list(set(preserved_methods_str + bundled_inputs_attributes))
  43. non_exist_methods = []
  44. for method in preserved_methods_str:
  45. if not hasattr(script_module, method):
  46. non_exist_methods.append(method)
  47. if non_exist_methods:
  48. raise AttributeError(
  49. 'The following methods to preserve do not exist in script_module: {}'
  50. .format(', '.join(non_exist_methods)))
  51. backend = backend.lower()
  52. if backend == 'cpu':
  53. optimized_cpp_module = torch._C._jit_pass_optimize_for_mobile(
  54. script_module._c,
  55. optimization_blocklist,
  56. preserved_methods_str)
  57. elif backend == 'vulkan':
  58. optimized_cpp_module = torch._C._jit_pass_vulkan_optimize_for_mobile(
  59. script_module._c,
  60. optimization_blocklist,
  61. preserved_methods_str)
  62. elif backend == 'metal':
  63. optimized_cpp_module = torch._C._jit_pass_metal_optimize_for_mobile(script_module._c, preserved_methods_str)
  64. else:
  65. raise TypeError("Unknown backend, must be one of 'CPU', 'Vulkan' or 'Metal'")
  66. return torch.jit._recursive.wrap_cpp_module(optimized_cpp_module)
  67. def generate_mobile_module_lints(script_module: torch.jit.ScriptModule):
  68. """
  69. Args:
  70. script_module: An instance of torch script module with type of ScriptModule
  71. Returns:
  72. lint_map: A list of dictionary that contains modules lints
  73. """
  74. if not isinstance(script_module, torch.jit.ScriptModule):
  75. raise TypeError(
  76. 'Got {}, but ScriptModule is expected.'.format(type(script_module)))
  77. lint_list = []
  78. if not hasattr(script_module, "_generate_bundled_inputs_for_forward"):
  79. lint_list.append({"name": LintCode.BUNDLED_INPUT.name, "message": "No bundled input for forward, please add bundled inputs "
  80. "before saving the module using torch.utils.bundled_inputs.augment_model_with_bundled_inputs."})
  81. for name, param in script_module.named_parameters():
  82. if param.requires_grad:
  83. lint_list.append({"name": LintCode.REQUIRES_GRAD.name, "message": "Param {} requires grad, "
  84. "please set torch.no_grad() to reduce memory usage and improve computation speed during "
  85. "inference phase.".format(name)})
  86. op_names = torch.jit.export_opnames(script_module)
  87. for op_name in op_names:
  88. if "dropout" in op_name:
  89. lint_list.append({"name": LintCode.DROPOUT.name, "message": "Operator {} exists, remember to call eval() before "
  90. "saving the module.and call torch.utils.mobile_optimizer.optimize_for_mobile to drop dropout "
  91. "operator.".format(op_name)})
  92. if "batch_norm" in op_name:
  93. lint_list.append({"name": LintCode.BATCHNORM.name, "message": "Operator {} exists, remember to call eval() before "
  94. "saving the module and call torch.utils.mobile_optimizer.optimize_for_mobile to drop batch_norm "
  95. "operator.".format(op_name)})
  96. return lint_list
  97. def _get_bundled_inputs_preserved_attributes(script_module: torch.jit.ScriptModule, preserved_methods: List[str]) -> List[str]:
  98. bundled_inputs_attributes = []
  99. # Has bundled inputs for forward
  100. if hasattr(script_module, 'get_all_bundled_inputs'):
  101. bundled_inputs_attributes.append('get_all_bundled_inputs')
  102. bundled_inputs_attributes.append('get_num_bundled_inputs')
  103. # Bundled inputs in module after the change that introduced bundled inputs for multiple functions
  104. if hasattr(script_module, 'get_bundled_inputs_functions_and_info'):
  105. bundled_inputs_attributes.append('get_bundled_inputs_functions_and_info')
  106. all_info = script_module.get_bundled_inputs_functions_and_info()
  107. for function_name in all_info:
  108. if function_name not in preserved_methods:
  109. bundled_inputs_attributes.append(function_name)
  110. bundled_inputs_attributes.append("get_all_bundled_inputs_for_" + function_name)
  111. bundled_inputs_attributes.append("_bundled_inputs_deflated_" + function_name)
  112. return bundled_inputs_attributes