CollapseDims.h 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <c10/util/Exception.h>
  2. #include <utility>
  3. namespace at {
  4. /*
  5. [collapse dims] Updates sizes, and strides to reflect a "collapse" of
  6. the info, possibly excluding the optional excludeDim. A "collapsed" version
  7. of the info is the fewest dims that order the tensor's elements in the same
  8. way as the original info. If excludeDim is specified, the collapse is the
  9. fewest dims that order the tensor's elements as the original and preserve the
  10. excluded dimension, unless the tensor collapses to a point.
  11. This function returns a pair of values.
  12. 1) The (new) index of the preserved dimension if excludeDim is
  13. specified. 0 if the tensor is collapsed to a point. -1
  14. otherwise.
  15. 2) The new number of dimensions.
  16. */
  17. template <typename T>
  18. inline std::pair<int64_t, int64_t> collapse_dims(
  19. T* sizes,
  20. T* strides,
  21. int64_t dims,
  22. const int excludeDim = -1) {
  23. TORCH_CHECK(
  24. excludeDim >= -1 && excludeDim < dims,
  25. "expected excluded dim between -1 and dims - 1");
  26. int64_t stopDim = (excludeDim == -1) ? dims : excludeDim;
  27. int64_t newIndex = -1;
  28. int64_t oldIndex = 0;
  29. int64_t remappedExcludedDim = -1;
  30. while (oldIndex < dims) {
  31. // Finds a dimension to collapse into
  32. for (; oldIndex < stopDim; ++oldIndex) {
  33. if (sizes[oldIndex] == 1) {
  34. continue;
  35. }
  36. ++newIndex;
  37. sizes[newIndex] = sizes[oldIndex];
  38. strides[newIndex] = strides[oldIndex];
  39. ++oldIndex;
  40. break;
  41. }
  42. // Collapses dims
  43. for (; oldIndex < stopDim; ++oldIndex) {
  44. if (sizes[oldIndex] == 1) {
  45. continue;
  46. }
  47. if (strides[newIndex] == sizes[oldIndex] * strides[oldIndex]) {
  48. sizes[newIndex] *= sizes[oldIndex];
  49. strides[newIndex] = strides[oldIndex];
  50. } else {
  51. ++newIndex;
  52. sizes[newIndex] = sizes[oldIndex];
  53. strides[newIndex] = strides[oldIndex];
  54. }
  55. }
  56. // Handles excludeDim being set (oldIndex == excludeDim)
  57. if (oldIndex != dims) {
  58. // Preserves excluded dimension
  59. ++newIndex;
  60. sizes[newIndex] = sizes[oldIndex];
  61. strides[newIndex] = strides[oldIndex];
  62. remappedExcludedDim = newIndex;
  63. // Restarts iteration after excludeDim
  64. ++oldIndex;
  65. stopDim = dims;
  66. }
  67. }
  68. // Handles special case of all dims size 1
  69. if (newIndex == -1 || (newIndex == 0 && sizes[0] == 1)) {
  70. dims = 1;
  71. sizes[0] = 1;
  72. strides[0] = 1;
  73. return std::pair<int64_t, int64_t>(0, 1);
  74. }
  75. dims = newIndex + 1;
  76. return std::pair<int64_t, int64_t>(remappedExcludedDim, dims);
  77. }
  78. } // namespace at