alibi.cu 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263
  1. #include "alibi.cuh"
  2. static __global__ void alibi_f32(const float * x, float * dst, const int ncols, const int k_rows,
  3. const int n_heads_log2_floor, const float m0, const float m1) {
  4. const int col = blockDim.x*blockIdx.x + threadIdx.x;
  5. if (col >= ncols) {
  6. return;
  7. }
  8. const int row = blockDim.y*blockIdx.y + threadIdx.y;
  9. const int i = row*ncols + col;
  10. const int k = row/k_rows;
  11. float m_k;
  12. if (k < n_heads_log2_floor) {
  13. m_k = powf(m0, k + 1);
  14. } else {
  15. m_k = powf(m1, 2 * (k - n_heads_log2_floor) + 1);
  16. }
  17. dst[i] = col * m_k + x[i];
  18. }
  19. static void alibi_f32_cuda(const float * x, float * dst, const int ncols, const int nrows,
  20. const int k_rows, const int n_heads_log2_floor, const float m0,
  21. const float m1, cudaStream_t stream) {
  22. const dim3 block_dims(CUDA_ALIBI_BLOCK_SIZE, 1, 1);
  23. const int num_blocks_x = (ncols + CUDA_ALIBI_BLOCK_SIZE - 1) / (CUDA_ALIBI_BLOCK_SIZE);
  24. const dim3 block_nums(num_blocks_x, nrows, 1);
  25. alibi_f32<<<block_nums, block_dims, 0, stream>>>(x, dst, ncols, k_rows, n_heads_log2_floor, m0, m1);
  26. }
  27. void ggml_cuda_op_alibi(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
  28. const ggml_tensor * src0 = dst->src[0];
  29. const float * src0_d = (const float *)src0->data;
  30. float * dst_d = (float *)dst->data;
  31. cudaStream_t stream = ctx.stream();
  32. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  33. GGML_ASSERT( dst->type == GGML_TYPE_F32);
  34. const int64_t ne00 = src0->ne[0];
  35. const int64_t ne01 = src0->ne[1];
  36. const int64_t ne02 = src0->ne[2];
  37. const int64_t nrows = ggml_nrows(src0);
  38. //const int n_past = ((int32_t *) dst->op_params)[0];
  39. const int n_head = ((int32_t *) dst->op_params)[1];
  40. float max_bias;
  41. memcpy(&max_bias, (int32_t *) dst->op_params + 2, sizeof(float));
  42. //GGML_ASSERT(ne01 + n_past == ne00);
  43. GGML_ASSERT(n_head == ne02);
  44. const int n_heads_log2_floor = 1 << (int) floor(log2(n_head));
  45. const float m0 = powf(2.0f, -(max_bias) / n_heads_log2_floor);
  46. const float m1 = powf(2.0f, -(max_bias / 2.0f) / n_heads_log2_floor);
  47. alibi_f32_cuda(src0_d, dst_d, ne00, nrows, ne01, n_heads_log2_floor, m0, m1, stream);
  48. }