| 1 | /* |
| 2 | * Adapted from |
| 3 | * https://github.com/NVIDIA/FasterTransformer/blob/release/v5.3_tag/src/fastertransformer/kernels/decoder_masked_multihead_attention/decoder_masked_multihead_attention_template.hpp |
| 4 | * Copyright (c) 2023, The vLLM team. |
| 5 | * Copyright (c) 2020-2023, NVIDIA CORPORATION. All rights reserved. |
| 6 | * |
| 7 | * Licensed under the Apache License, Version 2.0 (the "License"); |
| 8 | * you may not use this file except in compliance with the License. |
| 9 | * You may obtain a copy of the License at |
| 10 | * |
| 11 | * http://www.apache.org/licenses/LICENSE-2.0 |
| 12 | * |
| 13 | * Unless required by applicable law or agreed to in writing, software |
| 14 | * distributed under the License is distributed on an "AS IS" BASIS, |
| 15 | * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 16 | * See the License for the specific language governing permissions and |
| 17 | * limitations under the License. |
| 18 | */ |
| 19 | #pragma once |
| 20 | |
| 21 | #include "../../cuda_compat.h" |
| 22 | #include "../../attention/attention_dtypes.h" |
| 23 | |
| 24 | #include <float.h> |
| 25 | #include <type_traits> |
| 26 | |
| 27 | namespace vllm { |
| 28 | |
| 29 | // Q*K^T operation. |
| 30 | template <int THREAD_GROUP_SIZE, typename Vec, int N> |
| 31 | inline __device__ float qk_dot_(const Vec (&q)[N], const Vec (&k)[N]) { |
| 32 | using A_vec = typename FloatVec<Vec>::Type; |
| 33 | // Compute the parallel products for Q*K^T (treat vector lanes separately). |
| 34 | A_vec qk_vec = mul<A_vec, Vec, Vec>(q[0], k[0]); |
| 35 | #pragma unroll |
| 36 | for (int ii = 1; ii < N; ++ii) { |
| 37 | qk_vec = vllm::fma(q[ii], k[ii], qk_vec); |
| 38 | } |
| 39 | |
| 40 | // Finalize the reduction across lanes. |
| 41 | float qk = sum(qk_vec); |
| 42 | #pragma unroll |
| 43 | for (int mask = THREAD_GROUP_SIZE / 2; mask >= 1; mask /= 2) { |
| 44 | qk += VLLM_SHFL_XOR_SYNC(qk, mask); |
| 45 | } |
| 46 | return qk; |
| 47 | } |
| 48 | |
| 49 | template <typename T, int THREAD_GROUP_SIZE> |
| 50 | struct Qk_dot { |
| 51 | template <typename Vec, int N> |
| 52 | static inline __device__ float dot(const Vec (&q)[N], const Vec (&k)[N]) { |
| 53 | return qk_dot_<THREAD_GROUP_SIZE>(q, k); |
| 54 | } |
| 55 | }; |
| 56 | |
| 57 | } // namespace vllm |