tsembd.cpp 2.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273
  1. //
  2. // MIT license
  3. // Copyright (C) 2024 Intel Corporation
  4. // SPDX-License-Identifier: MIT
  5. //
  6. //
  7. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  8. // See https://llvm.org/LICENSE.txt for license information.
  9. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  10. //
  11. #include "tsembd.hpp"
  12. static void timestep_embedding_f32(
  13. const float * timesteps, float * dst, const int nb1,
  14. const int dim, const int max_period, const sycl::nd_item<3> &item_ct1) {
  15. // item_ct1.get_group(1)(blockIDx.y): idx of timesteps->ne[0]
  16. // item_ct1.get_group(2) (blockIDx.x): idx of ((dim + 1) / 2) / BLOCK_SIZE
  17. int i = item_ct1.get_group(1);
  18. int j = item_ct1.get_local_id(2) + item_ct1.get_group(2) * item_ct1.get_local_range(2);
  19. float * embed_data = (float *)((char *)dst + i*nb1);
  20. if (dim % 2 != 0 && j == ((dim + 1) / 2)) {
  21. embed_data[dim] = 0.f;
  22. }
  23. int half = dim / 2;
  24. if (j >= half) {
  25. return;
  26. }
  27. float timestep = timesteps[i];
  28. float freq = (float)sycl::native::exp(-(sycl::log((float)max_period)) * j / half);
  29. float arg = timestep * freq;
  30. embed_data[j] = sycl::cos(arg);
  31. embed_data[j + half] = sycl::sin(arg);
  32. }
  33. static void timestep_embedding_f32_sycl(
  34. const float * x, float * dst, const int ne00, const int nb1,
  35. const int dim, const int max_period, const queue_ptr& stream) {
  36. // As the kernel returns when thread.idx is larger than dim/2, the half_ceil does not need to pad
  37. int half_ceil = dim / 2;
  38. int num_blocks = (half_ceil + SYCL_TIMESTEP_EMBEDDING_BLOCK_SIZE - 1) / SYCL_TIMESTEP_EMBEDDING_BLOCK_SIZE;
  39. sycl::range<3> block_dims(1, 1, SYCL_TIMESTEP_EMBEDDING_BLOCK_SIZE);
  40. sycl::range<3> gridDim(1, ne00, num_blocks);
  41. stream->parallel_for(
  42. sycl::nd_range<3>(
  43. gridDim * block_dims, block_dims),
  44. [=](sycl::nd_item<3> item_ct1) {
  45. timestep_embedding_f32(
  46. x, dst, nb1, dim, max_period, item_ct1
  47. );
  48. });
  49. }
  50. void ggml_sycl_op_timestep_embedding(ggml_backend_sycl_context & ctx, ggml_tensor * dst) {
  51. const ggml_tensor *src0 = dst->src[0];
  52. const ggml_tensor *src1 = dst->src[1];
  53. const float * src0_d = (const float *)src0->data;
  54. float * dst_d = (float *)dst->data;
  55. dpct::queue_ptr stream = ctx.stream();
  56. GGML_ASSERT(src0->type == GGML_TYPE_F32);
  57. GGML_ASSERT(dst->type == GGML_TYPE_F32);
  58. const int dim = dst->op_params[0];
  59. const int max_period = dst->op_params[1];
  60. timestep_embedding_f32_sycl(src0_d, dst_d, src0->ne[0], dst->nb[1], dim, max_period, stream);
  61. GGML_UNUSED(src1);
  62. }