LegacyVmapTransforms.h 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182
  1. #pragma once
  2. #include <ATen/LegacyBatchedTensorImpl.h>
  3. #include <ATen/core/IListRef.h>
  4. namespace at {
  5. // This file contains abstractions used for transforming *logical* vmap
  6. // arguments into *physical* arguments. (Keep reading for definitions of these
  7. // terms).
  8. // NOTE: [Logical vs physical args]
  9. // Consider the following vmap.
  10. // vmap(vmap(func, in_dims=(2,)), in_dims=(0,))(torch.ones(2, 3, 4))
  11. // This would produce a BatchedTensor wrapping a Tensor of size [2, 3, 4],
  12. // with batch dims 0 and 2:
  13. // BatchedTensor(ones(2, 3, 4), bdims=[(lvl=1,dim=0),(lvl=2,dim=2)])
  14. //
  15. // We say the *logical* view of the tensor has size [3] -- tensors inside
  16. // `func` appear to have size [3].
  17. // However, the *physical* underlying tensor (the one passed to vmap) has size
  18. // [2, 3, 4].
  19. //
  20. // This notion of logical vs physical also extends to non-tensor arguments.
  21. // Consider the previous tensor; let's assume the user called
  22. // `torch.sum(tensor, dim=0)` inside of `func`. Then the logical
  23. // dimension they are reducing over is dim 0 but the physical dim is dim 1
  24. // (the first non-batch dimension)
  25. // Forward declared; see NOTE: [What is a VmapPhysicalView?]
  26. struct VmapPhysicalView;
  27. // Most PyTorch operators take 4 or fewer inputs.
  28. constexpr int64_t kVmapTransformStaticInputSize = 4;
  29. using VmapPhysicalViewVec =
  30. SmallVector<VmapPhysicalView, kVmapTransformStaticInputSize>;
  31. // Pytorch generally advertises good performance for <= 5 dims.
  32. // (see ATen/core/DimVector.h). We add a few extra dims (~3) for vmap
  33. // dimensions to get 8. Adjust this number as necessary
  34. constexpr int64_t kVmapStaticDimVecSize = 8;
  35. using VmapDimVector = SmallVector<int64_t, kVmapStaticDimVecSize>;
  36. // NOTE: [What is an VmapTransform?]
  37. // An *VmapTransform* converts logical views of tensors to physical views.
  38. //
  39. // Batching rules use VmapTransforms to convert logical arguments to
  40. // physical arguments, then call one or more at:: operator that handles the
  41. // physical arguments, and then converts the physical result back to a logical
  42. // argument.
  43. // VmapTransform for operators that take tensors with multiple batch dims.
  44. // Given one or more logical views on Tensors, `logicalToPhysical`
  45. // permutes all of the batch dims to the front of the tensor, aligns
  46. // and expands the batch dims to match each other (according to their `level`),
  47. // and returns a VmapPhysicalView on the tensor(s).
  48. struct TORCH_API MultiBatchVmapTransform {
  49. static VmapPhysicalView logicalToPhysical(const Tensor& logical_tensor);
  50. static VmapPhysicalViewVec logicalToPhysical(ITensorListRef logical_tensors);
  51. };
  52. // VmapTransform for operators that broadcast all inputs.
  53. // Given some logical views on Tensors, `logicalToPhysical`:
  54. // - permutes all of the batch dims to the front of the tensors
  55. // - aligns all the batch dims to the collective levels of all of the tensors.
  56. // If a tensor does not have a batch dim for a vmap level, then it receives
  57. // a size-one dimension for said level.
  58. // - aligns the non-batch dims to have the same dimensionality, adding extra
  59. // size-1 dimensions in between the batch dimensions and the non-batch
  60. // dimensions so that the batch dimensions are lined up from the right.
  61. //
  62. // For example: given inputs of size (B, 2) and (B, 3, 2) where B is the batch
  63. // dimension, BroadcastingVmapTransform returns VmapPhysicalViews that wrap
  64. // tensors of size (B, 1, 2) and (B, 3, 2).
  65. //
  66. // Given inputs of size (B, 2) and (2,), BroadcastingVmapTransform returns
  67. // VmapPhysicalViews wrapping tensors of size (B, 2) and (1, 2). We don't
  68. // actually *need* to return a tensor of size (1, 2) for the second tensor
  69. // because the broadcasting operation takes care of that for us, but we do
  70. // it anyways to keep things simple.
  71. struct TORCH_API BroadcastingVmapTransform {
  72. static VmapPhysicalViewVec logicalToPhysical(TensorList logical_tensors);
  73. };
  74. // Forward declared, if you're reading this file head to toe, don't worry about
  75. // it yet.
  76. struct VmapPhysicalToLogicalMap;
  77. // NOTE: [What is a VmapPhysicalView?]
  78. // VmapPhysicalView represents a physical view on a Tensor.
  79. //
  80. // One can use it to further convert logical dimension indices, logical shapes,
  81. // and more to their physical variants, or convert a new (physical) tensor into
  82. // a logical BatchedTensor. (TODO(rzou): some of these are not yet implemented).
  83. //
  84. // VmapPhysicalView stores a physical tensor with all of its batch dimensions at
  85. // the front and some levels that correspond to said batch dimensions.
  86. //
  87. // The levels bitset specifies which vmap levels correspond to the batch
  88. // dimensions at the front of the tensor. In particular, the number of set bits
  89. // corresponds to the number of batch dimensions on `tensor` and the rightmost
  90. // bit of `levels` specifies the maximum number of nested vmaps we are in at
  91. // this point in time.
  92. // For example, given:
  93. // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5, 6), levels={1, 3})
  94. //
  95. // Rightmost bit of `levels` is 3 indicating the number of nested vmaps less
  96. // than or equal to 3.
  97. // bitset: 010100
  98. // ^
  99. // |
  100. // levels: 012345
  101. struct TORCH_API VmapPhysicalView {
  102. VmapPhysicalView(Tensor&& tensor, std::bitset<kVmapNumLevels> levels)
  103. : levels_(levels), tensor_(tensor) {
  104. TORCH_INTERNAL_ASSERT(!isBatchedTensor(tensor));
  105. }
  106. Tensor& tensor() {
  107. return tensor_;
  108. }
  109. const Tensor& tensor() const {
  110. return tensor_;
  111. }
  112. // Maps logical dim indices to physical dim indices. Also does dim wrapping.
  113. //
  114. // For example, given:
  115. // physical_view = VmapPhysicalView(tensor=ones(2, 3, 4, 5), levels={1, 3})
  116. //
  117. // Then physical_view.getPhysicalDims({0, 1}) returns {2, 3}.
  118. // This is because the size of levels tell us that the first two dimensions
  119. // of `tensor_` are batch dimensions, so a logical dim of `n` is actually
  120. // a physical dim of `n + 2`.
  121. VmapDimVector getPhysicalDims(OptionalIntArrayRef logical_dims) const;
  122. int64_t getPhysicalDim(int64_t logical_dim) const;
  123. // Returns a VmapPhysicalToLogicalMap object. This can be used for
  124. // mapping a physical tensor to a new logical tensor (BatchedTensor)
  125. VmapPhysicalToLogicalMap getPhysicalToLogicalMap() const;
  126. // Maps a logical shape to a physical shape by pre-pending the batch
  127. // sizes to the logical shape.
  128. VmapDimVector getPhysicalShape(IntArrayRef logical_shape) const;
  129. int64_t numBatchDims() const;
  130. private:
  131. int64_t numLogicalDims() const;
  132. std::bitset<kVmapNumLevels> levels_;
  133. Tensor tensor_;
  134. };
  135. // Convenience struct used for mapping a physical tensor (a non-BatchedTensor)
  136. // to a logical one (BatchedTensor). It holds some levels that are used to do
  137. // the mapping and assumes that the batch dimensions in the physical tensor all
  138. // occur at the front of the tensor.
  139. struct TORCH_API VmapPhysicalToLogicalMap {
  140. VmapPhysicalToLogicalMap(std::bitset<kVmapNumLevels> levels)
  141. : levels_(levels) {}
  142. // Maps a physical tensor to a new logical tensor (BatchedTensor).
  143. // Assumes that all of the "batch dimensions" are at the front
  144. // of the physical tensor. For example, given:
  145. // - x = rank-4 Tensor with size 2, 3, 5, 7
  146. // - levels = (2, 4)
  147. // Returns:
  148. // - BatchedTensor(x, bdims=[(dim=0,lvl=2), (dim=1, lvl=4)])
  149. Tensor apply(const Tensor& physical_tensor) const;
  150. // Given a vector of physical tensors,
  151. // 1. maps each tensor to a new logical tensor. Assumes that all of the
  152. // "batch dimensions" are at the front of the physical tensors.
  153. // 2. stores the new logical tensors back into the passed-in vector. This is
  154. // to avoid additional dynamic allocations.
  155. void applyInplace(std::vector<Tensor>& physical_tensors) const;
  156. std::bitset<kVmapNumLevels> levels_;
  157. };
  158. } // namespace at