bundled_inputs.py 22 KB

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