ft_attention.cpp 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224
  1. #include <torch/extension.h>
  2. #include "ATen/cuda/CUDAContext.h"
  3. #include <c10/cuda/CUDAGuard.h>
  4. #include "decoder_masked_multihead_attention.h"
  5. #define CHECK_DEVICE(x) TORCH_CHECK(x.device().type() == torch::kCUDA, #x " must be on CUDA")
  6. #define CHECK_SHAPE(x, ...) TORCH_CHECK(x.sizes() == torch::IntArrayRef({__VA_ARGS__}), #x " must have shape (" #__VA_ARGS__ ")")
  7. #define CHECK_CONTIGUOUS(x) TORCH_CHECK(x.is_contiguous(), #x " must be contiguous")
  8. #define DISPATCH_FLOAT_AND_HALF_AND_BF16(TYPE, NAME, ...) \
  9. if (TYPE == at::ScalarType::Half) { \
  10. using scalar_t = at::Half; \
  11. __VA_ARGS__(); \
  12. } else if (TYPE == at::ScalarType::BFloat16) { \
  13. using scalar_t = at::BFloat16; \
  14. __VA_ARGS__(); \
  15. } else if (TYPE == at::ScalarType::Float) { \
  16. using scalar_t = float; \
  17. __VA_ARGS__(); \
  18. } else { \
  19. AT_ERROR(#NAME, " not implemented for type '", toString(TYPE), "'"); \
  20. }
  21. template<typename T>
  22. void masked_multihead_attention(const Masked_multihead_attention_params<T>& params,
  23. const cudaStream_t& stream);
  24. template<typename T>
  25. void cross_multihead_attention(const Masked_multihead_attention_params<T>& params,
  26. const cudaStream_t& stream);
  27. template<typename T>
  28. struct SATypeConverter {
  29. using Type = T;
  30. };
  31. template<>
  32. struct SATypeConverter<at::Half> {
  33. using Type = uint16_t;
  34. };
  35. template<>
  36. struct SATypeConverter<at::BFloat16> {
  37. using Type = __nv_bfloat16;
  38. };
  39. template <typename T>
  40. void set_params(Masked_multihead_attention_params<T> &params,
  41. const size_t batch_size,
  42. const size_t nheads,
  43. const size_t memory_max_seqlen,
  44. const size_t headdim,
  45. const int timestep,
  46. const int rotary_embedding_dim,
  47. const float rotary_base,
  48. const bool neox_rotary_style,
  49. const int qkv_batch_stride,
  50. const int nnz_heads,
  51. T *q_ptr,
  52. T *k_ptr,
  53. T *v_ptr,
  54. T *k_cache_ptr,
  55. T *v_cache_ptr,
  56. int *length_per_sample,
  57. T *rotary_cos,
  58. T *rotary_sin,
  59. T *out_ptr,
  60. int *nnz_head_idx) {
  61. // Reset the parameters
  62. memset(&params, 0, sizeof(params));
  63. params.q = q_ptr;
  64. params.k = k_ptr;
  65. params.v = v_ptr;
  66. params.q_bias = nullptr;
  67. params.k_bias = nullptr;
  68. params.v_bias = nullptr;
  69. params.k_cache = k_cache_ptr;
  70. params.v_cache = v_cache_ptr;
  71. params.out = out_ptr;
  72. params.cache_indir = nullptr;
  73. params.stride = qkv_batch_stride;
  74. params.batch_size = batch_size;
  75. params.beam_width = 1;
  76. params.memory_max_len = memory_max_seqlen;
  77. params.num_heads = nheads;
  78. params.nnz_heads = nnz_heads;
  79. params.hidden_size_per_head = headdim;
  80. params.rotary_embedding_dim = rotary_embedding_dim;
  81. params.rotary_base = rotary_base;
  82. params.neox_rotary_style = neox_rotary_style;
  83. params.timestep = timestep;
  84. params.inv_sqrt_dh = 1.f / sqrt(float(headdim));
  85. params.total_padding_tokens = nullptr;
  86. params.masked_tokens = nullptr;
  87. params.prefix_prompt_lengths = nullptr;
  88. params.max_prefix_prompt_length = 0;
  89. params.relative_attention_bias = nullptr;
  90. params.relative_attention_bias_stride = 0;
  91. params.cross_attention_out = nullptr;
  92. params.max_decoder_seq_len = 0;
  93. params.is_return_cross_attentions = false;
  94. params.finished = nullptr;
  95. params.memory_length_per_sample = nullptr;
  96. params.length_per_sample = length_per_sample;
  97. params.rotary_cos = rotary_cos;
  98. params.rotary_sin = rotary_sin;
  99. params.nnz_head_idx = nnz_head_idx;
  100. }
  101. torch::Tensor single_query_attention(const torch::Tensor q,
  102. const torch::Tensor k,
  103. const torch::Tensor v,
  104. torch::Tensor k_cache,
  105. torch::Tensor v_cache,
  106. c10::optional<const torch::Tensor> length_per_sample_,
  107. c10::optional<const torch::Tensor> rotary_cos_,
  108. c10::optional<const torch::Tensor> rotary_sin_,
  109. c10::optional<const torch::Tensor> nnz_head_idx_,
  110. const int timestep,
  111. int rotary_embedding_dim = 0,
  112. const float rotary_base = 10000.0f,
  113. const bool neox_rotary_style=true) {
  114. CHECK_DEVICE(q); CHECK_DEVICE(k); CHECK_DEVICE(v); CHECK_DEVICE(k_cache); CHECK_DEVICE(v_cache);
  115. int batch_size = v_cache.size(0);
  116. int nheads = v_cache.size(1);
  117. int memory_max_seqlen = v_cache.size(2);
  118. int headdim = v_cache.size(3);
  119. auto input_type = q.scalar_type();
  120. TORCH_CHECK(input_type == at::ScalarType::Float || input_type == at::ScalarType::Half || input_type == at::ScalarType::BFloat16);
  121. CHECK_SHAPE(q, batch_size, nheads, headdim);
  122. CHECK_SHAPE(k, batch_size, nheads, headdim);
  123. CHECK_SHAPE(v, batch_size, nheads, headdim);
  124. CHECK_SHAPE(v_cache, batch_size, nheads, memory_max_seqlen, headdim);
  125. // k_cache shape: [B, H, Dh/x, L, x] where x=8 for fp16 and x=4 for fp32
  126. int packsize = k_cache.dtype() == torch::kFloat32 ? 4 : 8;
  127. CHECK_SHAPE(k_cache, batch_size, nheads, headdim / packsize, memory_max_seqlen, packsize);
  128. TORCH_CHECK(q.stride(2) == 1 && q.stride(1) == headdim);
  129. TORCH_CHECK(k.stride(2) == 1 && k.stride(1) == headdim);
  130. TORCH_CHECK(v.stride(2) == 1 && v.stride(1) == headdim);
  131. TORCH_CHECK(q.stride(0) == k.stride(0) && q.stride(0) == v.stride(0));
  132. CHECK_CONTIGUOUS(v_cache); CHECK_CONTIGUOUS(k_cache);
  133. TORCH_CHECK(q.scalar_type() == input_type);
  134. TORCH_CHECK(k.scalar_type() == input_type);
  135. TORCH_CHECK(v.scalar_type() == input_type);
  136. TORCH_CHECK(k_cache.scalar_type() == input_type);
  137. TORCH_CHECK(v_cache.scalar_type() == input_type);
  138. if (length_per_sample_.has_value()) {
  139. auto length_per_sample = length_per_sample_.value();
  140. CHECK_DEVICE(length_per_sample);
  141. CHECK_SHAPE(length_per_sample, batch_size);
  142. CHECK_CONTIGUOUS(length_per_sample);
  143. TORCH_CHECK(length_per_sample.dtype() == torch::kInt32);
  144. }
  145. if (rotary_cos_.has_value()) {
  146. auto rotary_cos = rotary_cos_.value();
  147. CHECK_DEVICE(rotary_cos);
  148. rotary_embedding_dim = rotary_cos.size(0) * 2;
  149. CHECK_SHAPE(rotary_cos, rotary_embedding_dim / 2);
  150. CHECK_CONTIGUOUS(rotary_cos);
  151. TORCH_CHECK(rotary_cos.scalar_type() == input_type);
  152. TORCH_CHECK(rotary_sin_.has_value());
  153. auto rotary_sin = rotary_sin_.value();
  154. CHECK_DEVICE(rotary_sin);
  155. CHECK_SHAPE(rotary_cos, rotary_embedding_dim / 2);
  156. CHECK_CONTIGUOUS(rotary_sin);
  157. TORCH_CHECK(rotary_sin.scalar_type() == input_type);
  158. }
  159. if (nnz_head_idx_.has_value()) {
  160. auto nnz_head_idx = nnz_head_idx_.value();
  161. CHECK_DEVICE(nnz_head_idx);
  162. int nnz_heads = nnz_head_idx.size(0);
  163. CHECK_SHAPE(nnz_head_idx, nnz_heads);
  164. CHECK_CONTIGUOUS(nnz_head_idx);
  165. TORCH_CHECK(nnz_head_idx.dtype() == torch::kInt32);
  166. }
  167. // Otherwise the kernel will be launched from cuda:0 device
  168. // Cast to char to avoid compiler warning about narrowing
  169. at::cuda::CUDAGuard device_guard{(char)q.get_device()};
  170. torch::Tensor out = torch::empty_like(q);
  171. DISPATCH_FLOAT_AND_HALF_AND_BF16(q.scalar_type(), "single_query_attention", [&] {
  172. using DataType = typename SATypeConverter<scalar_t>::Type;
  173. Masked_multihead_attention_params<DataType> params;
  174. set_params(params, batch_size, nheads, memory_max_seqlen, headdim, timestep,
  175. rotary_embedding_dim, rotary_base, neox_rotary_style, q.stride(0),
  176. nnz_head_idx_.has_value() ? nnz_head_idx_.value().size(0) : 0,
  177. reinterpret_cast<DataType*>(q.data_ptr()),
  178. reinterpret_cast<DataType*>(k.data_ptr()),
  179. reinterpret_cast<DataType*>(v.data_ptr()),
  180. reinterpret_cast<DataType*>(k_cache.data_ptr()),
  181. reinterpret_cast<DataType*>(v_cache.data_ptr()),
  182. length_per_sample_.has_value()
  183. ? length_per_sample_.value().data_ptr<int>() : nullptr,
  184. rotary_cos_.has_value()
  185. ? reinterpret_cast<DataType*>(rotary_cos_.value().data_ptr()) : nullptr,
  186. rotary_sin_.has_value()
  187. ? reinterpret_cast<DataType*>(rotary_sin_.value().data_ptr()) : nullptr,
  188. reinterpret_cast<DataType*>(out.data_ptr()),
  189. nnz_head_idx_.has_value() ? nnz_head_idx_.value().data_ptr<int>() : nullptr
  190. );
  191. auto stream = at::cuda::getCurrentCUDAStream();
  192. masked_multihead_attention(params, stream);
  193. });
  194. return out;
  195. }
  196. PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  197. m.def("single_query_attention", &single_query_attention, "Attention with a single query",
  198. py::arg("q"), py::arg("k"), py::arg("v"), py::arg("k_cache"), py::arg("v_cache"),
  199. py::arg("length_per_sample_"), py::arg("rotary_cos_"),
  200. py::arg("rotary_sin_"), py::arg("nnz_head_idx_"),
  201. py::arg("timestep"), py::arg("rotary_embedding_dim")=0,
  202. py::arg("rotary_base")=10000.0f, py::arg("neox_rotary_style")=true);
  203. }