ggml
[Ported from github.com/ggml-org/ggml] docs : sync ggml_type enum in gguf.md (#1685)
Brought by drakestapleton
ggml / src / ggml-metal / kernels / argsort.metal
| 1 | #include "common.h" |
| 2 | |
| 3 | constant bool FC_topk_moe_with_norm [[function_constant(FC_TOPK_MOE + 0)]]; |
| 4 | constant int FC_topk_moe_n_expert [[function_constant(FC_TOPK_MOE + 1)]]; |
| 5 | constant int FC_topk_moe_top_k [[function_constant(FC_TOPK_MOE + 2)]]; |
| 6 | |
| 7 | constant int FC_moe_reduce_n_expert_used [[function_constant(FC_MOE_REDUCE + 0)]]; |
| 8 | |
| 9 | // bitonic sort implementation following the CUDA kernels as reference |
| 10 | typedef void (argsort_t)( |
| 11 | constant ggml_metal_kargs_argsort & args, |
| 12 | device const char * src0, |
| 13 | device int32_t * dst, |
| 14 | threadgroup int32_t * shmem_i32 [[threadgroup(0)]], |
| 15 | uint3 tgpig[[threadgroup_position_in_grid]], |
| 16 | ushort3 tpitg[[thread_position_in_threadgroup]], |
| 17 | ushort3 ntg[[threads_per_threadgroup]]); |
| 18 | |
| 19 | template<ggml_sort_order order> |
| 20 | kernel void kernel_argsort_f32_i32( |
| 21 | constant ggml_metal_kargs_argsort & args, |
| 22 | device const char * src0, |
| 23 | device int32_t * dst, |
| 24 | threadgroup int32_t * shmem_i32 [[threadgroup(0)]], |
| 25 | uint3 tgpig[[threadgroup_position_in_grid]], |
| 26 | ushort3 tpitg[[thread_position_in_threadgroup]], |
| 27 | ushort3 ntg[[threads_per_threadgroup]]) { |
| 28 | // bitonic sort |
| 29 | const int col = tpitg[0]; |
| 30 | const int ib = tgpig[0] / args.ne01; |
| 31 | |
| 32 | const int i00 = ib*ntg.x; |
| 33 | const int i01 = tgpig[0] % args.ne01; |
| 34 | const int i02 = tgpig[1]; |
| 35 | const int i03 = tgpig[2]; |
| 36 | |
| 37 | device const float * src0_row = (device const float *) (src0 + args.nb01*i01 + args.nb02*i02 + args.nb03*i03); |
| 38 | |
| 39 | // initialize indices |
| 40 | shmem_i32[col] = i00 + col; |
| 41 | |
| 42 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 43 | |
| 44 | for (int k = 2; k <= ntg.x; k *= 2) { |
| 45 | for (int j = k / 2; j > 0; j /= 2) { |
| 46 | int ixj = col ^ j; |
| 47 | if (ixj > col) { |
| 48 | if ((col & k) == 0) { |
| 49 | if (shmem_i32[col] >= args.ne00 || |
| 50 | (shmem_i32[ixj] < args.ne00 && (order == GGML_SORT_ORDER_ASC ? |
| 51 | src0_row[shmem_i32[col]] > src0_row[shmem_i32[ixj]] : |
| 52 | src0_row[shmem_i32[col]] < src0_row[shmem_i32[ixj]])) |
| 53 | ) { |
| 54 | SWAP(shmem_i32[col], shmem_i32[ixj]); |
| 55 | } |
| 56 | } else { |
| 57 | if (shmem_i32[ixj] >= args.ne00 || |
| 58 | (shmem_i32[col] < args.ne00 && (order == GGML_SORT_ORDER_ASC ? |
| 59 | src0_row[shmem_i32[col]] < src0_row[shmem_i32[ixj]] : |
| 60 | src0_row[shmem_i32[col]] > src0_row[shmem_i32[ixj]])) |
| 61 | ) { |
| 62 | SWAP(shmem_i32[col], shmem_i32[ixj]); |
| 63 | } |
| 64 | } |
| 65 | } |
| 66 | |
| 67 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 68 | } |
| 69 | } |
| 70 | |
| 71 | const int64_t i0 = ib*args.top_k; |
| 72 | |
| 73 | // copy the result to dst without the padding |
| 74 | if (i0 + col < args.ne0 && col < args.top_k) { |
| 75 | dst += i0 + args.ne0*i01 + args.ne0*args.ne1*i02 + args.ne0*args.ne1*args.ne2*i03; |
| 76 | |
| 77 | dst[col] = shmem_i32[col]; |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | template [[host_name("kernel_argsort_f32_i32_asc")]] kernel argsort_t kernel_argsort_f32_i32<GGML_SORT_ORDER_ASC>; |
| 82 | template [[host_name("kernel_argsort_f32_i32_desc")]] kernel argsort_t kernel_argsort_f32_i32<GGML_SORT_ORDER_DESC>; |
| 83 | |
| 84 | typedef void (argsort_merge_t)( |
| 85 | constant ggml_metal_kargs_argsort_merge & args, |
| 86 | device const char * src0, |
| 87 | device const int32_t * tmp, |
| 88 | device int32_t * dst, |
| 89 | uint3 tgpig[[threadgroup_position_in_grid]], |
| 90 | ushort3 tpitg[[thread_position_in_threadgroup]], |
| 91 | ushort3 ntg[[threads_per_threadgroup]]); |
| 92 | |
| 93 | template<ggml_sort_order order> |
| 94 | kernel void kernel_argsort_merge_f32_i32( |
| 95 | constant ggml_metal_kargs_argsort_merge & args, |
| 96 | device const char * src0, |
| 97 | device const int32_t * tmp, |
| 98 | device int32_t * dst, |
| 99 | uint3 tgpig[[threadgroup_position_in_grid]], |
| 100 | ushort3 tpitg[[thread_position_in_threadgroup]], |
| 101 | ushort3 ntg[[threads_per_threadgroup]]) { |
| 102 | |
| 103 | const int im = tgpig[0] / args.ne01; |
| 104 | const int i01 = tgpig[0] % args.ne01; |
| 105 | const int i02 = tgpig[1]; |
| 106 | const int i03 = tgpig[2]; |
| 107 | |
| 108 | const int start = im * (2 * args.len); |
| 109 | |
| 110 | const int len0 = MIN(args.len, MAX(0, args.ne0 - (int)(start))); |
| 111 | const int len1 = MIN(args.len, MAX(0, args.ne0 - (int)(start + args.len))); |
| 112 | |
| 113 | const int total = len0 + len1; |
| 114 | |
| 115 | device const int32_t * tmp0 = tmp + start |
| 116 | + i01*args.ne0 |
| 117 | + i02*args.ne0*args.ne01 |
| 118 | + i03*args.ne0*args.ne01*args.ne02; |
| 119 | |
| 120 | device const int32_t * tmp1 = tmp0 + args.len; |
| 121 | |
| 122 | dst += start |
| 123 | + i01*args.top_k |
| 124 | + i02*args.top_k*args.ne01 |
| 125 | + i03*args.top_k*args.ne01*args.ne02; |
| 126 | |
| 127 | device const float * src0_row = (device const float *)(src0 |
| 128 | + args.nb01*i01 |
| 129 | + args.nb02*i02 |
| 130 | + args.nb03*i03); |
| 131 | |
| 132 | if (total == 0) { |
| 133 | return; |
| 134 | } |
| 135 | |
| 136 | const int chunk = (total + ntg.x - 1) / ntg.x; |
| 137 | |
| 138 | const int k0 = tpitg.x * chunk; |
| 139 | const int k1 = MIN(MIN(k0 + chunk, total), args.top_k); |
| 140 | |
| 141 | if (k0 >= args.top_k) { |
| 142 | return; |
| 143 | } |
| 144 | |
| 145 | if (k0 >= total) { |
| 146 | return; |
| 147 | } |
| 148 | |
| 149 | int low = k0 > len1 ? k0 - len1 : 0; |
| 150 | int high = MIN(k0, len0); |
| 151 | |
| 152 | // binary-search partition (i, j) such that i + j = k |
| 153 | while (low < high) { |
| 154 | const int mid = (low + high) >> 1; |
| 155 | |
| 156 | const int32_t idx0 = tmp0[mid]; |
| 157 | const int32_t idx1 = tmp1[k0 - mid - 1]; |
| 158 | |
| 159 | const float val0 = src0_row[idx0]; |
| 160 | const float val1 = src0_row[idx1]; |
| 161 | |
| 162 | bool take_left; |
| 163 | if (order == GGML_SORT_ORDER_ASC) { |
| 164 | take_left = (val0 <= val1); |
| 165 | } else { |
| 166 | take_left = (val0 >= val1); |
| 167 | } |
| 168 | |
| 169 | if (take_left) { |
| 170 | low = mid + 1; |
| 171 | } else { |
| 172 | high = mid; |
| 173 | } |
| 174 | } |
| 175 | |
| 176 | int i = low; |
| 177 | int j = k0 - i; |
| 178 | |
| 179 | // keep the merge fronts into registers |
| 180 | int32_t idx0 = 0; |
| 181 | float val0 = 0.0f; |
| 182 | if (i < len0) { |
| 183 | idx0 = tmp0[i]; |
| 184 | val0 = src0_row[idx0]; |
| 185 | } |
| 186 | |
| 187 | int32_t idx1 = 0; |
| 188 | float val1 = 0.0f; |
| 189 | if (j < len1) { |
| 190 | idx1 = tmp1[j]; |
| 191 | val1 = src0_row[idx1]; |
| 192 | } |
| 193 | |
| 194 | for (int k = k0; k < k1; ++k) { |
| 195 | int32_t out_idx; |
| 196 | |
| 197 | if (i >= len0) { |
| 198 | while (k < k1) { |
| 199 | dst[k++] = tmp1[j++]; |
| 200 | } |
| 201 | break; |
| 202 | } else if (j >= len1) { |
| 203 | while (k < k1) { |
| 204 | dst[k++] = tmp0[i++]; |
| 205 | } |
| 206 | break; |
| 207 | } else { |
| 208 | bool take_left; |
| 209 | |
| 210 | if (order == GGML_SORT_ORDER_ASC) { |
| 211 | take_left = (val0 <= val1); |
| 212 | } else { |
| 213 | take_left = (val0 >= val1); |
| 214 | } |
| 215 | |
| 216 | if (take_left) { |
| 217 | out_idx = idx0; |
| 218 | ++i; |
| 219 | if (i < len0) { |
| 220 | idx0 = tmp0[i]; |
| 221 | val0 = src0_row[idx0]; |
| 222 | } |
| 223 | } else { |
| 224 | out_idx = idx1; |
| 225 | ++j; |
| 226 | if (j < len1) { |
| 227 | idx1 = tmp1[j]; |
| 228 | val1 = src0_row[idx1]; |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | dst[k] = out_idx; |
| 234 | } |
| 235 | } |
| 236 | |
| 237 | template [[host_name("kernel_argsort_merge_f32_i32_asc")]] kernel argsort_merge_t kernel_argsort_merge_f32_i32<GGML_SORT_ORDER_ASC>; |
| 238 | template [[host_name("kernel_argsort_merge_f32_i32_desc")]] kernel argsort_merge_t kernel_argsort_merge_f32_i32<GGML_SORT_ORDER_DESC>; |
| 239 | |
| 240 | static inline uint ggml_top_k_f2ui(float x) { |
| 241 | uint y = as_type<uint>(x); |
| 242 | if ((y & 0x80000000u) != 0u) { |
| 243 | y ^= 0xFFFFFFFFu; // negative floats: flip all bits |
| 244 | } else { |
| 245 | y |= 0x80000000u; // positive floats: set the sign bit |
| 246 | } |
| 247 | return y; |
| 248 | } |
| 249 | |
| 250 | kernel void kernel_top_k_f32_i32( |
| 251 | constant ggml_metal_kargs_top_k & args, |
| 252 | device const char * src0, |
| 253 | device int32_t * dst, |
| 254 | threadgroup atomic_uint * histo [[threadgroup(0)]], |
| 255 | threadgroup uint * sh_bucket [[threadgroup(1)]], |
| 256 | threadgroup uint * sh_above [[threadgroup(2)]], |
| 257 | threadgroup atomic_uint * out_count [[threadgroup(3)]], |
| 258 | uint3 tgpig[[threadgroup_position_in_grid]], |
| 259 | ushort3 tpitg[[thread_position_in_threadgroup]], |
| 260 | ushort3 ntg[[threads_per_threadgroup]]) { |
| 261 | |
| 262 | const uint ncols = args.ne00; |
| 263 | const uint top_k = args.top_k; |
| 264 | const uint i01 = tgpig[0]; |
| 265 | const uint i02 = tgpig[1]; |
| 266 | const uint i03 = tgpig[2]; |
| 267 | |
| 268 | device const float * src0_row = (device const float *) (src0 + args.nb01*i01 + args.nb02*i02 + args.nb03*i03); |
| 269 | |
| 270 | device int32_t * dst_row = dst + top_k*(i01 + args.ne01*i02 + args.ne01*args.ne02*i03); |
| 271 | |
| 272 | const uint tid = tpitg.x; |
| 273 | const uint ntg_x = ntg.x; |
| 274 | |
| 275 | uint prefix = 0; // fixed high bits of the threshold key |
| 276 | uint desired = top_k; // count still needed from the candidate range |
| 277 | |
| 278 | for (int shift = 24; shift >= 0; shift -= 8) { |
| 279 | for (uint i = tid; i < 256; i += ntg_x) { |
| 280 | atomic_store_explicit(&histo[i], 0u, memory_order_relaxed); |
| 281 | } |
| 282 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 283 | |
| 284 | const uint hi_mask = (shift + 8 >= 32) ? 0u : (0xFFFFFFFFu << uint(shift + 8)); |
| 285 | const uint prefix_hi = prefix & hi_mask; |
| 286 | |
| 287 | for (uint i = tid; i < ncols; i += ntg_x) { |
| 288 | const uint key = ggml_top_k_f2ui(src0_row[i]); |
| 289 | if ((key & hi_mask) == prefix_hi) { |
| 290 | atomic_fetch_add_explicit(&histo[(key >> uint(shift)) & 0xFFu], 1u, memory_order_relaxed); |
| 291 | } |
| 292 | } |
| 293 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 294 | |
| 295 | // top-down scan for the bucket holding the k-th value |
| 296 | if (tid == 0) { |
| 297 | uint acc = 0; |
| 298 | uint b = 0; |
| 299 | for (int bb = 255; bb >= 0; --bb) { |
| 300 | const uint c = atomic_load_explicit(&histo[bb], memory_order_relaxed); |
| 301 | if (acc + c >= desired) { |
| 302 | b = uint(bb); |
| 303 | break; |
| 304 | } |
| 305 | acc += c; |
| 306 | } |
| 307 | *sh_bucket = b; |
| 308 | *sh_above = acc; |
| 309 | } |
| 310 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 311 | |
| 312 | prefix |= *sh_bucket << uint(shift); |
| 313 | desired -= *sh_above; |
| 314 | |
| 315 | // ensure every thread has consumed sh_bucket/sh_above before the next pass |
| 316 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 317 | } |
| 318 | |
| 319 | if (tid == 0) { |
| 320 | atomic_store_explicit(out_count, 0u, memory_order_relaxed); |
| 321 | } |
| 322 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 323 | |
| 324 | // emit everything above the threshold, then fill the rest from ties |
| 325 | const uint threshold = prefix; |
| 326 | |
| 327 | for (uint i = tid; i < ncols; i += ntg_x) { |
| 328 | if (ggml_top_k_f2ui(src0_row[i]) > threshold) { |
| 329 | const uint pos = atomic_fetch_add_explicit(out_count, 1u, memory_order_relaxed); |
| 330 | dst_row[pos] = (int32_t) i; |
| 331 | } |
| 332 | } |
| 333 | threadgroup_barrier(mem_flags::mem_threadgroup); |
| 334 | |
| 335 | for (uint i = tid; i < ncols; i += ntg_x) { |
| 336 | if (ggml_top_k_f2ui(src0_row[i]) == threshold) { |
| 337 | const uint pos = atomic_fetch_add_explicit(out_count, 1u, memory_order_relaxed); |
| 338 | if (pos < top_k) { |
| 339 | dst_row[pos] = (int32_t) i; |
| 340 | } |
| 341 | } |
| 342 | } |
| 343 | } |
| 344 | |
| 345 | // fused SOFT_MAX + top-k + GET_ROWS (+ optional norm/scale) for MoE routing. |
| 346 | // One SIMDgroup handles one token row; n_expert is limited to 1024 by the host. |
| 347 | kernel void kernel_topk_moe_f32( |
| 348 | constant ggml_metal_kargs_topk_moe & args, |
| 349 | device const char * src0, |
| 350 | device float * weights, |
| 351 | device int32_t * ids, |
| 352 | uint3 tgpig[[threadgroup_position_in_grid]], |
| 353 | ushort tiisg[[thread_index_in_simdgroup]]) { |
| 354 | const int row = (int) tgpig.x; |
| 355 | if (row >= args.ne01) { |
| 356 | return; |
| 357 | } |
| 358 | |
| 359 | const int n_expert = FC_topk_moe_n_expert; |
| 360 | const int top_k = FC_topk_moe_top_k; |
| 361 | const int lane = (int) tiisg; |
| 362 | const int n_per_lane = (n_expert + 31) / 32; |
| 363 | |
| 364 | device const float * logits_row = (device const float *) (src0 + row * args.nb01); |
| 365 | device float * weights_row = weights + row * top_k; |
| 366 | device int32_t * ids_row = ids + row * (args.nb1_ids / sizeof(int32_t)); |
| 367 | |
| 368 | float wt[32]; |
| 369 | float output_weights[32]; |
| 370 | FOR_UNROLL (int i = 0; i < 32; ++i) { |
| 371 | wt[i] = -INFINITY; |
| 372 | output_weights[i] = 0.0f; |
| 373 | } |
| 374 | |
| 375 | for (int i = lane; i < n_expert; i += 32) { |
| 376 | const float v = logits_row[i]; |
| 377 | wt[i / 32] = isnan(v) ? -FLT_MAX : v; |
| 378 | } |
| 379 | |
| 380 | // softmax over the expert logits |
| 381 | float max_val = -INFINITY; |
| 382 | FOR_UNROLL (int i = 0; i < n_per_lane; ++i) { |
| 383 | max_val = max(max_val, wt[i]); |
| 384 | } |
| 385 | max_val = simd_max(max_val); |
| 386 | |
| 387 | float sum_val = 0.0f; |
| 388 | FOR_UNROLL (int i = 0; i < n_per_lane; ++i) { |
| 389 | wt[i] = exp(wt[i] - max_val); |
| 390 | sum_val += wt[i]; |
| 391 | } |
| 392 | sum_val = simd_sum(sum_val); |
| 393 | |
| 394 | const float inv_sum = 1.0f / sum_val; |
| 395 | FOR_UNROLL (int i = 0; i < n_per_lane; ++i) { |
| 396 | wt[i] *= inv_sum; |
| 397 | } |
| 398 | |
| 399 | float wt_sum = 0.0f; |
| 400 | |
| 401 | for (int k = 0; k < top_k; ++k) { |
| 402 | float best_val = -INFINITY; |
| 403 | int best_expert = -1; |
| 404 | |
| 405 | FOR_UNROLL (int i = 0; i < n_per_lane; ++i) { |
| 406 | const int expert = lane + i * 32; |
| 407 | if (expert < n_expert && (wt[i] > best_val || (wt[i] == best_val && expert < best_expert))) { |
| 408 | best_val = wt[i]; |
| 409 | best_expert = expert; |
| 410 | } |
| 411 | } |
| 412 | |
| 413 | FOR_UNROLL (int mask = 16; mask > 0; mask >>= 1) { |
| 414 | const float val = simd_shuffle_xor(best_val, mask); |
| 415 | const int expert = simd_shuffle_xor(best_expert, mask); |
| 416 | if (val > best_val || (val == best_val && expert < best_expert)) { |
| 417 | best_val = val; |
| 418 | best_expert = expert; |
| 419 | } |
| 420 | } |
| 421 | |
| 422 | if ((best_expert & 31) == lane) { |
| 423 | wt[best_expert / 32] = -INFINITY; |
| 424 | } |
| 425 | |
| 426 | if ((k & 31) == lane) { |
| 427 | output_weights[k / 32] = best_val; |
| 428 | } |
| 429 | |
| 430 | if ((best_expert & 31) == lane) { |
| 431 | ids_row[k] = best_expert; |
| 432 | if (FC_topk_moe_with_norm) { |
| 433 | wt_sum += best_val; |
| 434 | } |
| 435 | } |
| 436 | } |
| 437 | |
| 438 | if (FC_topk_moe_with_norm) { |
| 439 | wt_sum = simd_sum(wt_sum); |
| 440 | wt_sum = max(wt_sum, args.clamp); |
| 441 | const float inv = 1.0f / wt_sum; |
| 442 | FOR_UNROLL (int i = 0; i < n_per_lane; ++i) { |
| 443 | output_weights[i] *= inv; |
| 444 | } |
| 445 | } |
| 446 | |
| 447 | FOR_UNROLL (int i = 0; i < n_per_lane; ++i) { |
| 448 | const int idx = i * 32 + lane; |
| 449 | if (idx < top_k) { |
| 450 | weights_row[idx] = output_weights[i] * args.scale; |
| 451 | } |
| 452 | } |
| 453 | } |
| 454 | |
| 455 | // fused MoE expert weighting + reduction: weighted = sum(experts[e] * weights[e]). |
| 456 | // The host guarantees all tensors are contiguous F32. |
| 457 | kernel void kernel_moe_reduce_f32( |
| 458 | constant ggml_metal_kargs_moe_reduce & args, |
| 459 | device const float * experts, |
| 460 | device const float * weights, |
| 461 | device float * dst, |
| 462 | uint3 tgpig[[threadgroup_position_in_grid]], |
| 463 | ushort3 tpitg[[thread_position_in_threadgroup]], |
| 464 | ushort3 ntg[[threads_per_threadgroup]]) { |
| 465 | const int64_t token = tgpig.x; |
| 466 | const int64_t col = (int64_t) tgpig.y * ntg.x + tpitg.x; |
| 467 | if (token >= args.ne02 || col >= args.ne00) { |
| 468 | return; |
| 469 | } |
| 470 | |
| 471 | const int n_expert_used = FC_moe_reduce_n_expert_used; |
| 472 | |
| 473 | const int64_t base = token * (int64_t) n_expert_used * args.ne00 + col; |
| 474 | float sum = 0.0f; |
| 475 | FOR_UNROLL (int e = 0; e < n_expert_used; ++e) { |
| 476 | sum += experts[base + e * args.ne00] * weights[token * n_expert_used + e]; |
| 477 | } |
| 478 | dst[token * args.ne00 + col] = sum; |
| 479 | } |