FunctionalStorageImpl.h 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. #pragma once
  2. #include <ATen/Tensor.h>
  3. #include <utility>
  4. namespace at::functionalization {
  5. // See Note [Functionalization Pass In Core]
  6. enum class InverseReturnMode {
  7. /// Specifies that functional inverses should always return a view.
  8. AlwaysView,
  9. /// Specifies that functional inverses should always return a non-view / copy.
  10. NeverView,
  11. /// Specifies that functional inverses should return a view unless a (copying)
  12. /// scatter
  13. /// inverse exists, in which case that will be used instead.
  14. /// This avoids as_strided() calls that can be difficult for subclasses to
  15. /// handle.
  16. ViewOrScatterInverse,
  17. };
  18. #define FUNCTIONALIZATION_VIEWMETA_NAME(TYPE) \
  19. static const char* name() { \
  20. return #TYPE; \
  21. }
  22. #define FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE(...) \
  23. using SerializableTuple = std::tuple<__VA_ARGS__>
  24. // ViewMeta is a class used by the functionalization pass to navigate between
  25. // a base tensor and a view tensor.
  26. // For example, if I call `b = a.view1(...)`
  27. // the functionalization pass will generate and store a ViewMeta specialization
  28. // for `view1` operation on b that looks like:
  29. //
  30. // struct TORCH_API view1_ViewMeta : public ViewMeta {
  31. // FUNCTIONALIZATION_VIEWMETA_NAME(view1_ViewMeta);
  32. // FUNCTIONALIZATION_VIEWMETA_SERIALIZABLE_TUPLE(
  33. // bool /* reapply_views */,
  34. // const std::vector<int64_t>&);
  35. //
  36. // view1_ViewMeta(const SerializableTuple& tpl)
  37. // : view1_ViewMeta(std::get<0>(tpl), std::get<1>(tpl)) {}
  38. //
  39. // view1_ViewMeta(bool reapply_views, const std::vector<int64_t>& size)
  40. // : ViewMeta(/*has_symbolic_inputs=*/false),
  41. // reapply_views(reapply_views),
  42. // size(size) {}
  43. //
  44. // Tensor forward(const Tensor& base) override {
  45. // return base.view1(...);
  46. // }
  47. //
  48. // Tensor reverse(const Tensor& base, const Tensor& mutated_view) override {
  49. // return at::functionalization::impl::view1_inverse(base, mutated_view,
  50. // ...);
  51. // }
  52. //
  53. // SerializableTuple to_serializable_tuple() {
  54. // return std::make_tuple(reapply_views, size);
  55. // }
  56. //
  57. // bool reapply_views;
  58. // std::vector<int64_t> size;
  59. // };
  60. //
  61. // The forward function describes how to replay view1 on a tensor.
  62. //
  63. // The reverse function describes how, given a tensor that is already a view,
  64. // how to get the corresponding base tensor. See Note [Functionalization Pass:
  65. // View Inverses] for details.
  66. //
  67. // `SerializedTuple` is a typedef that defines an `std::tuple<...>` type
  68. // representing the `ViewMeta` instance state. Methods that take in/return such
  69. // a type are used for supporting pickle serialization.
  70. struct ViewMeta {
  71. ViewMeta(
  72. bool has_symbolic_inputs,
  73. bool is_multi_output = false,
  74. bool is_as_strided = false,
  75. int64_t out_idx = 0)
  76. : out_index(out_idx),
  77. is_multi_output(is_multi_output),
  78. is_as_strided(is_as_strided),
  79. has_symbolic_inputs(has_symbolic_inputs) {}
  80. virtual ~ViewMeta() = default;
  81. virtual Tensor forward(const Tensor& base) = 0;
  82. virtual Tensor reverse(const Tensor& base, const Tensor& mutated_view) = 0;
  83. // See Note [out_idx in ViewMeta]
  84. int64_t out_index;
  85. // Tells us if this is a multi-output view
  86. bool is_multi_output;
  87. bool is_as_strided;
  88. // Tells us if this view operation has any symbolic inputs
  89. bool has_symbolic_inputs;
  90. // Returns a new ViewMeta with the same forward/reverse
  91. // functions, but a new out index.
  92. //
  93. // This method should be implemented by those `ViewMeta` that have more than
  94. // one output.
  95. virtual std::shared_ptr<ViewMeta> to_out_index(int64_t out_index) {
  96. TORCH_CHECK_NOT_IMPLEMENTED(
  97. false,
  98. "ViewMeta::to_out_index not implemented. ",
  99. "Likely because there's only one output.");
  100. }
  101. };
  102. // FunctionalStorageImpl is a subclass of StorageImpl used by the
  103. // functionalization pass. It has no underlying data (similar to meta storage).
  104. // It also knows how to reflect mutations to tensors in the absence of a valid
  105. // data pointer.
  106. //
  107. // A storage represents the state shared by (potentially multiple) views of the
  108. // same tensor. For example, in the following code:
  109. //
  110. // b = a.view1(...)
  111. // c = b.view2(...)
  112. // b.add_(1)
  113. // --> storage.add_update(b, {view1_meta})
  114. //
  115. // The call to add_(1) will result in a call to alias.add_update(b,
  116. // {view1_meta}), queueing up the mutation from b onto the alias. Later, suppose
  117. // c is used in an expression (e.g. you try to print c, or pass it to an
  118. // operator). Doing so will involve "syncing" c. First we apply any pending
  119. // updates to the alias, and then we regenerate c by replaying its views off of
  120. // the updated alias. E.g:
  121. //
  122. // print(str(c))
  123. // --> c.sync_()
  124. // --> alias.apply_updates() // after this, the alias will be updated to
  125. // reflect the mutation to b
  126. struct TORCH_API FunctionalStorageImpl : public c10::StorageImpl {
  127. public:
  128. struct Update {
  129. // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
  130. const at::Tensor new_val;
  131. // NOLINTNEXTLINE(cppcoreguidelines-avoid-const-or-ref-data-members)
  132. const std::vector<std::shared_ptr<ViewMeta>> view_metas;
  133. };
  134. explicit FunctionalStorageImpl(const Tensor& value);
  135. void add_update(
  136. const Tensor& updated_val,
  137. const std::vector<std::shared_ptr<ViewMeta>>& view_metas);
  138. bool apply_updates();
  139. const Tensor& base() {
  140. return base_;
  141. }
  142. size_t generation() const {
  143. return generation_;
  144. }
  145. void freeze() {
  146. frozen_ = true;
  147. }
  148. c10::SymInt get_storage_size(bool before) {
  149. if (before) {
  150. return original_storage_size_;
  151. } else {
  152. return curr_storage_size_;
  153. }
  154. }
  155. ~FunctionalStorageImpl() override = default;
  156. uint64_t mutation_counter() {
  157. return mutation_counter_;
  158. }
  159. void mark_mutation() {
  160. mutation_counter_++;
  161. }
  162. void mark_mutation_during_no_grad_or_inference_mode() {
  163. mutation_counter_during_no_grad_or_inference_mode_++;
  164. }
  165. void mark_mutation_hidden_from_autograd() {
  166. mutation_counter_hidden_from_autograd_++;
  167. }
  168. bool are_all_mutations_under_no_grad_or_inference_mode() const {
  169. auto non_autograd_mutations =
  170. mutation_counter_during_no_grad_or_inference_mode_ +
  171. mutation_counter_hidden_from_autograd_;
  172. // The <= is because both counters will technically be incremented, if we
  173. // perform e.g. a triton kernel mutation under no_grad
  174. return mutation_counter_ <= non_autograd_mutations;
  175. }
  176. bool are_all_mutations_hidden_from_autograd() const {
  177. // mutations under no_grad / inference_mode are technically not hidden from
  178. // autograd - they change the version counter
  179. return mutation_counter_ <= mutation_counter_hidden_from_autograd_;
  180. }
  181. void mark_inductor_storage_resize(c10::SymInt new_size) {
  182. inductor_storage_resized_ = true;
  183. curr_storage_size_ = std::move(new_size);
  184. inductor_storage_resized_counter_++;
  185. }
  186. bool was_inductor_storage_resized() {
  187. return inductor_storage_resized_;
  188. }
  189. uint64_t inductor_storage_resized_counter() {
  190. return inductor_storage_resized_counter_;
  191. }
  192. private:
  193. // NB: base_ should always point to a tensor BELOW the current
  194. // functionalization layer. This is mainly to avoid reference cycles. e.g.
  195. // given `b = a.view(...)` Both a.storage_ and b.storage_ are a
  196. // FunctionStorageImpl containing an Walualias, with contains a Tensor
  197. // `base_`. In this case (where a and b are FunctionalTensorWrapper's), base_
  198. // should point not to a, but to a's unwrapped value, a.value_` See Note
  199. // [Functionalization: Walualias Removal] for a diagram that shows this
  200. // visually.
  201. at::Tensor base_;
  202. std::vector<Update> updates_;
  203. // generation_ gets incremented every time a mutation is queued onto the
  204. // alias. It is used to determine if a given tensor is "up to date", or if it
  205. // needs to be regenerated from the alias.
  206. size_t generation_ = 0;
  207. // If frozen, no more mutations are allowed on this storage. Once frozen, a
  208. // storage cannot be unfrozen.
  209. bool frozen_ = false;
  210. // These mutation counters are bumped on the storage
  211. // whenever a FunctionalTensorWrapper experiences a mutation.
  212. // When the mutation is under no_grad, or comes from a triton kernel, we also
  213. // bump the corresponding during_no_grad or hidden_from_autograd counters. Why
  214. // do we need to detect these two situations separately from "normal" input
  215. // mutations? (1) "normal" input mutations can mutate autograd metadata like
  216. // .grad_fn,
  217. // in which case they need to be replayed outside of the compiled graph
  218. // (2) "no_grad" input mutations are generally safe to keep in the graph (and
  219. // compile),
  220. // but they bump the tensor's VC, so we need to mark_dirty() on the inputs
  221. // in torch.compile
  222. // (3) mutations that are fully hidden from autograd (e.g. from a triton
  223. // kernel)
  224. // do not mutate any autograd state, and be fully kept in the graph
  225. // When we detect that an input was mutated, we need to be able to tell if:
  226. // (1) all of the mutations were from triton kernels
  227. // (2) all of the mutations were under no_grad
  228. uint64_t mutation_counter_during_no_grad_or_inference_mode_ = 0;
  229. uint64_t mutation_counter_ = 0;
  230. uint64_t mutation_counter_hidden_from_autograd_ = 0;
  231. // Used to tell if:
  232. // (1) There were any storage resizes on a graph input
  233. // (2) The original/curr storage size tell us if these resizes result in a nop
  234. bool inductor_storage_resized_ = false;
  235. uint64_t inductor_storage_resized_counter_ = 0;
  236. c10::SymInt original_storage_size_;
  237. c10::SymInt curr_storage_size_;
  238. };
  239. } // namespace at::functionalization