bundled_inputs.py 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473
  1. #!/usr/bin/env python3
  2. from typing import Any, TypeVar, Optional, Tuple, List, NamedTuple, Union, Sequence, Dict, Callable
  3. import textwrap
  4. import torch
  5. from torch._C import TupleType, ListType
  6. from torch.jit._recursive import wrap_cpp_module
  7. T = TypeVar("T")
  8. MAX_RAW_TENSOR_SIZE = 16
  9. class InflatableArg(NamedTuple):
  10. """ Helper type for bundled inputs.
  11. 'value' is the compressed/deflated input that is stored in the model. Value
  12. must be of the same type as the argument to the function that it is a deflated
  13. input for.
  14. 'fmt' is a formatable code string that is executed to inflate the compressed data into
  15. the appropriate input. It can use 'value' as an input to the format str. It must result
  16. in a value of the same type as 'value'.
  17. 'fmt_fn' is a formatable function code string that is executed to inflate the compressed
  18. data into the appropriate input. It must result in a value of the same type as 'value'.
  19. The function name should be the formatable part of the string.
  20. Note: Only top level InflatableArgs can be inflated. i.e. you cannot place
  21. an inflatable arg inside of some other structure. You should instead create
  22. an inflatable arg such that the fmt code string returns the full structure
  23. of your input.
  24. """
  25. value: Any
  26. fmt: str = "{}"
  27. fmt_fn: str = ""
  28. def bundle_inputs(
  29. model: torch.jit.ScriptModule,
  30. inputs: Union[Optional[Sequence[Tuple[Any, ...]]], Dict[Callable, Optional[Sequence[Tuple[Any, ...]]]]],
  31. info: Optional[Union[List[str], Dict[Callable, List[str]]]] = None,
  32. *,
  33. _receive_inflate_expr: Optional[List[str]] = None,
  34. ) -> torch.jit.ScriptModule:
  35. """Creates and returns a copy of the specified model with inputs attached. The original model is
  36. not mutated or changed in any way.
  37. Models with bundled inputs can be invoked in a uniform manner by
  38. benchmarking and code coverage tools.
  39. If inputs is passed in as a list then the inputs will be bundled for 'forward'.
  40. If inputs is instead passed in as a map then all the methods specified in the map
  41. will have their corresponding inputs bundled. Info should match watchever type is
  42. chosen for the inputs.
  43. The returned model will support the following methods:
  44. `get_all_bundled_inputs_for_<function_name>() -> List[Tuple[Any, ...]]`
  45. Returns a list of tuples suitable for passing to the model like
  46. `for inp in model.get_all_bundled_inputs_for_foo(): model.foo(*inp)`
  47. `get_bundled_inputs_functions_and_info() -> Dict[str, Dict[str: List[str]]]`
  48. Returns a dictionary mapping function names to a metadata dictionary.
  49. This nested dictionary maps preset strings like:
  50. 'get_inputs_function_name' -> the name of a function attribute in this model that can be
  51. run to get back a list of inputs corresponding to that function.
  52. 'info' -> the user provided extra information about the bundled inputs
  53. If forward has bundled inputs then these following functions will also be defined on the returned module:
  54. `get_all_bundled_inputs() -> List[Tuple[Any, ...]]`
  55. Returns a list of tuples suitable for passing to the model like
  56. `for inp in model.get_all_bundled_inputs(): model(*inp)`
  57. `get_num_bundled_inputs() -> int`
  58. Equivalent to `len(model.get_all_bundled_inputs())`,
  59. but slightly easier to call from C++.
  60. Inputs can be specified in one of two ways:
  61. - The model can define `_generate_bundled_inputs_for_<function_name>`.
  62. If the user chooses this method inputs[<function>] should map to None
  63. - The `inputs` argument to this function can be a dictionary mapping functions to a
  64. list of inputs, of the same form that will be returned by get_all_bundled_inputs_for_<function_name>.
  65. Alternatively if only bundling inputs for forward the map can be omitted and a singular list of inputs
  66. can be provided instead.
  67. The type of the inputs is List[Tuple[Any, ...]]. The outer list corresponds with a
  68. list of inputs, the inner tuple is the list of args that together make up one input.
  69. For inputs of functions that take one arg, this will be a tuple of length one. The Any, ...
  70. is the actual data that makes up the args, e.g. a tensor.
  71. Info is an optional parameter that maps functions to a list of strings providing extra information about that
  72. function's bundled inputs. Alternatively if only bundling inputs for forward the map can be omitted and
  73. a singular list of information can be provided instead. This could be descriptions, expected outputs, etc.
  74. - Ex: info={model.forward : ['man eating icecream', 'an airplane', 'a dog']}
  75. This function will attempt to optimize arguments so that (e.g.)
  76. arguments like `torch.zeros(1000)` will be represented compactly.
  77. Only top-level arguments will be optimized.
  78. Tensors in lists or tuples will not.
  79. """
  80. if not isinstance(model, torch.jit.ScriptModule):
  81. raise Exception("Only ScriptModule is supported.")
  82. ignored_methods, ignored_attrs = _get_bundled_inputs_attributes_and_methods(model)
  83. clone = torch._C._hack_do_not_use_clone_module_with_class( # type: ignore[attr-defined]
  84. model._c,
  85. ignored_methods,
  86. ignored_attrs,
  87. )
  88. # The above cloning function returns a torch._C.scriptmodule and we need a torch.jit.scriptmodule.
  89. # Fortunately theres a function in _recursive that does exactly that conversion.
  90. cloned_module = wrap_cpp_module(clone)
  91. if isinstance(inputs, dict):
  92. assert(isinstance(info, dict) or info is None)
  93. augment_many_model_functions_with_bundled_inputs(cloned_module, inputs, _receive_inflate_expr, info)
  94. else:
  95. assert(isinstance(info, list) or info is None)
  96. augment_model_with_bundled_inputs(cloned_module, inputs, _receive_inflate_expr, info)
  97. return cloned_module
  98. def augment_model_with_bundled_inputs(
  99. model: torch.jit.ScriptModule,
  100. inputs: Optional[Sequence[Tuple[Any, ...]]] = None,
  101. _receive_inflate_expr: Optional[List[str]] = None, # For debugging.
  102. info: Optional[List[str]] = None, # Optional argument to provide info about forward or its inputs
  103. skip_size_check=False,
  104. ) -> None:
  105. """ Add bundled sample inputs to a model for the forward function.
  106. Models with bundled inputs can be invoked in a uniform manner by
  107. benchmarking and code coverage tools.
  108. Augmented models will support the following methods:
  109. `get_all_bundled_inputs() -> List[Tuple[Any, ...]]`
  110. Returns a list of tuples suitable for passing to the model like
  111. `for inp in model.get_all_bundled_inputs(): model(*inp)`
  112. `get_num_bundled_inputs() -> int`
  113. Equivalent to `len(model.get_all_bundled_inputs())`,
  114. but slightly easier to call from C++.
  115. `get_bundled_inputs_functions_and_info() -> Dict[str, Dict[str: List[str]]]`
  116. Returns a dictionary mapping function names to a metadata dictionary.
  117. This nested dictionary maps preset strings like:
  118. 'get_inputs_function_name' -> the name of a function attribute in this model that can be
  119. run to get back a list of inputs corresponding to that function.
  120. 'info' -> the user provided extra information about the bundled inputs
  121. Inputs can be specified in one of two ways:
  122. - The model can define `_generate_bundled_inputs_for_forward`.
  123. If the user chooses this method inputs should be None
  124. - `inputs` is a list of inputs of form List[Tuple[Any, ...]]. A list of tuples where the elements
  125. of each tuple are the args that make up one input.
  126. """
  127. if not isinstance(model, torch.jit.ScriptModule):
  128. raise Exception("Only ScriptModule is supported.")
  129. forward: Callable = model.forward
  130. # Sometimes forward won't have a name attached so just in case
  131. if not hasattr(forward, "__name__"):
  132. forward.__name__ = 'forward'
  133. augment_many_model_functions_with_bundled_inputs(
  134. model,
  135. inputs={forward : inputs},
  136. _receive_inflate_expr=_receive_inflate_expr,
  137. info={forward : info} if info else None,
  138. skip_size_check=skip_size_check,
  139. )
  140. def augment_many_model_functions_with_bundled_inputs(
  141. model: torch.jit.ScriptModule,
  142. inputs: Dict[Callable, Optional[Sequence[Tuple[Any, ...]]]],
  143. _receive_inflate_expr: Optional[List[str]] = None, # For debugging.
  144. info: Optional[Dict[Callable, List[str]]] = None, # Optional argument to provide info about the function or its inputs
  145. skip_size_check=False,
  146. ) -> None:
  147. """Add bundled sample inputs to a model for an arbitrary list of public functions.
  148. Models with bundled inputs can be invoked in a uniform manner by
  149. benchmarking and code coverage tools.
  150. Augmented models will support the following methods:
  151. `get_all_bundled_inputs_for_<function_name>() -> List[Tuple[Any, ...]]`
  152. Returns a list of tuples suitable for passing to the model like
  153. `for inp in model.get_all_bundled_inputs_for_foo(): model.foo(*inp)`
  154. `get_bundled_inputs_functions_and_info() -> Dict[str, Dict[str: List[str]]]`
  155. Returns a dictionary mapping function names to a metadata dictionary.
  156. This nested dictionary maps preset strings like:
  157. 'get_inputs_function_name' -> the name of a function attribute in this model that can be
  158. run to get back a list of inputs corresponding to that function.
  159. 'info' -> the user provided extra information about the bundled inputs
  160. If forward has bundled inputs then these following functions are also defined:
  161. `get_all_bundled_inputs() -> List[Tuple[Any, ...]]`
  162. Returns a list of tuples suitable for passing to the model like
  163. `for inp in model.get_all_bundled_inputs(): model(*inp)`
  164. `get_num_bundled_inputs() -> int`
  165. Equivalent to `len(model.get_all_bundled_inputs())`,
  166. but slightly easier to call from C++.
  167. Inputs can be specified in one of two ways:
  168. - The model can define `_generate_bundled_inputs_for_<function_name>`.
  169. If the user chooses this method inputs[<function>] should map to None
  170. - The `inputs` argument to this function can be a dictionary mapping functions to a
  171. list of inputs, of the same form that will be returned by get_all_bundled_inputs_for_<function_name>.
  172. The type of the inputs is List[Tuple[Any, ...]]. The outer list corresponds with a
  173. list of inputs, the inner tuple is the list of args that together make up one input.
  174. For inputs of functions that take one arg, this will be a tuple of length one. The Any, ...
  175. is the actual data that makes up the args, e.g. a tensor.
  176. Info is an optional parameter that maps functions to a list of strings providing extra information about that
  177. function's bundled inputs. This could be descriptions, expected outputs, etc.
  178. - Ex: info={model.forward : ['man eating icecream', 'an airplane', 'a dog']}
  179. This function will attempt to optimize arguments so that (e.g.)
  180. arguments like `torch.zeros(1000)` will be represented compactly.
  181. Only top-level arguments will be optimized.
  182. Tensors in lists or tuples will not.
  183. """
  184. if not isinstance(model, torch.jit.ScriptModule):
  185. raise Exception("Only ScriptModule is supported.")
  186. if not inputs:
  187. raise Exception("Please provide inputs for at least 1 function")
  188. if hasattr(model, "get_all_bundled_inputs") or hasattr(model, "get_bundled_inputs_functions_and_info"):
  189. raise Exception(
  190. "Models can only be augmented with bundled inputs once. "
  191. "This Model seems to have already been augmented with "
  192. "bundled inputs. Please start afresh with one that "
  193. "doesn't have bundled inputs.",
  194. )
  195. get_bundled_inputs_functions_and_info_template = ""
  196. for function, input_list in inputs.items():
  197. if hasattr(function, "__name__"):
  198. function_name = function.__name__
  199. else:
  200. if hasattr(function, "name"):
  201. function_name = function.name # type: ignore[attr-defined]
  202. else:
  203. raise Exception(
  204. 'At least one of your functions has no attribute name please ensure all have one. m.foo.name = "foo"')
  205. if input_list is not None and not isinstance(input_list, Sequence):
  206. raise TypeError("Error inputs for function {0} is not a Sequence".format(function_name))
  207. function_arg_types = [arg.type for arg in function.schema.arguments[1:]] # type: ignore[attr-defined]
  208. deflated_inputs_type: ListType = ListType(TupleType(function_arg_types))
  209. model._c._register_attribute("_bundled_inputs_deflated_{name}".format(name=function_name), deflated_inputs_type, [])
  210. if hasattr(model, "_generate_bundled_inputs_for_" + function_name):
  211. if input_list is not None:
  212. raise Exception(
  213. "inputs[{name}] is not None, but _generate_bundled_inputs_for_{name} is already defined".format(
  214. name=function_name
  215. )
  216. )
  217. # Model author already defined _generate_bundled_inputs_for_<function_name>.
  218. elif input_list is None or len(input_list) == 0:
  219. raise Exception(
  220. "inputs for {name} must be specified if _generate_bundled_inputs_for_{name} is not already defined".format(
  221. name=function_name,
  222. )
  223. )
  224. else:
  225. # Iterate over the inputs and args in each input.
  226. # Accumulate `deflated_inputs` as (possibly) compressed values
  227. # and `parts` to be joined into the expression that unpacks them.
  228. deflated_inputs = []
  229. parts = []
  230. for inp_idx, args in enumerate(input_list):
  231. if not isinstance(args, Tuple) and not isinstance(args, List): # type: ignore[arg-type]
  232. raise TypeError(
  233. "Error bundled input for function {0} idx: {1} is not a Tuple or a List".format(function_name, inp_idx)
  234. )
  235. deflated_args = []
  236. parts.append("(")
  237. for arg_idx, arg in enumerate(args):
  238. inflate_helper_fn_name = _get_inflate_helper_fn_name(arg_idx, inp_idx, function_name)
  239. deflated, inflater, helper_definition = _inflate_expr(
  240. arg,
  241. f"deflated[{inp_idx}][{arg_idx}]",
  242. inflate_helper_fn_name,
  243. skip_size_check=skip_size_check,
  244. )
  245. deflated_args.append(deflated)
  246. parts.append(f" {inflater},")
  247. if helper_definition:
  248. model.define(textwrap.dedent(helper_definition))
  249. deflated_inputs.append(tuple(deflated_args))
  250. parts.append("),")
  251. parts.append("")
  252. expr = "\n".join(parts)
  253. # Back-channel return this expr for debugging.
  254. if _receive_inflate_expr is not None:
  255. _receive_inflate_expr.append(expr)
  256. setattr(model, "_bundled_inputs_deflated_{name}".format(name=function_name), deflated_inputs)
  257. definition = textwrap.dedent("""
  258. def _generate_bundled_inputs_for_{name}(self):
  259. deflated = self._bundled_inputs_deflated_{name}
  260. return [
  261. {expr}
  262. ]
  263. """).format(expr=expr, name=function_name)
  264. model.define(definition)
  265. # Define get_all_bundled_inputs_for_<function_name> that caches the generated inputs.
  266. model.define(textwrap.dedent("""
  267. def get_all_bundled_inputs_for_{name}(self):
  268. all_inputs = self._generate_bundled_inputs_for_{name}()
  269. assert all_inputs is not None
  270. return all_inputs
  271. """).format(name=function_name))
  272. # Add to the high level helper methods
  273. inputs_info = repr(info[function]) if info and function in info else '[]'
  274. get_bundled_inputs_functions_and_info_template += """
  275. temp_dict : Dict[str,List[str]] = {{}}
  276. info: List[str] = {info}
  277. temp_dict['info'] = info
  278. temp_dict['get_inputs_function_name'] = ['get_all_bundled_inputs_for_{name}']
  279. all_inputs['{name}'] = temp_dict
  280. """.format(
  281. name=function_name,
  282. info=inputs_info,
  283. )
  284. # To ensure backwards compatibility and a streamlined api for forward these wrappers are provided
  285. if function_name == 'forward':
  286. model.define(textwrap.dedent("""
  287. def get_all_bundled_inputs(self):
  288. return self.get_all_bundled_inputs_for_forward()
  289. """))
  290. model.define(textwrap.dedent("""
  291. def get_num_bundled_inputs(self):
  292. return len(self.get_all_bundled_inputs_for_forward())
  293. """))
  294. # Define some high level helper methods that act on all bundled inputs
  295. model.define(textwrap.dedent("""
  296. def get_bundled_inputs_functions_and_info(self):
  297. all_inputs : Dict[str, Dict[str,List[str]]] = {{}}
  298. {template}
  299. return all_inputs
  300. """.format(template=get_bundled_inputs_functions_and_info_template)))
  301. def _inflate_expr(
  302. arg: T, ref: str, inflate_helper_fn_name: str, skip_size_check: bool = False
  303. ) -> Tuple[Union[T, torch.Tensor], str, Optional[str]]:
  304. # Allow custom inflation expressions any object.
  305. # For example, calling custom image-decoding ops.
  306. # Or just use "{}" as the format string to ignore size limits.
  307. if isinstance(arg, InflatableArg):
  308. if arg.fmt_fn:
  309. if arg.fmt not in ["{}", ""]:
  310. raise Exception(
  311. f"Bundled input argument at position '{ref}' has "
  312. f"both arg.fmt_fn => \n{arg.fmt_fn} "
  313. f"\n and arg.fmt => {arg.fmt}. "
  314. "Please choose `arg.fmt` if the deflater is straightforward or "
  315. "`arg.fmt_fn` if you need a function."
  316. )
  317. helper_definition = arg.fmt_fn.format(inflate_helper_fn_name)
  318. expr = f"self.{inflate_helper_fn_name}({ref})"
  319. return arg.value, expr, helper_definition
  320. else:
  321. return arg.value, arg.fmt.format(ref), None
  322. if isinstance(arg, torch.Tensor):
  323. # Small-storage tensors can just be saved directly.
  324. if arg._typed_storage().size() <= MAX_RAW_TENSOR_SIZE or skip_size_check:
  325. return arg, ref, None
  326. # Small contiguous tensors can be cloned to have small storage.
  327. # TODO: Should we do this even for non-contiguous tensors?
  328. if arg.is_contiguous() and arg.numel() <= MAX_RAW_TENSOR_SIZE:
  329. return arg.clone(), ref, None
  330. # Example inputs commonly come from torch.zeros, torch.ones, or torch.full.
  331. # These can be represented compactly.
  332. for fmt in [torch.contiguous_format, torch.channels_last]:
  333. if arg.is_contiguous(memory_format=fmt) and (arg == arg.flatten()[0]).all().item():
  334. return (arg.flatten()[0].clone().expand(*arg.size()),
  335. f"{ref}.contiguous(memory_format={fmt})", None)
  336. # Prevent big tensors from being bundled by default.
  337. # TODO: Provide more useful diagnostics.
  338. raise Exception(
  339. f"Bundled input argument at position '{ref}' is "
  340. f"a tensor with storage size {arg._typed_storage().size()}. "
  341. f"You probably don't want to bundle this as an input. "
  342. )
  343. else:
  344. return arg, ref, None
  345. def _get_bundled_inputs_attributes_and_methods(script_module: torch.jit.ScriptModule) -> Tuple[List[str], List[str]]:
  346. methods: List[str] = []
  347. attributes: List[str] = []
  348. # Has bundled inputs for forward
  349. if hasattr(script_module, 'get_all_bundled_inputs'):
  350. methods.append('get_all_bundled_inputs')
  351. methods.append('get_num_bundled_inputs')
  352. methods.append('run_on_bundled_input')
  353. if hasattr(script_module, 'get_bundled_inputs_functions_and_info'):
  354. methods.append('get_bundled_inputs_functions_and_info')
  355. all_info = script_module.get_bundled_inputs_functions_and_info()
  356. for function_name in all_info:
  357. methods.append("get_all_bundled_inputs_for_" + function_name)
  358. methods.append("_generate_bundled_inputs_for_" + function_name)
  359. attributes.append("_bundled_inputs_deflated_" + function_name)
  360. bundled_inputs_fn = getattr(
  361. script_module,
  362. f"get_all_bundled_inputs_for_{function_name}"
  363. )
  364. num_bundled_inputs: int = len(bundled_inputs_fn())
  365. # Check inflate helper functions for each function, argument and bundled input
  366. func = getattr(script_module, function_name)
  367. for arg_idx in range(len(func.schema.arguments) - 1):
  368. for input_idx in range(num_bundled_inputs):
  369. helper_fn_name = _get_inflate_helper_fn_name(
  370. arg_idx=arg_idx,
  371. input_idx=input_idx,
  372. function_name=function_name
  373. )
  374. # if the arg has an InflatableArg with fmt_fn, add the helper function name
  375. if hasattr(script_module, helper_fn_name):
  376. methods.append(helper_fn_name)
  377. return (methods, attributes)
  378. def _get_inflate_helper_fn_name(
  379. arg_idx: int,
  380. input_idx: int,
  381. function_name: str,
  382. ) -> str:
  383. return f"_inflate_helper_for_{function_name}_input_{input_idx}_arg_{arg_idx}"
  384. def bundle_randn(*size, dtype=None):
  385. """Generate a tensor that will be inflated with torch.randn."""
  386. stub = torch.zeros(1, dtype=dtype).expand(*size)
  387. return InflatableArg(value=stub, fmt="torch.randn_like({})")
  388. def bundle_large_tensor(t):
  389. """Wrap a tensor to allow bundling regardless of size."""
  390. return InflatableArg(value=t, fmt="{}")