count-equal.cu 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. #include "common.cuh"
  2. #include "count-equal.cuh"
  3. #include <cstdint>
  4. template <typename T>
  5. static __global__ void count_equal(const T * __restrict__ x, const T * __restrict__ y, int64_t * __restrict__ dst, const int64_t dk, const int64_t k) {
  6. const int64_t i0 = (int64_t) blockIdx.x*dk;
  7. const int64_t i1 = min(i0 + dk, k);
  8. int nequal = 0;
  9. for (int64_t i = i0 + threadIdx.x; i < i1; i += WARP_SIZE) {
  10. const T xi = x[i];
  11. const T yi = y[i];
  12. nequal += xi == yi;
  13. }
  14. nequal = warp_reduce_sum(nequal);
  15. if (threadIdx.x != 0) {
  16. return;
  17. }
  18. atomicAdd((int *) dst, nequal);
  19. }
  20. void ggml_cuda_count_equal(ggml_backend_cuda_context & ctx, ggml_tensor * dst) {
  21. const ggml_tensor * src0 = dst->src[0];
  22. const ggml_tensor * src1 = dst->src[1];
  23. GGML_ASSERT(src0->type == src1->type);
  24. GGML_ASSERT( dst->type == GGML_TYPE_I64);
  25. GGML_ASSERT(ggml_are_same_shape(src0, src1));
  26. GGML_ASSERT(ggml_is_contiguous(src0));
  27. GGML_ASSERT(ggml_is_contiguous(src1));
  28. GGML_ASSERT(ggml_is_contiguous(dst));
  29. int64_t * dst_d = (int64_t *) dst->data;
  30. cudaStream_t stream = ctx.stream();
  31. const int nsm = ggml_cuda_info().devices[ggml_cuda_get_device()].nsm;
  32. const int64_t ne = ggml_nelements(src0);
  33. GGML_ASSERT(ne < (1 << 30) && "atomicAdd implementation only supports int");
  34. const int64_t dne = GGML_PAD(ne / (4*nsm), CUDA_COUNT_EQUAL_CHUNK_SIZE);
  35. CUDA_CHECK(cudaMemsetAsync(dst_d, 0, ggml_nbytes(dst), stream));
  36. const dim3 blocks_dim(WARP_SIZE, 1, 1);
  37. const dim3 blocks_num(std::min((int64_t)4*nsm, (ne + CUDA_COUNT_EQUAL_CHUNK_SIZE - 1)/CUDA_COUNT_EQUAL_CHUNK_SIZE), 1, 1);
  38. switch (src0->type) {
  39. case GGML_TYPE_I32: {
  40. const int * src0_d = (const int *) src0->data;
  41. const int * src1_d = (const int *) src1->data;
  42. count_equal<<<blocks_num, blocks_dim, 0, stream>>>(src0_d, src1_d, dst_d, dne, ne);
  43. } break;
  44. default:
  45. GGML_ASSERT(false);
  46. break;
  47. }
  48. }