tsembd.cu 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. #include "tsembd.cuh"
  2. static __global__ void timestep_embedding_f32(const float * timesteps, float * dst, const int nb1, const int dim, const int max_period) {
  3. // blockIDx.y: idx of timesteps->ne[0]
  4. // blockIDx.x: idx of ((dim + 1) / 2) / BLOCK_SIZE
  5. int i = blockIdx.y;
  6. int j = threadIdx.x + blockIdx.x * blockDim.x;
  7. float * embed_data = (float *)((char *)dst + i*nb1);
  8. if (dim % 2 != 0 && j == ((dim + 1) / 2)) {
  9. embed_data[dim] = 0.f;
  10. }
  11. int half = dim / 2;
  12. if (j >= half) {
  13. return;
  14. }
  15. float timestep = timesteps[i];
  16. float freq = (float)expf(-logf(max_period) * j / half);
  17. float arg = timestep * freq;
  18. embed_data[j] = cosf(arg);
  19. embed_data[j + half] = sinf(arg);
  20. }
  21. static void timestep_embedding_f32_cuda(const float * x, float * dst, const int ne00, const int nb1,
  22. const int dim, const int max_period, cudaStream_t stream) {
  23. int half_ceil = (dim + 1) / 2;
  24. int num_blocks = (half_ceil + CUDA_TIMESTEP_EMBEDDING_BLOCK_SIZE - 1) / CUDA_TIMESTEP_EMBEDDING_BLOCK_SIZE;
  25. dim3 gridDim(num_blocks, ne00, 1);
  26. timestep_embedding_f32<<<gridDim, CUDA_TIMESTEP_EMBEDDING_BLOCK_SIZE, 0, stream>>>(x, dst, nb1, dim, max_period);
  27. }
  28. void ggml_cuda_op_timestep_embedding(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
  29. const ggml_tensor * src0 = dst->src[0];
  30. const float * src0_d = (const float *)src0->data;
  31. float * dst_d = (float *)dst->data;
  32. cudaStream_t stream = ctx.stream();
  33. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  34. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  35. const int dim = dst->op_params[0];
  36. const int max_period = dst->op_params[1];
  37. timestep_embedding_f32_cuda(src0_d, dst_d, src0->ne[0], dst->nb[1], dim, max_period, stream);
  38. }