CuFFTPlanCache.h 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  1. #include <ATen/Config.h>
  2. #include <ATen/core/DimVector.h>
  3. #include <ATen/cuda/CUDAContext.h>
  4. #include <ATen/native/cuda/CuFFTUtils.h>
  5. #include <ATen/native/utils/ParamsHash.h>
  6. #include <c10/util/accumulate.h>
  7. #include <c10/util/irange.h>
  8. #include <cufft.h>
  9. #include <cufftXt.h>
  10. #include <limits>
  11. #include <list>
  12. #include <sstream>
  13. #include <stdexcept>
  14. #include <string>
  15. #include <unordered_map>
  16. namespace at { namespace native { namespace detail {
  17. // Enum representing the FFT type
  18. enum class CuFFTTransformType : int8_t {
  19. C2C, // Complex-to-complex
  20. R2C, // Real-to-complex
  21. C2R, // Complex-to-real
  22. };
  23. // This struct is used to let us easily compute hashes of the
  24. // parameters.
  25. // It will be the **key** to the plan cache.
  26. struct CuFFTParams
  27. {
  28. int64_t signal_ndim_; // between 1 and max_rank, i.e., 1 <= signal_ndim <= 3
  29. // These include additional batch dimension as well.
  30. int64_t sizes_[max_rank + 1];
  31. int64_t input_strides_[max_rank + 1];
  32. int64_t output_strides_[max_rank + 1];
  33. CuFFTTransformType fft_type_;
  34. ScalarType value_type_;
  35. CuFFTParams() = default;
  36. CuFFTParams(IntArrayRef in_strides, IntArrayRef out_strides,
  37. IntArrayRef signal_sizes, CuFFTTransformType fft_type, ScalarType value_type) {
  38. // Padding bits must be zeroed for hashing
  39. memset(this, 0, sizeof(*this));
  40. signal_ndim_ = signal_sizes.size() - 1;
  41. fft_type_ = fft_type;
  42. value_type_ = value_type;
  43. TORCH_INTERNAL_ASSERT(in_strides.size() == signal_sizes.size());
  44. TORCH_INTERNAL_ASSERT(out_strides.size() == signal_sizes.size());
  45. TORCH_INTERNAL_ASSERT(1 <= signal_ndim_ && signal_ndim_ <= max_rank);
  46. std::copy(signal_sizes.cbegin(), signal_sizes.cend(), sizes_);
  47. std::copy(in_strides.cbegin(), in_strides.cend(), input_strides_);
  48. std::copy(out_strides.cbegin(), out_strides.cend(), output_strides_);
  49. }
  50. };
  51. static_assert(std::is_trivial<CuFFTParams>::value, "");
  52. // Returns true if the transform type has complex input
  53. inline bool cufft_complex_input(CuFFTTransformType type) {
  54. switch (type) {
  55. case CuFFTTransformType::C2C:
  56. case CuFFTTransformType::C2R:
  57. return true;
  58. case CuFFTTransformType::R2C:
  59. return false;
  60. }
  61. TORCH_INTERNAL_ASSERT(false);
  62. }
  63. // Returns true if the transform type has complex output
  64. inline bool cufft_complex_output(CuFFTTransformType type) {
  65. switch (type) {
  66. case CuFFTTransformType::C2C:
  67. case CuFFTTransformType::R2C:
  68. return true;
  69. case CuFFTTransformType::C2R:
  70. return false;
  71. }
  72. TORCH_INTERNAL_ASSERT(false);
  73. }
  74. // Create transform type enum from bools representing if input and output are complex
  75. inline CuFFTTransformType GetCuFFTTransformType(bool complex_input, bool complex_output) {
  76. if (complex_input && complex_output) {
  77. return CuFFTTransformType::C2C;
  78. } else if (complex_input && !complex_output) {
  79. return CuFFTTransformType::C2R;
  80. } else if (!complex_input && complex_output) {
  81. return CuFFTTransformType::R2C;
  82. }
  83. TORCH_INTERNAL_ASSERT(false, "Real to real FFTs are not supported");
  84. }
  85. class CuFFTHandle {
  86. ::cufftHandle handle_;
  87. public:
  88. CuFFTHandle() {
  89. CUFFT_CHECK(cufftCreate(&handle_));
  90. }
  91. ::cufftHandle & get() { return handle_; }
  92. const ::cufftHandle & get() const { return handle_; }
  93. ~CuFFTHandle() {
  94. // Not using fftDestroy() for rocFFT to work around double freeing of handles
  95. #if !defined(USE_ROCM)
  96. cufftDestroy(handle_);
  97. #endif
  98. }
  99. };
  100. __forceinline__
  101. static bool is_pow_of_two(int64_t x) {
  102. return (x & (x - 1)) == 0;
  103. }
  104. using cufft_size_type = long long int;
  105. using CuFFTDimVector = c10::SmallVector<cufft_size_type, at::kDimVectorStaticSize>;
  106. // Struct representing a tensor in CuFFT's data layout for planning transforms
  107. // See NOTE [ cuFFT Embedded Strides ].
  108. struct CuFFTDataLayout {
  109. CuFFTDimVector embed;
  110. cufft_size_type stride, dist;
  111. bool must_clone, simple;
  112. };
  113. // Returns a cufft embedding for a contiguous signal of the given size.
  114. // e.g. if the input is cloned, this will be the resulting data layout
  115. // See NOTE [ cuFFT Embedded Strides ].
  116. inline CuFFTDataLayout cufft_simple_embed(IntArrayRef sizes, bool onesided) {
  117. CuFFTDataLayout layout;
  118. layout.simple = true;
  119. layout.must_clone = false;
  120. layout.embed.assign(sizes.cbegin() + 1, sizes.cend());
  121. if (onesided) {
  122. layout.embed.back() = sizes.back() / 2 + 1;
  123. }
  124. layout.stride = 1;
  125. layout.dist = 1;
  126. for (const auto& len : layout.embed) {
  127. layout.dist *= len;
  128. }
  129. return layout;
  130. }
  131. // Convert strides to a CuFFT embedded representation.
  132. // If strides cannot be embedded, returns a simple layout and sets must_clone flag
  133. // See NOTE [ cuFFT Embedded Strides ].
  134. inline CuFFTDataLayout as_cufft_embed(IntArrayRef strides, IntArrayRef sizes, bool onesided) {
  135. const auto signal_ndim = strides.size() - 1;
  136. CuFFTDataLayout layout;
  137. auto last_stride = strides[signal_ndim];
  138. layout.must_clone = (last_stride <= 0);
  139. const auto last_dim_size = onesided ?
  140. sizes[signal_ndim] / 2 + 1 : sizes[signal_ndim];
  141. const auto signal_numel = c10::multiply_integers(sizes.slice(1, sizes.size() - 2)) * last_dim_size;
  142. // Zero stides are not allowed, even if the batch size is one.
  143. // If that happens just set a dummy case
  144. if (sizes[0] == 1) {
  145. layout.dist = signal_numel;
  146. } else if (strides[0] == 0) {
  147. layout.must_clone = true;
  148. } else {
  149. layout.dist = strides[0];
  150. }
  151. // Calculate the embedding shape, or set must_clone if the strides cannot be embedded
  152. layout.embed.resize(signal_ndim);
  153. for (auto i = signal_ndim - 1; !layout.must_clone && i > 0; i--) {
  154. auto stride = strides[i];
  155. if (sizes[i] == 1) {
  156. layout.embed[i] = 1;
  157. } else if (stride > 0 && stride % last_stride == 0) {
  158. layout.embed[i] = stride / last_stride;
  159. last_stride = stride;
  160. } else {
  161. layout.must_clone = true;
  162. }
  163. }
  164. if (layout.must_clone) {
  165. // If the input needs to be cloned, assume it will be contiguous
  166. layout = cufft_simple_embed(sizes, onesided);
  167. layout.must_clone = true;
  168. } else {
  169. layout.embed[0] = sizes[1];
  170. layout.stride = strides[signal_ndim];
  171. // Determine if layout represents a simple embedding (contiguous data)
  172. layout.simple = [&] {
  173. for (const auto i : c10::irange(1, signal_ndim - 1)) {
  174. if (layout.embed[i] != sizes[i + 1]) {
  175. return false;
  176. }
  177. }
  178. return (layout.stride == 1 && layout.dist == signal_numel &&
  179. layout.embed.back() == last_dim_size);
  180. }();
  181. }
  182. return layout;
  183. }
  184. // This class contains all the information needed to execute a cuFFT plan:
  185. // 1. the plan
  186. // 2. whether to clone input before executing the plan
  187. // 3. the workspace size needed
  188. //
  189. // This class will be the **value** in the plan cache.
  190. // It **owns** the raw plan via a unique_ptr.
  191. class CuFFTConfig {
  192. public:
  193. // Only move semantics is enought for this class. Although we already use
  194. // unique_ptr for the plan, still remove copy constructor and assignment op so
  195. // we don't accidentally copy and take perf hit.
  196. CuFFTConfig(const CuFFTConfig&) = delete;
  197. CuFFTConfig& operator=(CuFFTConfig const&) = delete;
  198. explicit CuFFTConfig(const CuFFTParams& params):
  199. CuFFTConfig(
  200. IntArrayRef(params.input_strides_, params.signal_ndim_ + 1),
  201. IntArrayRef(params.output_strides_, params.signal_ndim_ + 1),
  202. IntArrayRef(params.sizes_, params.signal_ndim_ + 1),
  203. params.fft_type_,
  204. params.value_type_) {}
  205. // For complex types, strides are in units of 2 * element_size(dtype)
  206. // sizes are for the full signal, including batch size and always two-sided
  207. CuFFTConfig(IntArrayRef in_strides, IntArrayRef out_strides,
  208. IntArrayRef sizes, CuFFTTransformType fft_type, ScalarType dtype):
  209. fft_type_(fft_type), value_type_(dtype) {
  210. // signal sizes (excluding batch dim)
  211. CuFFTDimVector signal_sizes(sizes.begin() + 1, sizes.end());
  212. // input batch size
  213. const int64_t batch = sizes[0];
  214. const int64_t signal_ndim = sizes.size() - 1;
  215. // Since cuFFT has limited non-unit stride support and various constraints, we
  216. // use a flag to keep track throughout this function to see if we need to
  217. // input = input.clone();
  218. #if defined(USE_ROCM)
  219. // clone input to avoid issues with hipfft clobering the input and failing tests
  220. clone_input = true;
  221. #else
  222. clone_input = false;
  223. #endif
  224. // For half, base strides on the real part of real-to-complex and
  225. // complex-to-real transforms are not supported. Since our output is always
  226. // contiguous, only need to check real-to-complex case.
  227. if (dtype == ScalarType::Half) {
  228. // cuFFT on half requires compute capability of at least SM_53
  229. auto dev_prop = at::cuda::getCurrentDeviceProperties();
  230. TORCH_CHECK(dev_prop->major >= 5 && !(dev_prop->major == 5 && dev_prop->minor < 3),
  231. "cuFFT doesn't support signals of half type with compute "
  232. "capability less than SM_53, but the device containing input half "
  233. "tensor only has SM_", dev_prop->major, dev_prop->minor);
  234. for (const auto i : c10::irange(signal_ndim)) {
  235. TORCH_CHECK(is_pow_of_two(sizes[i + 1]),
  236. "cuFFT only supports dimensions whose sizes are powers of two when"
  237. " computing in half precision, but got a signal size of",
  238. sizes.slice(1));
  239. }
  240. clone_input |= in_strides.back() != 1;
  241. }
  242. CuFFTDataLayout in_layout;
  243. if (clone_input) {
  244. in_layout = cufft_simple_embed(sizes, fft_type == CuFFTTransformType::C2R);
  245. } else {
  246. in_layout = as_cufft_embed(in_strides, sizes, fft_type == CuFFTTransformType::C2R);
  247. }
  248. auto out_layout = as_cufft_embed(out_strides, sizes, fft_type == CuFFTTransformType::R2C);
  249. TORCH_INTERNAL_ASSERT(!out_layout.must_clone, "Out strides cannot be represented as CuFFT embedding");
  250. clone_input |= in_layout.must_clone;
  251. // Check if we can take advantage of simple data layout.
  252. //
  253. // See NOTE [ cuFFT Embedded Strides ] in native/cuda/SpectralOps.cu.
  254. const bool simple_layout = in_layout.simple && out_layout.simple;
  255. cudaDataType itype, otype, exec_type;
  256. const auto complex_input = cufft_complex_input(fft_type);
  257. const auto complex_output = cufft_complex_output(fft_type);
  258. if (dtype == ScalarType::Float) {
  259. itype = complex_input ? CUDA_C_32F : CUDA_R_32F;
  260. otype = complex_output ? CUDA_C_32F : CUDA_R_32F;
  261. exec_type = CUDA_C_32F;
  262. } else if (dtype == ScalarType::Double) {
  263. itype = complex_input ? CUDA_C_64F : CUDA_R_64F;
  264. otype = complex_output ? CUDA_C_64F : CUDA_R_64F;
  265. exec_type = CUDA_C_64F;
  266. } else if (dtype == ScalarType::Half) {
  267. itype = complex_input ? CUDA_C_16F : CUDA_R_16F;
  268. otype = complex_output ? CUDA_C_16F : CUDA_R_16F;
  269. exec_type = CUDA_C_16F;
  270. } else {
  271. TORCH_CHECK(false, "cuFFT doesn't support tensor of type: ", dtype);
  272. }
  273. // disable auto allocation of workspace to use THC allocator
  274. CUFFT_CHECK(cufftSetAutoAllocation(plan(), /* autoAllocate */ 0));
  275. size_t ws_size_t;
  276. // make plan
  277. if (simple_layout) {
  278. // If with unit-stride, we tell cuFFT by setting inembed == onembed == NULL.
  279. // In such case, cuFFT ignores istride, ostride, idist, and odist
  280. // by assuming istride = ostride = 1.
  281. //
  282. // See NOTE [ cuFFT Embedded Strides ] in native/cuda/SpectralOps.cu.
  283. CUFFT_CHECK(cufftXtMakePlanMany(plan(), signal_ndim, signal_sizes.data(),
  284. /* inembed */ nullptr, /* base_istride */ 1, /* idist */ 1, itype,
  285. /* onembed */ nullptr, /* base_ostride */ 1, /* odist */ 1, otype,
  286. batch, &ws_size_t, exec_type));
  287. } else {
  288. CUFFT_CHECK(cufftXtMakePlanMany(plan(), signal_ndim, signal_sizes.data(),
  289. in_layout.embed.data(), in_layout.stride, in_layout.dist, itype,
  290. out_layout.embed.data(), out_layout.stride, out_layout.dist, otype,
  291. batch, &ws_size_t, exec_type));
  292. }
  293. ws_size = static_cast<int64_t>(ws_size_t);
  294. }
  295. const cufftHandle &plan() const { return plan_ptr.get(); }
  296. CuFFTTransformType transform_type() const { return fft_type_; }
  297. ScalarType data_type() const { return value_type_; }
  298. bool should_clone_input() const { return clone_input; }
  299. int64_t workspace_size() const { return ws_size; }
  300. private:
  301. CuFFTHandle plan_ptr;
  302. bool clone_input;
  303. int64_t ws_size;
  304. CuFFTTransformType fft_type_;
  305. ScalarType value_type_;
  306. };
  307. #if defined(USE_ROCM)
  308. // Note that the max plan number for CUDA version < 10 has to be 1023
  309. // due to a bug that fails on the 1024th plan
  310. constexpr int64_t CUFFT_MAX_PLAN_NUM = 1023;
  311. constexpr int64_t CUFFT_DEFAULT_CACHE_SIZE = CUFFT_MAX_PLAN_NUM;
  312. #else
  313. constexpr int64_t CUFFT_MAX_PLAN_NUM = std::numeric_limits<int64_t>::max();
  314. // The default max cache size chosen for CUDA version > 10 is arbitrary.
  315. // This number puts a limit on how big of a plan cache should we maintain by
  316. // default. Users can always configure it via cufft_set_plan_cache_max_size.
  317. constexpr int64_t CUFFT_DEFAULT_CACHE_SIZE = 4096;
  318. #endif
  319. static_assert(0 <= CUFFT_MAX_PLAN_NUM && CUFFT_MAX_PLAN_NUM <= std::numeric_limits<int64_t>::max(),
  320. "CUFFT_MAX_PLAN_NUM not in size_t range");
  321. static_assert(CUFFT_DEFAULT_CACHE_SIZE >= 0 && CUFFT_DEFAULT_CACHE_SIZE <= CUFFT_MAX_PLAN_NUM,
  322. "CUFFT_DEFAULT_CACHE_SIZE not in [0, CUFFT_MAX_PLAN_NUM] range");
  323. // This cache assumes that the mapping from key to value never changes.
  324. // This is **NOT** thread-safe. Please use a mutex when using it **AND** the
  325. // value returned from try_emplace_value.
  326. // The contract of using this cache is that try_emplace_value should only be
  327. // used when the max_size is positive.
  328. class CuFFTParamsLRUCache {
  329. public:
  330. using kv_t = typename std::pair<CuFFTParams, CuFFTConfig>;
  331. using map_t = typename std::unordered_map<std::reference_wrapper<CuFFTParams>,
  332. typename std::list<kv_t>::iterator,
  333. ParamsHash<CuFFTParams>,
  334. ParamsEqual<CuFFTParams>>;
  335. using map_kkv_iter_t = typename map_t::iterator;
  336. CuFFTParamsLRUCache() : CuFFTParamsLRUCache(CUFFT_DEFAULT_CACHE_SIZE) {}
  337. CuFFTParamsLRUCache(int64_t max_size) {
  338. _set_max_size(max_size);
  339. }
  340. CuFFTParamsLRUCache(CuFFTParamsLRUCache&& other) noexcept :
  341. _usage_list(std::move(other._usage_list)),
  342. _cache_map(std::move(other._cache_map)),
  343. _max_size(other._max_size) {}
  344. CuFFTParamsLRUCache& operator=(CuFFTParamsLRUCache&& other) noexcept {
  345. _usage_list = std::move(other._usage_list);
  346. _cache_map = std::move(other._cache_map);
  347. _max_size = other._max_size;
  348. return *this;
  349. }
  350. // If key is in this cache, return the cached config. Otherwise, emplace the
  351. // config in this cache and return it.
  352. // Return const reference because CuFFTConfig shouldn't be tampered with once
  353. // created.
  354. const CuFFTConfig &lookup(CuFFTParams params) {
  355. AT_ASSERT(_max_size > 0);
  356. map_kkv_iter_t map_it = _cache_map.find(params);
  357. // Hit, put to list front
  358. if (map_it != _cache_map.end()) {
  359. _usage_list.splice(_usage_list.begin(), _usage_list, map_it->second);
  360. return map_it->second->second;
  361. }
  362. // Miss
  363. // remove if needed
  364. if (_usage_list.size() >= _max_size) {
  365. auto last = _usage_list.end();
  366. last--;
  367. _cache_map.erase(last->first);
  368. _usage_list.pop_back();
  369. }
  370. // construct new plan at list front, then insert into _cache_map
  371. _usage_list.emplace_front(std::piecewise_construct,
  372. std::forward_as_tuple(params),
  373. std::forward_as_tuple(params));
  374. auto kv_it = _usage_list.begin();
  375. _cache_map.emplace(std::piecewise_construct,
  376. std::forward_as_tuple(kv_it->first),
  377. std::forward_as_tuple(kv_it));
  378. return kv_it->second;
  379. }
  380. void clear() {
  381. _cache_map.clear();
  382. _usage_list.clear();
  383. }
  384. void resize(int64_t new_size) {
  385. _set_max_size(new_size);
  386. auto cur_size = _usage_list.size();
  387. if (cur_size > _max_size) {
  388. auto delete_it = _usage_list.end();
  389. for (size_t i = 0; i < cur_size - _max_size; i++) {
  390. delete_it--;
  391. _cache_map.erase(delete_it->first);
  392. }
  393. _usage_list.erase(delete_it, _usage_list.end());
  394. }
  395. }
  396. size_t size() const { return _cache_map.size(); }
  397. size_t max_size() const noexcept { return _max_size; }
  398. std::mutex mutex;
  399. private:
  400. // Only sets size and does value check. Does not resize the data structures.
  401. void _set_max_size(int64_t new_size) {
  402. // We check that 0 <= new_size <= CUFFT_MAX_PLAN_NUM here. Since
  403. // CUFFT_MAX_PLAN_NUM is of type size_t, we need to do non-negativity check
  404. // first.
  405. TORCH_CHECK(new_size >= 0,
  406. "cuFFT plan cache size must be non-negative, but got ", new_size);
  407. TORCH_CHECK(new_size <= CUFFT_MAX_PLAN_NUM,
  408. "cuFFT plan cache size can not be larger than ", CUFFT_MAX_PLAN_NUM, ", but got ", new_size);
  409. _max_size = static_cast<size_t>(new_size);
  410. }
  411. std::list<kv_t> _usage_list;
  412. map_t _cache_map;
  413. size_t _max_size;
  414. };
  415. // Since ATen is separated into CPU build and CUDA build, we need a way to call
  416. // these functions only when CUDA is loaded. We use CUDA hooks for this purpose
  417. // (at cuda/detail/CUDAHooks.cpp), and call the hooked functions from the actual
  418. // native function counterparts (at native/SpectralOps.cpp), i.e.,
  419. // _cufft_get_plan_cache_max_size, _cufft_set_plan_cache_max_size
  420. // _cufft_get_plan_cache_size, and _cufft_clear_plan_cache.
  421. int64_t cufft_get_plan_cache_max_size_impl(DeviceIndex device_index);
  422. void cufft_set_plan_cache_max_size_impl(DeviceIndex device_index, int64_t max_size);
  423. int64_t cufft_get_plan_cache_size_impl(DeviceIndex device_index);
  424. void cufft_clear_plan_cache_impl(DeviceIndex device_index);
  425. }}} // namespace at::native::detail