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/topk-moe.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 / topk-moe.cu` 516 lines ยท 20475 bytes Raw Blame History 1 #include "ggml-cuda/common.cuh" 2 #include "ggml.h" 3 #include "topk-moe.cuh" 4 5 #include 6 #include 7 8 // Kernel config struct - passed by value to CUDA kernel 9 struct topk_moe_config { 10 bool use_sigmoid; 11 bool use_sqrt_softplus; 12 bool with_norm; 13 bool delayed_softmax; 14 int n_groups; 15 int n_group_used; 16 }; 17 18 // Warp-local softmax used for both the pre-top-k logits and the post-top-k delayed path. 19 template 20 __device__ void softmax_warp_inplace(float (&vals)[experts_per_thread], const int limit, const int lane) { 21 float max_val = -INFINITY; 22 23 #pragma unroll 24 for (int i = 0; i < experts_per_thread; i++) { 25 const int idx = lane + i * WARP_SIZE; 26 const bool active = !use_limit || (idx < limit); 27 if (active) { 28 max_val = max(max_val, vals[i]); 29 } 30 } 31 32 max_val = warp_reduce_max(max_val); 33 34 float sum = 0.f; 35 36 #pragma unroll 37 for (int i = 0; i < experts_per_thread; i++) { 38 const int idx = lane + i * WARP_SIZE; 39 const bool active = !use_limit || (idx < limit); 40 if (active) { 41 const float val = expf(vals[i] - max_val); 42 vals[i] = val; 43 sum += val; 44 } else { 45 vals[i] = 0.f; 46 } 47 } 48 49 sum = warp_reduce_sum(sum); 50 51 const float inv_sum = 1.0f / sum; 52 53 #pragma unroll 54 for (int i = 0; i < experts_per_thread; i++) { 55 const int idx = lane + i * WARP_SIZE; 56 const bool active = !use_limit || (idx < limit); 57 if (active) { 58 vals[i] *= inv_sum; 59 } 60 } 61 } 62 63 template 64 __device__ void sigmoid_warp_inplace(float (&vals)[experts_per_thread], const int limit, const int lane) { 65 #pragma unroll 66 for (int i = 0; i < experts_per_thread; i++) { 67 const int idx = lane + i * WARP_SIZE; 68 const bool active = !use_limit || (idx < limit); 69 vals[i] = active ? 1.f / (1.f + expf(-vals[i])) : -INFINITY; 70 } 71 } 72 73 template 74 __device__ void sqrt_softplus_warp_inplace(float (&vals)[experts_per_thread], const int limit, const int lane) { 75 #pragma unroll 76 for (int i = 0; i < experts_per_thread; i++) { 77 const int idx = lane + i * WARP_SIZE; 78 const bool active = !use_limit || (idx < limit); 79 vals[i] = active ? sqrtf(vals[i] > 20.0f ? vals[i] : log1pf(expf(vals[i]))) : -INFINITY; 80 } 81 } 82 83 #if !defined(GGML_USE_HIP) || HIP_VERSION >= `60300000` 84 // Set -inf for experts outside the top n_group_used groups. Group score is the sum of its top-2 experts (DeepSeek V3). 85 template 86 __device__ void group_mask_warp_inplace(float (&vals)[experts_per_thread], const int n_groups, const int n_group_used, const int lane) { 87 const int n_per_group = n_experts / n_groups; 88 89 float score = -INFINITY; // lane g holds the score of group g 90 for (int g = 0; g < n_groups; g++) { 91 float top1 = -INFINITY; 92 float top2 = -INFINITY; 93 #pragma unroll 94 for (int i = 0; i < experts_per_thread; i++) { 95 if ((i * WARP_SIZE + lane) / n_per_group == g) { 96 top2 = fmaxf(top2, fminf(top1, vals[i])); 97 top1 = fmaxf(top1, vals[i]); 98 } 99 } 100 #pragma unroll 101 for (int offset = WARP_SIZE / 2; offset > 0; offset >>= 1) { 102 const float o1 = __shfl_xor_sync(0xFFFFFFFF, top1, offset, WARP_SIZE); 103 const float o2 = __shfl_xor_sync(0xFFFFFFFF, top2, offset, WARP_SIZE); 104 top2 = fmaxf(fminf(top1, o1), fmaxf(top2, o2)); 105 top1 = fmaxf(top1, o1); 106 } 107 if (lane == g) { 108 score = top1 + top2; 109 } 110 } 111 112 // rank of each group, lower index wins ties 113 int rank = 0; 114 for (int g = 0; g < n_groups; g++) { 115 const float other = __shfl_sync(0xFFFFFFFF, score, g, WARP_SIZE); 116 rank += other > score || (other == score && g < lane); 117 } 118 const auto keep = __ballot_sync(0xFFFFFFFFULL, lane < n_groups && rank < n_group_used); 119 120 #pragma unroll 121 for (int i = 0; i < experts_per_thread; i++) { 122 const int g = (i * WARP_SIZE + lane) / n_per_group; 123 if (g >= n_groups || !((keep >> g) & 1)) { 124 vals[i] = -INFINITY; 125 } 126 } 127 } 128 #endif // !defined(GGML_USE_HIP) || HIP_VERSION >= `60300000` 129 130 /* 131 This kernel does the following: 132 1. optionally softmax over the logits per token [n_experts, n_tokens] 133 2. argmax reduce over the top-k (n_experts_used) logits 134 3. write weights + ids to global memory 135 4. optionally normalize the weights or apply softmax over the selected logits 136 137 It is intended as fusion of softmax->top-k->get_rows pipeline for MoE models 138 */ 139 template 140 __launch_bounds__(TOPK_MOE_ROWS_PER_BLOCK * WARP_SIZE, 1) 141 __global__ void topk_moe_cuda(const float * logits, 142 float * weights, 143 int32_t * ids, 144 float * bias, 145 const int n_rows, 146 const int n_expert_used, 147 const float clamp_val, 148 const float scale_val, 149 const topk_moe_config config) { 150 #if defined(GGML_USE_MUSA) 151 // MUSA: every warp of a partially filled block must reach the barrier below. 152 const int row = MIN(blockIdx.x * blockDim.y + threadIdx.y, n_rows - 1); 153 #else 154 const int row = blockIdx.x * blockDim.y + threadIdx.y; 155 #endif // defined(GGML_USE_MUSA) 156 if (row >= n_rows) { 157 return; 158 } 159 160 logits += n_experts * row; 161 weights += n_expert_used * row; 162 ids += n_experts * row; 163 164 constexpr int experts_per_thread = (n_experts > WARP_SIZE) ? n_experts / WARP_SIZE : 1; 165 166 float wt[experts_per_thread]; 167 168 // Initialize all slots to -INFINITY 169 #pragma unroll 170 for (int i = 0; i < experts_per_thread; i++) { 171 wt[i] = -INFINITY; 172 } 173 174 ggml_cuda_pdl_sync(); 175 #pragma unroll 176 for (int i = 0; i < n_experts; i += WARP_SIZE) { 177 const int expert = i + threadIdx.x; 178 wt[i / WARP_SIZE] = (n_experts % WARP_SIZE == 0 || expert < n_experts) ? logits[expert] : -INFINITY; 179 } 180 181 // Weights and IDs can alias logits, so wait until every row in the block reads its logits. 182 __syncthreads(); 183 184 if (!config.delayed_softmax) { 185 if (config.use_sigmoid) { 186 sigmoid_warp_inplace(wt, n_experts, threadIdx.x); 187 } else if (config.use_sqrt_softplus) { 188 sqrt_softplus_warp_inplace(wt, n_experts, threadIdx.x); 189 } else { 190 softmax_warp_inplace(wt, n_experts, threadIdx.x); 191 } 192 } 193 194 // Sanitize NaN to -FLT_MAX so the iterative argmax produces unique expert IDs. 195 // NaN comparisons always return false, which would cause the same expert to be 196 // selected repeatedly. -FLT_MAX compares normally and is still excluded by the 197 // -INFINITY sentinel used after each selection round. 198 // More relevant for the cuBLAS path. See https://github.com/ggml-org/llama.cpp/issues/19659 199 #pragma unroll 200 for (int i = 0; i < experts_per_thread; i++) { 201 if (__isnanf(wt[i])) { 202 wt[i] = -FLT_MAX; 203 } 204 } 205 206 // selection_wt is only needed when bias is present (selection uses wt + bias) 207 // when no bias, we use wt directly for both selection and weight values 208 [[maybe_unused]] float selection_wt[has_bias ? experts_per_thread : 1]; 209 210 if constexpr (has_bias) { 211 #pragma unroll 212 for (int i = 0; i < experts_per_thread; i++) { 213 selection_wt[i] = -INFINITY; 214 } 215 #pragma unroll 216 for (int i = 0; i < n_experts; i += WARP_SIZE) { 217 const int expert = i + threadIdx.x; 218 selection_wt[i / WARP_SIZE] = 219 (n_experts % WARP_SIZE == 0 || expert < n_experts) ? wt[i / WARP_SIZE] + bias[expert] : -INFINITY; 220 } 221 } 222 223 #if !defined(GGML_USE_HIP) || HIP_VERSION >= `60300000` 224 // without bias, masking wt is safe: the matcher ensures the kept groups hold all used experts 225 if (config.n_groups > 0) { 226 if constexpr (has_bias) { 227 group_mask_warp_inplace(selection_wt, config.n_groups, config.n_group_used, threadIdx.x); 228 } else { 229 group_mask_warp_inplace(wt, config.n_groups, config.n_group_used, threadIdx.x); 230 } 231 } 232 #endif // !defined(GGML_USE_HIP) || HIP_VERSION >= `60300000` 233 234 //at this point, each thread holds either a portion of the softmax distribution 235 //or the raw logits. We do the argmax reduce over n_expert_used, each time marking 236 //the expert weight as -inf to exclude from the next iteration 237 238 float wt_sum = 0.f; 239 240 float output_weights[experts_per_thread]; 241 242 #pragma unroll 243 for (int i = 0; i < experts_per_thread; i++) { 244 output_weights[i] = 0.f; 245 } 246 247 ggml_cuda_pdl_lc(); 248 for (int k = 0; k < n_expert_used; k++) { 249 float max_val = wt[0]; 250 int max_expert = threadIdx.x; 251 252 if constexpr (has_bias) { 253 float max_val_s = selection_wt[0]; 254 255 #pragma unroll 256 for (int i = 1; i < experts_per_thread; i++) { 257 const int expert = threadIdx.x + i * WARP_SIZE; 258 if ((n_experts % WARP_SIZE == 0 || expert < n_experts) && selection_wt[i] > max_val_s) { 259 max_val = wt[i]; 260 max_val_s = selection_wt[i]; 261 max_expert = expert; 262 } 263 } 264 265 #pragma unroll 266 for (int mask = WARP_SIZE / 2; mask > 0; mask /= 2) { 267 const float val = __shfl_xor_sync(0xFFFFFFFF, max_val, mask, WARP_SIZE); 268 const float val_s = __shfl_xor_sync(0xFFFFFFFF, max_val_s, mask, WARP_SIZE); 269 const int expert = __shfl_xor_sync(0xFFFFFFFF, max_expert, mask, WARP_SIZE); 270 if (val_s > max_val_s || (val_s == max_val_s && expert < max_expert)) { 271 max_val = val; 272 max_val_s = val_s; 273 max_expert = expert; 274 } 275 } 276 277 if ((max_expert & (WARP_SIZE - 1)) == threadIdx.x) { 278 selection_wt[max_expert / WARP_SIZE] = -INFINITY; 279 } 280 } else { 281 #pragma unroll 282 for (int i = 1; i < experts_per_thread; i++) { 283 const int expert = threadIdx.x + i * WARP_SIZE; 284 if ((n_experts % WARP_SIZE == 0 || expert < n_experts) && wt[i] > max_val) { 285 max_val = wt[i]; 286 max_expert = expert; 287 } 288 } 289 290 #pragma unroll 291 for (int mask = WARP_SIZE / 2; mask > 0; mask /= 2) { 292 const float val = __shfl_xor_sync(0xFFFFFFFF, max_val, mask, WARP_SIZE); 293 const int expert = __shfl_xor_sync(0xFFFFFFFF, max_expert, mask, WARP_SIZE); 294 if (val > max_val || (val == max_val && expert < max_expert)) { 295 max_val = val; 296 max_expert = expert; 297 } 298 } 299 300 if ((max_expert & (WARP_SIZE - 1)) == threadIdx.x) { 301 wt[max_expert / WARP_SIZE] = -INFINITY; 302 } 303 } 304 305 if ((k & (WARP_SIZE - 1)) == threadIdx.x) { 306 output_weights[k / WARP_SIZE] = max_val; 307 } 308 309 if ((max_expert & (WARP_SIZE - 1)) == threadIdx.x) { 310 ids[k] = max_expert; 311 if (config.with_norm) { 312 wt_sum += max_val; 313 } 314 } 315 } 316 317 if (config.with_norm) { 318 wt_sum = warp_reduce_sum(wt_sum); 319 wt_sum = max(wt_sum, clamp_val); 320 const float inv_sum = 1.0f / wt_sum; 321 322 for (int i = 0; i < experts_per_thread; i++) { 323 output_weights[i] *= inv_sum; 324 } 325 } 326 327 if (config.delayed_softmax) { 328 softmax_warp_inplace(output_weights, n_expert_used, threadIdx.x); 329 } 330 331 #pragma unroll 332 for (int i = 0; i < experts_per_thread; i++) { 333 const int idx = i * WARP_SIZE + threadIdx.x; 334 if (idx < n_expert_used) { 335 weights[idx] = output_weights[i] * scale_val; 336 } 337 } 338 } 339 340 template 341 static void launch_topk_moe_cuda(ggml_backend_cuda_context & ctx, 342 const float * logits, 343 float * weights, 344 int32_t * ids, 345 float * bias, 346 const int n_rows, 347 const int n_expert, 348 const int n_expert_used, 349 const float clamp_val, 350 const float scale_val, 351 const topk_moe_config config) { 352 GGML_ASSERT(!(config.with_norm && config.delayed_softmax) && 353 "delayed softmax is not supported with weight normalization"); 354 const int rows_per_block = TOPK_MOE_ROWS_PER_BLOCK; 355 dim3 grid_dims((n_rows + rows_per_block - 1) / rows_per_block, 1, 1); 356 dim3 block_dims(WARP_SIZE, rows_per_block, 1); 357 cudaStream_t stream = ctx.stream(); 358 const ggml_cuda_kernel_launch_params launch_params = ggml_cuda_kernel_launch_params(grid_dims, block_dims, 0, stream); 359 360 #if defined(GGML_USE_HIP) && HIP_VERSION < `60300000` 361 GGML_ASSERT(config.n_groups == 0 && "expert groups fusion is not supported on this HIP version"); 362 #endif 363 364 switch (n_expert) { 365 case 1: 366 ggml_cuda_kernel_launch(topk_moe_cuda<1, has_bias>, launch_params, 367 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 368 break; 369 case 2: 370 ggml_cuda_kernel_launch(topk_moe_cuda<2, has_bias>, launch_params, 371 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 372 break; 373 case 4: 374 ggml_cuda_kernel_launch(topk_moe_cuda<4, has_bias>, launch_params, 375 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 376 break; 377 case 8: 378 ggml_cuda_kernel_launch(topk_moe_cuda<8, has_bias>, launch_params, 379 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 380 break; 381 case 16: 382 ggml_cuda_kernel_launch(topk_moe_cuda<16, has_bias>, launch_params, 383 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 384 break; 385 case 32: 386 ggml_cuda_kernel_launch(topk_moe_cuda<32, has_bias>, launch_params, 387 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 388 break; 389 case 64: 390 ggml_cuda_kernel_launch(topk_moe_cuda<64, has_bias>, launch_params, 391 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 392 break; 393 case 128: 394 ggml_cuda_kernel_launch(topk_moe_cuda<128, has_bias>, launch_params, 395 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 396 break; 397 case 256: 398 ggml_cuda_kernel_launch(topk_moe_cuda<256, has_bias>, launch_params, 399 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 400 break; 401 case 288: // StepFun 3.7 402 ggml_cuda_kernel_launch(topk_moe_cuda<288, has_bias>, launch_params, 403 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 404 break; 405 case 384: // DeepSeek V4.1 406 ggml_cuda_kernel_launch(topk_moe_cuda<384, has_bias>, launch_params, 407 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 408 break; 409 case 512: 410 ggml_cuda_kernel_launch(topk_moe_cuda<512, has_bias>, launch_params, 411 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 412 break; 413 case 576: 414 ggml_cuda_kernel_launch(topk_moe_cuda<576, has_bias>, launch_params, 415 logits, weights, ids, bias, n_rows, n_expert_used, clamp_val, scale_val, config); 416 break; 417 default: 418 GGML_ASSERT(false && "fatal error"); 419 } 420 } 421 422 void ggml_cuda_op_topk_moe(ggml_backend_cuda_context & ctx, 423 const ggml_tensor * logits, 424 ggml_tensor * weights, 425 ggml_tensor * ids, 426 const ggml_tensor * clamp, 427 const ggml_tensor * scale, 428 const ggml_tensor * bias, 429 const ggml_cuda_topk_moe_args & args) { 430 GGML_ASSERT(logits->type == GGML_TYPE_F32); 431 GGML_ASSERT(weights->type == GGML_TYPE_F32); 432 GGML_ASSERT(ids->type == GGML_TYPE_I32); 433 434 const int n_experts = logits->ne[0]; 435 const int n_rows = logits->ne[1]; 436 437 const float * logits_d = (const float *) logits->data; 438 float * weights_d = (float *) weights->data; 439 int32_t * ids_d = (int32_t *) ids->data; 440 float * bias_d = bias ? (float *) bias->data : nullptr; 441 442 float scale_val = scale ? ggml_get_op_params_f32(scale, 0) : 1.0f; 443 444 GGML_ASSERT(ids->nb[1] / ggml_type_size(ids->type) == (size_t) n_experts); 445 446 const int n_expert_used = weights->ne[1]; 447 448 const bool with_norm = clamp != nullptr; 449 450 float clamp_val = -INFINITY; 451 if (clamp) { 452 clamp_val = ggml_get_op_params_f32(clamp, 0); 453 } 454 455 topk_moe_config config; 456 config.use_sigmoid = args.sigmoid; 457 config.use_sqrt_softplus = args.sqrt_softplus; 458 config.with_norm = with_norm; 459 config.delayed_softmax = args.delayed_softmax; 460 config.n_groups = args.n_groups; 461 config.n_group_used = args.n_group_used; 462 463 if (bias) { 464 launch_topk_moe_cuda(ctx, logits_d, weights_d, ids_d, bias_d, n_rows, n_experts, n_expert_used, clamp_val, 465 scale_val, config); 466 } else { 467 launch_topk_moe_cuda(ctx, logits_d, weights_d, ids_d, bias_d, n_rows, n_experts, n_expert_used, clamp_val, 468 scale_val, config); 469 } 470 } 471 472 bool ggml_cuda_should_use_topk_moe(const ggml_tensor * gating_op, 473 const ggml_tensor * weights, 474 const ggml_tensor * logits, 475 const ggml_tensor * ids) { 476 // must match an instantiation of launch_topk_moe_cuda: a power of 2 up to 512, 477 // or one of the non-power-of-2 expert counts of supported models 478 const int n_expert = ids->nb[1] / ids->nb[0]; 479 if (((n_expert & (n_expert - 1)) != 0 || n_expert > 512) && n_expert != 288 && n_expert != 384 && n_expert != 576) { 480 return false; 481 } 482 483 if (!ggml_is_contiguous(weights) || !ggml_is_contiguous(logits)) { 484 return false; 485 } 486 487 if (gating_op->op == GGML_OP_SOFT_MAX) { 488 const ggml_tensor * softmax = gating_op; 489 float scale = 1.0f; 490 float max_bias = 0.0f; 491 492 memcpy(&scale, (const float *) softmax->op_params + 0, sizeof(float)); 493 memcpy(&max_bias, (const float *) softmax->op_params + 1, sizeof(float)); 494 495 if (!ggml_is_contiguous(softmax->src[0])) { 496 return false; 497 } 498 499 if (scale != 1.0f || max_bias != 0.0f) { 500 return false; 501 } 502 503 // don't fuse when masks or sinks are present 504 if (softmax->src[1] || softmax->src[2]) { 505 return false; 506 } 507 } else if (gating_op->op == GGML_OP_UNARY) { 508 ggml_unary_op op = ggml_get_unary_op(gating_op); 509 510 if (op != GGML_UNARY_OP_SIGMOID && op != GGML_UNARY_OP_SOFTPLUS) { 511 return false; 512 } 513 } 514 515 return true; 516 }