decomp_utils.py 5.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156
  1. # mypy: allow-untyped-defs
  2. from typing import Callable
  3. import torch
  4. from torch._export.utils import (
  5. _collect_all_valid_cia_ops,
  6. _collect_all_valid_cia_ops_for_aten_namespace,
  7. _get_decomp_for_cia,
  8. _is_aten_op,
  9. )
  10. __all__ = ["CustomDecompTable"]
  11. """
  12. Core ATen ops with Composite Implicit Autograd dispatch that should be excluded from decomposition
  13. by default. The decomposition logic should eventually exclude all core-tagged CIA ops, but until all
  14. backends are ready, this list allows opt-in one at a time.
  15. """
  16. PRESERVED_ATEN_CIA_OPS = {
  17. torch.ops.aten.upsample_bilinear2d.vec,
  18. torch.ops.aten.upsample_nearest2d.vec,
  19. }
  20. class CustomDecompTable(dict[torch._ops.OperatorBase, Callable]):
  21. """
  22. This is a custom dictionary that is specifically used for handling decomp_table in export.
  23. The reason we need this is because in the new world, you can only *delete* an op from decomp
  24. table to preserve it. This is problematic for custom ops because we don't know when the custom
  25. op will actually be loaded to the dispatcher. As a result, we need to record the custom ops operations
  26. until we really need to materialize it (which is when we run decomposition pass.)
  27. Invariants we hold are:
  28. 1. All aten decomp is loaded at the init time
  29. 2. We materialize ALL ops when user ever reads from the table to make it more likely
  30. that dispatcher picks up the custom op.
  31. 3. If it is write operation, we don't necessarily materialize
  32. 4. We load the final time during export, right before calling run_decompositions()
  33. """
  34. def __init__(self):
  35. super().__init__()
  36. from torch._decomp import _core_aten_decompositions_post_autograd
  37. # For aten ops, we load them up in the beginning
  38. self.decomp_table = _core_aten_decompositions_post_autograd()
  39. for op in _collect_all_valid_cia_ops_for_aten_namespace():
  40. if op not in PRESERVED_ATEN_CIA_OPS:
  41. self.decomp_table[op] = _get_decomp_for_cia(op)
  42. # This is to track the *pending* deleted custom ops that haven't been materialized yet
  43. self.deleted_custom_ops = set()
  44. # When this is true, there shouldn't be any pending operations in the table.
  45. self.has_materialized = False
  46. def __getitem__(self, key):
  47. self._materialize_if_needed()
  48. return self.decomp_table.__getitem__(key)
  49. def __setitem__(self, key, value) -> None:
  50. self.decomp_table.__setitem__(key, value)
  51. if key in self.deleted_custom_ops:
  52. self.deleted_custom_ops.remove(key)
  53. def keys(self):
  54. self._materialize_if_needed()
  55. return self.decomp_table.keys()
  56. def __delitem__(self, key) -> None:
  57. self.pop(key)
  58. def update(self, other_dict): # type: ignore[override]
  59. for k, v in other_dict.items():
  60. self.decomp_table.__setitem__(k, v)
  61. def __missing__(self, key) -> bool:
  62. return not self.__contains__(key)
  63. def __contains__(self, key) -> bool:
  64. self._materialize_if_needed()
  65. return self.decomp_table.__contains__(key)
  66. def __len__(self) -> int:
  67. self._materialize_if_needed()
  68. return self.decomp_table.__len__()
  69. def __iter__(self):
  70. self._materialize_if_needed()
  71. return self.decomp_table.__iter__()
  72. def __reversed__(self):
  73. self._materialize_if_needed()
  74. return self.decomp_table.__reversed__()
  75. def copy(self) -> "CustomDecompTable":
  76. new_dict = CustomDecompTable()
  77. new_dict.decomp_table = self.decomp_table.copy()
  78. new_dict.deleted_custom_ops = self.deleted_custom_ops.copy()
  79. new_dict.has_materialized = self.has_materialized
  80. return new_dict
  81. def pop(self, *args):
  82. def _pop_if_can(key):
  83. if _is_aten_op(key):
  84. return self.decomp_table.pop(key)
  85. if key in self.decomp_table:
  86. # Even if we materialized it, we should add it to the deleted
  87. # custom ops list so that when we materialize next time,
  88. # we should respect user's intention.
  89. self.deleted_custom_ops.add(key)
  90. return self.decomp_table.pop(key)
  91. if key in self.deleted_custom_ops:
  92. raise KeyError(f"{key} doesn't exist in the table")
  93. self.deleted_custom_ops.add(key)
  94. # We would come here when user pops off something that is
  95. # not in the table. In this case, we just pretend that it
  96. # was in the table.
  97. return _get_decomp_for_cia(key)
  98. if len(args) == 1:
  99. return _pop_if_can(args[0])
  100. if len(args) == 2:
  101. try:
  102. return _pop_if_can(args[0])
  103. except KeyError:
  104. return args[1]
  105. def items(self):
  106. self._materialize_if_needed()
  107. return self.decomp_table.items()
  108. def materialize(self) -> dict[torch._ops.OperatorBase, Callable]:
  109. for op in _collect_all_valid_cia_ops():
  110. if _is_aten_op(op):
  111. continue
  112. elif op in self.decomp_table:
  113. continue
  114. elif op not in self.deleted_custom_ops:
  115. self.decomp_table[op] = _get_decomp_for_cia(op)
  116. self.has_materialized = True
  117. self.deleted_custom_ops = set()
  118. return {**self.decomp_table}
  119. def _materialize_if_needed(self) -> None:
  120. if not self.has_materialized:
  121. self.materialize()