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/argsort.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 / argsort.cu` 308 lines ยท 14159 bytes Raw Blame History 1 #include "argsort.cuh" 2 3 #ifdef GGML_CUDA_USE_CUB 4 # include 5 // strided_iterator was added in CCCL 3.1 6 # if (CCCL_MAJOR_VERSION > 3 || (CCCL_MAJOR_VERSION == 3 && CCCL_MINOR_VERSION >= 1)) 7 # define STRIDED_ITERATOR_AVAILABLE 8 # include 9 # endif 10 using namespace cub; 11 #endif // GGML_CUDA_USE_CUB 12 13 static __global__ void init_indices(int * indices, const int ncols, const int nrows) { 14 const int col = blockIdx.x * blockDim.x + threadIdx.x; 15 const int row = blockIdx.y; 16 17 if (col < ncols && row < nrows) { 18 indices[row * ncols + col] = col; 19 } 20 } 21 22 #ifndef STRIDED_ITERATOR_AVAILABLE 23 static __global__ void init_offsets(int * offsets, const int ncols, const int nrows) { 24 const int idx = blockIdx.x * blockDim.x + threadIdx.x; 25 if (idx <= nrows) { 26 offsets[idx] = idx * ncols; 27 } 28 } 29 #endif // STRIDED_ITERATOR_AVAILABLE 30 31 // returns the suggested maximum number of rows to process at once, given the temporary buffer bytes per row 32 int ggml_cuda_chunk_nrows(const size_t row_bytes, const int64_t nrows) { 33 // process rows in chunks up to approximately this size (currently 64MB) 34 // to avoid excessive temporary buffers memory usage 35 const int chunk_bytes = 1 << 26; 36 37 // calculate how many rows will fit in one chunk (must be at least one) 38 const int chunk_nrows = std::max((int) (chunk_bytes / row_bytes), 1); 39 40 // limit the resulting amount to total nrows 41 return std::min((int64_t) chunk_nrows, nrows); 42 } 43 44 #ifdef GGML_CUDA_USE_CUB 45 46 void argsort_f32_i32_cuda_cub(ggml_cuda_pool & pool, 47 const float * x, 48 int * dst, 49 const int ncols, 50 const int nrows, 51 ggml_sort_order order, 52 cudaStream_t stream) { 53 ggml_cuda_pool_alloc temp_indices_alloc(pool, ncols * nrows); 54 ggml_cuda_pool_alloc temp_keys_alloc(pool, ncols * nrows); 55 // Device*Sort algorithms currently do not allow for in-place sorting/aliasing of input/outputs 56 ggml_cuda_pool_alloc temp_keys_out_alloc(pool, ncols * nrows); 57 58 int * temp_indices = temp_indices_alloc.get(); 59 float * temp_keys = temp_keys_alloc.get(); 60 float * temp_keys_out = temp_keys_out_alloc.get(); 61 62 static const int block_size = 256; 63 const dim3 grid_size((ncols + block_size - 1) / block_size, nrows); 64 init_indices<<>>(temp_indices, ncols, nrows); 65 66 #ifdef STRIDED_ITERATOR_AVAILABLE 67 auto offset_iterator = cuda::make_strided_iterator(cuda::make_counting_iterator(0), ncols); 68 #else 69 // offset_iterator needs to populate nrows + 1 elements, so we also have to ceildiv nrows + 1 by block_size 70 const int nrows_offset = nrows + 1; 71 ggml_cuda_pool_alloc offsets_alloc(pool, nrows_offset); 72 int * offset_iterator = offsets_alloc.get(); 73 const dim3 offset_grid((nrows_offset + block_size - 1) / block_size); 74 init_offsets<<>>(offset_iterator, ncols, nrows); 75 #endif 76 CUDA_CHECK(cudaMemcpyAsync(temp_keys, x, ncols * nrows * sizeof(float), cudaMemcpyDeviceToDevice, stream)); 77 78 size_t temp_storage_bytes = 0; 79 80 bool is_capturing = false; 81 #ifdef USE_CUDA_GRAPH 82 // Currently (confirmed for CCCL <= 3.2) DeviceSegmentedSort does not support stream capture, while DeviceSegmentedRadixSort does. 83 // See https://github.com/NVIDIA/cccl/issues/5661#issuecomment-`3229037149` 84 // TODO: constrain this to the CCCL versions that have this issue once it's resolved in a future CCCL release. 85 cudaStreamCaptureStatus capture_status; 86 CUDA_CHECK(cudaStreamIsCapturing(stream, &capture_status)); 87 is_capturing = (capture_status != cudaStreamCaptureStatusNone); 88 #endif // USE_CUDA_GRAPH 89 90 if (order == GGML_SORT_ORDER_ASC) { 91 if (nrows == 1) { 92 CUDA_CHECK(DeviceRadixSort::SortPairs(nullptr, temp_storage_bytes, temp_keys, temp_keys_out, // keys in, keys out 93 temp_indices, dst, // values (indices) 94 ncols, 0, sizeof(float) * 8, stream)); 95 } else if (is_capturing) { 96 CUDA_CHECK(DeviceSegmentedRadixSort::SortPairs( 97 nullptr, temp_storage_bytes, temp_keys, temp_keys_out, // keys in, keys out 98 temp_indices, dst, // values (indices) 99 ncols * nrows, nrows, // num items, num segments 100 offset_iterator, offset_iterator + 1, 0, sizeof(float) * 8, stream)); 101 } else { 102 CUDA_CHECK(DeviceSegmentedSort::SortPairs(nullptr, temp_storage_bytes, temp_keys, 103 temp_keys_out, // keys out 104 temp_indices, dst, // values (indices) 105 ncols * nrows, nrows, // num items, num segments 106 offset_iterator, offset_iterator + 1, stream)); 107 } 108 } else { 109 if (nrows == 1) { 110 CUDA_CHECK(DeviceRadixSort::SortPairsDescending(nullptr, temp_storage_bytes, temp_keys, 111 temp_keys_out, // keys out 112 temp_indices, dst, // values (indices) 113 ncols, 0, sizeof(float) * 8, stream)); 114 } else if (is_capturing) { 115 CUDA_CHECK(DeviceSegmentedRadixSort::SortPairsDescending( 116 nullptr, temp_storage_bytes, temp_keys, temp_keys_out, temp_indices, dst, ncols * nrows, nrows, 117 offset_iterator, offset_iterator + 1, 0, sizeof(float) * 8, stream)); 118 } else { 119 CUDA_CHECK(DeviceSegmentedSort::SortPairsDescending(nullptr, temp_storage_bytes, temp_keys, temp_keys_out, 120 temp_indices, dst, ncols * nrows, nrows, 121 offset_iterator, offset_iterator + 1, stream)); 122 } 123 } 124 125 ggml_cuda_pool_alloc temp_storage_alloc(pool, temp_storage_bytes); 126 void * d_temp_storage = temp_storage_alloc.get(); 127 128 if (order == GGML_SORT_ORDER_ASC) { 129 if (nrows == 1) { 130 CUDA_CHECK(DeviceRadixSort::SortPairs(d_temp_storage, temp_storage_bytes, temp_keys, 131 temp_keys_out, // keys out 132 temp_indices, dst, // values (indices) 133 ncols, 0, sizeof(float) * 8, stream)); 134 } else if (is_capturing) { 135 CUDA_CHECK(DeviceSegmentedRadixSort::SortPairs(d_temp_storage, temp_storage_bytes, temp_keys, temp_keys_out, 136 temp_indices, dst, ncols * nrows, nrows, offset_iterator, 137 offset_iterator + 1, 0, sizeof(float) * 8, stream)); 138 } else { 139 CUDA_CHECK(DeviceSegmentedSort::SortPairs(d_temp_storage, temp_storage_bytes, temp_keys, temp_keys_out, 140 temp_indices, dst, ncols * nrows, nrows, offset_iterator, 141 offset_iterator + 1, stream)); 142 } 143 } else { 144 if (nrows == 1) { 145 CUDA_CHECK(DeviceRadixSort::SortPairsDescending(d_temp_storage, temp_storage_bytes, temp_keys, 146 temp_keys_out, // keys out 147 temp_indices, dst, // values (indices) 148 ncols, 0, sizeof(float) * 8, stream)); 149 } else if (is_capturing) { 150 CUDA_CHECK(DeviceSegmentedRadixSort::SortPairsDescending( 151 d_temp_storage, temp_storage_bytes, temp_keys, temp_keys_out, temp_indices, dst, ncols * nrows, nrows, 152 offset_iterator, offset_iterator + 1, 0, sizeof(float) * 8, stream)); 153 } else { 154 CUDA_CHECK(DeviceSegmentedSort::SortPairsDescending(d_temp_storage, temp_storage_bytes, temp_keys, 155 temp_keys_out, temp_indices, dst, ncols * nrows, nrows, 156 offset_iterator, offset_iterator + 1, stream)); 157 } 158 } 159 } 160 #endif // GGML_CUDA_USE_CUB 161 162 // Bitonic sort implementation 163 template 164 static inline __device__ void ggml_cuda_swap(T & a, T & b) { 165 T tmp = a; 166 a = b; 167 b = tmp; 168 } 169 170 // One compare-exchange of the bitonic network at (k, j) for column col. 171 template 172 static inline __device__ void bitonic_step(const float * x_row, int * dst_row, const int ncols, const int col, const int k, const int j) { 173 const int ixj = col ^ j; 174 if (ixj <= col) { 175 return; 176 } 177 if ((col & k) == 0) { 178 if (dst_row[col] >= ncols || 179 (dst_row[ixj] < ncols && (order == GGML_SORT_ORDER_ASC ? 180 x_row[dst_row[col]] > x_row[dst_row[ixj]] : 181 x_row[dst_row[col]] < x_row[dst_row[ixj]])) 182 ) { 183 ggml_cuda_swap(dst_row[col], dst_row[ixj]); 184 } 185 } else { 186 if (dst_row[ixj] >= ncols || 187 (dst_row[col] < ncols && (order == GGML_SORT_ORDER_ASC ? 188 x_row[dst_row[col]] < x_row[dst_row[ixj]] : 189 x_row[dst_row[col]] > x_row[dst_row[ixj]])) 190 ) { 191 ggml_cuda_swap(dst_row[col], dst_row[ixj]); 192 } 193 } 194 } 195 196 // Bitonic sort of one row per block. Each thread owns the columns 197 // threadIdx.x + i * blockDim.x, so rows wider than the block (up to the 198 // shared memory limit) sort with several columns per thread. Every 199 // (k, j) stage runs all owned columns before the barrier; a pair 200 // (col, col ^ j) is exchanged by the owner of its lower index only. 201 template 202 static __global__ void k_argsort_f32_i32(const float * x, int * dst, const int ncols, int ncols_pad) { 203 const int row = blockIdx.x; 204 205 const float * x_row = x + row * ncols; 206 extern __shared__ int dst_row[]; 207 208 // initialize indices 209 for (int col = threadIdx.x; col < ncols_pad; col += blockDim.x) { 210 dst_row[col] = col; 211 } 212 213 __syncthreads(); 214 215 for (int k = 2; k <= ncols_pad; k *= 2) { 216 for (int j = k / 2; j > 0; j /= 2) { 217 for (int col = threadIdx.x; col < ncols_pad; col += blockDim.x) { 218 bitonic_step(x_row, dst_row, ncols, col, k, j); 219 } 220 __syncthreads(); 221 } 222 } 223 224 // copy the result to dst without the padding 225 for (int col = threadIdx.x; col < ncols; col += blockDim.x) { 226 dst[row * ncols + col] = dst_row[col]; 227 } 228 } 229 230 static int next_power_of_2(int x) { 231 int n = 1; 232 while (n < x) { 233 n *= 2; 234 } 235 return n; 236 } 237 238 void argsort_f32_i32_cuda_bitonic(const float * x, 239 int * dst, 240 const int ncols, 241 const int nrows, 242 ggml_sort_order order, 243 cudaStream_t stream) { 244 // bitonic sort requires ncols to be power of 2 245 const int ncols_pad = next_power_of_2(ncols); 246 247 // one thread per column up to the block limit, several columns per 248 // thread beyond it; shared memory is the remaining bound 249 const dim3 block_dims(ncols_pad < CUDA_ARGSORT_BLOCK_SIZE ? ncols_pad : CUDA_ARGSORT_BLOCK_SIZE, 1, 1); 250 const dim3 block_nums(nrows, 1, 1); 251 const size_t shared_mem = ncols_pad * sizeof(int); 252 253 // FIXME: this limit could be raised by ~2-4x on Ampere or newer 254 GGML_ASSERT(shared_mem <= ggml_cuda_info().devices[ggml_cuda_get_device()].smpb); 255 256 if (order == GGML_SORT_ORDER_ASC) { 257 k_argsort_f32_i32 258 <<>>(x, dst, ncols, ncols_pad); 259 } else if (order == GGML_SORT_ORDER_DESC) { 260 k_argsort_f32_i32 261 <<>>(x, dst, ncols, ncols_pad); 262 } else { 263 GGML_ABORT("fatal error"); 264 } 265 } 266 267 void ggml_cuda_op_argsort(ggml_backend_cuda_context & ctx, ggml_tensor * dst) { 268 const ggml_tensor * src0 = dst->src[0]; 269 const float * src0_d = (const float *)src0->data; 270 float * dst_d = (float *)dst->data; 271 cudaStream_t stream = ctx.stream(); 272 273 GGML_ASSERT(src0->type == GGML_TYPE_F32); 274 GGML_ASSERT( dst->type == GGML_TYPE_I32); 275 GGML_ASSERT(ggml_is_contiguous(src0)); 276 277 const int64_t ncols = src0->ne[0]; 278 const int64_t nrows = ggml_nrows(src0); 279 280 enum ggml_sort_order order = (enum ggml_sort_order) dst->op_params[0]; 281 282 #ifdef GGML_CUDA_USE_CUB 283 const int ncols_pad = next_power_of_2(ncols); 284 const size_t shared_mem = ncols_pad * sizeof(int); 285 const size_t max_shared_mem = ggml_cuda_info().devices[ggml_cuda_get_device()].smpb; 286 287 // early return if we can use bitonic argsort 288 if (shared_mem <= max_shared_mem && ncols <= 1024) { 289 argsort_f32_i32_cuda_bitonic(src0_d, (int *) dst_d, ncols, nrows, order, stream); 290 return; 291 } 292 293 const int chunk_nrows = ggml_cuda_chunk_nrows(src0->nb[1], nrows); 294 295 ggml_cuda_pool & pool = ctx.pool(); 296 297 for (int64_t i = 0; i < nrows; i += chunk_nrows) { 298 int iter_nrows = std::min((int64_t) chunk_nrows, nrows - i); 299 300 argsort_f32_i32_cuda_cub(pool, src0_d, (int *) dst_d, ncols, iter_nrows, order, stream); 301 302 src0_d += ncols * iter_nrows; 303 dst_d += ncols * iter_nrows; 304 } 305 #else 306 argsort_f32_i32_cuda_bitonic(src0_d, (int *) dst_d, ncols, nrows, order, stream); 307 #endif 308 }