_pytree.py 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103
  1. # mypy: allow-untyped-defs
  2. from collections import namedtuple
  3. from typing import Any, Callable, Dict, List, NamedTuple, Optional, Tuple, Type
  4. import torch.return_types
  5. from torch.utils._pytree import PyTree, TreeSpec
  6. FlattenFuncSpec = Callable[[PyTree, TreeSpec], List]
  7. FlattenFuncExactMatchSpec = Callable[[PyTree, TreeSpec], bool]
  8. SUPPORTED_NODES: Dict[Type[Any], FlattenFuncSpec] = {}
  9. SUPPORTED_NODES_EXACT_MATCH: Dict[Type[Any], Optional[FlattenFuncExactMatchSpec]] = {}
  10. def register_pytree_flatten_spec(
  11. cls: Type[Any],
  12. flatten_fn_spec: FlattenFuncSpec,
  13. flatten_fn_exact_match_spec: Optional[FlattenFuncExactMatchSpec] = None,
  14. ) -> None:
  15. SUPPORTED_NODES[cls] = flatten_fn_spec
  16. SUPPORTED_NODES_EXACT_MATCH[cls] = flatten_fn_exact_match_spec
  17. def tree_flatten_spec(
  18. pytree: PyTree,
  19. spec: TreeSpec,
  20. exact_structural_match=False,
  21. ) -> List[Any]:
  22. if spec.is_leaf():
  23. return [pytree]
  24. if spec.type not in SUPPORTED_NODES:
  25. raise RuntimeError(
  26. f"{type(pytree)} does not have a flatten_fn_spec associated with it. Please register one with "
  27. "torch.fx._pytree.register_pytree_flatten_spec. If you have serialized your model, make "
  28. "sure that any custom pytrees have been registered before loading it.",
  29. )
  30. flatten_fn_spec = SUPPORTED_NODES[spec.type]
  31. child_pytrees = flatten_fn_spec(pytree, spec)
  32. if exact_structural_match:
  33. flatten_fn_exact_match_spec = SUPPORTED_NODES_EXACT_MATCH[spec.type]
  34. if flatten_fn_exact_match_spec and not flatten_fn_exact_match_spec(
  35. pytree,
  36. spec,
  37. ):
  38. raise RuntimeError(f"Cannot flatten pytree {pytree}, given spec: {spec}")
  39. result = []
  40. for child, child_spec in zip(child_pytrees, spec.children_specs):
  41. flat = tree_flatten_spec(child, child_spec, exact_structural_match)
  42. result += flat
  43. return result
  44. def _dict_flatten_spec(d: Dict[Any, Any], spec: TreeSpec) -> List[Any]:
  45. return [d[k] for k in spec.context]
  46. def _list_flatten_spec(d: List[Any], spec: TreeSpec) -> List[Any]:
  47. return [d[i] for i in range(spec.num_children)]
  48. def _tuple_flatten_spec(d: Tuple[Any], spec: TreeSpec) -> List[Any]:
  49. return [d[i] for i in range(spec.num_children)]
  50. def _namedtuple_flatten_spec(d: NamedTuple, spec: TreeSpec) -> List[Any]:
  51. return [d[i] for i in range(spec.num_children)]
  52. def _dict_flatten_spec_exact_match(d: Dict[Any, Any], spec: TreeSpec) -> bool:
  53. return len(d) == spec.num_children
  54. def _list_flatten_spec_exact_match(d: List[Any], spec: TreeSpec) -> bool:
  55. return len(d) == spec.num_children
  56. def _tuple_flatten_spec_exact_match(d: Tuple[Any], spec: TreeSpec) -> bool:
  57. return len(d) == spec.num_children
  58. def _namedtuple_flatten_spec_exact_match(d: NamedTuple, spec: TreeSpec) -> bool:
  59. return len(d) == spec.num_children
  60. register_pytree_flatten_spec(dict, _dict_flatten_spec, _dict_flatten_spec_exact_match)
  61. register_pytree_flatten_spec(list, _list_flatten_spec, _list_flatten_spec_exact_match)
  62. register_pytree_flatten_spec(
  63. tuple,
  64. _tuple_flatten_spec,
  65. _tuple_flatten_spec_exact_match,
  66. )
  67. for return_type in torch.return_types.all_return_types:
  68. register_pytree_flatten_spec(
  69. return_type,
  70. _tuple_flatten_spec,
  71. _tuple_flatten_spec_exact_match,
  72. )
  73. register_pytree_flatten_spec(
  74. namedtuple, # type: ignore[arg-type]
  75. _namedtuple_flatten_spec,
  76. _namedtuple_flatten_spec_exact_match,
  77. )