ConvUtils.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405
  1. #pragma once
  2. #include <ATen/core/Tensor.h>
  3. #include <ATen/TensorUtils.h>
  4. #include <ATen/detail/CUDAHooksInterface.h>
  5. #include <ATen/native/DispatchStub.h>
  6. #include <c10/util/env.h>
  7. #include <c10/util/irange.h>
  8. namespace at { namespace native {
  9. using conv_depthwise2d_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
  10. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  11. at::IntArrayRef, at::IntArrayRef, std::array<bool, 2>);
  12. DECLARE_DISPATCH(conv_depthwise2d_backward_fn, conv_depthwise2d_backward_stub);
  13. using conv_depthwise3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  14. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  15. at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
  16. DECLARE_DISPATCH(conv_depthwise3d_backward_fn, conv_depthwise3d_backward_stub);
  17. using cudnn_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
  18. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  19. at::IntArrayRef, int64_t, bool, bool, bool, std::array<bool,2>);
  20. DECLARE_DISPATCH(cudnn_convolution_backward_fn, cudnn_convolution_backward_stub);
  21. using mps_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  22. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  23. at::IntArrayRef, int64_t, std::array<bool,3>);
  24. DECLARE_DISPATCH(mps_convolution_backward_fn, mps_convolution_backward_stub);
  25. using cudnn_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor>(*)(
  26. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  27. at::IntArrayRef, at::IntArrayRef, int64_t, bool, bool, bool, std::array<bool,2>);
  28. DECLARE_DISPATCH(cudnn_convolution_transpose_backward_fn, cudnn_convolution_transpose_backward_stub);
  29. using miopen_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  30. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  31. at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
  32. DECLARE_DISPATCH(miopen_convolution_backward_fn, miopen_convolution_backward_stub);
  33. using miopen_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  34. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  35. at::IntArrayRef, at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
  36. DECLARE_DISPATCH(miopen_convolution_transpose_backward_fn, miopen_convolution_transpose_backward_stub);
  37. using miopen_depthwise_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  38. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  39. at::IntArrayRef, int64_t, bool, bool, std::array<bool,3>);
  40. DECLARE_DISPATCH(miopen_depthwise_convolution_backward_fn, miopen_depthwise_convolution_backward_stub);
  41. using mkldnn_convolution_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  42. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  43. at::IntArrayRef, int64_t, std::array<bool,3>);
  44. DECLARE_DISPATCH(mkldnn_convolution_backward_fn, mkldnn_convolution_backward_stub);
  45. using mkldnn_convolution_transpose_fn = Tensor(*)(const Tensor&, const Tensor&, const c10::optional<Tensor>&,
  46. IntArrayRef, IntArrayRef, IntArrayRef, IntArrayRef, int64_t);
  47. DECLARE_DISPATCH(mkldnn_convolution_transpose_fn, mkldnn_convolution_transpose_stub);
  48. using mkldnn_convolution_transpose_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  49. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  50. at::IntArrayRef, at::IntArrayRef, int64_t, std::array<bool,3>);
  51. DECLARE_DISPATCH(mkldnn_convolution_transpose_backward_fn, mkldnn_convolution_transpose_backward_stub);
  52. using slow_conv_dilated2d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  53. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  54. at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
  55. DECLARE_DISPATCH(slow_conv_dilated2d_backward_fn, slow_conv_dilated2d_backward_stub);
  56. using slow_conv_dilated3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  57. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  58. at::IntArrayRef, at::IntArrayRef, std::array<bool, 3>);
  59. DECLARE_DISPATCH(slow_conv_dilated3d_backward_fn, slow_conv_dilated3d_backward_stub);
  60. using slow_conv_transpose2d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  61. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  62. at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, std::array<bool,3>);
  63. DECLARE_DISPATCH(slow_conv_transpose2d_backward_fn, slow_conv_transpose2d_backward_stub);
  64. using slow_conv_transpose3d_backward_fn = std::tuple<at::Tensor,at::Tensor,at::Tensor>(*)(
  65. const at::Tensor&, const at::Tensor&, const at::Tensor&, at::IntArrayRef, at::IntArrayRef,
  66. at::IntArrayRef, at::IntArrayRef, at::IntArrayRef, std::array<bool,3>);
  67. DECLARE_DISPATCH(slow_conv_transpose3d_backward_fn, slow_conv_transpose3d_backward_stub);
  68. namespace {
  69. static bool cudnnv8_heuristic_mode_b = c10::utils::check_env("TORCH_CUDNN_USE_HEURISTIC_MODE_B") == true;
  70. }
  71. static inline bool cudnnv8_enabled_check_debug() {
  72. static bool cudnnv8_flag = c10::utils::check_env("TORCH_CUDNN_V8_API_DISABLED") != true;
  73. static bool cudnnv8_debug = c10::utils::check_env("TORCH_CUDNN_V8_API_DEBUG") == true;
  74. static uint8_t cudnnv8_debugcount = 0;
  75. if (cudnnv8_debug == 1 && cudnnv8_debugcount < 10) {
  76. TORCH_WARN("TORCH_CUDNN_V8_DEBUG ON, V8 ON: ", cudnnv8_flag, " TORCH_CUDNN_USE_HEURISTIC_MODE B: ", cudnnv8_heuristic_mode_b);
  77. cudnnv8_debugcount++;
  78. }
  79. return cudnnv8_flag == 1;
  80. }
  81. static inline bool cudnnv8_use_heur_mode_b() {
  82. return cudnnv8_heuristic_mode_b;
  83. }
  84. // Keep in sync with py::enum_ in Module.cpp
  85. enum class ConvBackend {
  86. CudaDepthwise2d,
  87. CudaDepthwise3d,
  88. Cudnn,
  89. CudnnTranspose,
  90. Empty,
  91. Miopen,
  92. MiopenDepthwise,
  93. MiopenTranspose,
  94. Mkldnn,
  95. MkldnnTranspose,
  96. MkldnnEmpty,
  97. NnpackSpatial,
  98. Overrideable,
  99. Slow2d,
  100. Slow3d,
  101. SlowDilated2d,
  102. SlowDilated3d,
  103. SlowTranspose2d,
  104. SlowTranspose3d,
  105. Winograd3x3Depthwise,
  106. Xnnpack2d,
  107. Mps,
  108. MpsTranspose,
  109. };
  110. // Overload for selecting the convolution backend from the full set of convolution inputs.
  111. // This overload is exposed to python for testing, etc.
  112. TORCH_API ConvBackend select_conv_backend(
  113. const Tensor& input, const Tensor& weight, const c10::optional<Tensor>& bias_opt,
  114. IntArrayRef stride, SymIntArrayRef padding, IntArrayRef dilation,
  115. bool transposed, SymIntArrayRef output_padding, int64_t groups, const at::OptionalSymIntArrayRef bias_sizes_opt);
  116. TORCH_API at::MemoryFormat _determine_backend_memory_format(const Tensor& input,
  117. const Tensor& weight,
  118. const ConvBackend backend);
  119. // ---------------------------------------------------------------------
  120. //
  121. // Math
  122. //
  123. // ---------------------------------------------------------------------
  124. constexpr int input_batch_size_dim = 0; // also grad_input
  125. constexpr int input_channels_dim = 1;
  126. constexpr int output_batch_size_dim = 0; // also grad_output
  127. constexpr int output_channels_dim = 1;
  128. constexpr int weight_output_channels_dim = 0;
  129. constexpr int weight_input_channels_dim = 1;
  130. // Often written as 2 + max_dim (extra dims for batch size and channels)
  131. constexpr int max_dim = 3;
  132. // ---------------------------------------------------------------------
  133. //
  134. // Checking
  135. //
  136. // ---------------------------------------------------------------------
  137. // Used on pad, stride and dilation
  138. static void check_args(CheckedFrom c, IntArrayRef args, size_t expected_size, const char* arg_name)
  139. {
  140. TORCH_CHECK(args.size() <= expected_size,
  141. "Too many ", arg_name, " values (", args.size(), ") supplied, expecting ",
  142. expected_size, " (while checking arguments for ", c, ")");
  143. TORCH_CHECK(args.size() >= expected_size,
  144. "Not enough ", arg_name, " values (", args.size(), ") supplied, expecting ",
  145. expected_size, " (while checking arguments for ", c, ")");
  146. auto num_negative_values = std::count_if(args.begin(), args.end(), [](int x){return x < 0;});
  147. if (num_negative_values > 0){
  148. std::stringstream ss;
  149. ss << arg_name << " should be greater than zero but got (";
  150. std::copy(args.begin(), args.end() - 1, std::ostream_iterator<int>(ss,", "));
  151. ss << args.back() << ")" << " (while checking arguments for " << c << ")";
  152. AT_ERROR(ss.str());
  153. }
  154. }
  155. // NOTE [ Convolution checks ]
  156. //
  157. // NB: For many call sites, it is not strictly necessary to check all of
  158. // these relationships (for example, for forward convolution, we compute
  159. // the size of output ourselves, so we don't actually need to check
  160. // output. However, writing a single function that does everything
  161. // means we get to reuse it for both forwards and all backwards
  162. // variants, even when the set of "real" inputs varies. The magic of
  163. // relational computing!
  164. //
  165. // (There is one downside, which is that it is slightly harder to write
  166. // error messages which are able to distinguish between real inputs
  167. // (which the user can change) and computed inputs (which the user can
  168. // only indirectly affect). It would be an interesting exercise to
  169. // come up with a general framework to handle such situations.)
  170. static void convolution_shape_check(
  171. CheckedFrom c,
  172. const TensorGeometryArg& input, const TensorGeometryArg& weight, const TensorGeometryArg& output,
  173. IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups)
  174. {
  175. check_args(c, padding, input->dim() - 2, "padding");
  176. check_args(c, stride, padding.size(), "stride");
  177. check_args(c, dilation, padding.size(), "dilation");
  178. // Input
  179. checkDimRange(c, input, 3, 6 /* exclusive */);
  180. checkSize_symint(c, input, input_channels_dim, weight->size(1) * groups);
  181. // Weight
  182. checkSameDim(c, input, weight);
  183. // TODO: check that output->size() matches output_sizes
  184. // TODO: check that weight matches output->sizes()
  185. checkSameDim(c, input, output);
  186. }
  187. // NB: conv_output_size and conv_input_size are not bijections,
  188. // as conv_output_size loses information; this is why conv_input_size
  189. // takes an extra output_padding argument to resolve the ambiguity.
  190. template <typename T>
  191. static inline std::vector<T> _conv_output_size(
  192. ArrayRef<T> input_size, ArrayRef<T> weight_size,
  193. ArrayRef<T> padding, IntArrayRef stride, IntArrayRef dilation = IntArrayRef()
  194. ) {
  195. // ASSERT(input_size.size() > 2)
  196. // ASSERT(input_size.size() == weight_size.size())
  197. bool has_dilation = !dilation.empty();
  198. auto dim = input_size.size();
  199. std::vector<T> output_size(dim);
  200. output_size[0] = input_size[input_batch_size_dim];
  201. output_size[1] = weight_size[weight_output_channels_dim];
  202. for (const auto d : c10::irange(2, dim)) {
  203. auto dilation_ = has_dilation ? dilation[d - 2] : 1;
  204. auto kernel = dilation_ * (weight_size[d] - 1) + 1;
  205. output_size[d] = (input_size[d] + (2 * padding[d - 2]) - kernel) / stride[d - 2] + 1;
  206. }
  207. return output_size;
  208. }
  209. static inline std::vector<int64_t> conv_output_size(
  210. IntArrayRef input_size, IntArrayRef weight_size,
  211. IntArrayRef padding, IntArrayRef stride, IntArrayRef dilation = IntArrayRef()
  212. ) {
  213. return _conv_output_size(input_size, weight_size, padding, stride, dilation);
  214. }
  215. static inline std::vector<c10::SymInt> conv_output_size(
  216. SymIntArrayRef input_size, SymIntArrayRef weight_size,
  217. SymIntArrayRef padding, IntArrayRef stride, IntArrayRef dilation = IntArrayRef()
  218. ) {
  219. return _conv_output_size(input_size, weight_size, padding, stride, dilation);
  220. }
  221. template <typename T>
  222. std::vector<T> _conv_input_size(
  223. ArrayRef<T> output_size, ArrayRef<T> weight_size,
  224. ArrayRef<T> padding, ArrayRef<T> output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
  225. ) {
  226. // ASSERT(output_size.size() > 2)
  227. // ASSERT(output_size.size() == weight_size.size())
  228. auto dim = output_size.size();
  229. std::vector<T> input_size(dim);
  230. input_size[0] = output_size[output_batch_size_dim];
  231. input_size[1] = weight_size[weight_input_channels_dim] * groups;
  232. for (const auto d : c10::irange(2, dim)) {
  233. auto kernel = (weight_size[d] - 1) * dilation[d - 2] + 1;
  234. input_size[d] = (output_size[d] - 1) * stride[d - 2] - (padding[d - 2] * 2) +
  235. kernel + output_padding[d - 2];
  236. }
  237. return input_size;
  238. }
  239. static inline std::vector<c10::SymInt> conv_input_size(
  240. SymIntArrayRef output_size, SymIntArrayRef weight_size,
  241. SymIntArrayRef padding, SymIntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
  242. ) {
  243. return _conv_input_size(output_size, weight_size, padding, output_padding, stride, dilation, groups);
  244. }
  245. static inline std::vector<int64_t> conv_input_size(
  246. IntArrayRef output_size, IntArrayRef weight_size,
  247. IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
  248. ) {
  249. return _conv_input_size(output_size, weight_size, padding, output_padding, stride, dilation, groups);
  250. }
  251. template <typename T>
  252. std::vector<T> _conv_weight_size(
  253. ArrayRef<T> input_size, ArrayRef<T> output_size,
  254. ArrayRef<T> padding, ArrayRef<T> output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
  255. ) {
  256. auto dim = input_size.size();
  257. std::vector<T> weight_size(dim);
  258. weight_size[0] = output_size[1];
  259. weight_size[1] = input_size[1] / groups;
  260. for (const auto d : c10::irange(2, dim)) {
  261. auto kernel = input_size[d] - (output_size[d] - 1) * stride[d - 2]
  262. + padding[d - 2] * 2 - output_padding[d - 2];
  263. weight_size[d] = (kernel - 1) / dilation[d - 2] + 1;
  264. }
  265. return weight_size;
  266. }
  267. static inline std::vector<c10::SymInt> conv_weight_size(
  268. SymIntArrayRef input_size, SymIntArrayRef output_size,
  269. SymIntArrayRef padding, SymIntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
  270. ) {
  271. return _conv_weight_size(input_size, output_size, padding, output_padding, stride, dilation, groups);
  272. }
  273. static inline std::vector<int64_t> conv_weight_size(
  274. IntArrayRef input_size, IntArrayRef output_size,
  275. IntArrayRef padding, IntArrayRef output_padding, IntArrayRef stride, IntArrayRef dilation, int64_t groups
  276. ) {
  277. return _conv_weight_size(input_size, output_size, padding, output_padding, stride, dilation, groups);
  278. }
  279. static inline Tensor reshape_bias(int64_t dim, const Tensor& bias) {
  280. std::vector<int64_t> shape(dim, 1);
  281. shape[1] = -1;
  282. return bias.reshape(shape);
  283. }
  284. static inline at::MemoryFormat cudnn_conv_suggest_memory_format(const at::Tensor& input, const at::Tensor& weight) {
  285. // disable NHWC for float64 input.
  286. if (!at::detail::getCUDAHooks().compiledWithCuDNN() ||
  287. input.scalar_type() == at::kDouble ||
  288. weight.scalar_type() == at::kDouble) {
  289. return at::MemoryFormat::Contiguous;
  290. }
  291. long cudnn_version = at::detail::getCUDAHooks().versionCuDNN();
  292. auto input_memory_format = input.suggest_memory_format();
  293. auto weight_memory_format = weight.suggest_memory_format();
  294. auto weight_ndim = weight.ndimension();
  295. bool can_use_cudnn_channels_last_2d = (cudnn_version >= 7603) && (weight_ndim == 4) && (
  296. (input_memory_format == at::MemoryFormat::ChannelsLast) ||
  297. (weight_memory_format == at::MemoryFormat::ChannelsLast)
  298. );
  299. if (can_use_cudnn_channels_last_2d) {
  300. return at::MemoryFormat::ChannelsLast;
  301. }
  302. bool can_use_cudnn_channels_last_3d = (cudnn_version >= 8005) && (weight_ndim == 5) && (
  303. (input_memory_format == at::MemoryFormat::ChannelsLast3d) ||
  304. (weight_memory_format == at::MemoryFormat::ChannelsLast3d)
  305. );
  306. if (can_use_cudnn_channels_last_3d) {
  307. return at::MemoryFormat::ChannelsLast3d;
  308. }
  309. return at::MemoryFormat::Contiguous;
  310. }
  311. static inline bool miopen_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
  312. // disable NHWC for float64 input.
  313. if (!at::detail::getCUDAHooks().compiledWithMIOpen() ||
  314. input.scalar_type() == at::kDouble ||
  315. weight.scalar_type() == at::kDouble) {
  316. return false;
  317. }
  318. auto input_memory_format = input.suggest_memory_format();
  319. auto weight_memory_format = weight.suggest_memory_format();
  320. bool can_use_miopen_channels_last_2d = (
  321. (input_memory_format == at::MemoryFormat::ChannelsLast) ||
  322. (weight_memory_format == at::MemoryFormat::ChannelsLast)
  323. );
  324. bool can_use_miopen_channels_last_3d = false;
  325. return can_use_miopen_channels_last_2d || can_use_miopen_channels_last_3d;
  326. }
  327. static inline bool mkldnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
  328. // disable NHWC for float64 input.
  329. if (input.scalar_type() == at::kDouble ||
  330. weight.scalar_type() == at::kDouble) {
  331. return false;
  332. }
  333. // disable NHWC for MkldnnCPU tensor.
  334. if (input.is_mkldnn() || weight.is_mkldnn()) {
  335. return false;
  336. }
  337. auto input_memory_format = input.suggest_memory_format();
  338. auto weight_memory_format = weight.suggest_memory_format();
  339. bool can_use_mkldnn_channels_last_2d =
  340. (input_memory_format == at::MemoryFormat::ChannelsLast) ||
  341. (weight_memory_format == at::MemoryFormat::ChannelsLast);
  342. // TODO: add channels last 3d support
  343. bool can_use_mkldnn_channels_last_3d = false;
  344. return can_use_mkldnn_channels_last_2d || can_use_mkldnn_channels_last_3d;
  345. }
  346. static inline bool thnn_conv_use_channels_last(const at::Tensor& input, const at::Tensor& weight) {
  347. auto input_memory_format = input.suggest_memory_format();
  348. auto weight_memory_format = weight.suggest_memory_format();
  349. bool can_use_thnn_channels_last_2d = input.device().is_cpu() && (
  350. (input_memory_format == at::MemoryFormat::ChannelsLast) || (
  351. weight_memory_format == at::MemoryFormat::ChannelsLast));
  352. return can_use_thnn_channels_last_2d;
  353. }
  354. }} // namespace at::native