verifier.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430
  1. # mypy: allow-untyped-defs
  2. import inspect
  3. import math
  4. import operator
  5. from collections.abc import Iterable
  6. from typing import Any, Dict, final, List, Optional, Tuple, Type
  7. import torch
  8. from torch._ops import HigherOrderOperator, OpOverload
  9. from torch._subclasses.fake_tensor import FakeTensor
  10. from torch.export.exported_program import ExportedProgram
  11. from torch.export.graph_signature import (
  12. CustomObjArgument,
  13. InputKind,
  14. SymIntArgument,
  15. TensorArgument,
  16. TokenArgument,
  17. )
  18. from torch.fx import GraphModule
  19. from torch.fx.experimental.symbolic_shapes import SymBool, SymFloat, SymInt
  20. class SpecViolationError(Exception):
  21. pass
  22. def is_functional(op: OpOverload) -> bool:
  23. return not op._schema.is_mutable
  24. def _check_has_fake_tensor(node: torch.fx.Node) -> None:
  25. # TODO(angelayi): remove this in favor of _check_val
  26. return _check_val(node)
  27. def _check_val(node: torch.fx.Node) -> None:
  28. def _check_correct_val(val):
  29. if val is None:
  30. return True
  31. elif isinstance(val, (int, bool, str, float)):
  32. return True
  33. elif isinstance(val, (torch.memory_format, torch.dtype, torch.device, torch.layout)):
  34. return True
  35. elif isinstance(val, (FakeTensor, torch.Tensor)): # TODO(zhxchen17) Remove Tensor.
  36. return True
  37. elif isinstance(val, (SymInt, SymFloat, SymBool)):
  38. return True
  39. elif isinstance(val, CustomObjArgument):
  40. return True
  41. elif isinstance(val, Iterable):
  42. return all(_check_correct_val(x) for x in val)
  43. return False
  44. def _no_returns(op):
  45. if not isinstance(op, OpOverload):
  46. return False
  47. return len(op._schema.returns) == 0
  48. if "val" not in node.meta:
  49. if node.op == "call_function" and _no_returns(node.target):
  50. return
  51. raise SpecViolationError(f"Node.meta {node.name} is missing val field.")
  52. val = node.meta["val"]
  53. if not _check_correct_val(val):
  54. raise SpecViolationError(f"Node.meta {node.name} has invalid val field {val}")
  55. def _check_torch_fn(node: torch.fx.Node) -> None:
  56. torch_fn = node.meta.get("torch_fn")
  57. if torch_fn is None:
  58. raise SpecViolationError(f"Unable to find torch_fn metadata for node {node.name}")
  59. if (
  60. not isinstance(torch_fn, tuple) and
  61. isinstance(torch_fn[0], str) and
  62. isinstance(torch_fn[1], str)
  63. ):
  64. raise SpecViolationError(f"Node.meta {node.name} has invalid torch_fn field {torch_fn}")
  65. class _VerifierMeta(type):
  66. _registry: Dict[str, Type['Verifier']] = {}
  67. def __new__(metacls, name, bases, attrs):
  68. if bases:
  69. if "check" in attrs or "_check_graph_module" in attrs:
  70. raise SyntaxError("Overriding method check is not allowed.")
  71. assert "dialect" in attrs and attrs["dialect"] != "ATEN"
  72. else:
  73. assert "check" in attrs
  74. assert "_check_graph_module" in attrs
  75. assert attrs["dialect"] == "ATEN"
  76. assert isinstance(attrs["dialect"], str)
  77. ret = type.__new__(metacls, name, bases, attrs)
  78. metacls._registry[attrs["dialect"]] = ret # type: ignore[assignment]
  79. return ret
  80. def getattr_recursive(obj: Any, target: str) -> Any:
  81. target_atoms = target.split('.')
  82. attr_itr = obj
  83. for i, atom in enumerate(target_atoms):
  84. if not hasattr(attr_itr, atom):
  85. raise RuntimeError(f"Node referenced nonexistent target {'.'.join(target_atoms[:i])}")
  86. attr_itr = getattr(attr_itr, atom)
  87. return attr_itr
  88. class Verifier(metaclass=_VerifierMeta):
  89. dialect = "ATEN"
  90. def allowed_builtin_ops(self) -> List:
  91. return [
  92. operator.getitem,
  93. operator.add,
  94. operator.mul,
  95. operator.sub,
  96. operator.truediv,
  97. operator.ge,
  98. operator.le,
  99. operator.gt,
  100. operator.lt,
  101. operator.eq,
  102. operator.ne,
  103. operator.floordiv,
  104. operator.mod,
  105. operator.and_,
  106. operator.or_,
  107. operator.not_,
  108. operator.pow,
  109. operator.neg,
  110. operator.abs,
  111. math.ceil,
  112. math.floor,
  113. ]
  114. def allowed_op_types(self) -> Tuple[Type[Any], ...]:
  115. from torch._export.serde.serialize import allowed_registered_op_types # Avoid circular import.
  116. return (OpOverload, HigherOrderOperator, *allowed_registered_op_types())
  117. def allowed_getattr_types(self) -> Tuple[Type[Any], ...]:
  118. return (torch.fx.GraphModule,)
  119. def check_valid_op(self, op):
  120. pass
  121. def check_additional(self, gm: GraphModule) -> None:
  122. """
  123. Additional checks that are specific to some dialects.
  124. """
  125. pass
  126. @final
  127. def check(self, ep: ExportedProgram) -> None:
  128. self._check_graph_module(ep.graph_module)
  129. _verify_exported_program_signature(ep)
  130. @final
  131. def _check_graph_module(self, gm: torch.fx.GraphModule) -> None:
  132. def _allowed_getattr_types() -> Tuple[Type[Any], ...]:
  133. ret = self.allowed_getattr_types()
  134. assert not any(t is object for t in ret)
  135. return ret
  136. def _check_valid_op(op) -> None:
  137. def _allowed_builtin_ops() -> List:
  138. ret = self.allowed_builtin_ops()
  139. assert all(inspect.isbuiltin(op) for op in ret)
  140. return ret
  141. def _allowed_op_types() -> Tuple[Type[Any], ...]:
  142. ret = self.allowed_op_types()
  143. assert not any(t is object for t in ret)
  144. return ret
  145. # TODO Remove this allowlist.
  146. _allowed_torch_functions = (
  147. torch.autograd.grad_mode.set_grad_enabled,
  148. torch.sym_int,
  149. torch.sym_float,
  150. torch.sym_ite,
  151. torch.sym_max,
  152. torch.sym_min,
  153. torch.sym_not,
  154. torch.sym_sqrt,
  155. # TODO (tmanlaibaatar)
  156. # Predispatch export is able to contain autograd ops.
  157. # These will be modeled as HOO later
  158. torch._C._set_grad_enabled,
  159. )
  160. if not isinstance(op, _allowed_op_types()):
  161. if op not in _allowed_builtin_ops() and op not in _allowed_torch_functions:
  162. raise SpecViolationError(
  163. f"Operator '{op}' is not an allowed operator type: {_allowed_op_types()}\n"
  164. f"Valid builtin ops: {_allowed_builtin_ops()}"
  165. f"Valid torch functions: {_allowed_torch_functions}"
  166. )
  167. if isinstance(op, OpOverload):
  168. # All ops functional
  169. if not is_functional(op):
  170. raise SpecViolationError(
  171. f"operator '{op}' is not functional"
  172. )
  173. self.check_valid_op(op)
  174. for mod in gm.modules():
  175. if not isinstance(mod, torch.fx.GraphModule):
  176. continue
  177. mod.graph.lint()
  178. for node in mod.graph.nodes:
  179. # TODO(T140410192): should have fake tensor for all dialects
  180. if node.op in {"call_module", "call_method"}:
  181. raise SpecViolationError(
  182. f"call_module is not valid: got a class '{node.target}' ",
  183. )
  184. elif node.op == "call_function":
  185. _check_val(node)
  186. _check_valid_op(node.target)
  187. elif node.op == "get_attr":
  188. if not isinstance(node.target, str):
  189. raise SpecViolationError(
  190. f"Expected get_attr target to be string, but got {type(node.target)}"
  191. )
  192. attr = getattr_recursive(mod, node.target)
  193. if isinstance(attr, torch.nn.Module):
  194. def _is_type(name, ty):
  195. return isinstance(getattr(attr, name, None), ty)
  196. if type(attr).__name__ == "LoweredBackendModule":
  197. if _is_type("backend_id", str) \
  198. and _is_type("processed_bytes", bytes) \
  199. and _is_type("compile_specs", list) \
  200. and hasattr(attr, "original_module"):
  201. continue
  202. else:
  203. backend_id = getattr(attr, "backend_id", None)
  204. processed_bytes = getattr(attr, "processed_bytes", None)
  205. compile_specs = getattr(attr, "compile_specs", None)
  206. raise SpecViolationError(
  207. f"Invalid get_attr type {type(attr)}. \n"
  208. f"LoweredBackendModule fields: "
  209. f"backend_id(str) : {type(backend_id)}, "
  210. f"processed_bytes(bytes) : {type(processed_bytes)}, "
  211. f"compile_specs(list) : {type(compile_specs)}"
  212. )
  213. if not isinstance(attr, _allowed_getattr_types()):
  214. raise SpecViolationError(
  215. f"Invalid get_attr type {type(attr)}. \n"
  216. f"Valid get_attr types: {_allowed_getattr_types()}"
  217. )
  218. elif node.op == "placeholder":
  219. _check_val(node)
  220. # TODO(zhxchen17)
  221. # elif node.op == "output":
  222. # _check_flattened_outputs()
  223. self.check_additional(gm)
  224. def _verify_exported_program_signature(exported_program) -> None:
  225. # Check ExportedProgram signature matches
  226. gs = exported_program.graph_signature
  227. # Check every node in the signature exists in the graph
  228. input_node_names = [node.name for node in exported_program.graph.nodes if node.op == "placeholder"]
  229. if len(input_node_names) != len(gs.input_specs):
  230. raise SpecViolationError(
  231. f"Number of graph inputs ({len(input_node_names)}) "
  232. f"does not match number of inputs in the graph signature ({len(gs.user_inputs)})"
  233. )
  234. for input_spec, node in zip(gs.input_specs, input_node_names):
  235. if isinstance(input_spec.arg, (TensorArgument, SymIntArgument)):
  236. if input_spec.arg.name != node:
  237. raise SpecViolationError(
  238. f"Input spec name {input_spec.arg.name} does not match node name {node}"
  239. )
  240. if input_spec.kind == InputKind.USER_INPUT:
  241. continue
  242. elif input_spec.kind == InputKind.PARAMETER:
  243. if not isinstance(input_spec.arg, TensorArgument):
  244. raise SpecViolationError(
  245. f"Parameter {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead."
  246. )
  247. if input_spec.target is None:
  248. raise SpecViolationError(
  249. f"InputSpec for {input_spec.name} has no target."
  250. )
  251. param = input_spec.target
  252. if param not in exported_program.state_dict:
  253. raise SpecViolationError(
  254. f"Parameter {param} is not in the state dict."
  255. )
  256. if not isinstance(exported_program.state_dict[param], torch.nn.Parameter):
  257. raise SpecViolationError(
  258. f"State dict entry for parameter {param} is not an instance of torch.nn.Parameter."
  259. )
  260. elif input_spec.kind == InputKind.BUFFER:
  261. if not isinstance(input_spec.arg, TensorArgument):
  262. raise SpecViolationError(
  263. f"Buffer {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead."
  264. )
  265. if input_spec.target is None:
  266. raise SpecViolationError(
  267. f"InputSpec for {input_spec.name} has no target."
  268. )
  269. buffer = input_spec.target
  270. if input_spec.persistent is None:
  271. raise SpecViolationError(
  272. f"Buffer {buffer} is missing a persistence flag"
  273. )
  274. if input_spec.persistent is True and buffer not in exported_program.state_dict:
  275. raise SpecViolationError(
  276. f"Buffer {buffer} is not in the state dict."
  277. )
  278. if input_spec.persistent is False and buffer in exported_program.state_dict:
  279. raise SpecViolationError(
  280. f"Non-persistent buffer {buffer} is in the state dict, it should not be."
  281. )
  282. elif input_spec.kind == InputKind.CONSTANT_TENSOR:
  283. if not isinstance(input_spec.arg, TensorArgument):
  284. raise SpecViolationError(
  285. f"Constant tensor {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead."
  286. )
  287. if input_spec.target is None:
  288. raise SpecViolationError(
  289. f"InputSpec for {input_spec.name} has no target."
  290. )
  291. tensor_const = input_spec.target
  292. if tensor_const not in exported_program.constants:
  293. raise SpecViolationError(
  294. f"Constant tensor {tensor_const} is not in the constants dictionary."
  295. )
  296. elif input_spec.kind == InputKind.CUSTOM_OBJ:
  297. if not isinstance(input_spec.arg, CustomObjArgument):
  298. raise SpecViolationError(
  299. f"Custom object {input_spec.name} is not a custom object argument. Found {input_spec.arg} instead."
  300. )
  301. if input_spec.target is None:
  302. raise SpecViolationError(
  303. f"InputSpec for {input_spec.name} has no target."
  304. )
  305. custom_obj = input_spec.target
  306. if custom_obj not in exported_program.constants:
  307. raise SpecViolationError(
  308. f"Custom object {custom_obj} is not in the constants dictionary."
  309. )
  310. elif input_spec.kind == InputKind.TOKEN:
  311. if not isinstance(input_spec.arg, TokenArgument):
  312. raise SpecViolationError(
  313. f"Constant tensor {input_spec.name} is not a tensor argument. Found {input_spec.arg} instead."
  314. )
  315. else:
  316. raise SpecViolationError(
  317. f"Unknown InputKind {input_spec.kind}."
  318. )
  319. # Check outputs
  320. output_node = list(exported_program.graph.nodes)[-1]
  321. assert output_node.op == "output"
  322. output_nodes = [
  323. arg.name if isinstance(arg, torch.fx.Node) else arg
  324. for arg in output_node.args[0]
  325. ]
  326. if len(output_nodes) != len(gs.output_specs):
  327. raise SpecViolationError(
  328. f"Number of output nodes {len(output_nodes)} is different "
  329. "Than the number of outputs specified by the graph signature: \n"
  330. f"Number of mutated buffers: {len(gs.buffers_to_mutate)}. \n"
  331. f"Number of user outputs: {len(gs.user_outputs)}. \n"
  332. )
  333. num_tokens = len(gs.output_tokens)
  334. end = len(gs.buffers_to_mutate) + len(gs.user_inputs_to_mutate) + num_tokens
  335. mutate_nodes: List[str] = output_nodes[num_tokens:end]
  336. user_output_nodes = output_nodes[end:end + len(gs.user_outputs)]
  337. for mutation_node in mutate_nodes:
  338. if mutation_node in gs.buffers_to_mutate:
  339. if gs.buffers_to_mutate[mutation_node] not in gs.buffers:
  340. raise SpecViolationError(
  341. f"Buffer output {mutation_node} does not point to a buffer that exists. \n"
  342. f"Dict of buffers that are mutated, in order: {gs.buffers_to_mutate} \n"
  343. f"Buffer nodes available: {gs.buffers} \n"
  344. )
  345. elif mutation_node in gs.user_inputs_to_mutate:
  346. if gs.user_inputs_to_mutate[mutation_node] not in gs.user_inputs:
  347. raise SpecViolationError(
  348. f"User input output {mutation_node} does not point to a user input that exists. \n"
  349. f"Dict of user inputs that are mutated, in order: {gs.user_inputs_to_mutate} \n"
  350. f"User input nodes available: {gs.user_inputs} \n")
  351. else:
  352. raise SpecViolationError(
  353. f"Mutation node {mutation_node} is neither a buffer nor a user input. "
  354. f"Buffers to mutate: {gs.buffers_to_mutate}, User inputs to mutate: {gs.user_inputs_to_mutate}"
  355. )
  356. for user_output_node, user_output_name in zip(user_output_nodes, gs.user_outputs):
  357. if user_output_node != user_output_name:
  358. raise SpecViolationError(
  359. f"User output {user_output_node} is not in the correct "
  360. "order or is not found in the "
  361. f"exported program's user_output list: {gs.user_outputs}. "
  362. )
  363. def load_verifier(dialect: str) -> Optional[Type[Verifier]]:
  364. if dialect == "ATEN" or dialect == "":
  365. return _VerifierMeta._registry.get(dialect)
  366. return _VerifierMeta._registry[dialect]