File size: 30,889 Bytes
bdebe19 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 | // Torch binding: allocates workspace and launches the custom MoE megakernel pipeline (kernel.cu).
#include <torch/extension.h>
#include <ATen/cuda/CUDAContext.h>
#include <ATen/cuda/EmptyTensor.h>
#include <cmath>
#include <algorithm>
#include <cuda.h>
#include <cstring>
#include <vector>
#include <string>
#include <stdexcept>
#include "kernel.h"
#include "cutlass_path.h"
#include <unistd.h>
#ifdef MOE_XPROBE
#include <chrono>
#include <cstdio>
static double g_xp[8]; static int g_xpn[8];
static double xnow() { return std::chrono::duration<double, std::micro>(std::chrono::steady_clock::now().time_since_epoch()).count(); }
#define XPT(v) const double v = xnow()
#define XPA(i, d) do { g_xp[i] += (d); g_xpn[i]++; } while (0)
#else
#define XPT(v) do {} while (0)
#define XPA(i, d) do {} while (0)
#endif
#ifdef MOE_DIAG
#include <string>
#include <stdexcept>
std::string moe_persist_info();
#endif
#ifndef MOE_CUT_MIN
#define MOE_CUT_MIN 4096 // band probe w/ DQ: T4000 mega n192 3.805 vs mixed 3.965
#endif
static const int kCutlassMinTokens = MOE_CUT_MIN;
static int g_mkfill = 1;
static void* g_mkshadow = nullptr; // probe only: megakernel writes the args into this shadow workspace // MOE_MKFILL runtime switch (probe A/B only; production 1)
// Grow-only scratch buffers reused across calls (host overhead diet: no per-call caching-allocator
// round trips). Heap-allocated tensors, never destroyed (no static CUDA-tensor destructor at exit).
// All uses are stream-ordered on the torch current stream (side-stream work joins back into it).
static void* scratch_get(int slot, size_t bytes, const torch::Tensor& like) {
static at::Tensor** bufs = new at::Tensor*[4]();
static size_t* caps = new size_t[4]();
if (!bufs[slot] || caps[slot] < bytes) {
const size_t nb = std::max(bytes, caps[slot] + caps[slot] / 4);
if (!bufs[slot]) bufs[slot] = new at::Tensor();
*bufs[slot] = torch::empty({(long)nb}, like.options().dtype(torch::kUInt8));
caps[slot] = nb;
}
return bufs[slot]->data_ptr();
}
#ifdef MOE_STAGEPROBE
static cudaEvent_t* g_sev = nullptr; // DEBUG: stage boundary events of cutlass_run
#define SEV(i) do { if (g_sev) cudaEventRecord(g_sev[i], at::cuda::getCurrentCUDAStream()); } while (0)
#else
#define SEV(i) do {} while (0)
#endif
struct Knobs { int lag = 0 /*0: MOE_LAG*/; int nch = 0 /*0: auto*/; int ring = 0; int wpromo = 2; int xpromo = 2 /*probe: token map promo NONE -> 256B*/; int xwin = 1; int xpol = 1; int cpx = -1 /*-1: auto by nchunk*/; int dq = -1 /*-1: auto*/; int h64 = 2 /*2: exact-height Hs boxes*/; int opol = -1 /*-1: per-band default (MOE_OPOL_*)*/; int dil = -1 /*-1: per-band default (MOE_DIL_*)*/; int ew4 = -1; int r3off = -1; };
#ifndef MOE_CPX_MIN_NCH
#define MOE_CPX_MIN_NCH 128 // probe min-of-8 NCH128 gather4 / cp.async: T2048 3.219/3.219, T2144 3.46/3.40,
// T2240 3.76/3.60, T2304 3.89/3.69, T2400 3.72/3.62 -> cp.async everywhere
#endif
static void mega_path(const torch::Tensor& hidden_states, const torch::Tensor& expert_ids,
const torch::Tensor& expert_weights, const torch::Tensor& gate_proj_weights,
const torch::Tensor& up_proj_weights, const torch::Tensor& down_proj_weights,
torch::Tensor& out, const Knobs& kn) {
const int T = (int)hidden_states.size(0);
const int S = T * 8;
// (host-overhead trim: no TensorOptions construction here -- host time before the launch is
// idle GPU time in an isolated timed call)
// Token chunk per work item: smallest of {128,192,256} covering mean + 5 sd of the per-expert
// count (~Binomial(S, 1/256)), so experts almost never split while the smem token tile stays
// small (more pipeline stages).
const double avg = (double)S / 256.0;
const double need = avg + 5.0 * std::sqrt(avg);
const bool n128_dq = need > 128 && avg + 3.5 * std::sqrt(avg) <= 128;
int nchunk = (need <= 128 || n128_dq) ? 128 : (need <= 192 ? 192 : 256);
// NCH=160 sub-band of the old NCH=192 band: while mean + 4 sd of the per-expert count fits 160
// (T <~ 3720), 160-token chunks (10 KB token slots) buy a 6-deep weight ring instead of 5
// (expert split probability ~1e-5 per expert -> at worst one extra re-streamed expert, rare)
#ifndef MOE_N160
#define MOE_N160 0
#endif
// MOE_N176: within the NCH=192 band, 176-token chunks while mean + 5 sd of the per-expert count
// fits 176 (T <~ 3900; T3719: 116 + 54 = 170): token slots 11 KB instead of 12 KB (5-deep rings kept),
// HSN 11 maps, same DQ / LAG 16 / tail K-split 10 / bf16 tanh SwiGLU as NCH=192
#ifndef MOE_N176
#define MOE_N176 1
#endif
if (MOE_N176 && nchunk == 192 && need <= 176.0) nchunk = 176;
#ifdef MOE_TEST176
nchunk = 176;
#endif
if (MOE_N160 && nchunk == 192 && avg + 4.0 * std::sqrt(avg) <= 160.0) nchunk = 160;
if (kn.nch > 0) nchunk = kn.nch;
#ifdef MOE_TEST_DQ
nchunk = 192;
#endif
const int max_chunks = 256 + S / nchunk + 1;
// + 4*14*16 ints: room for the tail K-split down items (kernel.cu DSPLIT_CHUNKS <= 16 extra chunks of 14)
int* iws_p = (int*)scratch_get(0, (size_t)(4 * (22 * max_chunks + 14 * 16) + 2 * max_chunks + 4 + 3 * S) * 4, hidden_states);
void* hs_p = scratch_get(1, (size_t)S * 2048 * 2, hidden_states);
MoeArgs a;
a.T = T;
a.nchunk = nchunk;
#ifndef MOE_LAG
#define MOE_LAG 16
#endif
// MOE_DQLAG16: n128_dq band (T~2600-3000, incl. T2767) now uses LAG 16 like the NCH>=176 bands (was 32):
// shorter gate|up -> down queue distance = fewer live Hs chunks (smaller persisting set-aside, lag+8)
a.lag = MOE_LAG; // T2767 LAG32 probe: NCH128-DQ band (n128_dq) uses LAG 32; other bands LAG 16
a.hidden = (const __nv_bfloat16*)hidden_states.data_ptr();
a.ids = (const long long*)expert_ids.data_ptr();
a.ew = (const __nv_bfloat16*)expert_weights.data_ptr();
a.gate = (const __nv_bfloat16*)gate_proj_weights.data_ptr();
a.up = (const __nv_bfloat16*)up_proj_weights.data_ptr();
a.down = (const __nv_bfloat16*)down_proj_weights.data_ptr();
int* ip = iws_p;
a.item_info = (int4*)ip; // 16-B aligned (tensor base)
a.done = ip + 4 * (22 * max_chunks + 14 * 16);
a.num_items = a.done + 2 * max_chunks; // done[2c] gate|up, done[2c+1] down counters
a.sorted_slot = a.num_items + 4;
a.meta = (int2*)(a.sorted_slot + S); // 8-B aligned: all preceding int counts are even
a.hs = (__nv_bfloat16*)hs_p;
a.out = (__nv_bfloat16*)out.data_ptr();
a.wpromo = kn.wpromo; a.xpromo = kn.xpromo; a.xwin = kn.xwin; a.ring = kn.ring; a.xpol = kn.xpol;
a.cpx = kn.cpx >= 0 ? kn.cpx : (nchunk >= MOE_CPX_MIN_NCH ? 1 : 0);
if (kn.lag > 0) a.lag = kn.lag;
#ifndef MOE_DQ_MIN_T
#define MOE_DQ_MIN_T 0
#endif
a.dq = (a.cpx == 1 && ((nchunk == 160) || (nchunk == 176) || (nchunk == 192 && T >= MOE_DQ_MIN_T) || (nchunk == 128 && n128_dq))) ? 1 : 0;
if (kn.dq >= 0) a.dq = (a.cpx == 1) ? kn.dq : 0;
#ifdef MOE_TEST_DQ
a.dq = (nchunk == 192 && a.cpx == 1) ? 1 : 0;
#endif
// MOE_LAG16_2400: upper small-band sub-band (avg = T/32 >= 72, T2304-2600 incl. T2400; items n16 ~80-112)
// uses LAG 16 (-> 1 K-quarter tail chunk, 5772-item queue = 39 waves of 148 CTAs); T<2304 keeps LAG 24
if (kn.dq < 0 && kn.nch <= 0 && nchunk == 128 && a.cpx == 1 && !a.dq) { a.dq = 1; if (kn.lag <= 0) a.lag = (avg >= 72.0) ? 16 : 24; }
a.h64 = kn.h64;
// full-path out L2 policy (zero stores + down red.adds): 0 evict_last, 1 evict_normal, 2 evict_first.
// Per band: S = small-T NCH=128 (T <= ~2600), D = NCH=128 DQ band (T~2600-3000), W = NCH>=176 band.
#ifndef MOE_OPOL_S
#define MOE_OPOL_S 0
#endif
#ifndef MOE_OPOL_D
#define MOE_OPOL_D 0
#endif
#ifndef MOE_OPOL_W
#define MOE_OPOL_W 0
#endif
a.opol = kn.opol >= 0 ? kn.opol : (nchunk > 128 ? MOE_OPOL_W : (n128_dq ? MOE_OPOL_D : MOE_OPOL_S));
// down-weight interleave of the full path's down items (kernel.cu make_tmap_down4):
// 0 = 32-row halves of 64-row groups, 1 = 16-row halves of 32-row groups (both: full 128-B out lines per warp)
#ifndef MOE_DIL_S
#define MOE_DIL_S 0
#endif
#ifndef MOE_DIL_D
#define MOE_DIL_D 0
#endif
#ifndef MOE_DIL_W
#define MOE_DIL_W 0
#endif
a.dil = kn.dil >= 0 ? kn.dil : (nchunk > 128 ? MOE_DIL_W : (n128_dq ? MOE_DIL_D : MOE_DIL_S));
// small T (<= MOE_EW4_MAX_T, NCH=128 round-robin): 4 epilogue warps drain all TMEM columns
#ifndef MOE_EW4_MAX_T
#define MOE_EW4_MAX_T 4096
#endif
a.ew4 = (nchunk == 128 && a.cpx == 1 && (n128_dq || T <= MOE_EW4_MAX_T)) ? 1 : 0;
if (kn.ew4 >= 0) a.ew4 = (nchunk == 128 && a.cpx == 1) ? kn.ew4 : 0;
a.r3off = a.ew4 ? 1 : 0;
if (kn.r3off >= 0) a.r3off = a.ew4 ? kn.r3off : 0; // n16 ~96 items: 2-buffer TMEM plan (3-slot ring would be 1.5 deep)
moe_forward(a, at::cuda::getCurrentCUDAStream());
}
#ifndef MOE_CUT_DQ
#define MOE_CUT_DQ 1
#endif
// mixed large-T path knobs (gate|up megakernel stage + CUTLASS down): defaults = production
#ifndef MOE_CUT_RV
#define MOE_CUT_RV 1
#endif
// rv: top-8 reduce kernel variant (0: scalar bf16<->fp32 math, 1: packed bf16x2 products)
// fused: down GEMM epilogue scatters w*acc into out via red.add (no Dbuf, no reduce kernel);
// -1 = auto by T (>= MOE_FUSED_MIN_T), 0 = Dbuf + top-8 reduce, 1 = fused
#ifndef MOE_FUSED_MIN_T
#define MOE_FUSED_MIN_T 0
#endif
#ifndef MOE_DNOPOL
#define MOE_DNOPOL 2 // CUTLASS down epilogue out red.add L2 policy: 0 evict_last, 1 evict_normal, 2 evict_first, 3 evict_unchanged.
#endif
#ifndef MOE_CUT_NSW
#define MOE_CUT_NSW 0 // non-swapped gate|up items (NCH=256 chunks only)
#endif
#ifndef MOE_MIXGRAPH
#define MOE_MIXGRAPH 1 // MIX path: replay the launch sequence as a cached CUDA graph
#endif
struct CutKnobs { int nsw = MOE_CUT_NSW; int nch = 0 /*0: auto (192 if mean+2sd of per-expert count <= 192, else 256)*/; int cpx = 1; int ring = 0; int tileN = 0 /*0: auto*/; int dq = MOE_CUT_DQ; int rv = MOE_CUT_RV; int fused = -1; int dcfg = 0; int raster = 1; int swz = 1 /*AlongM, NO swizzle: tile id -> (expert group, mtile) with mtile fastest, so the 28 M-tiles of an expert run on concurrently-active clusters and its Hs token tile is read from DRAM once (L2-hot for the other 27)*/; int opol = MOE_DNOPOL; int zpol = -1 /*-1: MOE_ZPOL*/; int gucap = -1 /*-1: per-band MOE_GUCAP_*; 0 all*/; int dsms = -1 /*-1: per-band MOE_DSMS_*; 0 all*/; int graph = MOE_MIXGRAPH; int hsdisc = 0 /*MOE_MIXHSDISC: 0 off (production; probe: discard is a loss), 1 all, 2 batch-1 only*/; };
// MOE_GRIDCAP per-band defaults (MIX path): gate|up megakernel CTA cap and CUTLASS down SM budget;
// _5 = NCH192 gate|up band (T~4096-5600, incl. T5120), _W = NCH256 band (T6144). 0 = all SMs.
#ifndef MOE_GUCAP_5
#define MOE_GUCAP_5 0
#endif
#ifndef MOE_GUCAP_W
#define MOE_GUCAP_W 0
#endif
#ifndef MOE_DSMS_5
#define MOE_DSMS_5 0
#endif
#ifndef MOE_DSMS_W
#define MOE_DSMS_W 0
#endif
static void cutlass_run(const torch::Tensor&, const torch::Tensor&, const torch::Tensor&, const torch::Tensor&,
const torch::Tensor&, const torch::Tensor&, torch::Tensor&, const CutKnobs& ck = CutKnobs());
#ifdef MOE_PROBE_D2
#define PROBE_TS 5120, 6144
#define PROBE_MEGA_MAX 0
#define PCF(nm, f) { CutKnobs k; k.fused = 1; f; addc(nm, k); }
#define PROBE_CFGS PCF("rM", k.raster = 1) PCF("rMs2", k.raster = 1; k.swz = 2) PCF("rNs4", k.raster = 2; k.swz = 4) \
PCF("rMs4", k.raster = 1; k.swz = 4) PCF("fus2", (void)0) PCF("rN", k.raster = 2) PCF("fus3", (void)0)
#elif defined(MOE_PROBE_D)
#define PROBE_TS 5120, 6144
#define PROBE_MEGA_MAX 0
#define PCF(nm, f) { CutKnobs k; k.fused = 1; f; addc(nm, k); }
#define PROBE_CFGS PCF("rM", k.raster = 1) PCF("rN", k.raster = 2) PCF("rNs2", k.raster = 2; k.swz = 2) \
PCF("rNs4", k.raster = 2; k.swz = 4) PCF("rNs8", k.raster = 2; k.swz = 8) PCF("rMs4", k.raster = 1; k.swz = 4) \
PCF("c4", k.dcfg = 1) PCF("c4rN", k.dcfg = 1; k.raster = 2) PCF("sm1", k.dcfg = 2) PCF("sm1rN", k.dcfg = 2; k.raster = 2) \
PCF("bn128", k.tileN = 128) PCF("bn128rN", k.tileN = 128; k.raster = 2) PCF("bn256", k.tileN = 256) PCF("fus2", (void)0)
#endif
#ifdef MOE_PROBE_N
#define PROBE_TS 5120, 6144
#define PROBE_MEGA_MAX 0
#define PROBE_CFGS { CutKnobs k; k.fused = 1; k.nsw = 1; k.nch = 256; addc("nsw256", k); } \
{ CutKnobs k; k.fused = 1; k.nsw = 0; k.nch = 256; addc("sw256", k); } { CutKnobs k; k.fused = 1; k.nsw = 0; addc("def2", k); }
#endif
#ifdef MOE_PROBE_A
#define PROBE_TS 4600, 5120, 5600, 6144
#define PROBE_MEGA_MAX 0
#define PROBE_CFGS { CutKnobs k; k.fused = 1; k.nch = 192; k.dq = 0; addc("n192rr", k); } { CutKnobs k; k.fused = 1; k.dq = 0; addc("n256rr", k); } { CutKnobs k; k.fused = 1; k.nch = 192; addc("nch192", k); }
#endif
#if defined(MOE_PROBE) || defined(MOE_PROBE_D)
#ifndef PROBE_TS
#define PROBE_TS 4096, 5120, 6144
#define PROBE_MEGA_MAX 0
#define PROBE_CFGS { CutKnobs k; k.fused = 0; addc("unf", k); } { CutKnobs k; k.fused = 1; addc("fus2", k); } { CutKnobs k; k.fused = 0; addc("unf2", k); }
#endif
#endif
torch::Tensor run(torch::Tensor hidden_states, torch::Tensor expert_ids, torch::Tensor expert_weights,
torch::Tensor gate_proj_weights, torch::Tensor up_proj_weights,
torch::Tensor down_proj_weights) {
// copies only when needed (flag checks; already-OK inputs skip the dispatcher calls)
if (!hidden_states.is_contiguous()) hidden_states = hidden_states.contiguous();
if (expert_ids.scalar_type() != torch::kInt64 || !expert_ids.is_contiguous())
expert_ids = expert_ids.to(torch::kInt64).contiguous();
if (expert_weights.scalar_type() != torch::kBFloat16 || !expert_weights.is_contiguous())
expert_weights = expert_weights.to(torch::kBFloat16).contiguous();
if (!gate_proj_weights.is_contiguous()) gate_proj_weights = gate_proj_weights.contiguous();
if (!up_proj_weights.is_contiguous()) up_proj_weights = up_proj_weights.contiguous();
if (!down_proj_weights.is_contiguous()) down_proj_weights = down_proj_weights.contiguous();
const int T = (int)hidden_states.size(0);
const int S = T * 8;
(void)S;
// Output allocated via the direct CUDA empty path (skips the dispatcher / TensorOptions build;
// host time before the launch is idle GPU time in an isolated timed call).
torch::Tensor out(at::detail::empty_cuda({T, 7168}, at::kBFloat16, hidden_states.device(), c10::nullopt));
if (T == 0) return out;
if (T >= kCutlassMinTokens) {
cutlass_run(hidden_states, expert_ids, expert_weights, gate_proj_weights, up_proj_weights, down_proj_weights, out);
return out;
}
mega_path(hidden_states, expert_ids, expert_weights, gate_proj_weights, up_proj_weights, down_proj_weights, out, Knobs());
#ifdef MOE_DIAG
throw std::runtime_error(moe_persist_info());
#endif
return out;
}
static void cutlass_run(const torch::Tensor& hidden_states, const torch::Tensor& expert_ids,
const torch::Tensor& expert_weights, const torch::Tensor& gate_proj_weights,
const torch::Tensor& up_proj_weights, const torch::Tensor& down_proj_weights,
torch::Tensor& out, const CutKnobs& ck) {
const int T = (int)hidden_states.size(0);
{
const double avg = (double)T * 8.0 / 256.0;
const double need = avg + 2.3 * std::sqrt(avg);
static const int kTiles[] = {128, 160, 192, 224, 256};
int tileN = 256;
for (int t : kTiles) if (t >= need) { tileN = t; break; }
if (ck.tileN > 0) tileN = ck.tileN;
auto st = at::cuda::getCurrentCUDAStream();
moe_clear_persist(st); // large-T no-persist: set-aside 0, persisting lines reset, no stream window
size_t bytes = cutpath::moe_workspace_bytes(T, tileN);
void* ws_p = scratch_get(2, bytes, hidden_states);
// 1) down-GEMM args; H / inv workspace pointers
void* h = nullptr;
int* inv = nullptr;
SEV(0);
// Off the critical path: fork the side stream FIRST and put the down-GEMM argument setup (1-block
// route_gather) and the out memset there, enqueued before the gate|up megakernel on st (which
// does its own routing and touches neither). Previously both sat on st ahead of the megakernel.
cudaStream_t side = cutpath::moe_fork(st);
// down-GEMM args are filled later by a co-resident 1-warp kernel (moe_fill_down_args)
cutpath::moe_ws_ptrs(T, tileN, ws_p, &h, &inv);
// 2) fused gate|up + SwiGLU (tcgen05 megakernel in gate|up-only mode, 256-token chunks,
// cp.async token loader): H[p] = silu(x W_g^T) * (x W_u^T) for expert-sorted rows p
// gate|up chunk width: 192 while an expert's tokens (mean + 2 sd) fit one 192-token chunk, else 256.
// Probe min-of-12 (ms, synthetic routing) nch256 / nch192: T4000 4.30/4.06, T4300 4.20/4.07,
// T4600 3.89/3.82, T5120 4.39/4.24, T5600 4.67/4.70, T6144 4.69/5.44 (192 splits experts there).
const int S = T * 8;
const double cavg = (double)S / 256.0;
// MOE_N240: 240-token chunks while mean + 3.3 sd fits 240 (T6144: 192 + 46 = 238), else 256
// EXACT-N chunks (T6144 band): the megakernel already issues every gate|up item with MMA N =
// round_up(chunk count, 16) and per-item TMEM accumulators, so the only padded / re-streamed work
// left by the chunk bucket is an expert split into a full chunk + a <=16-row tail chunk (re-streams
// the expert's 58 MB of gate|up weights for a 16-column MMA). Above the 192 band the chunk cap is
// now the UMMA maximum N = 256 (was 240), so every expert with <= 256 tokens is ONE item whose
// N is exactly round_up(count, 16).
int nchunk = ck.nch > 0 ? ck.nch : (cavg + 2.0 * std::sqrt(cavg) <= 192.0 ? 192
: 256);
#ifdef MOE_TEST_GU256
nchunk = 256;
#endif
// MOE_N256_W: T6144 band back to 256-token chunks (re-test after E0REL/LFWD; was 240 while mean+3.3sd <= 240)
const int max_chunks = 256 + S / nchunk + 1;
int* iws_p = (int*)scratch_get(3, (size_t)(4 * 22 * max_chunks + 2 * max_chunks + 4 + S + 256 + 2 * S) * 4, hidden_states);
MoeArgs a;
a.T = T; a.nchunk = nchunk; a.lag = 16; a.xpol = 1; a.cpx = ck.cpx; a.ring = ck.ring; a.gu_only = 1; a.inv = inv;
a.dq = ck.cpx ? ck.dq : 0;
a.nsw = ck.nsw;
// MOE_GU_EW4: 4-epilogue-warp gate|up variant for the NCH=256 (T6144) band
#ifndef MOE_GU_EW4
#define MOE_GU_EW4 1
#endif
a.grid_cap = ck.gucap >= 0 ? ck.gucap : (nchunk >= 240 ? MOE_GUCAP_W : MOE_GUCAP_5);
cutpath::moe_set_hsdisc(ck.hsdisc);
cutpath::moe_set_down_sms(ck.dsms >= 0 ? ck.dsms : (nchunk >= 240 ? MOE_DSMS_W : MOE_DSMS_5));
a.ew4 = (MOE_GU_EW4 && (nchunk == 256 || nchunk == 240) && a.cpx == 1 && a.dq && !a.nsw) ? 1 : 0;
a.hidden = (const __nv_bfloat16*)hidden_states.data_ptr();
a.ids = (const long long*)expert_ids.data_ptr();
a.ew = (const __nv_bfloat16*)expert_weights.data_ptr();
a.gate = (const __nv_bfloat16*)gate_proj_weights.data_ptr();
a.up = (const __nv_bfloat16*)up_proj_weights.data_ptr();
a.down = (const __nv_bfloat16*)down_proj_weights.data_ptr();
int* ip = iws_p;
a.item_info = (int4*)ip;
a.done = ip + 4 * 22 * max_chunks;
a.num_items = a.done + 2 * max_chunks;
a.sorted_slot = a.num_items + 4;
a.hs = (__nv_bfloat16*)h;
a.cnt_out = a.sorted_slot + S; // [256] per-expert counts for the arg-fill kernel
// #BO: routing-time {out row, bf16x2 weight} metadata (8-B aligned: all preceding int counts even)
a.meta = (int2*)(a.cnt_out + 256);
a.out = (__nv_bfloat16*)out.data_ptr(); // not written in gate|up-only mode
const int fused = ck.fused >= 0 ? ck.fused : (T >= MOE_FUSED_MIN_T ? 1 : 0);
// fused down epilogue accumulates into out with red.add: zero it on st before the fork, so both
// down batches (side stream + st) are ordered after the memset
// (side stream; batch 0 down follows it on side, batch 1 on st waits the prep-done event)
// fused: out is zeroed INSIDE the gate|up megakernel by its (otherwise idle at start) epilogue
// warps (a.gu_zero): batch-1 down on st is ordered after the megakernel; batch-0 down on side
// waits (moe_batch_wait) for every warp's zero counter bump. (Was a side-stream memset that
// occupied SMs while the persistent megakernel was trying to become resident.)
a.gu_zero = fused ? 1 : 0;
// gu_only out zero-store L2 policy (megakernel epilogue warps): 2 evict_first, 1 evict_normal
#ifndef MOE_ZPOL
#define MOE_ZPOL 2
#endif
#ifndef MOE_ZPOL_5
#define MOE_ZPOL_5 1
#endif
#ifndef MOE_DNOPOL_5
#define MOE_DNOPOL_5 1
#endif
const bool band5 = nchunk < 240;
a.zpol = ck.zpol >= 0 ? ck.zpol : (band5 ? MOE_ZPOL_5 : MOE_ZPOL);
const int dn_opol = (ck.opol != MOE_DNOPOL) ? ck.opol : (band5 ? MOE_DNOPOL_5 : MOE_DNOPOL);
SEV(1);
// the 1-warp wait kernel (side) holds the batch-0 down GEMM until experts [0,128) have their Hs
// rows, so it overlaps the gate|up kernel's tail instead of starting after it
// expert batch split (must match kernel.cu route_in_kernel sp0): T6144 band (NCH>=240) 192, else 160
const int split0 = nchunk >= 240 ? MOE_SPLIT0_W : MOE_SPLIT0;
// MOE_SWZ_W (T6144 band, NCH>=240): AlongM tile-scheduler max swizzle 4 (default knob 1 elsewhere). Overflow
// experts run 2 N tiles that stream the SAME 7 MB of down weight rows; with
// swizzle 1 those tiles are 28 tiles apart, swizzle 4 puts the N tiles of one M tile next to each other so the
// second re-reads the weight rows from L2. Tile order only.
#ifndef MOE_SWZ_W
#define MOE_SWZ_W 4
#endif
#ifndef MOE_SWZ_5
#define MOE_SWZ_5 8
#endif
#ifndef MOE_RAS_5
#define MOE_RAS_5 2
#endif
const bool dflt_order = ck.swz == 1 && ck.raster == 1;
const int dn_swz = (dflt_order && nchunk >= 240) ? MOE_SWZ_W : ((dflt_order && band5) ? MOE_SWZ_5 : ck.swz);
const int dn_ras = (dflt_order && band5) ? MOE_RAS_5 : ck.raster;
#ifndef MOE_MKFILL
#define MOE_MKFILL 1
#endif
// MOE_MKFILL: the gate|up megakernel (CTA 0, epilogue warp 2) writes the down-GEMM argument arrays
// right after routing; the fill kernel then only gates batch 0 (off the first-down-wave critical path)
if (MOE_MKFILL && fused && g_mkfill) a.dnf = cutpath::moe_dn_fill_desc(T, tileN, ws_p, down_proj_weights.data_ptr(), split0, g_mkshadow);
const bool mk_args = a.dnf.on && g_mkshadow == nullptr;
// The whole MIX launch sequence on main stream s0 (+ side streams forked/joined inside):
// gate|up megakernel, side-stream epoch wait + arg fill, 4 CUTLASS down GEMMs (PDL chains).
auto launch_seq = [&](cudaStream_t s0, bool with_mega) {
if (with_mega) moe_gateup_forward(a, s0);
// side: ONE 1-warp kernel = arg fill (spins on this call's routing epoch) + batch-0 gate (Hs rows of
// experts [0,128) + out zeroing done) -> prep-done event.
// DEADLOCK FIX (residency): the 1-warp fill/gate kernel must not reach an SM before the persistent
// gate|up megakernel grid is fully resident, so the side stream first waits ON THE GPU FRONT END
// (stream memory op, no SM resources) until the megakernel has published this call's routing epoch.
static CUdeviceptr ep = (CUdeviceptr)moe_route_epoch_ptr();
static cudaEvent_t* late = nullptr;
if (cuStreamWaitValue32((CUstream)side, ep, (cuuint32_t)a.epoch, CU_STREAM_WAIT_VALUE_GEQ) != CUDA_SUCCESS) {
// stream memory ops unavailable: order the side stream after the whole megakernel (safe, no overlap)
cudaGetLastError();
if (!late) { late = new cudaEvent_t; cudaEventCreateWithFlags(late, cudaEventDisableTiming); }
cudaEventRecord(*late, s0);
cudaStreamWaitEvent(side, *late, 0);
}
int tgt = 0, ztgt = 0;
moe_batch_wait_targets(a, &tgt, &ztgt);
// MOE_MKFILL: args written by the megakernel -> the fill kernel only gates batch 0, on the args epoch
cutpath::moe_fill_down_args(a.cnt_out, mk_args ? moe_route_epoch_ptr() + 1 : moe_route_epoch_ptr(), a.epoch,
down_proj_weights.data_ptr(), T, tileN, ws_p, side, a.num_items, a.done, tgt, ztgt,
split0, mk_args ? 0 : 1);
cutpath::moe_side_prep_done();
// 3) CUTLASS down grouped GEMMs; fused epilogue out[token] += bf16(acc) (16-B L2 red.add)
cutpath::moe_down_reduce(expert_weights.data_ptr(), out.data_ptr(), a.sorted_slot, T, tileN, ws_p, s0, ck.rv,
fused, ck.dcfg, dn_ras, dn_swz, dn_opol, split0, a.epoch);
};
// ---- MIX-path CUDA graph (host-overhead cut): the sequence above is captured ONCE per
// (T, tile config, weight / workspace pointers) on a private capture stream and replayed with a
// single cudaGraphLaunch on st. Per call only the pointers that may change (hidden_states,
// expert_ids, expert_weights, out) are patched into the megakernel node and the 4 down-GEMM nodes
// (cudaGraphExecKernelNodeSetParams; node attributes such as the CUTLASS cluster dims and the
// programmatic (PDL) edges captured from the launch attributes are untouched). The graph uses the
// fixed routing epoch 1: its first node zeroes g_route_epoch, the megakernel publishes 1, the
// side-branch front-end wait and the fill kernel wait for >= 1 (graph replays are stream-ordered,
// so a replay never sees a stale epoch). First call of a key runs directly (warms every CUTLASS
// Gemm object / function attribute); any capture/update failure falls back to direct launches.
struct MixGraph {
int T, tileN, nchunk; const void *g, *u, *d, *ws, *iws; int calls; bool bad;
cudaGraph_t gr; cudaGraphExec_t ex; cudaGraphNode_t mega; cudaKernelNodeParams mkp; void* rec;
const void *hid, *ids, *ew; void* out;
bool useblk; // MOE_PTRBLK: megakernel node reads its per-call pointers from the device block
};
// MOE_PTRBLK: write {hidden, ids, ew, out} into the device pointer block on st with ONE
// cuStreamBatchMemOp (front-end 64-bit write-value ops: values captured at enqueue, stream-ordered
// after prior work and before the graph launch). Skipped when the block already holds them.
auto write_ptr_blk = [&]() -> bool {
static unsigned long long* last = new unsigned long long[4]();
static bool have = false;
const unsigned long long v[4] = {(unsigned long long)a.hidden, (unsigned long long)a.ids,
(unsigned long long)a.ew, (unsigned long long)a.out};
if (have && v[0] == last[0] && v[1] == last[1] && v[2] == last[2] && v[3] == last[3]) return true;
static CUdeviceptr pb = (CUdeviceptr)moe_ptr_blk_ptr();
CUstreamBatchMemOpParams ops[4];
memset(ops, 0, sizeof(ops));
for (int i = 0; i < 4; ++i) {
ops[i].writeValue.operation = CU_STREAM_MEM_OP_WRITE_VALUE_64;
ops[i].writeValue.address = pb + 8 * i;
ops[i].writeValue.value64 = (cuuint64_t)v[i];
ops[i].writeValue.flags = CU_STREAM_WRITE_VALUE_DEFAULT;
}
if (cuStreamBatchMemOp((CUstream)st, 4, ops, 0) != CUDA_SUCCESS) { cudaGetLastError(); have = false; return false; }
for (int i = 0; i < 4; ++i) last[i] = v[i];
have = true;
return true;
};
static std::vector<MixGraph*>* gcache = new std::vector<MixGraph*>();
static cudaStream_t cs = nullptr;
MixGraph* E = nullptr;
if (ck.graph) {
for (auto* e : *gcache)
if (e->T == T && e->tileN == tileN && e->nchunk == nchunk && e->g == a.gate && e->u == a.up && e->d == a.down &&
e->ws == ws_p && e->iws == iws_p) { E = e; break; }
if (!E && gcache->size() < 16) {
E = new MixGraph();
E->T = T; E->tileN = tileN; E->nchunk = nchunk; E->g = a.gate; E->u = a.up; E->d = a.down; E->ws = ws_p;
E->iws = iws_p;
gcache->push_back(E);
}
}
if (E && !E->bad && E->ex) {
bool ok = true;
if (E->useblk) {
XPT(xb0);
ok = write_ptr_blk();
XPT(xb1);
} else if (E->hid != a.hidden || E->ids != a.ids || E->ew != a.ew || E->out != a.out) {
XPT(xt0);
a.epoch = 1;
g_mega_dry = 1;
moe_gateup_forward(a, st); // rebuild the megakernel argument pack only
g_mega_dry = 0;
XPT(xt1);
cudaKernelNodeParams kp = E->mkp;
kp.kernelParams = g_mega_args;
kp.extra = nullptr;
ok = cudaGraphExecKernelNodeSetParams(E->ex, E->mega, &kp) == cudaSuccess;
XPT(xt2);
// MOE_OUTSLOT: the recorded down nodes read out from the device slot (written by the patched megakernel
// node) and never read ew -> no down-node SetParams per call
XPT(xt3);
if (ok) { E->hid = a.hidden; E->ids = a.ids; E->ew = a.ew; E->out = a.out; }
}
XPT(xl0);
const bool lok = ok && cudaGraphLaunch(E->ex, st) == cudaSuccess;
XPT(xl1);
if (lok) return;
cudaGetLastError();
E->bad = true; // permanent direct fallback for this key
#ifdef MOE_GRAPH_STRICT
throw std::runtime_error("graph launch/update failed");
#endif
}
if (E && !E->bad && !E->ex && E->calls >= 1) {
if (!cs) cudaStreamCreateWithFlags(&cs, cudaStreamNonBlocking);
// MOE_PTRBLK: write this call's pointers on st first (also probes stream mem-op support)
E->useblk = write_ptr_blk();
bool ok = cudaStreamBeginCapture(cs, cudaStreamCaptureModeRelaxed) == cudaSuccess;
cudaGraph_t gr = nullptr;
void* rec = nullptr;
if (ok) {
rec = cutpath::moe_down_rec_begin();
cudaMemsetAsync(moe_route_epoch_ptr(), 0, 12, cs); // routing + down-args + b1c1-started epochs
cutpath::moe_fork_join(cs);
a.epoch = 1;
g_mega_nopdl = 1;
a.pblk = E->useblk ? 1 : 0;
moe_gateup_forward(a, cs);
a.pblk = 0;
g_mega_nopdl = 0;
E->mega = moe_last_captured_node(cs);
launch_seq(cs, false); // rest of the sequence (side wait/fill, down GEMMs, joins)
cutpath::moe_down_rec_end();
ok = cudaStreamEndCapture(cs, &gr) == cudaSuccess && gr && E->mega &&
cutpath::moe_down_rec_size(rec) == 4;
}
if (ok) ok = cudaGraphInstantiate(&E->ex, gr, 0) == cudaSuccess;
if (ok) ok = cudaGraphKernelNodeGetParams(E->mega, &E->mkp) == cudaSuccess;
if (ok) {
E->gr = gr; E->rec = rec;
E->hid = a.hidden; E->ids = a.ids; E->ew = a.ew; E->out = a.out;
if (cudaGraphLaunch(E->ex, st) == cudaSuccess) return;
}
cudaGetLastError();
E->bad = true;
E->ex = nullptr;
#ifdef MOE_GRAPH_STRICT
throw std::runtime_error(std::string("graph capture failed: ") + cudaGetErrorString(cudaGetLastError()));
#endif
// nothing of the failed capture executed: fall through to the direct launches
}
if (E) ++E->calls;
a.epoch = moe_next_epoch();
launch_seq(st, true);
SEV(3);
}
}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run, "MoE expert computation (tcgen05 megakernel)"); }
|