fake_profile.py 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323
  1. import contextlib
  2. import io
  3. import logging
  4. import os
  5. from collections.abc import Generator
  6. from dataclasses import dataclass
  7. from typing import Any, Callable, Optional, Union
  8. import torch
  9. from torch._library.custom_ops import _maybe_get_opdef
  10. from torch.types import FileLike
  11. log = logging.getLogger(__name__)
  12. class MissingOpProfile(RuntimeError):
  13. """
  14. This is raised when we don't have an operator profile available for the
  15. given inputs.
  16. """
  17. @dataclass(frozen=True)
  18. class TensorMetadata:
  19. rank: int
  20. dtype: torch.dtype
  21. device: torch.device
  22. layout: torch.layout
  23. @staticmethod
  24. def maybe_from_tensor(t: Any) -> Optional["TensorMetadata"]:
  25. if not isinstance(t, torch.Tensor):
  26. return None
  27. return TensorMetadata(t.dim(), t.dtype, t.device, t.layout)
  28. @dataclass(frozen=True)
  29. class OpProfile:
  30. args_profile: tuple[Optional[TensorMetadata]]
  31. out_profile: Union[TensorMetadata, tuple[TensorMetadata]]
  32. def _generate_fake_kernel(op_name: str, op_profile: set[OpProfile]) -> Callable:
  33. def _match_args(args_profile: tuple[Optional[TensorMetadata]], args: Any) -> bool:
  34. return all(
  35. TensorMetadata.maybe_from_tensor(arg) == args_profile[i]
  36. for i, arg in enumerate(args)
  37. )
  38. def _generate_res(
  39. out_profile: Union[TensorMetadata, tuple[TensorMetadata]],
  40. ) -> Union[torch.Tensor, list[torch.Tensor]]:
  41. ctx = torch.library.get_ctx()
  42. def _generate_tensor_out(t: TensorMetadata) -> torch.Tensor:
  43. fake_shape = [ctx.new_dynamic_size() for _ in range(t.rank)]
  44. fake_strides = [-1] * t.rank
  45. expected = 1
  46. fake_stride = expected
  47. for i in range(t.rank):
  48. fake_strides[i] = fake_stride # type: ignore[assignment]
  49. fake_stride = fake_stride * fake_shape[i] # type: ignore[assignment]
  50. return torch.empty_strided(
  51. fake_shape,
  52. fake_strides,
  53. device=t.device,
  54. dtype=t.dtype,
  55. layout=t.layout,
  56. )
  57. if isinstance(out_profile, TensorMetadata):
  58. return _generate_tensor_out(out_profile)
  59. else:
  60. return [_generate_tensor_out(t) for t in out_profile]
  61. def _fake_kernel(*args, **kwargs): # type: ignore[no-untyped-def]
  62. for profile in op_profile:
  63. if _match_args(profile.args_profile, (*args, *kwargs.values())):
  64. return _generate_res(profile.out_profile)
  65. raise MissingOpProfile(
  66. f"No fake kernel was found for {op_name}, and although we have "
  67. "previously registered some profiles to generate a fake kernel, "
  68. f"no profiles match the given inputs: {args, kwargs}."
  69. )
  70. return _fake_kernel
  71. @contextlib.contextmanager
  72. def unsafe_generate_fake_kernels(op_profiles: dict[str, set[OpProfile]]) -> Generator:
  73. """
  74. Registers a fake kernel based on the given operator profiles. This fake
  75. kernel registration will override any existing fake kernel registrations.
  76. The input is a dictionary mapping operator names to a set of operator
  77. profiles, which we will use to generate fake kernels. The operator profiles
  78. are a record of the input and output tensor metadata. Based on this
  79. information we will match a given input to the recorded profile, and return
  80. an output with the same metadata as in the recorded profile. If a profile
  81. doesn't exist then an exception will be thrown.
  82. The fake kernel generation is considered unsafe because it relies on the
  83. rigid, pre-defined operator profiles that do not account for potential
  84. variations in output behavior. Specifically, the generated kernels assume a
  85. fixed relationship between input and output ranks. However, in reality, it's
  86. possible that data-dependent operations may produce outputs of different
  87. ranks even when given inputs of the same rank. The generated fake kernels
  88. are inflexible and unable to accommodate these nuances, making them
  89. potentially unsafe.
  90. Args:
  91. op_profiles (dict[str, set[OpProfile]]): A dictionary mapping operator
  92. name to a set of operator profiles from which we will generate fake
  93. kernels.
  94. Examples:
  95. >>> # Example: Registering an op-profile from draft-export
  96. >>> import torch
  97. >>> from torch.export._draft_export import draft_export
  98. >>>
  99. >>> @torch.library.custom_op("mylib::foo", mutates_args=())
  100. >>> def foo(x: Tensor, y: Tensor) -> Tensor:
  101. >>> return x + y
  102. >>>
  103. >>> class M(torch.nn.Module):
  104. >>> def forward(self, a, b):
  105. >>> res = torch.ops.mylib.foo(a, b) # no fake impl
  106. >>> return res
  107. >>>
  108. >>> ep = draft_export(M(), (torch.ones(3, 4), torch.ones(3, 4))
  109. >>>
  110. >>> with torch._library.fake_profile.unsafe_generate_fake_kernels(ep._report.op_profiles):
  111. >>> decomp = ep.run_decompositions()
  112. """
  113. libs: list[torch.library.Library] = []
  114. # Stores old fake impls from custom ops declared through @custom_op
  115. old_fake_impls: dict[str, Callable] = {}
  116. for op_name, profiles in op_profiles.items():
  117. log.warning(
  118. "Registering fake profile for %s. This will override any existing "
  119. "fake kernel registration.",
  120. op_name,
  121. )
  122. op_name_split = op_name.split(".")
  123. namespace, op_name_str = op_name_split[0], op_name_split[1]
  124. op_str = f"{namespace}::{op_name_str}"
  125. fake_kernel = _generate_fake_kernel(op_str, profiles)
  126. if opdef := _maybe_get_opdef(op_str):
  127. # If the op is a CustomOpDef, save the existing abstract_fn so that
  128. # we can restore it after this contextmanager
  129. if opdef._abstract_fn is not None:
  130. old_fake_impls[op_str] = opdef._abstract_fn
  131. opdef.register_fake(fake_kernel)
  132. else:
  133. # Create a new library so that we can register a new fake impl.
  134. # These libraries will then be destroyed after the contextmanager,
  135. # which will automatically restore the previously registered fake
  136. # impls.
  137. newlib = torch.library.Library(namespace, "FRAGMENT") # noqa: TOR901
  138. torch.library.register_fake(
  139. op_str, fake_kernel, lib=newlib, allow_override=True
  140. )
  141. libs.append(newlib)
  142. try:
  143. yield libs
  144. finally:
  145. # Destroying the libraries will automatically restore the previously
  146. # registered fake impls
  147. for lib in libs:
  148. lib._destroy()
  149. # Restore abstract_fns for CustomOpDefs
  150. for op_str, old_fake in old_fake_impls.items():
  151. opdef = _maybe_get_opdef(op_str)
  152. assert opdef is not None
  153. opdef.register_fake(old_fake)
  154. def get_torch_version() -> str:
  155. version = torch.__version__.split(".")
  156. return f"{int(version[0])}.{int(version[1])}"
  157. def generate_yaml_from_profiles(op_profiles: dict[str, set[OpProfile]]) -> str:
  158. """
  159. Generates a yaml string from the given operator profiles which can be saved
  160. to a file. The yaml string can be loaded back into an operator profile
  161. structure using `read_profiles_from_yaml`.
  162. """
  163. import yaml
  164. from torch._export.serde.serialize import (
  165. _TORCH_TO_SERIALIZE_DTYPE,
  166. _TORCH_TO_SERIALIZE_LAYOUT,
  167. )
  168. def serialize_tensor_metadata(t: TensorMetadata) -> dict:
  169. return {
  170. "rank": t.rank,
  171. "dtype": _TORCH_TO_SERIALIZE_DTYPE[t.dtype].value,
  172. "device": str(t.device),
  173. "layout": _TORCH_TO_SERIALIZE_LAYOUT[t.layout].value,
  174. }
  175. def serialize_op_profile(op: OpProfile) -> dict:
  176. return {
  177. "args_profile": [
  178. serialize_tensor_metadata(arg)
  179. for arg in op.args_profile
  180. if arg is not None
  181. ],
  182. "out_profile": (
  183. serialize_tensor_metadata(op.out_profile)
  184. if isinstance(op.out_profile, TensorMetadata)
  185. else [serialize_tensor_metadata(out) for out in op.out_profile]
  186. ),
  187. }
  188. serialized_data = {
  189. operator: [serialize_op_profile(profile) for profile in profiles]
  190. for operator, profiles in op_profiles.items()
  191. }
  192. return yaml.dump(
  193. {"torch_version": get_torch_version(), "operators": serialized_data},
  194. sort_keys=False,
  195. )
  196. def save_op_profiles(op_profiles: dict[str, set[OpProfile]], f: FileLike) -> None:
  197. """
  198. Serializes the given operator profiles into a yaml format and saves it to
  199. the given file. The operator profile can be loaded back using `load_op_profiles`.
  200. """
  201. yaml_str = generate_yaml_from_profiles(op_profiles)
  202. if isinstance(f, (str, os.PathLike)):
  203. f = os.fspath(f)
  204. with open(f, "w") as file:
  205. file.write(yaml_str)
  206. elif isinstance(f, io.BytesIO):
  207. f.write(yaml_str.encode("utf-8"))
  208. else:
  209. raise ValueError(f"Invalid type of file {f}")
  210. def read_profiles_from_yaml(yaml_str: str) -> dict[str, set[OpProfile]]:
  211. """
  212. Reads the yaml saved by `save_op_profiles` and returns the operator profiles.
  213. """
  214. import yaml
  215. from torch._export.serde.serialize import (
  216. _SERIALIZE_TO_TORCH_DTYPE,
  217. _SERIALIZE_TO_TORCH_LAYOUT,
  218. )
  219. def deserialize_tensor_metadata(data: dict) -> TensorMetadata:
  220. return TensorMetadata(
  221. rank=data["rank"],
  222. dtype=_SERIALIZE_TO_TORCH_DTYPE[data["dtype"]],
  223. device=torch.device(data["device"]),
  224. layout=_SERIALIZE_TO_TORCH_LAYOUT[data["layout"]],
  225. )
  226. def deserialize_op_profile(data: dict) -> OpProfile:
  227. args_profile = tuple(
  228. deserialize_tensor_metadata(arg) for arg in data["args_profile"]
  229. )
  230. out_profile_data = data["out_profile"]
  231. out_profile: Union[tuple[TensorMetadata], TensorMetadata] = (
  232. tuple(deserialize_tensor_metadata(out) for out in out_profile_data) # type: ignore[assignment]
  233. if isinstance(out_profile_data, list)
  234. else deserialize_tensor_metadata(out_profile_data)
  235. )
  236. return OpProfile(args_profile=args_profile, out_profile=out_profile) # type: ignore[arg-type]
  237. loaded_data = yaml.safe_load(yaml_str)
  238. loaded_torch_version = loaded_data["torch_version"]
  239. if loaded_torch_version != get_torch_version():
  240. raise RuntimeError(
  241. "Unable to load outdated profile. It was saved with torch version: "
  242. f"{loaded_torch_version} but the current torch version is: {get_torch_version()}"
  243. )
  244. operators_data = loaded_data["operators"]
  245. return {
  246. operator: {deserialize_op_profile(profile) for profile in profiles}
  247. for operator, profiles in operators_data.items()
  248. }
  249. def load_op_profiles(f: FileLike) -> dict[str, set[OpProfile]]:
  250. """
  251. Loads the saved operator profiles from `save_op_profiles`.
  252. """
  253. if isinstance(f, (str, os.PathLike)):
  254. f = os.fspath(f)
  255. with open(f) as file:
  256. yaml_str = file.read()
  257. elif isinstance(f, io.BytesIO):
  258. yaml_str = f.read().decode("utf-8")
  259. else:
  260. raise ValueError(f"Invalid type of file {f}")
  261. return read_profiles_from_yaml(yaml_str)