Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/ggml/blob/master/src/ggml-cuda/top-k.cu # ggml [Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685) Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers branch `master` Branches Tags History `ggml / src / ggml-cuda / top-k.cu` 337 lines ยท 12940 bytes Raw Blame History 1 #include "argsort.cuh" 2 #include "top-k.cuh" 3 4 // Adjusted implementation thresholds from #28547, can be overridden at build time 5 #ifndef GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC 6 # if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) 7 // not measured on HIP/MUSA, keep the old split 8 # define GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC 1024 9 # else 10 # define GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC 512 11 # endif 12 #endif // GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC 13 14 #ifndef GGML_CUDA_TOP_K_NCOLS_THRESHOLD_ARGSORT 15 # define GGML_CUDA_TOP_K_NCOLS_THRESHOLD_ARGSORT 4096 16 #endif // GGML_CUDA_TOP_K_NCOLS_THRESHOLD_ARGSORT 17 18 // bitonic up to this width while nrows fits in one wave of SMs, 0 disables 19 #ifndef GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC_FEW_ROWS 20 # if defined(GGML_USE_HIP) || defined(GGML_USE_MUSA) 21 # define GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC_FEW_ROWS 0 22 # else 23 # define GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC_FEW_ROWS 1024 24 # endif 25 #endif // GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC_FEW_ROWS 26 27 #ifdef GGML_CUDA_USE_CUB 28 # include 29 // DeviceTopK has a race condition before CCCL 3.4.3. 30 // https://github.com/NVIDIA/cccl/pull/10627 31 # if (CCCL_MAJOR_VERSION > 3 || \ 32 (CCCL_MAJOR_VERSION == 3 && CCCL_MINOR_VERSION > 4) || \ 33 (CCCL_MAJOR_VERSION == 3 && CCCL_MINOR_VERSION == 4 && CCCL_PATCH_VERSION >= 3)) 34 # define CUB_TOP_K_AVAILABLE 35 # include 36 using namespace cub; 37 # endif // CCCL >= 3.4.3 38 #endif // GGML_CUDA_USE_CUB 39 40 // max rows for the per-row DeviceTopK / CUB argsort path before switching to radix / bitonic 41 #ifndef GGML_CUDA_TOP_K_NROWS_THRESHOLD 42 # ifdef CUB_TOP_K_AVAILABLE 43 # define GGML_CUDA_TOP_K_NROWS_THRESHOLD 2 44 # else 45 # define GGML_CUDA_TOP_K_NROWS_THRESHOLD 1 46 # endif 47 #endif // GGML_CUDA_TOP_K_NROWS_THRESHOLD 48 49 #ifdef CUB_TOP_K_AVAILABLE 50 51 static void top_k_cub(ggml_cuda_pool & pool, 52 const float * src, 53 int * dst, 54 const int ncols, 55 const int k, 56 cudaStream_t stream) { 57 auto requirements = cuda::execution::require(cuda::execution::determinism::not_guaranteed, 58 cuda::execution::output_ordering::unsorted); 59 auto stream_env = cuda::stream_ref{ stream }; 60 auto env = cuda::std::execution::env{ stream_env, requirements }; 61 62 auto indexes_in = cuda::make_counting_iterator(0); 63 64 size_t temp_storage_bytes = 0; 65 CUDA_CHECK(DeviceTopK::MaxPairs(nullptr, temp_storage_bytes, src, cuda::discard_iterator(), indexes_in, dst, ncols, k, 66 env)); 67 68 ggml_cuda_pool_alloc temp_storage_alloc(pool, temp_storage_bytes); 69 void * d_temp_storage = temp_storage_alloc.get(); 70 71 CUDA_CHECK(DeviceTopK::MaxPairs(d_temp_storage, temp_storage_bytes, src, cuda::discard_iterator(), indexes_in, dst, 72 ncols, k, env)); 73 } 74 75 #endif // CUB_TOP_K_AVAILABLE 76 77 static int next_power_of_2(int x) { 78 int n = 1; 79 while (n < x) { 80 n *= 2; 81 } 82 return n; 83 } 84 85 static __device__ __forceinline__ uint32_t top_k_float_to_ordered(float value) { 86 const uint32_t bits = __float_as_uint(value); 87 const uint32_t mask = (uint32_t) (-(int32_t) (bits >> 31)) | 0x80000000U; 88 return bits ^ mask; 89 } 90 91 struct top_k_radix_state { 92 uint32_t prefix; 93 uint32_t prefix_mask; 94 int rank; 95 int greater_count; 96 int equal_count; 97 }; 98 99 static __global__ void top_k_radix_init(top_k_radix_state * states, int nrows, int k) { 100 const int row = blockIdx.x * blockDim.x + threadIdx.x; 101 if (row < nrows) { 102 states[row] = {0, 0, k, 0, 0}; 103 } 104 } 105 106 template 107 static __global__ void top_k_radix_histogram( 108 const float * __restrict__ src, 109 const top_k_radix_state * __restrict__ states, 110 int * __restrict__ block_histograms, 111 int ncols, 112 int blocks_per_row, 113 int shift) { 114 constexpr int NBINS = 1 << RADIX_BITS; 115 116 const int row = blockIdx.x / blocks_per_row; 117 const int row_block = blockIdx.x % blocks_per_row; 118 const int tid = threadIdx.x; 119 const float * row_src = src + (size_t) row * ncols; 120 __shared__ int histogram[NBINS]; 121 122 histogram[tid] = 0; 123 __syncthreads(); 124 125 const top_k_radix_state state = states[row]; 126 for (int64_t col = row_block * BLOCK_SIZE + tid; 127 col < ncols; 128 col += blocks_per_row * BLOCK_SIZE) { 129 const uint32_t key = top_k_float_to_ordered(row_src[col]); 130 if ((key & state.prefix_mask) == state.prefix) { 131 atomicAdd(&histogram[(key >> shift) & (NBINS - 1)], 1); 132 } 133 } 134 __syncthreads(); 135 136 const size_t histogram_offset = 137 ((size_t) row * blocks_per_row + row_block) * NBINS; 138 block_histograms[histogram_offset + tid] = histogram[tid]; 139 } 140 141 template 142 static __global__ void top_k_radix_select( 143 const int * __restrict__ block_histograms, 144 top_k_radix_state * __restrict__ states, 145 int blocks_per_row, 146 int shift) { 147 constexpr int NBINS = 1 << RADIX_BITS; 148 149 const int row = blockIdx.x; 150 const int tid = threadIdx.x; 151 __shared__ int histogram[NBINS]; 152 153 int count = 0; 154 for (int row_block = 0; row_block < blocks_per_row; ++row_block) { 155 const size_t offset = ((size_t) row * blocks_per_row + row_block) * NBINS; 156 count += block_histograms[offset + tid]; 157 } 158 histogram[tid] = count; 159 __syncthreads(); 160 161 if (tid == 0) { 162 top_k_radix_state state = states[row]; 163 int bin = NBINS - 1; 164 while (bin > 0 && histogram[bin] < state.rank) { 165 state.rank -= histogram[bin--]; 166 } 167 state.prefix |= (uint32_t) bin << shift; 168 state.prefix_mask |= (uint32_t) (NBINS - 1) << shift; 169 states[row] = state; 170 } 171 } 172 173 static __global__ void top_k_radix_reset_counters(top_k_radix_state * states, int nrows) { 174 const int row = blockIdx.x * blockDim.x + threadIdx.x; 175 if (row < nrows) { 176 states[row].greater_count = 0; 177 states[row].equal_count = 0; 178 } 179 } 180 181 template 182 static __global__ void top_k_radix_gather( 183 const float * __restrict__ src, 184 int * __restrict__ dst, 185 top_k_radix_state * __restrict__ states, 186 int ncols, 187 int k, 188 int blocks_per_row) { 189 const int row = blockIdx.x / blocks_per_row; 190 const int row_block = blockIdx.x % blocks_per_row; 191 const int tid = threadIdx.x; 192 const float * row_src = src + (size_t) row * ncols; 193 int * row_dst = dst + (size_t) row * k; 194 top_k_radix_state * state = &states[row]; 195 196 for (int64_t col = row_block * BLOCK_SIZE + tid; 197 col < ncols; 198 col += blocks_per_row * BLOCK_SIZE) { 199 const uint32_t key = top_k_float_to_ordered(row_src[col]); 200 if (key > state->prefix) { 201 const int pos = atomicAdd(&state->greater_count, 1); 202 row_dst[pos] = col; 203 } else if (key == state->prefix) { 204 const int pos = atomicAdd(&state->equal_count, 1); 205 if (pos < state->rank) { 206 row_dst[k - state->rank + pos] = col; 207 } 208 } 209 } 210 } 211 212 static void top_k_radix_cuda( 213 ggml_cuda_pool & pool, 214 const float * src, int * dst, int ncols, int64_t nrows, int k, cudaStream_t stream) { 215 constexpr int BLOCK_SIZE = 256; 216 constexpr int RADIX_BITS = 8; 217 constexpr int NBINS = 1 << RADIX_BITS; 218 const int blocks_per_row = (int) std::min(((int64_t) ncols + 1023) / 1024, 64); 219 220 // chunk the rows to bound the histogram memory to 64 MB 221 const int64_t chunk_nrows = ggml_cuda_chunk_nrows((size_t) blocks_per_row * NBINS * sizeof(int), nrows); 222 223 ggml_cuda_pool_alloc states_alloc(pool, chunk_nrows); 224 ggml_cuda_pool_alloc histograms_alloc(pool, (size_t) chunk_nrows * blocks_per_row * NBINS); 225 top_k_radix_state * states = states_alloc.get(); 226 int * histograms = histograms_alloc.get(); 227 228 for (int64_t i = 0; i < nrows; i += chunk_nrows) { 229 const int iter_nrows = std::min(chunk_nrows, nrows - i); 230 231 top_k_radix_init<<<(iter_nrows + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE, 0, stream>>>(states, iter_nrows, k); 232 233 const dim3 row_grid(blocks_per_row * iter_nrows); 234 for (int shift = 32 - RADIX_BITS; shift >= 0; shift -= RADIX_BITS) { 235 top_k_radix_histogram 236 <<>>( 237 src, states, histograms, ncols, blocks_per_row, shift); 238 top_k_radix_select 239 <<>>(histograms, states, blocks_per_row, shift); 240 } 241 242 top_k_radix_reset_counters 243 <<<(iter_nrows + BLOCK_SIZE - 1) / BLOCK_SIZE, BLOCK_SIZE, 0, stream>>>(states, iter_nrows); 244 top_k_radix_gather 245 <<>>( 246 src, dst, states, ncols, k, blocks_per_row); 247 248 src += (size_t) ncols * iter_nrows; 249 dst += (size_t) k * iter_nrows; 250 } 251 } 252 253 static void top_k_argsort_cuda( 254 ggml_cuda_pool & pool, 255 const float * src, int * dst, int ncols, int64_t nrows, int k, bool use_cub, cudaStream_t stream) { 256 const int64_t chunk_nrows = ggml_cuda_chunk_nrows((size_t) ncols * sizeof(int), nrows); 257 258 ggml_cuda_pool_alloc tmp_alloc(pool, (size_t) ncols * chunk_nrows); 259 int * tmp = tmp_alloc.get(); 260 261 for (int64_t i = 0; i < nrows; i += chunk_nrows) { 262 const int iter_nrows = std::min(chunk_nrows, nrows - i); 263 264 if (use_cub) { 265 #ifdef GGML_CUDA_USE_CUB 266 argsort_f32_i32_cuda_cub(pool, src, tmp, ncols, iter_nrows, GGML_SORT_ORDER_DESC, stream); 267 #else 268 GGML_ABORT("CUB is not available"); 269 #endif // GGML_CUDA_USE_CUB 270 } else { 271 argsort_f32_i32_cuda_bitonic(src, tmp, ncols, iter_nrows, GGML_SORT_ORDER_DESC, stream); 272 } 273 CUDA_CHECK(cudaMemcpy2DAsync(dst, k * sizeof(int), tmp, ncols * sizeof(int), k * sizeof(int), iter_nrows, 274 cudaMemcpyDeviceToDevice, stream)); 275 276 src += (size_t) ncols * iter_nrows; 277 dst += (size_t) k * iter_nrows; 278 } 279 } 280 281 void ggml_cuda_op_top_k(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { 282 const ggml_tensor * src0 = dst->src[0]; 283 const float * src0_d = (const float *) src0->data; 284 int * dst_d = (int *) dst->data; 285 cudaStream_t stream = ctx.stream(); 286 287 // are these asserts truly necessary? 288 GGML_ASSERT(src0->type == GGML_TYPE_F32); 289 GGML_ASSERT(dst->type == GGML_TYPE_I32); 290 GGML_ASSERT(ggml_is_contiguous(src0)); 291 292 const int64_t ncols = src0->ne[0]; 293 const int64_t nrows = ggml_nrows(src0); 294 const int64_t k = dst->ne[0]; 295 ggml_cuda_pool & pool = ctx.pool(); 296 297 const int device = ggml_cuda_get_device(); 298 299 #ifdef CUB_TOP_K_AVAILABLE 300 // a single row always uses DeviceTopK if available 301 const bool bitonic_short = nrows > 1 && ncols <= GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC; 302 #else 303 const bool bitonic_short = ncols <= GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC; 304 #endif // CUB_TOP_K_AVAILABLE 305 const bool bitonic_few_rows = nrows > GGML_CUDA_TOP_K_NROWS_THRESHOLD && 306 ncols <= GGML_CUDA_TOP_K_NCOLS_THRESHOLD_BITONIC_FEW_ROWS && 307 nrows <= ggml_cuda_info().devices[device].nsm; 308 309 if (bitonic_short || bitonic_few_rows) { 310 // the padded row must fit in shared memory 311 const int ncols_pad = next_power_of_2(ncols); 312 if (ncols_pad * sizeof(int) <= ggml_cuda_info().devices[device].smpb) { 313 top_k_argsort_cuda(pool, src0_d, dst_d, ncols, nrows, k, false, stream); 314 return; 315 } 316 } 317 318 if (nrows > GGML_CUDA_TOP_K_NROWS_THRESHOLD) { 319 top_k_radix_cuda(pool, src0_d, dst_d, ncols, nrows, k, stream); 320 return; 321 } 322 323 #ifdef CUB_TOP_K_AVAILABLE 324 // TODO: Assess perf of `DeviceBatchedTopK` for multi-row TopK & CCCL >= 3.5.0, re-running perf sweep of https://github.com/ggml-org/llama.cpp/pull/28713 325 for (int64_t i = 0; i < nrows; i++) { 326 top_k_cub(pool, src0_d + i * ncols, dst_d + i * k, ncols, k, stream); 327 } 328 #elif defined(GGML_CUDA_USE_CUB) // CUB_TOP_K_AVAILABLE 329 if (ncols <= GGML_CUDA_TOP_K_NCOLS_THRESHOLD_ARGSORT) { 330 top_k_argsort_cuda(pool, src0_d, dst_d, ncols, nrows, k, true, stream); 331 } else { 332 top_k_radix_cuda(pool, src0_d, dst_d, ncols, nrows, k, stream); 333 } 334 #else // GGML_CUDA_USE_CUB 335 top_k_radix_cuda(pool, src0_d, dst_d, ncols, nrows, k, stream); 336 #endif // CUB_TOP_K_AVAILABLE 337 }