Upload folder using huggingface_hub (part 5)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- kernels/L2/007_multimodal_rotary_embedding_attention/src/kernel.hAdded+106
- kernels/L2/007_multimodal_rotary_embedding_attention/src/main.cppAdded+1202
- kernels/L2/008_moe_sparse_routing_and_dispatch/README.mdAdded+11
- kernels/L2/008_moe_sparse_routing_and_dispatch/kernel.jsonAdded+65
- kernels/L2/008_moe_sparse_routing_and_dispatch/src/kernel.cuAdded
- kernels/L2/008_moe_sparse_routing_and_dispatch/src/kernel.hAdded+12
- kernels/L2/008_moe_sparse_routing_and_dispatch/src/main.cppAdded+71
- kernels/L2/008_moe_sparse_routing_and_dispatch/src/probe_cfg.hAdded+2
- kernels/L2/009_decoder_layer_with_residual_connections/README.mdAdded+11
- kernels/L2/009_decoder_layer_with_residual_connections/kernel.jsonAdded+78
- kernels/L2/009_decoder_layer_with_residual_connections/src/fa4.cuAdded+1462
- kernels/L2/009_decoder_layer_with_residual_connections/src/kernel.cuAdded
- kernels/L2/009_decoder_layer_with_residual_connections/src/kernel.hAdded+106
- kernels/L2/009_decoder_layer_with_residual_connections/src/main.cppAdded+292
- kernels/L2/009_decoder_layer_with_residual_connections/src/side_steal.cuhAdded+300
- kernels/L2/009_decoder_layer_with_residual_connections/src/ws_probe.cuAdded+162
- kernels/L2/010_moe_expert_computation_with_weighted_accumulation/README.mdAdded+11
- kernels/L2/010_moe_expert_computation_with_weighted_accumulation/kernel.jsonAdded+83
- kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/fast_path.cuAdded
- kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/g12fused.cuAdded
- kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/graph_launch.hAdded+50
- kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/kernel.cuAdded+997
- kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/kernel.hAdded+4
- kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/main.cppAdded+8
- kernels/L2/011_moe_sparse_routing_and_dispatch_backward/README.mdAdded+11
- kernels/L2/011_moe_sparse_routing_and_dispatch_backward/kernel.jsonAdded+78
- kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/dg_xdyn.cuhAdded+374
- kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/kernel.cuAdded
- kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/main.cppAdded+482
- kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/route_b.cuhAdded+318
- kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/route_c.cuhAdded+778
- kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/route_v.cuhAdded+107
- kernels/L2/012_moe_expert_batched_execution_with_capacity_factor/README.mdAdded+10
- kernels/L2/012_moe_expert_batched_execution_with_capacity_factor/kernel.jsonAdded+61
- kernels/L2/012_moe_expert_batched_execution_with_capacity_factor/src/kernel.cuAdded
- kernels/L2/012_moe_expert_batched_execution_with_capacity_factor/src/kernel.hAdded+12
- kernels/L2/012_moe_expert_batched_execution_with_capacity_factor/src/main.cppAdded+76
- kernels/L2/013_expert_weighted_aggregation_with_shared_expert/README.mdAdded+11
- kernels/L2/013_expert_weighted_aggregation_with_shared_expert/kernel.jsonAdded+164
- kernels/L2/013_expert_weighted_aggregation_with_shared_expert/src/fused_body.cuhAdded
- kernels/L2/013_expert_weighted_aggregation_with_shared_expert/src/kernel.cuAdded+1678
- kernels/L2/013_expert_weighted_aggregation_with_shared_expert/src/main.cppAdded+6
- kernels/L2/013_expert_weighted_aggregation_with_shared_expert/src/route_body.cuhAdded+707
- kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/README.mdAdded+10
- kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/kernel.jsonAdded+84
- kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/src/fastlaunch.hAdded+54
- kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/src/gemm.cuAdded
- kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/src/gemm.hAdded+17
- kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/src/kernel.cuAdded
- kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/src/kernel.hAdded+71
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106#pragma once#include <cuda_runtime.h>#include <cuda.h>#include <stdint.h>// Pre-encoded TMA descriptors for the fused QKV GEMM (A = activations, Q/K/V weights).// Cached on the host by (data_ptr, M) so cuTensorMapEncodeTiled runs only when inputs move.struct GemmMaps { CUtensorMap a, q, k, v, q32, k32, v32; }; // *32: 32-row weight boxes (half-head kernel)void qkv_make_maps(GemmMaps* m, const void* x, const void* qw, const void* kw, const void* vw, int M);void qkv_set_map_a(GemmMaps* m, const void* x, int M);void launch_qkv_rope(const GemmMaps& maps, const void* qb, const void* kb, const void* vb, const void* c, const void* s, void* q, void* k, void* v, int M, int MS, const void* mask, uint8_t* flags, unsigned long long* words, int B, int S, int nqt, int nkt, cudaStream_t st);void launch_attn(const void* q, const void* k, const void* v, const void* mask, const uint8_t* flags, void* o, int B, int S, int nqt, int nkt, cudaStream_t st);// FA4-style tcgen05 attention (used for S >= 512): TMA maps over the q [M,3584], k/v [M,512]// workspaces (cached on the host by q pointer + M).struct AttnMaps { CUtensorMap q, k, v, q32, k64, k3, v3; }; // k3/v3: 3-D K/V maps // q32: 32-row Q boxesvoid attn_make_maps(AttnMaps* m, const void* q, const void* k, const void* v, int M, int hm = 0);// head-major K/V output of the M >= 4096 persistent QKV GEMM (modes 48 / 58); used = layout actually writtenvoid qkv_set_kvhm(int on);int qkv_kvhm_used();void launch_attn_tc(const AttnMaps& maps, const void* mask, const uint8_t* flags, const unsigned long long* words, void* o, int B, int S, int n64, cudaStream_t st);// MS = row stride of one cos/sin section (= full B*S; M may be a batch-chunk's rows)// in-place mRoPE + Q pre-scale on cublasLt-produced q/k (+ mask tile flags), for the Lt QKV variant// single-pass tcgen05 attention for S <= 128 (CTA = one (q head, batch), all keys in one tile)void launch_attn_short(const AttnMaps& maps, const void* mask, const uint8_t* flags, void* o, int B, int S, int n64, cudaStream_t st);// FA4 ping-pong attention (two 128-row Q tiles per CTA, correction warpgroup), S >= 1024 candidate// GQA-packed FA4 attention (item = (q-tile, batch, kv head) x 7 q heads; K/V resident when <= 2 live tiles)void launch_attn_gqa(const AttnMaps& maps, const void* mask, const uint8_t* flags, const unsigned long long* words, void* o, int B, int S, int n64, cudaStream_t st, int sched = 0); // sched: item order, see gqa_build_groups// split-KV LPT persistent attn_tc (S >= 2048 candidate); false if not launchable// FA4 attention with 256-key kv tiles (S >= 1024 candidate, chosen by first-sight timing)// attn_pp structure with 3-stage K / 2-stage V rings (S >= 1024 candidate, first-sight timed)// GQA-packed single-pass attention for S <= 128 (CTA = (kv head, batch), 7 q heads streamed, K/V loaded once)// QKV GEMM || attention overlap (SM partitioning + readiness flags); pct = GEMM share of the cluster capacity// L2 prefetch target (o_proj weight) for the following attention launches (FA2 / short / short_gqa /// tc / gqa); nullptr disables. Each CTA prefetches a 1/grid slice right after griddepcontrol.wait.void attn_set_prefetch(const void* p, unsigned long long bytes, int spread = 0);// 2-warpgroup GQA single-pass attention for S <= 128 (CTA = (kv head, group of HG q heads, batch), 2 heads in flight)void launch_attn_short_gqa2(const AttnMaps& maps, const void* mask, const uint8_t* flags, void* o, int B, int S, int n64, int HG, cudaStream_t st, unsigned int* cnt = nullptr, bool lb = false, bool split = false);// 2-warpgroup GQA attention for 128 < S <= 256 (CTA = (kv head, group of HG q heads, batch), K/V of both key tiles resident)void launch_attn_mid_gqa2(const AttnMaps& maps, const void* mask, const uint8_t* flags, void* o, int B, int S, int n64, int HG, cudaStream_t st, unsigned int* cnt = nullptr, bool spl = false, bool lb = false);// 2 heads in flight, each over 2 column-split warpgroups (S <= 128; 512 threads)void launch_attn_short_gqa4(const AttnMaps& maps, const void* mask, const uint8_t* flags, void* o, int B, int S, int n64, int HG, cudaStream_t st, bool small = false);// FA4 head-pair attention: 2 Q tiles in flight = 2 q heads of one GQA group at the same q tile (K/V shared), S >= 512 candidate// attention || o_proj overlap (S <= 256): custom persistent tcgen05 o_proj (grid CTAs, 1/SM) consuming 128-row// blocks of attn as the (batch, q-tile128) completion counters (bumped by short/mid_gqa2 with cnt) reach 28;// the last CTA resets the counters (and *done) for the next forward.// small-M (M <= 512) custom o_proj: swap-AB (o_weight rows = MMA M128, 128 tokens = MMA N) split-K over// INDEPENDENT CTAs (grid 28 x ceil(M/128) x KS, no clusters); fp32 partials reduced (red.add) into a zeroed// global accumulation buffer `part` (64 KB per output tile), per-tile arrival counters `cnt` (>= 112 u32, zero-initialised, self-resetting): the last// CTA of a tile reduces the KS partials and writes bf16 out. PDL launch (weight TMA before griddepcontrol.wait).
extern int g_qkv_force;// QKV GEMM + inline attention (M <= 256): writes q/k/v and attn; false = not launched// o_weight (3584x3584 bf16) L2 prefetch issued by the persistent QKV GEMM (modes 24 / 29); nullptr = offvoid qkv_set_prefetch(const void* p);void qkv_set_xact(const void* p); // activations for the mode-61 A-operand prefetchvoid qkv_set_oweight(const void* p); // o_weight for the mode-59 classifier-warp prefetchvoid qkv_probe_epi(unsigned long long* cyc, unsigned long long* n, bool reset);extern int g_rec_qkv;extern int g_attn_poly; // 0 = all-MUFU exps, 1 / 2 = 8 / 12 of 32 exp pairs on the FMA pipe (attn_tc, attn_gqa)// 2-CTAs/SM occupancy FA4 attention (non-persistent, one item per CTA), first-sight timed per (M,S)void launch_attn_occ(const AttnMaps& maps, const void* mask, const unsigned long long* words, void* o, int B, int S, cudaStream_t st, int var = 3);
// fp32 -> bf16 (n % 8 == 0, 16-B aligned), used by the split-K cuDNN o_proj branch// sets graph conditional h = 1 iff the classified mask (class words of the latest epoch) is exactly causal
#include <vector>#include <algorithm>#include <cstdio>#include <cmath>struct SPick { int M, S, v; };inline int static_pick(const SPick* t, int n, int M, int S) { int bi = 0; float bd = 1e30f; for (int i = 0; i < n; i++) { const float d = fabsf(log2f((float)M) - log2f((float)t[i].M)) + fabsf(log2f((float)S) - log2f((float)t[i].S)); if (d < bd) { bd = d; bi = i; } } return t[bi].v;}#define SPICK(tab, M, S) static_pick(tab, (int)(sizeof(tab) / sizeof(tab[0])), (M), (S))
// FA2 attention with intra-CTA split-KV (256 threads, 2 halves over alternate live kv tiles), S < 512void launch_attn_s256(const AttnMaps& maps, const void* mask, const uint8_t* flags, void* o, int B, int S, int n64, cudaStream_t st);void launch_attn_split(const void* q, const void* k, const void* v, const void* mask, const uint8_t* flags, void* o, int B, int S, int nqt, int nkt, cudaStream_t st);
// persistent QKV GEMM -> attention fine-grained PDL overlap (rdy counters per 256-row m-block), M >= 4096 gateextern int g_gqa_var;extern int g_tc_var;extern float g_lpt_ch, g_lpt_ci;// big-M (M >= 8192) custom persistent 2-SM o_proj (TMA-store epilogue, 4-CTA weight multicast); false if not launchedbool launch_oproj_big(const void* attn, const void* ow, void* out, int M, cudaStream_t st);float oproj_big_wave_eff(int M);// side-branch o_weight L2 prefetch kernel (M <= 128)void launch_l2_prefetch(const void* p, unsigned long long bytes, int nctas, cudaStream_t st);// CLC-scheduled 2-SM 256x224 o_proj (4-CTA A-multicast clusters, TMA-store epilogue)bool launch_oproj_clc(const void* attn, const void* ow, void* out, int M, cudaStream_t st);float oproj_clc_wave_eff(int M);12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202// Host orchestration, ONE Python->C++ call per forward, minimal host overhead:// * the only torch op per call is torch::empty for the output tensor (contiguity is only// checked; .contiguous() copies happen only for non-contiguous inputs);// * intermediate workspaces (q, k, v, attn, mask-tile flags) are raw cudaMalloc buffers held// by a heap-allocated, never-destroyed cache, grown only when B*S increases;// * the 4 TMA tensormaps are re-encoded only when (x, Wq, Wk, Wv data_ptr, M) change;// * o_proj is a direct cublasLtMatmul with a cached matmul descriptor / layouts / algo per M// and a persistent 32 MB workspace (no at::mm dispatch). The algo is chosen by an// AUTOTUNE at first sight of each M: up to 16 heuristic candidates (incl. split-K /// reduction-scheme variants) are each timed with CUDA events on the current stream and// the fastest is cached (falls back to heuristic #0 while a stream capture is active).// Large batches (B >= 8): the whole pipeline runs over 1/2/4 batch chunks alternating between the// current stream and a second stream (fork/join events), count chosen by first-sight timing per (B,S).// QKV projection variant chosen per M at first sight (timed, cached; custom under stream capture):// (a) fused custom tcgen05 kernel below, or (b) 3 cublasLt bias-epilogue GEMMs into q/k/v + an// in-place mRoPE/pre-scale/mask-flag kernel.#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include <ATen/cuda/EmptyTensor.h>#include <cublasLt.h>#include <ATen/cuda/CUDAGraph.h>#include <c10/cuda/CUDACachingAllocator.h>#include <c10/cuda/CUDAGuard.h>#include <unordered_map>#include <vector>#include <cstdio>#include <string>#include <cstring>#include <cstdlib>#include <cmath>#include <climits>#include "kernel.h"
namespace {struct Workspace { int64_t capM = 0, capFlags = 0; void *q = nullptr, *k = nullptr, *v = nullptr, *attn = nullptr; uint8_t* flags = nullptr; unsigned* rdy = nullptr; // GEMM||attention overlap readiness counters (4 + M/256 u32) // attention||o_proj overlap (S <= 256): per-(b, q-tile128) completion counters + done counter // (self-resetting: zero between forwards), M + 2 u32 unsigned int *cnt = nullptr, *done = nullptr; // small-M custom o_proj (oproj_swap_kernel): fp32 split-K partials (2 #SMs x 64 KB) + per-tile arrival // counters (256 u32, zeroed once, self-resetting); allocated outside capture at the first decision float* opart = nullptr; unsigned int* ocnt = nullptr; unsigned int* tick = nullptr; // attn_g256 ticket counters: 4 chunk slots x 2 u32 (zeroed once, self-resetting) unsigned* fkv = nullptr; // fused QKV+attention readiness counters (self-resetting, 4 + M/256 u32) unsigned long long* words = nullptr; int64_t capWords = 0; // epoch-tagged class words (see kernel.cu) // tensormap cache key const void *kx = nullptr, *kq = nullptr, *kk = nullptr, *kv = nullptr; int kM = -1; GemmMaps maps; // attention tensormap cache (q/k/v workspaces), key = (q ptr, M) const void* aq = nullptr; int aM = -1; // workspace generation: bumped on every q/k/v/attn reallocation (q may reuse an old address while k/v // move, so pointer-equality of q alone cannot detect it); per-chunk tensormap caches key on it unsigned gen = 1, agen = 0; AttnMaps amaps;};struct LtPlan { cublasLtMatmulDesc_t op = nullptr; cublasLtMatrixLayout_t a = nullptr, b = nullptr, c = nullptr; cublasLtMatmulAlgo_t algo; bool has_algo = false; bool tuned = false;};struct LtState { cublasLtHandle_t h = nullptr; void* ws = nullptr; void* ws2 = nullptr; // workspace of the second pipeline stream size_t ws_bytes = 32u << 20; std::unordered_map<int64_t, LtPlan> plans; // keyed by M*8 + gemm id};// Heap-allocated, intentionally never freed (no static CUDA-object destructor at teardown).Workspace& WS() { static Workspace* w = new Workspace(); return *w; }LtState& LT() { static LtState* s = new LtState(); return *s; }
void ensure_ws(int64_t M, int64_t nflags, int64_t nwords) { Workspace& w = WS(); if (M > w.capM) { if (w.q) { cudaFree(w.q); cudaFree(w.k); cudaFree(w.v); cudaFree(w.attn); } cudaMalloc(&w.q, (size_t)M * 3584 * 2); cudaMalloc(&w.k, (size_t)M * 1024 * 2); cudaMalloc(&w.v, (size_t)M * 512 * 2); cudaMalloc(&w.attn, (size_t)M * 3584 * 2); if (w.rdy) cudaFree(w.rdy); cudaMalloc(&w.rdy, (size_t)(4 + (M + 255) / 256) * 4); if (w.cnt) cudaFree(w.cnt); cudaMalloc(&w.cnt, (size_t)(M + 2) * 4); cudaMemset(w.cnt, 0, (size_t)(M + 2) * 4); if (w.fkv) cudaFree(w.fkv); cudaMalloc(&w.fkv, (size_t)(4 + (M + 255) / 256) * 4); cudaMemset(w.fkv, 0, (size_t)(4 + (M + 255) / 256) * 4); cudaDeviceSynchronize(); w.done = w.cnt + M + 1; w.capM = M; w.gen++; } if (nflags > w.capFlags) { if (w.flags) cudaFree(w.flags); cudaMalloc(&w.flags, (size_t)nflags); w.capFlags = nflags; } if (!w.tick) { cudaMalloc(&w.tick, 64); cudaMemset(w.tick, 0, 64); cudaDeviceSynchronize(); } if (nwords > w.capWords) { // zeroed once (epoch tags start at 1) if (w.words) cudaFree(w.words); cudaMalloc(&w.words, (size_t)nwords * 8); cudaMemset(w.words, 0, (size_t)nwords * 8); w.capWords = nwords; }}
// ---- static cublasLt o_proj algo table (config tuples read with cublasLtMatmulAlgoConfigGetAttribute during development)// v[]: ALGO_ID, TILE_ID, SPLITK_NUM, REDUCTION_SCHEME, CTA_SWIZZLING, CUSTOM_OPTION, STAGES_ID, INNER_SHAPE_ID, CLUSTER_SHAPE_IDstruct LtCfg { int v[9]; };const cublasLtMatmulAlgoConfigAttributes_t kCfgAttr[9] = {CUBLASLT_ALGO_CONFIG_ID, CUBLASLT_ALGO_CONFIG_TILE_ID, CUBLASLT_ALGO_CONFIG_SPLITK_NUM, CUBLASLT_ALGO_CONFIG_REDUCTION_SCHEME, CUBLASLT_ALGO_CONFIG_CTA_SWIZZLING, CUBLASLT_ALGO_CONFIG_CUSTOM_OPTION, CUBLASLT_ALGO_CONFIG_STAGES_ID, CUBLASLT_ALGO_CONFIG_INNER_SHAPE_ID, CUBLASLT_ALGO_CONFIG_CLUSTER_SHAPE_ID};const int kCfgSize[9] = {4, 4, 4, 4, 4, 4, 4, 2, 2};const LtCfg kCfgT32 = {{66, 32, 1, 0, 0, 1, 35, 0, 3}};const LtCfg kCfgT29 = {{66, 29, 1, 0, 0, 1, 35, 0, 3}};const LtCfg kCfgT184 = {{66, 184, 1, 0, 0, 2, 35, 0, 5}};const LtCfg kCfgT165 = {{66, 165, 1, 0, 0, 2, 35, 0, 6}};const LtCfg* lt_static_cfg(int M) { if (M >= 768 && M < 1536) return &kCfgT165; // M = 1024 if (M >= 1536 && M < 3072) return &kCfgT184; // M = 2048 if (M >= 6144 && M < 12288) return &kCfgT29; if (M >= 12288 && M < 16896) return &kCfgT29; return nullptr;}bool lt_cfg_match(const cublasLtMatmulAlgo_t& a, const LtCfg& c) { for (int i = 0; i < 9; i++) { size_t sw = 0; int v = 0; if (kCfgSize[i] == 4) { uint32_t u = 0; if (cublasLtMatmulAlgoConfigGetAttribute(&a, kCfgAttr[i], &u, 4, &sw) != CUBLAS_STATUS_SUCCESS) return false; v = (int)u; } else { uint16_t u = 0; if (cublasLtMatmulAlgoConfigGetAttribute(&a, kCfgAttr[i], &u, 2, &sw) != CUBLAS_STATUS_SUCCESS) return false; v = (int)u; } if (v != c.v[i]) return false; } return true;}bool lt_cfg_set(cublasLtMatmulAlgo_t& a, const LtCfg& c) { for (int i = 1; i < 9; i++) { cublasStatus_t r; if (kCfgSize[i] == 4) { uint32_t u = (uint32_t)c.v[i]; r = cublasLtMatmulAlgoConfigSetAttribute(&a, kCfgAttr[i], &u, 4); } else { uint16_t u = (uint16_t)c.v[i]; r = cublasLtMatmulAlgoConfigSetAttribute(&a, kCfgAttr[i], &u, 2); } if (r != CUBLAS_STATUS_SUCCESS) return false; } return true;}// Generic cached + autotuned cublasLt plan for D[M, N] (row-major, ld N) = X[M,3584] @ W[N,3584]^T// (+ bias[N] via the BIAS epilogue when `bias`). In cublasLt column-major terms:// D(N x M, ld N) = op_T(W: 3584 x N, ld 3584) * X(3584 x M, ld 3584).// key = M*8 + id (id 0 = o_proj, 1/2/3 = q/k/v projection).// First sight: up to 16 heuristic algos, each timed (1 warm-up + 3 timed runs with cudaEvents on// the stream, on the live buffers); keep the fastest. D is overwritten by the real call later.LtPlan& get_plan(int64_t key, int M, int N, const void* bias, void* A, void* Bm, void* D, cudaStream_t st) { const int kid = (int)(key % 8) == 6 ? 0 : (int)(key % 8); // key id 6 = multi-batch M=4096 S>=512 (B8S512/B4S1024) o_proj, follows key-0 rules LtState& s = LT(); auto it = s.plans.find(key); if (it != s.plans.end() && it->second.tuned) { if (bias) cublasLtMatmulDescSetAttribute(it->second.op, CUBLASLT_MATMUL_DESC_BIAS_POINTER, &bias, sizeof(bias)); return it->second; } if (!s.h) { cublasLtCreate(&s.h); cudaMalloc(&s.ws, s.ws_bytes); } if (it == s.plans.end()) { LtPlan p; cublasLtMatmulDescCreate(&p.op, CUBLAS_COMPUTE_32F, CUDA_R_32F); cublasOperation_t ta = CUBLAS_OP_T, tb = CUBLAS_OP_N; cublasLtMatmulDescSetAttribute(p.op, CUBLASLT_MATMUL_DESC_TRANSA, &ta, sizeof(ta)); cublasLtMatmulDescSetAttribute(p.op, CUBLASLT_MATMUL_DESC_TRANSB, &tb, sizeof(tb)); if (bias) { cublasLtEpilogue_t ep = CUBLASLT_EPILOGUE_BIAS; cudaDataType_t bt = CUDA_R_16BF; cublasLtMatmulDescSetAttribute(p.op, CUBLASLT_MATMUL_DESC_EPILOGUE, &ep, sizeof(ep)); cublasLtMatmulDescSetAttribute(p.op, CUBLASLT_MATMUL_DESC_BIAS_DATA_TYPE, &bt, sizeof(bt)); } if (kid == 4 && !bias) { int nsm = 148; { int dev = 0; cudaGetDevice(&dev); cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); } if (cublasLtMatmulDescSetAttribute(p.op, CUBLASLT_MATMUL_DESC_SM_COUNT_TARGET, &nsm, sizeof(nsm)) != CUBLAS_STATUS_SUCCESS) cudaGetLastError(); } cublasLtMatrixLayoutCreate(&p.a, CUDA_R_16BF, 3584, N, 3584); cublasLtMatrixLayoutCreate(&p.b, CUDA_R_16BF, 3584, M, 3584); cublasLtMatrixLayoutCreate(&p.c, CUDA_R_16BF, N, M, N); it = s.plans.emplace(key, p).first; } LtPlan& p = it->second; if (bias) cublasLtMatmulDescSetAttribute(p.op, CUBLASLT_MATMUL_DESC_BIAS_POINTER, &bias, sizeof(bias)); cublasLtMatmulPreference_t pref; cublasLtMatmulPreferenceCreate(&pref); cublasLtMatmulPreferenceSetAttribute(pref, CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, &s.ws_bytes, sizeof(s.ws_bytes)); cublasLtMatmulHeuristicResult_t res[16]; int n = 0; if (cublasLtMatmulAlgoGetHeuristic(s.h, p.op, p.a, p.b, p.c, p.c, pref, 16, res, &n) != CUBLAS_STATUS_SUCCESS) n = 0; cublasLtMatmulPreferenceDestroy(pref); // fixed algo = the heuristic's first valid result (no timing); cublasLt default (nullptr algo) if none for (int i = 0; i < n; i++) if (res[i].state == CUBLAS_STATUS_SUCCESS && res[i].workspaceSize <= s.ws_bytes) { p.algo = res[i].algo; p.has_algo = true; break; } if ((kid == 0 || kid == 4 || (kid == 2 && M <= 512)) && !bias && N == 3584 && ((M >= 2048 && M < 16896) || M < 768) && p.has_algo && !lt_static_cfg(M)) { // M >= 16896 (B32S541) keeps heuristic #0 (+ CTA swizzle below) auto eff = [](float w) { if (w <= 0.f) return 0.f; const float c = ceilf(w); return c > 0.f ? w / c : 0.f; }; int i0 = -1; for (int i = 0; i < n; i++) if (res[i].state == CUBLAS_STATUS_SUCCESS && res[i].workspaceSize <= s.ws_bytes) { i0 = i; break; } if (i0 >= 0) { const float e0 = eff(res[i0].wavesCount); int bi = i0; float be = e0 * 1.06f; for (int i = i0 + 1; i < n; i++) if (res[i].state == CUBLAS_STATUS_SUCCESS && res[i].workspaceSize <= s.ws_bytes && res[i].wavesCount >= 1.f && eff(res[i].wavesCount) > be) { be = eff(res[i].wavesCount); bi = i; } p.algo = res[bi].algo; } } // static per-M-bucket o_proj algo override (fixed config tuples chosen offline; matched against the heuristic list, // else reconstructed and validated with AlgoCheck; else heuristic #0 is kept). o_proj only (id 0, no bias, N 3584). const LtCfg* want = ((kid == 0 || kid == 4 || kid == 2) && !bias && N == 3584) ? lt_static_cfg(M) : nullptr; // multi-batch M = 4096 o_proj (key id 0: B8S512 / B32S128) -> static 128x160 tile (tile id 29, 2x1 cluster): // GEMM 3584 x 4096 -> 28 x ceil(4096/160) = 728 tiles = 4.92 waves on 148 SMs instead of // 448 tiles of 128x256 = 3.03 waves -> 4 waves. Matched against the heuristic list or AlgoCheck-validated, // else the wave-aware heuristic pick stays. Single-sequence M = 4096 (key id 4, B1S4096) unchanged. bool m4k0 = kid == 0 && !bias && N == 3584 && M >= 3072 && M < 6144; if (m4k0) want = &kCfgT29; if (want && p.has_algo) { bool found = false; for (int i = 0; i < n && !found; i++) if (res[i].state == CUBLAS_STATUS_SUCCESS && res[i].workspaceSize <= s.ws_bytes && lt_cfg_match(res[i].algo, *want)) { p.algo = res[i].algo; found = true; } bool okw = found; if (!found) { cublasLtMatmulAlgo_t al; if (cublasLtMatmulAlgoInit(s.h, CUBLAS_COMPUTE_32F, CUDA_R_32F, CUDA_R_16BF, CUDA_R_16BF, CUDA_R_16BF, CUDA_R_16BF, want->v[0], &al) == CUBLAS_STATUS_SUCCESS && lt_cfg_set(al, *want)) { cublasLtMatmulHeuristicResult_t chk; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes) { p.algo = al; okw = true; } } } if (!okw) m4k0 = false; // tile-29 pick unavailable: seed path (4x1/2x1 cluster force below) } if ((kid == 0 || kid == 2) && !bias && N == 3584 && ((M >= 768 && M < 1536) || (M > 512 && M < 768) || (kid == 2 && M > 128 && M <= 256)) && p.has_algo) { cublasLtMatmulHeuristicResult_t chk; float wcur = 0.f; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &p.algo, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS) wcur = chk.wavesCount; size_t sz = 0; std::vector<uint32_t> tiles, stg; if (wcur > 0.f && cublasLtMatmulAlgoCapGetAttribute(&p.algo, CUBLASLT_ALGO_CAP_TILE_IDS, nullptr, 0, &sz) == CUBLAS_STATUS_SUCCESS && sz >= 4) { tiles.resize(sz / 4); cublasLtMatmulAlgoCapGetAttribute(&p.algo, CUBLASLT_ALGO_CAP_TILE_IDS, tiles.data(), sz, &sz); } sz = 0; if (!tiles.empty() && cublasLtMatmulAlgoCapGetAttribute(&p.algo, CUBLASLT_ALGO_CAP_STAGES_IDS, nullptr, 0, &sz) == CUBLAS_STATUS_SUCCESS && sz >= 4) { stg.resize(sz / 4); cublasLtMatmulAlgoCapGetAttribute(&p.algo, CUBLASLT_ALGO_CAP_STAGES_IDS, stg.data(), sz, &sz); } if (stg.empty()) { uint32_t s0 = 0; size_t w_ = 0; cublasLtMatmulAlgoConfigGetAttribute(&p.algo, CUBLASLT_ALGO_CONFIG_STAGES_ID, &s0, 4, &w_); stg.push_back(s0); } float best = wcur * 1.10f; bool fb = false; cublasLtMatmulAlgo_t ba = p.algo; for (uint32_t t : tiles) { if (t == 0) continue; for (uint32_t sg : stg) { cublasLtMatmulAlgo_t al = p.algo; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_TILE_ID, &t, 4) != CUBLAS_STATUS_SUCCESS) continue; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_STAGES_ID, &sg, 4) != CUBLAS_STATUS_SUCCESS) continue; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al, &chk) != CUBLAS_STATUS_SUCCESS || chk.state != CUBLAS_STATUS_SUCCESS || chk.workspaceSize > s.ws_bytes) continue; const float w = chk.wavesCount; if (w <= 1.0f && w > best) { best = w; ba = al; fb = true; break; } // first valid stage of this tile } } if (fb) p.algo = ba; cudaGetLastError(); } // M = 4096 o_proj bucket (no static cfg, wave-aware heuristic pick): keep the picked algo / tile but force a // 4x1 CTA cluster (CLUSTER_SHAPE_ID 3) so each weight (Wo) k-tile is TMA-multicast to 4 CTAs (L2->SM weight traffic // / 4); kept only if AlgoCheck validates it, else the heuristic algo is unchanged. Static, no timing. if ((kid == 0 || kid == 4) && !bias && N == 3584 && M >= 3072 && M < 6144 && p.has_algo && !lt_static_cfg(M) && !m4k0) { cublasLtMatmulAlgo_t al = p.algo; uint16_t cl = 3; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_CLUSTER_SHAPE_ID, &cl, 2) == CUBLAS_STATUS_SUCCESS) { cublasLtMatmulHeuristicResult_t chk; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes) p.algo = al; } } // M = 8192 o_proj bucket (key id 0, 6144 <= M < 12288: B32S256): static 2-SM 256x224 tile (256 out features x // 224 tokens, 2x1 cluster, CLUSTER_SHAPE_ID 3) instead of tile-29 (128x160 4x1): 14 x ceil(8192/224) = 518 pair tiles = // 1036 CTAs = exactly 7 full waves on 148 SMs, with 2-SM MMAs (half the per-SM B-operand smem traffic). TILE_ID found // deterministically from AlgoCheck wavesCount (token-dim tile count == ceil(n/224): w(M) == w(224*ceil(M/224)) < // w(+1), absolute waves == 2 x pairs / #SMs). Kept only if AlgoCheck validates it, else the tile-29 pick stays. No timing. if (kid == 0 && !bias && N == 3584 && M >= 6144 && M < 12288 && p.has_algo) { auto waves_of = [&](cublasLtMatmulAlgo_t& al, int ncols, float& w) -> bool { cublasLtMatrixLayout_t lb = nullptr, lc = nullptr; bool ok = false; if (cublasLtMatrixLayoutCreate(&lb, CUDA_R_16BF, 3584, ncols, 3584) == CUBLAS_STATUS_SUCCESS && cublasLtMatrixLayoutCreate(&lc, CUDA_R_16BF, N, ncols, N) == CUBLAS_STATUS_SUCCESS) { cublasLtMatmulHeuristicResult_t chk; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, lb, lc, lc, &al, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes) { w = chk.wavesCount; ok = w > 0.f; } } if (lb) cublasLtMatrixLayoutDestroy(lb); if (lc) cublasLtMatrixLayoutDestroy(lc); return ok; }; size_t sz = 0; std::vector<uint32_t> tiles, stg; if (cublasLtMatmulAlgoCapGetAttribute(&p.algo, CUBLASLT_ALGO_CAP_TILE_IDS, nullptr, 0, &sz) == CUBLAS_STATUS_SUCCESS && sz >= 4) { tiles.resize(sz / 4); cublasLtMatmulAlgoCapGetAttribute(&p.algo, CUBLASLT_ALGO_CAP_TILE_IDS, tiles.data(), sz, &sz); } { uint32_t s0 = 0; size_t w_ = 0; cublasLtMatmulAlgoConfigGetAttribute(&p.algo, CUBLASLT_ALGO_CONFIG_STAGES_ID, &s0, 4, &w_); stg.push_back(s0); } sz = 0; if (cublasLtMatmulAlgoCapGetAttribute(&p.algo, CUBLASLT_ALGO_CAP_STAGES_IDS, nullptr, 0, &sz) == CUBLAS_STATUS_SUCCESS && sz >= 4) { std::vector<uint32_t> t2(sz / 4); cublasLtMatmulAlgoCapGetAttribute(&p.algo, CUBLASLT_ALGO_CAP_STAGES_IDS, t2.data(), sz, &sz); for (uint32_t v : t2) if (v != stg[0]) stg.push_back(v); } int nsm = 148; { int dev = 0; cudaGetDevice(&dev); cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); } const int ntok = (M + 223) / 224, npair = 14 * ntok; const float wexp = 2.f * (float)npair / (float)nsm; bool fb = false; for (uint32_t t : tiles) { if (t == 0 || fb) continue; for (uint32_t sg : stg) { cublasLtMatmulAlgo_t al = p.algo; uint16_t cl = 3; uint32_t sw = 0; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_TILE_ID, &t, 4) != CUBLAS_STATUS_SUCCESS) continue; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_STAGES_ID, &sg, 4) != CUBLAS_STATUS_SUCCESS) continue; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_CLUSTER_SHAPE_ID, &cl, 2) != CUBLAS_STATUS_SUCCESS) continue; cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_CTA_SWIZZLING, &sw, 4); float w0 = 0.f, w1 = 0.f, w2 = 0.f; if (!waves_of(al, M, w0) || !waves_of(al, ntok * 224, w1) || !waves_of(al, ntok * 224 + 1, w2)) continue; if (fabsf(w1 - w0) <= 1e-3f * w0 && w2 > w0 * 1.01f && fabsf(w0 - wexp) <= 0.01f * wexp) { // final validation on the real problem layouts cublasLtMatmulHeuristicResult_t chk; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al, &chk) != CUBLAS_STATUS_SUCCESS || chk.state != CUBLAS_STATUS_SUCCESS || chk.workspaceSize > s.ws_bytes) continue; p.algo = al; fb = true; fprintf(stderr, "[mrope oproj M8192] 256x224 2x1 tile id %u stages %u waves %.3f\n", t, sg, w0); break; } } } if (!fb) fprintf(stderr, "[mrope oproj M8192] no 256x224 tile found, keeping tile-29 pick\n"); cudaGetLastError(); } if (((kid == 0 && M > 128 && M <= 256) || kid == 2) && !bias && N == 3584 && p.has_algo) { cublasLtMatmulAlgo_t al = p.algo; uint16_t cl = 5; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_CLUSTER_SHAPE_ID, &cl, 2) == CUBLAS_STATUS_SUCCESS) { cublasLtMatmulHeuristicResult_t chk; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes) p.algo = al; } cudaGetLastError(); } // B1S256 o_proj (key id 2, 128 < M <= 256, single wave): on top of the 1x2 token-dim cluster pick, try cublasLt // split-K 2 (fp32 compute-type reduction); kept only if AlgoCheck validates it and it stays single-wave (wavesCount <= 1) // while filling more SMs than the current pick. Deterministic, no timing. if (kid == 2 && !bias && N == 3584 && M > 128 && M <= 256 && p.has_algo) { cublasLtMatmulHeuristicResult_t chk; float w1 = 0.f; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &p.algo, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS) w1 = chk.wavesCount; float bw = w1 * 1.10f; int bsk = 0; cublasLtMatmulAlgo_t ba = p.algo; for (uint32_t sk = 2; w1 > 0.f && sk <= 8; sk++) { cublasLtMatmulAlgo_t al = p.algo; uint32_t rs = CUBLASLT_REDUCTION_SCHEME_COMPUTE_TYPE; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_SPLITK_NUM, &sk, 4) == CUBLAS_STATUS_SUCCESS && cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_REDUCTION_SCHEME, &rs, 4) == CUBLAS_STATUS_SUCCESS && cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes) { const float w2 = chk.wavesCount; fprintf(stderr, "[mrope oproj M%d] waves %.3f -> splitK%u %.3f\n", M, w1, sk, w2); if (w2 <= 1.0f + 1e-4f && w2 > bw) { bw = w2; bsk = (int)sk; ba = al; } } cudaGetLastError(); } if (bsk) { p.algo = ba; fprintf(stderr, "[mrope oproj M%d] take splitK%d (waves %.3f)\n", M, bsk, bw); } cudaGetLastError(); } if (kid == 0 && !bias && N == 3584 && M >= 768 && M < 1536 && p.has_algo) { cublasLtMatmulHeuristicResult_t chk; float w1 = 0.f; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &p.algo, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS) w1 = chk.wavesCount; cublasLtMatmulAlgo_t al = p.algo; uint32_t sk = 2, rs = CUBLASLT_REDUCTION_SCHEME_COMPUTE_TYPE; if (w1 > 0.f && cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_SPLITK_NUM, &sk, 4) == CUBLAS_STATUS_SUCCESS && cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_REDUCTION_SCHEME, &rs, 4) == CUBLAS_STATUS_SUCCESS && cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes) { const float w2 = chk.wavesCount; const bool take = w2 <= 1.0f + 1e-4f && w2 > w1 * 1.10f; fprintf(stderr, "[mrope oproj M%d] waves %.3f -> splitK2 %.3f : %s\n", M, w1, w2, take ? "splitK2" : "keep"); if (take) p.algo = al; } cudaGetLastError(); } if (kid == 0 && !bias && N == 3584 && M >= 1536 && M < 3072 && p.has_algo) { auto eff = [](float w) { if (w <= 0.f) return 0.f; const float c = ceilf(w); return c > 0.f ? w / c : 0.f; }; cublasLtMatmulHeuristicResult_t chk; uint32_t sk1 = 1; cublasLtMatmulAlgo_t base = p.algo; cublasLtMatmulAlgoConfigSetAttribute(&base, CUBLASLT_ALGO_CONFIG_SPLITK_NUM, &sk1, 4); float w1 = 0.f; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &base, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes) { w1 = chk.wavesCount; p.algo = base; } size_t sz = 0; std::vector<uint32_t> tiles, stg; if (cublasLtMatmulAlgoCapGetAttribute(&base, CUBLASLT_ALGO_CAP_TILE_IDS, nullptr, 0, &sz) == CUBLAS_STATUS_SUCCESS && sz >= 4) { tiles.resize(sz / 4); cublasLtMatmulAlgoCapGetAttribute(&base, CUBLASLT_ALGO_CAP_TILE_IDS, tiles.data(), sz, &sz); } { uint32_t s0 = 0; size_t w_ = 0; cublasLtMatmulAlgoConfigGetAttribute(&base, CUBLASLT_ALGO_CONFIG_STAGES_ID, &s0, 4, &w_); stg.push_back(s0); } sz = 0; if (cublasLtMatmulAlgoCapGetAttribute(&base, CUBLASLT_ALGO_CAP_STAGES_IDS, nullptr, 0, &sz) == CUBLAS_STATUS_SUCCESS && sz >= 4) { std::vector<uint32_t> t2(sz / 4); cublasLtMatmulAlgoCapGetAttribute(&base, CUBLASLT_ALGO_CAP_STAGES_IDS, t2.data(), sz, &sz); for (uint32_t v : t2) if (v != stg[0]) stg.push_back(v); } uint16_t cl0 = 0; { size_t w_ = 0; cublasLtMatmulAlgoConfigGetAttribute(&base, CUBLASLT_ALGO_CONFIG_CLUSTER_SHAPE_ID, &cl0, 2, &w_); } const uint16_t cls[3] = {cl0, 2, 3}; float be = w1 > 0.f ? eff(w1) + 0.02f : 0.f, bw = 0.f; bool fb = false; cublasLtMatmulAlgo_t ba = base; for (uint32_t t : tiles) { if (t == 0) continue; for (uint16_t cl : cls) { for (uint32_t sg : stg) { cublasLtMatmulAlgo_t al = base; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_TILE_ID, &t, 4) != CUBLAS_STATUS_SUCCESS) continue; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_STAGES_ID, &sg, 4) != CUBLAS_STATUS_SUCCESS) continue; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_CLUSTER_SHAPE_ID, &cl, 2) != CUBLAS_STATUS_SUCCESS) continue; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al, &chk) != CUBLAS_STATUS_SUCCESS || chk.state != CUBLAS_STATUS_SUCCESS || chk.workspaceSize > s.ws_bytes) continue; const float w = chk.wavesCount; if (w < 1.0f || w > 4.0f) continue; // keep reasonably large tiles (>= 1 full wave) const float e = eff(w); if (e > be + 1e-4f || (fb && fabsf(e - be) <= 1e-4f && ceilf(w) < ceilf(bw))) { be = e; bw = w; ba = al; fb = true; } break; // first valid stage of this (tile, cluster) } } } fprintf(stderr, "[mrope oproj M%d] splitK1 waves %.3f -> best %.3f : %s\n", M, w1, bw, fb ? "retile" : "keep"); if (fb) p.algo = ba; cudaGetLastError(); } // key-id-2 o_proj plans of the M=512 / M=1024 buckets (B4S128, B1S512, B8S128: 384 < M < 1536): CTA_SWIZZLING 1 // on the picked algo (L2-aware raster of the Wo n-bands across the token-dim 1x2 clusters); AlgoCheck-validated, else // unchanged. Plan attribute only, bit-identical math. if (((kid == 2 && M > 384 && M < 1536) || (kid == 0 && M > 512 && M < 768)) && !bias && N == 3584 && p.has_algo) { // + B1S613 key 0 cublasLtMatmulAlgo_t al2 = p.algo; uint32_t sw = 1; if (cublasLtMatmulAlgoConfigSetAttribute(&al2, CUBLASLT_ALGO_CONFIG_CTA_SWIZZLING, &sw, 4) == CUBLAS_STATUS_SUCCESS) { cublasLtMatmulHeuristicResult_t chk; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al2, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes) { p.algo = al2; fprintf(stderr, "[mrope oproj M%d key2] CTA swizzle 1\n", M); } } cudaGetLastError(); } // B1S128 o_proj (key 0, M <= 128, single wave): if the picked algo runs without a CTA cluster (cluster id 0 auto // or 2 = 1x1), force a 2x1 cluster along the FEATURE dim (CLUSTER_SHAPE_ID 3) so the 2 Wo-tile CTAs sharing the 128-token // attention tile receive each of its k-tiles by TMA multicast (attention-operand L2->SM ingress / 2). AlgoCheck-validated, // single wave kept (wavesCount <= 1), else unchanged. Static plan attribute, no timing; same math. if (kid == 0 && !bias && N == 3584 && M <= 128 && p.has_algo) { uint16_t cl0 = 0; size_t w_ = 0; cublasLtMatmulAlgoConfigGetAttribute(&p.algo, CUBLASLT_ALGO_CONFIG_CLUSTER_SHAPE_ID, &cl0, 2, &w_); if (cl0 == 0 || cl0 == 2) { cublasLtMatmulAlgo_t al = p.algo; uint16_t cl = 3; cublasLtMatmulHeuristicResult_t chk; if (cublasLtMatmulAlgoConfigSetAttribute(&al, CUBLASLT_ALGO_CONFIG_CLUSTER_SHAPE_ID, &cl, 2) == CUBLAS_STATUS_SUCCESS && cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes && chk.wavesCount <= 1.0f + 1e-4f) { p.algo = al; fprintf(stderr, "[mrope oproj M%d] cluster %u -> 2x1 (waves %.3f)\n", M, (unsigned)cl0, chk.wavesCount); } else fprintf(stderr, "[mrope oproj M%d] cluster %u kept\n", M, (unsigned)cl0); } else fprintf(stderr, "[mrope oproj M%d] cluster id %u already set\n", M, (unsigned)cl0); cudaGetLastError(); } // L2-aware rasterization for the large-M o_proj (M >= 12K, mirrors the QKV n-fastest order): enable // cublasLt CTA swizzling (CTA_SWIZZLING = 1) on the chosen static algo; kept only if AlgoCheck validates it. // key id 4 = single-sequence M = 4096 o_proj (B1S4096): CTA swizzle 1 on top of the 4x1-cluster pick, so the // L2-resident attention output (just written) is reused across a weight n-band; other M=4096 shapes unchanged. if (((kid == 0 && M >= 6144) || (kid == 4 && M >= 3072 && M < 6144)) && !bias && N == 3584 && p.has_algo) { // also the M=8192 bucket cublasLtMatmulAlgo_t al = p.algo; // B32S256-only (key id 0, 6144 <= M < 12288: 256x224 2x1 pick) tries CTA_SWIZZLING 2 first (wider L2-aware // raster over the attention-output rows), falls back to 1; AlgoCheck-validated, else unchanged. Bit-identical math. const bool b32s256 = kid == 0 && M >= 6144 && M < 12288; for (uint32_t sw : {b32s256 ? 2u : 1u, 1u}) { cublasLtMatmulAlgo_t al2 = al; if (cublasLtMatmulAlgoConfigSetAttribute(&al2, CUBLASLT_ALGO_CONFIG_CTA_SWIZZLING, &sw, 4) != CUBLAS_STATUS_SUCCESS) continue; cublasLtMatmulHeuristicResult_t chk; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al2, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes) { p.algo = al2; if (b32s256) fprintf(stderr, "[mrope oproj M%d] CTA swizzle %u\n", M, sw); break; } } cudaGetLastError(); } cudaGetLastError(); // key id 6 (multi-batch M = 4096, S >= 512: B8S512 / B4S1024 only): CTA_SWIZZLING 1 on the picked tile-29 128x160 // 2x1-cluster algo (L2-aware raster over the L2-resident attention output); AlgoCheck-validated, else unchanged. Bit-identical. if (key % 8 == 6 && !bias && N == 3584 && M >= 3072 && M < 6144 && p.has_algo) { cublasLtMatmulAlgo_t al2 = p.algo; uint32_t sw = 1; if (cublasLtMatmulAlgoConfigSetAttribute(&al2, CUBLASLT_ALGO_CONFIG_CTA_SWIZZLING, &sw, 4) == CUBLAS_STATUS_SUCCESS) { cublasLtMatmulHeuristicResult_t chk; if (cublasLtMatmulAlgoCheck(s.h, p.op, p.a, p.b, p.c, p.c, &al2, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.workspaceSize <= s.ws_bytes) { p.algo = al2; fprintf(stderr, "[mrope oproj M%d key6] CTA swizzle 1\n", M); } } cudaGetLastError(); } p.tuned = true; return p;}// wsi selects the cublasLt workspace: 0 = main stream, 1 = second pipeline stream (split-K// workspaces must not be shared by concurrently running GEMMs)void lt_run(LtPlan& p, const void* W, const void* X, void* D, cudaStream_t st, int wsi = 0) { const float alpha = 1.f, beta = 0.f; LtState& s = LT(); if (wsi && !s.ws2) cudaMalloc(&s.ws2, s.ws_bytes); cublasLtMatmul(s.h, p.op, &alpha, W, p.a, X, p.b, &beta, D, p.c, D, p.c, p.has_algo ? &p.algo : nullptr, wsi ? s.ws2 : s.ws, s.ws_bytes, st);}// QKV variant per M: 0 = fused custom tcgen05 kernel, 1 = cublasLt (bias epilogue) + in-place mRoPE.// Heap-allocated, never freed.// per-M o_proj choice (0 = cublasLt, c >= 1: launch_oproj_ds var c-1), set by the oproj-ds gate; also read by the// cuDNN-causal TRUE body. Heap-allocated, never freed.std::unordered_map<int, int>& OPDS_CHOICE() { static auto* m = new std::unordered_map<int, int>(); return *m; }std::unordered_map<int, int>& QKV_CHOICE() { static auto* m = new std::unordered_map<int, int>(); return *m; }std::unordered_map<int, std::pair<float, float>>& QKV_TIMES() { static auto* m = new std::unordered_map<int, std::pair<float, float>>(); return *m; }static inline bool capturing(cudaStream_t st) { cudaStreamCaptureStatus cs = cudaStreamCaptureStatusNone; cudaStreamIsCapturing(st, &cs); return cs != cudaStreamCaptureStatusNone;}// Short-S (S <= 128) attention variant c (see the dispatch `la` below): 0 FA2, 1 single-pass tc,// 7 short_gqa4 HG=1, 30 short_gqa2 LB HG=7.int attn_short_choice(int M, int S) { static const SPick t[] = {{128, 128, 7} /* B1S128 -> short_gqa4 CS4 (28 CTAs, 4 col-split WGs)*/, {512, 128, 7}, {1024, 128, 6}, {4096, 128, 30} /* B32S128 -> attn_short_gqa2 HG7 unsplit: 128 (b,kvh) items, 7 heads x m128 MMAs share one K/V load; was B32S128 short_gqa2 HG7 + split groups (148 CTAs)*/}; return SPICK(t, M, S);}// 128 < S <= 256 variant c (see `lm2`): 2 FA4 attn_tc_epw (S == 256), 0 existing path (FA4 tc / gqa or FA2), 1 attn_mid_gqa2 HG=1, 15 FA2 split-KV.int attn_mid_choice(int M, int S) { static const SPick t[] = {{256, 256, 16} /* B1S256 tcgen05 single-pass*/, {1024, 256, 2}, {8192, 256, 0}, {16384, 256, 0}}; return SPICK(t, M, S);}// Mid-S FA4 choice: 0 attn_tc, 9 attn_gqa with the host LPT item table (sched 4).int attn_gqa_choice(int M, int S) { static const SPick t[] = {{16384, 256, 0}, {8192, 256, 0}, {4096, 1024, 0}, {2048, 1024, 0}, {1024, 1024, 0}, {512, 512, 0}, {613, 613, 0}, {4096, 512, 0}, {17312, 541, 9}}; return SPICK(t, M, S);}// STATIC 2-CTAs/SM occupancy attention override (0 = normal dispatch), hoisted so the host can// decide the K/V layout before the QKV launchint attn_occ_choice(int M, int S) { static const SPick ot[] = {{512, 128, 0}, {16384, 256, 0}, {4096, 1024, 0}, {4096, 128, 0}, {17312, 541, 0}, {2048, 1024, 0}, {1024, 1024, 0}, {8192, 256, 0}, {512, 512, 0}, {1024, 256, 0}, {128, 128, 0}, {613, 613, 0}, {4096, 4096, 0}, {4096, 512, 0}, {1024, 128, 0}, {256, 256, 0}}; return SPICK(ot, M, S);}} // namespace
static inline torch::Tensor cont(const torch::Tensor& t) { return t.is_contiguous() ? t : t.contiguous(); }
namespace {// Second stream + fork/join events for the batch-chunk pipeline (heap, never destroyed).struct Pipe { cudaStream_t s2 = nullptr; cudaEvent_t fork = nullptr, join = nullptr; };Pipe& PIPE() { static Pipe* p = nullptr; if (!p) { p = new Pipe(); cudaStreamCreateWithFlags(&p->s2, cudaStreamNonBlocking); cudaEventCreateWithFlags(&p->fork, cudaEventDisableTiming); cudaEventCreateWithFlags(&p->join, cudaEventDisableTiming); } return *p;}// high-priority stream + fork/join events of the QKV||attention overlap mode (heap, never destroyed)struct OvlStreams { cudaStream_t s = nullptr; cudaEvent_t fork = nullptr, join = nullptr; };OvlStreams& OVLS() { static OvlStreams* p = nullptr; if (!p) { p = new OvlStreams(); int lo = 0, hi = 0; cudaDeviceGetStreamPriorityRange(&lo, &hi); cudaStreamCreateWithPriority(&p->s, cudaStreamNonBlocking, hi); cudaEventCreateWithFlags(&p->fork, cudaEventDisableTiming); cudaEventCreateWithFlags(&p->join, cudaEventDisableTiming); } return *p;}// tensormap caches per batch chunk (A map keyed by (x slice ptr, rows); attention maps keyed by// (q slice ptr, rows)). Plain POD values, heap-allocated maps.std::unordered_map<uint64_t, CUtensorMap>& AMAPC() { static auto* m = new std::unordered_map<uint64_t, CUtensorMap>(); return *m; }std::unordered_map<uint64_t, AttnMaps>& ATTMC() { static auto* m = new std::unordered_map<uint64_t, AttnMaps>(); return *m; }inline uint64_t pkey(const void* p, int M) { return ((uint64_t)(uintptr_t)p << 8) ^ ((uint64_t)M * 0x9E3779B97F4A7C15ull); }} // namespace
#ifndef OPROBE#define OPROBE 0#endifnamespace {bool g_cap_pdl = false; // set while capturing the forward graphint g_cdn_fail = 0; // set when building the cuDNN conditional node failed (graph discarded)int g_cdn_try = 0; // 1 = capture the forward with the cuDNN-causal IF/ELSE conditional (S >= 2048)int g_fz_force = -1; // probe hook: force the fused QKV+attention choiceint g_ocust = 0; // 1 = capture the forward with the custom swap-AB split-K o_proj (M <= 512)int g_cap_edge = 0; // 1 = programmatic edge installed in the current capture// env/probe-gated per-stage timing (g_stage = 1: eager forward records QKV / attention / o_proj boundaries of chunk 0// on cudaEvents g_sev[0..3]; off by default -> no dispatch change). g_rec: last chosen variants (probe report).int g_stage = 0;cudaEvent_t g_sev[4];int g_rec[6] = {0, 0, 0, 0, 0, 0};int g_rec_nch = 0;void pdl_edge_to_next(cudaStream_t s, bool lc = false) { cudaStreamCaptureStatus cst; unsigned long long id = 0; cudaGraph_t g = nullptr; const cudaGraphNode_t* deps = nullptr; size_t nd = 0;#if CUDART_VERSION >= 13000 const cudaGraphEdgeData* ed = nullptr; if (cudaStreamGetCaptureInfo(s, &cst, &id, &g, &deps, &ed, &nd) != cudaSuccess) { cudaGetLastError(); return; }#else const cudaGraphEdgeData* ed = nullptr; if (cudaStreamGetCaptureInfo_v3(s, &cst, &id, &g, &deps, &ed, &nd) != cudaSuccess) { cudaGetLastError(); return; }#endif if (cst != cudaStreamCaptureStatusActive || nd != 1) return; cudaGraphNodeType ty; if (cudaGraphNodeGetType(deps[0], &ty) != cudaSuccess || ty != cudaGraphNodeTypeKernel) { cudaGetLastError(); return; } cudaGraphNode_t n0 = deps[0]; cudaGraphEdgeData e = {}; // lc: LAUNCH-COMPLETION port (fires once every upstream CTA has begun execution) -- used only for the QKV -> // attention edge: every attention kernel reads q/k/v/flags strictly after griddepcontrol.wait (= full QKV completion + // memory flush), so the attention grid may be launched / run its prologue (barrier init, TMEM alloc, tensormap and // o_weight prefetch) while the QKV GEMM is still running, also for QKV modes that trigger only at their end. e.from_port = lc ? cudaGraphKernelNodePortLaunchCompletion : cudaGraphKernelNodePortProgrammatic; e.to_port = 0; e.type = cudaGraphDependencyTypeProgrammatic;#if CUDART_VERSION >= 13000 if (cudaStreamUpdateCaptureDependencies(s, &n0, &e, 1, cudaStreamSetCaptureDependencies) != cudaSuccess) { cudaGetLastError(); return; } if (lc) return;#else if (cudaStreamUpdateCaptureDependencies_v2(s, &n0, &e, 1, cudaStreamSetCaptureDependencies) != cudaSuccess) { cudaGetLastError(); return; }#endif g_cap_edge = 1;}float* split_ws(size_t n) { static float* p = nullptr; static size_t cap = 0; if (n > cap) { float* q = nullptr; if (cudaMalloc(&q, n * 4) != cudaSuccess) { cudaGetLastError(); return nullptr; } p = q; cap = n; } return p;}// D_f32[M, 3584] (+)= O_g[M, 896] (token stride ldb) x Wo[:, 896 g : 896 g + 896]^T (cublasLt, fp32 C/D)struct SplitPlan { cublasLtMatmulDesc_t op = nullptr; cublasLtMatrixLayout_t a = nullptr, b = nullptr, c = nullptr; cublasLtMatmulAlgo_t algo; bool has = false; };SplitPlan* split_plan(int M, int ldb) { static auto* mp = new std::unordered_map<int64_t, SplitPlan>(); const int64_t key = (int64_t)M * 65536 + ldb; auto it = mp->find(key); if (it != mp->end()) return &it->second; LtState& s = LT(); if (!s.h) { cublasLtCreate(&s.h); cudaMalloc(&s.ws, s.ws_bytes); } SplitPlan p; cublasLtMatmulDescCreate(&p.op, CUBLAS_COMPUTE_32F, CUDA_R_32F); cublasOperation_t ta = CUBLAS_OP_T, tb = CUBLAS_OP_N; cublasLtMatmulDescSetAttribute(p.op, CUBLASLT_MATMUL_DESC_TRANSA, &ta, sizeof(ta)); cublasLtMatmulDescSetAttribute(p.op, CUBLASLT_MATMUL_DESC_TRANSB, &tb, sizeof(tb)); cublasLtMatrixLayoutCreate(&p.a, CUDA_R_16BF, 896, 3584, 3584); // Wo column slice (K = 896 head dims of a group) cublasLtMatrixLayoutCreate(&p.b, CUDA_R_16BF, 896, M, ldb); // O_g, token-major cublasLtMatrixLayoutCreate(&p.c, CUDA_R_32F, 3584, M, 3584); // fp32 accumulator cublasLtMatmulPreference_t pref; cublasLtMatmulPreferenceCreate(&pref); cublasLtMatmulPreferenceSetAttribute(pref, CUBLASLT_MATMUL_PREF_MAX_WORKSPACE_BYTES, &s.ws_bytes, sizeof(s.ws_bytes)); cublasLtMatmulHeuristicResult_t res[1]; int n = 0; if (cublasLtMatmulAlgoGetHeuristic(s.h, p.op, p.a, p.b, p.c, p.c, pref, 1, res, &n) == CUBLAS_STATUS_SUCCESS && n > 0 && res[0].state == CUBLAS_STATUS_SUCCESS) { p.algo = res[0].algo; p.has = true; } cublasLtMatmulPreferenceDestroy(pref); cudaGetLastError(); if (!p.has) return nullptr; return &mp->emplace(key, p).first->second;}struct GraphCache { cudaStream_t cs = nullptr; std::unordered_map<uint64_t, cudaGraphExec_t> execs; // key: hash of every pointer + shape std::unordered_map<int64_t, int> dec; // (B,S) -> 0 undecided, 1 graph, 2 eager std::unordered_map<int64_t, int> seen, caps; std::unordered_map<int64_t, int> cdmode; // (B,S) -> 1: graph uses the cuDNN-causal conditional std::unordered_map<int64_t, int> omode; // (B,S) -> 1: graph uses the custom o_proj std::unordered_map<int64_t, int> emode; // (B,S) -> 1: EAGER PDL chain with the custom o_proj struct Regate { uint64_t key = 0; cudaGraphExec_t alt = nullptr; int altc = -1, altom = 0, altcdm = 0, calls = 0; bool done = true; }; std::unordered_map<int64_t, Regate> rg;};#define REGATE_N 50GraphCache& GC() { static GraphCache* g = new GraphCache(); return *g; }} // namespace
// ---------------------------------------------------------------- host fast path// Graph-exec key: (B,S) + every raw pointer the captured forward bakes in (11 inputs, the fresh// output, and the internal workspaces q/k/v/attn/words/flags).static inline uint64_t graph_key(int64_t skey, const void* const* in11, const void* outp) { Workspace& w = WS(); const void* ptrs[18] = {in11[0], in11[1], in11[2], in11[3], in11[4], in11[5], in11[6], in11[7], in11[8], in11[9], in11[10], outp, w.q, w.words, w.flags, w.k, w.v, w.attn}; uint64_t key = (uint64_t)skey * 0x9E3779B97F4A7C15ull; for (int i = 0; i < 18; i++) key = (key ^ (uint64_t)(uintptr_t)ptrs[i]) * 0x100000001B3ull + (uint64_t)i; return key;}// Last graph-launched call: if the next call has the same (B,S) and the same contiguous input// pointers, every per-call host step (contiguity copies, workspace / tensormap checks, chunk and// variant lookups) is a no-op, so run() goes straight to the graph-exec lookup + cudaGraphLaunch.// ex / outp / rgp = graph exec resolved for the last (inputs, output pointer) -> repeated calls with the same// caching-allocator output block skip graph_key hashing and both hash-map lookups. ex is reset on every exec destroy.struct FastLast { bool valid = false; int64_t B = 0, S = 0; const void* p[11]; int64_t n[11]; // n = numel per input (p order) cudaGraphExec_t ex = nullptr; const void* outp = nullptr; // up to 4 (output block -> graph exec) pairs for the CURRENT input set, scanned linearly in the // fast path, so an output block that alternates between a few caching-allocator blocks (outputs held // by the caller) still skips graph_key hashing + the exec hash lookup. Reset with ex. int nx = 0, rr = 0; const void* xo[4]; cudaGraphExec_t xe[4]; c10::ScalarType dt = c10::ScalarType::BFloat16; c10::Device dev = c10::Device(c10::DeviceType::CUDA, 0); cudaStream_t st = nullptr; }; // dtype / device / stream cached at resolve time// generation of the (input set, graph-exec table) the pre-wrapped output's resolved exec belongs tostatic unsigned long long g_fl_gen = 1;static FastLast& FL() { static FastLast* f = new FastLast(); return *f; }static inline bool all_contig(const torch::Tensor& a, const torch::Tensor& b, const torch::Tensor& c, const torch::Tensor& d, const torch::Tensor& e, const torch::Tensor& f, const torch::Tensor& g, const torch::Tensor& h, const torch::Tensor& i, const torch::Tensor& j, const torch::Tensor& k) { return a.is_contiguous() && b.is_contiguous() && c.is_contiguous() && d.is_contiguous() && e.is_contiguous() && f.is_contiguous() && g.is_contiguous() && h.is_contiguous() && i.is_contiguous() && j.is_contiguous() && k.is_contiguous();}static inline void remember_fast(int64_t B, int64_t S, const void* const* p, const torch::Tensor& x, const torch::Tensor& qw, const torch::Tensor& kw, const torch::Tensor& vw, const torch::Tensor& ow, const torch::Tensor& qb, const torch::Tensor& kb, const torch::Tensor& vb, const torch::Tensor& c, const torch::Tensor& s, const torch::Tensor& m) { FastLast& f = FL(); // only when the raw inputs themselves were used (no contiguous() copies) f.valid = all_contig(x, qw, kw, vw, ow, qb, kb, vb, c, s, m) && p[0] == x.data_ptr() && p[1] == qw.data_ptr(); f.B = B; f.S = S; f.ex = nullptr; f.nx = 0; g_fl_gen++; for (int i = 0; i < 11; i++) f.p[i] = p[i]; const torch::Tensor* tt[11] = {&x, &qw, &kw, &vw, &ow, &qb, &kb, &vb, &c, &s, &m}; for (int i = 0; i < 11; i++) f.n[i] = tt[i]->numel();}
struct PreOut { torch::Tensor t; int64_t B = -1, S = -1; cudaStream_t st = nullptr; c10::ScalarType dt = c10::ScalarType::BFloat16; int dev = -1; };static PreOut& PO() { static PreOut* p = new PreOut(); return *p; }static inline torch::Tensor take_out(int64_t B, int64_t S, c10::ScalarType dt, c10::Device dev, cudaStream_t st) { PreOut& p = PO(); if (p.t.defined()) { if (p.B == B && p.S == S && p.st == st && p.dt == dt && p.dev == (int)dev.index()) { torch::Tensor o = std::move(p.t); p.t = torch::Tensor(); p.B = -1; return o; } p.t = torch::Tensor(); p.B = -1; } return at::detail::empty_cuda({B, S, (int64_t)3584}, dt, dev, c10::nullopt);}static inline void refill_out(int64_t B, int64_t S, c10::ScalarType dt, c10::Device dev, cudaStream_t st) { // pre-allocated / pre-wrapped next output for EVERY M (was M <= 1024): the run_fast hit path of large shapes // also returns an already-wrapped output (no allocator call / Tensor wrap before the graph launch) PreOut& p = PO(); p.t = at::detail::empty_cuda({B, S, (int64_t)3584}, dt, dev, c10::nullopt); p.B = B; p.S = S; p.st = st; p.dt = dt; p.dev = (int)dev.index();}torch::Tensor run(const torch::Tensor& x, const torch::Tensor& qw, const torch::Tensor& qb, const torch::Tensor& kw, const torch::Tensor& kb, const torch::Tensor& vw, const torch::Tensor& vb, const torch::Tensor& ow, const torch::Tensor& cos, const torch::Tensor& sin, const torch::Tensor& mask) { { // FAST PATH: same shape + same contiguous inputs + same output block as the last graph-launched call. // Raw TensorImpl accessors (no Tensor-level checks), one contiguity pass, cached device index for the stream lookup. FastLast& f = FL(); if (f.valid && f.ex && !g_stage) { c10::TensorImpl* ti[11] = {x.unsafeGetTensorImpl(), qw.unsafeGetTensorImpl(), kw.unsafeGetTensorImpl(), vw.unsafeGetTensorImpl(), ow.unsafeGetTensorImpl(), qb.unsafeGetTensorImpl(), kb.unsafeGetTensorImpl(), vb.unsafeGetTensorImpl(), cos.unsafeGetTensorImpl(), sin.unsafeGetTensorImpl(), mask.unsafeGetTensorImpl()}; bool same = ti[0]->dim() == 3 && ti[0]->size(0) == f.B && ti[0]->size(1) == f.S; for (int i = 0; i < 11 && same; i++) same = ti[i]->is_contiguous() && ti[i]->data() == f.p[i]; // regate bookkeeping removed (no regate entry is ever created since the static dispatch) if (same) { cudaStream_t cs_ = at::cuda::getCurrentCUDAStream(f.dev.index()).stream(); auto o = take_out(f.B, f.S, f.dt, f.dev, cs_); const void* op = o.unsafeGetTensorImpl()->data(); for (int i = 0; i < f.nx; i++) { if (f.xo[i] == op) { cudaGraphLaunch(f.xe[i], cs_); refill_out(f.B, f.S, f.dt, f.dev, cs_); // next call's output, off the critical path return o; } } // output block moved: fall through to the general path (o released here) } } } const int64_t B = x.size(0), S = x.size(1), Hd = x.size(2); // fresh output every call; allocated directly through the CUDA caching allocator (no dispatcher) cudaStream_t st = at::cuda::getCurrentCUDAStream(x.device().index()).stream(); auto out = (Hd == 3584) ? take_out(B, S, x.scalar_type(), x.device(), st) : at::detail::empty_cuda({B, S, Hd}, x.scalar_type(), x.device(), c10::nullopt); const int M = (int)(B * S); if (M == 0) return out; { // resolver: same inputs as the last graph-launched call, output block / regate state changed FastLast& f = FL(); if (f.valid && f.B == B && f.S == S && !g_stage) { const void* p[11] = {x.data_ptr(), qw.data_ptr(), kw.data_ptr(), vw.data_ptr(), ow.data_ptr(), qb.data_ptr(), kb.data_ptr(), vb.data_ptr(), cos.data_ptr(), sin.data_ptr(), mask.data_ptr()}; bool same = true; for (int i = 0; i < 11; i++) same &= (p[i] == f.p[i]); if (same && all_contig(x, qw, kw, vw, ow, qb, kb, vb, cos, sin, mask)) { const void* op = out.data_ptr(); GraphCache& gc = GC(); auto it = gc.execs.find(graph_key(B * 1000003 + S, p, op)); if (it != gc.execs.end()) { f.ex = it->second; f.outp = op; if (f.nx < 4) { f.xo[f.nx] = op; f.xe[f.nx] = it->second; f.nx++; } else { f.xo[f.rr] = op; f.xe[f.rr] = it->second; f.rr = (f.rr + 1) & 3; } f.dt = x.scalar_type(); f.dev = x.device(); f.st = st; cudaGraphLaunch(it->second, st); refill_out(B, S, x.scalar_type(), x.device(), st); return out; } } } } torch::Tensor tmp[11]; auto C = [&](const torch::Tensor& t, int i) -> const torch::Tensor& { if (t.is_contiguous()) return t; tmp[i] = t.contiguous(); return tmp[i]; }; const torch::Tensor &xc = C(x, 0), &qwc = C(qw, 1), &kwc = C(kw, 2), &vwc = C(vw, 3), &owc = C(ow, 4); const torch::Tensor &qbc = C(qb, 5), &kbc = C(kb, 6), &vbc = C(vb, 7), &cc = C(cos, 8), &ss = C(sin, 9), &m = C(mask, 10); const int nqt = (int)((S + 63) / 64), nkt = nqt; const int nt128 = (nqt + 1) / 2, nwc = (nt128 + 31) / 32; ensure_ws(M, B * nqt * nkt, B * nt128 * nwc * 4); Workspace& w = WS(); const void *px = xc.data_ptr(), *pq = qwc.data_ptr(), *pk = kwc.data_ptr(), *pv = vwc.data_ptr(); if (pq != w.kq || pk != w.kk || pv != w.kv) { // weight maps (the A map is per chunk, below) qkv_make_maps(&w.maps, px, pq, pk, pv, M); w.kx = px; w.kq = pq; w.kk = pk; w.kv = pv; w.kM = M; } if (w.agen != w.gen) { ATTMC().clear(); AMAPC().clear(); w.aq = w.q; w.agen = w.gen; } // workspaces reallocated const void *pqb = qbc.data_ptr(), *pkb = kbc.data_ptr(), *pvb = vbc.data_ptr(); const void* pow_ = owc.data_ptr();
// ---- full forward of the batch slice [b0, b0+bc) on stream s (Lt workspace wsi). // Every buffer is sliced by rows r0 = b0*S (token-major), mask/flags by batch; cos/sin keep // the full section stride MS = B*S. Slices of different chunks are disjoint -> chunks on // different streams never race. auto fwd = [&](int b0, int bc, cudaStream_t s, int wsi) { const bool stg_on = g_stage && b0 == 0; auto STG = [&](int i) { if (stg_on) cudaEventRecord(g_sev[i], s); }; if (stg_on) for (int i = 0; i < 4; i++) cudaEventRecord(g_sev[i], s); const int Mc = bc * (int)S; const size_t r0 = (size_t)b0 * S; const void* xs = (const char*)px + r0 * 3584 * 2; void* qs = (char*)w.q + r0 * 3584 * 2; void* ks = (char*)w.k + r0 * 512 * 2; void* vs = (char*)w.v + r0 * 512 * 2; void* as = (char*)w.attn + r0 * 3584 * 2; void* os = (char*)out.data_ptr() + r0 * 3584 * 2; uint8_t* fl = w.flags + (size_t)b0 * nqt * nkt; unsigned long long* wd = w.words + (size_t)b0 * nt128 * nwc * 4; // chunk's class words const void* mk = (const char*)m.data_ptr() + (size_t)b0 * S * S * 2; const void* cs = (const char*)cc.data_ptr() + r0 * 128 * 2; const void* sn = (const char*)ss.data_ptr() + r0 * 128 * 2; GemmMaps gm = w.maps; // last-key fast path per chunk slot (b0 picks the slot; <= 4 chunks) struct FastA { uint64_t key = 0; bool ok = false; CUtensorMap a; }; struct FastT { uint64_t key = 0; const AttnMaps* p = nullptr; }; static FastA* fa = new FastA[4]; static FastT* ft = new FastT[4]; const int slot = (b0 == 0 ? 0 : (int)((b0 * 4) / (int)B)) & 3; static unsigned last_gen = 0; if (last_gen != w.gen) { for (int i = 0; i < 4; i++) { fa[i].ok = false; ft[i].p = nullptr; } last_gen = w.gen; } const uint64_t akey = pkey(xs, Mc); if (fa[slot].ok && fa[slot].key == akey) gm.a = fa[slot].a; else { auto& ac = AMAPC(); const uint64_t key = akey; auto it = ac.find(key); if (it == ac.end()) { if (ac.size() > 256) ac.clear(); GemmMaps tmp; qkv_set_map_a(&tmp, xs, Mc); it = ac.emplace(key, tmp.a).first; } gm.a = it->second; fa[slot].key = akey; fa[slot].a = it->second; fa[slot].ok = true; } // head-major K/V ([4][M][128]) written by the M >= 4096 persistent QKV GEMM when the attention that follows // is one of the 3-D-K/V-map kernels (attn_tc / attn_tc_epw / attn_gqa): S >= 256, no occupancy override, and for // S == 256 the FA4 branch of the mid dispatch. kvhm = layout actually written (set after the QKV launch). const bool want_hm = Mc >= 2048 && S >= 256 && bc == (int)B && attn_occ_choice(Mc, (int)S) == 0 && (S > 256 || attn_mid_choice(Mc, (int)S) == 0); int kvhm = 0; auto amaps = [&]() -> const AttnMaps& { const uint64_t key = pkey(qs, Mc) ^ (kvhm ? 0x5bd1e995ull : 0ull); if (ft[slot].p && ft[slot].key == key) return *ft[slot].p; auto& c = ATTMC(); auto it = c.find(key); if (it == c.end()) { if (c.size() > 256) { c.clear(); for (int i = 0; i < 4; i++) ft[i].p = nullptr; } AttnMaps a; attn_make_maps(&a, qs, ks, vs, Mc, kvhm); it = c.emplace(key, a).first; } ft[slot].key = key; ft[slot].p = &it->second; // node-based map: pointer stable until clear return it->second; }; int pfq = 0; // 1 = o_weight L2 prefetch issued by the persistent QKV GEMM (o-prefetch gate candidate 2) auto qkv_custom = [&]() { qkv_set_prefetch(pfq ? pow_ : nullptr); qkv_set_oweight(pow_); qkv_set_xact(xs); launch_qkv_rope(gm, pqb, pkb, pvb, cs, sn, qs, ks, vs, Mc, M, mk, fl, wd, bc, (int)S, nqt, nkt, s); qkv_set_prefetch(nullptr); }; // attention dispatch reduced to the variants the static tables can select (dead branches pruned): // S <= 128 : 0 FA2 | 1 single-pass tc | 7 short_gqa4 HG 1 | 30 short_gqa2 LB HG 7 // 128 < S <= 256: 15 FA2 split-KV | 1 mid_gqa2 HG 1 | 0 FA4 (attn_tc / attn_gqa LPT) when >= 2 waves, else FA2 // S >= 512 (or 256 <= S with >= 2 FA4 waves): attn_tc (static variant table) | attn_gqa LPT sched 4 (gc 9) auto attn_dispatch_inner = [&]() { const int64_t fa4_ctas = (int64_t)bc * 28 * ((S + 127) / 128); if (S >= 1024) g_rec[2] = 400; auto fa4_run = [&]() { const int gc = S <= 1024 ? attn_gqa_choice(Mc, (int)S) : 0; if (gc) launch_attn_gqa(amaps(), mk, fl, wd, as, bc, (int)S, nqt, s, gc - 5); // GQA-packed, host LPT table else launch_attn_tc(amaps(), mk, fl, wd, as, bc, (int)S, nqt, s); }; if (S > 128 && S <= 256) { const int c = attn_mid_choice(Mc, (int)S); g_rec[2] = 200 + c; if (c == 16 && bc == 1 && S > 128 && S <= 256) launch_attn_s256(amaps(), mk, fl, as, bc, (int)S, nqt, s); else if (c == 15 || c == 16) launch_attn_split(qs, ks, vs, mk, fl, as, bc, (int)S, nqt, nkt, s); else if (c == 1) launch_attn_mid_gqa2(amaps(), mk, fl, as, bc, (int)S, nqt, 1, s); else if (c == 2 && S >= 256) fa4_run(); // static: FA4 tcgen05 (attn_tc_epw, host LPT table) for B4S256 else if (S >= 256 && fa4_ctas >= 2 * 148) fa4_run(); else launch_attn(qs, ks, vs, mk, fl, as, bc, (int)S, nqt, nkt, s); } else if (S >= 512 || (S >= 256 && fa4_ctas >= 2 * 148)) { g_rec[2] = 300; fa4_run(); } else if (S <= 128) { const int c = attn_short_choice(Mc, (int)S); g_rec[2] = 100 + c; if (c == 30) launch_attn_short_gqa2(amaps(), mk, fl, as, bc, (int)S, nqt, 7, s, nullptr, true); else if (c == 31) launch_attn_short_gqa2(amaps(), mk, fl, as, bc, (int)S, nqt, 7, s, nullptr, true, true); // split groups fill idle SMs else if (c == 7) launch_attn_short_gqa4(amaps(), mk, fl, as, bc, (int)S, nqt, 1, s); else if (c == 8) launch_attn_short_gqa4(amaps(), mk, fl, as, bc, (int)S, nqt, 7, s); // B32S128 -> 512-thr short_gqa4 HG7 (2 heads in flight, each over 2 column-split WGs; 128 CTAs) else if (c == 6) launch_attn_short_gqa4(amaps(), mk, fl, as, bc, (int)S, nqt, 1, s, true); // 256-thr, 2 CTAs/SM else if (c == 1) launch_attn_short(amaps(), mk, fl, as, bc, (int)S, nqt, s); else launch_attn(qs, ks, vs, mk, fl, as, bc, (int)S, nqt, nkt, s); } else { launch_attn(qs, ks, vs, mk, fl, as, bc, (int)S, nqt, nkt, s); } }; auto attn_dispatch = [&]() { // STATIC exp2 FMA-emulation share (g_attn_poly, attn_tc / attn_gqa only), S >= 256: 0 all MUFU, // 1 / 2 = 8 / 12 of 32 exp pairs on the FMA pipe int pm = 0; if (S >= 256) { static const SPick pt[] = {{16384, 256, 2} /* B64S256 PM1->PM2*/, {8192, 256, 2} /* B32S256 PM0 -> PM2*/, {1024, 256, 2} /* B4S256 PM0 -> PM2*/, {256, 256, 0}, {4096, 1024, 2}, {2048, 1024, 1} /* B2S1024 PM2 -> PM1*/, {1024, 1024, 1}, {4096, 4096, 1} /* B1S4096 PM2->PM1*/, {17312, 541, 1} , {512, 512, 2}, {613, 613, 2}, {4096, 512, 2}}; // B1S1024 PM2->PM1, B1S512/613 PM1->PM2 // B1S512/B1S613 (attn_tc_epw ) PM1 pm = SPICK(pt, Mc, (int)S); } // STATIC 2-CTAs/SM occupancy attention override: oc = 1 + attn_occ variant (4 = variant 3: rescale // threshold 8, all-MUFU exps), 0 = the dispatch above. Picked only at B4 S256 (M 1024). const int oc = attn_occ_choice(Mc, (int)S); g_rec[0] = pm; g_rec[1] = oc; if (oc) { launch_attn_occ(amaps(), mk, wd, as, bc, (int)S, s, oc - 1); return; } g_attn_poly = pm; attn_dispatch_inner(); g_attn_poly = 0; }; int pfon = 0; const unsigned long long OWB = 3584ull * 3584ull * 2ull; if (Mc <= 512) pfon = (Mc <= 128 || S >= 512) ? 3 : 1; else if (Mc <= 4096) { // STATIC: attention-issued o_weight prefetch (1) only where it was picked (B8 S128) static const SPick ft[] = {{1024, 128, 3} /* B8S128 side-branch o_weight L2 prefetch*/, {1024, 256, 0}, {1024, 1024, 0}, {613, 613, 3} /* B1S613 side-branch o_weight L2 prefetch kernel (attention single wave leaves SMs free)*/, {2048, 1024, 0}, {4096, 128, 3} /* B32S128 side-branch o_weight L2 prefetch (attn_short_gqa2 grid 128 CTAs leaves 20 SMs free)*/, {4096, 512, 0}, {4096, 1024, 0}, {4096, 4096, 0}}; // B1S4096 spread o_weight prefetch dropped; B1S4096 attention-issued o_weight L2 prefetch (spread over items) pfon = SPICK(ft, Mc, (int)S); } else if (Mc >= 12288 && Mc < 16896 && S == 256) pfon = 3; // B64S256 side-branch lowest-priority o_weight L2 evict_last prefetch (overlaps attention) pfq = pfon == 2; // QKV-issued o_weight prefetch for the forward's QKV launch (tail_cur / fused paths) auto oproj_run = [&](bool pdl) { LtPlan& p = get_plan((int64_t)Mc * 8 + ((bc == 1 && Mc >= 3072 && Mc < 6144) ? 4 : (bc > 1 && S >= 512 && Mc >= 3072 && Mc < 6144) ? 6 : (((bc > 1 && S <= 128 && ((Mc >= 768 && Mc < 1536) || (Mc > 384 && Mc <= 512))) || (bc == 1 && S > 384 && S <= 512) || (bc == 1 && S > 128 && S <= 256)) ? 2 : 0)), Mc, 3584, nullptr, (void*)pow_, as, os, s); const bool b1s4k = bc == 1 && Mc == 4096 && S >= 2048; if (Mc >= 4096 && !b1s4k) { static auto* big = new std::unordered_map<int, int>(); auto bit = big->find(Mc); if (bit == big->end()) { float le = 0.f; cublasLtMatmulHeuristicResult_t chk; if (p.has_algo && cublasLtMatmulAlgoCheck(LT().h, p.op, p.a, p.b, p.c, p.c, &p.algo, &chk) == CUBLAS_STATUS_SUCCESS && chk.state == CUBLAS_STATUS_SUCCESS && chk.wavesCount > 0.f) le = chk.wavesCount / ceilf(chk.wavesCount); cudaGetLastError(); const float ce = Mc >= 8192 ? oproj_big_wave_eff(Mc) : 0.f; int on = ce > 0.f && ce >= le - 1e-4f; const float cc = oproj_clc_wave_eff(Mc); const float cur = on ? (ce > le ? ce : le) : le; if (cc > 0.f && cc >= cur - 1e-4f) on = 2; fprintf(stderr, "[mrope oproj-big] M=%d clc eff %.3f custom eff %.3f cublasLt eff %.3f -> %s\n", Mc, cc, ce, le, on == 2 ? "clc" : (on ? "custom" : "cublasLt")); bit = big->emplace(Mc, on).first; } if (bit->second) { // in graph capture, the attention -> custom big o_proj edge uses the LAUNCH-COMPLETION port (as the // QKV -> attention edge): oproj_tma reads attn only after griddepcontrol.wait (= full attention completion + // flush), so its grid is launched once every attention CTA has started and its CTAs (prologue: barrier init, // TMEM alloc, tensormap prefetch) land on SMs as attention CTAs retire instead of after the last CTA's trigger. // All attention CTAs are already resident at that point -> no deadlock. Restored to a full edge on failure. cudaGraphNode_t an = nullptr; if (g_cap_pdl) { cudaStreamCaptureStatus cst; unsigned long long id = 0; cudaGraph_t g = nullptr; const cudaGraphNode_t* deps = nullptr; const cudaGraphEdgeData* ed = nullptr; size_t nd = 0; if (cudaStreamGetCaptureInfo(s, &cst, &id, &g, &deps, &ed, &nd) == cudaSuccess && cst == cudaStreamCaptureStatusActive && nd == 1) { an = deps[0]; const int ce = g_cap_edge; pdl_edge_to_next(s, true); g_cap_edge = ce; } cudaGetLastError(); } if (bit->second == 2 && launch_oproj_clc(as, pow_, os, Mc, s)) return; if (bit->second == 1 && launch_oproj_big(as, pow_, os, Mc, s)) return; // custom persistent 2-SM o_proj (PDL launch) if (an) { cudaStreamUpdateCaptureDependencies(s, &an, nullptr, 1, cudaStreamSetCaptureDependencies); cudaGetLastError(); } } } if (pdl && g_cap_pdl) pdl_edge_to_next(s); lt_run(p, pow_, as, os, s, wsi); }; // default tail: attention (dispatch rules above) then cublasLt o_proj on s auto attn_oproj_cur = [&]() { attn_set_prefetch(pfon == 1 ? pow_ : nullptr, OWB, Mc > 1024); attn_dispatch(); attn_set_prefetch(nullptr, 0); STG(2); oproj_run(true); }; qkv_set_kvhm(want_hm ? 1 : 0); qkv_custom(); kvhm = qkv_kvhm_used(); qkv_set_kvhm(0); // pfon 3: o_weight L2 prefetch kernel on a side branch forked after the QKV launch (full // dependency on QKV, nothing downstream depends on it; joined back only at the end of the forward) Pipe* pp3 = nullptr; if (pfon == 3) { pp3 = &PIPE(); cudaEventRecord(pp3->fork, s); cudaStreamWaitEvent(pp3->s2, pp3->fork, 0); launch_l2_prefetch(pow_, OWB, (Mc > 512 && Mc <= 1024) ? 148 : (Mc <= 128 ? 120 : 64), pp3->s2); // B1S128 -> 120 prefetch CTAs (SMs idle beside the 28-CTA attention) // B1S613 / B8S128 -> 148 prefetch CTAs (1/SM) cudaEventRecord(pp3->join, pp3->s2); } if (g_cap_pdl) { const int ce = g_cap_edge; pdl_edge_to_next(s, true); g_cap_edge = ce; } // QKV -> attention launch-completion edge STG(1); attn_oproj_cur(); STG(3); if (pp3) cudaStreamWaitEvent(s, pp3->join, 0); };
g_rec_nch = 1; { GraphCache& gc = GC(); const int64_t skey = B * 1000003 + S; int& dec = gc.dec[skey]; if (dec != 2 && !g_stage) { const void* ptrs[11] = {px, pq, pk, pv, pow_, pqb, pkb, pvb, cc.data_ptr(), ss.data_ptr(), m.data_ptr()}; const uint64_t key = graph_key(skey, ptrs, out.data_ptr()); auto it = gc.execs.find(key); if (it != gc.execs.end()) { remember_fast(B, S, ptrs, x, qw, kw, vw, ow, qb, kb, vb, cos, sin, mask); cudaGraphLaunch(it->second, st); refill_out(B, S, x.scalar_type(), x.device(), st); return out; } int& sn = gc.seen[skey]; if (!capturing(st) && sn >= 1) { if (++gc.caps[skey] > 16 && dec == 0) dec = 2; // pointer churn before any graph was kept: stay eager if (dec != 2) { if (!gc.cs) { int lo_ = 0, hi_ = 0; cudaDeviceGetStreamPriorityRange(&lo_, &hi_); cudaStreamCreateWithPriority(&gc.cs, cudaStreamNonBlocking, hi_); } // highest-priority capture stream cudaGraph_t graph = nullptr; cudaGraphExec_t ex = nullptr; bool ok = cudaStreamBeginCapture(gc.cs, cudaStreamCaptureModeRelaxed) == cudaSuccess; if (ok) { g_cap_pdl = true; g_cap_edge = 0; g_ocust = 0; g_cdn_fail = 0; g_cdn_try = 0; fwd(0, (int)B, gc.cs, 0); g_cap_pdl = false; ok = cudaStreamEndCapture(gc.cs, &graph) == cudaSuccess && graph; } if (ok) ok = cudaGraphInstantiate(&ex, graph, cudaGraphInstantiateFlagUseNodePriority) == cudaSuccess; // nodes keep the capture stream's (highest) priority // pre-upload the exec on the launch stream so replays never pay the lazy upload if (ok && ex) cudaGraphUpload(ex, st); if (graph) cudaGraphDestroy(graph); cudaGetLastError(); if (!ok) { if (ex) cudaGraphExecDestroy(ex); ex = nullptr; dec = 2; } if (ex) { dec = 1; if (gc.execs.size() >= 32) { FL().ex = nullptr; FL().nx = 0; g_fl_gen++; for (auto& kv : gc.execs) cudaGraphExecDestroy(kv.second); gc.execs.clear(); } gc.execs.emplace(key, ex); remember_fast(B, S, ptrs, x, qw, kw, vw, ow, qb, kb, vb, cos, sin, mask); cudaGraphLaunch(ex, st); refill_out(B, S, x.scalar_type(), x.device(), st); return out; } } } sn++; } } fwd(0, (int)B, st, 0); // eager forward return out;}static PyObject* g_run_pb = nullptr;struct PreObj { PyObject* obj = nullptr; const void* ptr = nullptr; int64_t B = -1, S = -1; cudaStream_t st = nullptr; c10::ScalarType dt = c10::ScalarType::BFloat16; int dev = -1; cudaGraphExec_t ex = nullptr; unsigned long long gen = 0; }; // exec resolved at prewrap timestatic PreObj& PREOBJ() { static PreObj* p = new PreObj(); return *p; }static inline void prewrap_out(int64_t B, int64_t S, c10::ScalarType dt, c10::Device dev, cudaStream_t st) { refill_out(B, S, dt, dev, st); // allocates PO().t (M <= 1024 only) PreOut& p = PO(); if (!p.t.defined()) return; PreObj& q = PREOBJ(); if (q.obj) { Py_DECREF(q.obj); q.obj = nullptr; } q.ptr = p.t.unsafeGetTensorImpl()->data(); q.B = B; q.S = S; q.st = st; q.dt = dt; q.dev = (int)dev.index(); q.obj = THPVariable_Wrap(std::move(p.t)); p.t = torch::Tensor(); p.B = -1; // resolve the graph exec of this output block NOW (after the current launch, off the next call's critical path), // so a hit in run_fast is one generation compare + cudaGraphLaunch (no exec-table scan / key compares before launch) q.ex = nullptr; q.gen = g_fl_gen; FastLast& f = FL(); for (int i = 0; i < f.nx; i++) if (f.xo[i] == q.ptr) { q.ex = f.xe[i]; break; }}static PyObject* run_fast(PyObject* /*self*/, PyObject* const* args, Py_ssize_t nargs, PyObject* kwnames) { static PyObject* s_args[11] = {nullptr}; // TensorImpl* of each cached arg object (kept alive by the strong refs in s_args); when the same Python objects // are passed again the per-arg THPVariable_Unpack is skipped (data ptr / numel / contiguity still checked). static c10::TensorImpl* s_impl[11] = {nullptr}; bool fast = kwnames == nullptr && nargs == 11; bool ident = fast; for (Py_ssize_t i = 0; ident && i < 11; i++) ident = args[i] == s_args[i]; for (Py_ssize_t i = 0; fast && !ident && i < 11; i++) fast = THPVariable_Check(args[i]); if (!fast) return PyObject_Vectorcall(g_run_pb, args, (size_t)nargs, kwnames); try { // Python-level graph fast path. Same (data_ptr, numel, contiguity) of all 11 inputs + same (B, S) as the last // graph-launched call -> output from the pre-allocated slot, exec looked up by output block, cudaGraphLaunch on the // current stream (thread-local lookup on the cached device). Any mismatch -> the full run() path (unchanged). FastLast& f = FL(); if (f.valid && f.nx > 0 && !g_stage) { static const int pidx[11] = {0, 1, 5, 2, 6, 3, 7, 4, 8, 9, 10}; // run() argument order -> f.p order // one Unpack / TensorImpl fetch per input (args[0] was unpacked twice); x's (B, S) checked in the loop bool same = true; for (int i = 0; i < 11 && same; i++) { c10::TensorImpl* ti = ident ? s_impl[i] : THPVariable_Unpack(args[i]).unsafeGetTensorImpl(); const int j = pidx[i]; same = ti->data() == f.p[j] && ti->numel() == f.n[j] && ti->is_contiguous(); if (i == 0 && same) same = ti->dim() == 3 && ti->sizes()[0] == f.B && ti->sizes()[1] == f.S; } if (same) { // current-stream handle cached by torch's stream id (thread-local current-stream lookup on the // cached device, no CUDAGuard / device switch: the explicit device index is passed); the cudaStream_t // is re-derived only when the stream id changes. // device index hoisted once; stream handle taken straight from the current CUDAStream (no id cache branch) const c10::DeviceIndex di_ = f.dev.index(); cudaStream_t cs_ = c10::cuda::getCurrentCUDAStream(di_).stream(); // PRE-WRAPPED output. The next call's output tensor is created AND wrapped as a Python object // (THPVariable) right after this call's cudaGraphLaunch; a hit returns that already-owned PyObject (no // allocator call, no Tensor wrap on the critical path). The graph exec is selected by the output block // (captured per output pointer, no param update needed). Key mismatch -> object dropped, normal path. PreObj& po = PREOBJ(); if (po.obj && po.ex && po.gen == g_fl_gen && po.st == cs_ && po.dt == f.dt) { PyObject* r = po.obj; po.obj = nullptr; cudaGraphLaunch(po.ex, cs_); if (!ident) for (int k = 0; k < 11; k++) { Py_INCREF(args[k]); Py_XDECREF(s_args[k]); s_args[k] = args[k]; s_impl[k] = THPVariable_Unpack(args[k]).unsafeGetTensorImpl(); } prewrap_out(f.B, f.S, f.dt, f.dev, cs_); return r; } if (po.obj) { if (po.st == cs_ && po.B == f.B && po.S == f.S && po.dt == f.dt && po.dev == (int)di_) { for (int i = 0; i < f.nx; i++) { if (f.xo[i] == po.ptr) { PyObject* r = po.obj; po.obj = nullptr; cudaGraphLaunch(f.xe[i], cs_); if (!ident) for (int k = 0; k < 11; k++) { Py_INCREF(args[k]); Py_XDECREF(s_args[k]); s_args[k] = args[k]; s_impl[k] = THPVariable_Unpack(args[k]).unsafeGetTensorImpl(); } // strong refs: no address reuse prewrap_out(f.B, f.S, f.dt, f.dev, cs_); return r; } } } Py_DECREF(po.obj); po.obj = nullptr; } torch::Tensor o = take_out(f.B, f.S, f.dt, f.dev, cs_); const void* op = o.unsafeGetTensorImpl()->data(); for (int i = 0; i < f.nx; i++) { if (f.xo[i] == op) { cudaGraphLaunch(f.xe[i], cs_); if (!ident) for (int k = 0; k < 11; k++) { Py_INCREF(args[k]); Py_XDECREF(s_args[k]); s_args[k] = args[k]; s_impl[k] = THPVariable_Unpack(args[k]).unsafeGetTensorImpl(); } prewrap_out(f.B, f.S, f.dt, f.dev, cs_); return THPVariable_Wrap(std::move(o)); } } // output block not cached: hand back to the full path (o released) } } } catch (const std::exception& e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return nullptr; } try { torch::Tensor o = run(THPVariable_Unpack(args[0]), THPVariable_Unpack(args[1]), THPVariable_Unpack(args[2]), THPVariable_Unpack(args[3]), THPVariable_Unpack(args[4]), THPVariable_Unpack(args[5]), THPVariable_Unpack(args[6]), THPVariable_Unpack(args[7]), THPVariable_Unpack(args[8]), THPVariable_Unpack(args[9]), THPVariable_Unpack(args[10])); return THPVariable_Wrap(std::move(o)); } catch (const std::exception& e) { PyErr_SetString(PyExc_RuntimeError, e.what()); return nullptr; }}static PyMethodDef g_run_def = {"run", (PyCFunction)(void (*)(void))run_fast, METH_FASTCALL | METH_KEYWORDS, "fused mRoPE GQA attention forward"};PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run_pb", &run); g_run_pb = m.attr("run_pb").ptr(); Py_INCREF(g_run_pb); PyObject* f = PyCFunction_NewEx(&g_run_def, nullptr, m.ptr()); if (!f) throw pybind11::error_already_set(); m.add_object("run", pybind11::reinterpret_steal<pybind11::object>(f));}1234567891011# MoE sparse routing and dispatch (L2 008)
An MoE block: a softmax router picks the top 8 experts per token, each chosen expert runs a SwiGLU MLP, and the outputs are summed with the router weights.
- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 4 (6,098 lines).- Idea: Router kernel (softmax, top-8, per-expert token blocks), then a persistent tcgen05 kernel running gate/up + SwiGLU tasks and down tasks that add weighted rows into the output.- Result: SOL score 0.902; speedup 3.43x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11.- Origin: search agent (Claude).- Comments edited; unused test helpers removed; the code that runs is identical to the scored submission.- Re-checked on a B200 after the edit: it builds and passes every workload of the SOL-ExecBench correctness check.- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465{ "board": "L2", "id": "008_moe_sparse_routing_and_dispatch", "name": "MoE sparse routing and dispatch", "language": "CUDA C++", "files": [ { "path": "src/kernel.cu", "lines": 6013, "bytes": 367450 }, { "path": "src/kernel.h", "lines": 12, "bytes": 805 }, { "path": "src/main.cpp", "lines": 71, "bytes": 3405 }, { "path": "src/probe_cfg.h", "lines": 2, "bytes": 33 } ], "origin": "search agent (Claude)", "result": { "public": true, "sol_score": 0.902345, "speedup": 3.4315, "board_row": true, "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" }, "idea": "Router kernel (softmax, top-8, per-expert token blocks), then a persistent tcgen05 kernel running gate/up + SwiGLU tasks and down tasks that add weighted rows into the output.", "spec": { "languages": [ "cuda_cpp" ], "target_hardware": [ "B200", "LOCAL" ], "entry_point": "main.cpp::run", "binding": "torch", "destination_passing_style": false, "dependencies": [], "compile_options": { "cuda_cflags": [ "-std=c++17", "-O3", "-gencode=arch=compute_100a,code=sm_100a", "-DGCAP_AO=6" ], "ld_flags": [] }, "sources": [ "kernel.h", "kernel.cu", "main.cpp", "probe_cfg.h" ] }}123456789101112#pragma once#include <cstdint>#include <cuda_runtime.h>// Host launcher for the full MoE pipeline (see kernel.cu for the algorithm).// cnt: persistent counter workspace NE+4 ints (compact histogram + router / fused-kernel tickets) followed by// done[max_blocks] (A-task counters) and hist[NE*32] (line-padded slot counters); zeroed once at allocation and// self-reset on device by the last consumer of each counter.// lst: expert-major (token,k) pair list [NE][T] written by the router.void launch_moe(const void* x, const void* gw, const void* gp, const void* up, const void* dp, int T, bool norm, int max_blocks, int* cnt, int* tid, float* tw, int* slot, int* start, int* blk_expert, int* meta, int* lst, void* inter, void* out, cudaStream_t st);1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071// Torch binding: allocates workspaces and calls the CUDA pipeline in kernel.cu.#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include "kernel.h"#include "probe_cfg.h"
torch::Tensor run_impl(torch::Tensor hs, torch::Tensor gw, torch::Tensor gp, torch::Tensor up, torch::Tensor dp, bool norm) { const int64_t H = 2048, I = 768, E = 128, K = 8, BM = 128; auto x = hs.reshape({-1, H}).contiguous(); auto gwc = gw.contiguous(); auto gpc = gp.contiguous(); auto upc = up.contiguous(); auto dpc = dp.contiguous(); int64_t T = x.size(0); int64_t P = T * K; int64_t max_blocks = (P + BM - 1) / BM + std::min<int64_t>(E, P); auto oi = x.options().dtype(torch::kInt32); // PERSISTENT counter workspace cnt[E+4] | done[max_blocks] | hist[E*32]: zeroed ONCE at // allocation; every counter/ticket is reset to 0 on device by its last consumer (router align CTA, // fused kernel's last-exiting CTA), so no per-call memset is needed. Between calls the whole // region except cnt[0..E) (compact histogram, plain data) is zero, so a different T (different layout // offsets) reuses it safely. Heap-held raw cudaMalloc, grown on demand, never destructed at exit. struct Ctr { int* p = nullptr; int64_t cap = 0; }; static Ctr& ctr = *new Ctr(); const int64_t nctr = E + 8 + max_blocks + E * 32; auto stream = at::cuda::getCurrentCUDAStream(); if (nctr > ctr.cap) { if (ctr.p) { cudaDeviceSynchronize(); cudaFree(ctr.p); } const int64_t cap = std::max<int64_t>(nctr, 2 * ctr.cap); cudaMalloc((void**)&ctr.p, cap * sizeof(int)); cudaMemsetAsync(ctr.p, 0, cap * sizeof(int), stream); // one-time zero (only on growth) ctr.cap = cap; } int* cnt = ctr.p; // per-call int32 workspace: tid[P] | slot[P] | start[E] | blk_expert[4*max_blocks] (int4 {e,start,cnt,0} per block, 16 B aligned) | meta[4] | lst[E*T] // (lst = expert-major (token,k) pair list written by the router: pair of slot j of expert e at lst[e*T + j]) // (tw[P] fp32 appended to the same allocation: one allocator call fewer per call) const int64_t nint = P * 2 + E + 4 * max_blocks + 4 + E * T; auto ws_i = torch::empty({nint + E * T}, oi); // tw: expert-major [E*T] fp32 (indexed like lst) int* tid = ws_i.data_ptr<int>(); int* slot = tid + P; int* start = slot + P; int* blk_expert = start + E; int* meta = blk_expert + 4 * max_blocks; int* lst = meta + 4; float* twp = (float*)(tid + nint); // (no Xs buffer: the fused kernel gathers x rows directly; the router split-K partials live in DSMEM) auto inter = torch::empty({max_blocks * BM, I}, x.options()); auto out = torch::empty({T, H}, x.options()); // zeroed on device by the fused kernel's epilogue warps, then accumulated if (T > 0) launch_moe(x.data_ptr(), gwc.data_ptr(), gpc.data_ptr(), upc.data_ptr(), dpc.data_ptr(), (int)T, norm, (int)max_blocks, cnt, tid, twp, slot, start, blk_expert, meta, lst, inter.data_ptr(), out.data_ptr(), stream); return out.reshape(hs.sizes());}
#ifndef MOE_PROBE#define MOE_PROBE 0#endif
torch::Tensor run(torch::Tensor hs, torch::Tensor gw, torch::Tensor gp, torch::Tensor up, torch::Tensor dp, bool norm) { return run_impl(hs, gw, gp, up, dp, norm);}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run, "MoE sparse routing + dispatch"); }12#pragma once#define MOE_PROBE 01234567891011# Decoder layer with residual connections (L2 009)
A full MoE decoder layer in fp32: RMSNorm, GQA attention with QK-norm, RoPE and a mask, then RMSNorm, a top-k router and the experts, with residual adds.
- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 6 (14,726 lines).- Idea: tcgen05 chain (fp16 or FP8 by size): QKV GEMM with RoPE + QK-norm epilogue, flash attention that skips masked tiles, o_proj + residual, router, grouped expert GEMMs.- Result: SOL score 0.828; speedup 3.36x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11.- Origin: edited after the search by Claude agents.- Comments edited; unused test helpers removed; the code that runs is identical to the scored submission.- Re-checked on a B200 after the edit: it builds and passes every workload of the SOL-ExecBench correctness check.- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778{ "board": "L2", "id": "009_decoder_layer_with_residual_connections", "name": "Decoder layer with residual connections", "language": "CUDA C++", "files": [ { "path": "src/fa4.cu", "lines": 1462, "bytes": 87940 }, { "path": "src/kernel.cu", "lines": 12404, "bytes": 773391 }, { "path": "src/kernel.h", "lines": 106, "bytes": 8415 }, { "path": "src/main.cpp", "lines": 292, "bytes": 19377 }, { "path": "src/side_steal.cuh", "lines": 300, "bytes": 13466 }, { "path": "src/ws_probe.cu", "lines": 162, "bytes": 9056 } ], "origin": "edited after the search by Claude agents", "result": { "public": true, "sol_score": 0.8275, "speedup": 3.3628, "board_row": true, "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" }, "idea": "tcgen05 chain (fp16 or FP8 by size): QKV GEMM with RoPE + QK-norm epilogue, flash attention that skips masked tiles, o_proj + residual, router, grouped expert GEMMs.", "spec": { "languages": [ "cuda_cpp" ], "target_hardware": [ "B200", "LOCAL" ], "entry_point": "main.cpp::run", "binding": "torch", "destination_passing_style": false, "dependencies": [], "compile_options": { "cuda_cflags": [ "-std=c++17", "-O3", "-gencode=arch=compute_100a,code=sm_100a" ], "ld_flags": [ "-lcuda" ] }, "sources": [ "kernel.h", "side_steal.cuh", "kernel.cu", "fa4.cu", "ws_probe.cu", "main.cpp" ] }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462// fa4.cu - FA4-style tcgen05 flash attention for long sequences (B200, sm_100a), used for S >= FA4_MIN_S.//// Work item = (batch b, q head h, q-tile PAIR qp): two 128-row query tiles Q0 = rows [256 qp, +128) and// Q1 = rows [256 qp + 128, +128) of ONE head share every K/V smem tile (one K/V load feeds 2 x 128 query rows).// Persistent: grid = min(#SMs, #items), items fetched from a global atomic counter in LPT order (largest qp first).// 384 threads, warp-specialized, registers rebalanced with setmaxnreg (ptxas allocates per role after it):// warps 0-3 : softmax WG0 (Q0), thread = one FULL 128-key S row (TMEM lane = row) -> no cross-thread max/sum// exchange; online softmax in the exp2 domain, lazy O rescale (only when the row max grows by > 11// in log2 units), P (fp16 pairs) written with tcgen05.st over S columns [0,64) of its own buffer,// final O / l normalize + fp16 store. (setmaxnreg 216)// warps 4-7 : softmax WG1 (Q1), same. (setmaxnreg 216)// warp 8 : item fetch + TMA producer: Q0/Q1 (64 KB) per item, then K tiles and V^T tiles (separate 2-stage// rings, K issued one kv tile ahead of V), 32 KB each, for every kv tile not fully masked for// Q0 or Q1. (setmaxnreg 72)// warp 9 : TMEM allocator + single-thread MMA issuer. (setmaxnreg 72)// warps 10-11: idle (complete the 3rd warpgroup for setmaxnreg).// TMEM (512 cols): [0,128) S0/P0, [128,256) S1/P1, [256,384) O0, [384,512) O1.// MMA issue order per kv tile j: PV0(j), S0(j+1), PV1(j), S1(j+1) - while softmax WG x works on S_x(j+1) the tensor// core runs the other tile's PV / S, so it always has independent work. S_x(j+1) is issued right after PV_x(j) without// waiting: tcgen05.mma from one thread execute in order, so S_x(j+1) overwrites P_x(j) only after PV_x(j) read it.// Mask: per-(q tile, kv tile) codes from mask_classify (0 = fully masked -> skipped for that q tile, 1 = all zero,// 2 = mixed -> compact log2e-prescaled tile). q, k are fp16 x 2^-6 each (folded into sl2), V^T x 2^-10 (kept in out).#include "kernel.h"#include "side_steal.cuh"#include <cuda.h>#include <cuda_fp16.h>#include <cstdint>#include <cmath>
#ifndef FA4_DBG#define FA4_DBG 0#endif#ifdef FA_PROBEnamespace fa4 { __device__ unsigned long long g_fa4_t[2][256]; } // per-CTA globaltimer: start (after acquire), end#endif#ifndef FA4_ROT#define FA4_ROT 0#endifnamespace fa4 {#if FA4_DBG__device__ unsigned long long g_dbg[16];#define DBG_T0(v) long long v = clock64()#define DBG_ADD(i, v) (dacc[i] += (unsigned long long)(clock64() - (v)))#define DBG_CNT(i) (dacc[i] += 1ull)#else#define DBG_T0(v)#define DBG_ADD(i, v)#define DBG_CNT(i)#endif__device__ __forceinline__ uint32_t smem_u32(const void* p) { return (uint32_t)__cvta_generic_to_shared(p); }__device__ __forceinline__ void mbar_init(uint32_t a, uint32_t cnt) { asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(a), "r"(cnt));}__device__ __forceinline__ void mbar_expect_tx(uint32_t a, uint32_t bytes) { asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(a), "r"(bytes) : "memory");}__device__ __forceinline__ void mbar_arrive(uint32_t a) { asm volatile("mbarrier.arrive.shared::cta.b64 _, [%0];" ::"r"(a) : "memory");}__device__ __forceinline__ void mbar_wait(uint32_t a, uint32_t parity) { uint32_t ok = 0; while (!ok) { asm volatile( "{ .reg .pred p; mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2; selp.u32 %0, 1, 0, p; }" : "=r"(ok) : "r"(a), "r"(parity) : "memory"); }}// mbarrier wait with try_wait's suspend-time hint: the waiting warp sleeps in hardware until the phase completes// (instead of re-issuing a polling loop that steals issue slots from the co-resident softmax warpgroup)__device__ __forceinline__ void mbar_wait_hint(uint32_t a, uint32_t parity) { uint32_t ok = 0; while (!ok) { asm volatile( "{ .reg .pred p; mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2, %3; selp.u32 %0, 1, 0, p; }" : "=r"(ok) : "r"(a), "r"(parity), "r"(10000000u) : "memory"); }}// non-blocking: true iff the phase with the given parity has completed__device__ __forceinline__ bool mbar_test(uint32_t a, uint32_t parity) { uint32_t ok; asm volatile( "{ .reg .pred p; mbarrier.test_wait.parity.shared::cta.b64 p, [%1], %2; selp.u32 %0, 1, 0, p; }" : "=r"(ok) : "r"(a), "r"(parity) : "memory"); return ok != 0;}// test first (no suspend round trip when the phase already completed), then the hinted blocking wait__device__ __forceinline__ void mbar_wait_fast(uint32_t a, uint32_t parity) { if (!mbar_test(a, parity)) mbar_wait_hint(a, parity);}__device__ __forceinline__ void tma_load_2d_hint(uint32_t dst, const CUtensorMap* map, int x, int y, uint32_t bar, uint64_t pol) { asm volatile( "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3}], [%4], %5;" ::"r"( dst), "l"((uint64_t)map), "r"(x), "r"(y), "r"(bar), "l"(pol) : "memory");}// TMA 2D load, default L2 policy__device__ __forceinline__ void tma_load_2d(uint32_t dst, const CUtensorMap* map, int x, int y, uint32_t bar) { asm volatile( "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"(dst), "l"((uint64_t)map), "r"(x), "r"(y), "r"(bar) : "memory");}// ---- 2-CTA cluster helpers (MCL path: the two CTAs of a cluster share every K / V^T tile by TMA multicast)__device__ __forceinline__ uint32_t cl_rank() { uint32_t r; asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); return r; }__device__ __forceinline__ uint32_t mapa_sh(uint32_t a, uint32_t rank) { uint32_t r; asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(rank)); return r;}__device__ __forceinline__ void mbar_arrive_cl(uint32_t a) { // a: shared::cluster address asm volatile("mbarrier.arrive.release.cluster.shared::cluster.b64 _, [%0];" ::"r"(a) : "memory");}__device__ __forceinline__ void mbar_wait_cl(uint32_t a, uint32_t parity) { uint32_t ok = 0; while (!ok) asm volatile("{ .reg .pred p; mbarrier.try_wait.parity.acquire.cluster.shared::cta.b64 p, [%1], %2; selp.u32 %0, 1, 0, p; }" : "=r"(ok) : "r"(a), "r"(parity) : "memory");}__device__ __forceinline__ void cl_sync() { asm volatile("barrier.cluster.arrive.release.aligned;\nbarrier.cluster.wait.acquire.aligned;" ::: "memory");}// TMA 2D load multicast to the same smem offset (data + complete_tx on the same-offset mbarrier) of the CTAs in mask__device__ __forceinline__ void tma_load_2d_mc(uint32_t dst, const CUtensorMap* map, int x, int y, uint32_t bar, uint16_t mask) { asm volatile( "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.multicast::cluster [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(dst), "l"((uint64_t)map), "r"(x), "r"(y), "r"(bar), "h"(mask) : "memory");}__device__ __forceinline__ void mma_commit_mc(uint32_t bar, uint16_t mask) { asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.multicast::cluster.b64 [%0], %1;" ::"r"(bar), "h"(mask) : "memory");}__device__ __forceinline__ uint64_t keep_pol() { uint64_t pol; asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol)); return pol;}__device__ __forceinline__ uint64_t first_pol() { uint64_t pol; asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); return pol;}__device__ __forceinline__ void st_u4_hint(uint4* addr, uint4 v, uint64_t pol) { asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(addr), "r"(v.x), "r"(v.y), "r"(v.z), "r"(v.w), "l"(pol) : "memory");}__device__ __forceinline__ void tc_fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); }__device__ __forceinline__ void tc_fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); }// K-major operand, 128B swizzle, 8-row core-matrix groups 1024 B apart (SBO), sm100 descriptor version 1.__device__ __forceinline__ uint64_t make_sdesc(uint32_t addr) { uint64_t d = 0; d |= (uint64_t)((addr & 0x3FFFF) >> 4); d |= (uint64_t)1 << 16; d |= (uint64_t)(1024 >> 4) << 32; d |= (uint64_t)1 << 46; d |= (uint64_t)2 << 61; return d;}__device__ __forceinline__ void mma_f16_ss(uint32_t tmem, uint64_t ad, uint64_t bd, uint32_t idesc, uint32_t acc) { asm volatile( "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, p; }" ::"r"( tmem), "l"(ad), "l"(bd), "r"(idesc), "r"(acc));}__device__ __forceinline__ void mma_f16_ts(uint32_t tmem, uint32_t a_tmem, uint64_t bd, uint32_t idesc, uint32_t acc) { asm volatile( "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::1.kind::f16 [%0], [%1], %2, %3, p; }" ::"r"( tmem), "r"(a_tmem), "l"(bd), "r"(idesc), "r"(acc));}// kind::f8f6f4 SS MMA (e4m3 x e4m3 -> f32, K = 32 = 32 B of the 128B-swizzled K-major rows; same idesc bits as f16// with a/b format 0 = E4M3)__device__ __forceinline__ void mma_f8_ss(uint32_t tmem, uint64_t ad, uint64_t bd, uint32_t idesc, uint32_t acc) { asm volatile( "{ .reg .pred p; setp.ne.b32 p, %4, 0; tcgen05.mma.cta_group::1.kind::f8f6f4 [%0], %1, %2, %3, p; }" ::"r"(tmem), "l"(ad), "l"(bd), "r"(idesc), "r"(acc));}// elect.sync: true in exactly one (the lowest) active lane of the full warp__device__ __forceinline__ bool elect_one() { uint32_t pred; asm volatile("{ .reg .pred P; elect.sync _|P, 0xffffffff; selp.u32 %0, 1, 0, P; }" : "=r"(pred)); return pred != 0;}__device__ __forceinline__ void mma_commit(uint32_t bar) { asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(bar) : "memory");}// two 32-column TMEM loads (32 lanes x 32 bit) in flight, one wait__device__ __forceinline__ void tmem_ld32x2(uint32_t ta, float* va, uint32_t tb, float* vb) { uint32_t r[32], u[32]; asm volatile( "tcgen05.ld.sync.aligned.32x32b.x32.b32 {%0,%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];" : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]), "=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]), "=r"(r[14]), "=r"(r[15]), "=r"(r[16]), "=r"(r[17]), "=r"(r[18]), "=r"(r[19]), "=r"(r[20]), "=r"(r[21]), "=r"(r[22]), "=r"(r[23]), "=r"(r[24]), "=r"(r[25]), "=r"(r[26]), "=r"(r[27]), "=r"(r[28]), "=r"(r[29]), "=r"(r[30]), "=r"(r[31]) : "r"(ta)); asm volatile( "tcgen05.ld.sync.aligned.32x32b.x32.b32 {%0,%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];" : "=r"(u[0]), "=r"(u[1]), "=r"(u[2]), "=r"(u[3]), "=r"(u[4]), "=r"(u[5]), "=r"(u[6]), "=r"(u[7]), "=r"(u[8]), "=r"(u[9]), "=r"(u[10]), "=r"(u[11]), "=r"(u[12]), "=r"(u[13]), "=r"(u[14]), "=r"(u[15]), "=r"(u[16]), "=r"(u[17]), "=r"(u[18]), "=r"(u[19]), "=r"(u[20]), "=r"(u[21]), "=r"(u[22]), "=r"(u[23]), "=r"(u[24]), "=r"(u[25]), "=r"(u[26]), "=r"(u[27]), "=r"(u[28]), "=r"(u[29]), "=r"(u[30]), "=r"(u[31]) : "r"(tb)); asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory");#pragma unroll for (int i = 0; i < 32; i++) { va[i] = __uint_as_float(r[i]); vb[i] = __uint_as_float(u[i]); }}__device__ __forceinline__ void tmem_ld32(uint32_t taddr, float* v) { uint32_t r[32]; asm volatile( "tcgen05.ld.sync.aligned.32x32b.x32.b32 {%0,%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];" : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]), "=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]), "=r"(r[14]), "=r"(r[15]), "=r"(r[16]), "=r"(r[17]), "=r"(r[18]), "=r"(r[19]), "=r"(r[20]), "=r"(r[21]), "=r"(r[22]), "=r"(r[23]), "=r"(r[24]), "=r"(r[25]), "=r"(r[26]), "=r"(r[27]), "=r"(r[28]), "=r"(r[29]), "=r"(r[30]), "=r"(r[31]) : "r"(taddr)); asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory");#pragma unroll for (int i = 0; i < 32; i++) v[i] = __uint_as_float(r[i]);}__device__ __forceinline__ void tmem_st32(uint32_t taddr, const float* v) { asm volatile( "tcgen05.st.sync.aligned.32x32b.x32.b32 [%0], {%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};" ::"r"(taddr), "f"(v[0]), "f"(v[1]), "f"(v[2]), "f"(v[3]), "f"(v[4]), "f"(v[5]), "f"(v[6]), "f"(v[7]), "f"(v[8]), "f"(v[9]), "f"(v[10]), "f"(v[11]), "f"(v[12]), "f"(v[13]), "f"(v[14]), "f"(v[15]), "f"(v[16]), "f"(v[17]), "f"(v[18]), "f"(v[19]), "f"(v[20]), "f"(v[21]), "f"(v[22]), "f"(v[23]), "f"(v[24]), "f"(v[25]), "f"(v[26]), "f"(v[27]), "f"(v[28]), "f"(v[29]), "f"(v[30]), "f"(v[31]));}// one tcgen05.ld 32x32b.x128 (128 columns, one instruction) + one wait::ld__device__ __forceinline__ void tmem_ld128(uint32_t taddr, float* v) { uint32_t r[128]; asm volatile("tcgen05.ld.sync.aligned.32x32b.x128.b32 {%0,%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];" : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]), "=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]), "=r"(r[14]), "=r"(r[15]), "=r"(r[16]), "=r"(r[17]), "=r"(r[18]), "=r"(r[19]), "=r"(r[20]), "=r"(r[21]), "=r"(r[22]), "=r"(r[23]), "=r"(r[24]), "=r"(r[25]), "=r"(r[26]), "=r"(r[27]), "=r"(r[28]), "=r"(r[29]), "=r"(r[30]), "=r"(r[31]), "=r"(r[32]), "=r"(r[33]), "=r"(r[34]), "=r"(r[35]), "=r"(r[36]), "=r"(r[37]), "=r"(r[38]), "=r"(r[39]), "=r"(r[40]), "=r"(r[41]), "=r"(r[42]), "=r"(r[43]), "=r"(r[44]), "=r"(r[45]), "=r"(r[46]), "=r"(r[47]), "=r"(r[48]), "=r"(r[49]), "=r"(r[50]), "=r"(r[51]), "=r"(r[52]), "=r"(r[53]), "=r"(r[54]), "=r"(r[55]), "=r"(r[56]), "=r"(r[57]), "=r"(r[58]), "=r"(r[59]), "=r"(r[60]), "=r"(r[61]), "=r"(r[62]), "=r"(r[63]), "=r"(r[64]), "=r"(r[65]), "=r"(r[66]), "=r"(r[67]), "=r"(r[68]), "=r"(r[69]), "=r"(r[70]), "=r"(r[71]), "=r"(r[72]), "=r"(r[73]), "=r"(r[74]), "=r"(r[75]), "=r"(r[76]), "=r"(r[77]), "=r"(r[78]), "=r"(r[79]), "=r"(r[80]), "=r"(r[81]), "=r"(r[82]), "=r"(r[83]), "=r"(r[84]), "=r"(r[85]), "=r"(r[86]), "=r"(r[87]), "=r"(r[88]), "=r"(r[89]), "=r"(r[90]), "=r"(r[91]), "=r"(r[92]), "=r"(r[93]), "=r"(r[94]), "=r"(r[95]), "=r"(r[96]), "=r"(r[97]), "=r"(r[98]), "=r"(r[99]), "=r"(r[100]), "=r"(r[101]), "=r"(r[102]), "=r"(r[103]), "=r"(r[104]), "=r"(r[105]), "=r"(r[106]), "=r"(r[107]), "=r"(r[108]), "=r"(r[109]), "=r"(r[110]), "=r"(r[111]), "=r"(r[112]), "=r"(r[113]), "=r"(r[114]), "=r"(r[115]), "=r"(r[116]), "=r"(r[117]), "=r"(r[118]), "=r"(r[119]), "=r"(r[120]), "=r"(r[121]), "=r"(r[122]), "=r"(r[123]), "=r"(r[124]), "=r"(r[125]), "=r"(r[126]), "=r"(r[127]) : "r"(taddr)); asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory");#pragma unroll for (int i = 0; i < 128; i++) v[i] = __uint_as_float(r[i]);}// one tcgen05.st 32x32b.x64 (64 columns, one instruction)__device__ __forceinline__ void tmem_st64(uint32_t taddr, const float* v) { asm volatile("tcgen05.st.sync.aligned.32x32b.x64.b32 [%0], {%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};" ::"r"(taddr), "f"(v[0]), "f"(v[1]), "f"(v[2]), "f"(v[3]), "f"(v[4]), "f"(v[5]), "f"(v[6]), "f"(v[7]), "f"(v[8]), "f"(v[9]), "f"(v[10]), "f"(v[11]), "f"(v[12]), "f"(v[13]), "f"(v[14]), "f"(v[15]), "f"(v[16]), "f"(v[17]), "f"(v[18]), "f"(v[19]), "f"(v[20]), "f"(v[21]), "f"(v[22]), "f"(v[23]), "f"(v[24]), "f"(v[25]), "f"(v[26]), "f"(v[27]), "f"(v[28]), "f"(v[29]), "f"(v[30]), "f"(v[31]), "f"(v[32]), "f"(v[33]), "f"(v[34]), "f"(v[35]), "f"(v[36]), "f"(v[37]), "f"(v[38]), "f"(v[39]), "f"(v[40]), "f"(v[41]), "f"(v[42]), "f"(v[43]), "f"(v[44]), "f"(v[45]), "f"(v[46]), "f"(v[47]), "f"(v[48]), "f"(v[49]), "f"(v[50]), "f"(v[51]), "f"(v[52]), "f"(v[53]), "f"(v[54]), "f"(v[55]), "f"(v[56]), "f"(v[57]), "f"(v[58]), "f"(v[59]), "f"(v[60]), "f"(v[61]), "f"(v[62]), "f"(v[63]));}__device__ __forceinline__ float fast_exp2(float x) { float y; asm("ex2.approx.ftz.f32 %0, %1;" : "=f"(y) : "f"(x)); return y;}// one cvt.rn.f16x2.f32: low half = a, high half = b__device__ __forceinline__ uint32_t cvt_h2(uint32_t a, uint32_t b) { uint32_t d; asm("cvt.rn.f16x2.f32 %0, %1, %2;" : "=r"(d) : "f"(__uint_as_float(b)), "f"(__uint_as_float(a))); return d;}__device__ __forceinline__ uint32_t pack_h2(float a, float b) { __half2 h = __floats2half2_rn(a, b); return *reinterpret_cast<uint32_t*>(&h);}// Blackwell packed fp32x2 ALU (FFMA2 / FADD2 / FMUL2: one issued instruction for two lanes, per-lane IEEE .rn)// and the 3-input max - the same packed softmax math as the head-pair kernel in kernel.cu.__device__ __forceinline__ float2 ffma2(float2 a, float2 b, float2 c) { float2 d; asm("{ .reg .b64 ra, rb, rc, rd; mov.b64 ra, {%2, %3}; mov.b64 rb, {%4, %5}; mov.b64 rc, {%6, %7};\n" "fma.rn.f32x2 rd, ra, rb, rc; mov.b64 {%0, %1}, rd; }" : "=f"(d.x), "=f"(d.y) : "f"(a.x), "f"(a.y), "f"(b.x), "f"(b.y), "f"(c.x), "f"(c.y)); return d;}__device__ __forceinline__ float2 fadd2(float2 a, float2 b) { float2 d; asm("{ .reg .b64 ra, rb, rd; mov.b64 ra, {%2, %3}; mov.b64 rb, {%4, %5};\n" "add.rn.f32x2 rd, ra, rb; mov.b64 {%0, %1}, rd; }" : "=f"(d.x), "=f"(d.y) : "f"(a.x), "f"(a.y), "f"(b.x), "f"(b.y)); return d;}__device__ __forceinline__ float2 fmul2(float2 a, float2 b) { float2 d; asm("{ .reg .b64 ra, rb, rd; mov.b64 ra, {%2, %3}; mov.b64 rb, {%4, %5};\n" "mul.rn.f32x2 rd, ra, rb; mov.b64 {%0, %1}, rd; }" : "=f"(d.x), "=f"(d.y) : "f"(a.x), "f"(a.y), "f"(b.x), "f"(b.y)); return d;}// packed fp32x2 subtract (sub.rn.f32x2): a - b without a separate negation of b (bit-identical to fadd2(a, -b))__device__ __forceinline__ float2 fsub2(float2 a, float2 b) { float2 d; asm("{ .reg .b64 ra, rb, rd; mov.b64 ra, {%2, %3}; mov.b64 rb, {%4, %5};\n" "sub.rn.f32x2 rd, ra, rb; mov.b64 {%0, %1}, rd; }" : "=f"(d.x), "=f"(d.y) : "f"(a.x), "f"(a.y), "f"(b.x), "f"(b.y)); return d;}__device__ __forceinline__ float fmax3(float a, float b, float c) { float d; asm("max.f32 %0, %1, %2, %3;" : "=f"(d) : "f"(a), "f"(b), "f"(c)); return d;}
// ---- MUFU offload (ported from; 1/4): a fraction of the exp2 pairs per row run on the FMA pipe.// x clamped to >= -126 (-inf -> ~2^-126 -> 0 in fp16), j = round(x) via the 1.5*2^23 magic add (FADD2),// f = x - j in [-0.5, 0.5], 2^f by a degree-3 least-squares polynomial (FFMA2 Horner, max rel err 7.7e-5),// exponent added in the integer domain: bits(p) + (bits(x + magic) << 23).__device__ __forceinline__ float2 exp2_poly2(float2 x) { x.x = fmaxf(x.x, -126.f); x.y = fmaxf(x.y, -126.f); const float2 mg = make_float2(12582912.f, 12582912.f); const float2 r = fadd2(x, mg); const float2 j = fadd2(r, make_float2(-12582912.f, -12582912.f)); const float2 f = fsub2(x, j); // sub.rn.f32x2 (bit-identical to x + (-j)) float2 p = ffma2(make_float2(0.05508877f, 0.05508877f), f, make_float2(0.24260466f, 0.24260466f)); p = ffma2(p, f, make_float2(0.69327628f, 0.69327628f)); p = ffma2(p, f, make_float2(0.9999289f, 0.9999289f)); return make_float2(__uint_as_float(__float_as_uint(p.x) + (__float_as_uint(r.x) << 23)), __uint_as_float(__float_as_uint(p.y) + (__float_as_uint(r.y) << 23)));}__device__ __forceinline__ float2 exp2_poly2d2(float2 x) { x.x = fmaxf(x.x, -126.f); x.y = fmaxf(x.y, -126.f); const float2 mg = make_float2(12582912.f, 12582912.f); const float2 r = fadd2(x, mg); const float2 j = fadd2(r, make_float2(-12582912.f, -12582912.f)); const float2 f = fsub2(x, j); float2 p = ffma2(make_float2(0.23842119f, 0.23842119f), f, make_float2(0.70343379f, 0.70343379f)); p = ffma2(p, f, make_float2(1.00044259f, 1.00044259f)); return make_float2(__uint_as_float(__float_as_uint(p.x) + (__float_as_uint(r.x) << 23)), __uint_as_float(__float_as_uint(p.y) + (__float_as_uint(r.y) << 23)));}// 4 fp32 -> 4 e4m3 bytes (a lowest), RN, saturating; identical to kernel.cu__device__ __forceinline__ uint32_t cvt_e4m3x4(float a, float b, float c, float d) { uint16_t lo, hi; asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(lo) : "f"(b), "f"(a)); asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(hi) : "f"(d), "f"(c)); return (uint32_t)lo | ((uint32_t)hi << 16);}// exact pow2 scale with mx * s < 2^top (bit-identical to kernel.cu f8_scale, which o_proj uses to undo it)__device__ __forceinline__ float f8_scale(float mx, int top) { if (!(mx > 0.f) || !(mx < INFINITY)) return 1.f; int e; e = sidew::frexp_e(mx); int x = top - e; x = x < -60 ? -60 : (x > 60 ? 60 : x); return sidew::pow2i(x);}// global e4m3 Q / K scale - identical expression to qk8_scale in kernel.cu (the QKV epilogue that wrote q / k)__device__ __forceinline__ float qk8_scale(const unsigned* qkb, int which) { const float bound = 11.3137085f * __uint_as_float(qkb[2 + which]) * (__uint_as_float(qkb[0]) + __uint_as_float(qkb[1])); return f8_scale(bound, 8);}
// scaled output conversion - 4 (or 2) O values x the folded output scale (1/l [x global fp8 scale]) as packed// FMUL2 (bit-identical to the scalar products), then one packed cvt per pair.__device__ __forceinline__ uint32_t e4m3x4_s(const float* p, float2 s2) { const float2 a = fmul2(make_float2(p[0], p[1]), s2), b = fmul2(make_float2(p[2], p[3]), s2); return cvt_e4m3x4(a.x, a.y, b.x, b.y);}__device__ __forceinline__ uint32_t h2_s(const float* p, float2 s2) { const float2 a = fmul2(make_float2(p[0], p[1]), s2); return pack_h2(a.x, a.y);}__device__ __forceinline__ void side_acquire(const unsigned long long* ctr, unsigned long long target) { while (true) { unsigned long long v; asm volatile("ld.acquire.gpu.global.u64 %0, [%1];" : "=l"(v) : "l"(ctr) : "memory"); if (v >= target) break; __nanosleep(32); }}
// softmax instruction diet: one asm block per MUFU pair = scale-and-subtract-max (fma.rn.f32x2), 2 x ex2.approx.ftz,// row-sum accumulate (add.rn.f32x2) and fp16x2 pack (cvt.rn.f16x2.f32, low half = first key): bit-identical to the// former ffma2 / fast_exp2 / fadd2 / pack_h2 sequence, without the intermediate 64-bit mov round trips__device__ __forceinline__ uint32_t sm_exp_pack(float s0, float s1, float2 ks, float2 nb, float2& acc) { uint32_t pk; asm("{ .reg .b64 rs, rk, rn, rt, ra, re; .reg .f32 t0, t1, e0, e1;\n" " mov.b64 rs, {%3, %4}; mov.b64 rk, {%5, %6}; mov.b64 rn, {%7, %8}; mov.b64 ra, {%1, %2};\n" " fma.rn.f32x2 rt, rs, rk, rn; mov.b64 {t0, t1}, rt;\n" " ex2.approx.ftz.f32 e0, t0; ex2.approx.ftz.f32 e1, t1;\n" " mov.b64 re, {e0, e1}; add.rn.f32x2 ra, ra, re; mov.b64 {%1, %2}, ra;\n" " cvt.rn.f16x2.f32 %0, e1, e0; }" : "=r"(pk), "+f"(acc.x), "+f"(acc.y) : "f"(s0), "f"(s1), "f"(ks.x), "f"(ks.y), "f"(nb.x), "f"(nb.y)); return pk;}// FMA-pipe (polynomial) exp2 pair fused into ONE asm block: scale-and-subtract-max (fma.rn.f32x2), clamp,// magic round, Horner 2^f (fma.rn.f32x2), integer exponent insert, row-sum accumulate (add.rn.f32x2) and fp16x2 pack.// Same ops / constants / order as ffma2 + exp2_poly2{,d2} + fadd2 + pack_h2 (bit-identical), no 64-bit mov round trips.template <int DEG>__device__ __forceinline__ uint32_t sm_poly_pack(float s0, float s1, float2 ks, float2 nb, float2& acc) { uint32_t pk; if (DEG == 3) { asm("{ .reg .b64 rs, rk, rn, rt, rx, rm, rmn, rr, rj, rf, rp, ka, kb, kc, kd, ra, re;\n" " .reg .f32 t0, t1, x0, x1, r0, r1, p0, p1, e0, e1; .reg .b32 u0, u1, v0, v1;\n" " mov.b64 rs, {%3, %4}; mov.b64 rk, {%5, %6}; mov.b64 rn, {%7, %8}; mov.b64 ra, {%1, %2};\n" " mov.b64 rm, {%9, %9}; mov.b64 rmn, {%10, %10};\n" " mov.b64 ka, {%11, %11}; mov.b64 kb, {%12, %12}; mov.b64 kc, {%13, %13}; mov.b64 kd, {%14, %14};\n" " fma.rn.f32x2 rt, rs, rk, rn; mov.b64 {t0, t1}, rt;\n" " max.f32 x0, t0, %15; max.f32 x1, t1, %15; mov.b64 rx, {x0, x1};\n" " add.rn.f32x2 rr, rx, rm; add.rn.f32x2 rj, rr, rmn; sub.rn.f32x2 rf, rx, rj;\n" " fma.rn.f32x2 rp, ka, rf, kb; fma.rn.f32x2 rp, rp, rf, kc; fma.rn.f32x2 rp, rp, rf, kd;\n" " mov.b64 {p0, p1}, rp; mov.b64 {r0, r1}, rr;\n" " mov.b32 u0, p0; mov.b32 u1, p1; mov.b32 v0, r0; mov.b32 v1, r1;\n" " shl.b32 v0, v0, 23; shl.b32 v1, v1, 23; add.u32 u0, u0, v0; add.u32 u1, u1, v1;\n" " mov.b32 e0, u0; mov.b32 e1, u1;\n" " mov.b64 re, {e0, e1}; add.rn.f32x2 ra, ra, re; mov.b64 {%1, %2}, ra;\n" " cvt.rn.f16x2.f32 %0, e1, e0; }" : "=r"(pk), "+f"(acc.x), "+f"(acc.y) : "f"(s0), "f"(s1), "f"(ks.x), "f"(ks.y), "f"(nb.x), "f"(nb.y), "f"(12582912.f), "f"(-12582912.f), "f"(0.05508877f), "f"(0.24260466f), "f"(0.69327628f), "f"(0.9999289f), "f"(-126.f)); } else { asm("{ .reg .b64 rs, rk, rn, rt, rx, rm, rmn, rr, rj, rf, rp, kb, kc, kd, ra, re;\n" " .reg .f32 t0, t1, x0, x1, r0, r1, p0, p1, e0, e1; .reg .b32 u0, u1, v0, v1;\n" " mov.b64 rs, {%3, %4}; mov.b64 rk, {%5, %6}; mov.b64 rn, {%7, %8}; mov.b64 ra, {%1, %2};\n" " mov.b64 rm, {%9, %9}; mov.b64 rmn, {%10, %10};\n" " mov.b64 kb, {%11, %11}; mov.b64 kc, {%12, %12}; mov.b64 kd, {%13, %13};\n" " fma.rn.f32x2 rt, rs, rk, rn; mov.b64 {t0, t1}, rt;\n" " max.f32 x0, t0, %14; max.f32 x1, t1, %14; mov.b64 rx, {x0, x1};\n" " add.rn.f32x2 rr, rx, rm; add.rn.f32x2 rj, rr, rmn; sub.rn.f32x2 rf, rx, rj;\n" " fma.rn.f32x2 rp, kb, rf, kc; fma.rn.f32x2 rp, rp, rf, kd;\n" " mov.b64 {p0, p1}, rp; mov.b64 {r0, r1}, rr;\n" " mov.b32 u0, p0; mov.b32 u1, p1; mov.b32 v0, r0; mov.b32 v1, r1;\n" " shl.b32 v0, v0, 23; shl.b32 v1, v1, 23; add.u32 u0, u0, v0; add.u32 u1, u1, v1;\n" " mov.b32 e0, u0; mov.b32 e1, u1;\n" " mov.b64 re, {e0, e1}; add.rn.f32x2 ra, ra, re; mov.b64 {%1, %2}, ra;\n" " cvt.rn.f16x2.f32 %0, e1, e0; }" : "=r"(pk), "+f"(acc.x), "+f"(acc.y) : "f"(s0), "f"(s1), "f"(ks.x), "f"(ks.y), "f"(nb.x), "f"(nb.y), "f"(12582912.f), "f"(-12582912.f), "f"(0.23842119f), "f"(0.70343379f), "f"(1.00044259f), "f"(-126.f)); } return pk;}// same bytes as kernel.cu cvt_e5m2x4p (byte 0 = a)__device__ __forceinline__ uint32_t cvt_e5m2x4p(uint32_t a, uint32_t b, uint32_t c, uint32_t d) { uint32_t r; asm("{ .reg .b16 lo, hi; cvt.rn.satfinite.e5m2x2.f32 lo, %2, %1; cvt.rn.satfinite.e5m2x2.f32 hi, %4, %3;\n" " mov.b32 %0, {lo, hi}; }" : "=r"(r) : "f"(__uint_as_float(a)), "f"(__uint_as_float(b)), "f"(__uint_as_float(c)), "f"(__uint_as_float(d))); return r;}constexpr int TILE = 128 * 128 * 2; // one 128 x 128 fp16 tile (32 KB)// smem: Q0 | Q1 | K ring (2 x 32 KB) | V^T ring (2 x 32 KB) | barriers. Separate K / V rings: K (needed by the S// MMAs one kv tile before PV needs V) is released right after the S MMAs, so the next K load is not held back by// the PVs of the current tile.// NS = K / V ring depth (template). NS = 3 requires the FP8 QK^T mode (16 KB Q / K tiles):// Q0|Q1 32 KB + K 3 x 16 KB + V^T 3 x 32 KB = 176 KB; NS = 2 (fp16 QK) keeps the 192 KB layout.// KSN = K ring depth (default NS). fp16 QK^T: Fa4Cfg<3, 2> = 3-stage V^T ring + 2-stage K ring// (Q 64 KB + K 2 x 32 KB + V^T 3 x 32 KB = 224 KB); FP8: Fa4Cfg<3, 3> (16 KB Q / K tiles).// Q8 explicit; FP8 QK^T uses Fa4Cfg<2, 4, true> = 4-stage K ring (16 KB) + 2-stage V^T ring// (Q 32 KB + K 4 x 16 KB + V^T 2 x 32 KB = 160 KB): K stages refill earlier (S(j+1) issues before PV(j)).template <int NS, int KSN = NS, bool Q8 = (KSN >= 3)> struct Fa4Cfg { static constexpr int QT = Q8 ? TILE / 2 : TILE; // smem stride of one Q / K tile static constexpr int K_OFF = 2 * QT; static constexpr int V_OFF = K_OFF + KSN * QT; static constexpr int BAR_OFF = V_OFF + NS * TILE; // barriers use 224 B (dbg timestamps at +256 only in FA4_DBG builds): the FP8 config <2, 4, true> then needs // 165120 B (+ static + 1 KB reserved < 164 KB carve-out step) instead of 165376 B (-> 196 KB step): larger L1 static constexpr int SMEM = BAR_OFF + (FA4_DBG ? 512 : 256) + 1024; // + barriers + 1024 alignment slack // MCL (in-kernel mask classification): misc at BAR_OFF + 512, 64 KB mask tile buffer at BAR_OFF + 1024 static constexpr int MCL_OFF = BAR_OFF + 1024; static constexpr int SMEM_MCL = MCL_OFF + 65536 + 1024;};static_assert(Fa4Cfg<2, 4, true>::SMEM_MCL <= 232448 - 256, "fa4 MCL smem");static_assert(Fa4Cfg<2>::SMEM <= 232448 && Fa4Cfg<3>::SMEM <= 232448 && Fa4Cfg<3, 2>::SMEM <= 232448 && Fa4Cfg<2, 4, true>::SMEM <= 232448 && Fa4Cfg<3, 4, true>::SMEM <= 232448, "fa4 smem");constexpr int THREADS = 384;constexpr uint32_t IDESC = (1u << 4) | ((128u >> 3) << 17) | ((128u >> 4) << 24); // f32 acc, f16 A/B, M=N=128
template <int NS, int KSN = NS, bool Q8 = (KSN >= 3), int DEG = 3, bool MCL = false>__global__ void __launch_bounds__(THREADS, 1) fa4_attn_kernel(const __grid_constant__ CUtensorMap tmQ, const __grid_constant__ CUtensorMap tmK, const __grid_constant__ CUtensorMap tmV, const float* __restrict__ mask, const uint8_t* tcode, __half* __restrict__ out, int S, int nQT, int nKT, float sl2, int B, int* __restrict__ work_ctr, const sidew::MaskJob MJ, int qpt, const unsigned* __restrict__ vmax, const unsigned* __restrict__ qkb, const __grid_constant__ CUtensorMap tmM, int* rowctr, const float* pcg, const float* pcu, uint8_t* pscr, int* pctr, int pcap) { extern __shared__ uint8_t smem_raw[]; uint8_t* smem = (uint8_t*)(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; // CL (MCL instantiation): 2-CTA cluster. Cluster ticket ci (rank 0 fetches, publishes to both CTAs' item // slots); CTA r runs head-pair item 2 ci + r = the same (batch, q tile, kv head) with head pairs 2m + r -> both // CTAs stream IDENTICAL K / V^T tiles: rank 0 TMA-multicasts each K tile, each rank multicasts one V^T half-box, // so every K / V byte is read from L2 once per cluster instead of once per CTA. Same per-CTA math (bit-identical). constexpr bool CL = MCL; const uint32_t crank = CL ? cl_rank() : 0u; using CP = const volatile uint8_t*; // coherent code-byte loads (codes may be written in this kernel) constexpr int K_STAGES = KSN, V_STAGES = NS; using CF = Fa4Cfg<NS, KSN, Q8>; static_assert(KSN <= 4 && NS <= 3, "fa4 barrier arrays: K <= 4, V <= 3 stages"); constexpr int QT = CF::QT, K_OFF = CF::K_OFF, V_OFF = CF::V_OFF, BAR_OFF = CF::BAR_OFF; const int nQP = (nQT + 1) >> 1; // Tail-free schedule: items [0, nhead) are q-tile-PAIR items (qp = nQP-1 .. qpt, one head, Q0/Q1 = q tiles // 2qp, 2qp+1); items [nhead, total) are HEAD-PAIR items over the low q tiles qt = ntq-1 .. 0 (two q heads 2p, // 2p+1 of one kv group at the SAME q tile -> same K/V stream, both WGs equally long). Costs (kv steps) decrease // monotonically through the queue (LPT); the head-pair tail halves the item granularity where the dynamic // queue drains, so the last wave consists of many 1..few-kv-tile items instead of 2qp+2-tile pair items. const int ntq = 2 * qpt < nQT ? 2 * qpt : nQT; const int nhead = (nQP - qpt) * 32 * B; const int total_items = nhead + ntq * 16 * B;
#if FA4_DBG unsigned long long dacc[13];#pragma unroll for (int i = 0; i < 13; i++) dacc[i] = 0; const long long tstart = clock64();#endif const uint32_t sb = smem_u32(smem); const uint32_t bq_full = sb + BAR_OFF; // Q0 + Q1 landed const uint32_t bq_empty = sb + BAR_OFF + 8; // all S MMAs of an item done -> Q smem reusable const uint32_t bk_full = sb + BAR_OFF + 16; // [<=4] K tile landed const uint32_t bk_empty = sb + BAR_OFF + 48; // [<=4] released after the S MMAs of the kv tile const uint32_t bv_full = sb + BAR_OFF + 80; // [<=3] V^T tile landed const uint32_t bv_empty = sb + BAR_OFF + 104; // [<=3] released after PV1 of the kv tile const uint32_t bs_full = sb + BAR_OFF + 128; // [2] per q tile x: S_x ready const uint32_t bp_full = sb + BAR_OFF + 144; // [2] per q tile x: P_x published (4 softmax warps) const uint32_t bo_done = sb + BAR_OFF + 160; // [2] per q tile x: PV_x complete const uint32_t bit_full = sb + BAR_OFF + 176; // [2] work item slot published const uint32_t bit_empty = sb + BAR_OFF + 192; // [2] consumed (MMA thread + 8 softmax warps) const uint32_t tslot = sb + BAR_OFF + 208; volatile uint32_t* tslot_ptr = (volatile uint32_t*)(smem + BAR_OFF + 208); volatile int* item_slot = (volatile int*)(smem + BAR_OFF + 216); // int[2]#if FA4_DBG volatile long long* dbg_ts = (volatile long long*)(smem + BAR_OFF + 256); // [6] TMA issue timestamps#endif
if (threadIdx.x == 0) { mbar_init(bq_full, 1); mbar_init(bq_empty, 1); // CL: a K / V^T stage is refilled (by multicast from either CTA) only once BOTH CTAs' MMAs released it for (int i = 0; i < K_STAGES; i++) { mbar_init(bk_full + 8 * i, 1); mbar_init(bk_empty + 8 * i, CL ? 2 : 1); } for (int i = 0; i < V_STAGES; i++) { mbar_init(bv_full + 8 * i, 1); mbar_init(bv_empty + 8 * i, CL ? 2 : 1); } for (int i = 0; i < 2; i++) { mbar_init(bs_full + 8 * i, 1); mbar_init(bp_full + 8 * i, 4); mbar_init(bo_done + 8 * i, 1); mbar_init(bit_full + 8 * i, 1); mbar_init(bit_empty + 8 * i, CL ? 19 : 9); // CL leader: 9 local + 10 peer } asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmQ) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmK) : "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmV) : "memory"); if (MCL) { mbar_init(sb + BAR_OFF + 512, 1); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); asm volatile("prefetch.tensormap [%0];" ::"l"((uint64_t)&tmM) : "memory"); } } if (warp == 9) { asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(tslot), "r"(512)); asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); } tc_fence_before(); __syncthreads(); if (CL) cl_sync(); // peer barriers initialised before any remote arrive / multicast complete_tx tc_fence_after(); const uint32_t tbase = *tslot_ptr; if constexpr (!MCL) sidew::mask_acquire_steal(MJ); else (void)MJ; // the producer warp (8) fetches + publishes its first work item and scans its mask codes (side-stream // products, acquired above; work_ctr zeroed by prep_qkv, complete before the QKV grid triggered this launch) // BEFORE its griddepcontrol.wait; it waits right before the first Q / K / V TMA load (QKV outputs). if (warp != 8 && !(MCL && warp >= 10)) { // MCL: classifier warps read only the input mask (no PDL dependency) asm volatile("griddepcontrol.wait;" ::: "memory"); asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); } // FP8 QK^T: S_acc = (q sq) . (k sk) instead of (q 2^-6) . (k 2^-6): sl2 *= 2^-12 / (sq sk) (exact, powers of 2) const bool qk8 = qkb != nullptr; if (qk8) sl2 = sl2 * (1.f / 4096.f) / (qk8_scale(qkb, 0) * qk8_scale(qkb, 1)); const uint32_t qk_tile = qk8 ? TILE / 2 : TILE; // bytes of one Q / K tile#ifdef FA_PROBE if (threadIdx.x == 0) { unsigned long long t_; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t_)); g_fa4_t[0][blockIdx.x] = t_; }#endif
// item -> (q tile pair qp, batch b, head h); heaviest (largest qp, most causal kv tiles) first // item -> (q tile pair qp, batch b, q head h); heaviest (largest qp, most causal kv tiles) first // item -> (q tile qa / head ha for WG0, q tile qb / head hb for WG1, batch b); ha >> 3 == hb >> 3 always auto decode = [&](int item, int& qa, int& qb, int& b, int& ha, int& hb) { if (item < nhead) { const int per = 32 * B; const int qp = nQP - 1 - item / per; const int r = item - (item / per) * per; b = r >> 5; ha = hb = r & 31; qa = 2 * qp; qb = 2 * qp + 1; // qb may be == nQT (odd nQT): codes_of -> nullptr, never stored } else { const int t = item - nhead, per = 16 * B; const int qt = ntq - 1 - t / per; const int r = t - (t / per) * per; b = r >> 4; ha = (r & 15) * 2; hb = ha + 1; qa = qb = qt; } }; auto codes_of = [&](int b, int qt) -> CP { return qt < nQT ? tcode + ((size_t)b * nQT + qt) * nKT : nullptr; }; auto rot_of = [&](CP c0, CP c1, int h) -> int {#if FA4_ROT int klast = -1; for (int kt = 0; kt < nKT; kt++) if (c0[kt] || (c1 && c1[kt])) klast = kt; return ((h & 7) * (klast + 1)) >> 3;#else (void)c0; (void)c1; (void)h; return 0;#endif }; // causal kv bound: 1 + last kv tile active for c0 or c1 (0 = fully masked item). Backward scan, so for // causal masks every role stops at the diagonal instead of walking (and code-testing) all nKT tiles; with a // kv rotation (FA4_ROT) the full range is kept. auto kend_of = [&](CP c0, CP c1) -> int { int e = nKT; while (e > 0 && !(c0[e - 1] || (c1 && c1[e - 1]))) e--;#if FA4_ROT return e > 0 ? nKT : 0;#else return e;#endif }; // load-coalescing: warp-collective kend_of (all 32 lanes must call it). nKT <= 64: the code bytes of both // q tiles are read with 2 coalesced byte loads per lane + ballots (instead of up to nKT serial dependent loads // of the backward scan); identical result. nKT > 64: the scalar scan. auto kend_w = [&](CP c0, CP c1) -> int { if (nKT > 64) return kend_of(c0, c1); const int l0 = lane, l1 = lane + 32; const bool a0 = l0 < nKT && (c0[l0] != 0 || (c1 && c1[l0] != 0)); const bool a1 = l1 < nKT && (c0[l1] != 0 || (c1 && c1[l1] != 0)); const unsigned lo = __ballot_sync(0xffffffffu, a0), hi = __ballot_sync(0xffffffffu, a1); const int e = hi ? 64 - __clz(hi) : (lo ? 32 - __clz(lo) : 0);#if FA4_ROT return e > 0 ? nKT : 0;#else return e;#endif }; auto get_item = [&](int ic) -> int { const int slot = ic & 1; if (CL) { mbar_wait_cl(bit_full + 8 * slot, (ic >> 1) & 1); return 2 * item_slot[slot] + (int)crank; // slot holds the cluster ticket } mbar_wait(bit_full + 8 * slot, (ic >> 1) & 1); return item_slot[slot]; }; // item-slot release (one elected lane per consumer warp): CL -> the leader's bit_empty (it writes both slots) auto rel_item = [&](int ic) { if (CL) mbar_arrive_cl(mapa_sh(bit_empty + 8 * (ic & 1), 0)); else mbar_arrive(bit_empty + 8 * (ic & 1)); }; // MCL: warp-collective acquire of the classified mask rows (b, qa) / (b, qb) (lane 0 spins, warp sync orders) auto acq_rows = [&](int b, int qa, int qb) { if (lane == 0) {#pragma unroll 1 for (int x = 0; x < 2; x++) { const int qt = x ? qb : qa; if (qt >= nQT || (x && qb == qa)) continue; const int* rp = rowctr + 1 + b * nQT + qt; while (true) { int v; asm volatile("ld.acquire.gpu.global.b32 %0, [%1];" : "=r"(v) : "l"(rp) : "memory"); if (v >= nKT) break; __nanosleep(64); } } } __syncwarp(); };
if (warp >= 8) { asm volatile("setmaxnreg.dec.sync.aligned.u32 72;\n" ::: "memory"); if (warp == 8) { // ---------------- item fetch + TMA producer: the WHOLE warp loops (warp-uniform mbarrier waits); // lane 0 fetches the work item and broadcasts it, one elect.sync lane publishes it and issues // expect_tx + every TMA load int ks = 0, kph = 0, vs = 0, vph = 0, qi = 0; bool pdl_done = false; // Q/K/V TMA loads use the default L2 policy for (int ic = 0;; ic++) { int item; const int slot = ic & 1; if (CL && crank != 0) { item = get_item(ic); // ticket published by the leader __syncwarp(); if (elect_one()) rel_item(ic); __syncwarp(); } else { int item0 = 0; if (elect_one()) item0 = atomicAdd(work_ctr, 1); item = __shfl_sync(0xffffffffu, item0, 0); if (CL) mbar_wait_cl(bit_empty + 8 * slot, ((ic >> 1) & 1) ^ 1); // peer slot reads done else mbar_wait(bit_empty + 8 * slot, ((ic >> 1) & 1) ^ 1); __syncwarp(); if (elect_one()) { item_slot[slot] = item; if (CL) { // peer slot (DSMEM store) + remote release arrive on its bit_full const uint32_t ra = mapa_sh(smem_u32((const void*)(item_slot + slot)), 1); asm volatile("st.shared::cluster.u32 [%0], %1;" ::"r"(ra), "r"(item) : "memory"); mbar_arrive_cl(mapa_sh(bit_full + 8 * slot, 1)); } mbar_arrive(bit_full + 8 * slot); } __syncwarp(); if (CL) item = 2 * item; // leader runs item 2 ci } if (item >= total_items) break; int qa, qb, b, h, hb; decode(item, qa, qb, b, h, hb); if (MCL) acq_rows(b, qa, qb); CP c0 = codes_of(b, qa); CP c1 = codes_of(b, qb); const int kend = kend_w(c0, c1); if (kend == 0) continue; // fully masked for both q tiles: no loads, no MMAs if (!pdl_done) { // QKV outputs (q / k / V^T) needed from here on asm volatile("griddepcontrol.wait;" ::: "memory"); asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); pdl_done = true; } if (qi > 0) mbar_wait(bq_empty, (qi - 1) & 1); // previous item's S MMAs done reading Q __syncwarp(); if (elect_one()) { mbar_expect_tx(bq_full, 2 * qk_tile);#pragma unroll for (int x = 0; x < 2; x++) { // (Q1 rows past S belong to the next head / are OOB zero-filled: computed, never stored) const int qrow = (b * 32 + (x ? hb : h)) * S + (x ? qb : qa) * 128; tma_load_2d(sb + x * QT, &tmQ, 0, qrow, bq_full); if (!qk8) tma_load_2d(sb + x * QT + TILE / 2, &tmQ, 64, qrow, bq_full); } } __syncwarp(); qi++; const int kvh = h >> 3; // K runs one kv tile ahead of V: K(t0) K(t1) V(t0) K(t2) V(t1) ... V(tlast) auto load_k = [&](int kt) { DBG_T0(t5); mbar_wait_hint(bk_empty + 8 * ks, kph ^ 1); DBG_ADD(6, t5);#if FA4_DBG dbg_ts[ks] = clock64();#endif const uint32_t fb = bk_full + 8 * ks, dst = sb + K_OFF + ks * QT; const int krow = (b * 4 + kvh) * S + kt * 128; __syncwarp(); if (elect_one()) { mbar_expect_tx(fb, qk_tile); if (CL) { // qk8 (16 KB, one box): rank 0 multicasts the K tile into both CTAs if (crank == 0) tma_load_2d_mc(dst, &tmK, 0, krow, fb, (uint16_t)3); } else { tma_load_2d(dst, &tmK, 0, krow, fb); if (!qk8) tma_load_2d(dst + TILE / 2, &tmK, 64, krow, fb); } } __syncwarp(); if (++ks == K_STAGES) { ks = 0; kph ^= 1; } }; auto load_v = [&](int kt) { mbar_wait_hint(bv_empty + 8 * vs, vph ^ 1);#if FA4_DBG dbg_ts[4 + vs] = clock64();#endif const uint32_t fb = bv_full + 8 * vs, dst = sb + V_OFF + vs * TILE; const int vrow = (b * 4 + kvh) * 128; __syncwarp(); if (elect_one()) { mbar_expect_tx(fb, TILE); if (CL) { // rank r multicasts V^T half-box r (keys kt*128 + 64 r ..) into both CTAs tma_load_2d_mc(dst + crank * (TILE / 2), &tmV, kt * 128 + 64 * (int)crank, vrow, fb, (uint16_t)3); } else { tma_load_2d(dst, &tmV, kt * 128, vrow, fb); tma_load_2d(dst + TILE / 2, &tmV, kt * 128 + 64, vrow, fb); } } __syncwarp(); if (++vs == V_STAGES) { vs = 0; vph ^= 1; } }; int prev = -1; const int rot = rot_of(c0, c1, h); for (int ii = 0; ii < kend; ii++) { const int kt = ii + rot < nKT ? ii + rot : ii + rot - nKT; if (!(c0[kt] || (c1 && c1[kt]))) continue; load_k(kt); if (prev >= 0) load_v(prev); prev = kt; } if (prev >= 0) load_v(prev); } if (!pdl_done) { asm volatile("griddepcontrol.wait;" ::: "memory"); asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); } if (CL) { // drain: both CTAs' final multicast commits of every K / V^T stage landed here before exit for (int i = 0; i < K_STAGES; i++) { mbar_wait_cl(bk_empty + 8 * ks, kph ^ 1); if (++ks == K_STAGES) { ks = 0; kph ^= 1; } } for (int i = 0; i < V_STAGES; i++) { mbar_wait_cl(bv_empty + 8 * vs, vph ^ 1); if (++vs == V_STAGES) { vs = 0; vph ^= 1; } } } } else if (warp == 9) { int KT = 0, qi = 0; // KT: kv tiles consumed so far (ring index / parity) int npv[2] = {0, 0}; // PVs issued so far per q tile (= P_x index for bp_full parity) for (int ic = 0;; ic++) { const int item = get_item(ic); __syncwarp(); if (elect_one()) rel_item(ic); if (item >= total_items) break; int qa, qb, b, h, hb; decode(item, qa, qb, b, h, hb); if (MCL) acq_rows(b, qa, qb); CP c0 = codes_of(b, qa); CP c1 = codes_of(b, qb); // kv-tile activity of q tile 0 / 1 as 64-bit masks (one warp ballot per item, nKT <= 64) so the // issue loop does no dependent global code loads between MMA groups (issuer latency = tensor idle) const bool smallT = nKT <= 64; uint64_t m0 = 0, m1 = 0; if (smallT) { const int l0 = lane, l1 = lane + 32; const bool b00 = l0 < nKT && c0[l0] != 0, b01 = l1 < nKT && c0[l1] != 0; const bool b10 = c1 && l0 < nKT && c1[l0] != 0, b11 = c1 && l1 < nKT && c1[l1] != 0; m0 = (uint64_t)__ballot_sync(0xffffffffu, b00) | ((uint64_t)__ballot_sync(0xffffffffu, b01) << 32); m1 = (uint64_t)__ballot_sync(0xffffffffu, b10) | ((uint64_t)__ballot_sync(0xffffffffu, b11) << 32); } auto A0 = [&](int kt) -> bool { return smallT ? ((m0 >> kt) & 1ull) != 0 : c0[kt] != 0; }; auto A1 = [&](int kt) -> bool { return smallT ? ((m1 >> kt) & 1ull) != 0 : (c1 && c1[kt]); }; auto inL = [&](int kt) -> bool { return A0(kt) || A1(kt); }; const int rot = rot_of(c0, c1, h); auto ktof = [&](int ii) -> int { return ii + rot < nKT ? ii + rot : ii + rot - nKT; }; // kend from the ballot masks (no serial code-byte scan); FA4_ROT keeps the scalar path const int kend = (smallT && !FA4_ROT) ? ((m0 | m1) ? 64 - __clzll((long long)(m0 | m1)) : 0) : kend_of(c0, c1); auto nextI = [&](int ii) -> int { // next visiting index >= ii whose kv tile is active (kend = none) if (smallT && rot == 0) { if (ii >= kend) return kend; const uint64_t r = (m0 | m1) & (~0ull << ii); const int f = r ? __ffsll((long long)r) - 1 : kend; return f < kend ? f : kend; } while (ii < kend && !inL(ktof(ii))) ii++; return ii; }; int ii = nextI(0); if (ii >= kend) continue; int kt = ktof(ii); DBG_T0(t4); mbar_wait(bq_full, qi & 1); DBG_ADD(5, t4); qi++; // S_x = Q_x K^T for the kv tile in ring stage st (8 x m128n128k16 SS MMAs into S buffer x) auto issue_S = [&](int x, int st) { const uint32_t kb = sb + K_OFF + st * QT; const uint32_t qb = sb + x * QT; const uint32_t d = tbase + x * 128; const uint64_t qd = make_sdesc(qb), kd = make_sdesc(kb); __syncwarp(); if (elect_one()) { if (qk8) {#pragma unroll for (int kk = 0; kk < 4; kk++) // 128 e4m3 = one 128 B row: K = 32 (32 B) per MMA mma_f8_ss(d, qd + 2 * kk, kd + 2 * kk, IDESC, kk > 0); } else {#pragma unroll for (int kk = 0; kk < 8; kk++) { const uint32_t off = ((kk >> 2) * (TILE / 2) + (kk & 3) * 32) >> 4; // descriptor units mma_f16_ss(d, qd + off, kd + off, IDESC, kk > 0); } } mma_commit(bs_full + 8 * x); } __syncwarp(); }; { const int st = KT % K_STAGES; mbar_wait(bk_full + 8 * st, (KT / K_STAGES) & 1); tc_fence_after(); if (A0(kt)) issue_S(0, st); if (A1(kt)) issue_S(1, st); if (elect_one()) { if (CL) mma_commit_mc(bk_empty + 8 * st, 3); else mma_commit(bk_empty + 8 * st); } // K stage free once these S MMAs complete __syncwarp(); } bool started[2] = {false, false}; while (ii < kend) { const int iin = nextI(ii + 1); const int kn = iin < kend ? ktof(iin) : nKT; const int vst = KT % V_STAGES, kstn = (KT + 1) % K_STAGES; DBG_CNT(7); DBG_T0(t3); if (kn < nKT) mbar_wait_fast(bk_full + 8 * kstn, ((KT + 1) / K_STAGES) & 1); else { if (elect_one()) mma_commit(bq_empty); // every S MMA of this item has been issued __syncwarp(); } DBG_ADD(4, t3);#if FA4_DBG if (kn < nKT) dacc[9] += (unsigned long long)(clock64() - dbg_ts[kstn]);#endif DBG_T0(t7); mbar_wait_fast(bv_full + 8 * vst, (KT / V_STAGES) & 1); DBG_ADD(10, t7);#if FA4_DBG dacc[11] += (unsigned long long)(clock64() - dbg_ts[4 + vst]);#endif#pragma unroll for (int x = 0; x < 2; x++) { const bool has = x == 0 ? A0(kt) : A1(kt); if (has) { // O_x += P_x V (A = P_x from TMEM S cols [0,64) of buffer x, B = V^T smem) DBG_T0(t2); // P-published wait as plain try_wait (no suspend hint). HS probe (1x8192, clock64 per // link): last softmax arrive -> issuer wake 385 cyc/PV with the suspend-hinted wait (largest // handshake link; S issue->softmax wake 392 incl. MMA exec, ld128 150, st+wait::st+fence 158) mbar_wait(bp_full + 8 * x, npv[x] & 1); DBG_ADD(3, t2); tc_fence_after(); const uint32_t vb = sb + V_OFF + vst * TILE; const uint32_t ptm = tbase + x * 128; const uint32_t ot = tbase + 256 + x * 128; const uint32_t acc0 = started[x] ? 1u : 0u; const uint64_t vd = make_sdesc(vb); __syncwarp(); if (elect_one()) {#pragma unroll for (int kk = 0; kk < 8; kk++) { const uint32_t off = ((kk >> 2) * (TILE / 2) + (kk & 3) * 32) >> 4; mma_f16_ts(ot, ptm + kk * 8, vd + off, IDESC, (acc0 || kk > 0) ? 1u : 0u); } mma_commit(bo_done + 8 * x); } __syncwarp(); started[x] = true; npv[x]++; } if (x == 1) { if (elect_one()) { if (CL) mma_commit_mc(bv_empty + 8 * vst, 3); else mma_commit(bv_empty + 8 * vst); } // both q tiles consumed this V stage __syncwarp(); } if (kn < nKT) { const bool hn = x == 0 ? A0(kn) : A1(kn); if (hn) { tc_fence_after(); issue_S(x, kstn); } } } if (kn < nKT) { if (elect_one()) { if (CL) mma_commit_mc(bk_empty + 8 * kstn, 3); else mma_commit(bk_empty + 8 * kstn); } // S MMAs of tile kn issued __syncwarp(); } KT++; ii = iin; kt = kn; } } } if constexpr (MCL) { if (warp >= 10) { // ---------------- mask classifier warps 10, 11 (64 threads). Unit u (ticket) -> mask row k = u / nKT // (q tile qt = nQT-1 - k / B, batch b = k % B: the order in which LPT items need the rows), kv tile // kt = u % nKT. One 3D TMA box (128 x 128 fp32, OOB zero-filled) per unit into the 64 KB buffer (row r // at +512 r); warp w classifies tile rows 64w..64w+63, lane = 4 columns; same expressions / codes / // compact log2e tiles as mask_bulk_tile. const int w = warp - 10, ct = (warp - 10) * 32 + lane; const uint32_t mbar = sb + BAR_OFF + 512, mbuf = sb + CF::MCL_OFF; volatile int* s_u = (volatile int*)(smem + BAR_OFF + 520); volatile int* flg = (volatile int*)(smem + BAR_OFF + 528); // [3][2] const uint8_t* mtl = smem + CF::MCL_OFF; const int nRows = B * nQT, nU = nRows * nKT; uint8_t* codes_w = const_cast<uint8_t*>(tcode); float* mtile_w = const_cast<float*>(mask); uint32_t mph = 0; for (;;) { if (ct == 0) *s_u = atomicAdd(rowctr, 1); asm volatile("bar.sync 9, 64;" ::: "memory"); // ticket visible; previous tile's smem reads done const int u = *s_u; if (u >= nU) break; const int k = u / nKT, kt = u - k * nKT; const int qt = nQT - 1 - k / B, b = k - (k / B) * B; if (ct == 0) { asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); mbar_expect_tx(mbar, 65536u); asm volatile( "cp.async.bulk.tensor.3d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4}], [%5], %6;" ::"r"(mbuf), "l"((uint64_t)&tmM), "r"(kt * 128), "r"(qt * 128), "r"(b), "r"(mbar), "l"(first_pol()) : "memory"); } __syncwarp(); mbar_wait(mbar, mph); mph ^= 1u; const int nrows = S - qt * 128 < 128 ? S - qt * 128 : 128; const int ncols = S - kt * 128 < 128 ? S - kt * 128 : 128; const int gc0 = kt * 128 + lane * 4, r0 = qt * 128 + 64 * w; const uint8_t* tw = mtl + (size_t)(64 * w) * 512 + lane * 16; // row 64w + i at + 512 i int notneg = 0, nonzero = 0, notcausal = 0; if (kt != qt && nrows == 128 && ncols == 128) { uint32_t on = 0u, oz = 0u;#pragma unroll 8 for (int i = 0; i < 64; i++) { const uint4 xv = *reinterpret_cast<const uint4*>(tw + 512 * i); on |= (xv.x ^ 0xFF800000u) | (xv.y ^ 0xFF800000u) | (xv.z ^ 0xFF800000u) | (xv.w ^ 0xFF800000u); oz |= xv.x | xv.y | xv.z | xv.w; } const uint32_t won = __reduce_or_sync(0xffffffffu, on), woz = __reduce_or_sync(0xffffffffu, oz & 0x7FFFFFFFu); notneg = won != 0u; nonzero = woz != 0u; notcausal = kt > qt ? notneg : nonzero; } else {#pragma unroll 4 for (int i = 0; i < 64; i++) { if (r0 + i >= S || gc0 >= S) continue; const float4 mv = *reinterpret_cast<const float4*>(tw + 512 * i); const float v[4] = {mv.x, mv.y, mv.z, mv.w};#pragma unroll for (int e = 0; e < 4; e++) { if (gc0 + e < S) { notneg |= v[e] != -INFINITY; nonzero |= v[e] != 0.f; notcausal |= (gc0 + e > r0 + i) ? (v[e] != -INFINITY) : (v[e] != 0.f); } } } } const int wn = __any_sync(0xffffffffu, notneg), wz = __any_sync(0xffffffffu, nonzero), wc = __any_sync(0xffffffffu, notcausal); if (lane == 0) { flg[w] = wn; flg[2 + w] = wz; flg[4 + w] = wc; } asm volatile("bar.sync 9, 64;" ::: "memory"); const int an = flg[0] | flg[1], az = flg[2] | flg[3], ac = flg[4] | flg[5]; const bool partial = (kt * 128 + 128 > S); const uint8_t code = !an ? 0 : ((!az && !partial) ? 1 : (!ac ? 3 : 2)); if (ct == 0) codes_w[((size_t)b * nQT + qt) * nKT + kt] = code; if (code == 2) { const float LOG2E = 1.4426950408889634f; float4* dst = reinterpret_cast<float4*>(mtile_w + (((size_t)b * nQT + qt) * nKT + kt) * 16384) + lane * 128 + 64 * w;#pragma unroll 4 for (int i = 0; i < 64; i++) { const bool rok = r0 + i < S; float4 mv = make_float4(0.f, 0.f, 0.f, 0.f); if (rok && gc0 < S) mv = *reinterpret_cast<const float4*>(tw + 512 * i); const float v[4] = {mv.x, mv.y, mv.z, mv.w}; float o[4];#pragma unroll for (int e = 0; e < 4; e++) o[e] = gc0 + e >= S ? -INFINITY : (rok ? v[e] * LOG2E : 0.f); dst[i] = make_float4(o[0], o[1], o[2], o[3]); } } asm volatile("bar.sync 9, 64;" ::: "memory"); // both warps' code / tile stores before the release if (ct == 0) asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(rowctr + 1 + b * nQT + qt), "r"(1) : "memory"); } // MoE weight pre-conversion while attention runs (DRAM mostly idle). Warp-level tickets of 4 rows // of expert gate|up (expert e = ticket / 384, rows 0..767 gate, 768..1535 up), fp32 -> e5m2 (same // cvt as the MoE converters) into the persistent scratch [2][pcap * 768][2048] bytes; per-expert // completed-row counters pctr[1 + e] (target 1536). New tickets stop once every attention work item // has been handed out (the remaining experts are converted in-stream by the MoE as before). if (pscr != nullptr) { const int ntk = pcap * 384;#pragma unroll 1 for (;;) { int tk = ntk; if (lane == 0) { int wc; asm volatile("ld.relaxed.gpu.global.b32 %0, [%1];" : "=r"(wc) : "l"(work_ctr) : "memory"); if (2 * wc < total_items) tk = atomicAdd(pctr, 1); } tk = __shfl_sync(0xffffffffu, tk, 0); if (tk >= ntk) break; const int e = tk / 384, rb = (tk - e * 384) * 4;#pragma unroll 1 for (int rr = 0; rr < 4; rr++) { const int row = rb + rr, tn = row >= 768 ? 1 : 0, rw = row - 768 * tn; const float4* src = reinterpret_cast<const float4*>((tn ? pcu : pcg) + ((size_t)e * 768 + rw) * 2048); uint32_t* dst = reinterpret_cast<uint32_t*>(pscr + ((size_t)tn * pcap * 768 + (size_t)e * 768 + rw) * 2048);#pragma unroll 1 for (int hh = 0; hh < 2; hh++) { float4 v[8];#pragma unroll for (int i = 0; i < 8; i++) asm volatile("ld.global.nc.L1::no_allocate.L2::cache_hint.v4.f32 {%0,%1,%2,%3}, [%4], %5;" : "=f"(v[i].x), "=f"(v[i].y), "=f"(v[i].z), "=f"(v[i].w) : "l"(src + hh * 256 + lane + 32 * i), "l"(first_pol()));#pragma unroll for (int i = 0; i < 8; i++) dst[hh * 256 + lane + 32 * i] = cvt_e5m2x4p(__float_as_uint(v[i].x), __float_as_uint(v[i].y), __float_as_uint(v[i].z), __float_as_uint(v[i].w)); } } __syncwarp(); if (lane == 0) asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(pctr + 1 + e), "r"(4) : "memory"); } } } } } else { asm volatile("setmaxnreg.inc.sync.aligned.u32 216;\n" ::: "memory"); // ---------------- softmax warpgroup x (q tile x of the item); thread = query row (TMEM lane) const int x = warp >> 2; const int q = warp & 3; const int row = q * 32 + lane; const uint32_t tl = tbase + ((uint32_t)(q * 32) << 16); const uint32_t sbuf = tl + x * 128, obuf = tl + 256 + x * 128; const uint32_t bsf = bs_full + 8 * x, bpf = bp_full + 8 * x, bod = bo_done + 8 * x; int ns = 0; // S tiles of q tile x consumed so far (barrier parity) // global fp8 output scale hoisted out of the per-item epilogue (vmax final: QKV done, PDL wait above) const float vsc8 = vmax ? f8_scale(__uint_as_float(*vmax) * 0.0009765625f, 7) : 0.f; for (int ic = 0;; ic++) { const int item = get_item(ic); __syncwarp(); if (elect_one()) rel_item(ic); if (item >= total_items) break; int qa, qb, b, ha, hb; decode(item, qa, qb, b, ha, hb); const int qt = x ? qb : qa, h = x ? hb : ha; if (MCL) acq_rows(b, qa, qb); CP cx = codes_of(b, qt); const int grow = qt * 128 + row; float m_used = -INFINITY, l = 0.f; int j = 0; if (cx) { const int rot = rot_of(codes_of(b, qa), codes_of(b, qb), ha); const int kendx = kend_w(cx, nullptr); for (int ii = 0; ii < kendx; ii++) { const int kt = ii + rot < nKT ? ii + rot : ii + rot - nKT; const int code = cx[kt]; if (!code) continue; DBG_T0(t0); mbar_wait(bsf, ns & 1); // plain try_wait (no suspend hint) on the S-ready critical path if (lane == 0) DBG_ADD(0, t0); DBG_T0(t1); tc_fence_after(); float s[128]; // whole S row with ONE tcgen05.ld x128 + one wait (was 4 x32 loads / 2 waits) tmem_ld128(sbuf, s); // row max: 4 independent 3-input-max accumulators (each max3 folds 2 scores). code 1 tiles keep // raw scores (scale folded into the exp FFMA2, ks = sl2); code 2 tiles are scaled + masked here // with packed FFMA2 (ks = 1). float mxa[4];#pragma unroll for (int i = 0; i < 4; i++) mxa[i] = -INFINITY; float ks; if (code == 2) { // compact log2e-prescaled mask tile: float4 unit g*128 + row = cols 4g..4g+3 of this row ks = 1.f; const float4* mt = reinterpret_cast<const float4*>(mask + (((size_t)b * nQT + qt) * nKT + kt) * 16384) + row; const float2 sl2v = make_float2(sl2, sl2);#pragma unroll for (int c = 0; c < 8; c++) { float4 mv[4];#pragma unroll for (int i = 0; i < 4; i++) mv[i] = __ldg(mt + (4 * c + i) * 128);#pragma unroll for (int i = 0; i < 4; i++) { const int col = 16 * c + 4 * i; const float2 x0 = ffma2(make_float2(s[col], s[col + 1]), sl2v, make_float2(mv[i].x, mv[i].y)); const float2 x1 = ffma2(make_float2(s[col + 2], s[col + 3]), sl2v, make_float2(mv[i].z, mv[i].w)); s[col] = x0.x; s[col + 1] = x0.y; s[col + 2] = x1.x; s[col + 3] = x1.y; mxa[(2 * i) & 3] = fmax3(mxa[(2 * i) & 3], x0.x, x0.y); mxa[(2 * i + 1) & 3] = fmax3(mxa[(2 * i + 1) & 3], x1.x, x1.y); } } } else if (code == 3) { // causal tile: key gc masked iff gc > query row or gc >= S (index compare, no mask load). // raw scores kept (as code 1) - the sl2 scale is folded into the exp-argument FFMA2 // (ks = sl2) and into the row max (mx *= sl2, exact: rounding is monotone), saving one FMUL2 // per score pair on diagonal tiles ks = sl2; const int cl = (grow < S ? grow : S - 1) - kt * 128; // last unmasked column of the tile#pragma unroll for (int c = 0; c < 64; c++) { s[2 * c] = 2 * c > cl ? -INFINITY : s[2 * c]; s[2 * c + 1] = 2 * c + 1 > cl ? -INFINITY : s[2 * c + 1]; mxa[c & 3] = fmax3(mxa[c & 3], s[2 * c], s[2 * c + 1]); } } else { ks = sl2;#pragma unroll for (int c = 0; c < 64; c++) mxa[c & 3] = fmax3(mxa[c & 3], s[2 * c], s[2 * c + 1]); } float mx = fmax3(fmax3(mxa[0], mxa[1], mxa[2]), mxa[3], -INFINITY); if (code == 1 || code == 3) mx *= sl2; const float m_new = fmaxf(m_used, mx); const bool need = m_new > m_used + 11.f; // lazy-rescale threshold 2^8 -> 2^11 (P <= 2048 in fp16, fewer O rescales) // alpha / m_used / l updated here (exp base), but the O correction TMEM round trips are // issued AFTER the P tcgen05.st below, so they overlap the async P store (one final wait::st). // PV_x(j) reads O only after bp_full, which is arrived after both. Same products -> bit-identical. float alpha = 1.f; bool resc = false; if (__any_sync(0xffffffff, need)) { alpha = need ? fast_exp2(m_used - m_new) : 1.f; if (need) { l *= alpha; m_used = m_new; } resc = j > 0; } const float base = m_used == -INFINITY ? 0.f : m_used; // packed: x*ks - base as FFMA2, row sum as FADD2 into 4 pair accumulators float2 rsa[4];#pragma unroll for (int i = 0; i < 4; i++) rsa[i] = make_float2(0.f, 0.f); const float2 ksv = make_float2(ks, ks), nbv = make_float2(-base, -base);#pragma unroll { float pk[64];#pragma unroll for (int i = 0; i < 64; i++) { // MUFU offload (1/4): pairs i % 4 == 0 (compile-time, warp-uniform) use the FMA-pipe // polynomial, the rest MUFU ex2.approx.f32 (fused asm block, ) if ((i & 3) == 0) { pk[i] = __uint_as_float(sm_poly_pack<DEG>(s[2 * i], s[2 * i + 1], ksv, nbv, rsa[0])); } else { pk[i] = __uint_as_float(sm_exp_pack(s[2 * i], s[2 * i + 1], ksv, nbv, rsa[i & 3])); } } tmem_st64(sbuf, pk); } if (resc) { // previous PV_x complete (implied by S_x(j) completion; explicit wait for ordering) mbar_wait(bod, (ns - 1) & 1); tc_fence_after();#pragma unroll 1 for (int c = 0; c < 4; c++) { // 32-col chunks float o[32]; tmem_ld32(obuf + c * 32, o);#pragma unroll for (int i = 0; i < 16; i++) { // packed FMUL2 correction const float2 r2 = fmul2(make_float2(o[2 * i], o[2 * i + 1]), make_float2(alpha, alpha)); o[2 * i] = r2.x; o[2 * i + 1] = r2.y; } tmem_st32(obuf + c * 32, o); } } l += ((rsa[0].x + rsa[0].y) + (rsa[1].x + rsa[1].y)) + ((rsa[2].x + rsa[2].y) + (rsa[3].x + rsa[3].y)); asm volatile("tcgen05.wait::st.sync.aligned;" ::: "memory"); tc_fence_before(); __syncwarp(); if (elect_one()) mbar_arrive(bpf); if (lane == 0) { DBG_ADD(1, t1); DBG_CNT(2); } ns++; j++; } } DBG_T0(t6); // ---- epilogue: O / l as fp16 [B*S, 4096] (V's x 2^-10 kept; undone by o_proj) const float inv = 1.f / l; if (j > 0) { mbar_wait(bod, (ns - 1) & 1); // last PV of this q tile, plain try_wait (epilogue critical path) tc_fence_after(); }#pragma unroll 1 for (int c = 0; c < 4; c += 2) { float o[64]; if (j > 0) tmem_ld32x2(obuf + c * 32, o, obuf + c * 32 + 32, o + 32); else {#pragma unroll for (int i = 0; i < 64; i++) o[i] = 0.f; } if (vmax) { // fp8: 64 columns -> 64 e4m3 bytes (|O| <= max|V| -> |O * sa| < 2^7). coalesced store - the 4 // 16 B units of this thread's 64 B are transposed inside each 4-lane group (2 xor-shuffle rounds, // warp-uniform), so lane g holds unit g of the group's 4 consecutive rows and every st.v4 writes // 8 rows x 64 contiguous bytes (full sectors) instead of 32 rows x 16 B. const float sc8 = j > 0 ? inv * vsc8 : 0.f; uint4 u[4];#pragma unroll for (int i = 0; i < 4; i++) { const float* oi = o + 16 * i; const float2 s2 = make_float2(sc8, sc8); u[i] = make_uint4(e4m3x4_s(oi, s2), e4m3x4_s(oi + 4, s2), e4m3x4_s(oi + 8, s2), e4m3x4_s(oi + 12, s2)); }#pragma unroll for (int m = 1; m <= 2; m <<= 1) { const bool bit = (lane & m) != 0;#pragma unroll for (int c0 = 0; c0 < 4; c0++) { if (c0 & m) continue; const int c1 = c0 | m; // bit-0 lane keeps unit c0, bit-1 lane keeps unit c1 const uint4 snd = bit ? u[c0] : u[c1]; uint4 rcv; rcv.x = __shfl_xor_sync(0xffffffffu, snd.x, m); rcv.y = __shfl_xor_sync(0xffffffffu, snd.y, m); rcv.z = __shfl_xor_sync(0xffffffffu, snd.z, m); rcv.w = __shfl_xor_sync(0xffffffffu, snd.w, m); if (bit) u[c0] = rcv; else u[c1] = rcv; } } // u[i] = unit (lane & 3) of row (grow - (lane & 3)) + i const int g4 = lane & 3, rb = grow - g4;#pragma unroll for (int i = 0; i < 4; i++) { if (rb + i < S) { uint4* dst8 = reinterpret_cast<uint4*>(reinterpret_cast<uint8_t*>(out) + ((size_t)b * S + rb + i) * 4096 + h * 128 + c * 32) + g4; *dst8 = u[i]; } } } else { // fp16: this thread's 64 columns = 8 x 16 B units; per group of 4 units a 4x4 transpose // inside each 4-lane group (2 xor-shuffle rounds, all lanes participate) leaves lane g holding unit // g of the group's 4 consecutive rows -> each st.v4 writes 8 rows x 64 contiguous bytes (full // sectors) instead of 32 rows x 16 B. Bit-identical bytes to the per-row store. const float sc = j > 0 ? inv : 0.f; const int g4 = lane & 3, rb = grow - g4;#pragma unroll for (int gq = 0; gq < 2; gq++) { uint4 u[4];#pragma unroll for (int i = 0; i < 4; i++) { const float* oi = o + 8 * (4 * gq + i); const float2 s2 = make_float2(sc, sc); u[i].x = h2_s(oi, s2); u[i].y = h2_s(oi + 2, s2); u[i].z = h2_s(oi + 4, s2); u[i].w = h2_s(oi + 6, s2); }#pragma unroll for (int m = 1; m <= 2; m <<= 1) { const bool bit = (lane & m) != 0;#pragma unroll for (int c0 = 0; c0 < 4; c0++) { if (c0 & m) continue; const int c1 = c0 | m; const uint4 snd = bit ? u[c0] : u[c1]; uint4 rcv; rcv.x = __shfl_xor_sync(0xffffffffu, snd.x, m); rcv.y = __shfl_xor_sync(0xffffffffu, snd.y, m); rcv.z = __shfl_xor_sync(0xffffffffu, snd.z, m); rcv.w = __shfl_xor_sync(0xffffffffu, snd.w, m); if (bit) u[c0] = rcv; else u[c1] = rcv; } } // u[i] = unit (4 gq + g4) of row rb + i#pragma unroll for (int i = 0; i < 4; i++) { if (rb + i < S) { uint4* dst = reinterpret_cast<uint4*>(out + ((size_t)b * S + rb + i) * 4096 + h * 128 + c * 32) + 4 * gq + g4; *dst = u[i]; // attn (default L2 policy) } } } } } tc_fence_before(); // O reads ordered before the next item's P publish (-> PV overwrite of O) if (lane == 0) DBG_ADD(8, t6); } }#if FA4_DBG if (threadIdx.x == 0) dacc[12] = (unsigned long long)(clock64() - tstart); if (lane == 0) for (int i = 0; i < 13; i++) if (dacc[i]) atomicAdd(&g_dbg[i], dacc[i]);#endif tc_fence_before(); __syncthreads(); if (CL) cl_sync(); // peer done with every remote arrive / multicast into this CTA before exit#ifdef FA_PROBE if (threadIdx.x == 0) { unsigned long long t_; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t_)); g_fa4_t[1][blockIdx.x] = t_; }#endif if (warp == 9) { __syncwarp(); tc_fence_after(); asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, %1;" ::"r"(tbase), "r"(512)); }}} // namespace fa4
static int g_fa4_last_ncl;int g_fa4_qpt_override = -1;int g_fa4_thr = 6; // head-pair tail >= 6 x #SMs items// Host launcher (PDL-chained). Maps: Q [B*32*S, 128] fp16 box 128 rows, K [B*4*S, 128], V^T [B*4*128, Spad].void launch_fa4_attn(const CUtensorMap& mq, const CUtensorMap& mk, const CUtensorMap& mv, const float* mask, const uint8_t* codes, __half* out, int B, int S, float sl2, int* work_ctr, const sidew::MaskJob* mj, int nsm, cudaStream_t s, const unsigned* vmax, const unsigned* qkb, const CUtensorMap* mmap, int* rowctr, const float* pcg, const float* pcu, uint8_t* pscr, int* pctr, int pcap) { static bool attr = false; if (!attr) { cudaFuncSetAttribute(fa4::fa4_attn_kernel<2, 4, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, fa4::Fa4Cfg<2, 4, true>::SMEM); cudaFuncSetAttribute(fa4::fa4_attn_kernel<2, 4, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, fa4::Fa4Cfg<2, 4, true>::SMEM); cudaFuncSetAttribute(fa4::fa4_attn_kernel<3, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, fa4::Fa4Cfg<3, 2>::SMEM); cudaFuncSetAttribute(fa4::fa4_attn_kernel<3, 4, true, 2>, cudaFuncAttributeMaxDynamicSharedMemorySize, fa4::Fa4Cfg<3, 4, true>::SMEM); cudaFuncSetAttribute(fa4::fa4_attn_kernel<3, 4, true, 3>, cudaFuncAttributeMaxDynamicSharedMemorySize, fa4::Fa4Cfg<3, 4, true>::SMEM); cudaFuncSetAttribute(fa4::fa4_attn_kernel<2, 4, true, 3, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, fa4::Fa4Cfg<2, 4, true>::SMEM_MCL); cudaFuncSetAttribute(fa4::fa4_attn_kernel<2, 4, true, 2, true>, cudaFuncAttributeMaxDynamicSharedMemorySize, fa4::Fa4Cfg<2, 4, true>::SMEM_MCL); attr = true; } // FP8 QK^T (16 KB Q / K tiles) -> 4-stage K ring + 2-stage V^T ring (was 3/3), and ALL items head-pair (two q heads of one kv // group x one q tile: both softmax WGs see identical kv-step counts / causal-diagonal work) const bool ns3 = qkb != nullptr; const int nT = (S + 127) / 128; // tail split point: smallest qpt whose head-pair tail holds >= 3 x #SMs items (all head-pair if never) const int nQP = (nT + 1) / 2; int qpt = 0; while (qpt < nQP && (2 * qpt < nT ? 2 * qpt : nT) * 16 * B < g_fa4_thr * nsm) qpt++; qpt = nQP; // all items head-pair for fp16 QK^T as well if (g_fa4_qpt_override >= 0) qpt = g_fa4_qpt_override < nQP ? g_fa4_qpt_override : nQP; const int ntq = 2 * qpt < nT ? 2 * qpt : nT; const int items = (nQP - qpt) * 32 * B + ntq * 16 * B; const int grid = items < nsm ? items : nsm; cudaLaunchConfig_t cfg = {}; const bool v3 = ns3 && S >= 2048 && S <= 4096; const bool v3d3 = ns3 && S >= 300 && S < 2048 && B * S < 6000; // FP8-QK short-S many-batch band (S < 300, T >= 6000: 32x256 class, nKT <= 2 kv tiles per item): 3-stage // V^T ring so the next item's V^T tiles are in flight under the current item's PVs; degree-3 exp2 kept (numerics identical) const bool v3s = ns3 && S < 300 && B * S >= 6000; cfg.gridDim = dim3(grid); cfg.blockDim = dim3(fa4::THREADS); cfg.dynamicSmemBytes = (v3 || v3d3 || v3s) ? fa4::Fa4Cfg<3, 4, true>::SMEM : ns3 ? fa4::Fa4Cfg<2, 4, true>::SMEM : fa4::Fa4Cfg<3, 2>::SMEM; cfg.stream = s; cudaLaunchAttribute at[1]; at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; at[0].val.programmaticStreamSerializationAllowed = 1; cfg.attrs = at; cfg.numAttrs = 1; g_fa4_last_ncl = grid; const bool d2 = ns3 && S >= 2048 && S <= 4096; // in-kernel mask classification (host-gated: S > 4096, S % 4 == 0, FP8 QK^T; the side mask grid is skipped) const bool mcl = mmap != nullptr && rowctr != nullptr && ns3 && !v3 && !v3d3 && !v3s && !d2; cudaLaunchAttribute at2[2]; if (mcl) { cfg.dynamicSmemBytes = fa4::Fa4Cfg<2, 4, true>::SMEM_MCL; // 2-CTA clusters (K / V^T multicast); requires all items head-pair (qpt = nQP: even item count) at2[0] = at[0]; at2[1].id = cudaLaunchAttributeClusterDimension; at2[1].val.clusterDim.x = 2; at2[1].val.clusterDim.y = 1; at2[1].val.clusterDim.z = 1; cfg.attrs = at2; cfg.numAttrs = 2; int g2 = (items < nsm ? items : nsm) & ~1; if (g2 < 2) g2 = 2; cfg.gridDim = dim3(g2); qpt = nQP; } cudaLaunchKernelEx(&cfg, mcl ? fa4::fa4_attn_kernel<2, 4, true, 2, true> : v3 ? fa4::fa4_attn_kernel<3, 4, true, 2> : v3d3 ? fa4::fa4_attn_kernel<3, 4, true, 2> : v3s ? fa4::fa4_attn_kernel<3, 4, true, 3> : d2 ? fa4::fa4_attn_kernel<2, 4, true, 2> : ns3 ? fa4::fa4_attn_kernel<2, 4, true> : fa4::fa4_attn_kernel<3, 2>, mq, mk, mv, mask, codes, out, S, nT, nT, sl2, B, work_ctr, *mj, qpt, vmax, qkb, mcl ? *mmap : mq, mcl ? rowctr : (int*)nullptr, pcg, pcu, mcl ? pscr : (uint8_t*)nullptr, pctr, pcap);}
#ifdef STRESS_PROBEvoid fa4_steal_read(unsigned long long* h) { cudaMemcpyFromSymbol(h, sidew::g_steal_cnt, 16); }#endif// debug counters (FA4_DBG builds only); h[15] = #clusters of the last launchvoid fa4_dbg_read(unsigned long long* h, bool reset) {#if FA4_DBG cudaMemcpyFromSymbol(h, fa4::g_dbg, sizeof(unsigned long long) * 16); if (reset) { unsigned long long z[16] = {0}; cudaMemcpyToSymbol(fa4::g_dbg, z, sizeof(z)); }#else for (int i = 0; i < 16; i++) h[i] = 1; (void)reset;#endif h[15] = (unsigned long long)g_fa4_last_ncl;}
#ifdef FA_PROBE// per-CTA end spread of the last fa4 launch (us): max end - min end, and makespan max end - min startvoid fa4_spread(double* spread, double* span) { unsigned long long h[2][256]; cudaMemcpyFromSymbol(h, fa4::g_fa4_t, sizeof(h)); unsigned long long s0 = ~0ull, e0 = ~0ull, e1 = 0; for (int i = 0; i < g_fa4_last_ncl; i++) { if (h[0][i] < s0) s0 = h[0][i]; if (h[1][i] < e0) e0 = h[1][i]; if (h[1][i] > e1) e1 = h[1][i]; } *spread = (e1 - e0) / 1000.0; *span = (e1 - s0) / 1000.0;}#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106// kernel.h - launcher declarations for the fused Qwen3-MoE decoder layer (B200, sm_100a).#pragma once// #define ABL_PROBE // QKV / o_proj GEMM ablation probe (throws from run())// #define RS_PROBE // isolated router/scan/scatter/gather timing probe (throws from run())// #define CHAIN_PROBE // back-to-back chain stamps + side-order e2e probe (throws from run())// #define TMA_PROBE // probe: bf16 high-half TMA over fp32 Wqkv (result: infeasible, see kernel.cu)// #define FA_PROBE // isolated attention probe: results thrown as an exception from run()// #define WS_PROBE2 // DRAM read-floor probe of the expert weight stream (throws from run())#include <cuda_runtime.h>#include <cuda_fp16.h>#include <cstdint>
// RMSNorm over rows of 2048 floats: TF32 hi/lo pair (router) or fp16 output (QKV GEMM operand).void launch_rmsnorm_hl(const float* x, const float* w, float eps, int T, float* hi, float* lo, float* ssq, cudaStream_t s);void launch_rmsnorm_h(const float* x, const float* w, float eps, int T, __half* out, float* ssq, cudaStream_t s);// fp32 -> fp16 weight conversion, pre-scaled by 2^4.// Fused rmsnorm1 (fp16 xn, zero ssq) + Wq|Wk|Wv fp16 conversion in one launch.void launch_prep_qkv(const float* x, const float* w, float eps, int T, __half* xn, float* ssq, const float* wq, const float* wk, const float* wv, __half* wqkv16, const float* cs, const float* sn, float* csT, float* snT, int* zbuf, int nz, __half* vt, int S, int Spad, cudaStream_t s, const float* qnw, const float* knw, float* winvq = nullptr, float* xinv = nullptr, __half* xn16s = nullptr);// T >= 2048: QKV GEMM on e4m3 operands (prep writes e4m3 xn / Wqkv rows with per-row pow2 scales, inverses in// xinv[T] / winvq[5120]; kind::f8f6f4 mainloop, epilogue dequantizes with xinv[row] * winvq[col])bool qkv_use_f8(int T, int S);bool qkv_vsplit(int T, int S); // e4m3 Q/K tiles + fp16 V tiles in the QKV GEMMvoid launch_convert_w16(const float* src, __half* dst, size_t n, const float* wr, float* wrh, float* wrl, cudaStream_t s, int f8 = 0, float* winv = nullptr, int T = 0); // + router W hi/lo split (extra CTAs)
// tcgen05 GEMMs (TMA -> smem -> tcgen05.mma -> TMEM -> fused epilogue)void launch_qkv_rope_gemm(const __half* xn, const __half* wqkv, const float* bq, const float* bk, const float* bv, const float* cs, const float* sn, const float* qnw, const float* knw, float eps, int B, int S, int Spad, __half* q, __half* k, __half* v, cudaStream_t s, unsigned* vmax = nullptr, const float* winvq = nullptr, const float* xinv = nullptr, const __half* xn16s = nullptr, const float* wq32 = nullptr, const float* wk32 = nullptr, const float* wv32 = nullptr, int* qbc = nullptr); // per-M-tile completion counters (T < 2048)bool qkv_w32(int T); // T < 2048 QKV GEMM on fp32 Wqkv (prep writes no fp16 Wqkv copy)// T < 2048 QKV GEMM on 3-term fp16 hi/lo operands (xn and Wqkv rows are 3 x 2048 halves: K = QKV_X3_K)bool qkv_x3(int T);constexpr int QKV_X3_K = 3 * 2048;void launch_oproj_gemm(const __half* attn, const __half* wo16, const float* bo, const float* resid, float* h, int T, float* ssq, cudaStream_t s, const unsigned* vmax = nullptr, const float* winv = nullptr, int* sctr = nullptr, const float* wo32 = nullptr, int* mtctr = nullptr);// fp8 (e4m3, kind::f8f6f4) o_proj for this T: attention writes e4m3 attn, convert_w16 writes e4m3 Wo + inverse scalesbool oproj_use_f8(int T);bool attn_qk_f8(int B, int S); // FA4 FP8 QK^T (e4m3 q / k rows)
// codes per 128x128 tile + compact pre-scaled copies of mixed (code 2) tiles in mtile[B*nT*nT][16384]void launch_mask_classify(const float* mask, int B, int S, uint8_t* codes, float* mtile, cudaStream_t s);// mask = compact tile buffer written by launch_mask_classify
void launch_flash_attn(const __half* q, const __half* k, const __half* vt, const float* mask, const uint8_t* codes, __half* out, int B, int S, int Spad, int* work_ctr, cudaStream_t s, const unsigned* vmax = nullptr, const float* pfg = nullptr, const float* pfu = nullptr, const int* qbc = nullptr);
void launch_router_wsplit(const float* wr, float* wrh, float* wrl, cudaStream_t s);// fused post-attention RMSNorm (from h + ssq) + 3xTF32 router GEMM + softmax / top-8 / histogram// dead intermediate buffers whose L2 lines the router invalidates (discard.global.L2, no write-back)struct L2Discard { const void* p[8]; unsigned long long bytes[8]; int n; int late; };extern L2Discard g_moe_dl; // dead-buffer discard list run by the MoE kernel before its PDL waitextern int g_disc_mode;extern L2Discard g_oproj_dl; // o_proj epilogue-warp discard list (set by run() before launch_oproj_gemm)void launch_router(const float* h, const float* lnw, const float* ssq, float eps, const float* wrh, const float* wrl, int T, int* topk_idx, float* topk_w, int* counts, const float* wg, const float* wu, cudaStream_t s, __half* xn16 = nullptr, uint8_t* xn8 = nullptr, float* f8inv = nullptr, const L2Discard* dl = nullptr, int* btok = nullptr, float* bw = nullptr, int* mtctr = nullptr);// T < 2048 MoE without scatter launch (router buckets + in-kernel group tables)bool moe_self_tables(int T);int moe_self_ws_ints(); // per-CTA global self-table slices (variants whose smem cannot hold it)// xn16: also write fp16 xn2 rows (T >= 2048 path); xn8 / f8inv: e4m3 xn2 rows + 1/scale (FP8 MoE path)bool moe_use_fp8(int T);extern int g_cur_S; // current call seq length (MoE silu gate)
// Expert offsets / M-tile table / permutation (perm_tok, perm_w and inverse map inv_pos[t*8+k] = sorted slot).void launch_moe_scan_scatter(int T, const int* topk_idx, const float* topk_w, int* counts, int* offsets, int* cursor, int* tile_expert, int* tile_mstart, int* total_tiles, int* perm_tok, float* perm_w, int* inv_pos, int* grp, cudaStream_t s, const float* h = nullptr, const float* lnw = nullptr, float eps = 0.f, const float* ssq = nullptr, float* xn2 = nullptr);// Fused RMSNorm2-recompute + gather: read h row once, normalize (TF32 hi), stream it into its 8 sorted slots.void launch_moe_norm_gather(const float* h, const float* w, float eps, const int* inv_pos, const float* ssq, int T, float* aperm, cudaStream_t s);
void launch_moe_gemms(const float* aperm, const float* wg, const float* wu, const float* wd, int T, const int* tile_expert, const int* tile_mstart, const int* total_tiles, const int* offsets, const int* counts, const int* perm_tok, const float* perm_w, float* act, float* out, const int* grp, int* moe_sync, cudaStream_t s);// true -> gather writes fp16 A and gate/up runs the fp16 amortized-conversion kernelbool moe_use_f16_gateup(int T);// upper bound on the number of (<= 3 M-tile) expert groups for n = T*8 routed rows (grp table sizing)int moe_max_groups(int n);
// FA4-style flash attention (fa4.cu): one head x two 128-row q tiles per item sharing K/V,// 2 softmax warpgroups (full row per thread), setmaxnreg 216/56; elect.sync whole-warp MMA issuer.#include <cuda.h>namespace sidew { struct MaskJob; }void launch_fa4_attn(const CUtensorMap& mq, const CUtensorMap& mk, const CUtensorMap& mv, const float* mask, const uint8_t* codes, __half* out, int B, int S, float sl2, int* work_ctr, const sidew::MaskJob* mj, int nsm, cudaStream_t s, const unsigned* vmax, const unsigned* qkb = nullptr, const CUtensorMap* mmap = nullptr, int* rowctr = nullptr, const float* pcg = nullptr, const float* pcu = nullptr, uint8_t* pscr = nullptr, int* pctr = nullptr, int pcap = 0);// in-kernel (FA4 idle warps) mask classification for this shape; rowctr = zeroed [1 + B nT] ints (main.cpp)bool fa4_mcl(int B, int S);extern int* g_mcl_ctr;extern int* g_pre_ctr; // zeroed [1 + 64] ints: [0] conversion ticket, [1 + e] converted rows of expert econstexpr int PRE_CAP = 64;123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292// main.cpp - torch binding; orchestrates the fused decoder-layer kernels (see kernel.cu).#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include "kernel.h"#include <string>#include <vector>#include <algorithm>#include <chrono>// #define FRONT_PROBE // isolated front (prep_qkv / mask classifier) BW probe#ifndef SIDE_HIPRIO#define SIDE_HIPRIO 0#endifstatic int g_side_hiprio = 0; // probe builds only#ifndef SIDE_ORDER#define SIDE_ORDER 1#endif
static inline __half* hp(torch::Tensor& t) { return reinterpret_cast<__half*>(t.data_ptr()); }// Sub-buffer of the single per-call workspace (one caching-allocator request per forward instead of ~28).struct Buf { uint8_t* p = nullptr; template <typename T> T* data_ptr() const { return reinterpret_cast<T*>(p); }};static inline __half* hp(const Buf& b) { return reinterpret_cast<__half*>(b.p); }// Bump allocator over the workspace: pass 1 (base == nullptr) only sums the 256 B-aligned sizes.struct Carver { uint8_t* base = nullptr; size_t off = 0; Buf take(size_t bytes) { Buf b; b.p = base ? base + off : nullptr; off += (bytes + 255) & ~(size_t)255; return b; }};
// ORDER: host enqueue position of the side-stream grids (mask_classify, convert_w16) relative to the main chain:// 0 = before prep_qkv, 1 = right after prep_qkv, 2 = after the QKV GEMM (always before their consumers).static int g_stg_on = 0;static cudaEvent_t g_stg_ev[8];#define STG(i) do { if (g_stg_on) cudaEventRecord(g_stg_ev[i], st); } while (0)static int g_no_discard = 0;static torch::Tensor run_impl(int order, torch::Tensor hidden, torch::Tensor cos, torch::Tensor sin, torch::Tensor mask, torch::Tensor ln1w, torch::Tensor wq, torch::Tensor bq, torch::Tensor wk, torch::Tensor bk, torch::Tensor wv, torch::Tensor bv, torch::Tensor qnw, torch::Tensor knw, torch::Tensor wo, torch::Tensor bo, torch::Tensor ln2w, torch::Tensor wr, torch::Tensor wg, torch::Tensor wu, torch::Tensor wd, double eps_d) {#ifdef FA_PROBE { extern std::string fa4_probe(); static bool once = false; if (!once) { once = true; throw std::runtime_error(fa4_probe()); } }#endif hidden = hidden.contiguous(); cos = cos.contiguous(); sin = sin.contiguous(); mask = mask.contiguous(); wq = wq.contiguous(); wk = wk.contiguous(); wv = wv.contiguous(); wo = wo.contiguous(); wr = wr.contiguous(); wg = wg.contiguous(); wu = wu.contiguous(); wd = wd.contiguous(); const int B = hidden.size(0), S = hidden.size(1), T = B * S; g_cur_S = S; const float eps = (float)eps_d; auto st = at::cuda::getCurrentCUDAStream().stream(); auto f32 = hidden.options(); auto u8 = hidden.options().dtype(torch::kUInt8);
const int Spad = (S + 127) / 128 * 128; const int nsync = 1 + (T * 8 + 127) / 128 + 128; const int qbc_off = 129 + nsync + 128 + 4 + 16 + (T + 127) / 128 + 2; // QKV per-M-tile completion counters const int mcl_off = qbc_off + (T + 127) / 128; // [ticket][B nT row counters] (FA4 in-kernel mask classify) const int pre_off = mcl_off + 1 + B * ((S + 127) / 128); // [ticket][PRE_CAP expert row counters] const int nz = pre_off + 1 + PRE_CAP; // + o_proj M-tile counters // + 16 Wo16-slice counters of the merged o_proj+router launch // + zeroed per-expert scatter cursors + fp8 max|V| slot at the end const bool f8 = oproj_use_f8(T); // e4m3 o_proj path (attn / Wo as e4m3 with pow2 scales) const int nT = (S + 127) / 128; const int n = T * 8; const int maxTiles = (n + 127) / 128 + 128; const int maxGroups = moe_max_groups(n); // M-tile groups (<= 3 tiles of one expert) for fp16 gate/up // ONE workspace allocation per forward: every intermediate is a 256 B-aligned slice (sizes per call/shape). const bool qvs = qkv_vsplit(T, S); // split QKV: e4m3 Q/K + fp16 V tiles const bool q8 = qkv_use_f8(T, S) || qvs; const bool selft = moe_self_tables(T); // no scatter launch Buf bktok, bkw, xn16s, winv, winvq, xinv, v, zbuf, codes, mtile, wqkv16, wo16, wrh, wrl, xn, ssq, csT, snT, q, k, attn, topk_idx, topk_w, offsets, cursor, tile_expert, tile_mstart, total_tiles, perm_tok, perm_w, inv_pos, grp, aperm, act; auto carve_all = [&](Carver& cv) { bktok = cv.take(selft ? (size_t)128 * T * 4 : 0); // router buckets [128][T] bkw = cv.take(selft ? (size_t)128 * T * 4 : 0); xn16s = cv.take(qvs ? (size_t)T * 2048 * 2 : 0); // VS: fp16 xn copy (xn holds e4m3) winv = cv.take((size_t)2048 * 4); // fp8 mode: inverse per-row Wo scales winvq = cv.take((size_t)5120 * 4); // fp8 QKV: inverse per-row Wqkv scales xinv = cv.take((size_t)T * 4); // fp8 QKV: inverse per-row xn scales v = cv.take((size_t)(B) * (size_t)(4) * (size_t)(128) * (size_t)(Spad) * 2); zbuf = cv.take((size_t)(nz) * 4); codes = cv.take((size_t)(B) * (size_t)(nT) * (size_t)(nT) * 1); mtile = cv.take((size_t)((int64_t)B * nT * nT * 16384) * 4); wqkv16 = cv.take((size_t)(5120) * (size_t)(2048) * 2); wo16 = cv.take((size_t)(2048) * (size_t)(4096) * 2); wrh = cv.take((size_t)(128) * (size_t)(2048) * 4); wrl = cv.take((size_t)(128) * (size_t)(2048) * 4); xn = cv.take((size_t)(T) * (size_t)(qkv_x3(T) ? QKV_X3_K : 2048) * 2); // 3-term rows for T < 2048 ssq = cv.take((size_t)(T) * 4); csT = cv.take((size_t)((int64_t)((T + 31) / 32) * 32 * 128) * 4); snT = cv.take((size_t)((int64_t)((T + 31) / 32) * 32 * 128) * 4); q = cv.take((size_t)(B) * (size_t)(32) * (size_t)(S) * (size_t)(128) * 2); k = cv.take((size_t)(B) * (size_t)(4) * (size_t)(S) * (size_t)(128) * 2); attn = cv.take((size_t)(T) * (size_t)(4096) * 2); topk_idx = cv.take((size_t)(T * 8) * 4); topk_w = cv.take((size_t)(T * 8) * 4); offsets = cv.take((size_t)(128) * 4); tile_expert = cv.take((size_t)(maxTiles) * 4); tile_mstart = cv.take((size_t)(2 * maxTiles) * 4); // + tile_mend[maxTiles] total_tiles = cv.take((size_t)(1) * 4); perm_tok = cv.take((size_t)(n) * 4); perm_w = cv.take((size_t)(n) * 4); inv_pos = cv.take((size_t)(n) * 4); grp = cv.take((size_t)std::max(6 * maxGroups + 2, selft ? moe_self_ws_ints() : 0) * 4); // + group row ends at [5G + 2, 6G + 2) aperm = cv.take((size_t)T * (moe_use_f16_gateup(T) ? 1024 : 2048) * 4); act = cv.take((size_t)(n) * (size_t)(768) * 4); }; Carver sizer; carve_all(sizer); auto ws = torch::empty({(int64_t)sizer.off}, u8); Carver cv; cv.base = ws.data_ptr<uint8_t>(); carve_all(cv); { // converted Wqkv (+ inverse e4m3 row scales) in a persistent raw cudaMalloc buffer (never freed, no // tensor state): prep_qkv's conversion blocks write it without waiting on the previous call's kernels (see // prep_qkv_kernel); a per-call workspace slice could alias memory the previous call's MoE still reads. static uint8_t* wqp = nullptr; // sized for the 3-term [5120][QKV_X3_K] fp16 layout (qkv_x3, T < 2048); the other layouts use its head if (!wqp) { cudaMalloc(&wqp, (size_t)5120 * QKV_X3_K * 2 + 5120 * 4); cudaDeviceSynchronize(); } wqkv16.p = wqp; winvq.p = wqp + (size_t)5120 * QKV_X3_K * 2; } Buf counts = zbuf, fa_ctr = zbuf, moe_sync = zbuf; fa_ctr.p += 128 * 4; moe_sync.p += 129 * 4; cursor = zbuf; cursor.p += (size_t)(129 + nsync) * 4; // zeroed scatter cursors (relative slot within each expert) Buf vmaxb = zbuf; vmaxb.p += (size_t)(129 + nsync + 128) * 4; // zeroed global max |V| (fp32 bits), fp8 o_proj mode only unsigned* vmax = f8 ? vmaxb.data_ptr<unsigned>() : nullptr; // zero-initialized buffers are created up front so the fill kernels do not break the PDL kernel chain // V^T; padding keys [S, Spad) zeroed inside prep_qkv (P is 0 there, avoid 0*NaN) // one int buffer zeroed inside prep_qkv (no separate fill launches): // [0,128) expert histogram, [128] flash-attention work counter, // [129, ...) fused MoE: [0] work queue counter, [1 + mt] per-M-tile gate/up completion counters // 3 (forked). mask-tile classification depends only on the input mask -> side stream, so its streaming read // (268 MB at S=8192) overlaps convert / RMSNorm / QKV GEMM, which stay PDL-chained on the main stream. // Stream/events are plain handles (no tensor state), created once and intentionally never destroyed. static cudaStream_t side_lo = nullptr, side_hi = nullptr; static cudaEvent_t ev_fork = nullptr, ev_join = nullptr, ev_wo = nullptr; if (!side_lo) { { int lo = 0, hi = 0; cudaDeviceGetStreamPriorityRange(&lo, &hi); cudaStreamCreateWithPriority(&side_lo, cudaStreamNonBlocking, SIDE_HIPRIO ? hi : lo); cudaStreamCreateWithPriority(&side_hi, cudaStreamNonBlocking, hi); } cudaEventCreateWithFlags(&ev_fork, cudaEventDisableTiming); cudaEventCreateWithFlags(&ev_join, cudaEventDisableTiming); cudaEventCreateWithFlags(&ev_wo, cudaEventDisableTiming); } cudaStream_t side = g_side_hiprio ? side_hi : side_lo; // side_hi: probe A/B only g_mcl_ctr = zbuf.data_ptr<int>() + mcl_off; g_pre_ctr = zbuf.data_ptr<int>() + pre_off; STG(0); cudaEventRecord(ev_fork, st); cudaStreamWaitEvent(side, ev_fork, 0); auto side_launch = [&]() { launch_mask_classify(mask.data_ptr<float>(), B, S, codes.data_ptr<uint8_t>(), mtile.data_ptr<float>(), side); // ev_join / ev_wo records removed (no stream ever waited on them: consumers acquire the side completion // counters on the device) -> two fewer host API calls between the fork and the first side launch // 0. fp16 copies of the dense projection weights (x 2^4). Wo is only needed by o_proj, so its conversion runs on // the side stream after mask_classify (joined via ev_wo right before o_proj), off the critical path. // [Wq;Wk;Wv] stays on the main stream (needed by the QKV GEMM). // + router weight TF32 hi/lo split as extra CTAs of the same launch (input-only, covered by the ev_wo join) launch_convert_w16(wo.data_ptr<float>(), hp(wo16), (size_t)2048 * 4096, wr.data_ptr<float>(), wrh.data_ptr<float>(), wrl.data_ptr<float>(), side, f8 ? 1 : 0, winv.data_ptr<float>(), T); }; if (order == 0) side_launch(); // 0+1. ONE launch: input RMSNorm -> fp16 xn (first T CTAs) + [Wq;Wk;Wv] -> fp16 (remaining CTAs) // cos/sin re-laid out as [T/32][32 float4 groups][32 rows] (coalesced row-per-thread loads in the QKV epilogue) launch_prep_qkv(hidden.data_ptr<float>(), ln1w.data_ptr<float>(), eps, T, hp(xn), ssq.data_ptr<float>(), wq.data_ptr<float>(), wk.data_ptr<float>(), wv.data_ptr<float>(), hp(wqkv16), cos.data_ptr<float>(), sin.data_ptr<float>(), csT.data_ptr<float>(), snT.data_ptr<float>(), zbuf.data_ptr<int>(), nz, hp(v), S, Spad, st, qnw.data_ptr<float>(), knw.data_ptr<float>(), q8 ? winvq.data_ptr<float>() : nullptr, q8 ? xinv.data_ptr<float>() : nullptr, qvs ? hp(xn16s) : nullptr); if (order == 1) side_launch(); // 2/3. fused QKV GEMM (tcgen05, fp16) + bias + q/k RMSNorm + RoPE -> fp16 q/k/v STG(1); auto qkv_call = [&]() { launch_qkv_rope_gemm(hp(xn), hp(wqkv16), bq.data_ptr<float>(), bk.data_ptr<float>(), bv.data_ptr<float>(), csT.data_ptr<float>(), snT.data_ptr<float>(), qnw.data_ptr<float>(), knw.data_ptr<float>(), eps, B, S, Spad, hp(q), hp(k), hp(v), st, vmax, winvq.data_ptr<float>(), xinv.data_ptr<float>(), qvs ? hp(xn16s) : nullptr, wq.data_ptr<float>(), wk.data_ptr<float>(), wv.data_ptr<float>(), T < 2048 ? zbuf.data_ptr<int>() + qbc_off : nullptr); }; qkv_call(); if (order == 2) side_launch(); // 4/5. attention (mask codes from the side stream; join right before flash attention) // (mask codes: acquired inside flash attention via the side completion counter - no event join here) STG(2); launch_flash_attn(hp(q), hp(k), hp(v), mtile.data_ptr<float>(), codes.data_ptr<uint8_t>(), hp(attn), B, S, Spad, fa_ctr.data_ptr<int>(), st, vmax, wg.data_ptr<float>(), wu.data_ptr<float>(), T < 2048 ? zbuf.data_ptr<int>() + qbc_off : nullptr); // 6. o_proj + bias + residual -> out (= h) auto out = torch::empty({B, S, 2048}, f32); // dead-buffer L2 discard. Wqkv16 / xn / q / k / V^T (/ fp16 xn copy) are dead once attention completed: // discarded by the o_proj epilogue warps; Wo16 / attn (read by o_proj) are discarded by the router. L2Discard dl{}, dlo{}; { const size_t eq = attn_qk_f8(B, S) ? 1 : 2, ea = f8 ? 1 : 2; auto add = [&](L2Discard& d, const Buf& b, size_t bytes) { d.p[d.n] = b.p; d.bytes[d.n] = bytes; d.n++; }; const size_t kx3 = qkv_x3(T) ? 3 : 1; // 3-term xn / Wqkv rows add(dlo, wqkv16, (size_t)5120 * 2048 * 2 * kx3); add(dl, wo16, (size_t)2048 * 4096 * ea); add(dlo, xn, (size_t)T * 2048 * 2 * kx3); add(dlo, q, (size_t)B * 32 * S * 128 * eq); add(dlo, k, (size_t)B * 4 * S * 128 * eq); add(dlo, v, (size_t)B * 4 * 128 * Spad * 2); add(dl, attn, (size_t)T * 4096 * ea); if (qvs) add(dlo, xn16s, (size_t)T * 2048 * 2); } g_oproj_dl = (g_no_discard & 1) ? L2Discard{} : dlo; g_moe_dl = L2Discard{}; if (T >= 897 && T < 2048 && moe_self_tables(T)) { if (g_disc_mode == 2) { g_moe_dl = dl; dl.n = 0; } if (g_disc_mode == 1) dl.late = 1; } // Wo fp16 copy: acquired by the o_proj TMA producer via the side completion counter (no event join) STG(3); auto opj_call = [&]() { launch_oproj_gemm(hp(attn), hp(wo16), bo.data_ptr<float>(), hidden.data_ptr<float>(), out.data_ptr<float>(), T, ssq.data_ptr<float>(), st, vmax, winv.data_ptr<float>(), (g_no_discard & 2) ? nullptr : zbuf.data_ptr<int>() + (129 + nsync + 128 + 4), wo.data_ptr<float>(), zbuf.data_ptr<int>() + (129 + nsync + 128 + 4 + 16)); }; opj_call(); // 7+8. router: post-attention RMSNorm fused into the 3xTF32 tensor-core router GEMM (h read once via TMA), // fp32 softmax / top-8 (Wr hi/lo split was done on the side stream before ev_wo) STG(4); launch_router(out.data_ptr<float>(), ln2w.data_ptr<float>(), ssq.data_ptr<float>(), eps, wrh.data_ptr<float>(), wrl.data_ptr<float>(), T, topk_idx.data_ptr<int>(), topk_w.data_ptr<float>(), counts.data_ptr<int>(), wg.data_ptr<float>(), wu.data_ptr<float>(), st, (moe_use_f16_gateup(T) && !moe_use_fp8(T)) ? hp(aperm) : nullptr, // fp16 path: router writes xn2 moe_use_fp8(T) ? aperm.data_ptr<uint8_t>() : nullptr, // FP8 path: e4m3 xn2 rows moe_use_fp8(T) ? reinterpret_cast<float*>(aperm.data_ptr<uint8_t>() + (size_t)T * 2048) : nullptr, (g_no_discard & 2) ? nullptr : &dl, selft ? bktok.data_ptr<int>() : nullptr, selft ? bkw.data_ptr<float>() : nullptr, zbuf.data_ptr<int>() + (129 + nsync + 128 + 4 + 16)); // 9. sort by expert, then fused rmsnorm2-recompute + gather (h row read once -> 8 sorted slots) // + pair-group section (TF32 fused MoE): count + up to n/256 + 128 entries STG(5); if (!selft) launch_moe_scan_scatter(T, topk_idx.data_ptr<int>(), topk_w.data_ptr<float>(), counts.data_ptr<int>(), offsets.data_ptr<int>(), cursor.data_ptr<int>(), tile_expert.data_ptr<int>(), tile_mstart.data_ptr<int>(), total_tiles.data_ptr<int>(), perm_tok.data_ptr<int>(), perm_w.data_ptr<float>(), (int*)nullptr /* inv_pos: unread in production */, grp.data_ptr<int>(), st, out.data_ptr<float>(), ln2w.data_ptr<float>(), eps, ssq.data_ptr<float>(), moe_use_f16_gateup(T) ? nullptr : aperm.data_ptr<float>()); // + fused norm-gather CTAs // fp16 MoE path (T >= 4096): xn2 stored once per token as fp16 [T, 2048] (gathered inside the MoE kernel); // TF32 path: fp32 xn2 [T, 2048] once per token (gathered by the fused TF32 MoE kernel) // (TF32 path: xn2 written by the fused gather CTAs of the scatter launch above) // 10/11. grouped expert GEMMs (tcgen05), accumulate into out STG(6); launch_moe_gemms(aperm.data_ptr<float>(), wg.data_ptr<float>(), wu.data_ptr<float>(), wd.data_ptr<float>(), T, tile_expert.data_ptr<int>(), tile_mstart.data_ptr<int>(), total_tiles.data_ptr<int>(), offsets.data_ptr<int>(), counts.data_ptr<int>(), selft ? bktok.data_ptr<int>() : perm_tok.data_ptr<int>(), selft ? bkw.data_ptr<float>() : perm_w.data_ptr<float>(), act.data_ptr<float>(), out.data_ptr<float>(), grp.data_ptr<int>(), moe_sync.data_ptr<int>(), st); STG(7);#ifdef RS_PROBE { cudaDeviceSynchronize(); extern std::string rs_probe(const float*, float, const float*, const float*, const float*, const float*); throw std::runtime_error(rs_probe(ln2w.data_ptr<float>(), eps, wrh.data_ptr<float>(), wrl.data_ptr<float>(), wg.data_ptr<float>(), wu.data_ptr<float>())); }#endif return out;}
torch::Tensor run(torch::Tensor hidden, torch::Tensor cos, torch::Tensor sin, torch::Tensor mask, torch::Tensor ln1w, torch::Tensor wq, torch::Tensor bq, torch::Tensor wk, torch::Tensor bk, torch::Tensor wv, torch::Tensor bv, torch::Tensor qnw, torch::Tensor knw, torch::Tensor wo, torch::Tensor bo, torch::Tensor ln2w, torch::Tensor wr, torch::Tensor wg, torch::Tensor wu, torch::Tensor wd, double eps_d) {#ifdef TMA_PROBE { extern std::string tma_probe(); throw std::runtime_error(tma_probe()); }#endif // long sequences (S >= 4096): side grids (mask classification, Wo convert) enqueued AFTER the QKV GEMM on the // low-priority side stream, so the 1-CTA/SM QKV grid is not delayed by the mask stream; mask units still unclaimed // when flash attention starts are classified inline by the FA4 CTAs (claim/steal protocol, identical codes) // also 2048 <= S < 4096 (2x2048 class): side grids after the QKV GEMM launch // also S >= 300 with T >= 2048 (8x373 / 16x449 classes) // T < 2048 band: side grids (mask classify + Wo convert) enqueued BEFORE prep_qkv (order 0; csteal for the // QKV convert-steal is still computed before the QKV launch). Host-only ordering, numerics identical. const int ord = (hidden.size(1) >= 2048 || (hidden.size(1) >= 300 && hidden.size(0) * hidden.size(1) >= 2048)) ? 2 : 0; // also the S < 300, T >= 2048 band (16x128 / 8x256 / 32x256): side grids before prep_qkv return run_impl(ord, hidden, cos, sin, mask, ln1w, wq, bq, wk, bk, wv, bv, qnw, knw, wo, bo, ln2w, wr, wg, wu, wd, eps_d);}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run, "decoder layer"); }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300// side_steal.cuh - deadlock-free side-stream work: claimable units + consumer work stealing (included by kernel.cu, fa4.cu)//#pragma once#include <cuda_runtime.h>#include <cuda_fp16.h>#include <cstdint>#include <cmath>
namespace sidew {#ifdef STEAL_COUNTstatic __device__ unsigned long long g_steal_cnt[2]; // probe builds: units executed by consumers (mask, convert)#define STEAL_INC(i) atomicAdd(&sidew::g_steal_cnt[i], 1ull)#else#define STEAL_INC(i) do { } while (0)#endif
struct MaskJob { // mask_classify units: u = (b * nT + qt) * nT + kt const float* mask; int S, nT, n; uint8_t* codes; float* mtile; unsigned* st; unsigned ep; unsigned long long* done; unsigned long long target;};struct ConvJob { // convert_w16 units: [0, nconv) Wo blocks (1024 float4), [nconv, n) router Wr blocks (2 rows) const float* src; void* dst; int nconv, n, f8; const float* wr; float* wrh; float* wrl; float* winv; unsigned* st; unsigned ep; unsigned long long* done; unsigned long long target;};
__device__ __forceinline__ uint64_t pol_first() { uint64_t pol; asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(pol)); return pol;}__device__ __forceinline__ uint64_t pol_last() { uint64_t pol; asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pol)); return pol;}__device__ __forceinline__ float4 ld4(const void* addr, uint64_t pol) { float4 v; asm volatile("ld.global.nc.L2::cache_hint.v4.f32 {%0, %1, %2, %3}, [%4], %5;" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) : "l"(addr), "l"(pol)); return v;}__device__ __forceinline__ void st2(void* addr, uint2 v, uint64_t pol) { asm volatile("st.global.L2::cache_hint.v2.b32 [%0], {%1, %2}, %3;" ::"l"(addr), "r"(v.x), "r"(v.y), "l"(pol) : "memory");}__device__ __forceinline__ uint32_t h2(float a, float b) { __half2 h = __floats2half2_rn(a, b); return *reinterpret_cast<uint32_t*>(&h);}__device__ __forceinline__ uint32_t e4m3x4(float a, float b, float c, float d) { unsigned short lo, hi; asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(lo) : "f"(b), "f"(a)); asm("cvt.rn.satfinite.e4m3x2.f32 %0, %1, %2;" : "=h"(hi) : "f"(d), "f"(c)); return (uint32_t)lo | ((uint32_t)hi << 16);}// frexpf / ldexpf replacements (bit-identical for the call sites: mx > 0 finite, |x| <= 60). The libdevice// frexpf writes its exponent through a pointer, which left a 16 B local stack frame in every kernel using it.__device__ __forceinline__ int frexp_e(float mx) { // mx > 0 finite: mx = f * 2^e, f in [0.5, 1) uint32_t b = __float_as_uint(mx); int ex = (int)((b >> 23) & 0xFFu); if (ex == 0) { b = __float_as_uint(mx * 18446744073709551616.f); ex = (int)((b >> 23) & 0xFFu) - 64; } // subnormal return ex - 126;}__device__ __forceinline__ float pow2i(int x) { return __uint_as_float((uint32_t)(x + 127) << 23); } // x in [-126, 127]__device__ __forceinline__ float scale_top(float mx, int top) { // == f8_scale(mx, top); top 14 == pow2_scale if (!(mx > 0.f) || !(mx < INFINITY)) return 1.f; int e; e = sidew::frexp_e(mx); int x = top - e; x = x < -60 ? -60 : (x > 60 ? 60 : x); return sidew::pow2i(x);}__device__ __forceinline__ unsigned long long ld_acq(const unsigned long long* p) { unsigned long long v; asm volatile("ld.acquire.gpu.global.u64 %0, [%1];" : "=l"(v) : "l"(p) : "memory"); return v;}__device__ __forceinline__ unsigned ld_rlx(const unsigned* p) { unsigned v; asm volatile("ld.relaxed.gpu.global.u32 %0, [%1];" : "=r"(v) : "l"(p) : "memory"); return v;}// single-thread claim of unit u for this call__device__ __forceinline__ bool claim(unsigned* st, int u, unsigned ep) { return atomicMax(st + u, ep) < ep; }
__device__ __forceinline__ int warp_steal(unsigned* st, int n, unsigned ep, int off, int& i) { const int lane = threadIdx.x & 31; while (i < n) { const int j = i + lane; int u = off + j; if (u >= n) u -= n; const bool cand = j < n && ld_rlx(st + u) < ep; unsigned m = __ballot_sync(0xffffffffu, cand); while (m) { const int l = __ffs(m) - 1; int got = 0; if (lane == l) got = claim(st, u, ep) ? 1 : 0; got = __shfl_sync(0xffffffffu, got, l); const int uu = __shfl_sync(0xffffffffu, u, l); if (got) { i += l + 1; return uu; } m &= m - 1; } i += 32; } i = 0; return -1;}
// ---- mask tile classification unit (block-level: every thread of the CTA must call it; threads >= 256 only join// the barriers). Identical to the former mask_classify_kernel body (codes + compact log2e-prescaled mixed tiles).__device__ __forceinline__ void mask_unit(const MaskJob& J, int u) { __shared__ int flags[3][8]; const int nKT = J.nT, nQT = J.nT, S = J.S; const int kt = u % nKT, qt = (u / nKT) % nQT, b = u / (nKT * nQT); const bool act = threadIdx.x < 256; const int warp = (threadIdx.x >> 5) & 7, lane = threadIdx.x & 31; const int gc0 = kt * 128 + lane * 4; const int r0 = qt * 128 + warp * 16; const float* mask = J.mask; float4 m[16]; if ((S & 3) == 0) { const uint64_t pol = pol_first(); const bool cok = gc0 < S && act;#pragma unroll for (int i = 0; i < 16; i++) { const int gr = r0 + i; m[i] = make_float4(0.f, 0.f, 0.f, 0.f); if (gr < S && cok) m[i] = ld4(mask + ((size_t)b * S + gr) * S + gc0, pol); } } else {#pragma unroll for (int i = 0; i < 16; i++) { const int gr = r0 + i; const float* mr = mask + ((size_t)b * S + (gr < S ? gr : 0)) * S; float t[4];#pragma unroll for (int e = 0; e < 4; e++) t[e] = (act && gr < S && gc0 + e < S) ? __ldcs(mr + gc0 + e) : 0.f; m[i] = make_float4(t[0], t[1], t[2], t[3]); } } int notneg = 0, nonzero = 0, notcausal = 0;#pragma unroll for (int i = 0; i < 16; i++) { if (r0 + i >= S) continue; const float v[4] = {m[i].x, m[i].y, m[i].z, m[i].w};#pragma unroll for (int e = 0; e < 4; e++) { if (gc0 + e < S) { notneg |= v[e] != -INFINITY; nonzero |= v[e] != 0.f; notcausal |= (gc0 + e > r0 + i) ? (v[e] != -INFINITY) : (v[e] != 0.f); } } } const int wn = __any_sync(0xffffffffu, notneg), wz = __any_sync(0xffffffffu, nonzero), wc = __any_sync(0xffffffffu, notcausal); __syncthreads(); // previous unit's flag reads done (repeated calls in one CTA) if (lane == 0 && act) { flags[0][warp] = wn; flags[1][warp] = wz; flags[2][warp] = wc; } __syncthreads(); int any_notneg = 0, any_nonzero = 0, any_notcausal = 0;#pragma unroll for (int w = 0; w < 8; w++) { any_notneg |= flags[0][w]; any_nonzero |= flags[1][w]; any_notcausal |= flags[2][w]; } const bool partial = (kt * 128 + 128 > S); const uint8_t code = !any_notneg ? 0 : ((!any_nonzero && !partial) ? 1 : (!any_notcausal ? 3 : 2)); if (threadIdx.x == 0) J.codes[((size_t)b * nQT + qt) * nKT + kt] = code; if (code == 2 && act) { const float LOG2E = 1.4426950408889634f; float4* dst = reinterpret_cast<float4*>(J.mtile + (((size_t)b * nQT + qt) * nKT + kt) * 16384) + lane * 128 + warp * 16;#pragma unroll for (int i = 0; i < 16; i++) { const bool rok = r0 + i < S; const float v[4] = {m[i].x, m[i].y, m[i].z, m[i].w}; float o[4];#pragma unroll for (int e = 0; e < 4; e++) o[e] = gc0 + e >= S ? -INFINITY : (rok ? v[e] * LOG2E : 0.f); dst[i] = make_float4(o[0], o[1], o[2], o[3]); } } // release: this unit's codes / tile visible before the completion count __syncthreads(); if (threadIdx.x == 0) { asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(J.done), "l"((unsigned long long)(1ull)) : "memory"); }}
// Block-level consumer acquire of the mask counter with work stealing (all threads of the CTA call it).__device__ __forceinline__ void mask_acquire_steal(const MaskJob& J) { __shared__ int s_u; int i = 0; const int off = (int)(((long long)blockIdx.x * J.n) / (gridDim.x > 0 ? gridDim.x : 1)); const int warp = threadIdx.x >> 5, lane = threadIdx.x & 31; for (;;) { if (warp == 0) { int r = 0; if (lane == 0) r = ld_acq(J.done) >= J.target ? -2 : 0; r = __shfl_sync(0xffffffffu, r, 0); if (r == 0) r = warp_steal(J.st, J.n, J.ep, off < J.n ? off : 0, i); if (lane == 0) s_u = r; } __syncthreads(); const int u = s_u; __syncthreads(); if (u == -2) break; if (u >= 0) { if (threadIdx.x == 0) STEAL_INC(0); mask_unit(J, u); } else if (threadIdx.x == 0) __nanosleep(64); }}
// ---- convert unit, warp-level (bit-identical outputs to the block-level convert_w16_kernel)__device__ __forceinline__ void conv_unit_warp(const ConvJob& J, int u) { const int lane = threadIdx.x & 31; if (u >= J.nconv) { // router Wr block: rows 2 blk, 2 blk + 1 (512 float4 each), per-row pow2 scale (top 14), fp16 hi / lo const int blk = u - J.nconv; const float4* src = reinterpret_cast<const float4*>(J.wr) + (size_t)blk * 1024; float mr[2] = {0.f, 0.f};#pragma unroll for (int r = 0; r < 2; r++) // row index compile-time (mr[j >> 4] under unroll 4 was runtime-indexed)#pragma unroll 4 for (int jj = 0; jj < 16; jj++) { const float4 v = __ldcs(src + (16 * r + jj) * 32 + lane); mr[r] = fmaxf(mr[r], fmaxf(fmaxf(fabsf(v.x), fabsf(v.y)), fmaxf(fabsf(v.z), fabsf(v.w)))); }#pragma unroll for (int o = 16; o; o >>= 1)#pragma unroll for (int r = 0; r < 2; r++) mr[r] = fmaxf(mr[r], __shfl_xor_sync(0xffffffffu, mr[r], o)); const float sc[2] = {scale_top(mr[0], 14), scale_top(mr[1], 14)}; uint2* h16 = reinterpret_cast<uint2*>(J.wrh);#pragma unroll for (int r = 0; r < 2; r++)#pragma unroll 4 for (int jj = 0; jj < 16; jj++) { const int j = 16 * r + jj; const int i = blk * 1024 + j * 32 + lane; const float4 v = __ldcs(src + j * 32 + lane); const float s_ = sc[r]; const float x0 = v.x * s_, x1 = v.y * s_, x2 = v.z * s_, x3 = v.w * s_; const __half2 h01 = __floats2half2_rn(x0, x1), h23 = __floats2half2_rn(x2, x3); const float2 f01 = __half22float2(h01), f23 = __half22float2(h23); h16[i] = make_uint2(*reinterpret_cast<const uint32_t*>(&h01), *reinterpret_cast<const uint32_t*>(&h23)); (void)f01; (void)f23; // Wr_lo no longer written (router reads Wr_hi only) } if (lane == 0) { J.wrl[2 * blk] = sc[0]; J.wrl[2 * blk + 1] = sc[1]; } } else { const float4* src = reinterpret_cast<const float4*>(J.src) + (size_t)u * 1024; const uint64_t rf = pol_first(), kp = pol_last(); if (J.f8) { float m = 0.f;#pragma unroll 4 for (int j = 0; j < 32; j++) { // max pass with the default L2 policy (lines kept for the convert pass, which reads them // EVICT_FIRST) -> one DRAM pass per Wo row instead of two (identical bytes) const float4 v = __ldcg(src + j * 32 + lane); m = fmaxf(m, fmaxf(fmaxf(fabsf(v.x), fabsf(v.y)), fmaxf(fabsf(v.z), fabsf(v.w)))); }#pragma unroll for (int o = 16; o; o >>= 1) m = fmaxf(m, __shfl_xor_sync(0xffffffffu, m, o)); const float sc = scale_top(m, 8); uint32_t* d8 = reinterpret_cast<uint32_t*>(J.dst) + (size_t)u * 1024;#pragma unroll 4 for (int j = 0; j < 32; j++) { const float4 v = ld4(src + j * 32 + lane, rf); d8[j * 32 + lane] = e4m3x4(v.x * sc, v.y * sc, v.z * sc, v.w * sc); } if (lane == 0) J.winv[u] = 1.f / sc; } else { uint2* d = reinterpret_cast<uint2*>(J.dst) + (size_t)u * 1024;#pragma unroll 4 for (int j = 0; j < 32; j++) { const float4 v = ld4(src + j * 32 + lane, rf); st2(d + j * 32 + lane, make_uint2(h2(v.x * 16.f, v.y * 16.f), h2(v.z * 16.f, v.w * 16.f)), kp); } } } __syncwarp(); // warp-ordered writes, lane 0's cumulative fence releases them (one membar.gl) if (lane == 0) { asm volatile("red.release.gpu.global.add.u64 [%0], %1;" ::"l"(J.done), "l"((unsigned long long)(1ull)) : "memory"); }}
// Warp-level consumer acquire of the convert counter with work stealing (all 32 lanes of one warp call it).__device__ __forceinline__ void conv_acquire_steal(const ConvJob& J, int off) { const int lane = threadIdx.x & 31; int i = 0; off = J.n > 0 ? off % J.n : 0; for (;;) { int r = 0; if (lane == 0) r = ld_acq(J.done) >= J.target ? 1 : 0; if (__shfl_sync(0xffffffffu, r, 0)) break; const int u = warp_steal(J.st, J.n, J.ep, off, i); if (u >= 0) { if (lane == 0) STEAL_INC(1); conv_unit_warp(J, u); } else __nanosleep(64); } __syncwarp();}
} // namespace sidew123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162// ws_probe.cu - WS_PROBE2 builds only (compiled out of production): DRAM read-floor probe for the 2.416 GB of fp32// expert gate / up / down weights. Patterns: (a) TMA 2D tiles (128B swizzle, 32 cols x 128 rows boxes, 2 per 32 KB// stage, NS-stage ring, 148 persistent CTAs, contiguous unit ranges, k fastest = moe_fused1's walk), (b) 1D// cp.async.bulk chunks into an NS-stage ring, (c) ld.global.nc.v4 with 8 independent loads in flight per thread.#include "kernel.h"#ifdef WS_PROBE2#include <cuda.h>#include <string>#include <cstdio>namespace wsp {__device__ __forceinline__ uint32_t su32(const void* p) { return (uint32_t)__cvta_generic_to_shared(p); }__device__ __forceinline__ void minit(uint32_t a) { asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" ::"r"(a)); }__device__ __forceinline__ void mexp(uint32_t a, uint32_t b) { asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" ::"r"(a), "r"(b) : "memory");}__device__ __forceinline__ void mwait(uint32_t a, uint32_t ph) { uint32_t ok = 0; while (!ok) asm volatile("{ .reg .pred p; mbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2; selp.u32 %0, 1, 0, p; }" : "=r"(ok) : "r"(a), "r"(ph) : "memory");}// (a) TMA 2D: unit u (of 3 * 768 * 32) = tensor u / 24576, 128-row block (u % 24576) / 32, 64-float k chunk u % 32template <int NS>__global__ void __launch_bounds__(32, 1) tma2d(const __grid_constant__ CUtensorMap m0, const __grid_constant__ CUtensorMap m1, const __grid_constant__ CUtensorMap m2, int U) { extern __shared__ __align__(1024) uint8_t sm[]; __shared__ __align__(8) uint64_t bar[NS]; uint8_t* s = (uint8_t*)(((uintptr_t)sm + 1023) & ~(uintptr_t)1023); if (threadIdx.x != 0) return; for (int i = 0; i < NS; i++) minit(su32(&bar[i])); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); const int u0 = (int)((long long)blockIdx.x * U / gridDim.x), u1 = (int)((long long)(blockIdx.x + 1) * U / gridDim.x); auto issue = [&](int u, int st) { const int t = u / 24576, r = u % 24576, rb = r / 32, kc = r % 32; const CUtensorMap* m = t == 0 ? &m0 : (t == 1 ? &m1 : &m2); const uint32_t b = su32(&bar[st]), d = su32(s + st * 32768); mexp(b, 32768);#pragma unroll for (int h = 0; h < 2; h++) asm volatile("cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"(d + 16384 * h), "l"((uint64_t)m), "r"(kc * 64 + 32 * h), "r"(rb * 128), "r"(b) : "memory"); }; int it = 0; for (int u = u0; u < u0 + NS && u < u1; u++) issue(u, u - u0); for (int u = u0; u < u1; u++, it++) { const int st = it % NS; mwait(su32(&bar[st]), (it / NS) & 1); if (u + NS < u1) issue(u + NS, st); }}// (b) 1D bulk: the flat 2.416 GB (3 tensors) split into chunks of CH bytes, contiguous chunk ranges per CTAtemplate <int NS, int CH>__global__ void __launch_bounds__(32, 1) bulk1d(const char* p0, const char* p1, const char* p2, long long per, int nch) { extern __shared__ __align__(1024) uint8_t sm[]; __shared__ __align__(8) uint64_t bar[NS]; if (threadIdx.x != 0) return; for (int i = 0; i < NS; i++) minit(su32(&bar[i])); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); const int cpt = (int)(per / CH); const int c0 = (int)((long long)blockIdx.x * nch / gridDim.x), c1 = (int)((long long)(blockIdx.x + 1) * nch / gridDim.x); auto issue = [&](int c, int st) { const int t = c / cpt; const char* src = (t == 0 ? p0 : (t == 1 ? p1 : p2)) + (long long)(c - t * cpt) * CH; const uint32_t b = su32(&bar[st]); mexp(b, CH); asm volatile("cp.async.bulk.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1], %2, [%3];" ::"r"(su32(sm + (size_t)st * CH)), "l"(src), "r"((uint32_t)CH), "r"(b) : "memory"); }; int it = 0; for (int c = c0; c < c0 + NS && c < c1; c++) issue(c, c - c0); for (int c = c0; c < c1; c++, it++) { const int st = it % NS; mwait(su32(&bar[st]), (it / NS) & 1); if (c + NS < c1) issue(c + NS, st); }}// (c) ld.global.nc.L1::no_allocate.v4, 8 independent loads per thread per iteration, grid-stride over each tensor__global__ void ldv4(const float4* p0, const float4* p1, const float4* p2, long long n4, unsigned* sink) { unsigned acc = 0; const long long nth = (long long)gridDim.x * blockDim.x, tid = (long long)blockIdx.x * blockDim.x + threadIdx.x; for (int t = 0; t < 3; t++) { const float4* p = t == 0 ? p0 : (t == 1 ? p1 : p2); for (long long i = tid; i < n4; i += 8 * nth) { float4 v[8];#pragma unroll for (int j = 0; j < 8; j++) { const long long k = i + j * nth; if (k < n4) asm volatile("ld.global.nc.L1::no_allocate.v4.f32 {%0,%1,%2,%3}, [%4];" : "=f"(v[j].x), "=f"(v[j].y), "=f"(v[j].z), "=f"(v[j].w) : "l"(p + k)); else v[j] = make_float4(0.f, 0.f, 0.f, 0.f); }#pragma unroll for (int j = 0; j < 8; j++) acc ^= __float_as_uint(v[j].x) ^ __float_as_uint(v[j].w); } } if (acc == 0x9E3779B9u) *sink = acc;}} // namespace wsp
static CUtensorMap wsp_map(const float* p) { CUtensorMap m; cuuint64_t dims[2] = {2048, 98304}; cuuint64_t str[1] = {8192}; cuuint32_t box[2] = {32, 128}; cuuint32_t es[2] = {1, 1}; cuTensorMapEncodeTiled(&m, CU_TENSOR_MAP_DATA_TYPE_FLOAT32, 2, (void*)p, dims, str, box, es, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, CU_TENSOR_MAP_L2_PROMOTION_L2_256B, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); return m;}std::string ws_stream_probe(const float* wg, const float* wu, const float* wd, cudaStream_t st) { const double bytes = 3.0 * 128 * 768 * 2048 * 4; int nsm = 0, dev = 0; cudaGetDevice(&dev); cudaDeviceGetAttribute(&nsm, cudaDevAttrMultiProcessorCount, dev); cudaEvent_t e0, e1; cudaEventCreate(&e0); cudaEventCreate(&e1); unsigned* sink; cudaMalloc(&sink, 4); std::string res = " | STREAM (2.416 GB, best/avg of 6 after 2 warm-ups, us TB/s):"; auto tm = [&](const char* nm, auto fn) { for (int r = 0; r < 2; r++) fn(); cudaStreamSynchronize(st); float best = 1e30f, tot = 0.f; for (int r = 0; r < 6; r++) { cudaEventRecord(e0, st); fn(); cudaEventRecord(e1, st); cudaEventSynchronize(e1); float ms; cudaEventElapsedTime(&ms, e0, e1); best = ms < best ? ms : best; tot += ms; } char b[200]; snprintf(b, sizeof(b), " %s %.1f/%.1f (%.2f) e%d;", nm, 1000.f * best, 1000.f * tot / 6, bytes / (best * 1e9), (int)cudaGetLastError()); res += b; }; const CUtensorMap mg = wsp_map(wg), mu = wsp_map(wu), md = wsp_map(wd); const int U = 3 * 768 * 32; auto tma = [&](auto ns_tag, int grid) { constexpr int NS = decltype(ns_tag)::value; const int smem = NS * 32768 + 1024; cudaFuncSetAttribute(wsp::tma2d<NS>, cudaFuncAttributeMaxDynamicSharedMemorySize, smem); wsp::tma2d<NS><<<grid, 32, smem, st>>>(mg, mu, md, U); }; tm("tma2d NS4 g148", [&] { tma(std::integral_constant<int, 4>{}, nsm); }); tm("tma2d NS6 g148", [&] { tma(std::integral_constant<int, 6>{}, nsm); }); tm("tma2d NS3 g296", [&] { tma(std::integral_constant<int, 3>{}, 2 * nsm); }); const long long per = 128LL * 768 * 2048 * 4; auto bulk = [&](auto ns_tag, auto ch_tag, int grid) { constexpr int NS = decltype(ns_tag)::value, CH = decltype(ch_tag)::value; const int smem = NS * CH; cudaFuncSetAttribute(wsp::bulk1d<NS, CH>, cudaFuncAttributeMaxDynamicSharedMemorySize, smem); wsp::bulk1d<NS, CH><<<grid, 32, smem, st>>>((const char*)wg, (const char*)wu, (const char*)wd, per, (int)(3 * per / CH)); }; tm("bulk1d 3x64K g148", [&] { bulk(std::integral_constant<int, 3>{}, std::integral_constant<int, 65536>{}, nsm); }); tm("bulk1d 6x32K g148", [&] { bulk(std::integral_constant<int, 6>{}, std::integral_constant<int, 32768>{}, nsm); }); tm("bulk1d 12x16K g148", [&] { bulk(std::integral_constant<int, 12>{}, std::integral_constant<int, 16384>{}, nsm); }); tm("bulk1d 2x48K... skip", [&] {}); const long long n4 = per / 16; tm("ldv4 8x 512thr 2blk/SM", [&] { wsp::ldv4<<<2 * nsm, 512, 0, st>>>((const float4*)wg, (const float4*)wu, (const float4*)wd, n4, sink); }); tm("ldv4 8x 1024thr 2blk/SM", [&] { wsp::ldv4<<<2 * nsm, 1024, 0, st>>>((const float4*)wg, (const float4*)wu, (const float4*)wd, n4, sink); }); tm("ldv4 8x 256thr 8blk/SM", [&] { wsp::ldv4<<<8 * nsm, 256, 0, st>>>((const float4*)wg, (const float4*)wu, (const float4*)wd, n4, sink); }); cudaFree(sink); return res;}#endif1234567891011# MoE expert computation with weighted accumulation (L2 010)
Given each token's top-k experts and routing weights, runs the token through those experts' SwiGLU MLPs and sums the outputs weighted by the routing weights.
- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 6 (6,516 lines).- Idea: Tokens sorted by expert on the GPU, then one persistent tcgen05 kernel runs both GEMMs (gate/up + SwiGLU, down + routing weight) from one work queue; CUDA graph.- Result: SOL score 0.956; speedup 7.71x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11.- Origin: search agent (Claude).- Comments edited; unused test helpers removed; the code that runs is identical to the scored submission.- Re-checked on a B200 after the edit: it builds and passes every workload of the SOL-ExecBench correctness check.- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready.1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283{ "board": "L2", "id": "010_moe_expert_computation_with_weighted_accumulation", "name": "MoE expert computation with weighted accumulation", "language": "CUDA C++", "files": [ { "path": "src/fast_path.cu", "lines": 2422, "bytes": 144511 }, { "path": "src/g12fused.cu", "lines": 3035, "bytes": 205494 }, { "path": "src/graph_launch.h", "lines": 50, "bytes": 2522 }, { "path": "src/kernel.cu", "lines": 997, "bytes": 60858 }, { "path": "src/kernel.h", "lines": 4, "bytes": 246 }, { "path": "src/main.cpp", "lines": 8, "bytes": 609 } ], "origin": "search agent (Claude)", "result": { "public": true, "sol_score": 0.956297, "speedup": 7.7057, "board_row": true, "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" }, "idea": "Tokens sorted by expert on the GPU, then one persistent tcgen05 kernel runs both GEMMs (gate/up + SwiGLU, down + routing weight) from one work queue; CUDA graph.", "spec": { "languages": [ "cuda_cpp" ], "target_hardware": [ "B200", "LOCAL" ], "entry_point": "main.cpp::run", "binding": "torch", "destination_passing_style": false, "dependencies": [], "compile_options": { "cuda_cflags": [ "-std=c++17", "-O3", "-gencode=arch=compute_100a,code=sm_100a", "--expt-relaxed-constexpr", "--expt-extended-lambda", "-DNDEBUG", "-DCUTLASS_ENABLE_GDC_FOR_SM100=1", "-Xptxas=-O3,--allow-expensive-optimizations=true,-v" ], "ld_flags": [ "-lcuda" ] }, "sources": [ "fast_path.cu", "g12fused.cu", "graph_launch.h", "kernel.cu", "kernel.h", "main.cpp" ] }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950#pragma once// graph_launch.h: one launch wrapper for every kernel of the MoE forward, so the per-T launch sequence can be// captured into a CUDA graph and later re-parameterized in place.// EAGER : plain cudaLaunchKernelExC on the caller's stream (PDL / cluster attributes as given).// CAPTURE : same launch redirected to the private capture stream (stream capture keeps the PDL attributes as// programmatic graph edges and the cluster dims as node attributes).// PATCH : no launch; the arguments of the captured kernel node with the same function pointer are replaced via// cudaGraphExecKernelNodeSetParams (pointer / tensor-map changes without re-capturing).#include <cuda_runtime.h>#include <utility>#include <vector>namespace moegraph {enum Mode { EAGER = 0, CAPTURE = 1, PATCH = 2 };struct Ctx { int mode = EAGER; cudaStream_t cap = nullptr; cudaGraphExec_t exec = nullptr; const std::vector<std::pair<const void*, cudaGraphNode_t>>* nodes = nullptr; std::vector<const void*> launched; // CAPTURE: kernel functions in launch order bool fail = false; // PATCH: some node could not be updated unsigned ws_gen = 0; // bumped whenever a persistent workspace is re-allocated};Ctx& ctx(); // defined in kernel.cu (heap-held, never destroyed)inline cudaError_t launch_c(const cudaLaunchConfig_t* cfg, const void* k, void** args) { Ctx& c = ctx(); if (c.mode == PATCH) { for (auto& n : *c.nodes) if (n.first == k) { cudaKernelNodeParams p = {}; p.func = const_cast<void*>(k); p.gridDim = cfg->gridDim; p.blockDim = cfg->blockDim; p.sharedMemBytes = (unsigned)cfg->dynamicSmemBytes; p.kernelParams = args; p.extra = nullptr; if (cudaGraphExecKernelNodeSetParams(c.exec, n.second, &p) != cudaSuccess) { c.fail = true; cudaGetLastError(); } return cudaSuccess; } c.fail = true; return cudaSuccess; } if (c.mode == CAPTURE) { c.launched.push_back(k); cudaLaunchConfig_t cc = *cfg; cc.stream = c.cap; return cudaLaunchKernelExC(&cc, k, args); } return cudaLaunchKernelExC(cfg, k, args);}// argument coercion exactly like the cudaLaunchKernelEx C++ templatetemplate <typename... Exp, typename... Act>inline cudaError_t launch(const cudaLaunchConfig_t* cfg, void (*k)(Exp...), Act&&... a) { return [&](Exp... ca) { void* p[] = {(void*)&ca...}; return launch_c(cfg, (const void*)k, p); }(std::forward<Act>(a)...);}} // namespace moegraph123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997// DOS: g12 route_kernel no longer writes the unread expert-offset table (off_out).// RNWG: g12 route_kernel drops its griddepcontrol.wait (predecessor g12 never triggers early -> fully exited).// MoE expert computation (Qwen3-MoE SwiGLU experts + weighted top-k accumulation) for B200, all custom tcgen05.//// Dispatch (moe_forward at the bottom):// T < 1152 : fastpath::moe_forward (fast_path.cu): merged persistent 1-CTA tcgen05 kernel, hi/lo bf16 h.// 1152 <= T < 1250 : fastpath single-H; T >= 1250 : this file's path, all on device, no host sync:// 1) route_kernel : ONE thread-block cluster (16 CTAs, or 8 if not schedulable): per-CTA expert histograms of// contiguous slot slices, DSMEM reduction after a cluster barrier, coalesced scatter// -> perm_slot[p] (slot id t*8+k), perm_w[p] (routing weight), expert offsets, the GEMM1 / GEMM2// work-item tables (token chunks of <= 256 rows per expert) and zeroed ready[] counters.// 2) gather_kernel : Xp[p,:] = X[token(p),:] (expert-sorted activations), zeroes out, L2-prefetches X / weights.// 3) g12::launch : fused persistent 2-CTA swap-AB tcgen05 kernel (g12fused.cu) running GEMM1 (SwiGLU -> H) and// GEMM2 (H Wd^T, weighted, bf16 bulk-reduce into out) from one ordered work list.// (Disabled CUTLASS grouped-GEMM / unfused g1swap / g2swap / reduce paths and probe builds were removed.)#include <cuda_runtime.h>#include <cuda.h>#include <cuda_bf16.h>#include "kernel.h"#include "graph_launch.h"#include <ATen/cuda/CUDAContext.h>#include <c10/cuda/CUDAGuard.h>#include <ATen/cuda/EmptyTensor.h>#include <algorithm>#include <cmath>#include <cstdint>#include <unordered_map>#include <string>#include <vector>
namespace g12 {int cluster_size(int nrows, int num_sms, int* max_cl_out);int wmc_mode(int nrows, int num_sms);extern int g_wmc, g_n2, g_n4;extern int g_a5d2_off;extern int g_epmx;extern int g_zpre;extern int g_epl_min;extern int g_unh;extern int g_tk6;extern int g_ncl_cap;extern int g_tkn;extern int g_hk;extern int g_wsk, g_wprom;extern int g_wide2, g_w2lo, g_rg;extern int g_rdef, g_rpf, g_pairi;extern int g_dyn;extern int g_s8lo;extern int g_force_cs, g_knob, g_force_deep, g_pf_off, g_rhelp, g_xld_off, g_xld_nc, g_padskip;int deep_ring(int nrows, int num_sms); // 1: chunks capped at 128 rows (4 x 48 KB ring)int wide_mode(int nrows, int num_sms);int s7_mode(int nrows, int num_sms); // 1: g12 7-slot ring kernel, chunks capped at 192 rows // 1: g12 wide-unit kernel, chunks capped at 272 rows (240 main + 32 remainder)void launch(const void* gw, const void* uw, const void* dw, const void* Xp, const void* H, int nrows, const int4* items1, const int* n_items1, const int4* items2, const int* n_items2, const int* perm_slot, const float* perm_w, int* ready, __nv_bfloat16* Ys, int num_sms, cudaStream_t stream, const void* X, int xlines, int xld, int xpf_lines, const void* gwp, const void* uwp, int npf, int pfb, int zero_tok, int* zero_done, int dual);}
constexpr int HD = 2048, ID = 768, NE = 128, TK = 8;
// PDL (programmatic dependent launch): every kernel waits for its predecessor's completion before// touching global memory, then lets its successor start launching (its prologue overlaps our tail).__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); }__device__ __forceinline__ void pdl_trigger() { asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); }
// ------------------------------------------------------------------ routing kernels
__device__ __forceinline__ uint32_t rt_cluster_rank() { uint32_t r; asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); return r;}__device__ __forceinline__ int rt_ld_dsmem(const int* p, uint32_t rank) { uint32_t a = (uint32_t)__cvta_generic_to_shared(p), ra; asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(ra) : "r"(a), "r"(rank)); int v; asm volatile("ld.shared::cluster.s32 %0, [%1];" : "=r"(v) : "r"(ra) : "memory"); return v;}constexpr int ROUTE_THREADS = 1024;constexpr int ROUTE_SLOTS_PER_CLUSTER = 65536; // register slots per cluster (NC * 1024 * RK), T <= 8192 single-passtemplate <int NC> constexpr int route_rk() { return ROUTE_SLOTS_PER_CLUSTER / (NC * ROUTE_THREADS); }template <int NC> constexpr int route_dsmem() { return route_rk<NC>() * ROUTE_THREADS * 8; } // staged int2 per slot// Route codegen fold (template band specialization): CP >= 0 = compile-time chunk policy (cap / split mode / wmc /// GEMM2-LPT bits; the runtime cpol argument is ignored), LP = 0 / 1 compile-time LPT off / on (LP = 1 only launched// with nfix < NE, LP = 0 only with nfix >= NE). -1 = runtime argument (generic kernel, also the attribute / occupancy// query instantiation). The host picks the instantiation matching the runtime values exactly -> identical tables.// PO >= 0: compile-time pair_order (runtime pair_order argument ignored); OV = 0: host guarantees slice <= RK*1024// (no overflow slots) -> the overflow histogram / cursor / scatter paths compile out. Value-identical tables.// RK2 (route register-slot diet): RKT > 0 overrides the per-thread register slot count (RKT = 2 when the host// guarantees slice <= 2 * 1024, i.e. T <= 4096 on 16-CTA / T < 2048 on 8-CTA clusters): the fully unrolled per-slot// load / histogram / staging / scatter-precompute loops shrink from 8 (4) to 2 predicated iterations. Same tables.template <int NC, int CP = -1, int LP = -1, int PO = -1, int OV = 1, int RKT = 0> // NC: cluster size (16: non-portable cluster, 8: fallback)__global__ void __launch_bounds__(ROUTE_THREADS) route_kernel( const int64_t* __restrict__ sel, const float* __restrict__ rw, int n, int slice, int* __restrict__ off_out, int* __restrict__ perm_slot, float* __restrict__ perm_w, int4* __restrict__ items, int* __restrict__ n_items, int4* __restrict__ items2, int* __restrict__ n_items2, int* __restrict__ ready, int pair_order_rt, int nfix_rt /* experts [0,nfix) keep identity order; nfix = NE: LPT off */, int cpol_rt /* chunk policy: bits 0-15 = row cap (multiple of 16, <= 256; 128 = deep ring), bits 16+ = split mode (0: 16-aligned near-equal + remainder, 1: equal split, 2: cap-full + remainder) */, int g2ncl /* >0 (with cpol bit 21): g12 cluster count -> GEMM2 units of experts in the last partial static GEMM1 wave go last */) { __shared__ int h[NE], hreg[NE], lpre[NE], tot[NE], cur[NE], ovf[NE], off[NE + 1], cof[NE + 1], bse[NE]; __shared__ int wsum[4], wcsum[4]; // per-warp totals of the 4-warp (one expert per thread) global scan // LPT unit order: kch[e] = chunks of expert e, key[e] = sort key (descending = work-table order); // the rank pass turns them straight into cof[e] = sum of kch over experts with a larger key __shared__ int kch[NE], key[NE]; // GEMM2-only cost order (cpol bit 21): key2 -> cof2 = first GEMM2 table chunk position of expert e __shared__ int key2[NE], cof2[NE]; const int cpol = CP >= 0 ? CP : cpol_rt; const int pair_order = PO >= 0 ? PO : pair_order_rt; // compile-time in the band instantiations // compile-time in the band instantiations const int nfix = LP == 0 ? NE : nfix_rt; const bool lpt = LP >= 0 ? (LP == 1) : (nfix < NE); // LPT unit order (compile-time when LP >= 0) const bool g2lpt = ((cpol >> 21) & 1) != 0; __shared__ __align__(16) int hall[NC][NE]; // dynamic smem: this CTA's register slots in local expert-sorted order, ONE 8-byte entry per slot: // x = slot id << 7 | expert, y = routing weight bits (one st.shared.v2 per slot instead of 3 scattered stores) // st.async completion barrier of hall[][]: every CTA (incl. this one) delivers its 512 B histogram row with // st.async ... mbarrier::complete_tx into each CTA's hall[b][*] and signals that CTA's hbar (NC * 512 tx bytes) __shared__ __align__(8) unsigned long long hbar; extern __shared__ int2 rt_dyn2[]; int2* st = rt_dyn2; pdl_trigger(); // let the gather kernel launch now (it griddepcontrol.waits for our completion) // cluster phase 0 (split): arrive at entry, wait right before the first remote store (guarantees every peer CTA // has started executing before we write its shared memory; by then the wait completes immediately) // hbar init (one arrival = thread 0's expect_tx), published cluster-wide before the phase-0 arrive (CUTLASS // fence_barrier_init + cluster_arrive_relaxed pattern): peers st.async into it only after the phase-0 wait // h-zero fused into the entry smem init (before the slot loads / cluster arrive; ordered by the barrier below) if (threadIdx.x < NE) h[threadIdx.x] = 0; if (threadIdx.x == 0) { asm volatile("mbarrier.init.shared::cta.b64 [%0], 1;" :: "r"((uint32_t)__cvta_generic_to_shared(&hbar)) : "memory"); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); } asm volatile("barrier.cluster.arrive.relaxed.aligned;" ::: "memory"); const int tid = threadIdx.x; const int b = (int)rt_cluster_rank(); const int s0 = b * slice, s1 = min(n, s0 + slice); // Single-pass routing: this thread's first RK slots (i = s0 + tid + k*1024) are loaded into registers once // (sel / rw are pure inputs -> before griddepcontrol.wait); the phase-1 histogram atomicAdd's return value is the // slot's rank among this CTA's slots of that expert. Before griddepcontrol.wait the slots are staged in smem in // local expert-sorted order (local prefix + rank) and every thread precomputes its scatter stores (position, slot, // weight) and its work-table items in registers; after the wait only the global stores remain. // Slots beyond RK*1024 per CTA (T > 8K) are ranked after the register slots via smem cursors (scattered). constexpr int RK = RKT > 0 ? RKT : route_rk<NC>(); static_assert(RK % 2 == 0, "slot pairs"); static_assert(RK <= route_rk<NC>(), "staging smem sized for route_rk"); int esel[RK]; float ewt[RK]; auto rslot = [&](int k) { return s0 + 2 * tid + (k >> 1) * 2 * ROUTE_THREADS + (k & 1); };#pragma unroll // Vectorized slot loads: thread tid owns slot PAIRS (s0 + 2*tid + kp*2*ROUTE_THREADS + {0,1}); one 16 B load = 2 int64 // expert ids, one 8 B load = 2 routing weights. s0, s1 are even (even slice, n = 8T) -> a pair is entirely in or out // of the slice and the loads are aligned. Register slot k <-> slot id rslot(k) (bijection onto [s0, s0+RK*ROUTE_THREADS)). for (int kp = 0; kp < RK / 2; kp++) { const int i = s0 + 2 * tid + kp * 2 * ROUTE_THREADS; int4 sv = make_int4(0, 0, 0, 0); float2 wv = make_float2(0.f, 0.f); if (i < s1) { sv = __ldg(reinterpret_cast<const int4*>(sel + i)); wv = __ldg(reinterpret_cast<const float2*>(rw + i)); } esel[2 * kp] = sv.x; esel[2 * kp + 1] = sv.z; // low words of the int64 ids (0..127) ewt[2 * kp] = wv.x; ewt[2 * kp + 1] = wv.y; } __syncthreads(); // h[] zeroed at kernel entry (fused with the smem init) // phase 1: histogram + per-slot rank (register slots), then the overflow slots (counted only) int rk[RK];#pragma unroll for (int k = 0; k < RK; k++) rk[k] = (rslot(k) < s1) ? atomicAdd(&h[esel[k]], 1) : 0; const bool has_ovf = OV != 0 && s0 + RK * ROUTE_THREADS < s1; // CTA-uniform (always false if OV == 0) const int nreg = max(0, min(s1 - s0, RK * ROUTE_THREADS)); // register slots of this CTA __syncthreads(); if (tid < 32) { // register-slot counts + their exclusive scan -> local expert offsets (4 experts per lane) int v[4], s = 0;#pragma unroll for (int j = 0; j < 4; j++) { v[j] = h[tid * 4 + j]; hreg[tid * 4 + j] = v[j]; s += v[j]; } int inc = s;#pragma unroll for (int d = 1; d < 32; d <<= 1) { const int t = __shfl_up_sync(0xffffffffu, inc, d); if (tid >= d) inc += t; } int o = inc - s;#pragma unroll for (int j = 0; j < 4; j++) { lpre[tid * 4 + j] = o; o += v[j]; } } if (has_ovf) { __syncthreads(); // warp 0 has read the register-slot counts for (int i = s0 + tid + RK * ROUTE_THREADS; i < s1; i += ROUTE_THREADS) atomicAdd(&h[(int)sel[i]], 1); } __syncthreads(); // h[] final (incl. overflow atomics), lpre visible asm volatile("barrier.cluster.wait.aligned;" ::: "memory"); // phase 0: all peers running, their hbar initialized const uint32_t hbl = (uint32_t)__cvta_generic_to_shared(&hbar); if (tid == 0) asm volatile("mbarrier.arrive.expect_tx.shared::cta.b64 _, [%0], %1;" :: "r"(hbl), "r"((uint32_t)(NC * NE * 4)) : "memory"); if (tid < NC * 32) { const int r = tid >> 5, q = tid & 31; const int4 v = make_int4(h[4 * q], h[4 * q + 1], h[4 * q + 2], h[4 * q + 3]); const uint32_t la = (uint32_t)__cvta_generic_to_shared(&hall[b][4 * q]); uint32_t ra, rb; asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(ra) : "r"(la), "r"((uint32_t)r)); asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(rb) : "r"(hbl), "r"((uint32_t)r)); asm volatile("st.async.shared::cluster.mbarrier::complete_tx::bytes.v4.s32 [%0], {%1, %2, %3, %4}, [%5];" :: "r"(ra), "r"(v.x), "r"(v.y), "r"(v.z), "r"(v.w), "r"(rb) : "memory"); } // local staging overlaps the st.async delivery#pragma unroll for (int k = 0; k < RK; k++) { const int i = rslot(k); if (i < s1) st[lpre[esel[k]] + rk[k]] = make_int2((i << 7) | esel[k], __float_as_int(ewt[k])); } __syncthreads(); // staging visible if (tid < NE) { // all NC histogram rows delivered into hall[][] (the readers below are exactly these threads) uint32_t ok = 0; do { asm volatile("{\n .reg .pred p;\n mbarrier.try_wait.parity.shared::cta.b64 p, [%1], 0;\n selp.u32 %0, 1, 0, p;\n}\n" : "=r"(ok) : "r"(hbl) : "memory"); } while (!ok); } // cluster-wide reduction of the NC histograms through DSMEM, done directly by the 128 scan threads (one expert // per thread, NC independent remote loads issued back-to-back -> one DSMEM latency). Route-phase probe //: the former // 1024-thread read + rpart smem staging needed an extra CTA barrier and smem round trip before the scan. int my_pre = 0, my_off = 0, my_cof = 0, t = 0; if (tid < NE) { int v[NC];#pragma unroll for (int r = 0; r < NC; r++) v[r] = hall[r][tid]; // local (pushed by CTA r)#pragma unroll for (int r = 0; r < NC; r++) { t += v[r]; my_pre += r < b ? v[r] : 0; } } // exclusive scans of the 128 totals and chunk counts: warps 0-3, one expert per thread, warp-local shfl scans, // then warp bases added after one CTA barrier if (tid < NE) { const int ccap = cpol & 0xFFFF; // chunks of <= ccap rows (t >= 0); cpol bit 20 (g12 weight-multicast mode): EVEN chunk count per expert so // items 2u / 2u+1 are two chunks of the same (expert, m-tile) (a 1-row expert gets one empty chunk) const int c = (cpol & (1 << 20)) ? 2 * ((t + 2 * ccap - 1) / (2 * ccap)) : (t + ccap - 1) / ccap; int inc = t, cinc = c;#pragma unroll for (int d = 1; d < 32; d <<= 1) { const int tt = __shfl_up_sync(0xffffffffu, inc, d), ct = __shfl_up_sync(0xffffffffu, cinc, d); if ((tid & 31) >= d) { inc += tt; cinc += ct; } } tot[tid] = t; my_off = inc - t; my_cof = cinc - c; kch[tid] = c; // Longest-processing-time-first: experts by rows-per-chunk descending, ties by id; the first nfix experts (whose // gate/up slabs the first-wave prefetch guessed) stay in front in id order. nfix = NE -> identity order (off). // LPT key = per-atom MMA cost of the expert's chunks: max(349, 2*N) clocks, N = 16-rounded chunk width (UMMA N // granularity; 349 = fixed per-atom feed floor) -> chunks that cost the same per atom tie and fall back to id order. const int n16 = c > 0 ? ((((t + c - 1) / c) + 15) & ~15) : 0; const int ccost = c > 0 ? max(349, 2 * n16) : 0; key[tid] = tid < nfix ? (1 << 24) - tid : (ccost << 7) | (127 - tid); // GEMM2 table order (mid-T tail balance): descending per-atom MMA cost, ties by id -> the cheapest GEMM2 units // are claimed last from the dynamic queue (finer last wave). GEMM1 order (first-wave prefetch guess) unchanged. key2[tid] = (ccost << 7) | (127 - tid); if ((tid & 31) == 31) { wsum[tid >> 5] = inc; wcsum[tid >> 5] = cinc; } cof[tid] = my_cof; // stash: warp-local exclusive chunk prefix (final cof written below) } __syncthreads(); // LWD (last-wave demotion, dyn GEMM2 queue bands): GEMM1 unit u runs on cluster u % ncl in static wave u / ncl, so // the units of the last PARTIAL wave (u >= nu1 - nu1 % ncl, identity order = highest experts) finish one GEMM1 unit // later than everything else. Their experts' GEMM2 units are moved behind all others in the cost-descending GEMM2 // table, so early (claim-ahead) GEMM2 claims never block on a not-yet-finished GEMM1 chunk. Table order only. if (g2lpt && !lpt && g2ncl > 0) { // CTA-uniform if (tid < NE) { int wcb = 0, nc = 0;#pragma unroll for (int q = 0; q < 4; q++) { nc += wcsum[q]; if (q < (tid >> 5)) wcb += wcsum[q]; } const int nu1 = 6 * nc, rem = nu1 % g2ncl; if (rem > 0 && 6 * (cof[tid] + wcb + kch[tid]) > nu1 - rem) key2[tid] -= 1 << 20; } __syncthreads(); } // Parallel rank pass (all 1024 threads, before the per-expert block): expert e = tid >> 3 (8 threads per expert), // thread sub = tid & 7 compares its 16 keys e2 = sub + 8j, the 8-lane group reduces with shfl_xor. Same counts as // the former 128-step serial loop on 128 threads (unique keys -> rank = #larger keys is a permutation of [0, NE)). static_assert(ROUTE_THREADS == 8 * NE, "rank pass: 8 threads per expert"); if (lpt || g2lpt) { // CTA-uniform const int e = tid >> 3, sub = tid & 7; int r1 = 0, r2 = 0; if (lpt) { const int mk = key[e];#pragma unroll for (int j = 0; j < NE / 8; j++) { const bool gt = key[sub + 8 * j] > mk; r1 += gt ? kch[sub + 8 * j] : 0; } } if (g2lpt) { const int mk2 = key2[e];#pragma unroll for (int j = 0; j < NE / 8; j++) { const bool gt = key2[sub + 8 * j] > mk2; r2 += gt ? kch[sub + 8 * j] : 0; } }#pragma unroll for (int d = 1; d < 8; d <<= 1) { r1 += __shfl_xor_sync(0xffffffffu, r1, d); r2 += __shfl_xor_sync(0xffffffffu, r2, d); } // RCOF (route diet): r1 / r2 = sum of the chunk counts of all experts with a LARGER key = the exclusive prefix of // chunk counts in key-descending work-table order -> written as cof / cof2 directly (was: rank -> srt[rank] = kch, // warp-0 scan, gather cof = srt[rnk]: 1 scan + 2 CTA barriers per order). Keys are unique -> identical tables. if (sub == 0) { if (lpt) cof[e] = r1; if (g2lpt) cof2[e] = r2; } } if (tid < NE) { const int g = tid >> 5; int wb = 0, wcb = 0;#pragma unroll for (int q = 0; q < 3; q++) if (q < g) { wb += wsum[q]; wcb += wcsum[q]; } const int o = my_off + wb; off[tid] = o; if (!lpt) { // LPT off: keys (1<<24)-tid strictly decrease -> rank = tid (skip the 128-step rank loop). // Identity order -> the work-table-order chunk scan equals the identity scan already done here (warp-local + // warp bases): cof directly, no extra warp scan / 2 CTA barriers (route diet, bit-identical). cof[tid] = my_cof + wcb; } // LPT: cof written by the parallel rank pass above const int cb = my_pre + o; // this CTA's global base of expert tid cur[tid] = cb; bse[tid] = cb - lpre[tid]; // staged entry j of expert tid -> p = bse + j if (has_ovf) ovf[tid] = cb + hreg[tid]; if (tid == 0) { off[NE] = wsum[0] + wsum[1] + wsum[2] + wsum[3]; cof[NE] = wcsum[0] + wcsum[1] + wcsum[2] + wcsum[3]; } } __syncthreads(); // (LPT / GEMM2-LPT chunk offsets cof / cof2 were written by the rank pass; visible after the barrier above) // precompute (before griddepcontrol.wait) this thread's scatter stores: staged entry j -> p = base[e] + (j - lpre[e]) int sp[RK], ss[RK]; float sw[RK];#pragma unroll for (int k = 0; k < RK; k++) { const int j = tid + k * ROUTE_THREADS; sp[k] = -1; ss[k] = 0; sw[k] = 0.f; if (j < nreg) { const int2 v = st[j]; const int e = v.x & 127; sp[k] = bse[e] + j; ss[k] = v.x >> 7; // slot id = token*TK + k sw[k] = __int_as_float(v.y); } } // ESS (early scatter stores): phase 3a / 3b stores are issued right after their targets are known, BEFORE the // work-item precompute below (no wait gates them, RNWG), so their drain overlaps the item math. Same stores. // phase 3a: scatter stores of the register slots, overflow slots via smem cursors#pragma unroll for (int k = 0; k < RK; k++) if (sp[k] >= 0) { perm_slot[sp[k]] = ss[k]; perm_w[sp[k]] = sw[k]; } if (OV) for (int i = s0 + tid + RK * ROUTE_THREADS; i < s1; i += ROUTE_THREADS) { // slices > RK*1024 slots (T > 8K) const int e = (int)sel[i]; const int p = atomicAdd(&ovf[e], 1); perm_slot[p] = i; perm_w[p] = rw[i]; } // phase 3b: per-chunk GEMM1 -> GEMM2 ready counters of the fused kernel (g12fused.cu), zeroed every call for (int i = b * ROUTE_THREADS + tid; i < cof[NE]; i += NC * ROUTE_THREADS) ready[i] = 0; // precompute the first work item of this thread. CTA b builds m-tile mb = b % 8 for the experts e with // e % NH == b / 8 (NH = NC / 8 cluster halves); 8*NH threads per expert stride over its chunks. // Expert e -> nch near-equal token chunks (<= 256 rows); chunks of one (e, m-tile) are adjacent item ids. // GEMM1 (g12): 6 m-tiles of 128 intermediate cols; GEMM2: 8 Wd m-tiles. constexpr int NH = NC / 8, CST = 8 * NH; const int mb = b & 7; const int ie = (tid / CST) * NH + (b >> 3), isub = tid % CST; const int im = tot[ie], inch = kch[ie], icof = cof[ie], ioff = off[ie]; const int i2cof = g2lpt ? cof2[ie] : icof; // GEMM2 table chunk position of expert ie auto make_item = [&](int c, int4& it, int& i1) { const int smode = (cpol >> 16) & 15; const int as = smode == 2 ? (cpol & 0xFFFF) : (((im + inch - 1) / inch) + 15) & ~15; const bool al = smode != 1 && inch > 1 && (inch - 1) * as < im; const int b0 = al ? c * as : c * im / inch; const int b1 = al ? (c + 1 == inch ? im : (c + 1) * as) : (c + 1) * im / inch; it = make_int4(ie | ((icof + c) << 8), mb | (inch << 8), ioff + b0, b1 - b0); // pair_order (4-CTA g12 clusters): m-tile pair (mb>>1) -> chunk -> mb&1, so items 2u / 2u+1 share one token // chunk with adjacent m-tiles (the two CTA pairs of a cluster take them and multicast the token tile) i1 = pair_order ? ((mb >> 1) * inch + c) * 2 + (mb & 1) : mb * inch + c; }; const bool g1raster = (cpol & (1 << 20)) == 0; auto g1idx = [&](int c, int i1) { return g1raster ? c * 6 + mb : i1; }; int4 it0 = make_int4(0, 0, 0, 0); int i10 = 0; if (isub < inch) make_item(isub, it0, i10); const int ncof = cof[NE]; // RNWG (no griddepcontrol.wait, port of fastpath RNW): this kernel's global writes touch only the g12 workspace, // whose readers are the previous call's gather / g12 kernels; g12 never triggers launch_dependents early, so every // block of it (and, transitively, of the gather it waited on) has exited before this kernel can launch. sel / rw // were already read pre-wait under the same argument. g12 still griddepcontrol.waits for our completion. // phase 3c: work items (first one precomputed; experts with > 8 chunks loop) if (isub < inch) { if (mb < 6) items[6 * icof + g1idx(isub, i10)] = it0; items2[8 * i2cof + i10] = it0; for (int c = isub + CST; c < inch; c += CST) { int4 it; int i1; make_item(c, it, i1); if (mb < 6) items[6 * icof + g1idx(c, i1)] = it; items2[8 * i2cof + i1] = it; } } // n_items2[1] = zero_done counter of g12's in-kernel out zeroing (no-gather mode), reset every call if (b == 0 && tid == 0) { *n_items = 6 * ncof; *n_items2 = 8 * ncof; n_items2[1] = 0; n_items2[2] = 0; } // [2]: g12 dyn GEMM2 claim counter // expert-offset table: each CTA writes its 1/NC share (experts e with e % NC == b; offset NE by the last CTA), // in parallel with the other CTAs' item writes (was CTA 0 alone). Identical table. // DOS (dead offset stores): the expert-offset table off_out has no reader (g12 consumes only the item tables, // perm_slot / perm_w, ready[] and the counts) -> its stores are dropped; argument kept for the launch signature. (void)off_out; // (no trailing cluster barrier: a CTA passes its hbar wait only after every peer's st.async into it landed, and // after the phase-0 wait no CTA touches a peer's shared memory except through those st.async)}// (c) gather: one warp per sorted row copies the token's X row (4 KB) into Xp.// zero_out != nullptr: warp of sorted row p with p % 8 == 0 also zeroes output row p / 8 (the fused kernel's GEMM2// epilogue atomically accumulates into it).// Weight L2 prefetch (fused 2-CTA g12 path, small T): DRAM is otherwise nearly idle for weights during the// route + gather + launch window. Threads after the X-prefetch lines issue one bulk L2 prefetch of the// first pfb bytes (K prefix) of each gate / up weight row of g12's first-wave GEMM1 units u < npf (cluster c// starts with unit c; with one token chunk per expert, unit u = expert u/6, m-tile u%6 = rows (u%6)*128..+128).// The mapping is a guess made before routing is known: a wrong guess only wastes bandwidth (prefetch is a// hint). pfb is sized on the host so Xp + prefetched weights fit in L2.__global__ void __launch_bounds__(256) gather_kernel(const int* __restrict__ perm_slot, int n, const __nv_bfloat16* __restrict__ X, __nv_bfloat16* __restrict__ Xp, __nv_bfloat16* __restrict__ zero_out, const __nv_bfloat16* __restrict__ gw, const __nv_bfloat16* __restrict__ uw, int npf, int pfb, int xcopy /* 0: g12 reads X directly (xld) -> only zero out + prefetch, no Xp copy */) { // Before waiting for the routing kernel (X is a pure input): L2-prefetch all of X (T rows x 4 KB = T*32 lines // of 128 B, one line per thread over the first T*32 threads of the grid) with evict_last, so the post-wait // row reads below hit L2 instead of HBM. { const size_t line = (size_t)blockIdx.x * blockDim.x + threadIdx.x; if (line < (size_t)(n / TK) * (HD * 2 / 128)) asm volatile("prefetch.global.L2::evict_last [%0];" :: "l"(X + line * 64) : "memory"); const size_t nxl = (size_t)(n / TK) * (HD * 2 / 128); if (pfb > 0 && line >= nxl && line < nxl + (size_t)npf * 256) { const int j = (int)(line - nxl), u = j >> 8, rr = j & 255; const size_t row = (size_t)(u / 6) * ID + (u % 6) * 128 + (rr & 127); // expert u/6, m-tile u%6 const __nv_bfloat16* src = (rr < 128 ? gw : uw) + row * HD; asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" :: "l"(src), "r"(pfb) : "memory"); } } pdl_wait(); pdl_trigger(); // rows are copied in REVERSE sorted order (block 0 -> last rows): the rows written last (= lowest experts, which // g12 consumes first) are the ones still resident in L2 when Xp exceeds L2 (T >= ~4K tokens) const int row = n - 1 - (int)(blockIdx.x * 8 + (threadIdx.x >> 5)), lane = threadIdx.x & 31; if (row < 0) return; if (zero_out != nullptr && (row & 7) == 0) { uint4* zr = (uint4*)(zero_out + (size_t)(row >> 3) * HD);#pragma unroll for (int c = 0; c < HD / 8 / 32; c++) // EVICT_LAST: out rows receive 8 bulk reduces later asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1, %1, %1, %1}, %2;" :: "l"(zr + c * 32 + lane), "r"(0u), "l"(0x14F0000000000000ull) : "memory"); } if (!xcopy) return; const uint4* srow = (const uint4*)(X + (size_t)(perm_slot[row] / TK) * HD); uint4* drow = (uint4*)(Xp + (size_t)row * HD); uint4 v[HD / 8 / 32];#pragma unroll for (int c = 0; c < HD / 8 / 32; c++) v[c] = srow[c * 32 + lane];#pragma unroll for (int c = 0; c < HD / 8 / 32; c++) drow[c * 32 + lane] = v[c];}// (c') gather2_kernel: persistent variant of gather_kernel (grid = 2 CTAs per SM, grid-stride over sorted rows):// no 32K-block launch stream, and each warp keeps TWO rows' loads (2 x 4 KB) in flight before storing.// Same prefetch / zeroing / reverse row order semantics as gather_kernel.__global__ void __launch_bounds__(256, 2) gather2_kernel(const int* __restrict__ perm_slot, int n, const __nv_bfloat16* __restrict__ X, __nv_bfloat16* __restrict__ Xp, __nv_bfloat16* __restrict__ zero_out, const __nv_bfloat16* __restrict__ gw, const __nv_bfloat16* __restrict__ uw, int npf, int pfb, int xcopy) { (void)xcopy; // probe-only variant: always copies (not usable with xld) { const size_t nthr = (size_t)gridDim.x * blockDim.x, g = (size_t)blockIdx.x * blockDim.x + threadIdx.x; const size_t nxl = (size_t)(n / TK) * (HD * 2 / 128); for (size_t line = g; line < nxl; line += nthr) // X L2 prefetch (pure input, before the wait) asm volatile("prefetch.global.L2::evict_last [%0];" :: "l"(X + line * 64) : "memory"); if (pfb > 0) for (size_t j = g; j < (size_t)npf * 256; j += nthr) { // first-wave gate/up K-prefix prefetch (see above) const int u = (int)(j >> 8), rr = (int)(j & 255); const size_t row = (size_t)(u / 6) * ID + (u % 6) * 128 + (rr & 127); const __nv_bfloat16* src = (rr < 128 ? gw : uw) + row * HD; asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" :: "l"(src), "r"(pfb) : "memory"); } } pdl_wait(); pdl_trigger(); const int lane = threadIdx.x & 31; const int nw = gridDim.x * 8; for (int j = blockIdx.x * 8 + (threadIdx.x >> 5); j < n; j += 2 * nw) { const int r0 = n - 1 - j; // reverse sorted order (see gather_kernel) const bool h1 = j + nw < n; // warp-uniform const int r1 = h1 ? n - 1 - (j + nw) : r0; const uint4* s0 = (const uint4*)(X + (size_t)(perm_slot[r0] / TK) * HD); const uint4* s1 = (const uint4*)(X + (size_t)(perm_slot[r1] / TK) * HD); uint4 v0[HD / 8 / 32], v1[HD / 8 / 32];#pragma unroll for (int c = 0; c < HD / 8 / 32; c++) v0[c] = __ldg(s0 + c * 32 + lane); if (h1) {#pragma unroll for (int c = 0; c < HD / 8 / 32; c++) v1[c] = __ldg(s1 + c * 32 + lane); } if (zero_out != nullptr) { if ((r0 & 7) == 0) { uint4* zr = (uint4*)(zero_out + (size_t)(r0 >> 3) * HD);#pragma unroll for (int c = 0; c < HD / 8 / 32; c++) zr[c * 32 + lane] = make_uint4(0, 0, 0, 0); } if (h1 && (r1 & 7) == 0) { uint4* zr = (uint4*)(zero_out + (size_t)(r1 >> 3) * HD);#pragma unroll for (int c = 0; c < HD / 8 / 32; c++) zr[c * 32 + lane] = make_uint4(0, 0, 0, 0); } } uint4* d0 = (uint4*)(Xp + (size_t)r0 * HD);#pragma unroll for (int c = 0; c < HD / 8 / 32; c++) d0[c * 32 + lane] = v0[c]; if (h1) { uint4* d1 = (uint4*)(Xp + (size_t)r1 * HD);#pragma unroll for (int c = 0; c < HD / 8 / 32; c++) d1[c * 32 + lane] = v1[c]; } }}// ------------------------------------------------------------------ host side// Persistent per-call workspace (replaces a per-call torch::empty): raw device memory, grown on demand, never// freed at teardown (heap-held static pointer -> no static CUDA-object destructor). Stream ordering keeps reuse// safe exactly like the caching allocator's reuse of the previous call's block.static int g_skip = 0; // probe only: 1 = skip gather, 2 = skip g12static int g_xpf_off = 0; // probe only: 1 = no X pre-wait L2 prefetch in g12 (xld path)static int g_cpol_force = -1;static int g_dual_lo = 4600, g_dual_hi = 5376; // T 5376-6655 -> non-dual FIX2 kernel (re-test on warp-wide issuer base)#ifndef LPT_DEFAULT// + the WIDE2 band 4600 <= T < 5376#define LPT_DEFAULT(T) ((T) >= 6000 || ((T) >= 4600 && (T) < 5376))#endif// LPT unit order (route_kernel nfix): g_lpt_force 0 = shipped table, 1 = off, 2 = on (probe)static int g_lpt_force = 0;static bool lpt_on(int T) { return g_lpt_force == 2 ? true : g_lpt_force == 1 ? false : LPT_DEFAULT(T); }static int chunk_policy(int T) { if (g_cpol_force >= 0) return g_cpol_force; return 256;}// large-T first-wave prefetch K-prefix bytes per row; g_pf_force: -1 auto, 0 off, >0 probe overridestatic int g_pf_force = -1;#ifndef LARGE_PF_BYTES#define LARGE_PF_BYTES 1024#endifstatic uint8_t* persistent_ws(size_t bytes) { static uint8_t* p = nullptr; static size_t cap = 0; if (bytes > cap) { if (p) { cudaDeviceSynchronize(); cudaFree(p); } moegraph::ctx().ws_gen++; // cached graphs hold workspace pointers -> invalidate their keys cap = (bytes + (1u << 20) - 1) & ~(size_t)((1u << 20) - 1); TORCH_CHECK(cudaMalloc(&p, cap) == cudaSuccess, "workspace cudaMalloc failed"); } return p;}
// Launch a plain kernel with the programmatic-stream-serialization attribute (PDL).template <class... KArgs, class... Args>static void launch_pdl_smem(void (*k)(KArgs...), int grid, int block, size_t smem, cudaStream_t st, Args... args) { cudaLaunchConfig_t cfg = {}; cfg.gridDim = dim3(grid); cfg.blockDim = dim3(block); cfg.dynamicSmemBytes = smem; cfg.stream = st; cudaLaunchAttribute at[2]; at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; at[0].val.programmaticStreamSerializationAllowed = 1; at[1].id = cudaLaunchAttributeClusterDimension; // whole grid = one cluster (route_kernel) at[1].val.clusterDim.x = grid; at[1].val.clusterDim.y = 1; at[1].val.clusterDim.z = 1; cfg.attrs = at; cfg.numAttrs = 2; TORCH_CHECK(moegraph::launch(&cfg, k, ((KArgs)args)...) == cudaSuccess, "kernel launch failed");}template <class... KArgs, class... Args>static void launch_pdl(void (*k)(KArgs...), int grid, int block, cudaStream_t st, Args... args) { cudaLaunchConfig_t cfg = {}; cfg.gridDim = dim3(grid); cfg.blockDim = dim3(block); cfg.dynamicSmemBytes = 0; cfg.stream = st; cudaLaunchAttribute at[1]; at[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; at[0].val.programmaticStreamSerializationAllowed = 1; cfg.attrs = at; cfg.numAttrs = 1; TORCH_CHECK(moegraph::launch(&cfg, k, ((KArgs)args)...) == cudaSuccess, "kernel launch failed");}
// Band instantiations of route_kernel (compile-time chunk policy + LPT flag) for the g12 bands (T >= 1750):// 256 / LPT off (1750-2700, dual 4600-6000 outside WIDE2), 256|bit21 (2700-4000 non-dual), 288|bit21 (WIDE 4000-4600),// 352 / LPT on (WIDE2 4600-5376), 256 / LPT on (T >= 6000). Anything else -> generic runtime kernel.using RouteFn = void (*)(const int64_t*, const float*, int, int, int*, int*, float*, int4*, int*, int4*, int*, int*, int, int, int, int);template <int NC, int PO>static RouteFn route_select_po(int csh, int lp, bool rk2) { constexpr int B21 = 1 << 21; RouteFn f = nullptr; if (rk2 && csh == 160 && lp == 0) f = route_kernel<NC, 160, 0, PO, 0, 2>; else if (rk2 && csh == 192 && lp == 0) f = route_kernel<NC, 192, 0, PO, 0, 2>; else if (rk2 && csh == 256 && lp == 0) f = route_kernel<NC, 256, 0, PO, 0, 2>; else if (rk2 && csh == (256 | B21) && lp == 0) f = route_kernel<NC, 256 | B21, 0, PO, 0, 2>; else if (rk2 && csh == (288 | B21) && lp == 0) f = route_kernel<NC, 288 | B21, 0, PO, 0, 2>; else if (csh == 256 && lp == 0) f = route_kernel<NC, 256, 0, PO, 0>; else if (csh == 192 && lp == 0) f = route_kernel<NC, 192, 0, PO, 0>; else if (csh == 160 && lp == 0) f = route_kernel<NC, 160, 0, PO, 0>; else if (csh == 256 && lp == 1) f = route_kernel<NC, 256, 1, PO, 0>; else if (csh == (256 | B21) && lp == 0) f = route_kernel<NC, 256 | B21, 0, PO, 0>; else if (csh == (288 | B21) && lp == 0) f = route_kernel<NC, 288 | B21, 0, PO, 0>; else if (csh == 352 && lp == 1) f = route_kernel<NC, 352, 1, PO, 0>; else if (csh == 352 && lp == 0) f = route_kernel<NC, 352, 0, PO, 0>; else return route_kernel<NC>; // one-time attributes per specialized instantiation (same as the generic kernel's) static std::unordered_map<const void*, bool>& done = *new std::unordered_map<const void*, bool>(); if (!done[(const void*)f]) { done[(const void*)f] = true; cudaFuncSetAttribute(f, cudaFuncAttributeMaxDynamicSharedMemorySize, route_dsmem<NC>()); if (NC == 16) cudaFuncSetAttribute(f, cudaFuncAttributeNonPortableClusterSizeAllowed, 1); cudaGetLastError(); } return f;}// specialized (OV = 0, compile-time pair order) only when every CTA's slice fits its register slots; else generictemplate <int NC>static RouteFn route_select_nc(int csh, int lp, int po, int slice) { if (slice > route_rk<NC>() * ROUTE_THREADS) return route_kernel<NC>; const bool rk2 = route_rk<NC>() > 2 && slice <= 2 * ROUTE_THREADS; // RK2: 2 register slots per thread suffice return po ? route_select_po<NC, 1>(csh, lp, rk2) : route_select_po<NC, 0>(csh, lp, rk2);}static RouteFn route_select(int nc, int csh, int lp, int po, int slice) { return nc == 16 ? route_select_nc<16>(csh, lp, po, slice) : route_select_nc<8>(csh, lp, po, slice);}
static torch::Tensor moe_forward_g12(torch::Tensor hs, torch::Tensor rw, torch::Tensor sel, torch::Tensor gw, torch::Tensor uw, torch::Tensor dw, torch::Tensor out) { // host-overhead: .contiguous() only when needed (each call is a dispatcher round trip otherwise) if (!hs.is_contiguous()) hs = hs.contiguous(); if (!rw.is_contiguous()) rw = rw.contiguous(); if (!sel.is_contiguous()) sel = sel.contiguous(); // routing kernels load sel as 16 B (2 x int64) and rw as 8 B vectors: re-base misaligned views if ((reinterpret_cast<uintptr_t>(sel.data_ptr()) & 15) != 0) sel = sel.clone(); if ((reinterpret_cast<uintptr_t>(rw.data_ptr()) & 7) != 0) rw = rw.clone(); if (!gw.is_contiguous()) gw = gw.contiguous(); if (!uw.is_contiguous()) uw = uw.contiguous(); if (!dw.is_contiguous()) dw = dw.contiguous(); const int T = hs.size(0); // out allocated by the caller (outside any graph capture) if (T == 0) return out; auto stream = at::cuda::getCurrentCUDAStream(); const int nrows = T * TK;
static int num_sms = 0; if (!num_sms) cudaDeviceGetAttribute(&num_sms, cudaDevAttrMultiProcessorCount, hs.get_device()); // single routing kernel: one cluster of 16 CTAs (non-portable size) when the device can schedule it, else 8 static int route_nc = 0; if (!route_nc) { TORCH_CHECK(cudaFuncSetAttribute(route_kernel<8>, cudaFuncAttributeMaxDynamicSharedMemorySize, route_dsmem<8>()) == cudaSuccess, "route_kernel smem attribute failed"); route_nc = 8; if (cudaFuncSetAttribute(route_kernel<16>, cudaFuncAttributeNonPortableClusterSizeAllowed, 1) == cudaSuccess && cudaFuncSetAttribute(route_kernel<16>, cudaFuncAttributeMaxDynamicSharedMemorySize, route_dsmem<16>()) == cudaSuccess) { cudaLaunchConfig_t qc = {}; qc.gridDim = dim3(16); qc.blockDim = dim3(ROUTE_THREADS); qc.dynamicSmemBytes = route_dsmem<16>(); cudaLaunchAttribute qa[1]; qa[0].id = cudaLaunchAttributeClusterDimension; qa[0].val.clusterDim.x = 16; qa[0].val.clusterDim.y = 1; qa[0].val.clusterDim.z = 1; qc.attrs = qa; qc.numAttrs = 1; int ncl = 0; if (cudaOccupancyMaxActiveClusters(&ncl, route_kernel<16>, &qc) == cudaSuccess && ncl >= 1) route_nc = 16; } cudaGetLastError(); } TORCH_CHECK(nrows < (1 << 24), "route_kernel packs slot ids into 24 bits");
// Host/launch diet: everything that depends only on (T, workspace base) -- workspace carve-up, route slice / // cluster mode, gather prefetch plan, prebuilt cudaLaunchConfig + attribute arrays -- is computed once per T and // cached (heap-held, no CUDA objects -> no teardown destructor). The per-call path only patches the stream and // fills in the tensor pointers. struct G12Plan { int T = -1; uint8_t* ws = nullptr; int* off; int* n_items; int* n_items2; int4* items; int4* items2; int* ready; int* perm_slot; float* perm_w; __nv_bfloat16* Xp; __nv_bfloat16* H; int rnc = 8, g2ncl = 0, rslice, pair_order, dual, csh, pf_units, pf_bytes, xld, fcs = -1, cpk = -1, pfk = -2, dlo = -1, dhi = -1; void (*rk)(const int64_t*, const float*, int, int, int*, int*, float*, int4*, int*, int4*, int*, int*, int, int, int, int); cudaLaunchConfig_t rcfg, gcfg; cudaLaunchAttribute rat[2], gat[1]; }; static std::unordered_map<int, G12Plan*>& plans = *new std::unordered_map<int, G12Plan*>(); static G12Plan* last = nullptr; auto al = [](size_t x) { return (x + 255) & ~(size_t)255; }; const size_t nch = (size_t)(nrows / 128 + NE + 1); // upper bound on token chunks // workspace: [meta | GEMM1 items | GEMM2 items | ready | perm_slot | perm_w | Xp | H], 256 B aligned regions const size_t sz_meta = al(4 * (2 * NE + 8)), sz_items = al(16 * 6 * nch), sz_items2 = al(16 * 8 * nch), sz_ready = al(4 * nch), sz_slot = al(4 * (size_t)nrows), sz_w = al(4 * (size_t)nrows), sz_xp = al(2 * (size_t)nrows * HD), sz_h = al(2 * (size_t)nrows * ID); uint8_t* wsb = persistent_ws(sz_meta + sz_items + sz_items2 + sz_ready + sz_slot + sz_w + sz_xp + sz_h); G12Plan* pl = (last && last->T == T) ? last : nullptr; if (!pl) { auto f = plans.find(T); if (f != plans.end()) pl = f->second; else { pl = new G12Plan(); plans[T] = pl; } last = pl; } if (pl->T != T || pl->ws != wsb || pl->fcs != (g12::g_knob ^ (g12::g_wmc << 24)) || pl->cpk != g_cpol_force || pl->pfk != g_pf_force || pl->dlo != g_dual_lo || pl->dhi != g_dual_hi) { pl->T = T; pl->ws = wsb; pl->fcs = g12::g_knob ^ (g12::g_wmc << 24); pl->cpk = g_cpol_force; pl->pfk = g_pf_force; pl->dlo = g_dual_lo; pl->dhi = g_dual_hi; uint8_t* p = wsb; pl->off = (int*)p + NE; pl->n_items = pl->off + NE + 2; pl->n_items2 = pl->off + NE + 3; p += sz_meta; pl->items = (int4*)p; p += sz_items; pl->items2 = (int4*)p; p += sz_items2; pl->ready = (int*)p; p += sz_ready; pl->perm_slot = (int*)p; p += sz_slot; pl->perm_w = (float*)p; p += sz_w; pl->Xp = (__nv_bfloat16*)p; p += sz_xp; pl->H = (__nv_bfloat16*)p; // CLKW: T < 2048 routes on an 8-CTA cluster (fewer SMs active during routing) pl->rnc = T < 2048 ? 8 : route_nc; pl->rslice = (((nrows + pl->rnc - 1) / pl->rnc) + 1) & ~1; const bool cs4 = g12::cluster_size(nrows, num_sms, nullptr) == 4; const int wdm = g12::wide_mode(nrows, num_sms); // 2: WIDE2 band replaces dual units pl->dual = (!cs4 && wdm != 2 && T >= g_dual_lo && T < g_dual_hi) ? 1 : 0; // mid-T dual units (1750 <= T < 2250) dropped const int wmc = g12::wmc_mode(nrows, num_sms); // weight-multicast 4-CTA mode: plain order, even chunks pl->pair_order = ((cs4 && !wmc) || pl->dual) ? 1 : 0; // X-direct token loads in g12 (2-CTA clusters): GEMM1's B rows are cp.async-gathered from X, no Xp copy pl->xld = (!cs4 && !g12::g_xld_off) ? 1 : 0; pl->csh = g12::deep_ring(nrows, num_sms) ? 128 : wdm == 2 ? 352 : wdm ? 288 : g12::s7_mode(nrows, num_sms) == 2 ? 160 : g12::s7_mode(nrows, num_sms) ? 192 : (chunk_policy(T) | (wmc ? (1 << 20) : 0)); // mid-T tail balance (2700 <= T < 4600, dyn GEMM2 queue): GEMM2 units in descending cost order (route bit 21) if (!cs4 && !pl->dual && T >= 2700 && T < 4600) pl->csh |= (1 << 21); { int mcl2 = 0; g12::cluster_size(nrows, num_sms, &mcl2); pl->g2ncl = cs4 ? 0 : mcl2; } // LWD: g12 cluster count // first-wave weight prefetch (see gather_kernel): fused 2-CTA path where experts have one token chunk w.h.p. // (T <= 2600: mean 8T/128 <= 163 rows, chunk limit 256); per-row K prefix sized so Xp + X + prefetch <= ~88 MB of L2#ifndef GATHER_PF_MAX#define GATHER_PF_MAX 1024 // per-row K-prefix cap (bytes): 1 KB x 74 units x 256 rows ~ 19 MB ~ the routing window#endif int pf_units = 0, pf_bytes = 0; if (T <= 2600 && !g12::g_pf_off) { int mcl = 0; if (g12::cluster_size(nrows, num_sms, &mcl) == 2) { const bool pf2s = pl->xld && T < 2100; pf_units = std::min((pl->dual || pf2s) ? 2 * mcl : mcl, 6 * NE); // dual: first wave covers 2*mcl GEMM1 items const double budget = 88.0e6 - (pf2s ? 0.0 : (double)nrows * HD * 2) - (double)T * HD * 2; const int b = budget > 0 ? (int)std::min((double)(g_pf_force > 0 ? g_pf_force : GATHER_PF_MAX), budget / (pf_units * 256.0)) & ~255 : 0; pf_bytes = b; if ((size_t)(nrows + 7) / 8 * 256 < (size_t)T * 32 + (size_t)pf_units * 256) pf_bytes = 0; // not enough threads } } else if (!g12::g_pf_off && g_pf_force != 0) { // Large-T first-wave weight prefetch (X-direct 2-CTA path; g12 issues it pre-griddepcontrol.wait, overlapping the // routing kernel). Expert row counts t ~ Binomial(T, 1/16); route chunks = ceil(t/256). When mean +- 3 sd lies // inside one chunk-count bucket g >= 2, every expert has g chunks w.h.p. -> GEMM1 item u = expert u/(6g), // m-tile (u%(6g))/g, chunk u%g, so the mcl first-wave units cover ceil(mcl/g) DISTINCT (expert, m-tile) gate|up // slabs -- exactly g12's prefetch mapping (slab q = expert q/6, m-tile q%6) with npf = ceil(mcl/g). // A wrong guess (some early expert off-bucket) only wastes bandwidth (prefetch is a hint). const double mu = (double)nrows / NE, sd = std::sqrt(mu * (1.0 - (double)TK / NE)); // per-expert p = TK/NE const double ccap = (double)(pl->csh & 0xFFFF); // route chunk cap const int glo = (int)std::ceil((mu - 3.0 * sd) / ccap), ghi = (int)std::ceil((mu + 3.0 * sd) / ccap); int mcl = 0; // PFGW: WIDE (cap 288, T4000-4599) / WIDE2 (cap 352, T4600-5375) bands: experts are single-chunk w.h.p. // (glo == 1) -> GEMM1 unit u = expert u/6, m-tile u%6 = g12's slab mapping; prefetch those slabs too // PFNW: also the non-wide single-chunk band (T2601-3599): glo == ghi == 1 -> same exact slab mapping const bool wpf = (wdm != 0 && glo == 1) || (glo == 1 && ghi == 1); if (((glo == ghi && glo >= 2) || wpf) && g12::cluster_size(nrows, num_sms, &mcl) == 2) { // dual units: the first wave covers 2*mcl GEMM1 items (pair order keeps the slabs in (expert, m-tile) order) const int fw = pl->dual ? 2 * mcl : mcl; pf_units = std::min((fw + glo - 1) / glo, 6 * NE); // L2 budget: X (evict_last, T x 4 KB) + prefetched slabs (pf_units x 256 rows x pfb) <= ~88 MB const double budget = 88.0e6 - (double)T * HD * 2; // FIX2 band (T >= 5376): 2 KB K-prefix per row, 1 KB below const int cap = g_pf_force > 0 ? g_pf_force : (T >= 5376 ? 2 * LARGE_PF_BYTES : LARGE_PF_BYTES); pf_bytes = budget > 0 ? (int)std::min((double)cap, budget / (pf_units * 256.0)) & ~255 : 0; } } pl->pf_units = pf_units; pl->pf_bytes = pf_bytes; // prebuilt launch configs (route: PDL + whole-grid cluster; gather: PDL) pl->rcfg = cudaLaunchConfig_t{}; pl->rcfg.gridDim = dim3(pl->rnc); pl->rcfg.blockDim = dim3(ROUTE_THREADS); pl->rcfg.dynamicSmemBytes = (size_t)(pl->rnc == 16 ? route_dsmem<16>() : route_dsmem<8>()); pl->rat[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; pl->rat[0].val.programmaticStreamSerializationAllowed = 1; pl->rat[1].id = cudaLaunchAttributeClusterDimension; pl->rat[1].val.clusterDim.x = pl->rnc; pl->rat[1].val.clusterDim.y = 1; pl->rat[1].val.clusterDim.z = 1; pl->rcfg.attrs = pl->rat; pl->rcfg.numAttrs = 2; pl->gcfg = cudaLaunchConfig_t{}; pl->gcfg.gridDim = dim3((nrows + 7) / 8); pl->gcfg.blockDim = dim3(256); pl->gcfg.dynamicSmemBytes = 0; pl->gat[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; pl->gat[0].val.programmaticStreamSerializationAllowed = 1; pl->gcfg.attrs = pl->gat; pl->gcfg.numAttrs = 1; } int* off = pl->off; int* n_items = pl->n_items; int* n_items2 = pl->n_items2; int4* items = pl->items; int4* items2 = pl->items2; int* ready = pl->ready; int* perm_slot = pl->perm_slot; float* perm_w = pl->perm_w; __nv_bfloat16* Xp = pl->Xp; __nv_bfloat16* H = pl->H;
const int64_t* selp = (const int64_t*)sel.data_ptr(); pl->rcfg.stream = stream; const int rnfix = lpt_on(T) ? (pl->pf_bytes > 0 ? std::min(NE, (pl->pf_units + 5) / 6) : 0) : NE; pl->rk = route_select(pl->rnc, pl->csh, rnfix < NE ? 1 : 0, pl->pair_order, pl->rslice); TORCH_CHECK(moegraph::launch(&pl->rcfg, pl->rk, selp, (const float*)rw.data_ptr(), nrows, pl->rslice, off, perm_slot, perm_w, items, n_items, items2, n_items2, ready, pl->pair_order, rnfix, pl->csh, (pl->csh & (1 << 21)) ? pl->g2ncl : 0) == cudaSuccess, "route launch failed"); pl->gcfg.stream = stream;#ifdef G12_PROBE cudaLaunchConfig_t gc2 = pl->gcfg; if (g_gmode) gc2.gridDim = dim3(std::min((nrows + 7) / 8, 2 * num_sms)); TORCH_CHECK(moegraph::launch(&gc2, g_gmode ? gather2_kernel : gather_kernel, (const int*)perm_slot, nrows, (const __nv_bfloat16*)hs.data_ptr(), Xp, (__nv_bfloat16*)out.data_ptr(), (const __nv_bfloat16*)gw.data_ptr(), (const __nv_bfloat16*)uw.data_ptr(), pl->pf_units, pl->pf_bytes, pl->xld ? 0 : 1) == cudaSuccess, "gather launch failed");#else // xld (X-direct) path: no gather kernel at all -- g12 prefetches X / first-wave weights in its pre-wait prologue // and zeroes out itself (one launch less; g12 now launches during the routing kernel) if (!(g_skip & 1) && !pl->xld) TORCH_CHECK(moegraph::launch(&pl->gcfg, gather_kernel, (const int*)perm_slot, nrows, (const __nv_bfloat16*)hs.data_ptr(), Xp, (__nv_bfloat16*)out.data_ptr(), (const __nv_bfloat16*)gw.data_ptr(), (const __nv_bfloat16*)uw.data_ptr(), pl->pf_units, pl->pf_bytes, pl->xld ? 0 : 1) == cudaSuccess, "gather launch failed");#endif
// fused GEMM1+GEMM2 persistent kernel (g12fused.cu), one launch, per-chunk ready counters; // GEMM2 epilogue bulk-reduces (bf16 add) the weighted expert rows directly into the zeroed out if (!(g_skip & 2)) g12::launch(gw.data_ptr(), uw.data_ptr(), dw.data_ptr(), Xp, H, nrows, items, n_items, items2, n_items2, perm_slot, perm_w, ready, (__nv_bfloat16*)out.data_ptr(), num_sms, stream, // X was L2-prefetched evict_last by gather_kernel; g12 demotes those lines once the gather is done hs.data_ptr(), T * (HD * 2 / 128), pl->xld, (pl->xld && !g_xpf_off && T < 4600) ? T * (HD * 2 / 128) : 0, gw.data_ptr(), uw.data_ptr(), pl->pf_units, pl->xld ? pl->pf_bytes : 0, pl->xld ? T : 0, n_items2 + 1, pl->dual); return out;}
// ------------------------------------------------------------------ backend dispatch
namespace moegraph {Ctx& ctx() { static Ctx& c = *new Ctx(); return c; }}// PLCE helper: re-wire every programmatic out-edge of the kernel node running `kfn` (route) to the launch-completion port.static void plce_rewire(cudaGraph_t g, const void* kfn) {#if CUDART_VERSION >= 13000#define PLCE_GET cudaGraphGetEdges#define PLCE_RM cudaGraphRemoveDependencies#define PLCE_ADD cudaGraphAddDependencies#else#define PLCE_GET cudaGraphGetEdges_v2#define PLCE_RM cudaGraphRemoveDependencies_v2#define PLCE_ADD cudaGraphAddDependencies_v2#endif size_t n = 0; if (PLCE_GET(g, nullptr, nullptr, nullptr, &n) != cudaSuccess || n == 0) { cudaGetLastError(); return; } std::vector<cudaGraphNode_t> fr(n), to(n); std::vector<cudaGraphEdgeData> ed(n); if (PLCE_GET(g, fr.data(), to.data(), ed.data(), &n) != cudaSuccess) { cudaGetLastError(); return; } for (size_t i = 0; i < n; i++) { if (ed[i].type != cudaGraphDependencyTypeProgrammatic) continue; cudaGraphNodeType ty; if (cudaGraphNodeGetType(fr[i], &ty) != cudaSuccess || ty != cudaGraphNodeTypeKernel) { cudaGetLastError(); continue; } cudaKernelNodeParams kp = {}; if (cudaGraphKernelNodeGetParams(fr[i], &kp) != cudaSuccess) { cudaGetLastError(); continue; } if ((const void*)kp.func != kfn) continue; cudaGraphEdgeData ne = ed[i]; ne.from_port = cudaGraphKernelNodePortLaunchCompletion; if (PLCE_RM(g, &fr[i], &to[i], &ed[i], 1) != cudaSuccess) { cudaGetLastError(); continue; } if (PLCE_ADD(g, &fr[i], &to[i], &ne, 1) != cudaSuccess) { cudaGetLastError(); if (PLCE_ADD(g, &fr[i], &to[i], &ed[i], 1) != cudaSuccess) cudaGetLastError(); // restore original edge } }#undef PLCE_GET#undef PLCE_RM#undef PLCE_ADD}template <class F>static torch::Tensor graph_forward(int T, const torch::Tensor& hs, const torch::Tensor& rw, const torch::Tensor& sel, const torch::Tensor& gw, const torch::Tensor& uw, const torch::Tensor& dw, torch::Tensor& out, F&& run_path) { using namespace moegraph; constexpr int NKEY = 8, MAXE = 3; struct Ent { uintptr_t key[NKEY]; cudaGraph_t g; cudaGraphExec_t x; std::vector<std::pair<const void*, cudaGraphNode_t>> nodes; uint64_t used; }; struct PerT { bool seen = false, off = false; std::vector<Ent*> ents; Ent* mru = nullptr; }; // mru: last replayed instance (checked first) static std::unordered_map<int, PerT*>& tab = *new std::unordered_map<int, PerT*>(); static uint64_t tick = 0; static cudaStream_t cap = nullptr; Ctx& c = ctx(); cudaStream_t stream = at::cuda::getCurrentCUDAStream(); // host diet: the last T's table entry is cached (back-to-back calls of one shape skip the hash lookup) static int last_T = -1; static PerT* last_pt = nullptr; PerT* pt = (T == last_T) ? last_pt : nullptr; if (!pt) { PerT*& slot = tab[T]; if (!slot) slot = new PerT(); pt = slot; last_T = T; last_pt = pt; } if (!pt->seen || pt->off) { pt->seen = true; run_path(); return out; } cudaStreamCaptureStatus cs = cudaStreamCaptureStatusNone; if (cudaStreamIsCapturing(stream, &cs) != cudaSuccess || cs != cudaStreamCaptureStatusNone) { cudaGetLastError(); run_path(); return out; } const uintptr_t key[NKEY] = {(uintptr_t)hs.data_ptr(), (uintptr_t)rw.data_ptr(), (uintptr_t)sel.data_ptr(), (uintptr_t)gw.data_ptr(), (uintptr_t)uw.data_ptr(), (uintptr_t)dw.data_ptr(), (uintptr_t)out.data_ptr(), (uintptr_t)c.ws_gen}; // host diet: back-to-back calls with the same buffers hit the most recently replayed instance first Ent* hit = nullptr; if (pt->mru) { bool eq = true; for (int i = 0; i < NKEY; i++) eq = eq && pt->mru->key[i] == key[i]; if (eq) hit = pt->mru; } if (!hit) for (Ent* e : pt->ents) { bool eq = true; for (int i = 0; i < NKEY; i++) eq = eq && e->key[i] == key[i]; if (eq) { hit = e; break; } } if (!hit && (int)pt->ents.size() >= MAXE) { // re-parameterize the least recently used instance in place Ent* lru = pt->ents[0]; for (Ent* e : pt->ents) if (e->used < lru->used) lru = e; c.mode = PATCH; c.exec = lru->x; c.nodes = &lru->nodes; c.fail = false; try { run_path(); } catch (...) { c.mode = EAGER; throw; } c.mode = EAGER; if (c.fail) { pt->off = true; run_path(); return out; } // could not update: eager from now on for (int i = 0; i < NKEY; i++) lru->key[i] = key[i]; if (cudaGraphUpload(lru->x, stream) != cudaSuccess) cudaGetLastError(); // HUP: re-upload patched params hit = lru; } if (!hit) { if (!cap) TORCH_CHECK(cudaStreamCreateWithFlags(&cap, cudaStreamNonBlocking) == cudaSuccess, "capture stream"); c.launched.clear(); c.mode = CAPTURE; c.cap = cap; cudaGraph_t g = nullptr; if (cudaStreamBeginCapture(cap, cudaStreamCaptureModeRelaxed) != cudaSuccess) { c.mode = EAGER; cudaGetLastError(); pt->off = true; run_path(); return out; } try { run_path(); } catch (...) { c.mode = EAGER; cudaStreamEndCapture(cap, &g); if (g) cudaGraphDestroy(g); cudaGetLastError(); throw; } c.mode = EAGER; const cudaError_t ee = cudaStreamEndCapture(cap, &g); cudaGraphExec_t x = nullptr; // PLCE (all bands; PLCEF extends it to the fastpath route_cluster/count_scan -> moe_gemm hand-off, T < 1250): the route -> next-kernel graph edge (captured as a programmatic edge from the PDL // attribute, port = griddepcontrol.launch_dependents) is re-wired to the kernel node's LAUNCH-COMPLETION port: the // dependent kernel may launch once every route block has STARTED (triggerAtBlockStart semantics), without waiting // for the in-kernel trigger instruction. Memory visibility is unchanged: the dependent still griddepcontrol.waits, // which blocks until route has fully completed and flushed. Any API failure leaves the original edge in place. if (ee == cudaSuccess && g != nullptr && c.launched.size() >= 2) plce_rewire(g, c.launched[0]); // PLCEF: all bands (fastpath route/count_scan -> moe_gemm too) bool ok = ee == cudaSuccess && g != nullptr && cudaGraphInstantiate(&x, g, 0) == cudaSuccess; Ent* e = new Ent(); if (ok) { size_t n = 0; cudaGraphGetNodes(g, nullptr, &n); std::vector<cudaGraphNode_t> ns(n); if (n) cudaGraphGetNodes(g, ns.data(), &n); for (auto nd : ns) { cudaGraphNodeType ty; if (cudaGraphNodeGetType(nd, &ty) != cudaSuccess || ty != cudaGraphNodeTypeKernel) continue; cudaKernelNodeParams kp = {}; if (cudaGraphKernelNodeGetParams(nd, &kp) != cudaSuccess) { ok = false; break; } e->nodes.push_back({(const void*)kp.func, nd}); } // every launched kernel must map to exactly one node (PATCH matches nodes by kernel function) ok = ok && e->nodes.size() == c.launched.size(); for (const void* f : c.launched) { int m = 0; for (auto& pr : e->nodes) m += pr.first == f; ok = ok && m == 1; } } if (!ok) { cudaGetLastError(); if (x) cudaGraphExecDestroy(x); if (g) cudaGraphDestroy(g); delete e; pt->off = true; run_path(); return out; } e->g = g; e->x = x; // HUP: upload the executable graph to the device once at instantiation (on the caller's stream) so the // first replay does not pay the implicit per-launch upload of its node / parameter state; replays are // then pure cudaGraphLaunch calls. Host-side only, no change to any kernel or value. if (cudaGraphUpload(x, stream) != cudaSuccess) cudaGetLastError(); for (int i = 0; i < NKEY; i++) e->key[i] = key[i]; pt->ents.push_back(e); hit = e; } hit->used = ++tick; pt->mru = hit; TORCH_CHECK(cudaGraphLaunch(hit->x, stream) == cudaSuccess, "graph launch failed"); return out;}
namespace fastpath {extern int g_fp_grid;extern int g_fp_pfkb, g_fp_hpl;extern int g_fp_tsl, g_fp_tm96s;extern int g_fp_rnc;torch::Tensor moe_forward(torch::Tensor hs, torch::Tensor rw, torch::Tensor sel, torch::Tensor gw, torch::Tensor uw, torch::Tensor dw, int hilo, int no2, torch::Tensor out);}torch::Tensor moe_forward(const torch::Tensor& hs, const torch::Tensor& rw, const torch::Tensor& sel, const torch::Tensor& gw, const torch::Tensor& uw, const torch::Tensor& dw) { const bool canon = hs.is_contiguous() && rw.is_contiguous() && sel.is_contiguous() && gw.is_contiguous() && uw.is_contiguous() && dw.is_contiguous() && ((reinterpret_cast<uintptr_t>(sel.data_ptr()) & 15) | (reinterpret_cast<uintptr_t>(rw.data_ptr()) & 7)) == 0; if (!canon) { torch::Tensor h2 = hs.contiguous(), r2 = rw.contiguous(), s2 = sel.contiguous(); if ((reinterpret_cast<uintptr_t>(s2.data_ptr()) & 15) != 0) s2 = s2.clone(); if ((reinterpret_cast<uintptr_t>(r2.data_ptr()) & 7) != 0) r2 = r2.clone(); return moe_forward(h2, r2, s2, gw.contiguous(), uw.contiguous(), dw.contiguous()); // canonical now }
#ifndef G12_S8LO_H#define G12_S8LO_H 1250#endif const int T = (int)hs.size(0); torch::Tensor out(at::detail::empty_cuda({T, HD}, hs.scalar_type(), hs.device(), c10::nullopt)); if (T == 0) return out; // host path of the selected backend (launches go through moegraph::launch: eager / capture / patch) auto run_path = [&]() {#ifndef MID_FAST_MAX#define MID_FAST_MAX 1250#endif if (T < 1152) fastpath::moe_forward(hs, rw, sel, gw, uw, dw, 1, 0, out); else if (T < MID_FAST_MAX) fastpath::moe_forward(hs, rw, sel, gw, uw, dw, 0, 0, out); else moe_forward_g12(hs, rw, sel, gw, uw, dw, out); }; return graph_forward(T, hs, rw, sel, gw, uw, dw, out, run_path);}1234#pragma once#include <torch/extension.h>torch::Tensor moe_forward(const torch::Tensor& hs, const torch::Tensor& rw, const torch::Tensor& sel, const torch::Tensor& gw, const torch::Tensor& uw, const torch::Tensor& dw);12345678// Entry point: run(...) -> moe_forward (all device work is launched on the current stream).#include "kernel.h"// const references: pybind's casters own the Tensors; no per-call refcount copies (launch-sequence audit)torch::Tensor run(const torch::Tensor& hs, const torch::Tensor& rw, const torch::Tensor& sel, const torch::Tensor& gw, const torch::Tensor& uw, const torch::Tensor& dw) { return moe_forward(hs, rw, sel, gw, uw, dw);}PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run, "MoE forward (PLCE launch-completion edge, all bands; CLKW 8-CTA route T<2048; ESS)"); }1234567891011# MoE sparse routing and dispatch backward (L2 011)
Backward of an MoE router (softmax, top-k, weight normalization): gradients for the hidden states and the gate weight.
- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 6 (7,317 lines).- Idea: Two launches in a CUDA graph: a warp-per-token router backward kernel, then one tcgen05 kernel that computes both gradient GEMMs (hidden states and gate weight).- Result: SOL score 0.833; speedup 4.26x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11.- Origin: search agent (Claude).- Comments edited; unused test helpers removed; the code that runs is identical to the scored submission.- Re-checked on a B200 after the edit: it builds and passes every workload of the SOL-ExecBench correctness check.- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778{ "board": "L2", "id": "011_moe_sparse_routing_and_dispatch_backward", "name": "MoE sparse routing and dispatch backward", "language": "CUDA C++", "files": [ { "path": "src/dg_xdyn.cuh", "lines": 374, "bytes": 18845 }, { "path": "src/kernel.cu", "lines": 5258, "bytes": 336112 }, { "path": "src/main.cpp", "lines": 482, "bytes": 24623 }, { "path": "src/route_b.cuh", "lines": 318, "bytes": 15727 }, { "path": "src/route_c.cuh", "lines": 778, "bytes": 41599 }, { "path": "src/route_v.cuh", "lines": 107, "bytes": 5382 } ], "origin": "search agent (Claude)", "result": { "public": true, "sol_score": 0.832835, "speedup": 4.2604, "board_row": true, "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" }, "idea": "Two launches in a CUDA graph: a warp-per-token router backward kernel, then one tcgen05 kernel that computes both gradient GEMMs (hidden states and gate weight).", "spec": { "languages": [ "cuda_cpp" ], "target_hardware": [ "B200", "LOCAL" ], "entry_point": "main.cpp::run", "binding": "torch", "destination_passing_style": false, "dependencies": [], "compile_options": { "cuda_cflags": [ "-std=c++17", "-gencode=arch=compute_100a,code=sm_100a" ], "ld_flags": [ "-lcuda" ], "cflags": [] }, "sources": [ "kernel.cu", "main.cpp", "route_b.cuh", "route_c.cuh", "route_v.cuh", "dg_xdyn.cuh" ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374// XDYN: large band (T >= 16384) fused dual GEMM over ALL SMs with a dynamic tile scheduler.//// Split-K: each CTA bulk-reduces (cp.reduce.async.bulk .add.f32) its fp32 acc2 partial(s) into the zeroed fp32// accumulator ws, then a grid-wide epoch barrier (all CTAs co-resident), then CTA b casts / re-zeroes its 1/NC// slice of the 128 x 2048 sums -> out2 (bf16); CTA c < 16 resets queue c after the barrier.// Warp roles (8 warps): 0 = TMA producer (claims, H + G rings), 1 = GEMM1 issuer (out1 tile = G @ W chunk),// 6 = GEMM2 issuer (acc2 += G^T @ H), 2..5 = out1 epilogue (TMEM -> bf16 SW128 box -> TMA store),// 0/1/6/7 = acc2 drain + finalize after their loops.// smem: W 32KB | H ring 3 x 32KB | G ring 2 x 32KB | 2 x 16KB out1 boxes (same carve-up as dual_gemm_tc_kernel).// TMEM (512 cols): acc1 x2 (0..255), acc2 buffer 0 = home chunk (256..383), buffer 1 = stolen chunk (384..511).// NA1 = 3 (ACC3, STEAL == 0 only): acc1 TRIPLE-buffered in TMEM (cols 0, 128, 384; acc2 stays at 256) so the// out1 epilogue may lag GEMM1 by 3 tiles before the G ring (released by GEMM1) back-pressures GEMM2 / the H stream.// Third buffer barriers: A1F 19, A1E 20.template <int STEAL, int PFD = 2, int NA1 = 2> // PFD: rolling H L2 prefetch distance (items ahead, 1 or 2); 0 = no cross-chunk stealing, else: steal only if the target has >= STEAL tiles left__global__ void __launch_bounds__(DG_NTHREADS, 1)dg_xdyn_kernel(const __grid_constant__ CUtensorMap tmG, // G [T,128] box {64,128} const __grid_constant__ CUtensorMap tmW, // W [128,2048] box {64,128} const __grid_constant__ CUtensorMap tmH, // H [T,2048] box {64,128} const __grid_constant__ CUtensorMap tmO, // out1[T,2048] box {64,128} __nv_bfloat16* __restrict__ out2, // [128,2048] float* __restrict__ ws, // [128,2048] fp32 accum, zero on entry (re-zeroed) unsigned long long* __restrict__ xc, // [0] grid barrier epoch, [1 + b] work counter of CTA b int T) { B4GE(); if (threadIdx.x == 0) { tmap_prefetch(&tmG); tmap_prefetch(&tmW); tmap_prefetch(&tmH); tmap_prefetch(&tmO); } extern __shared__ __align__(1024) unsigned char smem_raw[]; unsigned char* smem = reinterpret_cast<unsigned char*>(((uintptr_t)smem_raw + 1023) & ~(uintptr_t)1023); const uint32_t sbase = smem_u32(smem); uint64_t* bars = reinterpret_cast<uint64_t*>(smem + DG_OFF_BAR); // barriers: W 0, HF 1..3, HE 4..6, GF 7..8, GE 9..10, A1F 11..12, A1E 13..14, A2F 15, (16 = TMEM slot), WE 17, G1D 18 constexpr uint32_t B_W = 0, B_HF = 1, B_HE = 4, B_GF = 7, B_GE = 9, B_A1F = 11, B_A1E = 13, B_A2F = 15, B_WE = 17, B_G1D = 18; uint32_t* tmem_slot = reinterpret_cast<uint32_t*>(smem + DG_OFF_BAR + 128); __shared__ int s_tile[16]; // item id ring (it & 15), -1 = end __shared__ int s_used[2]; // acc2 buffer 0 / 1 received MMAs __shared__ int s_cs; // chunk of acc2 buffer 1 (stolen chunk) auto bar = [&](uint32_t i) { return smem_u32(&bars[i]); }; static_assert(NA1 == 2 || (NA1 == 3 && STEAL == 0), "ACC3 uses the stolen-chunk acc2 TMEM columns"); auto a1f = [&](int i) { return bar(i < 2 ? B_A1F + i : 19); }; auto a1e = [&](int i) { return bar(i < 2 ? B_A1E + i : 20); }; auto a1c = [&](int i) { return (uint32_t)(i < 2 ? i * 128 : 384); }; // acc1 buffer i TMEM column
const int tid = threadIdx.x, lane = tid & 31, warp = tid >> 5; const int b = blockIdx.x, NC = gridDim.x; const int ntiles = (T + TBT - 1) / TBT; const int c0 = b % 16; unsigned long long* const cq = xc + 1; bool od = false, sd = STEAL == 0; // claim state (thread 0 only) int cs = -1; // stolen chunk auto claim = [&]() -> int { if (!od) { const unsigned long long t = atomicAdd(cq + c0, 1ull); if (t < (unsigned long long)ntiles) return c0 * ntiles + (int)t; od = true; } if (!sd) { if (cs < 0) { // pick the chunk with the most remaining tiles (lowest counter) unsigned long long v[16];#pragma unroll for (int c = 0; c < 16; c++) asm volatile("ld.relaxed.gpu.global.u64 %0, [%1];" : "=l"(v[c]) : "l"(cq + c) : "memory"); unsigned long long best = ~0ull;#pragma unroll for (int j = 0; j < 16; j++) { const int c = (c0 + 1 + j) & 15; if (c != c0 && v[c] < best) { best = v[c]; cs = c; } } if (cs >= 0 && best + (unsigned long long)STEAL > (unsigned long long)ntiles) cs = -1; // too little left } if (cs >= 0) { const unsigned long long t = atomicAdd(cq + cs, 1ull); if (t < (unsigned long long)ntiles) return cs * ntiles + (int)t; } sd = true; } return -1; };
if (tid == 0) { mbar_init(bar(B_W), 1); for (int s = 0; s < DG_HNS; s++) { mbar_init(bar(B_HF + s), 1); mbar_init(bar(B_HE + s), 1); } for (int s = 0; s < DG_GNS; s++) { mbar_init(bar(B_GF + s), 1); mbar_init(bar(B_GE + s), 2); } // GE: both issuers for (int i = 0; i < NA1; i++) { mbar_init(a1f(i), 1); mbar_init(a1e(i), 128); } mbar_init(bar(B_A2F), 1); mbar_init(bar(B_WE), 1); mbar_init(bar(B_G1D), 1); asm volatile("fence.mbarrier_init.release.cluster;" ::: "memory"); } if (warp == 1) { asm volatile("tcgen05.alloc.cta_group::1.sync.aligned.shared::cta.b32 [%0], 512;" :: "r"(smem_u32(tmem_slot))); asm volatile("tcgen05.relinquish_alloc_permit.cta_group::1.sync.aligned;"); } tc_fence_before(); __syncthreads(); tc_fence_after(); const uint32_t tmem = *tmem_slot;
// ---- PDL prologue (G-independent): W chunk c0 + the first DG_HNS claimed items' H tiles if (tid == 0) { mbar_expect_tx(bar(B_W), TILE_BYTES); tma_load2d(sbase + DG_OFF_W, &tmW, c0 * BN, 0, bar(B_W)); tma_load2d(sbase + DG_OFF_W + BOX_BYTES, &tmW, c0 * BN + 64, 0, bar(B_W)); for (int s = 0; s < DG_HNS; s++) { const int item = claim(); s_tile[s] = item; if (item < 0) continue; const int col0 = (item / ntiles) * BN, tok0 = (item % ntiles) * TBT; mbar_expect_tx(bar(B_HF + s), TILE_BYTES); tma_load2d(sbase + DG_OFF_H(s), &tmH, col0, tok0, bar(B_HF + s)); tma_load2d(sbase + DG_OFF_H(s) + BOX_BYTES, &tmH, col0 + 64, tok0, bar(B_HF + s)); } } pdl_wait(); // route (producer of G) complete + visible
if (warp == 0) { // ------------------------------------------------------------ producer: claims (lane 0) + H / G rings __syncwarp(); for (int it = 0;; it++) { const int item = *(volatile int*)&s_tile[it & 15]; if (item < 0) { // end: G FULL arrival without bytes once the G slot is free (consumers see -1) const int sg = it % DG_GNS; if (it >= DG_GNS) mbar_wait_w(bar(B_GE + sg), ((it / DG_GNS) - 1) & 1); if (lane == 0) mbar_arrive(bar(B_GF + sg)); if (lane == 0) s_cs = cs; __syncwarp(); break; } int r = -1; if (lane == 0) r = claim(); // item it + 3 (result consumed at the end of this iteration) const int i2 = *(volatile int*)&s_tile[(it + PFD) & 15]; if (it + PFD >= DG_HNS && i2 >= 0) { // rolling L2 prefetch of the H tile PFD items ahead (both 64-col boxes) const int pc = (i2 / ntiles) * BN, pt = (i2 % ntiles) * TBT; asm volatile("{\n .reg .pred e;\n .reg .b32 r;\n elect.sync r|e, 0xffffffff;\n" " @e cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%1, %2}];\n" " @e cp.async.bulk.prefetch.tensor.2d.L2.global.tile [%0, {%3, %2}];\n}" :: "l"(reinterpret_cast<uint64_t>(&tmH)), "r"(pc), "r"(pt), "r"(pc + 64) : "memory"); } const int col0 = (item / ntiles) * BN, tok0 = (item % ntiles) * TBT; if (it >= DG_HNS) { const int sh = it % DG_HNS; mbar_wait_w(bar(B_HE + sh), ((it / DG_HNS) - 1) & 1); mbar_expect_tx_e(bar(B_HF + sh), TILE_BYTES); tma_load2d_e(sbase + DG_OFF_H(sh), &tmH, col0, tok0, bar(B_HF + sh)); tma_load2d_e(sbase + DG_OFF_H(sh) + BOX_BYTES, &tmH, col0 + 64, tok0, bar(B_HF + sh)); } const int sg = it % DG_GNS; if (it >= DG_GNS) mbar_wait_w(bar(B_GE + sg), ((it / DG_GNS) - 1) & 1); mbar_expect_tx_e(bar(B_GF + sg), TILE_BYTES); tma_load2d_e(sbase + DG_OFF_G(sg), &tmG, 0, tok0, bar(B_GF + sg)); tma_load2d_e(sbase + DG_OFF_G(sg) + BOX_BYTES, &tmG, 64, tok0, bar(B_GF + sg)); if (lane == 0) s_tile[(it + 3) & 15] = r; __syncwarp(); } } else if (warp == 1) { // ------------------------------------------------------------ GEMM1: acc1[b][tok][c] = sum_e G[tok][e] W[e][c] constexpr uint32_t ID1 = make_idesc(0, 1); // A=G K-major, B=W MN-major mbar_wait(bar(B_W), 0); __syncwarp(); tc_fence_after(); const uint64_t dA0 = make_desc(sbase + DG_OFF_G(0), 16, 1024); const uint64_t dB0 = make_desc(sbase + DG_OFF_W, BOX_BYTES, 1024); int curc = c0; uint32_t wph = 1, wep = 0; for (int it = 0;; it++) { const int sg = it % DG_GNS, bb = it % NA1; const uint32_t aph = (uint32_t)((it / NA1) & 1); mbar_wait(bar(B_GF + sg), (it / DG_GNS) & 1); __syncwarp(); const int item = *(volatile int*)&s_tile[it & 15]; if (item < 0) { // forward the end to the epilogue (empty commit) mbar_wait(a1e(bb), aph ^ 1); __syncwarp(); tc_fence_after(); umma_commit_e(a1f(bb)); break; } const int ch = item / ntiles; if (ch != curc) { // chunk switch: all GEMM1 MMAs on the old W done -> reload W in place umma_commit_e(bar(B_WE)); mbar_wait(bar(B_WE), wep); wep ^= 1u; __syncwarp(); mbar_expect_tx_e(bar(B_W), TILE_BYTES); tma_load2d_e(sbase + DG_OFF_W, &tmW, ch * BN, 0, bar(B_W)); tma_load2d_e(sbase + DG_OFF_W + BOX_BYTES, &tmW, ch * BN + 64, 0, bar(B_W)); mbar_wait(bar(B_W), wph); wph ^= 1u; __syncwarp(); curc = ch; } mbar_wait(a1e(bb), aph ^ 1); __syncwarp(); tc_fence_after(); const uint64_t aS = dA0 + (uint64_t)((uint32_t)(sg * TILE_BYTES) >> 4);#pragma unroll for (int kk = 0; kk < 8; kk++) umma_e(tmem + a1c(bb), aS + (uint64_t)(((kk >> 2) * BOX_BYTES + (kk & 3) * 32) >> 4), dB0 + (uint64_t)(kk * (2048 >> 4)), ID1, kk > 0); umma_commit_e(a1f(bb)); umma_commit_e(bar(B_GE + sg)); } umma_commit_e(bar(B_G1D)); // every GEMM1 MMA (G ring / W readers) complete } else if (warp == 6) { // ------------------------------------------------------------ GEMM2: acc2[buf][e][c] += sum_tok G[tok][e] H[tok][c] constexpr uint32_t ID2 = make_idesc(1, 1); // A=G^T MN-major, B=H MN-major const uint64_t dA0 = make_desc(sbase + DG_OFF_G(0), BOX_BYTES, 1024); const uint64_t dB0 = make_desc(sbase + DG_OFF_H(0), BOX_BYTES, 1024); uint32_t on0 = 0, on1 = 0; for (int it = 0;; it++) { const int sg = it % DG_GNS, sh = it % DG_HNS; mbar_wait(bar(B_GF + sg), (it / DG_GNS) & 1); __syncwarp(); const int item = *(volatile int*)&s_tile[it & 15]; if (item < 0) break; const int ch = item / ntiles, tl = item % ntiles; const int bu = ch != c0 ? 1 : 0; // home chunk -> buffer 0, stolen chunk -> buffer 1 const int vt = T - tl * TBT; const int nk = vt >= TBT ? 8 : (vt + 15) >> 4; // K-trim: rows >= T are zero mbar_wait(bar(B_HF + sh), (it / DG_HNS) & 1); __syncwarp(); tc_fence_after(); const uint64_t aS = dA0 + (uint64_t)((uint32_t)(sg * TILE_BYTES) >> 4); const uint64_t bS = dB0 + (uint64_t)((uint32_t)(sh * TILE_BYTES) >> 4); const uint32_t d = tmem + 256 + bu * 128; uint32_t on = bu ? on1 : on0; if (nk == 8 && on) {#pragma unroll for (int kk = 0; kk < 8; kk++) umma_e(d, aS + (uint64_t)(kk * (2048 >> 4)), bS + (uint64_t)(kk * (2048 >> 4)), ID2, 1u); } else {#pragma unroll for (int kk = 0; kk < 8; kk++) { if (kk < nk) { umma_e(d, aS + (uint64_t)(kk * (2048 >> 4)), bS + (uint64_t)(kk * (2048 >> 4)), ID2, on); on = 1; } } } if (bu) on1 = on; else on0 = on; umma_commit_e(bar(B_GE + sg)); umma_commit_e(bar(B_HE + sh)); } if (lane == 0) { s_used[0] = (int)on0; s_used[1] = (int)on1; } umma_commit_e(bar(B_A2F)); } else if (warp >= 2 && warp <= 5) { // ------------------------------------------------------------ out1 epilogue (warps 2..5, TMEM lane quarter warp & 3) const int q = warp & 3; const int row = q * 32 + lane; const int et = tid - 64; for (int it = 0;; it++) { const int bb = it % NA1; mbar_wait(a1f(bb), (it / NA1) & 1); const int item = *(volatile int*)&s_tile[it & 15]; if (item < 0) break; const int col0e = (item / ntiles) * BN, tok0e = (item % ntiles) * TBT; tc_fence_after();#pragma unroll for (int h = 0; h < 2; h++) { const uint32_t sO = sbase + DG_OFF_O + h * BOX_BYTES; unsigned char* pO = smem + DG_OFF_O + h * BOX_BYTES; uint32_t rr2[2][32]; tmem_ld64_nw(tmem + ((uint32_t)(q * 32) << 16) + a1c(bb) + h * 64, &rr2[0][0]); // in flight across the reuse wait if (et == 0) asm volatile("cp.async.bulk.wait_group.read 1;" ::: "memory"); named_bar(1, 128); tmem_ld_wait(); reg_pin32(rr2[0]); reg_pin32(rr2[1]); if (h == 1) { tc_fence_before(); mbar_arrive(a1e(bb)); } // acc1[bb] free for GEMM1#pragma unroll for (int c2 = 0; c2 < 2; c2++) {#pragma unroll for (int j = 0; j < 4; j++) { const int c16 = c2 * 4 + j; // 16B chunk within the 128B box row const uint32_t* r = rr2[c2]; uint4 v; v.x = pack_bf16(r[j * 8 + 0], r[j * 8 + 1]); v.y = pack_bf16(r[j * 8 + 2], r[j * 8 + 3]); v.z = pack_bf16(r[j * 8 + 4], r[j * 8 + 5]); v.w = pack_bf16(r[j * 8 + 6], r[j * 8 + 7]); *reinterpret_cast<uint4*>(pO + row * 128 + ((c16 ^ (row & 7)) << 4)) = v; // 128B swizzle } } asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); named_bar(1, 128); if (et == 0) { tma_store2d(&tmO, sO, col0e + h * 64, tok0e); // rows >= T clipped asm volatile("cp.async.bulk.commit_group;" ::: "memory"); } } } if (et == 0) asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); tc_fence_before(); asm volatile("bar.arrive 2, 160;" ::: "memory"); B4X(); return; } // ---------------- warps 0, 1, 6, 7: acc2 drain (bulk reduce into ws), grid barrier, distributed finalize __syncwarp(); named_bar(3, 128); // warp 6's s_used visible const int u0 = s_used[0], u1 = s_used[1], cb1 = s_cs; const int q = warp & 3; const int row = q * 32 + lane; if (u0 | u1) { mbar_wait(bar(B_A2F), 0); // all GEMM2 MMAs (H ring readers) done mbar_wait(bar(B_G1D), 0); // all GEMM1 MMAs (G ring readers) done -> H + G rings free for staging __syncwarp(); tc_fence_after();#pragma unroll 1 for (int u = 0; u < 2; u++) { if (!(u ? u1 : u0)) continue; uint32_t r[4][32]; tmem_ld64_nw(tmem + ((uint32_t)(q * 32) << 16) + 256 + u * 128, &r[0][0]); tmem_ld64_nw(tmem + ((uint32_t)(q * 32) << 16) + 256 + u * 128 + 64, &r[2][0]); tmem_ld_wait();#pragma unroll for (int cc = 0; cc < 4; cc++) reg_pin32(r[cc]); float* stg = reinterpret_cast<float*>(smem + DG_OFF_H(0)) + u * (E * ACC_LD);#pragma unroll for (int cc = 0; cc < 4; cc++)#pragma unroll for (int j = 0; j < 8; j++) *reinterpret_cast<float4*>(stg + row * ACC_LD + cc * 32 + j * 4) = make_float4(__uint_as_float(r[cc][j * 4]), __uint_as_float(r[cc][j * 4 + 1]), __uint_as_float(r[cc][j * 4 + 2]), __uint_as_float(r[cc][j * 4 + 3])); asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); asm volatile("cp.reduce.async.bulk.global.shared::cta.bulk_group.add.f32 [%0], [%1], 512;" :: "l"(ws + (long)row * HID + (u ? cb1 : c0) * BN), "r"(smem_u32(stg + row * ACC_LD)) : "memory"); asm volatile("cp.async.bulk.commit_group;" ::: "memory"); } asm volatile("cp.async.bulk.wait_group 0;" ::: "memory"); asm volatile("fence.proxy.async.global;" ::: "memory"); __threadfence(); // release the bulk reduces before the grid barrier arrival } tc_fence_before(); named_bar(3, 128);#ifdef BENCH_VF if (tid == 0) { const unsigned long long ta_ = b4time(); atomicMin(&g_b4[21], ta_); atomicMax(&g_b4[22], ta_); }#endif if (tid == 0) { // grid-wide EPOCH barrier: every CTA adds 1; the counter is a multiple of NC at kernel entry (grid size is fixed // = #SMs), so this call's arrivals see old in [base, base + NC) -> wait until base + NC. const unsigned long long old = atomicAdd(xc, 1ull); const unsigned long long tgt = (old / (unsigned long long)NC + 1ull) * (unsigned long long)NC; unsigned long long cv; do { asm volatile("ld.acquire.gpu.global.u64 %0, [%1];" : "=l"(cv) : "l"(xc) : "memory"); } while (cv < tgt); // every claim on a chunk queue precedes its claimer's barrier arrival -> CTA c < 16 resets queue c if (b < 16) *(volatile unsigned long long*)(cq + b) = 0ull; } named_bar(3, 128); { // distributed finalize: CTA b casts + re-zeroes float4 slice [b*TOT/NC, (b+1)*TOT/NC) of the 128 x 2048 sums constexpr int TOT = E * HID / 4; const int dt = ((warp & 3) << 5) | lane; // 0..127 const int f0 = (int)((long)b * TOT / NC), f1 = (int)((long)(b + 1) * TOT / NC); constexpr int KU = 4; for (int base = f0; base < f1; base += KU * 128) { float4 v[KU];#pragma unroll for (int k = 0; k < KU; k++) { const int idx = base + dt + k * 128; if (idx < f1) v[k] = __ldcg(reinterpret_cast<const float4*>(ws) + idx); }#pragma unroll for (int k = 0; k < KU; k++) { const int idx = base + dt + k * 128; if (idx < f1) { __nv_bfloat162 lo = __floats2bfloat162_rn(v[k].x, v[k].y), hi = __floats2bfloat162_rn(v[k].z, v[k].w); uint2 o; o.x = *reinterpret_cast<uint32_t*>(&lo); o.y = *reinterpret_cast<uint32_t*>(&hi); st_na_u2(out2 + (long)idx * 4, o); __stcg(reinterpret_cast<float4*>(ws) + idx, make_float4(0.f, 0.f, 0.f, 0.f)); } } } } if (warp == 1) { // TMEM dealloc after the epilogue warps' (bar 2) and the drain warps' TMEM reads named_bar(2, 160); __syncwarp(); tc_fence_after(); asm volatile("tcgen05.dealloc.cta_group::1.sync.aligned.b32 %0, 512;" :: "r"(tmem)); } B4X();}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482// Host binding: exactly 2 kernel launches per call (route_bwd + one GEMM kernel). The GEMM// path is chosen inside launch_all by T band (see kernel.cu); GEMM kernels are PDL secondaries// of route_bwd. T == 0: a zero-fill of grad_gate.// Launch path: the 2 launches are captured into a CUDA graph ONCE per T (LRU of 8 Ts)// and replayed with cudaGraphLaunch. Key = (device, stream, T, every input/output/scratch// pointer). On a POINTER-ONLY miss (same T -> same kernels, same launch configs) the cached// exec is PATCHED in place: the two launches are re-captured into a throwaway graph (this// re-encodes the per-call tensor maps, which are __grid_constant__ kernel params) and each// kernel node's params are copied into the exec with cudaGraphExecKernelNodeSetParams (node// handles of the exec's source graph kept), no whole-graph cudaGraphExecUpdate / re-instantiate.// Up to TPER_T (4) execs per T are kept before patching. Fallbacks: node-count mismatch / SetParams failure -> re-instantiate.// No per-call scratch allocations (G scratch + fp32 split-K accumulator are cached heap// buffers, never freed; the accumulator and counters self-reset inside the kernels).#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include <ATen/cuda/EmptyTensor.h>#include <cuda_runtime.h>#include <cstring>#include <chrono>#include <algorithm>bool launch_all(const float* probs, const int64_t* sel, const float* wsum, const void* grw, const void* gmask, const void* grl, const void* W, const void* H, void* G, void* out1, void* out2, float* ws, int* counters, int T, cudaStream_t s);void launch_init();extern int g_vf, g_redot_off, g_mvr, g_mvg; // kernel.cu: variant selectors (BENCH_VF builds only; fixed in production)
#define NPTR 13#define GCACHE 8#define MAXKN 4#define TPER_T 4 // max cached execs (pointer sets) per T before patching in placestruct GEntry { int dev = -1; cudaStream_t st = nullptr; int T = -1; int vf = 0; const void* p[NPTR] = {}; cudaGraph_t graph = nullptr; cudaGraphExec_t exec = nullptr; unsigned long long used = 0; int nk = 0; cudaGraphNode_t kn[MAXKN] = {}; // kernel nodes of 'graph' (capture order)};struct GCacheS { GEntry e[GCACHE]; unsigned long long tick = 0; cudaStream_t cap = nullptr; };
#define MAX_S 16#define CNT_BYTES (1024 * sizeof(int))// Heap-allocated, never destructed workspace (avoids static CUDA teardown issues).struct WS { float* ws = nullptr; int* cnt = nullptr; void* G = nullptr; long gcap = 0; };
struct CallArgs { const float* probs; const int64_t* sel; const float* wsum; const void* grw; const void* gmask; const void* grl; const void* W; const void* H; void* G; void* o1; void* o2; float* ws; int* cnt; int T; int dev; cudaStream_t s;};
static int kernel_nodes(cudaGraph_t g, cudaGraphNode_t* kn) { size_t n = 0; if (cudaGraphGetNodes(g, nullptr, &n) != cudaSuccess || n == 0 || n > 16) return -1; cudaGraphNode_t all[16]; if (cudaGraphGetNodes(g, all, &n) != cudaSuccess) return -1; int k = 0; for (size_t i = 0; i < n; i++) { cudaGraphNodeType ty; if (cudaGraphNodeGetType(all[i], &ty) != cudaSuccess) return -1; if (ty == cudaGraphNodeTypeKernel) { if (k >= MAXKN) return -1; kn[k++] = all[i]; } } return k;}
// LCE (small band T < LCE_MAX_T): the captured route -> GEMM PDL edge (type Programmatic, outgoing// port Programmatic = fires when every route block has executed griddepcontrol.launch_dependents) is// re-wired to the LAUNCH-COMPLETION port (fires once every route block has BEGUN execution; all small-band// route blocks are co-resident, so this is ~the route start). The edge type stays Programmatic, so the// GEMM's griddepcontrol.wait still waits for full route completion + memory flush (correctness unchanged);// only the GEMM CTA launch/landing moves earlier. Any API failure leaves the original edge in place.#ifndef L2P_ON#define L2P_ON 1#endif#ifndef LCE_EDGE#define LCE_EDGE 1#endif#ifndef LCE_MAX_T#define LCE_MAX_T 16384 // small + coupled mid + DEC bands; large band keeps the Programmatic port#endifstatic void lce_rewrite(cudaGraph_t g) { size_t n = 0;#if CUDART_VERSION >= 13000 if (cudaGraphGetEdges(g, nullptr, nullptr, nullptr, &n) != cudaSuccess || n == 0 || n > 8) { cudaGetLastError(); return; } cudaGraphNode_t fr[8], to[8]; cudaGraphEdgeData ed[8]; if (cudaGraphGetEdges(g, fr, to, ed, &n) != cudaSuccess) { cudaGetLastError(); return; }#define LCE_RM(f, t, e) cudaGraphRemoveDependencies(g, f, t, e, 1)#define LCE_ADD(f, t, e) cudaGraphAddDependencies(g, f, t, e, 1)#else if (cudaGraphGetEdges_v2(g, nullptr, nullptr, nullptr, &n) != cudaSuccess || n == 0 || n > 8) { cudaGetLastError(); return; } cudaGraphNode_t fr[8], to[8]; cudaGraphEdgeData ed[8]; if (cudaGraphGetEdges_v2(g, fr, to, ed, &n) != cudaSuccess) { cudaGetLastError(); return; }#define LCE_RM(f, t, e) cudaGraphRemoveDependencies_v2(g, f, t, e, 1)#define LCE_ADD(f, t, e) cudaGraphAddDependencies_v2(g, f, t, e, 1)#endif for (size_t i = 0; i < n; i++) { if (ed[i].type != cudaGraphDependencyTypeProgrammatic || ed[i].from_port != cudaGraphKernelNodePortProgrammatic) continue; cudaGraphEdgeData ne = ed[i]; ne.from_port = cudaGraphKernelNodePortLaunchCompletion; if (LCE_RM(&fr[i], &to[i], &ed[i]) != cudaSuccess) { cudaGetLastError(); continue; } if (LCE_ADD(&fr[i], &to[i], &ne) != cudaSuccess) { // restore the original programmatic edge cudaGetLastError(); LCE_ADD(&fr[i], &to[i], &ed[i]); cudaGetLastError(); } }#undef LCE_RM#undef LCE_ADD}
static cudaGraph_t capture(GCacheS& gc, const CallArgs& a) { cudaGraph_t graph = nullptr; if (cudaStreamBeginCapture(gc.cap, cudaStreamCaptureModeThreadLocal) != cudaSuccess) { cudaGetLastError(); return nullptr; } launch_all(a.probs, a.sel, a.wsum, a.grw, a.gmask, a.grl, a.W, a.H, a.G, a.o1, a.o2, a.ws, a.cnt, a.T, gc.cap); if (cudaStreamEndCapture(gc.cap, &graph) != cudaSuccess || !graph) { cudaGetLastError(); return nullptr; } if (LCE_EDGE && a.T > 0 && a.T < LCE_MAX_T) lce_rewrite(graph); // L2P: small band (T < 2600) - every captured kernel node gets an L2 access-policy window over the // pre-tiled G scratch (route -> GEMM hand-off, <= 650KB) with hitProp persisting, so G lines stay in the // persisting L2 set-aside (limit set once in workspace()). Host-side, fixed per graph; outputs unchanged. if (L2P_ON && a.T > 0 && a.T < 16384) { // L2PC-DEC: small + coupled + DEC bands (G <= 4MB + counters < 5MB limit) cudaGraphNode_t kn[MAXKN]; const int nk = kernel_nodes(graph, kn); cudaKernelNodeAttrValue v = {}; // L2PW: scratch layout = [counters 4KB | G]; the coupled/DEC/small GEMMs own no other global scratch // (split-K is DSMEM; the fp32 ws accumulator is large-band only). Window = counters + the G bytes THIS T uses // (whole 128-token tiles), not the grow-only G capacity (a prior large-T call no longer inflates it past the limit). v.accessPolicyWindow.base_ptr = a.cnt; v.accessPolicyWindow.num_bytes = (size_t)CNT_BYTES + (size_t)((a.T + 127) / 128) * 128 * 128 * 2; v.accessPolicyWindow.hitRatio = 1.0f; v.accessPolicyWindow.hitProp = cudaAccessPropertyPersisting; v.accessPolicyWindow.missProp = cudaAccessPropertyStreaming; for (int i = 0; i < nk; i++) if (cudaGraphKernelNodeSetAttribute(kn[i], cudaKernelNodeAttributeAccessPolicyWindow, &v) != cudaSuccess) cudaGetLastError(); } return graph;}
// strat: 0 = patch kernel-node params (production), 1 = direct launches (no graph),// 2 = whole-graph cudaGraphExecUpdate on a pointer miss, 3 = re-instantiate on a miss.static void dispatch(GCacheS& gc, const CallArgs& a, int strat) { if (strat == 1) { launch_init(); launch_all(a.probs, a.sel, a.wsum, a.grw, a.gmask, a.grl, a.W, a.H, a.G, a.o1, a.o2, a.ws, a.cnt, a.T, a.s); return; } const void* key[NPTR] = {a.probs, a.sel, a.wsum, a.grw, a.gmask, a.grl, a.W, a.H, a.G, a.o1, a.o2, a.ws, a.cnt}; if (!gc.cap) cudaStreamCreateWithFlags(&gc.cap, cudaStreamNonBlocking); gc.tick++; const int vfk = (g_vf * 2 + g_redot_off) * 256 + g_mvr * 16 + g_mvg; // variant is part of the graph key (constant in production) GEntry* hit = nullptr; GEntry* sameT = nullptr; GEntry* lru = &gc.e[0]; int nsameT = 0; for (int i = 0; i < GCACHE; i++) { GEntry& g = gc.e[i]; if (g.exec && g.dev == a.dev && g.T == a.T && g.st == a.s && g.vf == vfk) { if (memcmp(g.p, key, sizeof(key)) == 0) { hit = &g; break; } nsameT++; if (!sameT || g.used < sameT->used) sameT = &g; // LRU exec of this (dev, stream, T) } if (!g.exec) { if (lru->exec) lru = &g; } else if (lru->exec && g.used < lru->used) lru = &g; } if (!hit) { launch_init(); cudaGraph_t ng = capture(gc, a); if (ng) { GEntry* tgt = nullptr; // strat 0: up to TPER_T pointer sets per T get their own exec (an allocator cycling a few // output buffers then always hits); beyond that the LRU same-T exec is patched in place. if (sameT && (strat != 0 || nsameT >= TPER_T)) { if (strat == 0) { cudaGraphNode_t kn[MAXKN]; bool ok = kernel_nodes(ng, kn) == sameT->nk && sameT->nk > 0; for (int i = 0; ok && i < sameT->nk; i++) { cudaKernelNodeParams kp; ok = cudaGraphKernelNodeGetParams(kn[i], &kp) == cudaSuccess && cudaGraphExecKernelNodeSetParams(sameT->exec, sameT->kn[i], &kp) == cudaSuccess; } if (ok) { tgt = sameT; cudaGraphDestroy(ng); ng = nullptr; } else cudaGetLastError(); } else if (strat == 2) { cudaGraphExecUpdateResultInfo info; if (cudaGraphExecUpdate(sameT->exec, ng, &info) == cudaSuccess) { tgt = sameT; std::swap(sameT->graph, ng); sameT->nk = kernel_nodes(sameT->graph, sameT->kn); cudaGraphDestroy(ng); ng = nullptr; } else cudaGetLastError(); } if (!tgt) { // fall back: drop the same-T entry and instantiate fresh cudaGraphExecDestroy(sameT->exec); sameT->exec = nullptr; if (sameT->graph) cudaGraphDestroy(sameT->graph); sameT->graph = nullptr; lru = sameT; } } if (!tgt) { if (lru->exec) { cudaGraphExecDestroy(lru->exec); lru->exec = nullptr; } if (lru->graph) { cudaGraphDestroy(lru->graph); lru->graph = nullptr; } cudaGraphExec_t ex = nullptr; if (cudaGraphInstantiate(&ex, ng, 0) == cudaSuccess) { lru->exec = ex; lru->graph = ng; ng = nullptr; lru->nk = kernel_nodes(lru->graph, lru->kn); tgt = lru; } else cudaGetLastError(); } if (ng) cudaGraphDestroy(ng); if (tgt) { tgt->dev = a.dev; tgt->st = a.s; tgt->T = a.T; tgt->vf = vfk; memcpy(tgt->p, key, sizeof(key)); hit = tgt; } } } if (hit) { hit->used = gc.tick; cudaGraphLaunch(hit->exec, a.s); } else { // capture unavailable: launch the same kernels directly launch_init(); launch_all(a.probs, a.sel, a.wsum, a.grw, a.gmask, a.grl, a.W, a.H, a.G, a.o1, a.o2, a.ws, a.cnt, a.T, a.s); }}
static WS& workspace() { static WS& w = *new WS(); if (!w.ws) { cudaMalloc(&w.ws, (size_t)(MAX_S + 1) * 128 * 2048 * sizeof(float)); cudaMemset(w.ws + (size_t)MAX_S * 128 * 2048, 0, (size_t)128 * 2048 * sizeof(float)); // L2PC: counters (1024 ints) live right after the G scratch in ONE allocation (see ensure_G) so the // small-band persisting L2 window covers G + counters contiguously. if (L2P_ON) { // L2P: persisting L2 set-aside for the small-band G window (1MB) if (cudaDeviceSetLimit(cudaLimitPersistingL2CacheSize, (size_t)5 << 20) /* 5MB = DEC-band G cap (<= 4MB at T<16384) + counters*/ != cudaSuccess) cudaGetLastError(); } cudaDeviceSynchronize(); } return w;}static void ensure_G(WS& w, int T) { long need = (long)((std::max(T, 1) + 127) / 128 * 128) * 128; // whole 128-token tiles (pre-tiled G) if (need > w.gcap) { // grow-only cached G scratch [T,128] bf16 if (w.G) { cudaDeviceSynchronize(); cudaFree(w.cnt); } // allocation base = counter block long cap = std::max(need, (long)4096 * 128); // multiple of 128*128 elements -> counters 32KB-aligned void* blk = nullptr; cudaMalloc(&blk, cap * 2 + CNT_BYTES); w.cnt = reinterpret_cast<int*>(blk); // counters first (4KB)... w.G = reinterpret_cast<char*>(blk) + CNT_BYTES; // ... then G (4KB-aligned) // counters [G cap bytes, +4KB): every counter is reset-consistent at 0 (epochs are multiples of their // period, queues are reset per call), so a fresh zeroed block after a device sync is valid. cudaMemset(w.cnt, 0, CNT_BYTES); cudaDeviceSynchronize(); w.gcap = cap; }}
static std::vector<torch::Tensor> run_impl(const torch::Tensor& hidden_states, const torch::Tensor& gate_weight, const torch::Tensor& routing_probs, const torch::Tensor& selected_experts, const torch::Tensor& routing_weights_sum, const torch::Tensor& grad_routing_weights, const torch::Tensor& grad_expert_mask, const torch::Tensor& grad_router_logits);#ifdef PROBE5#include <cmath>#ifndef P5_N#define P5_N 120#endifvoid* b4_sym();void p5_lat(const void* const* bufs, const unsigned long long* sizes, int nb, unsigned* out_dev, cudaStream_t s);struct P5 { unsigned* dlat = nullptr; double ht[P5_N]; int T[P5_N]; unsigned hp[P5_N], op[P5_N]; unsigned long long* dring = nullptr; unsigned long long* dini = nullptr; int n = 0; std::chrono::high_resolution_clock::time_point t0; };static P5& p5() { static P5& p = *new P5(); return p; }#ifndef P5_AB#define P5_AB 0#endif#ifndef P5_SKIP#define P5_SKIP 22#endifstatic const int p5_vars[] = {P5_VARS};static const int p5_nv = sizeof(p5_vars) / sizeof(p5_vars[0]);static int p5_vf[P5_N];static void p5_pre(const torch::Tensor& H, const std::vector<torch::Tensor>& ins) { P5& p = p5(); if (P5_AB) g_vf = p5_vars[p.n % p5_nv]; p5_vf[p.n] = g_vf; if (!p.dlat) cudaMalloc(&p.dlat, 32 * 4 * P5_N); if (0) { const void* bufs[9]; unsigned long long sz[9]; int nb = 0; for (auto& x : ins) { bufs[nb] = x.data_ptr(); sz[nb] = x.numel() * x.element_size(); nb++; } p5_lat(bufs, sz, nb, p.dlat + 32 * p.n, at::cuda::getCurrentCUDAStream()); } if (!p.dring) { cudaMalloc(&p.dring, sizeof(unsigned long long) * 6 * P5_N); cudaMalloc(&p.dini, 48); unsigned long long h[6] = {~0ull, 0ull, ~0ull, 0ull, ~0ull, 0ull}; cudaMemcpy(p.dini, h, 48, cudaMemcpyHostToDevice); p.t0 = std::chrono::high_resolution_clock::now(); } cudaMemcpyAsync(b4_sym(), p.dini, 48, cudaMemcpyDeviceToDevice, at::cuda::getCurrentCUDAStream()); p.ht[p.n] = std::chrono::duration<double, std::micro>(std::chrono::high_resolution_clock::now() - p.t0).count(); p.T[p.n] = H.size(0); p.hp[p.n] = (unsigned)((uintptr_t)H.data_ptr() >> 8);}#include <fstream>static int p5_cupti() { // 1 if libcupti is mapped into this process, 2 if also kineto symbols lib std::ifstream f("/proc/self/maps"); std::string l; int r = 0; while (std::getline(f, l)) { if (l.find("cupti") != std::string::npos) r |= 1; if (l.find("nsys") != std::string::npos || l.find("ToolsInjection") != std::string::npos) r |= 2; } return r;}static int p5_cu[P5_N];static void p5_post(const torch::Tensor& o1) { P5& p = p5(); p5_cu[p.n] = p5_cupti(); p.op[p.n] = (unsigned)((uintptr_t)o1.data_ptr() >> 8); cudaMemcpyAsync(p.dring + 6 * p.n, b4_sym(), 48, cudaMemcpyDeviceToDevice, at::cuda::getCurrentCUDAStream()); if (++p.n < P5_N) return; cudaDeviceSynchronize(); std::vector<unsigned long long> d(6 * P5_N); cudaMemcpy(d.data(), p.dring, d.size() * 8, cudaMemcpyDeviceToHost); std::vector<unsigned> lat(32 * P5_N); cudaMemcpy(lat.data(), p.dlat, lat.size() * 4, cudaMemcpyDeviceToHost); std::ostringstream os; os.setf(std::ios::fixed); os.precision(1); if (P5_AB) { std::vector<double> a(p5_nv, 0), a2(p5_nv, 0), la(p5_nv, 0); std::vector<int> c(p5_nv, 0); for (int i = P5_SKIP; i < P5_N; i++) { const unsigned long long* q = &d[6 * i]; const int v = i % p5_nv; const double sp = (double)(q[1] - q[0]) * 1e-3; a[v] += sp; a2[v] += sp * sp; la[v] += (double)(long long)(q[4] - q[0]) * 1e-3; c[v]++; } os.precision(3); for (int v = 0; v < p5_nv; v++) { const double mu = a[v] / c[v]; os << "AB vf" << p5_vars[v] << " n" << c[v] << " span " << mu << " sd " << sqrt(std::max(0.0, a2[v] / c[v] - mu * mu)) << " land " << la[v] / c[v] << " d% " << 100.0 * (mu / (a[0] / c[0]) - 1) << "\n"; } } for (int i = 0; i < P5_N; i++) { if (P5_AB || (i < 8 && i > 1)) continue; const unsigned long long* q = &d[6 * i]; os << i << ":c" << p5_cu[i] << " h" << p.ht[i] << " sp" << (double)(q[1] - q[0]) * 1e-3 << " tl " << (double)(q[0] - q[2]) * 1e-3 << " " << (double)(q[3] - q[0]) * 1e-3 << " " << (double)(long long)(q[4] - q[0]) * 1e-3 << " " << (double)(long long)(q[1] - q[3]) * 1e-3; if (i) os << " gap" << ((double)(long long)(q[2] - d[6 * (i - 1) + 1])) * 1e-3;
os << "\n"; } TORCH_CHECK(false, "PROBE5:\n" + os.str());}#endif#ifdef PROBE4#include "bench4.h"#endif
#ifdef PROBE12#include <sstream>#include <vector>void p12_run(const void* buf, int nc, int mode, unsigned* cnt, unsigned gen, unsigned long long* out);static std::string probe12() { std::ostringstream os; os.setf(std::ios::fixed); os.precision(1); unsigned char* buf; cudaMalloc(&buf, (size_t)148 * 9 * 32768); unsigned* cnt; cudaMalloc(&cnt, 4); cudaMemset(cnt, 0, 4); unsigned long long* out; cudaMalloc(&out, 148 * 8); void* fl; cudaMalloc(&fl, 256 << 20); unsigned gen = 0; for (int cold = 0; cold < 2; cold++) for (int nc : {64, 128}) for (int mode = 0; mode < 3; mode++) { std::vector<double> med, mx; for (int rep = 0; rep < 12; rep++) { if (cold) cudaMemset(fl, rep, 256 << 20); cudaMemset(buf, rep + 1, (size_t)(mode == 2 ? nc : 1) * 9 * 32768); // write -> L2-resident (like route G) cudaMemset(cnt, 0, 4); gen = 1; p12_run(buf, nc, mode, cnt, gen, out); cudaDeviceSynchronize(); std::vector<unsigned long long> h(nc); cudaMemcpy(h.data(), out, nc * 8, cudaMemcpyDeviceToHost); std::sort(h.begin(), h.end()); if (rep < 2) continue; med.push_back(h[nc / 2] * 1e-3); mx.push_back(h[nc - 1] * 1e-3); } std::sort(med.begin(), med.end()); std::sort(mx.begin(), mx.end()); const double m = med[med.size() / 2], x = mx[mx.size() / 2]; os << "flush" << cold << " nc" << nc << " mode" << mode << ": CTA median " << m << "us (" << 294.912 / m / 1e3 * 1e3 << " GB/s/SM) max " << x << "us\n"; } if (cudaGetLastError() != cudaSuccess) os << "CUDAERR"; return os.str();}#endif#ifdef PROBE13#include <sstream>#include <vector>void p13_run(unsigned char* gout, int npairs, int N, int M, int st1, unsigned* cnt, unsigned long long* out);static double p13med(std::vector<double> v) { std::sort(v.begin(), v.end()); return v[v.size() / 2]; }static std::string probe13() { std::ostringstream os; os.setf(std::ios::fixed); os.precision(2); unsigned char* buf; cudaMalloc(&buf, (size_t)148 << 20); unsigned* cnt; cudaMalloc(&cnt, 4); unsigned long long* out; cudaMalloc(&out, 74 * 4 * 8); void* fl; cudaMalloc(&fl, 256 << 20); // {N, M, st1}: rank-0 global boxes, pushed boxes, rank-1 re-stores const int cf[][3] = {{4, 0, 0}, {0, 2, 0}, {4, 2, 0}, {4, 2, 1}, {6, 0, 0}, {16, 0, 0}, {0, 8, 0}, {16, 8, 0}, {16, 8, 1}, {24, 0, 0}, {32, 0, 0}, {0, 12, 0}, {32, 12, 0}, {32, 12, 1}, {44, 0, 0}}; for (int np : {40, 64, 74}) for (auto& c : cf) { std::vector<double> r0d, r1r, r1d, pend; for (int rep = 0; rep < 12; rep++) { cudaMemset(fl, rep, 256 << 20); cudaMemset(cnt, 0, 4); cudaMemset(out, 0, 74 * 32); p13_run(buf, np, c[0], c[1], c[2], cnt, out); cudaDeviceSynchronize(); std::vector<unsigned long long> h(np * 4); cudaMemcpy(h.data(), out, np * 32, cudaMemcpyDeviceToHost); if (rep < 2) continue; std::vector<double> a, b, d, e; for (int p = 0; p < np; p++) { a.push_back(h[4 * p + 1] * 1e-3); b.push_back(h[4 * p + 2] * 1e-3); d.push_back(h[4 * p + 3] * 1e-3); e.push_back(std::max(h[4 * p + 1], std::max(h[4 * p + 2], h[4 * p + 3])) * 1e-3); } r0d.push_back(p13med(a)); r1r.push_back(p13med(b)); r1d.push_back(p13med(d)); pend.push_back(p13med(e)); } const double pe = p13med(pend), kb = (c[0] + c[1]) * 16.384; os << "np" << np << " N" << c[0] << " M" << c[1] << " st" << c[2] << ": r0 done " << p13med(r0d) << " r1 recv " << p13med(r1r) << " r1 done " << p13med(r1d) << " pair " << pe << "us -> src egress " << kb / pe << " GB/s" << " (glob " << (c[0] ? c[0] * 16.384 / p13med(r0d) : 0.0) << ", push " << (c[1] ? c[1] * 16.384 / p13med(r1r) : 0.0) << ")\n"; } if (cudaGetLastError() != cudaSuccess) os << "CUDAERR"; return os.str();}#endif#ifdef PROBE6#include "probe6.h"#endifstd::vector<torch::Tensor> run(const torch::Tensor& hidden_states, const torch::Tensor& gate_weight, const torch::Tensor& router_logits, const torch::Tensor& routing_probs, const torch::Tensor& selected_experts, const torch::Tensor& routing_weights_sum, const torch::Tensor& grad_routing_weights, const torch::Tensor& grad_expert_mask, const torch::Tensor& grad_router_logits) {#ifdef PROBE4 #ifdef B6 { std::string r = bench6(); TORCH_CHECK(false, "PROBE4: " + r); } #elif defined(B5) { std::string r = bench5(); TORCH_CHECK(false, "PROBE4: " + r); }#else { std::string r = bench4(); TORCH_CHECK(false, "PROBE4: " + r); }#endif#endif#ifdef PROBE12 { std::string r = probe12(); TORCH_CHECK(false, "PROBE12:\n" + r); }#endif#ifdef PROBE13 { std::string r = probe13(); TORCH_CHECK(false, "PROBE13:\n" + r); }#endif#ifdef PROBE6 { std::string r = probe6(); TORCH_CHECK(false, "PROBE6:\n" + r); }#endif#ifdef PROBE5 p5_pre(hidden_states, {hidden_states, gate_weight, router_logits, routing_probs, selected_experts, routing_weights_sum, grad_routing_weights, grad_expert_mask, grad_router_logits}); auto r5 = run_impl(hidden_states, gate_weight, routing_probs, selected_experts, routing_weights_sum, grad_routing_weights, grad_expert_mask, grad_router_logits); p5_post(r5[0]); return r5;#endif return run_impl(hidden_states, gate_weight, routing_probs, selected_experts, routing_weights_sum, grad_routing_weights, grad_expert_mask, grad_router_logits);}static std::vector<torch::Tensor> run_impl(const torch::Tensor& hidden_states, const torch::Tensor& gate_weight, const torch::Tensor& routing_probs, const torch::Tensor& selected_experts, const torch::Tensor& routing_weights_sum, const torch::Tensor& grad_routing_weights, const torch::Tensor& grad_expert_mask, const torch::Tensor& grad_router_logits) { WS& w = workspace(); int T = hidden_states.size(0); ensure_G(w, T); // ONE fresh allocation per output per call via at::detail::empty_cuda (direct caching-allocator call). const int dev = hidden_states.get_device(); const c10::Device cdev(c10::DeviceType::CUDA, (c10::DeviceIndex)dev); const int64_t sz1[2] = {(int64_t)T, 2048}, sz2[2] = {128, 2048}; at::Tensor out1 = at::Tensor(at::detail::empty_cuda(c10::IntArrayRef(sz1, 2), at::kBFloat16, cdev, c10::nullopt)); at::Tensor out2 = at::Tensor(at::detail::empty_cuda(c10::IntArrayRef(sz2, 2), at::kBFloat16, cdev, c10::nullopt)); CallArgs a{static_cast<const float*>(routing_probs.data_ptr()), static_cast<const int64_t*>(selected_experts.data_ptr()), static_cast<const float*>(routing_weights_sum.data_ptr()), grad_routing_weights.data_ptr(), grad_expert_mask.data_ptr(), grad_router_logits.data_ptr(), gate_weight.data_ptr(), hidden_states.data_ptr(), w.G, out1.data_ptr(), out2.data_ptr(), w.ws, w.cnt, T, dev, at::cuda::getCurrentCUDAStream()}; static GCacheS& gc = *new GCacheS(); dispatch(gc, a, 0); std::vector<torch::Tensor> res; res.reserve(2); res.emplace_back(std::move(out1)); res.emplace_back(std::move(out2)); return res;}PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run); }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318// route_b_kernel<WARPS, NT, MODE>: BATCHED route backward (one warp per token, NT consecutive// tokens per warp). All independent loads (probs, grl, sel, grw, wsum) of the NT tokens are// issued first, then all NT sparse grad_expert_mask gathers, then the per-token math. This// raises the bytes in flight per warp (memory-level parallelism) vs the 1-token-at-a-time loop.// MODE 0: G = bf16(p * grl) (bisection probe only: pure streaming)// MODE 1: + softmax backward dot / second pass (probe only, no sparse terms)// MODE 2: + sel/grw/wsum loads + norm-grad scatter (probe only, no gmask gather)// MODE 3: full math, per-token smem gather/scatter.// MODE 4: probe only: sparse operands loaded, consumed trivially (no scatter, no gather).// MODE 5: full math, REGISTER-only (shuffle gather/scatter, no smem/syncwarp).// MODE 6: full math, smem path in LOCKSTEP over the NT tokens (2 syncwarps per warp total).// MODE 7: MODE 3 with ONE reciprocal 1/S instead of 3 IEEE divisions.// MODE 11: MODE 7 with the approximate reciprocal (__fdividef, ~2 ulp).// Math (MODE 3) identical to route_bwd_smem_kernel: per-warp smem rows, LDS gather of// probs[t, e_k], shared atomicAdd scatter of the norm + mask grads, warp-shuffle reductions.#pragma oncetemplate <int WARPS, int NT, int MODE>__global__ void __launch_bounds__(WARPS * 32)route_b_kernel(const float* __restrict__ probs, const int64_t* __restrict__ sel, const float* __restrict__ wsum, const __nv_bfloat16* __restrict__ grw, const __nv_bfloat16* __restrict__ gmask, const __nv_bfloat16* __restrict__ grl, __nv_bfloat16* __restrict__ out, int T) { constexpr bool SM = (MODE == 2 || MODE == 3 || MODE == 6 || MODE == 7 || MODE == 11); __shared__ __align__(16) float sp[SM ? WARPS : 1][SM ? NT : 1][SM ? E : 4]; __shared__ __align__(16) float sg[SM ? WARPS : 1][SM ? NT : 1][SM ? E : 4]; B4RE(); pdl_wait(); B4S(); pdl_launch_dependents(); const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; const long t0 = ((long)blockIdx.x * WARPS + w) * NT; float4 p[NT]; uint2 gr[NT]; int e[NT]; unsigned short gw[NT], mk[NT]; float S[NT]; // ---- phase 1: every independent load of the NT tokens in flight#pragma unroll for (int i = 0; i < NT; i++) { const long t = t0 + i; p[i] = make_float4(0.f, 0.f, 0.f, 0.f); gr[i] = make_uint2(0u, 0u); e[i] = 0; gw[i] = 0; mk[i] = 0; S[i] = 1.f; if (t < T) { p[i] = ld_nc_f4(reinterpret_cast<const float4*>(probs + t * E) + lane); gr[i] = ld_nc_u2(reinterpret_cast<const uint2*>(grl + t * E) + lane); if (MODE >= 2) { // MODE 2..6 all load the sparse operands if (lane < TOPK) { e[i] = (int)__ldg(sel + t * TOPK + lane) & (E - 1); gw[i] = __ldg(reinterpret_cast<const unsigned short*>(grw) + t * TOPK + lane); } S[i] = __ldg(wsum + t); } } } // ---- phase 2: the dependent sparse gathers grad_expert_mask[e_k, k, t] of all NT tokens if (MODE == 3 || MODE >= 5) { // modes with the gmask gather#pragma unroll for (int i = 0; i < NT; i++) { const long t = t0 + i; if (t < T && lane < TOPK) asm volatile("ld.global.nc.L1::no_allocate.u16 %0, [%1];" : "=h"(mk[i]) : "l"(reinterpret_cast<const unsigned short*>(gmask) + ((long)e[i] * TOPK + lane) * T + t)); } } if (MODE == 5) { // REGISTER path (no smem, no syncwarp): all NT tokens' shuffle chains are independent so the // compiler can interleave them. dot uses the identity // sum_j (grl_j + add_j) p_j = sum_j grl_j p_j + sum_k contrib_k * p[e_k].#pragma unroll for (int i = 0; i < NT; i++) { const long t = t0 + i; if (t >= T) break; // warp-uniform __nv_bfloat162 g01 = *reinterpret_cast<const __nv_bfloat162*>(&gr[i].x); __nv_bfloat162 g23 = *reinterpret_cast<const __nv_bfloat162*>(&gr[i].y); float g[4] = {__low2float(g01), __high2float(g01), __low2float(g23), __high2float(g23)}; const float pv[4] = {p[i].x, p[i].y, p[i].z, p[i].w}; const int ei = e[i]; const int src = lane < TOPK ? (ei >> 2) : lane; const float s0 = __shfl_sync(0xffffffff, pv[0], src); const float s1 = __shfl_sync(0xffffffff, pv[1], src); const float s2 = __shfl_sync(0xffffffff, pv[2], src); const float s3 = __shfl_sync(0xffffffff, pv[3], src); const int jj = ei & 3; const float wk = jj == 0 ? s0 : (jj == 1 ? s1 : (jj == 2 ? s2 : s3)); // probs[t, e_k] const float gwk = __uint_as_float((uint32_t)gw[i] << 16); // 0 on lanes >= 8 const float mkk = __uint_as_float((uint32_t)mk[i] << 16); float c = gwk * wk / S[i]; c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); float contrib = (gwk / S[i] - c / S[i]) + mkk; if (lane >= TOPK) contrib = 0.f; float dot = g[0] * pv[0] + g[1] * pv[1] + g[2] * pv[2] + g[3] * pv[3] + contrib * wk;#pragma unroll for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffff, dot, o); // scatter: owner lane (e_k >> 2) adds contrib_k to slot e_k & 3#pragma unroll for (int k = 0; k < TOPK; k++) { const int ek = __shfl_sync(0xffffffff, ei, k); const float ck = __shfl_sync(0xffffffff, contrib, k); if ((ek >> 2) == lane) {#pragma unroll for (int q = 0; q < 4; q++) if (q == (ek & 3)) g[q] += ck; } } __nv_bfloat162 o01 = __floats2bfloat162_rn(pv[0] * (g[0] - dot), pv[1] * (g[1] - dot)); __nv_bfloat162 o23 = __floats2bfloat162_rn(pv[2] * (g[2] - dot), pv[3] * (g[3] - dot)); uint2 ow; ow.x = *reinterpret_cast<uint32_t*>(&o01); ow.y = *reinterpret_cast<uint32_t*>(&o23); reinterpret_cast<uint2*>(out + t * E)[lane] = ow; } B4RX(); return; } if (MODE == 6) { // LOCKSTEP smem path: stage all NT rows, ONE syncwarp, all gathers/reductions, all // atomics, ONE syncwarp, then all dots/stores (same math/order as MODE 3). const int nv = (T - t0) < NT ? (int)(T - t0) : NT; // valid tokens of this warp (warp-uniform) if (nv <= 0) return; float4 g[NT];#pragma unroll for (int i = 0; i < NT; i++) { __nv_bfloat162 g01 = *reinterpret_cast<const __nv_bfloat162*>(&gr[i].x); __nv_bfloat162 g23 = *reinterpret_cast<const __nv_bfloat162*>(&gr[i].y); g[i] = make_float4(__low2float(g01), __high2float(g01), __low2float(g23), __high2float(g23)); reinterpret_cast<float4*>(sp[w][i])[lane] = p[i]; reinterpret_cast<float4*>(sg[w][i])[lane] = g[i]; } __syncwarp(); float contrib[NT];#pragma unroll for (int i = 0; i < NT; i++) { const float gwk = __uint_as_float((uint32_t)gw[i] << 16); const float mkk = __uint_as_float((uint32_t)mk[i] << 16); const float wk = sp[w][i][e[i]]; float c = gwk * wk / S[i]; c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); contrib[i] = (gwk / S[i] - c / S[i]) + mkk; }#pragma unroll for (int i = 0; i < NT; i++) if (lane < TOPK) atomicAdd(&sg[w][i][e[i]], contrib[i]); __syncwarp();#pragma unroll for (int i = 0; i < NT; i++) { const long t = t0 + i; const float4 gg = reinterpret_cast<const float4*>(sg[w][i])[lane]; const float4 pv = p[i]; float dot = gg.x * pv.x + gg.y * pv.y + gg.z * pv.z + gg.w * pv.w;#pragma unroll for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffff, dot, o); __nv_bfloat162 o01 = __floats2bfloat162_rn(pv.x * (gg.x - dot), pv.y * (gg.y - dot)); __nv_bfloat162 o23 = __floats2bfloat162_rn(pv.z * (gg.z - dot), pv.w * (gg.w - dot)); uint2 ow; ow.x = *reinterpret_cast<uint32_t*>(&o01); ow.y = *reinterpret_cast<uint32_t*>(&o23); if (i < nv) reinterpret_cast<uint2*>(out + t * E)[lane] = ow; } return; } // ---- phase 3: per-token math + 8B/lane store#pragma unroll for (int i = 0; i < NT; i++) { const long t = t0 + i; if (t >= T) break; // warp-uniform __nv_bfloat162 g01 = *reinterpret_cast<const __nv_bfloat162*>(&gr[i].x); __nv_bfloat162 g23 = *reinterpret_cast<const __nv_bfloat162*>(&gr[i].y); float4 g = make_float4(__low2float(g01), __high2float(g01), __low2float(g23), __high2float(g23)); const float4 pv = p[i]; __nv_bfloat162 o01, o23; if (MODE == 0) { o01 = __floats2bfloat162_rn(pv.x * g.x, pv.y * g.y); o23 = __floats2bfloat162_rn(pv.z * g.z, pv.w * g.w); } else { if (MODE == 4) { // probe: sparse operands loaded and consumed trivially const float gwk = __uint_as_float((uint32_t)gw[i] << 16); g.x += gwk / S[i] + (float)e[i] * 1e-9f; } if (MODE == 2 || MODE == 3 || MODE == 7 || MODE == 11) { float* spr = sp[w][i]; float* sgr = sg[w][i]; reinterpret_cast<float4*>(spr)[lane] = pv; reinterpret_cast<float4*>(sgr)[lane] = g; __syncwarp(); const float gwk = __uint_as_float((uint32_t)gw[i] << 16); // 0 on lanes >= 8 const float mkk = __uint_as_float((uint32_t)mk[i] << 16); const float wk = spr[e[i]]; float contrib; if (MODE == 7 || MODE == 11) { // one reciprocal replaces 3 IEEE divisions (MODE 11: approximate MUFU.RCP) const float rS = MODE == 11 ? __fdividef(1.0f, S[i]) : 1.0f / S[i]; float c = gwk * wk; c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); contrib = (gwk - c * rS) * rS + mkk; } else { float c = gwk * wk / S[i]; c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); contrib = (gwk / S[i] - c / S[i]) + mkk; } if (lane < TOPK) atomicAdd(&sgr[e[i]], contrib); __syncwarp(); g = reinterpret_cast<const float4*>(sgr)[lane]; } float dot = g.x * pv.x + g.y * pv.y + g.z * pv.z + g.w * pv.w;#pragma unroll for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffff, dot, o); o01 = __floats2bfloat162_rn(pv.x * (g.x - dot), pv.y * (g.y - dot)); o23 = __floats2bfloat162_rn(pv.z * (g.z - dot), pv.w * (g.w - dot)); } uint2 ow; ow.x = *reinterpret_cast<uint32_t*>(&o01); ow.y = *reinterpret_cast<uint32_t*>(&o23); reinterpret_cast<uint2*>(out + t * E)[lane] = ow; }}
// route_h_kernel<WARPS, RCP>: HALF-WARP per token (2 tokens per warp, 16 lanes x 8 experts).// Every per-lane instruction covers 8 experts (vs 4), and the 8-lane top-k work of the two// tokens runs in the same instructions -> ~half the issued instructions per token.// Lane hl = lane & 15 owns experts hl*8 .. hl*8+7 of token t = 2*warp_global + (lane >> 4).// Loads: probs 2 x 16B (nc), grl 16B (nc); lanes hl < 8: sel (int64) + grw; then the sparse// gmask gather. probs/grad rows staged in per-half smem: LDS gather of probs[t, e_k], shared// atomicAdd scatter; reductions are xor-shuffles confined to the 16-lane half.// RCP: 1/S computed once (IEEE reciprocal) instead of 3 IEEE divisions.template <int WARPS, bool RCP>__global__ void __launch_bounds__(WARPS * 32)route_h_kernel(const float* __restrict__ probs, const int64_t* __restrict__ sel, const float* __restrict__ wsum, const __nv_bfloat16* __restrict__ grw, const __nv_bfloat16* __restrict__ gmask, const __nv_bfloat16* __restrict__ grl, __nv_bfloat16* __restrict__ out, int T) { __shared__ __align__(16) float sp[WARPS][2][E]; __shared__ __align__(16) float sg[WARPS][2][E]; pdl_wait(); pdl_launch_dependents(); const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; const int hl = lane & 15, hs = lane >> 4; const long tw = ((long)blockIdx.x * WARPS + w) * 2; if (tw >= T) return; // warp-uniform const long t = tw + hs; const bool valid = t < T; // upper half may be past the end (odd T) float4 p0 = make_float4(0.f, 0.f, 0.f, 0.f), p1 = p0; uint4 gr = make_uint4(0u, 0u, 0u, 0u); int e = 0; unsigned short gw = 0, mk = 0; float S = 1.f; if (valid) { if (hl < TOPK) { e = (int)__ldg(sel + t * TOPK + hl) & (E - 1); gw = __ldg(reinterpret_cast<const unsigned short*>(grw) + t * TOPK + hl); } p0 = ld_nc_f4(reinterpret_cast<const float4*>(probs + t * E) + hl * 2); p1 = ld_nc_f4(reinterpret_cast<const float4*>(probs + t * E) + hl * 2 + 1); asm volatile("ld.global.nc.L1::no_allocate.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(gr.x), "=r"(gr.y), "=r"(gr.z), "=r"(gr.w) : "l"(reinterpret_cast<const uint4*>(grl + t * E) + hl)); S = __ldg(wsum + t); if (hl < TOPK) // sparse dependent gather grad_expert_mask[e_k, k, t] asm volatile("ld.global.nc.L1::no_allocate.u16 %0, [%1];" : "=h"(mk) : "l"(reinterpret_cast<const unsigned short*>(gmask) + ((long)e * TOPK + hl) * T + t)); } float* spr = sp[w][hs]; float* sgr = sg[w][hs]; float g[8]; { const uint32_t gu[4] = {gr.x, gr.y, gr.z, gr.w};#pragma unroll for (int j = 0; j < 4; j++) { __nv_bfloat162 b = *reinterpret_cast<const __nv_bfloat162*>(&gu[j]); g[2 * j] = __low2float(b); g[2 * j + 1] = __high2float(b); } } reinterpret_cast<float4*>(spr)[hl * 2] = p0; reinterpret_cast<float4*>(spr)[hl * 2 + 1] = p1; reinterpret_cast<float4*>(sgr)[hl * 2] = make_float4(g[0], g[1], g[2], g[3]); reinterpret_cast<float4*>(sgr)[hl * 2 + 1] = make_float4(g[4], g[5], g[6], g[7]); __syncwarp(); const float gwk = __uint_as_float((uint32_t)gw << 16); // 0 on hl >= 8 const float mkk = __uint_as_float((uint32_t)mk << 16); const float wk = spr[e]; // probs[t, e_k] float contrib; if (RCP) { const float rS = 1.0f / S; float c = gwk * wk; c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); contrib = (gwk - c * rS) * rS + mkk; } else { float c = gwk * wk / S; c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); contrib = (gwk / S - c / S) + mkk; } if (hl < TOPK) atomicAdd(&sgr[e], contrib); // scatter of norm grad + mask grad __syncwarp(); const float4 ga = reinterpret_cast<const float4*>(sgr)[hl * 2]; const float4 gb = reinterpret_cast<const float4*>(sgr)[hl * 2 + 1]; float dot = ga.x * p0.x + ga.y * p0.y + ga.z * p0.z + ga.w * p0.w + gb.x * p1.x + gb.y * p1.y + gb.z * p1.z + gb.w * p1.w;#pragma unroll for (int o = 8; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffff, dot, o); // within the half __nv_bfloat162 o0 = __floats2bfloat162_rn(p0.x * (ga.x - dot), p0.y * (ga.y - dot)); __nv_bfloat162 o1 = __floats2bfloat162_rn(p0.z * (ga.z - dot), p0.w * (ga.w - dot)); __nv_bfloat162 o2 = __floats2bfloat162_rn(p1.x * (gb.x - dot), p1.y * (gb.y - dot)); __nv_bfloat162 o3 = __floats2bfloat162_rn(p1.z * (gb.z - dot), p1.w * (gb.w - dot)); uint4 ow; ow.x = *reinterpret_cast<uint32_t*>(&o0); ow.y = *reinterpret_cast<uint32_t*>(&o1); ow.z = *reinterpret_cast<uint32_t*>(&o2); ow.w = *reinterpret_cast<uint32_t*>(&o3); if (valid) reinterpret_cast<uint4*>(out + t * E)[hl] = ow; // 16B per lane, 256B per token}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778// route_c_kernel<WARPS, FL>: latency-trimmed route backward (one warp per token, WARPS tok/block).// Same math as route_b MODE 7, with the critical path (sel load -> dependent gmask gather -> G// store) shortened. Feature bits FL:// RC_L2PF (1): probs / grl loads with the .L2::256B prefetch hint.// RC_SEL32 (2): selected_experts read as the low 32-bit word of each int64 (indices < 128).// RC_SELF (4): sel (+ grw) issued FIRST so the dependent gather starts as early as possible.// RC_EDOT (8): softmax-backward dot split: dot = sum_j grl_j p_j (full 128-wide reduction,// runs while the gather is in flight) + sum_k contrib_k p[e_k] (8-lane// correction after the gather) -> only 3 shuffles remain on the critical path.// RC_ST16 (16): G stored as 16B per even lane (odd lane's 8B pulled in with 2 shuffles).#pragma once#ifndef RT_NA#define RT_NA 0#endif#ifndef RW64#define RW64 0#endif#define RC_L2PF 1#define RC_SEL32 2#define RC_SELF 4#define RC_EDOT 8#define RC_ST16 16// RC_ONEBUF (64): ONE per-warp smem row (probs staged, gathered, then overwritten by the grad// row; 2 extra __syncwarp) -> 4KB/block instead of 8KB, so more route blocks// co-reside with the big-smem GEMM CTAs (mid band 1408 <= T < 6144).#define RC_ONEBUF 64#define RC_PDE 128// RC_LATE (256, ): launch_dependents only AFTER this warp's G store (the GEMM grid launches once every// route block has triggered/exited -> its griddepcontrol.wait idle, counted in its kernel// duration, shrinks to ~the completion flush).#define RC_LATE 256#define RC_MIDT 512// PROBE-only ablation / variant bits (large-band study, never in production)#define RC_AB_NOG 1024 // no gmask gather (mk = 0)#define RC_AB_NOP 2048 // probs not read (constant)#define RC_AB_NOR 4096 // grl not read (constant)#define RC_AB_NOS 8192 // G store suppressed (store only on an impossible value)#define RC_G64 16384 // gather with .L2::64B hint#define RC_PERS 65536 // persistent grid-stride route (large band)#define RC_MB8 131072#define RC_S64 262144 // sel / grw loads ld.global.nc.L1::no_allocate.L2::64B // __launch_bounds__ min blocks = 64 warps / SM#define RC_NOTILE (1 << 25)// RC_GPS (probe): non-persistent route - before griddepcontrol.wait lanes < 8 load their (possibly stale) sel low// word and prefetch.global.L2 the grad_expert_mask gather element (pure cache hint: in-bounds address for any value,// the real sel / gather loads are re-issued after the wait).#define RC_GPS (1 << 20)// RC_GTLB (small band): pre-wait, thread 0 of route block b L2-prefetches one grad_expert_mask line at byte// offset b * 64KB (if in range) -> address translation of every 64KB gather region warmed. Pure cache hint.#define RC_GTLB (1 << 21)// RC_SPF: small band - before griddepcontrol.wait each warp L2-prefetches its own token's sel row//. prefetch.global.L2 is only a cache hint// (L2 is the coherence point, no data reaches the SM before the wait), so it is safe pre-wait; it moves// the cold-DRAM latency of the first link of the sel -> gmask-gather chain into the PDL wait window.// RC_GPA (persistent large-band route only): before its token loop each warp loads the selected_experts low// words of ALL its grid-stride tokens (<= 16; lane l -> token slot l>>3, top-k slot l&7, 4 tokens per pass) and// prefetch.global.L2's the matching grad_expert_mask gather element, so every token's dependent// sel -> gmask gather chain runs on L2 hits instead of two serialized DRAM latencies.// Inputs only (never written by the previous grid) -> issued before griddepcontrol.wait.#define RC_GPA (1 << 27)// RC_G128: the sparse gmask gather uses the.L2::128B prefetch-size hint (instead of RC_G64's 64B)#define RC_G128 (1 << 28)// RC_F2: per-lane softmax-bwd dot partial with packed sm_100 mul/fma.rn.f32x2 (2 instr instead of 4)#define RC_F2 (1 << 29)// RC_LDG (small band): the chain-critical sel low-word load and the dependent gmask gather use plain// (weak, non-.nc) ld.global.L1::no_allocate.L2::64B instead of the read-only .nc path (shorter per-hop latency test)#define RC_LDG (1 << 30)#define RC_SPF (1 << 26) // row-major G only (outt statically ignored -> tiled-store code compiled out)#define RC_STCS 32768 // G store st.global.cs // probe: launch_dependents right after the gmask gather is issued__device__ __forceinline__ float4 ld_nc_f4_pf(const float4* p) { float4 v; asm volatile("ld.global.nc.L1::no_allocate.L2::256B.v4.f32 {%0,%1,%2,%3}, [%4];" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) : "l"(p)); return v;}__device__ __forceinline__ uint2 ld_nc_u2_pf(const uint2* p) { uint2 v; asm volatile("ld.global.nc.L1::no_allocate.L2::256B.v2.u32 {%0,%1}, [%2];" : "=r"(v.x), "=r"(v.y) : "l"(p)); return v;}
template <int WARPS, int FL>__global__ void __launch_bounds__(WARPS * 32, (FL & RC_MB8) ? 2048 / (WARPS * 32) : 1) // RC_MB8: full 64-warp occupancyroute_c_kernel(const float* __restrict__ probs, const int64_t* __restrict__ sel, const float* __restrict__ wsum, const __nv_bfloat16* __restrict__ grw, const __nv_bfloat16* __restrict__ gmask, const __nv_bfloat16* __restrict__ grl, __nv_bfloat16* __restrict__ out, int T, unsigned char* __restrict__ outt) { __shared__ __align__(16) float sbuf[(FL & RC_ONEBUF) ? 1 : 2][WARPS][E];#ifdef PROBE_TS unsigned psl = 0; if (threadIdx.x == 0) { unsigned long long t0 = gtime(); psl = slot_now(); atomicMin(&g_ts[0][psl], t0); atomicMax(&g_ts[1][psl], t0); }#endif // RC_PDE: release the dependent GEMM grid BEFORE waiting on the prior grid (the GEMM // still griddepcontrol.waits for this grid's completion before reading G). B4RE(); if (FL & RC_PDE) pdl_launch_dependents(); if ((FL & RC_SPF) && !(FL & RC_PERS)) { const int ln = threadIdx.x & 31; const long tp = (long)blockIdx.x * WARPS + (threadIdx.x >> 5); if (tp < T && ln < 2) { // chain-critical sel row only (+ grw); dense rows stay post-wait const void* pa; if (ln == 0) pa = sel + tp * TOPK; // 64B sel row else pa = grw + tp * TOPK; // 16B grw row asm volatile("prefetch.global.L2 [%0];" :: "l"(pa)); } } if ((FL & RC_GTLB) && threadIdx.x == 0) { const size_t off = (size_t)blockIdx.x * 32768u; // bf16 elements = 64KB if (off < (size_t)E * TOPK * (size_t)T) asm volatile("prefetch.global.L2 [%0];" :: "l"(reinterpret_cast<const unsigned short*>(gmask) + off)); } if ((FL & RC_GPS) && !(FL & RC_PERS)) { const int ln = threadIdx.x & 31; const long tp = (long)blockIdx.x * WARPS + (threadIdx.x >> 5); if (tp < T && ln < TOPK) { int ev; asm volatile("ld.global.L1::no_allocate.L2::64B.s32 %0, [%1];" : "=r"(ev) : "l"(reinterpret_cast<const int*>(sel) + (tp * TOPK + ln) * 2)); asm volatile("prefetch.global.L2 [%0];" :: "l"(reinterpret_cast<const unsigned short*>(gmask) + tp + (size_t)(unsigned)((ev & (E - 1)) * TOPK + ln) * (unsigned)T)); } } if ((FL & RC_GPA) && (FL & RC_PERS)) { const int ln = threadIdx.x & 31; const long stride = (long)gridDim.x * WARPS; const long tw0 = (long)blockIdx.x * WARPS + (threadIdx.x >> 5); const int k = ln & 7, js = ln >> 3;#pragma unroll 1 for (int j0 = 0; j0 < 16; j0 += 8) { if (tw0 + (long)j0 * stride >= T) break; // warp-uniform int ev[2] = {0, 0}; long tv[2];#pragma unroll for (int u = 0; u < 2; u++) { tv[u] = tw0 + (long)(j0 + u * 4 + js) * stride; if (tv[u] < T) asm volatile("ld.global.nc.L1::no_allocate.L2::64B.s32 %0, [%1];" : "=r"(ev[u]) : "l"(reinterpret_cast<const int*>(sel) + (tv[u] * TOPK + k) * 2)); }#pragma unroll for (int u = 0; u < 2; u++) if (tv[u] < T) asm volatile("prefetch.global.L2 [%0];" :: "l"(reinterpret_cast<const unsigned short*>(gmask) + tv[u] + (size_t)(unsigned)((ev[u] & (E - 1)) * TOPK + k) * (unsigned)T)); } } pdl_wait(); B4S(); // BENCH_VF only: device-span start stamp B4DLY(); if (!(FL & (RC_PDE | RC_LATE | RC_MIDT))) pdl_launch_dependents(); if (FL & RC_NOTILE) outt = nullptr; // DEC band route never writes the tiled G layout const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; // per-token body as a lambda; RC_PERS = persistent grid-stride loop over tokens auto tok = [&](const long t) {#ifdef MM_ZROUTE if (!(FL & RC_PERS)) return;#endif const long toff = ((t >> 7) * 2 + (lane >> 4)) * 16384 + (t & 127) * 128 + ((((lane & 15) >> 1) ^ (int)(t & 7)) << 4) + (lane & 1) * 8; if (t >= T) { // warp-uniform if (outt && t < ((T + 127) & ~127)) *reinterpret_cast<uint2*>(outt + toff) = make_uint2(0u, 0u);
return; } int e = 0; unsigned short gw = 0, mk = 0; auto load_sel = [&]() { if (lane < TOPK) { if ((FL & RC_SEL32) && (FL & RC_S64) && (FL & RC_LDG)) asm volatile("ld.global.L1::no_allocate.L2::64B.s32 %0, [%1];" : "=r"(e) : "l"(reinterpret_cast<const int*>(sel) + (t * TOPK + lane) * 2)); else if ((FL & RC_SEL32) && (FL & RC_S64)) // low word of the 64B sel row,.L2::64B hint asm volatile("ld.global.nc.L1::no_allocate.L2::64B.s32 %0, [%1];" : "=r"(e) : "l"(reinterpret_cast<const int*>(sel) + (t * TOPK + lane) * 2)); else if (FL & RC_SEL32) e = __ldg(reinterpret_cast<const int*>(sel) + (t * TOPK + lane) * 2); else if (FL & RC_S64) { // sel row (64B) + grw row with.L2::64B prefetch-size hint, L1 no_allocate long long ev; asm volatile("ld.global.nc.L1::no_allocate.L2::64B.s64 %0, [%1];" : "=l"(ev) : "l"(sel + t * TOPK + lane)); e = (int)ev; } else e = (int)__ldg(sel + t * TOPK + lane); if (FL & RC_S64) asm volatile("ld.global.nc.L1::no_allocate.L2::64B.u16 %0, [%1];" : "=h"(gw) : "l"(reinterpret_cast<const unsigned short*>(grw) + t * TOPK + lane)); else gw = __ldg(reinterpret_cast<const unsigned short*>(grw) + t * TOPK + lane); } }; if (FL & RC_SELF) load_sel(); float4 p; uint2 gr; if (FL & (RC_AB_NOP | RC_AB_NOR)) { if (FL & RC_AB_NOP) p = make_float4(0.01f, 0.02f, 0.003f, 0.004f * (float)lane); else p = ld_nc_f4(reinterpret_cast<const float4*>(probs + t * E) + lane); if (FL & RC_AB_NOR) gr = make_uint2(0x3c003c00u ^ (uint32_t)lane, 0x3c003c00u); else gr = ld_nc_u2(reinterpret_cast<const uint2*>(grl + t * E) + lane); } else if (FL & RC_L2PF) { p = ld_nc_f4_pf(reinterpret_cast<const float4*>(probs + t * E) + lane); gr = ld_nc_u2_pf(reinterpret_cast<const uint2*>(grl + t * E) + lane); } else { p = ld_nc_f4(reinterpret_cast<const float4*>(probs + t * E) + lane); gr = ld_nc_u2(reinterpret_cast<const uint2*>(grl + t * E) + lane); } if (!(FL & RC_SELF)) load_sel();#ifndef RC_GPF_ON#define RC_GPF_ON 0#endif // small band (outt != nullptr): L2 PREFETCH of this token group's grad_expert_mask columns, // issued while sel is still in flight -> the dependent sel -> gmask gather hits L2 instead of // DRAM. A 16-token group g0 = t & ~15 covers 32B of each of the 1024 (e,k) rows; warp t&15 of // the group prefetches rows (t&15)*64 + lane*2 + {0,1}, at the first and last token of the // group (an unaligned 32B span may straddle two sectors). Pure cache hint (no data dependence). if (RC_GPF_ON && outt) { const long g0 = t & ~15L; const long g1 = (g0 + 15 < T ? g0 + 15 : (long)T - 1) - g0; const unsigned short* gm = reinterpret_cast<const unsigned short*>(gmask) + g0;#pragma unroll for (int j = 0; j < 2; j++) { const unsigned short* rp = gm + (size_t)((int)(t & 15) * 64 + lane * 2 + j) * (unsigned)T; asm volatile("prefetch.global.L2 [%0];" :: "l"(rp)); asm volatile("prefetch.global.L2 [%0];" :: "l"(rp + g1)); } }#if RW64 float S; if (FL & RC_LDG) asm volatile("ld.global.nc.L1::no_allocate.L2::64B.f32 %0, [%1];" : "=f"(S) : "l"(wsum + t)); else S = __ldg(wsum + t);#else const float S = __ldg(wsum + t);#endif e &= (E - 1); // sparse dependent gather grad_expert_mask[e_k, k, t] if (FL & RC_AB_NOG) { mk = (unsigned short)(e * 3 + lane); } else if ((FL & RC_G128) && lane < TOPK) { asm volatile("ld.global.nc.L1::no_allocate.L2::128B.u16 %0, [%1];" : "=h"(mk) : "l"(reinterpret_cast<const unsigned short*>(gmask) + t + (size_t)(unsigned)(e * TOPK + lane) * (unsigned)T)); } else if ((FL & RC_G64) && (FL & RC_LDG) && lane < TOPK) { asm volatile("ld.global.L1::no_allocate.L2::64B.u16 %0, [%1];" : "=h"(mk) : "l"(reinterpret_cast<const unsigned short*>(gmask) + t + (size_t)(unsigned)(e * TOPK + lane) * (unsigned)T)); } else if ((FL & RC_G64) && lane < TOPK) asm volatile("ld.global.nc.L1::no_allocate.L2::64B.u16 %0, [%1];" : "=h"(mk) : "l"(reinterpret_cast<const unsigned short*>(gmask) + t + (size_t)(unsigned)(e * TOPK + lane) * (unsigned)T)); else if (lane < TOPK) asm volatile("ld.global.nc.L1::no_allocate.u16 %0, [%1];" : "=h"(mk) : "l"(reinterpret_cast<const unsigned short*>(gmask) + t + (size_t)(unsigned)(e * TOPK + lane) * (unsigned)T)); if (FL & RC_MIDT) pdl_launch_dependents(); // ---- everything that does not depend on the gather __nv_bfloat162 g01 = *reinterpret_cast<const __nv_bfloat162*>(&gr.x); __nv_bfloat162 g23 = *reinterpret_cast<const __nv_bfloat162*>(&gr.y); const float4 g0 = make_float4(__low2float(g01), __high2float(g01), __low2float(g23), __high2float(g23)); float* spr = sbuf[0][w]; float* sgr = sbuf[(FL & RC_ONEBUF) ? 0 : 1][w]; reinterpret_cast<float4*>(spr)[lane] = p; if (!(FL & RC_ONEBUF)) reinterpret_cast<float4*>(sgr)[lane] = g0; __syncwarp(); const float gwk = __uint_as_float((uint32_t)gw << 16); // 0 on lanes >= 8 const float wk = spr[e]; // probs[t, e_k] if (FL & RC_ONEBUF) { // all gathers done -> overwrite the row with the grad row __syncwarp(); reinterpret_cast<float4*>(sgr)[lane] = g0; __syncwarp(); } // one correctly-rounded reciprocal per token (__frcp_rn) + the S-only products gwk/S and 1/S^2 // computed off the shuffle-reduction chain -> normalization grad = ONE FMA after the reduction: // ncon = gwk/S - (sum_k gwk*wk) / S^2 const float rS = __frcp_rn(S); const float gr_s = gwk * rS, rS2 = rS * rS; float c = gwk * wk; c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); const float ncon = fmaf(-c, rS2, gr_s); // normalization grad (pre-mask) float dot0 = 0.f; if (FL & RC_EDOT) { if (FL & RC_F2) { // packed f32x2: v = (g0.xy * p.xy); v = fma(g0.zw, p.zw, v); dot0 = v.lo + v.hi unsigned long long v; asm("{\n .reg .b64 a, b, c, d;\n mov.b64 a, {%1, %2};\n mov.b64 b, {%3, %4};\n mov.b64 c, {%5, %6};\n" " mov.b64 d, {%7, %8};\n mul.rn.f32x2 a, a, b;\n fma.rn.f32x2 %0, c, d, a;\n}" : "=l"(v) : "f"(g0.x), "f"(g0.y), "f"(p.x), "f"(p.y), "f"(g0.z), "f"(g0.w), "f"(p.z), "f"(p.w)); dot0 = __uint_as_float((uint32_t)v) + __uint_as_float((uint32_t)(v >> 32)); } else dot0 = g0.x * p.x + g0.y * p.y + g0.z * p.z + g0.w * p.w;#pragma unroll for (int o = 16; o > 0; o >>= 1) dot0 += __shfl_xor_sync(0xffffffff, dot0, o); } // ---- after the gather const float contrib = ncon + __uint_as_float((uint32_t)mk << 16); // scatter of norm grad + mask grad: top-k indices are distinct -> plain RMW (no shared atomic) if (lane < TOPK) sgr[e] += contrib; float dot; if (FL & RC_EDOT) { float d = lane < TOPK ? contrib * wk : 0.f; d += __shfl_xor_sync(0xffffffff, d, 1); d += __shfl_xor_sync(0xffffffff, d, 2); d += __shfl_xor_sync(0xffffffff, d, 4); dot = dot0 + __shfl_sync(0xffffffff, d, 0); } __syncwarp(); const float4 g = reinterpret_cast<const float4*>(sgr)[lane]; if (!(FL & RC_EDOT)) { dot = g.x * p.x + g.y * p.y + g.z * p.z + g.w * p.w;#pragma unroll for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffff, dot, o); } __nv_bfloat162 o01 = __floats2bfloat162_rn(p.x * (g.x - dot), p.y * (g.y - dot)); __nv_bfloat162 o23 = __floats2bfloat162_rn(p.z * (g.z - dot), p.w * (g.w - dot)); uint2 ow; ow.x = *reinterpret_cast<uint32_t*>(&o01); ow.y = *reinterpret_cast<uint32_t*>(&o23); if (outt) { // pre-tiled layout (small band), checked first#if RT_NA st_na_u2(outt + toff, ow); // RTNA: no L1 allocation for the write-once pre-tiled G#else *reinterpret_cast<uint2*>(outt + toff) = ow;#endif } else if (FL & RC_ST16) { const uint32_t nx = __shfl_down_sync(0xffffffff, ow.x, 1); const uint32_t ny = __shfl_down_sync(0xffffffff, ow.y, 1); if ((FL & RC_AB_NOS) && (ow.x != 0x7fc17fc1u || nx != 0x7fc27fc2u)) { } else if (FL & RC_STCS) { if (!(lane & 1)) asm volatile("st.global.cs.v4.b32 [%0], {%1, %2, %3, %4};" :: "l"(reinterpret_cast<uint4*>(out + t * E) + (lane >> 1)), "r"(ow.x), "r"(ow.y), "r"(nx), "r"(ny) : "memory"); } else if (!(lane & 1)) reinterpret_cast<uint4*>(out + t * E)[lane >> 1] = make_uint4(ow.x, ow.y, nx, ny); } else { st_na_u2(reinterpret_cast<uint2*>(out + t * E) + lane, ow); // no L1 allocate } if (FL & RC_LATE) pdl_launch_dependents(); }; if (FL & RC_PERS) { // persistent: grid = (#SMs x resident blocks), each warp strides over tokens (no block churn) const long stride = (long)gridDim.x * WARPS; for (long t = (long)blockIdx.x * WARPS + w; t < T; t += stride) { __syncwarp(); tok(t); } } else { tok((long)blockIdx.x * WARPS + w); }#ifdef MM_DLY if (blockIdx.x == 0 && threadIdx.x == 0) { unsigned long long t0_, t1_; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t0_)); do { asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t1_)); } while (t1_ - t0_ < MM_DLY); }#endif B4RX();#ifdef PROBE_TS if (threadIdx.x == 0) atomicMax(&g_ts[2][psl], gtime());#endif}
// route_m_kernel<WARPS> (mid band RS_MAX_T <= T < 16384, row-major G): HALF-WARP per token.// Each warp carries 2 tokens (lanes 0..15 / 16..31), lane hl = lane & 15 owns experts hl*8..hl*8+7// -> twice the tokens in flight per thread and ~half the issued instructions per token vs route_c.// Load order per token (critical chain sel -> gmask gather -> reductions -> G store):// sel low word + grw (lanes hl < 8) FIRST, then the dense probs (2 x 16B) / grl (16B) / wsum// loads, then the dependent gmask gather as soon as sel lands (the dense loads are in flight// during its latency). One smem row per half-warp: probs staged (gather of probs[t, e_k]),// then overwritten with the grad row (scatter target, plain RMW: top-k indices are distinct).// Reductions are xor-shuffles confined to the half / its 8 top-k lanes. 16B G store per lane.// An odd tail half-warp clamps its loads to token T-1 and masks its store.template <int WARPS>__global__ void __launch_bounds__(WARPS * 32)route_m_kernel(const float* __restrict__ probs, const int64_t* __restrict__ sel, const float* __restrict__ wsum, const __nv_bfloat16* __restrict__ grw, const __nv_bfloat16* __restrict__ gmask, const __nv_bfloat16* __restrict__ grl, __nv_bfloat16* __restrict__ out, int T, unsigned char* __restrict__ /*outt (unused)*/) { __shared__ __align__(16) float sbuf[WARPS][2][E]; pdl_wait(); pdl_launch_dependents(); const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; const int hl = lane & 15, hs = lane >> 4; const long tw = ((long)blockIdx.x * WARPS + w) * 2; if (tw >= T) return; // warp-uniform const long t = tw + hs; const bool valid = t < T; const long tc = valid ? t : (long)T - 1; // clamped (tail half: loads stay in bounds) int e = 0; unsigned short gw = 0, mk = 0; if (hl < TOPK) { e = __ldg(reinterpret_cast<const int*>(sel) + (tc * TOPK + hl) * 2) & (E - 1); gw = __ldg(reinterpret_cast<const unsigned short*>(grw) + tc * TOPK + hl); } const float4 p0 = ld_nc_f4(reinterpret_cast<const float4*>(probs + tc * E) + hl * 2); const float4 p1 = ld_nc_f4(reinterpret_cast<const float4*>(probs + tc * E) + hl * 2 + 1); uint4 gr; asm volatile("ld.global.nc.L1::no_allocate.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(gr.x), "=r"(gr.y), "=r"(gr.z), "=r"(gr.w) : "l"(reinterpret_cast<const uint4*>(grl + tc * E) + hl)); const float S = __ldg(wsum + tc); if (hl < TOPK) // sparse dependent gather grad_expert_mask[e_k, k, t] asm volatile("ld.global.nc.L1::no_allocate.u16 %0, [%1];" : "=h"(mk) : "l"(reinterpret_cast<const unsigned short*>(gmask) + tc + (size_t)(unsigned)(e * TOPK + hl) * (unsigned)T)); float* row = sbuf[w][hs]; reinterpret_cast<float4*>(row)[hl * 2] = p0; reinterpret_cast<float4*>(row)[hl * 2 + 1] = p1; __syncwarp(); const float wk = row[e]; // probs[t, e_k] (unused on hl >= 8) float g[8]; { const uint32_t gu[4] = {gr.x, gr.y, gr.z, gr.w};#pragma unroll for (int j = 0; j < 4; j++) { __nv_bfloat162 b = *reinterpret_cast<const __nv_bfloat162*>(&gu[j]); g[2 * j] = __low2float(b); g[2 * j + 1] = __high2float(b); } } __syncwarp(); // all gathers of the probs row done -> overwrite it with the grad row reinterpret_cast<float4*>(row)[hl * 2] = make_float4(g[0], g[1], g[2], g[3]); reinterpret_cast<float4*>(row)[hl * 2 + 1] = make_float4(g[4], g[5], g[6], g[7]); const float gwk = __uint_as_float((uint32_t)gw << 16); // 0 on hl >= 8 const float rS = 1.0f / S; float c = gwk * wk; // xor 1/2/4 stays inside lanes hl < 8 c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); const float contrib = (gwk - c * rS) * rS + __uint_as_float((uint32_t)mk << 16); __syncwarp(); if (hl < TOPK) row[e] += contrib; // scatter of norm grad + mask grad (distinct experts) __syncwarp(); const float4 ga = reinterpret_cast<const float4*>(row)[hl * 2]; const float4 gb = reinterpret_cast<const float4*>(row)[hl * 2 + 1]; float dot = ga.x * p0.x + ga.y * p0.y + ga.z * p0.z + ga.w * p0.w + gb.x * p1.x + gb.y * p1.y + gb.z * p1.z + gb.w * p1.w;#pragma unroll for (int o = 8; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffff, dot, o); // within the half __nv_bfloat162 o0 = __floats2bfloat162_rn(p0.x * (ga.x - dot), p0.y * (ga.y - dot)); __nv_bfloat162 o1 = __floats2bfloat162_rn(p0.z * (ga.z - dot), p0.w * (ga.w - dot)); __nv_bfloat162 o2 = __floats2bfloat162_rn(p1.x * (gb.x - dot), p1.y * (gb.y - dot)); __nv_bfloat162 o3 = __floats2bfloat162_rn(p1.z * (gb.z - dot), p1.w * (gb.w - dot)); uint4 ow; ow.x = *reinterpret_cast<uint32_t*>(&o0); ow.y = *reinterpret_cast<uint32_t*>(&o1); ow.z = *reinterpret_cast<uint32_t*>(&o2); ow.w = *reinterpret_cast<uint32_t*>(&o3); if (valid) reinterpret_cast<uint4*>(out + t * E)[hl] = ow; // 16B per lane, 256B per token}
// route_mp_kernel<WARPS, MINB> (LARGE band T >= 16384, row-major G): PERSISTENT HALF-WARP-per-token route.// Each warp carries 2 tokens per iteration (lanes 0..15 -> token tw, 16..31 -> tw+1); lane hl owns experts// hl*8..hl*8+7, so every dense load is 128-bit (probs 2 x 16B, grl 16B, ld.global.nc.L1::no_allocate) and// routing_probs is read exactly once (kept in registers for the softmax-bwd dot and the output product;// the probs[t, e_k] gather goes through a per-half smem row). sel low word / grw / the sparse// grad_expert_mask gather use .L2::64B hints. Grid = one resident wave, warps grid-stride over token pairs.template <int WARPS, int MINB>__global__ void __launch_bounds__(WARPS * 32, MINB)route_mp_kernel(const float* __restrict__ probs, const int64_t* __restrict__ sel, const float* __restrict__ wsum, const __nv_bfloat16* __restrict__ grw, const __nv_bfloat16* __restrict__ gmask, const __nv_bfloat16* __restrict__ grl, __nv_bfloat16* __restrict__ out, int T, unsigned char* __restrict__ /*outt (unused)*/) { __shared__ __align__(16) float sbuf[WARPS][2][E]; B4RE(); pdl_wait(); B4S(); pdl_launch_dependents(); const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; const int hl = lane & 15, hs = lane >> 4; float* row = sbuf[w][hs]; const long stride = (long)gridDim.x * WARPS * 2; for (long tw = ((long)blockIdx.x * WARPS + w) * 2; tw < T; tw += stride) { __syncwarp(); // previous iteration's smem reads done const long t = tw + hs; const bool valid = t < T; const long tc = valid ? t : (long)T - 1; // tail half: loads clamped in bounds, store masked int e = 0; unsigned short gw = 0, mk = 0; if (hl < TOPK) { asm volatile("ld.global.nc.L1::no_allocate.L2::64B.s32 %0, [%1];" : "=r"(e) : "l"(reinterpret_cast<const int*>(sel) + (tc * TOPK + hl) * 2)); asm volatile("ld.global.nc.L1::no_allocate.L2::64B.u16 %0, [%1];" : "=h"(gw) : "l"(reinterpret_cast<const unsigned short*>(grw) + tc * TOPK + hl)); } const float4 p0 = ld_nc_f4(reinterpret_cast<const float4*>(probs + tc * E) + hl * 2); const float4 p1 = ld_nc_f4(reinterpret_cast<const float4*>(probs + tc * E) + hl * 2 + 1); uint4 gr; asm volatile("ld.global.nc.L1::no_allocate.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(gr.x), "=r"(gr.y), "=r"(gr.z), "=r"(gr.w) : "l"(reinterpret_cast<const uint4*>(grl + tc * E) + hl)); const float S = __ldg(wsum + tc); e &= (E - 1); if (hl < TOPK) // sparse dependent gather grad_expert_mask[e_k, k, t] asm volatile("ld.global.nc.L1::no_allocate.L2::64B.u16 %0, [%1];" : "=h"(mk) : "l"(reinterpret_cast<const unsigned short*>(gmask) + tc + (size_t)(unsigned)(e * TOPK + hl) * (unsigned)T)); reinterpret_cast<float4*>(row)[hl * 2] = p0; reinterpret_cast<float4*>(row)[hl * 2 + 1] = p1; float g[8]; { const uint32_t gu[4] = {gr.x, gr.y, gr.z, gr.w};#pragma unroll for (int j = 0; j < 4; j++) { __nv_bfloat162 b = *reinterpret_cast<const __nv_bfloat162*>(&gu[j]); g[2 * j] = __low2float(b); g[2 * j + 1] = __high2float(b); } } __syncwarp(); const float wk = row[e]; // probs[t, e_k] (unused on hl >= 8) __syncwarp(); // gathers done -> overwrite the row with the grad row reinterpret_cast<float4*>(row)[hl * 2] = make_float4(g[0], g[1], g[2], g[3]); reinterpret_cast<float4*>(row)[hl * 2 + 1] = make_float4(g[4], g[5], g[6], g[7]); const float gwk = __uint_as_float((uint32_t)gw << 16); // 0 on hl >= 8 const float rS = 1.0f / S; float c = gwk * wk; // xor 1/2/4 stays inside lanes hl < 8 of each half c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); const float contrib = (gwk - c * rS) * rS + __uint_as_float((uint32_t)mk << 16); __syncwarp(); if (hl < TOPK) row[e] += contrib; // scatter (top-k experts distinct) __syncwarp(); const float4 ga = reinterpret_cast<const float4*>(row)[hl * 2]; const float4 gb = reinterpret_cast<const float4*>(row)[hl * 2 + 1]; float dot = ga.x * p0.x + ga.y * p0.y + ga.z * p0.z + ga.w * p0.w + gb.x * p1.x + gb.y * p1.y + gb.z * p1.z + gb.w * p1.w;#pragma unroll for (int o = 8; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffff, dot, o); // within the half __nv_bfloat162 o0 = __floats2bfloat162_rn(p0.x * (ga.x - dot), p0.y * (ga.y - dot)); __nv_bfloat162 o1 = __floats2bfloat162_rn(p0.z * (ga.z - dot), p0.w * (ga.w - dot)); __nv_bfloat162 o2 = __floats2bfloat162_rn(p1.x * (gb.x - dot), p1.y * (gb.y - dot)); __nv_bfloat162 o3 = __floats2bfloat162_rn(p1.z * (gb.z - dot), p1.w * (gb.w - dot)); if (valid) asm volatile("st.global.L1::no_allocate.v4.b32 [%0], {%1, %2, %3, %4};" :: "l"(reinterpret_cast<uint4*>(out + t * E) + hl), "r"(*reinterpret_cast<uint32_t*>(&o0)), "r"(*reinterpret_cast<uint32_t*>(&o1)), "r"(*reinterpret_cast<uint32_t*>(&o2)), "r"(*reinterpret_cast<uint32_t*>(&o3)) : "memory"); } B4RX();}
template <int WARPS, int MINB>__global__ void __launch_bounds__(WARPS * 32, MINB)route_mpp_kernel(const float* __restrict__ probs, const int64_t* __restrict__ sel, const float* __restrict__ wsum, const __nv_bfloat16* __restrict__ grw, const __nv_bfloat16* __restrict__ gmask, const __nv_bfloat16* __restrict__ grl, __nv_bfloat16* __restrict__ out, int T, unsigned char* __restrict__ /*outt (unused)*/) { __shared__ __align__(16) float sbuf[WARPS][2][E]; B4RE(); pdl_wait(); B4S(); pdl_launch_dependents(); const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; const int hl = lane & 15, hs = lane >> 4; float* row = sbuf[w][hs]; const long stride = (long)gridDim.x * WARPS * 2; // independent per-pair operands (loaded one pair ahead) int e = 0; unsigned short gw = 0; float4 p0 = make_float4(0.f, 0.f, 0.f, 0.f), p1 = p0; uint4 gr = make_uint4(0u, 0u, 0u, 0u); float S = 1.f; auto load = [&](long tw) { // tw < T (warp-uniform); tail half clamps to T-1 const long t = tw + hs; const long tc = t < T ? t : (long)T - 1; if (hl < TOPK) { asm volatile("ld.global.nc.L1::no_allocate.L2::64B.s32 %0, [%1];" : "=r"(e) : "l"(reinterpret_cast<const int*>(sel) + (tc * TOPK + hl) * 2)); asm volatile("ld.global.nc.L1::no_allocate.L2::64B.u16 %0, [%1];" : "=h"(gw) : "l"(reinterpret_cast<const unsigned short*>(grw) + tc * TOPK + hl)); } p0 = ld_nc_f4(reinterpret_cast<const float4*>(probs + tc * E) + hl * 2); p1 = ld_nc_f4(reinterpret_cast<const float4*>(probs + tc * E) + hl * 2 + 1); asm volatile("ld.global.nc.L1::no_allocate.v4.u32 {%0,%1,%2,%3}, [%4];" : "=r"(gr.x), "=r"(gr.y), "=r"(gr.z), "=r"(gr.w) : "l"(reinterpret_cast<const uint4*>(grl + tc * E) + hl)); S = __ldg(wsum + tc); }; long tw = ((long)blockIdx.x * WARPS + w) * 2; if (tw < T) load(tw); for (; tw < T; tw += stride) { const long t = tw + hs; const bool valid = t < T; const long tc = valid ? t : (long)T - 1; // current pair: take its operands, issue its dependent gather const int ec = e & (E - 1); const unsigned short gwc = gw; const float4 q0 = p0, q1 = p1; const uint4 grc = gr; const float Sc = S; unsigned short mk = 0; if (hl < TOPK) // sparse dependent gather grad_expert_mask[e_k, k, t] asm volatile("ld.global.nc.L1::no_allocate.L2::64B.u16 %0, [%1];" : "=h"(mk) : "l"(reinterpret_cast<const unsigned short*>(gmask) + tc + (size_t)(unsigned)(ec * TOPK + hl) * (unsigned)T)); // next pair's independent loads in flight during this pair's math if (tw + stride < T) load(tw + stride); __syncwarp(); // previous iteration's smem reads done reinterpret_cast<float4*>(row)[hl * 2] = q0; reinterpret_cast<float4*>(row)[hl * 2 + 1] = q1; float g[8]; { const uint32_t gu[4] = {grc.x, grc.y, grc.z, grc.w};#pragma unroll for (int j = 0; j < 4; j++) { __nv_bfloat162 b = *reinterpret_cast<const __nv_bfloat162*>(&gu[j]); g[2 * j] = __low2float(b); g[2 * j + 1] = __high2float(b); } } __syncwarp(); const float wk = row[ec]; // probs[t, e_k] (unused on hl >= 8) __syncwarp(); // gathers done -> overwrite the row with the grad row reinterpret_cast<float4*>(row)[hl * 2] = make_float4(g[0], g[1], g[2], g[3]); reinterpret_cast<float4*>(row)[hl * 2 + 1] = make_float4(g[4], g[5], g[6], g[7]); const float gwk = __uint_as_float((uint32_t)gwc << 16); // 0 on hl >= 8 const float rS = 1.0f / Sc; float c = gwk * wk; c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); const float contrib = (gwk - c * rS) * rS + __uint_as_float((uint32_t)mk << 16); __syncwarp(); if (hl < TOPK) row[ec] += contrib; // scatter (top-k experts distinct) __syncwarp(); const float4 ga = reinterpret_cast<const float4*>(row)[hl * 2]; const float4 gb = reinterpret_cast<const float4*>(row)[hl * 2 + 1]; float dot = ga.x * q0.x + ga.y * q0.y + ga.z * q0.z + ga.w * q0.w + gb.x * q1.x + gb.y * q1.y + gb.z * q1.z + gb.w * q1.w;#pragma unroll for (int o = 8; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffff, dot, o); __nv_bfloat162 o0 = __floats2bfloat162_rn(q0.x * (ga.x - dot), q0.y * (ga.y - dot)); __nv_bfloat162 o1 = __floats2bfloat162_rn(q0.z * (ga.z - dot), q0.w * (ga.w - dot)); __nv_bfloat162 o2 = __floats2bfloat162_rn(q1.x * (gb.x - dot), q1.y * (gb.y - dot)); __nv_bfloat162 o3 = __floats2bfloat162_rn(q1.z * (gb.z - dot), q1.w * (gb.w - dot)); if (valid) asm volatile("st.global.L1::no_allocate.v4.b32 [%0], {%1, %2, %3, %4};" :: "l"(reinterpret_cast<uint4*>(out + t * E) + hl), "r"(*reinterpret_cast<uint32_t*>(&o0)), "r"(*reinterpret_cast<uint32_t*>(&o1)), "r"(*reinterpret_cast<uint32_t*>(&o2)), "r"(*reinterpret_cast<uint32_t*>(&o3)) : "memory"); } B4RX();}
#if RCL_SMALL // compiled only when the (off) cluster route is enabled (it was the only spilling kernel)// RCL (small band T < 1408): CLUSTER route. (8,1,1) clusters, one cluster per 64-token window// [t0, t0+64); CTA rank r (8 warps, one token per warp: t = t0 + 8r + warp) loads, right after// griddepcontrol.wait and concurrently with its sel / probs / grl loads, the grad_expert_mask slab// rows (e,k) in [128r, 128r+128) x tokens [t0, t0+64) (128 full 128B lines = 16KB, zero past T) into// smem. After one cluster barrier (all slabs landed) each top-k lane reads its gmask value from the// owning rank's smem via DSMEM (owner = (e*8+k) >> 7) -> the dependent sel -> DRAM gather hop is gone.// A trailing cluster barrier keeps every slab alive until all peers read it. Math = route_c_kernel// <4, R4_FL> (bit-exact); writes only the pre-tiled G layout (outt), zero-filling rows T..roundup(T,128).__global__ void __launch_bounds__(256, 8)route_cl_kernel(const float* __restrict__ probs, const int64_t* __restrict__ sel, const float* __restrict__ wsum, const __nv_bfloat16* __restrict__ grw, const __nv_bfloat16* __restrict__ gmask, const __nv_bfloat16* __restrict__ grl, __nv_bfloat16* __restrict__ /*out (unused)*/, int T, unsigned char* __restrict__ outt) { __shared__ __align__(16) float sbuf[2][8][E]; __shared__ __align__(128) unsigned short slab[128 * 64]; // [local (e,k) row][64 tokens] B4RE(); pdl_launch_dependents(); // RC_PDE const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; uint32_t rank; asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(rank)); const long t0 = (long)(blockIdx.x >> 3) * 64; const long t = (long)blockIdx.x * 8 + w; if (t < T && lane < 2) { // RC_SPF: pre-wait L2 prefetch of the sel / grw rows const void* pa = lane == 0 ? (const void*)(sel + t * TOPK) : (const void*)(grw + t * TOPK); asm volatile("prefetch.global.L2 [%0];" :: "l"(pa)); } if (threadIdx.x == 0) { // RC_GTLB: warm the translation of this rank's slab region const size_t off = ((size_t)rank * 128) * (size_t)T + (size_t)t0; if (off < (size_t)E * TOPK * (size_t)T) asm volatile("prefetch.global.L2 [%0];" :: "l"(reinterpret_cast<const unsigned short*>(gmask) + off)); } pdl_wait(); B4S(); B4DLY(); // ---- slab loads (inputs only; issued first so their latency overlaps the per-token loads) const unsigned short* gsl = reinterpret_cast<const unsigned short*>(gmask) + (size_t)rank * 128 * (size_t)T; uint32_t sv[16]; const bool even = (T & 1) == 0; const int c2 = threadIdx.x & 31, rg = threadIdx.x >> 5; // even T: token pair c2, rows rg + 8j const int c1 = threadIdx.x & 63, rq = threadIdx.x >> 6; // odd T: token c1, rows rq + 4j if (even) { const long tc = t0 + 2 * c2;#pragma unroll for (int j = 0; j < 16; j++) { sv[j] = 0u; if (tc < T) asm volatile("ld.global.nc.L1::no_allocate.L2::128B.u32 %0, [%1];" : "=r"(sv[j]) : "l"(gsl + (size_t)(rg + 8 * j) * (size_t)T + tc)); } } else { const long tc = t0 + c1;#pragma unroll for (int j = 0; j < 32; j++) { unsigned short v = 0; if (tc < T) asm volatile("ld.global.nc.L1::no_allocate.L2::128B.u16 %0, [%1];" : "=h"(v) : "l"(gsl + (size_t)(rq + 4 * j) * (size_t)T + tc)); if (j & 1) sv[j >> 1] |= (uint32_t)v << 16; else sv[j >> 1] = v; } } // ---- per-token loads (route_c R4_FL order: sel first) const bool valid = t < T; int e = 0; unsigned short gw = 0; float4 p = make_float4(0.f, 0.f, 0.f, 0.f); uint2 gr = make_uint2(0u, 0u); float S = 1.f; if (valid) { if (lane < TOPK) { asm volatile("ld.global.L1::no_allocate.L2::64B.s32 %0, [%1];" : "=r"(e) : "l"(reinterpret_cast<const int*>(sel) + (t * TOPK + lane) * 2)); asm volatile("ld.global.nc.L1::no_allocate.L2::64B.u16 %0, [%1];" : "=h"(gw) : "l"(reinterpret_cast<const unsigned short*>(grw) + t * TOPK + lane)); } p = ld_nc_f4(reinterpret_cast<const float4*>(probs + t * E) + lane); gr = ld_nc_u2(reinterpret_cast<const uint2*>(grl + t * E) + lane); S = __ldg(wsum + t); } e &= (E - 1); // ---- slab -> smem, cluster barrier #1 arrive (release) if (even) {#pragma unroll for (int j = 0; j < 16; j++) *reinterpret_cast<uint32_t*>(&slab[(rg + 8 * j) * 64 + 2 * c2]) = sv[j]; } else {#pragma unroll for (int j = 0; j < 32; j++) slab[(rq + 4 * j) * 64 + c1] = (unsigned short)((j & 1) ? (sv[j >> 1] >> 16) : (sv[j >> 1] & 0xffffu)); } __syncwarp(); asm volatile("barrier.cluster.arrive.release.aligned;" ::: "memory"); // ---- work independent of the gather __nv_bfloat162 g01 = *reinterpret_cast<const __nv_bfloat162*>(&gr.x); __nv_bfloat162 g23 = *reinterpret_cast<const __nv_bfloat162*>(&gr.y); const float4 g0 = make_float4(__low2float(g01), __high2float(g01), __low2float(g23), __high2float(g23)); float* spr = sbuf[0][w]; float* sgr = sbuf[1][w]; reinterpret_cast<float4*>(spr)[lane] = p; reinterpret_cast<float4*>(sgr)[lane] = g0; __syncwarp(); const float gwk = __uint_as_float((uint32_t)gw << 16); const float wk = spr[e]; const float rS = __frcp_rn(S); const float gr_s = gwk * rS, rS2 = rS * rS; float c = gwk * wk; c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); const float ncon = fmaf(-c, rS2, gr_s); float dot0 = g0.x * p.x + g0.y * p.y + g0.z * p.z + g0.w * p.w;#pragma unroll for (int o = 16; o > 0; o >>= 1) dot0 += __shfl_xor_sync(0xffffffff, dot0, o); // ---- all slabs landed -> DSMEM gather of grad_expert_mask[e_k, k, t] asm volatile("barrier.cluster.wait.acquire.aligned;" ::: "memory"); unsigned short mk = 0; if (valid && lane < TOPK) { const uint32_t row = (uint32_t)(e * TOPK + lane); uint32_t ra; asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(ra) : "r"((uint32_t)__cvta_generic_to_shared(slab) + (row & 127u) * 128u + (uint32_t)(t - t0) * 2u), "r"(row >> 7)); asm volatile("ld.shared::cluster.u16 %0, [%1];" : "=h"(mk) : "r"(ra) : "memory"); } __syncwarp(); asm volatile("barrier.cluster.arrive.relaxed.aligned;" ::: "memory"); // remote reads consumed const float contrib = ncon + __uint_as_float((uint32_t)mk << 16); if (lane < TOPK) sgr[e] += contrib; float d = lane < TOPK ? contrib * wk : 0.f; d += __shfl_xor_sync(0xffffffff, d, 1); d += __shfl_xor_sync(0xffffffff, d, 2); d += __shfl_xor_sync(0xffffffff, d, 4); const float dot = dot0 + __shfl_sync(0xffffffff, d, 0); __syncwarp(); const float4 g = reinterpret_cast<const float4*>(sgr)[lane]; __nv_bfloat162 o01 = __floats2bfloat162_rn(p.x * (g.x - dot), p.y * (g.y - dot)); __nv_bfloat162 o23 = __floats2bfloat162_rn(p.z * (g.z - dot), p.w * (g.w - dot)); uint2 ow; ow.x = *reinterpret_cast<uint32_t*>(&o01); ow.y = *reinterpret_cast<uint32_t*>(&o23); const long toff = ((t >> 7) * 2 + (lane >> 4)) * 16384 + (t & 127) * 128 + ((((lane & 15) >> 1) ^ (int)(t & 7)) << 4) + (lane & 1) * 8; if (valid) *reinterpret_cast<uint2*>(outt + toff) = ow; else if (t < ((T + 127) & ~127)) *reinterpret_cast<uint2*>(outt + toff) = make_uint2(0u, 0u); asm volatile("barrier.cluster.wait.aligned;" ::: "memory"); // peers done reading this slab B4RX();}#endif123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107// route_v_kernel<WARPS, TPW, MINB, NC, SEL32, BULK>: generic large-band route backward.// Same math as route_bwd_smem_kernel (one warp per token, probs/grad rows staged in// per-warp smem; gather = LDS, top-k scatter = shared atomicAdd).// Block = WARPS warps, each warp loops over TPW consecutive tokens -> WARPS*TPW tok/block.// NC: probs / grl read with ld.global.nc.L1::no_allocate (streamed, no L1 pollution).// SEL32: selected_experts read as the low 32-bit word of each int64 (indices < 128).// GNC: the sparse grad_expert_mask gather also uses ld.global.nc.L1::no_allocate.// BULK: the block's G rows are staged in smem and written with ONE cp.async.bulk store.#pragma once__device__ __forceinline__ float4 ld_nc_f4(const float4* p) { float4 v; asm volatile("ld.global.nc.L1::no_allocate.v4.f32 {%0,%1,%2,%3}, [%4];" : "=f"(v.x), "=f"(v.y), "=f"(v.z), "=f"(v.w) : "l"(p)); return v;}__device__ __forceinline__ uint2 ld_nc_u2(const uint2* p) { uint2 v; asm volatile("ld.global.nc.L1::no_allocate.v2.u32 {%0,%1}, [%2];" : "=r"(v.x), "=r"(v.y) : "l"(p)); return v;}
template <int WARPS, int TPW, int MINB, bool NC, bool SEL32, bool BULK, bool GNC = false>__global__ void __launch_bounds__(WARPS * 32, MINB)route_v_kernel(const float* __restrict__ probs, const int64_t* __restrict__ sel, const float* __restrict__ wsum, const __nv_bfloat16* __restrict__ grw, const __nv_bfloat16* __restrict__ gmask, const __nv_bfloat16* __restrict__ grl, __nv_bfloat16* __restrict__ out, int T) { constexpr int TOKB = WARPS * TPW; __shared__ __align__(16) float sp[WARPS][E]; __shared__ __align__(16) float sg[WARPS][E]; __shared__ __align__(128) uint2 so[BULK ? TOKB * 32 : 1]; // BULK: G rows of this block pdl_wait(); pdl_launch_dependents(); const int lane = threadIdx.x & 31, w = threadIdx.x >> 5; const long tb = (long)blockIdx.x * TOKB;#pragma unroll 1 for (int i = 0; i < TPW; i++) { const int lt = w * TPW + i; // local token (consecutive per warp) const long t = tb + lt; if (t >= T) break; // warp-uniform int e = 0; unsigned short gw_raw = 0, mk_raw = 0; if (lane < TOPK) { if (SEL32) e = __ldg(reinterpret_cast<const int*>(sel) + (t * TOPK + lane) * 2); else e = (int)__ldg(sel + t * TOPK + lane); gw_raw = __ldg(reinterpret_cast<const unsigned short*>(grw) + t * TOPK + lane); } float4 p; uint2 graw; if (NC) { p = ld_nc_f4(reinterpret_cast<const float4*>(probs + t * E) + lane); graw = ld_nc_u2(reinterpret_cast<const uint2*>(grl + t * E) + lane); } else { p = __ldg(reinterpret_cast<const float4*>(probs + t * E) + lane); graw = __ldg(reinterpret_cast<const uint2*>(grl + t * E) + lane); } const float S = __ldg(wsum + t); e &= (E - 1); if (lane < TOPK && GNC) asm volatile("ld.global.nc.L1::no_allocate.u16 %0, [%1];" : "=h"(mk_raw) : "l"(reinterpret_cast<const unsigned short*>(gmask) + ((long)e * TOPK + lane) * T + t)); else if (lane < TOPK) mk_raw = __ldg(reinterpret_cast<const unsigned short*>(gmask) + ((long)e * TOPK + lane) * T + t); const float gwk = __uint_as_float((uint32_t)gw_raw << 16); const float mk = __uint_as_float((uint32_t)mk_raw << 16); __nv_bfloat162 g01 = *reinterpret_cast<const __nv_bfloat162*>(&graw.x); __nv_bfloat162 g23 = *reinterpret_cast<const __nv_bfloat162*>(&graw.y); __syncwarp(); // previous iteration's smem reads done reinterpret_cast<float4*>(sp[w])[lane] = p; reinterpret_cast<float4*>(sg[w])[lane] = make_float4(__low2float(g01), __high2float(g01), __low2float(g23), __high2float(g23)); __syncwarp(); const float wk = sp[w][e]; float c = gwk * wk / S; c += __shfl_xor_sync(0xffffffff, c, 1); c += __shfl_xor_sync(0xffffffff, c, 2); c += __shfl_xor_sync(0xffffffff, c, 4); const float contrib = (gwk / S - c / S) + mk; if (lane < TOPK) atomicAdd(&sg[w][e], contrib); __syncwarp(); const float4 g = reinterpret_cast<const float4*>(sg[w])[lane]; float dot = g.x * p.x + g.y * p.y + g.z * p.z + g.w * p.w;#pragma unroll for (int o = 16; o > 0; o >>= 1) dot += __shfl_xor_sync(0xffffffff, dot, o); __nv_bfloat162 o01 = __floats2bfloat162_rn(p.x * (g.x - dot), p.y * (g.y - dot)); __nv_bfloat162 o23 = __floats2bfloat162_rn(p.z * (g.z - dot), p.w * (g.w - dot)); uint2 ow; ow.x = *reinterpret_cast<uint32_t*>(&o01); ow.y = *reinterpret_cast<uint32_t*>(&o23); if (BULK) so[lt * 32 + lane] = ow; else reinterpret_cast<uint2*>(out + t * E)[lane] = ow; } if (BULK) { // one bulk async store of the block's contiguous G rows [tb, tb + ntok) asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); __syncthreads(); if (threadIdx.x == 0) { const long rem = (long)T - tb; const int ntok = rem < TOKB ? (int)rem : TOKB; asm volatile("cp.async.bulk.global.shared::cta.bulk_group [%0], [%1], %2;" :: "l"(out + tb * E), "r"((uint32_t)__cvta_generic_to_shared(so)), "r"(ntok * E * 2) : "memory"); asm volatile("cp.async.bulk.commit_group;" ::: "memory"); asm volatile("cp.async.bulk.wait_group.read 0;" ::: "memory"); } }}12345678910# MoE expert batched execution with capacity factor (L2 012)
Mixture-of-experts layer with a capacity factor: each expert keeps at most a set number of its routed tokens (the rest are dropped), runs a SwiGLU MLP, and outputs are summed with the routing weights.
- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 3 (4,655 lines).- Idea: Routing kernels rank tokens and drop over-capacity ones; swap-AB tcgen05 grouped GEMMs gather tokens, fuse SwiGLU, and scatter-add weighted rows in the down epilogue; PDL chain- Result: SOL score 0.900; speedup 1.70x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11.- Origin: search agent (Claude).- Comments edited; the code that runs is identical to the scored submission.- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready.12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061{ "board": "L2", "id": "012_moe_expert_batched_execution_with_capacity_factor", "name": "MoE expert batched execution with capacity factor", "language": "CUDA C++", "files": [ { "path": "src/kernel.cu", "lines": 4567, "bytes": 265536 }, { "path": "src/kernel.h", "lines": 12, "bytes": 997 }, { "path": "src/main.cpp", "lines": 76, "bytes": 3944 } ], "origin": "search agent (Claude)", "result": { "public": true, "sol_score": 0.899786, "speedup": 1.7019, "board_row": true, "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" }, "idea": "Routing kernels rank tokens and drop over-capacity ones; swap-AB tcgen05 grouped GEMMs gather tokens, fuse SwiGLU, and scatter-add weighted rows in the down epilogue; PDL chain", "spec": { "languages": [ "cuda_cpp" ], "target_hardware": [ "B200", "LOCAL" ], "entry_point": "main.cpp::run", "binding": "torch", "destination_passing_style": false, "dependencies": [], "compile_options": { "cuda_cflags": [ "-std=c++17", "-O3", "-gencode=arch=compute_100a,code=sm_100a" ], "ld_flags": [ "-lcuda" ], "cflags": [] }, "sources": [ "kernel.h", "kernel.cu", "main.cpp" ] }}123456789101112#pragma once
#include <cstdint>#include <cuda_runtime.h>// Host launcher for the full MoE pipeline (fused route+gather, gate/up GEMM, down GEMM, combine).// counts must have room for 2*E + 3 ints: [0,E) admitted counts, [E,2E) experts sorted by count// (heaviest first, LPT order), [2E], [2E+1] dynamic tile counters of the two GEMMs, [2E+2] W_down L2-prefetch unit counter,// [2E+3] output-zeroing-done counter, [2E+4, 3E+4) per-expert H-ready counters, [3E+4] tail-zero chunk grab counter, [3E+5] in-kernel gather unit grab, [3E+6, 4E+6) per-expert X-ready [4E+6, 5E+6) per-expert X-consumed (sized 2-SM gate/up X discard) (5E+6 ints total).void moe_launch(const void* hs, const int64_t* sel, const void* rw, const void* wg, const void* wu, const void* wd, int T, int topk, int E, int hidden, int inter, int cap, int* counts, int* hist, int* tok_list, int2* wt_list, int* pos_map, void* X, void* Hbuf, void* Y, void* out, cudaStream_t st);12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576// Torch binding: persistent workspaces + call into the custom CUDA pipeline in kernel.cu.// Host overhead removal: all intermediate buffers (routing tables, X/H/Y expert batches) live in// ONE heap-allocated, never-destructed workspace that only grows (no per-call torch allocations,// stable pointers so kernel.cu can cache its TMA tensor maps). Only the output tensor is// allocated per call. No memsets, no host syncs on the steady-state path.#include <torch/extension.h>#include <ATen/cuda/CUDAContext.h>#include <cuda_runtime.h>#include "kernel.h"#include <string>#include <cstdio>#include <vector>#include <algorithm>
namespace {struct Workspace { void* base = nullptr; size_t bytes = 0;};inline size_t al(size_t x) { return (x + 255) & ~size_t(255); }} // namespace
torch::Tensor run(torch::Tensor hidden_states, torch::Tensor selected_experts, torch::Tensor routing_weights, torch::Tensor expert_gate_weights, torch::Tensor expert_up_weights, torch::Tensor expert_down_weights) { auto hs = hidden_states.contiguous(); auto sel = selected_experts.scalar_type() == torch::kInt64 ? selected_experts.contiguous() : selected_experts.contiguous().to(torch::kInt64); auto rw = routing_weights.contiguous(); auto wg = expert_gate_weights.contiguous(); auto wu = expert_up_weights.contiguous(); auto wd = expert_down_weights.contiguous(); int T = hs.size(0); const int hidden = hs.size(1); const int E = wg.size(0), inter = wg.size(2), topk = sel.size(1); TORCH_CHECK(hidden == 6144 && inter == 2560, "kernel compiled for hidden=6144, inter=2560"); TORCH_CHECK(E <= 256 && topk <= 32, "routing kernels support E<=256, topk<=32"); auto out = torch::empty({T, hidden}, hs.options().dtype(torch::kBFloat16)); if (T == 0) return out; cudaStream_t st = at::cuda::getCurrentCUDAStream(); const void* wgp = wg.data_ptr(); const void* wup = wu.data_ptr(); auto do_run2 = [&](int T, const torch::Tensor& hs, const torch::Tensor& sel, const torch::Tensor& rw, torch::Tensor& out) { const double capd = ((double)T * topk / (double)E) * 1.25; int cap = (int)capd; if (cap < 1) cap = 1; const int64_t total = (int64_t)T * topk; const int64_t nb = (total + 1023) / 1024; const int64_t rows = (int64_t)E * cap; // workspace layout (each region 256B aligned) const size_t o_counts = 0; const size_t o_hist = o_counts + al((5 * (size_t)E + 6) * 4); // + gate/up->down sync ctrs const size_t o_tok = o_hist + al((size_t)(nb > 0 ? nb : 1) * E * 4); const size_t o_wt = o_tok + al((size_t)rows * 4); const size_t o_pos = o_wt + al((size_t)rows * 8); // packed int2 (token, weight bits) const size_t o_X = o_pos + al((size_t)total * 4); const size_t o_H = o_X + al((size_t)rows * hidden * 2); const size_t o_Y = o_H + al((size_t)rows * inter * 2); const size_t need = o_Y; // (no Y buffer: combine fused into the down epilogue) static Workspace& ws = *new Workspace(); // heap, never destructed (no teardown crash) if (need > ws.bytes) { if (ws.base) { cudaDeviceSynchronize(); cudaFree(ws.base); ws.base = nullptr; ws.bytes = 0; } const size_t nbytes = need * 2; TORCH_CHECK(cudaMalloc(&ws.base, nbytes) == cudaSuccess, "workspace cudaMalloc failed"); ws.bytes = nbytes; } char* b = static_cast<char*>(ws.base); moe_launch(hs.data_ptr(), sel.data_ptr<int64_t>(), rw.data_ptr(), wgp, wup, wd.data_ptr(), T, topk, E, hidden, inter, cap, (int*)(b + o_counts), (int*)(b + o_hist), (int*)(b + o_tok), (int2*)(b + o_wt), (int*)(b + o_pos), b + o_X, b + o_H, nullptr, out.data_ptr(), st); }; auto do_run = [&](int T) { do_run2(T, hs, sel, rw, out); }; do_run(T); return out;}
PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run, "MoE capacity-factor expert execution"); }1234567891011# Expert weighted aggregation with shared expert (L2 013)
MoE layer with given routing (expert ids and weights): each token's experts run a SwiGLU MLP, the outputs are summed with the routing weights, and a shared expert scaled by a sigmoid gate is added.
- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 4 (5,192 lines).- Idea: Routing groups tokens by expert; one persistent 2-CTA tcgen05 swap-AB grouped GEMM does gate/up + SwiGLU, then down + atomic weighted adds; shared expert as an extra expert.- Result: SOL score 0.945; speedup 3.59x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11.- Origin: search agent (Claude).- Comments edited; unused test helpers removed; the code that runs is identical to the scored submission.- Re-checked on a B200 after the edit: it builds and passes every workload of the SOL-ExecBench correctness check.- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164{ "board": "L2", "id": "013_expert_weighted_aggregation_with_shared_expert", "name": "Expert weighted aggregation with shared expert", "language": "CUDA C++", "files": [ { "path": "src/fused_body.cuh", "lines": 2801, "bytes": 159817 }, { "path": "src/kernel.cu", "lines": 1678, "bytes": 70791 }, { "path": "src/main.cpp", "lines": 6, "bytes": 603 }, { "path": "src/route_body.cuh", "lines": 707, "bytes": 37089 } ], "origin": "search agent (Claude)", "result": { "public": true, "sol_score": 0.944881, "speedup": 3.5869, "board_row": true, "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" }, "idea": "Routing groups tokens by expert; one persistent 2-CTA tcgen05 swap-AB grouped GEMM does gate/up + SwiGLU, then down + atomic weighted adds; shared expert as an extra expert.", "spec": { "languages": [ "cuda_cpp" ], "target_hardware": [ "B200", "LOCAL" ], "entry_point": "main.cpp::run", "binding": "torch", "destination_passing_style": false, "dependencies": [], "compile_options": { "cuda_cflags": [ "-std=c++17", "-O3", "-gencode=arch=compute_100a,code=sm_100a", "-DWIN=1", "-DRGMAX=10", "-DPERSIST_MB=60", "-DLAGRS=520", "-DRSEM=1", "-DGUO=2", "-DTAILP=1", "-DDIEB=1", "-DDWMAX=296", "-DLAGPM=9665", "-DDACT=0", "-DSPD=56", "-DRING=1", "-DDNEPI=0", "-DSDI=0", "-DNPF=12", "-DNPFS=10", "-DCHSM=128", "-DSPLITS=1", "-DSHSF=40", "-DARRS=1", "-DARRD=1", "-DNLWS=1", "-DERING=4", "-DGXP=1", "-DCHB=192", "-DCHSB=192", "-DSHSPL=20", "-DNLWB=4", "-DWRP=3", "-DWRPB=2", "-DSHSPB=25", "-DMMAS=1000000", "-DFPF=8", "-DPFX=0", "-DMWWB=1", "-DMWWS=1", "-DRPB=2", "-DTWWS=1", "-DTWWB=1", "-DWSS=5", "-DCPNIB=1", "-DSTEALB=1", "-DSPDDIV=102", "-DSPDMAX=80", "-DHRSS=64", "-DFPFL=4", "-DMFWHB=0", "-DTAILPB=10", "-DSPFL=1", "-DCFSTB=1", "-DXRL=1", "-DHLL=1", "-DSHSPBD=10", "-DSGFU=2", "-DSDEND=0", "-DSRPS=1", "-DRFL=0", "-DSRF=1", "-DWINMB=50", "-DSPDBP=34", "-DSPLITB=1", "-DWSB=4", "-DTSBG=8", "-DCPPF=128", "-DSMR_LO=40", "-DSMR_HI=128", "-DETSB=1", "-DKRNS=16", "-DKRMS=5", "-DKRNB=16", "-DKRMB=5", "-DKRSHS=0", "-DCROS=1", "-DSHSFL=80", "-DERLS=1", "-DERLGS=1", "-DHDTL=400", "-DLCLB=1", "-DEXA=1", "-DLCGS=12", "-DLCGB=16", "-DDNSMS=1", "-DTSS=6", "-DRINGS=2", "-DRINGB=1", "-DH64B=0", "-DG4VS=1", "-DHDR=1", "-DWHEBB=1", "-DLKRSS=1", "-DRDOS=1", "-DGRDOS=1", "-DXPG=3", "-DSFSPB=1", "-DEPCS=1", "-DRSV4S=1", "-DMFWHS=2000", "-DLKSPS=0", "-DSFSPS=0" ], "ld_flags": [] }, "sources": [ "main.cpp", "kernel.cu", "fused_body.cuh", "route_body.cuh" ] }}1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678// MoE expert aggregation + gated shared expert on B200 (sm_100a), tcgen05 "swap-AB" grouped GEMM.// ZS+GUPERM: both epilogues are shuffle-free: GU via the GUPERM row-permuted Wg/Wu boxes, DOWN via the 5D Wd box// {64,8,4,4,2} (tcgen05.ld.16x256b.x2 -> 8 contiguous hidden cols per thread -> direct red.v8, see make_map_dn).//// 2-SM PAIR VERSION: the fused kernel runs as CTA PAIRS (2-CTA clusters, tcgen05 cta_group::2 everywhere).// The leader CTA issues M=256 x N=Nm MMAs: A = 128 weight rows from EACH CTA's smem (gate/up: rows j0+128*rank of// Wg/Wu; down: rows r0+256*rank (+128) of Wd), B = the chunk's tokens SPLIT along N (CTA r holds token rows// r*Nm/2 .. +Nm/2), so each SM reads half the token operand per MMA and the pair issues half the MMAs per SM.// Both CTAs' TMA (cta_group::2) / loader arrivals land on the leader's full barriers, MMA commits are multicast// to both CTAs, the leader's scheduler publishes every (pair) item into both CTAs' rings via DSMEM, each CTA// runs the epilogue of its own 128 accumulator rows. Scheduling (spatial split, early head, ...) is per pair.//// The op is weight-bandwidth bound (3.2 GB of expert weights, every expert active), so each weight// tile is streamed from DRAM exactly once. WEIGHTS are the MMA M operand (128 rows per MMA) and the// expert's gathered TOKENS are the MMA N operand (up to CH=192 tokens per chunk):// gate/up : D_g[128 j, N tok] = Wg[e][j0:j0+128, :] . X[tok, :]^T (K = 2048)// D_u[128 j, N tok] = Wu[e][j0:j0+128, :] . X[tok, :]^T// -> SwiGLU epilogue -> H[pair, 512] (bf16, rows sorted by expert)// down : D0/D1[128 n, N tok] = Wd[e][n0(+128):+128, :] . H[pair, :]^T (K = 512, 256-row tile/item)// -> * routing weight -> bf16 vector atomic add (red.v4.bf16x2) into output[token, 2048]// Down epilogue: TMEM (lane = hidden col, column = token) is read 32x32b.x16, rounded to// bf16, then transposed in registers with a 3-stage warp-shuffle butterfly so that each// thread owns 8 CONTIGUOUS hidden columns of 2 tokens -> routing weight applied in fp32// -> two 16-byte vector stores per thread per 16-token block (instead of 16 2-byte stores).//// Pipeline stage = 2 weight tiles (2 x 128 rows x 64 K = 32 KB, TMA, SWIZZLE_128B, L2 evict_first; down items load// both tiles with ONE 256-row box: Wd/Sd tensor maps use box 64 x 256)// + token tile (192 rows x 64 K = 24 KB; MODE0 cp.async X row gather, MODE1 TMA of H in 32-row boxes).// 4 stages = 224 KB smem.// H is row-major [P, 512] with each expert's pairs contiguous, so the down kernel's token operand is a// plain 2D box of H, TMA-loaded (SWIZZLE_128B, evict_last) by a single producer thread.// Gate/up epilogue: tcgen05.ld x16, SwiGLU via silu = h + h*tanh(h), h=g/2 (packed tanh.approx.bf16x2 + fma.rn.bf16x2, 0.5 MUFU/elem), butterfly transpose -> 16-byte H stores// (st.global.L2::cache_hint evict_last so H stays L2-resident until the down items TMA-read it).//// Kernels (2 launches, no memset: persistent self-resetting counters, chained with Programmatic Dependent Launch). gate/up and down now run in ONE// persistent kernel (moe_fused_kernel) with one dynamic item queue: all gate/up items, then all down items;// per-chunk H-ready counters (release/acquire) order a down item's H loads after its chunk's gate/up epilogues.// Route-independent head: the shared-expert gate/up items (chunks 0..ntS-1) are statically split over// CTAs and run entirely BEFORE griddepcontrol.wait, hiding route_kernel; only routed items wait on it.// Historical structure notes follow:// 1. route_kernel : clusters of 8 CTAs, NO software grid barrier. Cluster 0 routes (smem histogram/rank,// DSMEM-distributed counts + hardware barrier.cluster, redundant scan, rank 0 publishes// offsets + LPT chunk list, scatter); the other clusters zero the output and compute the// shared gate sigmoid(x.w) in parallel.// 2. moe_gemm_kernel<0> (gate/up) and <1> (down): PERSISTENT warp-specialized kernels// (scheduler warp / 4 loader warps / single-thread MMA issuer / 8 epilogue warps) with a DYNAMIC// atomic-counter tile scheduler and double-buffered TMEM accumulators.// PDL early prefetch: down's producer issues Wd TMA into all stages BEFORE griddepcontrol.wait (only// H tile loads wait on gate/up); gate/up L2-prefetches the route-independent shared-expert weights// before waiting on route_kernel.// 3. no combine kernel: route_kernel zeroes output, the down epilogue reduces into it directly.// TWW: converged-warp + elect.sync issue for the weight-TMA producer warp and the loader's// single-lane TMA token paths (shared X, H): all 32 lanes run the ring bookkeeping / empty waits, one elected lane// issues expect_tx + cp.async.bulk.tensor. Shipped -DTWWS=1 -DTWWB=1.// SMALL-T RE-TUNE after MWW/TWW issuer diets: ctl.4640/.4642/.4640 |// WSS5 TSS6 .4626/.4629 (shipped) | WSS5 TSS7 .4626/.4629 | WSS5 TSS8 .4629 | CHSM192 WSS5 .4637 | SPD40 .4639 |// SPD72 .4690 | f63 band at T=3296 (BIGT=3000) .4798. CH 96/160 invalid (BH % 32). -> -DWSS=5 -DTSS=6.// (3) 64-row shared-X boxes | (4) hoisted leader kfull mapa per item | (5) lane-0-only kempty poll + __syncwarp |// (6) dropping the per-item barrier.sync re-convergence (NLT = 32) | (7) H-path n8 tail as one 16/24-row box |// (5) split pair_pos overflow loop by expert range | (6) worker XPG3 prefetch issued before the zero-fill of the previous block |#include <torch/extension.h>#include <cuda_bf16.h>#include <cuda_runtime.h>#include <cuda.h>#include <ATen/cuda/CUDAContext.h>#include <c10/cuda/CUDAGuard.h>#include <ATen/cuda/EmptyTensor.h>#include <cub/cub.cuh>#include <vector>#include <algorithm>
#define HID 2048#define INTER 512#define NE 512#define NE1 513#define TOPK 10#ifndef CHB#define CHB 192 // max tokens per routed chunk (MMA N) of the large-T variant, multiple of 16, <= 256#endif#ifndef CHSM#define CHSM 192#endif#ifndef SPLITS#define SPLITS 0#endif#ifndef WSS#define WSS 5#endif#ifndef TSS#define TSS 4#endif#define CH CHSM // max tokens per routed chunk of the current instantiation (host sizing: min over variants)#ifndef CHS#define CHS 128 // shared-expert tokens per chunk (<= CH, multiple of 16; Nm<=128 -> one TMEM slot)#endifstatic_assert(CHS <= CH && CHS % 16 == 0, "CHS");#define BK 64 // K per stage (one 128B swizzle atom row)#define HBOX 32 // rows per TMA box of H in the down kernel
typedef __nv_bfloat16 bf16;
// ---------------- PDL helpers (griddepcontrol)__device__ __forceinline__ void pdl_wait() { asm volatile("griddepcontrol.wait;" ::: "memory"); }__device__ __forceinline__ void pdl_trigger() { asm volatile("griddepcontrol.launch_dependents;" ::: "memory"); }
// ---------------- thread-block-cluster helpers (hardware cluster barrier + DSMEM loads)__device__ __forceinline__ void cluster_arrive_release() { asm volatile("barrier.cluster.arrive.release.aligned;" ::: "memory"); }__device__ __forceinline__ void cluster_arrive_relaxed() { asm volatile("barrier.cluster.arrive.relaxed.aligned;" ::: "memory"); }__device__ __forceinline__ void cluster_wait_acquire() { asm volatile("barrier.cluster.wait.acquire.aligned;" ::: "memory"); }__device__ __forceinline__ uint32_t cluster_ctarank() { uint32_t r; asm volatile("mov.u32 %0, %%cluster_ctarank;" : "=r"(r)); return r; }__device__ __forceinline__ uint32_t cluster_id_x() { uint32_t r; asm volatile("mov.u32 %0, %%clusterid.x;" : "=r"(r)); return r; }// load a 32-bit value from the same smem offset in CTA `rank` of this cluster (DSMEM)__device__ __forceinline__ int ld_dsmem(const int* p, uint32_t rank) { uint32_t a = (uint32_t)__cvta_generic_to_shared(p), ra; int v; asm volatile("mapa.shared::cluster.u32 %0, %1, %2;" : "=r"(ra) : "r"(a), "r"(rank)); asm volatile("ld.shared::cluster.s32 %0, [%1];" : "=r"(v) : "r"(ra) : "memory"); return v;}
// route_kernel: launched with clusters of RCL CTAs (grid = multiple of RCL), NO software grid barrier.// * cluster 0 (blockIdx 0..RCL-1) = ROUTING. CTA rank r owns a contiguous 1/RCL slice of the T*TOPK// (token,k) pairs:// phase 1: coalesced sel loads, block-local smem histogram whose atomicAdd return value is the pair's// rank within (CTA, expert) (stashed in pair_pos).// hardware cluster barrier (barrier.cluster arrive.release / wait.acquire)// phase 2: thread e reads lc[e] of all RCL CTAs through DSMEM -> total count of expert e and this// CTA's base slot (sum over lower ranks) -- replaces the global atomics + grid barrier.// Every CTA scans the 512 counts redundantly (cub BlockScan); rank 0 publishes counts,// offsets and the LPT chunk list (16-token size buckets, descending).// phase 3: scatter: pos = offset[e] + base[e] + rank -> pair_token / pair_w.// A final cluster wait keeps every CTA's smem alive until all remote DSMEM reads are done.// * all other clusters (independent, no synchronization): zero the output (the down epilogue reduces// into it) and compute the shared-expert gate sigmoid(x . w) per token (warp per token), written into// the shared-expert pair slot T*TOPK + t.// The fused kernel's griddepcontrol.wait waits for this whole grid, so all results are visible there.#ifndef DIAGR#define DIAGR 0#endif__device__ unsigned long long* g_rd;#ifndef DIAGT#define DIAGT 0#endif#ifndef DNX#define DNX 1 // full-line output reductions (4D down-weight box, see the down epilogue)#endif#ifndef DIAGI#define DIAGI 0#endif#ifndef DIAG_EPI#define DIAG_EPI 0#endif#ifndef DIAG_NOEPI_DN#define DIAG_NOEPI_DN 0#endif#ifndef DIAG_NOMMA_DN#define DIAG_NOMMA_DN 0#endif#define DT_NB 700#ifndef DTCK#define DTCK 0 // DIAGT wait timers: 1 = SM clock64 cycles (fine-grained), 0 = globaltimer ns#endif#define CKT() (DTCK ? (unsigned long long)clock64() : rgt())#define DTA(k, t) do { if (DIAGT) _da[(k) & 7] += CKT() - (t); } while (0)__device__ unsigned long long* g_dt; // [0] t0 | [8 + 4*cta] entry, firstTMA, end, - | buckets (u32 KB) at +1024__device__ __forceinline__ unsigned long long rgt() { unsigned long long t; asm volatile("mov.u64 %0, %%globaltimer;" : "=l"(t)); return t; }// per-CTA phase-end marks (max over warps)#define RMARK(k) do { if (DIAGR && lane == 0) atomicMax(g_rd + blockIdx.x * 16 + (k), rgt()); } while (0)#ifndef RCP#define RCP 16 // routing pairs per thread kept in registers between histogram and scatter#endif#define RSTAGE_MAX (200 * 1024) // route_kernel dynamic smem cap (scatter stage)#ifndef R0LIST#define R0LIST 1 // routing-cluster rank 0 builds the chunk list only (no pair slice)#endif#define RT 512 // == NE: thread e owns expert e in the scan#define RCL 8 // routing cluster size (portable)#ifndef GUO#define GUO 0 // routed GU chunk order: 0 LPT, 1 mid-first first wave, 2 expert order + LPT tail#endif#ifndef FWC#define FWC 37 // GUO 1: first-wave chunks (x NT0 = 148 items)#endif#ifndef MIDP#define MIDP 50 // GUO 1: LPT-rank percentile of the first-wave centre#endif#ifndef TAILP#define TAILP 20 // GUO 2: percent of routed chunks (smallest) kept in LPT order at the end#endif#ifndef DIAGS#define DIAGS 0#endif#if DIAGS__device__ int g_tailp = TAILP;__device__ int g_lagr = 96;#define TAILPV g_tailp#else#define TAILPV TAILP#endif// Per-T feature selection from the sustained-mode audit of the top-5 archive nodes (see moe_fused_kernel):// T < AUDBIG: DNEPI ext down epilogue on, shared-down interleave SDI on, 32-row H boxes (= node 9f73)// T >= AUDBIG: DNEPI off, SDI off, 64-row H boxes (H64) (= node 9507)// RP = output-red L2 policy code (3 = no hint). DIAGS builds override each knob at runtime (-1 = per-T rule).#ifndef AUDBIG#define AUDBIG 6144#endif#if DIAGS__device__ int g_dnepi = -1, g_sdi = -1, g_h64 = -1, g_rp = 3;#define KNOB(gv, autov) ((gv) >= 0 ? (gv) : (autov))#define RPV g_rp#else#define KNOB(gv, autov) (autov)#define RPV RP#endif#ifndef NPF#define NPF 16 // # experts whose first chunk heads the routed list (their Wg/Wu are L2-prefetched pre-PDL-wait)#endif#ifndef NPFS#define NPFS 12#endif#ifndef NPFB#define NPFB 8#endif#ifndef CHSS#define CHSS 128#endif#ifndef CHSB#define CHSB 192#endifstatic_assert(NPFS >= NPFB && CHSS <= CHSB && CHSB <= CHB && CHSS <= CHSM && CHSM <= CHB && CHSB % 16 == 0, "per-T NPF/CHS config");#ifndef SHSFL#define SHSFL 100 // static shared gate/up fraction (% of pairs, in items) for T >= SHTMAX (100 = all static)#endif#ifndef DIAGQ#define DIAGQ 0#endif#ifndef DIAGG#define DIAGG 0#endif#ifndef DIAGCK#define DIAGCK 0#endif#ifndef DIAGC#define DIAGC 0#endif#ifndef DIAGCV#define DIAGCV 7#endif#ifndef DIAGF#define DIAGF 0#endif#ifndef DIAGK#define DIAGK 0 // per-pair timeline (diag build only, see the DIAGK driver)#endif#ifndef DNSMS#define DNSMS 0#endif#ifndef DIAGP#define DIAGP 0#endif__device__ int g_dnsm = DNSMS; // DIAGP runtime A/B of the DNSM placement mode#define DNSMV (DIAGP ? g_dnsm : DNSMS)#ifndef DPTH#define DPTH 60#endif__device__ unsigned long long g_pkt0 = ~0ull; // DIAGP: first fused CTA entry (globaltimer ns)__device__ int g_krole[128]; // DIAGK: scheduler role (dn_s)__device__ unsigned long long g_pk[32 * 128]; // DIAGK: per pair [role, entry, first item, exit, #GU, #DN, cyc next_item, tempty, wfull, lastGU, lastDN, firstDN, item cyc, whalf, #sharedGU, cyc/ns<<32]__device__ int g_abl = 0; // DIAGC ablation bits: 1 no X gather, 2 no H store/load, 4 no reds, 8 no epilogue math, 16 suspend MMA full wait__device__ unsigned long long g_dc[4]; // DIAGC: sum clock64 cycles, sum ns, # CTAs__device__ int g_erlg = 0, g_gu32 = 0;#ifndef DIAGV#define DIAGV 0#endif#ifndef CHB2#define CHB2 256#endif#ifndef NPFB2#define NPFB2 8#endif#ifndef CHSB2#define CHSB2 CHSB // DIAGV variant 2: shared-expert chunk size#endif#ifndef DIAGX#define DIAGX 0#endif// LARGE-T BOUNDED GU->DN LAG (DNH chunks, 0 = off), see fused_body.cuh; DIAGV builds make it a runtime knob#ifndef DNH#define DNH 0#endif__device__ int g_dnh = DNH;__device__ int g_shtok = 1 << 30;#define SHT(T) (DIAGX ? min((T), g_shtok) : (T))#ifndef SHSF#define SHSF 50 // % of the grid (in items) run as static pre-route shared gate/up items (100 = all)#endif#ifndef SHSP#define SHSP 10 // % of the routed gate/up queue over which the dynamic shared chunks are spread#endif#ifndef SHTMAX#define SHTMAX 6144 // the SHSF cap applies only for T < SHTMAX#endif#if DIAGX__device__ int g_shsf = SHSF, g_shsp = SHSP;#define SHSFV g_shsf#define SHSPV g_shsp#else#define SHSFV SHSF#define SHSPV SHSP#endif// LARGE-T SHARED/ROUTED INTERLEAVE (T >= SHTMAX): % of the routed gate/up queue over which the dynamic// (non-static) shared-expert N=256 chunks are spread (one shared chunk every b routed chunks), so the// L2-resident, MMA-heavy shared tiles are mixed into the DRAM-streaming routed items instead of bunched.#ifndef SHSPL#define SHSPL 40#endif#if DIAGV__device__ int g_shsfl = SHSFL;__device__ int g_shspl = SHSPL;#define SHSFLV g_shsfl#define SHSPLV g_shspl#else#define SHSFLV SHSFL#define SHSPLV SHSPL#endif// PRE-ROUTE SHARED DOWN (ZROW): route workers zero the output rows of each 32-token gate block right// before its gate and publish per-shared-chunk readiness (zfl = early + ZOFF, token counts); the fused// kernel then runs the down items of the static (pre-route) shared chunks as static items too, before// griddepcontrol.wait, filling the pre-route window of CTAs without static gate/up work.#ifndef ZROW#define ZROW 1#endif#ifndef SDN#define SDN 0#endif#ifndef SDNC#define SDNC 4 // max # shared chunks whose down items run as static pre-route items#endif#ifndef ZPUB#define ZPUB SDN#endif#define ZOFF 64 // zfl offset inside the early[] block (>= max EARLYN)static_assert(CHSS % 32 == 0 && CHSB % 32 == 0, "ZROW: gate blocks of 32 tokens must lie in one shared chunk");#undef NPF#undef CHS#define NPF NPFS#define CHS CHSS#ifndef GUOB#define GUOB GUO#endif#ifndef TAILPB#define TAILPB TAILP#endif// SHSTB (large-T variant, ported from 71715078): shared-expert down items STORE the output (route rb skips the// output zero-fill: RNOZ), routed down reds wait for them. STEALB / SHDN (SHSFL >= 200): large-T scheduler knobs.#ifndef SHSTB#define SHSTB 0#endif#ifndef STEALB#define STEALB 0#endif#ifndef XPG#define XPG 0 // route X evict_last prefetch granule: 0 per 128 B line, 1 per 256 B, 2 bulk per 4 KB row#endif#ifndef XPGS#define XPGS 131072 // XPG 3/4: bytes per bulk X L2 prefetch (multiple of 16)#endif#ifndef XPGP#define XPGP 1 // XPG 3/4 X prefetch policy: 1 evict_last, 0 no hint (evict_normal)#endif// bulk L2 prefetch of sz bytes of X (16 B aligned/multiple), policy XPGP__device__ __forceinline__ void xpf_bulk(const void* p, uint32_t sz) { if (XPGP) { uint64_t pxl; asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pxl)); asm volatile("cp.async.bulk.prefetch.L2.global.L2::cache_hint [%0], %1, %2;" ::"l"(p), "r"(sz), "l"(pxl) : "memory"); } else { asm volatile("cp.async.bulk.prefetch.L2.global [%0], %1;" ::"l"(p), "r"(sz) : "memory"); }}#ifndef XRL#define XRL 0 // small-T route gate GEMV loads X with an L2 evict_last hint (see route_body.cuh)#endif#ifndef SGFS#define SGFS 1 // small T: shared gate computed by the fused kernel's shared GU epilogue (route skips the GEMV)#endif#ifndef SGFB#define SGFB 0#endif#define RSGF SGFS#ifndef RDISTB#define RDISTB 1 // large-T route: distributed routing (see route_body.cuh RDIST)#endif#define RDIST 0#define GUOR GUO#define TAILPR TAILPV#define RNOZ 0#ifndef EPCS#define EPCS 0 // small-T early-head publish via per-CTA release counter (route_body EPC)#endif#ifndef RSV4S#define RSV4S 0 // small-T route counter reset with 16 B stores (route_body RSV4)#endif#define EPC EPCS#define RSV4 RSV4Snamespace rs {#include "route_body.cuh"}#undef EPC#undef RSV4#define EPC 0 // large-T route: unchanged#define RSV4 0#undef NPF#undef CHS#define NPF NPFB#define CHS CHSB#undef CH#define CH CHB#undef GUOR#undef TAILPR#undef RNOZ#define GUOR GUOB#define TAILPR TAILPB#define RNOZ SHSTB#undef RSGF#define RSGF SGFB#undef RDIST#define RDIST RDISTB#ifndef MCADB#define MCADB 1 // large-T route: multi-chunk experts' chunks adjacent in the address-ordered queue (MCAD)#endif#undef MCADR#define MCADR MCADBnamespace rb {#include "route_body.cuh"}#undef MCADR#define MCADR 0#undef GUOR#undef TAILPR#undef RNOZ#define GUOR GUO#define TAILPR TAILPV#define RNOZ 0#undef RDIST#define RDIST 0#if DIAGV#undef NPF#undef CH#undef CHS#define NPF NPFB2#define CH CHB2#define CHS CHSB2namespace rb2 {#include "route_body.cuh"}#define RB2 rb2::route_kernel#else#define RB2 rs::route_kernel#endif#undef NPF#undef CHS#undef CH#define NPF NPFS#define CHS CHSS#define CH CHSM
// ---------------- PTX helpers__device__ __forceinline__ uint32_t smem_u32(const void* p) { return (uint32_t)__cvta_generic_to_shared(p); }// CPPF: L2 prefetch-size hint on the cp.async X gather (large-T variant only: the small-T variant gathers X with TMA// gather4). 0 = none, 128 / 256 = .L2::128B / .L2::256B (the next K-steps' bytes of the same 4 KB X row enter L2 early).#ifndef CPPF#define CPPF 0#endif#if CPPF == 256#define CPPFS ".L2::256B"#elif CPPF == 128#define CPPFS ".L2::128B"#else#define CPPFS ""#endif__device__ __forceinline__ void cp_async16(uint32_t dst, const void* src) { asm volatile("cp.async.cg.shared.global" CPPFS " [%0], [%1], 16;" ::"r"(dst), "l"(src) : "memory");}// cp.async 16B with an L2 cache-policy hint (X rows: evict_last, re-gathered by every gate/up tile)__device__ __forceinline__ void cp_async16_hint(uint32_t dst, const void* src, uint64_t pol) { asm volatile("cp.async.cg.shared.global.L2::cache_hint [%0], [%1], 16, %2;" ::"r"(dst), "l"(src), "l"(pol) : "memory");}__device__ __forceinline__ void cp_commit() { asm volatile("cp.async.commit_group;" ::: "memory"); }template <int N> __device__ __forceinline__ void cp_wait() { asm volatile("cp.async.wait_group %0;" ::"n"(N) : "memory"); }__device__ __forceinline__ void fence_proxy_async() { asm volatile("fence.proxy.async.shared::cta;" ::: "memory"); }__device__ __forceinline__ void mbar_init(uint32_t bar, uint32_t cnt) { asm volatile("mbarrier.init.shared::cta.b64 [%0], %1;" ::"r"(bar), "r"(cnt) : "memory");}// POWER PASS (MMAS): the MMA issuer's weight / token full-barrier waits (the only hot spin loops left) use// try_wait with an explicit suspend-time hint (MMAS ns, 0 = plain try_wait spin): the thread sleeps in// hardware until the phase completes instead of re-issuing try_wait -> fewer issue slots / less power.#ifndef MMAS#define MMAS 0#endif// MMA-issuer full-barrier wait with a per-variant compile-time suspend hint H (0 = plain try_wait spin: the// small-T variant's issuer is on the critical path, so it polls without a suspend hint and issues immediately)template <int H> __device__ __forceinline__ void mbar_wait_h(uint32_t bar, uint32_t parity) { uint32_t ok; do { if (H > 0) asm volatile("{\n.reg .pred p;\nmbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2, %3;\nselp.u32 %0, 1, 0, p;\n}\n" : "=r"(ok) : "r"(bar), "r"(parity), "n"(H > 0 ? H : 1) : "memory"); else asm volatile("{\n.reg .pred p;\nmbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2;\nselp.u32 %0, 1, 0, p;\n}\n" : "=r"(ok) : "r"(bar), "r"(parity) : "memory"); } while (!ok);}__device__ __forceinline__ void mbar_wait(uint32_t bar, uint32_t parity) { uint32_t ok; do {#if MMAS > 0 asm volatile("{\n.reg .pred p;\nmbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2, %3;\nselp.u32 %0, 1, 0, p;\n}\n" : "=r"(ok) : "r"(bar), "r"(parity), "n"(MMAS) : "memory");#else asm volatile("{\n.reg .pred p;\nmbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2;\nselp.u32 %0, 1, 0, p;\n}\n" : "=r"(ok) : "r"(bar), "r"(parity) : "memory");#endif } while (!ok);}// Low-power wait for long, non-critical waits (epilogue accumulator, scheduler ring, loader ring):// try_wait with an explicit suspend-time hint so the warp sleeps in hardware until the phase completes// (or the hint expires) instead of re-issuing try_wait in a tight loop -> lower issue power / clock droop.__device__ __forceinline__ void mbar_wait_sleep(uint32_t bar, uint32_t parity) { uint32_t ok; do { asm volatile("{\n.reg .pred p;\nmbarrier.try_wait.parity.shared::cta.b64 p, [%1], %2, %3;\nselp.u32 %0, 1, 0, p;\n}\n" : "=r"(ok) : "r"(bar), "r"(parity), "r"(1000000u) : "memory"); } while (!ok);}__device__ __forceinline__ void mbar_arrive_expect_tx(uint32_t bar, uint32_t bytes) { asm volatile("mbarrier.arrive.expect_tx.release.cta.shared::cta.b64 _, [%0], %1;" ::"r"(bar), "r"(bytes) : "memory");}// L2 evict_first: weights are streamed exactly once__device__ __forceinline__ uint64_t policy_evict_first() { uint64_t p; asm volatile("createpolicy.fractional.L2::evict_first.b64 %0, 1.0;" : "=l"(p)); return p;}// L2 evict_last: H tiles are re-read by all NT weight tiles of a chunk__device__ __forceinline__ uint64_t policy_evict_last() { uint64_t p; asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(p)); return p;}__device__ __forceinline__ uint64_t policy_evict_normal() { uint64_t p; asm volatile("createpolicy.fractional.L2::evict_normal.b64 %0, 1.0;" : "=l"(p)); return p;}#ifndef HLD#define HLD 2#endif#ifndef HST#define HST 1#endif__device__ __forceinline__ uint64_t policy_sel(int m) { return m == 1 ? policy_evict_last() : (m == 2 ? policy_evict_first() : policy_evict_normal());}// TMA 2D tile load (SWIZZLE_128B) -> smem, completes tx bytes on mbarrier__device__ __forceinline__ void tma_load_2d(uint32_t dst, const CUtensorMap* map, int c0, int c1, uint32_t bar, uint64_t pol) { asm volatile( "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3}], [%4], %5;" ::"r"(dst), "l"(reinterpret_cast<uint64_t>(map)), "r"(c0), "r"(c1), "r"(bar), "l"(pol) : "memory");}#ifndef WRP#define WRP 2#endif#ifndef WSP#define WSP 1 // shared-expert weights (re-read by every shared chunk): evict_last#endif#ifndef XP#define XP 3#endif#ifndef RP#define RP 3 // output red.add: no hint (output already covered by the persisting window)#endif__device__ __forceinline__ uint64_t policy_code(int m) { return m == 3 ? 0ull : policy_sel(m); }__device__ __forceinline__ void tma_load_2d_nh(uint32_t dst, const CUtensorMap* map, int c0, int c1, uint32_t bar) { asm volatile( "cp.async.bulk.tensor.2d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3}], [%4];" ::"r"(dst), "l"(reinterpret_cast<uint64_t>(map)), "r"(c0), "r"(c1), "r"(bar) : "memory");}// 4D TMA tile load (down weights, DNX layout): coords {k, 0, row/64, 0}__device__ __forceinline__ void tma_load_4d_p(uint32_t dst, const CUtensorMap* map, int c0, int c2, uint32_t bar, uint64_t pol, int m) { if (m == 3) asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3, %4, %5}], [%6];" ::"r"(dst), "l"(reinterpret_cast<uint64_t>(map)), "r"(c0), "r"(0), "r"(c2), "r"(0), "r"(bar) : "memory"); else asm volatile("cp.async.bulk.tensor.4d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4, %5}], [%6], %7;" ::"r"(dst), "l"(reinterpret_cast<uint64_t>(map)), "r"(c0), "r"(0), "r"(c2), "r"(0), "r"(bar), "l"(pol) : "memory");}// 3D TMA tile load (fused gate+up weight box): coords {k, row, 0}; the 3rd dim (size 2) spans the// [lower-address | higher-address] pair of the gate/up weight tensors (stride = pointer difference)__device__ __forceinline__ void tma_load_3d_p(uint32_t dst, const CUtensorMap* map, int c0, int c1, uint32_t bar, uint64_t pol, int m) { if (m == 3) asm volatile("cp.async.bulk.tensor.3d.shared::cluster.global.mbarrier::complete_tx::bytes [%0], [%1, {%2, %3, %4}], [%5];" ::"r"(dst), "l"(reinterpret_cast<uint64_t>(map)), "r"(c0), "r"(c1), "r"(0), "r"(bar) : "memory"); else asm volatile("cp.async.bulk.tensor.3d.shared::cluster.global.mbarrier::complete_tx::bytes.L2::cache_hint [%0], [%1, {%2, %3, %4}], [%5], %6;" ::"r"(dst), "l"(reinterpret_cast<uint64_t>(map)), "r"(c0), "r"(c1), "r"(0), "r"(bar), "l"(pol) : "memory");}// TMA load with policy code m (3 = no hint)__device__ __forceinline__ void tma_load_p(uint32_t dst, const CUtensorMap* map, int c0, int c1, uint32_t bar, uint64_t pol, int m) { if (m == 3) tma_load_2d_nh(dst, map, c0, c1, bar); else tma_load_2d(dst, map, c0, c1, bar, pol);}__device__ __forceinline__ void tc_fence_before() { asm volatile("tcgen05.fence::before_thread_sync;" ::: "memory"); }__device__ __forceinline__ void tc_fence_after() { asm volatile("tcgen05.fence::after_thread_sync;" ::: "memory"); }// UMMA smem descriptor: K-major, SWIZZLE_128B, 8-row atoms of 1024B (SBO=1024), version 1.__device__ __forceinline__ uint64_t make_desc(uint32_t addr) { uint64_t d = 0; d |= (uint64_t)((addr & 0x3FFFF) >> 4); d |= (uint64_t)1 << 16; d |= (uint64_t)(1024 >> 4) << 32; d |= (uint64_t)1 << 46; d |= (uint64_t)2 << 61; return d;}// instruction descriptor: D=f32, A=B=bf16, both K-major, M=128, N=n__device__ __forceinline__ uint32_t make_idesc(int n) { return (1u << 4) | (1u << 7) | (1u << 10) | ((uint32_t)(n >> 3) << 17) | ((uint32_t)(128 >> 4) << 24);}__device__ __forceinline__ void mma_bf16(uint32_t dtmem, uint64_t a, uint64_t b, uint32_t idesc, uint32_t accum) { asm volatile("{\n.reg .pred p;\nsetp.ne.b32 p, %4, 0;\ntcgen05.mma.cta_group::1.kind::f16 [%0], %1, %2, %3, p;\n}\n" ::"r"(dtmem), "l"(a), "l"(b), "r"(idesc), "r"(accum) : "memory");}__device__ __forceinline__ void mma_commit(uint32_t bar) { asm volatile("tcgen05.commit.cta_group::1.mbarrier::arrive::one.shared::cluster.b64 [%0];" ::"r"(bar) : "memory");}// 32 lanes x 16 columns fp32; caller must tmem_wait()__device__ __forceinline__ void tmem_ld16(uint32_t taddr, uint32_t* r) { asm volatile( "tcgen05.ld.sync.aligned.32x32b.x16.b32 {%0,%1,%2,%3,%4,%5,%6,%7,%8,%9,%10,%11,%12,%13,%14,%15}, [%16];" : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]), "=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]), "=r"(r[14]), "=r"(r[15]) : "r"(taddr));}// 32 lanes x 32 columns fp32; caller must tmem_wait()__device__ __forceinline__ void tmem_ld32(uint32_t taddr, uint32_t* r) { asm volatile( "tcgen05.ld.sync.aligned.32x32b.x32.b32 {%0,%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];" : "=r"(r[0]), "=r"(r[1]), "=r"(r[2]), "=r"(r[3]), "=r"(r[4]), "=r"(r[5]), "=r"(r[6]), "=r"(r[7]), "=r"(r[8]), "=r"(r[9]), "=r"(r[10]), "=r"(r[11]), "=r"(r[12]), "=r"(r[13]), "=r"(r[14]), "=r"(r[15]), "=r"(r[16]), "=r"(r[17]), "=r"(r[18]), "=r"(r[19]), "=r"(r[20]), "=r"(r[21]), "=r"(r[22]), "=r"(r[23]), "=r"(r[24]), "=r"(r[25]), "=r"(r[26]), "=r"(r[27]), "=r"(r[28]), "=r"(r[29]), "=r"(r[30]), "=r"(r[31]) : "r"(taddr));}__device__ __forceinline__ void tmem_wait() { asm volatile("tcgen05.wait::ld.sync.aligned;" ::: "memory"); }// cta_group::2 allocation (fused kernel runs as CTA pairs): one warp in EACH CTA of the pair allocatestemplate <int NCOLS> __device__ __forceinline__ void tmem_alloc(uint32_t dst_smem) { asm volatile("tcgen05.alloc.cta_group::2.sync.aligned.shared::cta.b32 [%0], %1;" ::"r"(dst_smem), "n"(NCOLS) : "memory"); asm volatile("tcgen05.relinquish_alloc_permit.cta_group::2.sync.aligned;" ::: "memory");}template <int NCOLS> __device__ __forceinline__ void tmem_dealloc(uint32_t taddr) { asm volatile("tcgen05.dealloc.cta_group::2.sync.aligned.b32 %0, %1;" ::"r"(taddr), "n"(NCOLS) : "memory");}// packed fp32x2 -> bf16x2 round-to-nearest: low half = lo, high half = hi__device__ __forceinline__ uint32_t cvt_bf16x2(float lo, float hi) { uint32_t r; asm("cvt.rn.bf16x2.f32 %0, %1, %2;" : "=r"(r) : "f"(hi), "f"(lo)); return r;}__device__ __forceinline__ uint32_t bmul2(uint32_t a, uint32_t b) { uint32_t r; asm("mul.rn.bf16x2 %0, %1, %2;" : "=r"(r) : "r"(a), "r"(b)); return r;}// exp(-x) via one ex2.approx.ftz (pre-scaled by -log2 e)__device__ __forceinline__ float expneg_approx(float x) { float r; asm("ex2.approx.ftz.f32 %0, %1;" : "=f"(r) : "f"(x * -1.4426950408889634f)); return r;}__device__ __forceinline__ float rcp_approx(float x) { float r; asm("rcp.approx.ftz.f32 %0, %1;" : "=f"(r) : "f"(x)); return r;}// fp32 tanh via one MUFU op (silu(g) = h + h*tanh(h), h = g/2)__device__ __forceinline__ float tanh_approx(float x) { float r; asm("tanh.approx.f32 %0, %1;" : "=f"(r) : "f"(x)); return r;}// packed bf16x2 silu from h = g/2: h + h*tanh(h) (tanh.approx.bf16x2 + fma.rn.bf16x2)__device__ __forceinline__ uint32_t silu_bf16x2(uint32_t h) { uint32_t t, r; asm("tanh.approx.bf16x2 %0, %1;" : "=r"(t) : "r"(h)); asm("fma.rn.bf16x2 %0, %1, %2, %3;" : "=r"(r) : "r"(h), "r"(t), "r"(h)); return r;}__device__ __forceinline__ float bf_lo(uint32_t p) { return __uint_as_float(p << 16); }__device__ __forceinline__ float bf_hi(uint32_t p) { return __uint_as_float(p & 0xffff0000u); }// byte offset of (row, 16B chunk) inside a 128B-swizzled K-major tile (rows of 128 bytes)__device__ __forceinline__ uint32_t swz(int row, int ch) { return (uint32_t)(row * 128 + ((ch ^ (row & 7)) << 4)); }
// pack two fp32 -> bf16x2 (lo in bits 0..15) and back__device__ __forceinline__ uint32_t pack_bf2(float lo, float hi) { __nv_bfloat162 h = __floats2bfloat162_rn(lo, hi); return *reinterpret_cast<uint32_t*>(&h);}__device__ __forceinline__ float2 unpack_bf2(uint32_t v) { return __bfloat1622float2(*reinterpret_cast<__nv_bfloat162*>(&v));}
// red semantic/scope qualifiers: RSEM 0 = .relaxed.gpu, 1 = none (PTX default), 2 = .relaxed.sys#ifndef RSEM#define RSEM 0#endif#if RSEM == 0#define RSEMS ".relaxed.gpu"#elif RSEM == 1#define RSEMS ""#else#define RSEMS ".relaxed.sys"#endif// 16-byte vector bf16x2 add-reduction to global (sm_90+): 8 bf16 lanes, no flush-to-zero__device__ __forceinline__ void red_add_v4bf16x2(bf16* addr, uint32_t a, uint32_t b, uint32_t c, uint32_t d, uint64_t pol, int m = RPV) { if (m != 3) { // L2 cache-hinted variant (RP = policy code): one v8.bf16 reduction carrying the policy asm volatile("{\n.reg .b16 h<8>;\n" "mov.b32 {h0, h1}, %1;\nmov.b32 {h2, h3}, %2;\nmov.b32 {h4, h5}, %3;\nmov.b32 {h6, h7}, %4;\n" "red" RSEMS ".global.add.L2::cache_hint.noftz.v8.bf16 [%0], {h0, h1, h2, h3, h4, h5, h6, h7}, %5;\n}\n" ::"l"(addr), "r"(a), "r"(b), "r"(c), "r"(d), "l"(pol) : "memory"); } else { // one 16-byte reduction of 8 contiguous bf16 hidden columns (.v8.bf16 form, lo half = lower address) asm volatile("{\n.reg .b16 h<8>;\n" "mov.b32 {h0, h1}, %1;\nmov.b32 {h2, h3}, %2;\nmov.b32 {h4, h5}, %3;\nmov.b32 {h6, h7}, %4;\n" "red" RSEMS ".global.add.noftz.v8.bf16 [%0], {h0, h1, h2, h3, h4, h5, h6, h7};\n}\n" ::"l"(addr), "r"(a), "r"(b), "r"(c), "r"(d) : "memory"); }}
// output write of 8 bf16: plain 16-byte store (SHST shared-expert down = first writer) or bf16 red.add__device__ __forceinline__ void out_v4(bf16* addr, uint32_t a, uint32_t b, uint32_t c, uint32_t d, uint64_t pol, int m, bool st) { if (st) asm volatile("st.global.v4.b32 [%0], {%1, %2, %3, %4};" ::"l"(addr), "r"(a), "r"(b), "r"(c), "r"(d) : "memory"); else red_add_v4bf16x2(addr, a, b, c, d, pol, m);}
// 32-bit global store with an L2 evict_last cache hint (H is re-read via TMA by the down items)__device__ __forceinline__ void st_evict_last_u32(bf16* addr, uint32_t v, uint64_t pol) { asm volatile("st.global.L2::cache_hint.b32 [%0], %1, %2;" ::"l"(addr), "r"(v), "l"(pol) : "memory");}
// 16-byte global store with an L2 evict_last cache hint__device__ __forceinline__ void st_evict_last_v4(bf16* addr, uint32_t a, uint32_t b, uint32_t c, uint32_t d, uint64_t pol) {#if HST != 3 asm volatile("st.global.L2::cache_hint.v4.b32 [%0], {%1, %2, %3, %4}, %5;" ::"l"(addr), "r"(a), "r"(b), "r"(c), "r"(d), "l"(pol) : "memory");#else asm volatile("st.global.v4.b32 [%0], {%1, %2, %3, %4};" ::"l"(addr), "r"(a), "r"(b), "r"(c), "r"(d) : "memory");#endif}
#ifndef DACT#define DACT 0#endif#ifndef DIAGW#define DIAGW 0#endif// (code diet: delayed-activation lag is the compile-time constant DACT, no runtime device knob)#ifndef DIAGE#define DIAGE 0#endif__device__ unsigned long long g_de[8 + 4 * 160]; // DIAGE: [0] t0 | per CTA [8+4b]: exit, role (1 GU, 2 DN), last GU item end, last DN item end__device__ unsigned long long g_dd[8]; // DIAGW: [0] t0 [1] dn H-wait [2] gu H-wait [3] dn end [4] gu end [5] switch t sum [6] #switch#define SPLIT SPLITS#if SPLITS#define WS WSS#define TS TSS#endif#ifndef NLWS#define NLWS 4 // small-T pair variant: X-gather loader warps#endif#ifndef EPGS#define EPGS 2 // small-T pair variant: epilogue groups of 4 warps#endif#ifndef XG4S#define XG4S 1#endif#ifndef XG4B#define XG4B 0#endif#define XG4 XG4S// ERL (early down-epilogue TMEM release, see fused_body.cuh): large-T variant only#ifndef ERLB#define ERLB 1#endif#ifndef ERLB2#define ERLB2 ERLB#endif#ifndef ERLS#define ERLS 0 // small-T variant: early down-epilogue TMEM release after the last tcgen05.ld (see fused_body.cuh ERL)#endif#define ERL ERLS// HT8: exact-size H tail boxes for down items (see fused_body.cuh); DIAGH builds make it a runtime knob#ifndef HT8#define HT8 1#endif#ifndef DIAGH#define DIAGH 0#endif#if DIAGH__device__ int g_ht8 = HT8;#define HT8V (g_ht8 != 0)#else#define HT8V (HT8 != 0)#endif#ifndef WRPB#define WRPB WRP#endif#ifndef WSPB#define WSPB WSP#endif__device__ int g_wrpb = -1, g_wspb = -1; // DIAGV runtime override (-1 = compile-time per-variant code)#define FWRP WRP#define FWSP WSP__device__ int g_rpb = -1; // DIAGV runtime override of the output red.add L2 policy code#ifndef RPB#define RPB RP#endif#define FRP RP#ifndef SMRS#define SMRS 0#endif#ifndef SMR_LOS#define SMR_LOS 56#endif#ifndef SMR_HIS#define SMR_HIS 152#endif#if SMRS#define SMR 1#define SMR_LO SMR_LOS#define SMR_LM SMR_LOS#define SMR_HI SMR_HIS#endif#ifndef MWWS#define MWWS 0 // whole-warp MMA issuer (see fused_body.cuh MWW), small-T variant#endif#define MWW MWWS#ifndef TWWS#define TWWS 0 // whole-warp weight-TMA producer / loader TMA token paths, small-T variant#endif#define TWW TWWS#ifndef MFWHS#define MFWHS 0 // small-T variant: MMA full-barrier wait = plain try_wait spin (no suspend hint)#endif#ifndef MFWHB#define MFWHB MMAS // large-T variant: unchanged (suspend-hinted try_wait)#endif#define MFWH MFWHS// HRS (per variant): loader H-ready poll back-off in ns (0 = tight acquire spin, wakes on the first poll after the// chunk's last GU epilogue release); small-T variant HRSS, large-T HRSB (64 = previous behaviour)#ifndef HRSS#define HRSS 64#endif#ifndef HRSB#define HRSB 64#endif#define HRS HRSS#define SGF SGFS#ifndef RFL#define RFL 0#endif#ifndef SRPS#define SRPS 0 // small-T static routed head items with pre-PDL weight-ring fill (see fused_body.cuh SRP)#endif#define SRP SRPS// SMALL-T SPIN PORT (TPESS / ETSS, f62): the large-T weight-producer empty wait spin (TPESB) and the epilogue// accumulator-full wait spin (ETSB) as separate small-T knobs (0 = suspend-hinted try_wait, previous behaviour).#ifndef TPESS#define TPESS 0#endif#ifndef ETSS#define ETSS 0#endif#define TPES TPESS#define ETS ETSS// KROT (small-T f62 only): gate/up K-block start rotation, KRNS starts x (32/KRNS) blocks, multiplier KRMS (see fused_body.cuh)#ifndef KRNS#define KRNS 0#endif#ifndef KRMS#define KRMS 1#endif#define KRN KRNS#define KRM KRMS#ifndef KRSHS#define KRSHS 1#endif#define KRSH KRSHS#ifndef CROS#define CROS 0#endif#define CRO CROS#ifndef ECAS#define ECAS 1 // small-T variant: early consumed atomic (see fused_body.cuh ECA)#endif#define ECA ECAS// ERLGS (small-T f62): early GU TMEM release -- the gate/up epilogue arrives on tempty right after the LAST block's// tcgen05.ld + wait::ld (gate+up of one 16-token block = 32 regs, already held), before its SwiGLU / H stores.#ifndef ERLGS#define ERLGS 0#endif#define ERLG ERLGS#ifndef GUF32S#define GUF32S 1 // small-T: fp32 single-rounding SwiGLU (fused_body GUF32)#endif#undef GUF32#define GUF32 GUF32S#ifndef LCLS#define LCLS 1 // small-T variant: late next-item claim (see fused_body.cuh LCL)#endif#define LCL LCLS// LCGS / LCGB: per-variant LCL claim-gate depth (K-steps before the TMA end of the last published item)#ifndef LCGS#define LCGS 8#endif#ifndef LCGB#define LCGB 8#endif#define LCG LCGS#ifndef HREAS#define HREAS 2 // small-T variant: early H-ready ld.acquire overlapping the first token-stage empty wait#endif#define HREA HREAS// PER-VARIANT SCHEDULER SLOT RING (RINGS small T / RINGB large T): producer-consumer slot-empty ring depth// (ERING data ring DR=4 unchanged). Small T: RINGS=2 (scheduler publishes up to 2 items ahead of the TMA/loader/MMA// consumers) together with the TSS 8->6 token-ring re-split; large T keeps RING (1).#ifndef RINGS#define RINGS 1#endif#ifndef RINGB#define RINGB 1#endif#undef RING#define RING RINGS// FRESH-EYES SMALL-T #5/#6 (f62 only): G4VS = gather4 row indices as one int4 load; FPFAS = FPF prediction from the real// pair arrival rank (1 = SR / static shared items, 2 = + guessed post-head dynamic routed item)#ifndef G4VS#define G4VS 0#endif#ifndef FPFAS#define FPFAS 0#endif#define G4V G4VS#define FPFA FPFAS// LKSPS / LKRSS (small-T f62 loader fresh-eyes knobs, see fused_body.cuh LKSP / LKRS); large T keeps 0#ifndef LKSPS#define LKSPS 0#endif#ifndef LKRSS#define LKRSS 0#endif#define LKSP LKSPS#define LKRS LKRSS#ifndef SFSPS#define SFSPS 0 // small-T: TMA / MMA warps spin on the scheduler slot-full barrier (see fused_body.cuh SFSP)#endif#define SFSP SFSPS#ifndef TLAS#define TLAS 0 // small-T: weight-TMA producer item-boundary lookahead (see fused_body.cuh TLA)#endif#define TLA TLAS#ifndef RDOS#define RDOS 0 // small-T down-epilogue red issue order (see fused_body.cuh RDO)#endif#ifndef GRDOS#define GRDOS 0 // small-T GU-epilogue H store issue order (see fused_body.cuh GRDO)#endif#define RDO RDOS#define GRDO GRDOS#undef EPC#define EPC EPCS// RS3 (small-T f62): per-variant epilogue data-ring depth ERINGS (DR) so the producer slot ring RINGS can be 3// (DR % RING == 0): the scheduler may publish up to RINGS claimed items ahead of the TMA/loader/MMA consumers.#ifndef ERINGS#define ERINGS 4#endif#ifndef ERINGB#define ERINGB 4#endif#undef ERING#define ERING ERINGS// GPF AUDIT (PTX memory model, proxy-preserved base causality order): a generic-proxy write W is ordered before an// async-proxy (TMA) read R iff a proxy fence lies ANYWHERE on the base-causality path W -> R. Path here: H st.global (W)// -> __syncwarp -> red.release.gpu ready[c] (writer) -> ld.acquire.gpu ready[c] (down H loader, every lane of the// converged loader warp) -> fence.proxy.async.global (same lane, program order) -> cp.async.bulk.tensor (R, issued by// that lane). The reader-side fence is on the path in BOTH variants (large T: acquire spin + fence; small T HREA=2:// early ld.acquire + fence at kt==0), so the per-thread writer-side fence is redundant -> legal to drop. GPFS (small T)// now follows GPFB=0: one reader fence per down item instead of 32 writer fences per GU warp per tile.#ifndef GPFS#define GPFS 0#endif#undef GPF#define GPF GPFSnamespace f62 {#define NLW NLWS#define EPG EPGS#include "fused_body.cuh"}#undef SPLIT#undef WS#undef TS#undef NLW#undef EPG#undef NPF#undef CHS#undef CH#define NPF NPFB#define CHS CHSB#define CH CHB#ifndef SPLITB#define SPLITB 0#endif#ifndef WSB#define WSB 5#endif#ifndef TSBG#define TSBG 4#endif#define SPLIT SPLITB#if SPLITB#define WS WSB#define TS TSBG#endif#undef G4V#undef FPFA#define G4V 0#define FPFA 0#undef RDO#undef GRDO#define RDO 0 // large-T: unchanged#define GRDO 0#undef XG4#define XG4 XG4B#undef ERL#define ERL ERLB#ifndef ERL2PB#define ERL2PB 0#endif#undef ERL2P#define ERL2P ERL2PB#ifndef ERLGB#define ERLGB 1 // large-T variant: early GU TMEM release (see the DIAGC power study note in the header)#endif#undef ERLG#define ERLG ERLGB#undef GUF32#define GUF32 0 // large-T: unchanged#undef LCL#ifndef LCLB#define LCLB 0 // large-T variant: late next-item claim (see fused_body.cuh LCL)#endif#define LCL LCLB#undef LCG#define LCG LCGB#undef HREA#define HREA 0 // large-T variant: unchanged#ifndef NLWB#define NLWB 6#endif// large-T variant: setmaxnreg rebalance (608 -> 640 threads, launch 96 regs; loaders + MMA/sched/TMA -> SMR_LO,// epilogue -> SMR_HI) and the 2-blocks-per-tmem_wait GU epilogue (GU32), previously register-limited at 104 regs#ifndef SMRB#define SMRB 1#endif#ifndef GU32B#define GU32B 0#endif#undef SMR#undef SMR_LO#undef SMR_LM#undef SMR_HI#define SMR SMRB#ifndef SMR_LO#define SMR_LO 56#endif#ifndef SMR_LM#define SMR_LM SMR_LO#endif#ifndef SMR_HI#define SMR_HI 120#endif#undef GU32#define GU32 GU32B#undef FWRP#undef FWSP#define FWRP WRPB#define FWSP WSPB#undef FRP#define FRP RPB#undef MWW#ifndef MWWB#define MWWB 0 // whole-warp MMA issuer, large-T variant#endif#define MWW MWWB#undef TWW#ifndef TWWB#define TWWB 0 // whole-warp TMA producer, large-T variant#endif#define TWW TWWB#ifndef CPNIB#define CPNIB 0#endif#undef CPNI#define CPNI CPNIB#undef MFWH#define MFWH MFWHB#ifndef TPESB#define TPESB 1 // large-T variant: weight-TMA producer empty wait = plain try_wait spin (release-latency pass)#endif#undef TPES#define TPES TPESB#undef HRS#define HRS HRSB#undef SHST#define SHST SHSTB#undef STEAL#define STEAL STEALB#ifndef CFSTB#define CFSTB 0#endif#undef CFST#define CFST CFSTB#ifndef CFTEB#define CFTEB 1 // large-T tail fix: no DN pre-claims after GU queue exhaustion (see fused_body.cuh CFTE)#endif#undef CFTE#define CFTE CFTEB#undef SGF#define SGF SGFB#ifndef WHBB#define WHBB 1 // large-T variant: weight half barriers (see fused_body.cuh WHB)#endif#undef WHB#define WHB WHBB#undef SRP#define SRP 0#ifndef DNWB#define DNWB 1 // large-T variant: wide (x4, 32-token segment) down-epilogue TMEM loads (see fused_body.cuh DNW)#endif#undef DNW#define DNW DNWB#ifndef GUPLB#define GUPLB 0#endif#ifndef ETSB#define ETSB 0#endif#undef GUPL#undef ETS#define GUPL GUPLB#define ETS ETSB#undef KRN#ifndef KRNB#define KRNB 0#endif#ifndef KRMB#define KRMB 1#endif#ifndef KRDB#define KRDB 0#endif#ifndef KRDMB#define KRDMB 1#endif#undef KRM#define KRN KRNB // large-T variant: GU K rotation (weight TMA + cp.async X gather), see fused_body.cuh KROT#define KRM KRMB#define KRD KRDB // large-T variant: DN K rotation (Wd TMA + H TMA)#define KRDM KRDMB#undef KRSH#undef CRO#undef ECA#define ECA 0 // large-T variant: unchanged#define CRO 0 // large-T variant: fused single box on both CTAs#define KRSH 1 // large-T: shared GU rotation follows KROT (seed)#undef RING#define RING RINGB#ifndef WHEBB#define WHEBB 0 // large-T: weight half-empty barriers (see fused_body.cuh WHEB)#endif#ifndef PLAGB#define PLAGB 1 // large-T: peer cp.async arrival lag depth (see fused_body.cuh PLAG)#endif#undef WHEB#define WHEB WHEBB#ifndef TFAB#define TFAB 1 // large-T: split accumulator-full signal (A0 early) for two-slot items#endif#undef TFA#define TFA TFAB#undef PLAG#define PLAG PLAGB#undef LKSP#undef LKRS#define LKSP 0#define LKRS 0#undef SFSP#ifndef SFSPB#define SFSPB 0 // large-T: TMA / MMA warps spin on the scheduler slot-full barrier (SFSP)#endif#define SFSP SFSPB// LARGE-T SCHEDULER FRESH-EYES (f63 CFST path): SCAB / SCBB knobs, see fused_body.cuh SCA / SCB#ifndef SCAB#define SCAB 0#endif#ifndef SCBB#define SCBB 0#endif#undef SCA#undef SCB#define SCA SCAB#define SCB SCBB#undef EPC#define EPC 0#undef ERING#define ERING ERINGB#undef TLA#define TLA 0#ifndef DHLB#define DHLB 1 // large-T: early H consumed count + L2 discard in the leader H loader (fused_body DHL)#endif#ifndef GPFB#define GPFB 0 // large-T: no writer-side proxy fence in the GU H publish (reader fences after acquire)#endif#undef GPF#define GPF GPFB#undef DHL#define DHL DHLBnamespace f63 {#define NLW NLWB#define EPG 3#include "fused_body.cuh"}#undef DHL#define DHL 0#undef GPF#define GPF 1#undef ERL2P#define ERL2P 0#undef SCA#undef SCB#define SCA 0#define SCB 0#undef GUPL#undef ETS#undef DNW#define DNW 0#undef WHB#define WHB 0#undef WHEB#define WHEB 0#undef TFA#define TFA 0#undef PLAG#define PLAG 1#undef SPLIT#undef WS#undef TS#undef CH#define CH CHSM#undef NPF#undef CHS#define NPF NPFS // host sizing: max over variants#define CHS CHSS // host sizing: min over variants#undef NLW#undef EPGusing f62::NT1;// fused-kernel variant table: kernel pointer + block size (smem layout is identical in all variants)typedef decltype(&f62::moe_fused_kernel) FusedFn;struct FusedVar { FusedFn fn; int threads; int smem; };#if DIAGV#define NVAR 3#else#define NVAR 2#endifstatic const FusedVar kVars[NVAR] = { {f62::moe_fused_kernel, f62::kThreads, f62::smem_total()}, {f63::moe_fused_kernel, f63::kThreads, f63::smem_total()}};#ifndef FAPW#define FAPW 1 // 1 = fused launch also carries the persisting access-policy window (see host)#endif#ifndef BIGV#define BIGV 1 // variant index used for T >= BIGT ((6,3))#endif#ifndef BIGT#define BIGT 6144#endif
#ifndef SPDDIV#define SPDDIV 128#endif#ifndef SPDMAX#define SPDMAX 64#endif// SPDBP > 0: fixed # of down-only PAIRS for the large-T variant (T >= BIGT); 0 = the clamp(T/SPDDIV) rule below#ifndef SPDBP#define SPDBP 0#endif// BAND KNOBS (T in [BANDLO, BIGT)): SPDBD > 0 = fixed # of down-only PAIRS there (0 = clamp rule); see SHSPBD in fused_body#ifndef BANDLO#define BANDLO 3600#endif#ifndef SPDBD#define SPDBD 0#endifstatic int spd_rule(int T) { if (SPD <= 0 || T < SPDT) return 0; if (SPDBP > 0 && T >= BIGT) return SPDBP; if (SPDBD > 0 && T >= BANDLO && T < BIGT) return SPDBD; // (CTA-count rule, converted to down-only PAIRS for the 2-SM pair kernel) return std::min(SPDMAX, std::max(SPD, T / SPDDIV)) / 2;}template <typename... KArgs, typename... Args>static void launch_pdl(void (*kern)(KArgs...), int grid, int block, size_t smem, cudaStream_t st, const cudaAccessPolicyWindow* apw, Args... args) { cudaLaunchConfig_t cfg = {}; cfg.gridDim = dim3(grid); cfg.blockDim = dim3(block); cfg.dynamicSmemBytes = smem; cfg.stream = st; cudaLaunchAttribute attr[3]; attr[0].id = cudaLaunchAttributeProgrammaticStreamSerialization; attr[0].val.programmaticStreamSerializationAllowed = 1; // CTA pairs (cluster of 2) for the cta_group::2 MMAs attr[1].id = cudaLaunchAttributeClusterDimension; attr[1].val.clusterDim.x = 2; attr[1].val.clusterDim.y = 1; attr[1].val.clusterDim.z = 1; int na = 2; if (apw) { // per-launch L2 access policy window (persisting set-aside for the output accumulator) attr[2].id = cudaLaunchAttributeAccessPolicyWindow; attr[2].val.accessPolicyWindow = *apw; na = 3; } cfg.attrs = attr; cfg.numAttrs = na; cudaLaunchKernelEx(&cfg, kern, ((KArgs)args)...);}
typedef CUresult (*PFN_encodeTiled)(CUtensorMap*, CUtensorMapDataType, cuuint32_t, void*, const cuuint64_t*, const cuuint64_t*, const cuuint32_t*, const cuuint32_t*, CUtensorMapInterleave, CUtensorMapSwizzle, CUtensorMapL2promotion, CUtensorMapFloatOOBfill);static PFN_encodeTiled get_encode() { static PFN_encodeTiled fn = nullptr; if (!fn) { void* p = nullptr; cudaDriverEntryPointQueryResult q; cudaGetDriverEntryPoint("cuTensorMapEncodeTiled", &p, cudaEnableDefault, &q); TORCH_CHECK(p != nullptr, "cuTensorMapEncodeTiled unavailable"); fn = (PFN_encodeTiled)p; } return fn;}// 2D bf16 row-major [rows, cols] -> box 64 cols (128B) x box_rows rows, SWIZZLE_128B (matches swz()/make_desc)#ifndef PERSIST_MB#define PERSIST_MB 80 // persisting-L2 set-aside request (clamped to the device max)#endif#ifndef HITR#define HITR 1.0 // hitRatio cap#endif#ifndef WIN#define WIN 1 // 0 = window over output only; 1 = window over the contiguous [output | H scratch] allocation#endif#ifndef WINT#define WINT 6144 // max T for which the persisting window also covers the head of H#endif#ifndef PROMO#define PROMO 3 // CUtensorMapL2promotion: 0 none, 1 64B, 2 128B, 3 256B#endif#ifndef PROMOT#define PROMOT PROMO // L2 promotion of the token-operand maps (X / H)#endifstatic CUtensorMap make_map(const void* ptr, uint64_t rows, uint64_t cols, uint32_t box_rows = 128, int promo = PROMO) { CUtensorMap m; cuuint64_t dims[2] = {cols, rows}; cuuint64_t strides[1] = {cols * sizeof(bf16)}; cuuint32_t box[2] = {64, box_rows}; cuuint32_t es[2] = {1, 1}; CUresult r = get_encode()(&m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 2, const_cast<void*>(ptr), dims, strides, box, es, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, (CUtensorMapL2promotion)promo, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); TORCH_CHECK(r == CUDA_SUCCESS, "cuTensorMapEncodeTiled failed"); return m;}
static CUtensorMap make_map_dn(const void* ptr, uint64_t rows, uint32_t sbox = 2) { CUtensorMap m; const cuuint64_t R = INTER * sizeof(bf16); // one row = 1 KB cuuint64_t dims[5] = {INTER, 8, 4, rows / 64, 2}; cuuint64_t strides[4] = {8 * R, 2 * R, 64 * R, R}; cuuint32_t box[5] = {64, 8, 4, 4, sbox}; cuuint32_t es[5] = {1, 1, 1, 1, 1}; CUresult r = get_encode()(&m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 5, const_cast<void*>(ptr), dims, strides, box, es, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, (CUtensorMapL2promotion)PROMO, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); TORCH_CHECK(r == CUDA_SUCCESS, "cuTensorMapEncodeTiled (5D down, zero-shuffle layout) failed"); return m;}
static CUtensorMap make_map_gu4(const void* ptr, uint64_t rows) { CUtensorMap m; cuuint64_t dims[4] = {HID, 8, 2, rows / 16}; cuuint64_t strides[3] = {2 * HID * sizeof(bf16), HID * sizeof(bf16), 16 * HID * sizeof(bf16)}; cuuint32_t box[4] = {64, 8, 2, 8}; cuuint32_t es[4] = {1, 1, 1, 1}; CUresult r = get_encode()(&m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 4, const_cast<void*>(ptr), dims, strides, box, es, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, (CUtensorMapL2promotion)PROMO, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); TORCH_CHECK(r == CUDA_SUCCESS, "cuTensorMapEncodeTiled (4D gate/up, GUPERM) failed"); return m;}// fused gate+up map with the GUPERM row permutation: 5D {k, i, s, G, gu 2 (stride = pointer distance)}static CUtensorMap make_map_gu(const void* g, const void* u, uint64_t rows, int& flags) { CUtensorMap m; memset(&m, 0, sizeof(m)); const uintptr_t pg = (uintptr_t)g, pu = (uintptr_t)u; const bool swp = pu < pg; const uintptr_t lo = swp ? pu : pg, d = swp ? pg - pu : pu - pg; flags = 0; if (d == 0 || (d & 15) || d >= (1ull << 40)) return m; cuuint64_t dims[5] = {HID, 8, 2, rows / 16, 2}; cuuint64_t strides[4] = {2 * HID * sizeof(bf16), HID * sizeof(bf16), 16 * HID * sizeof(bf16), (cuuint64_t)d}; cuuint32_t box[5] = {64, 8, 2, 8, 2}; cuuint32_t es[5] = {1, 1, 1, 1, 1}; CUresult r = get_encode()(&m, CU_TENSOR_MAP_DATA_TYPE_BFLOAT16, 5, (void*)lo, dims, strides, box, es, CU_TENSOR_MAP_INTERLEAVE_NONE, CU_TENSOR_MAP_SWIZZLE_128B, (CUtensorMapL2promotion)PROMO, CU_TENSOR_MAP_FLOAT_OOB_FILL_NONE); if (r == CUDA_SUCCESS) flags = 1 | (swp ? 2 : 0); return m;}
static torch::Tensor moe_forward_impl(torch::Tensor x, torch::Tensor rw, torch::Tensor sel, torch::Tensor wg, torch::Tensor wu, torch::Tensor wd, torch::Tensor swg, torch::Tensor swu, torch::Tensor swd, torch::Tensor sgw, int force_var = -1, int force_spd = -1) { // HOST-PATH DIET (per-call overhead pass): the route kernel + PDL-chained fused kernel are the only GPU work // per call (no memsets, no extra launches: zero-fill / counter reset already live in route_kernel). Remaining // host cost trimmed: contiguous() only when actually needed (no tensor handle churn on the normal path) and // the output view built directly on obuf's storage (no as_strided dispatcher round trip).#define MK_CONTIG(t) do { if (!(t).is_contiguous()) (t) = (t).contiguous(); } while (0) MK_CONTIG(x); MK_CONTIG(rw); MK_CONTIG(sel); MK_CONTIG(wg); MK_CONTIG(wu); MK_CONTIG(wd); MK_CONTIG(swg); MK_CONTIG(swu); MK_CONTIG(swd); MK_CONTIG(sgw);#undef MK_CONTIG TORCH_CHECK(x.is_cuda() && x.dim() == 2 && x.size(1) == HID && x.scalar_type() == at::kBFloat16, "hidden_states [T, 2048] bf16 CUDA"); TORCH_CHECK(sel.scalar_type() == at::kLong && sel.dim() == 2 && sel.size(0) == x.size(0) && sel.size(1) == TOPK, "selected_experts [T, 10] int64"); TORCH_CHECK(rw.scalar_type() == at::kBFloat16 && rw.dim() == 2 && rw.size(0) == x.size(0) && rw.size(1) == TOPK, "routing_weights [T, 10] bf16"); TORCH_CHECK(wg.numel() == (int64_t)NE * INTER * HID && wu.numel() == (int64_t)NE * INTER * HID && wd.numel() == (int64_t)NE * HID * INTER, "expert weights"); TORCH_CHECK(swg.numel() == (int64_t)INTER * HID && swu.numel() == (int64_t)INTER * HID && swd.numel() == (int64_t)HID * INTER && sgw.numel() == HID, "shared weights"); TORCH_CHECK(wg.scalar_type() == at::kBFloat16 && wu.scalar_type() == at::kBFloat16 && wd.scalar_type() == at::kBFloat16 && swg.scalar_type() == at::kBFloat16 && swu.scalar_type() == at::kBFloat16 && swd.scalar_type() == at::kBFloat16 && sgw.scalar_type() == at::kBFloat16, "weights must be bf16"); const c10::cuda::CUDAGuard dev_guard(x.device()); static int g_dev = -1; if (g_dev < 0) g_dev = x.get_device(); TORCH_CHECK(x.get_device() == g_dev, "moe_forward: process-wide caches are bound to the first CUDA device used"); const int T = x.size(0); if (T == 0) return torch::empty({T, HID}, x.options()); // per-T variant (warp roles + NPF/CHS config): route_kernel and fused kernel instances must match const int vi = force_var >= 0 ? force_var : (T >= BIGT ? BIGV : 0); TORCH_CHECK((int64_t)T * HID < (1ll << 32), "T too large (32-bit output row offsets)"); const int P0 = T * (TOPK + 1); // ONE allocation [output (T x HID) | H scratch (P x INTER)] so a single persisting L2 access-policy // window can cover both the reduction target and the L2-resident intermediate H. // Host-path diet: the int32 / fp32 routing workspaces are appended to the SAME allocation // [output | H | int ws | float ws] -> one caching-allocator call per run() instead of three. const int P = T * (TOPK + 1); const int max_chunks = (T * TOPK) / CH + T / CHS + NE1 + 2; // routed chunks + shared chunks const int64_t ints0 = 2 + 1 + 513 + (int64_t)max_chunks + 514 + 513 + 1 + 2 * (int64_t)max_chunks + P + (int64_t)T * TOPK + max_chunks; // DECODE TABLE: one packed 16-byte chunk descriptor {expert, pair offset, #tokens, start} per chunk, written by // route_kernel (rank 0 of the routing cluster) at a 16 B aligned slot after the int workspace -> the fused // kernel's scheduler decodes a dynamic item with ONE int4 load instead of the dependent chain // chunk_expert -> chunk_start -> offsets[e] / counts[e]. const int64_t desc_i = (ints0 + 3) & ~(int64_t)3; const int64_t ints = desc_i + 4 * (int64_t)max_chunks; const int64_t ints_al = (ints + 63) & ~(int64_t)63; // keep the float workspace 256 B aligned const int64_t nbf = (int64_t)T * HID + (int64_t)P0 * INTER; // bf16 elements of [output | H] // Host-path diet (time from run() entry to the route_kernel launch is exposed when the timed calls are // synchronized): allocate through at::detail::empty_cuda (caching allocator, no dispatcher round trip) // and build the output view with ONE as_strided instead of narrow + view. const int64_t nbuf = nbf + 2 * ints_al + 2 * ((int64_t)P + T); at::Tensor obuf(at::detail::empty_cuda({nbuf}, at::kBFloat16, x.device(), c10::nullopt)); // [T, HID] contiguous view at storage offset 0 of obuf (shares obuf's storage, keeps it alive) at::Tensor out; { auto impl = c10::make_intrusive<c10::TensorImpl>(c10::Storage(obuf.storage()), obuf.key_set(), obuf.dtype()); impl->set_sizes_contiguous({(int64_t)T, (int64_t)HID}); out = at::Tensor(std::move(impl)); } cudaStream_t stream = at::cuda::getCurrentCUDAStream(); int* iws_ptr = reinterpret_cast<int*>((bf16*)obuf.data_ptr() + nbf); static int* g_ctr = nullptr; static int g_cap = 0; static unsigned g_call = 0; if (max_chunks > g_cap) { cudaDeviceSynchronize(); // old block (if any) no longer in use if (g_ctr) cudaFree(g_ctr); g_cap = std::max(max_chunks, 4096); cudaMalloc(&g_ctr, 2 * (2 + 3 * (size_t)g_cap + ZOFF) * sizeof(int)); cudaMemset(g_ctr, 0, 2 * (2 + 3 * (size_t)g_cap + ZOFF) * sizeof(int)); cudaDeviceSynchronize(); } const size_t setn = 2 + 3 * (size_t)g_cap + ZOFF; // [sched | ready | consumed | early (ZOFF) | zfl[cap]] int* sched = g_ctr + (g_call & 1) * setn; int* rst = g_ctr + ((g_call + 1) & 1) * setn; // next call's set, zeroed by this call's route_kernel g_call++; int* ready = sched + 2; // per-chunk H-ready counters int* consumed = ready + g_cap; // per-chunk count of finished down items (H discard trigger) int* early = consumed + g_cap; // early head publication [flag | nhead | lists]; flag self-reset by the fused kernel int* counts = iws_ptr + 3; // fully written by route_kernel int* offsets = counts + 513 + 2 * max_chunks; int* cursor = offsets + 514; int* num_chunks = cursor + 513; int* chunk_expert = num_chunks + 1; int* chunk_start = chunk_expert + max_chunks; int* pair_token = chunk_start + max_chunks; int* pair_pos = pair_token + P; float* pair_w = reinterpret_cast<float*>(iws_ptr + ints_al); int4* chunk_desc = reinterpret_cast<int4*>(iws_ptr + desc_i); // iws_ptr is 1 KB aligned (2*nbf bytes in) bf16* Hbase = (bf16*)obuf.data_ptr() + (size_t)T * HID; // H [P, 512], 4 KB aligned (T*HID*2 bytes)
// (no memset: counters are persistent and self-reset by the fused kernel, see above)
static int num_sms = 0; static size_t g_persist_bytes = 0, g_max_window = 0; if (num_sms == 0) { int dev; cudaGetDevice(&dev); cudaDeviceGetAttribute(&num_sms, cudaDevAttrMultiProcessorCount, dev); for (int v = 0; v < NVAR; v++) cudaFuncSetAttribute(kVars[v].fn, cudaFuncAttributeMaxDynamicSharedMemorySize, kVars[v].smem); cudaFuncSetAttribute(rs::route_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, RSTAGE_MAX); cudaFuncSetAttribute(rb::route_kernel, cudaFuncAttributeMaxDynamicSharedMemorySize, RSTAGE_MAX); // persisting-L2 set-aside (once): the output is red.add-ed ~11x over the fused kernel; pinning it // in a persisting L2 partition keeps those lines from being thrashed by the streamed weights / H. int maxp = 0, maxw = 0; cudaDeviceGetAttribute(&maxp, cudaDevAttrMaxPersistingL2CacheSize, dev); cudaDeviceGetAttribute(&maxw, cudaDevAttrMaxAccessPolicyWindowSize, dev); g_persist_bytes = std::min<size_t>((size_t)maxp, (size_t)PERSIST_MB << 20); g_max_window = (size_t)maxw; if (g_persist_bytes > 0) cudaDeviceSetLimit(cudaLimitPersistingL2CacheSize, g_persist_bytes); cudaGetLastError(); } // route_kernel reads selected_experts / routing_weights with 16 B / 4 B vector loads of pair pairs if (((uintptr_t)sel.data_ptr() & 15) != 0) sel = sel.clone(); if (((uintptr_t)rw.data_ptr() & 3) != 0) rw = rw.clone(); const bf16* X = (const bf16*)x.data_ptr(); // routing cluster (RCL CTAs) + worker clusters for output zeroing / shared gate (>= 1 worker cluster)#ifndef RGMAX#define RGMAX 9 // cap on route_kernel clusters (72 CTAs): leaves ~half the SMs free for the fused kernel pre-wait#endif#ifndef RGMAXB#define RGMAXB RGMAX // route-cluster cap for T >= BIGT (large-T ramp: fewer route SMs -> more fused pairs start at t=0)#endif const int rgm = T >= BIGT ? RGMAXB : RGMAX; const int gr = RCL * std::max(NPF > 0 ? 3 : 2, std::min(std::min(num_sms / RCL, rgm), 1 + (T + 15) / 16 / RCL)); // access policy window over the output: hitRatio scaled so the persisting footprint fits the set-aside cudaAccessPolicyWindow apw = {}; const cudaAccessPolicyWindow* papw = nullptr; if (g_persist_bytes > 0 && g_max_window > 0) { const bool winH = WIN && T <= WINT; const size_t full = winH ? ((size_t)T * HID + (size_t)P * INTER) * sizeof(bf16) : (size_t)T * HID * sizeof(bf16); // window = the output followed by as much of H as fits in the set-aside (hitRatio 1): the output (reduced // into ~11x) is always fully persisting, the head of H fills the remaining persisting room deterministically const size_t ob = std::min(std::min(full, g_max_window), std::max(g_persist_bytes, (size_t)T * HID * sizeof(bf16)));#ifndef WINMB#define WINMB 0 // >0: cap the persisting window at WINMB MB (never below the output itself). Band A/B (DIAGO B, T=3889 min ms,#endif const size_t obc = WINMB > 0 ? std::min(ob, std::max((size_t)WINMB << 20, (size_t)T * HID * sizeof(bf16))) : ob; apw.base_ptr = out.data_ptr(); apw.num_bytes = obc; apw.hitRatio = (float)std::min((double)HITR, (double)g_persist_bytes / (double)obc); apw.hitProp = cudaAccessPropertyPersisting; apw.missProp = cudaAccessPropertyStreaming; papw = &apw; } // route_kernel is launched with the SAME persisting window: its output zero-fill inserts the output lines // into L2 as persisting from the start (otherwise they enter as normal lines and are evicted by the weight // stream before the fused kernel's first red.add reaches them -> extra DRAM read + write-back per line). { cudaLaunchConfig_t cfg = {}; cfg.gridDim = dim3(gr); cfg.blockDim = dim3(RT); // smem stage for the routing cluster's coalesced scatter: 8 B per pair of a CTA's slice (<= RSTAGE_MAX) const int per = ((R0LIST ? (T * TOPK + RCL - 2) / (RCL - 1) : (T * TOPK + RCL - 1) / RCL) + 1) & ~1; // = device slice (even) const int stage_cap = ((size_t)per * 8 <= RSTAGE_MAX) ? per : 0; cfg.dynamicSmemBytes = (size_t)stage_cap * 8; cfg.stream = stream; cudaLaunchAttribute attr[1]; int na = 0; if (papw) { attr[0].id = cudaLaunchAttributeAccessPolicyWindow; attr[0].val.accessPolicyWindow = *papw; na = 1; } cfg.attrs = attr; cfg.numAttrs = na; cudaLaunchKernelEx(&cfg, vi == 1 ? rb::route_kernel : (DIAGV && vi == 2 ? RB2 : rs::route_kernel), X, (const int64_t*)sel.data_ptr<int64_t>(), (const bf16*)rw.data_ptr(), (const bf16*)sgw.data_ptr(), counts, offsets, chunk_desc, chunk_start, num_chunks, pair_token, pair_w, pair_pos, (bf16*)out.data_ptr(), early, T, stage_cap, rst, (int)setn); } // Tensor maps cached across calls: the 8 weight maps are keyed on the weight data_ptrs (re-encoded only // when a weight pointer changes), the H map on (H pointer, P). Heap-held, never freed (plain PODs). struct MapCache { const void* key[6] = {nullptr, nullptr, nullptr, nullptr, nullptr, nullptr}; CUtensorMap Wg, Wu, Wd, Sg, Su, Sd, Wd1, Sd1, H, H2, H8, X, GU, SGU, XG; int guf = 0; const void* xkey = nullptr; int xT = -1; const void* hkey = nullptr; int hP = -1; }; static MapCache& mc = *new MapCache(); const void* wk[6] = {wg.data_ptr(), wu.data_ptr(), wd.data_ptr(), swg.data_ptr(), swu.data_ptr(), swd.data_ptr()}; if (memcmp(wk, mc.key, sizeof(wk)) != 0) { mc.Wg = make_map_gu4(wk[0], (uint64_t)NE * INTER); // GUPERM row order (fallback loads + L2 prefetch) mc.Wu = make_map_gu4(wk[1], (uint64_t)NE * INTER); mc.Wd = DNX ? make_map_dn(wk[2], (uint64_t)NE * HID) : make_map(wk[2], (uint64_t)NE * HID, INTER, 256); mc.Sg = make_map_gu4(wk[3], INTER); mc.Su = make_map_gu4(wk[4], INTER); mc.Sd = DNX ? make_map_dn(wk[5], HID) : make_map(wk[5], HID, INTER, 256); // tmWd1 / tmSd1: 5D half down boxes (s extent 1, 16 KB) for the HS wrapped weight half-slot pair mc.Wd1 = make_map_dn(wk[2], (uint64_t)NE * HID, 1); mc.Sd1 = make_map_dn(wk[5], HID, 1); int fr = 0, fs = 0; mc.GU = make_map_gu(wk[0], wk[1], (uint64_t)NE * INTER, fr); mc.SGU = make_map_gu(wk[3], wk[4], INTER, fs); mc.guf = fr | (fs << 2); // bit0/1 routed usable/swapped, bit2/3 shared usable/swapped memcpy(mc.key, wk, sizeof(wk)); } bf16* Hp = Hbase; bf16* Yp = (bf16*)out.data_ptr(); // down epilogue accumulates into out if (mc.hkey != (const void*)Hp || mc.hP != P) { mc.H = make_map(Hp, (uint64_t)P, INTER, HBOX, PROMOT); mc.H2 = make_map(Hp, (uint64_t)P, INTER, 2 * HBOX, PROMOT); mc.H8 = make_map(Hp, (uint64_t)P, INTER, 8, PROMOT); // exact H tail boxes (HT8) mc.hkey = Hp; mc.hP = P; } const CUtensorMap &mWg = mc.Wg, &mWu = mc.Wu, &mWd = mc.Wd, &mSg = mc.Sg, &mSu = mc.Su, &mSd = mc.Sd; const CUtensorMap &mH = mc.H, &mWd1 = mc.Wd1, &mSd1 = mc.Sd1; if (mc.xkey != (const void*)X || mc.xT != T) { mc.X = make_map(X, (uint64_t)T, HID, HBOX, PROMOT); mc.XG = make_map(X, (uint64_t)T, HID, 1, PROMOT); // gather4 map (1-row boxes, 4 rows per request) mc.xkey = X; mc.xT = T; } // per-T warp-role configuration of the fused kernel const FusedVar& fv = kVars[vi]; // persistent pair grid: all CTA pairs must be co-resident (static items / H-ready waits), so cap the grid // at the device's max number of simultaneously active 2-CTA clusters of this variant static int max_cl[3] = {0, 0, 0}; if (max_cl[vi] == 0) { cudaLaunchConfig_t qc = {}; qc.gridDim = dim3(num_sms & ~1); qc.blockDim = dim3(fv.threads); qc.dynamicSmemBytes = fv.smem; cudaLaunchAttribute qa[1]; qa[0].id = cudaLaunchAttributeClusterDimension; qa[0].val.clusterDim.x = 2; qa[0].val.clusterDim.y = 1; qa[0].val.clusterDim.z = 1; qc.attrs = qa; qc.numAttrs = 1; int n = 0; if (cudaOccupancyMaxActiveClusters(&n, fv.fn, &qc) != cudaSuccess || n <= 0) { cudaGetLastError(); n = num_sms / 2; } max_cl[vi] = std::max(1, std::min(n, num_sms / 2)); } const int g = 2 * std::max(1, std::min(max_cl[vi], max_chunks * NT1)); launch_pdl(fv.fn, g, fv.threads, (size_t)fv.smem, stream, FAPW ? papw : nullptr, mWg, mWu, mSg, mSu, mWd, mSd, mH, mWd1, mSd1, mc.X, mc.H2, mc.GU, mc.SGU, mc.XG, mc.H8, mc.guf, X, (const bf16*)sgw.data_ptr(), (const int*)counts, (const int*)offsets, (const int4*)chunk_desc, (const int*)chunk_start, (const int*)num_chunks, (const int*)pair_token, pair_w, Hp, Yp, sched, ready, consumed, (const int*)early, T, force_spd >= 0 ? force_spd : spd_rule(T)); return out;}
// (code diet: the diagnostic A/B / audit drivers -- DIAGG/C/T/E/R/H/X/V/Q/A/S -- were removed from the production// build; production entry = moe_forward_impl with the per-T default variant / spatial split)torch::Tensor moe_forward(torch::Tensor x, torch::Tensor rw, torch::Tensor sel, torch::Tensor wg, torch::Tensor wu, torch::Tensor wd, torch::Tensor swg, torch::Tensor swu, torch::Tensor swd, torch::Tensor sgw) { return moe_forward_impl(x, rw, sel, wg, wu, wd, swg, swu, swd, sgw);}123456#include <torch/extension.h>torch::Tensor moe_forward(torch::Tensor x, torch::Tensor rw, torch::Tensor sel, torch::Tensor wg, torch::Tensor wu, torch::Tensor wd, torch::Tensor swg, torch::Tensor swu, torch::Tensor swd, torch::Tensor sgw);torch::Tensor run(torch::Tensor x, torch::Tensor rw, torch::Tensor sel, torch::Tensor wg, torch::Tensor wu, torch::Tensor wd, torch::Tensor swg, torch::Tensor swu, torch::Tensor swd, torch::Tensor sgw) { return moe_forward(x, rw, sel, wg, wu, wd, swg, swu, swd, sgw);}PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) { m.def("run", &run, "MoE with shared expert"); }123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707#ifndef ZV8#define ZV8 0 // route worker zero-fill with 32-byte st.global.v8 stores#endif#ifndef MCADR#define MCADR 0 // multi-chunk experts kept in the address-ordered region (set per variant by kernel.cu)#endif#ifndef MCCAP#define MCCAP 128#endif#ifndef RWD#define RWD 0 // route worker loop diet when the shared gate lives in the fused kernel (RSGF)#endif#define RWDV (RWD && RSGF && !ZPUB)// route_body.cuh: route_kernel (see kernel.cu for the algorithm). Included ONCE PER (NPF, CHS) configuration// inside its own namespace (rs = small T, rb = T >= BIGT); NPF / CHS are (re)defined by the includer.__global__ void __cluster_dims__(RCL, 1, 1) __launch_bounds__(RT, 1) route_kernel( const bf16* __restrict__ x, const int64_t* __restrict__ sel, const bf16* __restrict__ rw, const bf16* __restrict__ sgw, int* counts, int* offsets, int4* __restrict__ chunk_desc, int* __restrict__ chunk_start, int* num_chunks, int* __restrict__ pair_token, float* __restrict__ pair_w, int* pair_pos, bf16* __restrict__ out, int* early, int T, int stage_cap, int* __restrict__ rst, int nrst) { // griddepcontrol.launch_dependents is the very FIRST instruction (also in diag builds). pdl_trigger(); if (DIAGT && threadIdx.x == 0) atomicMin(g_dt, rgt()); const int tid = threadIdx.x, lane = tid & 31; constexpr int NW = RT / 32; if (DIAGR && tid == 0) g_rd[blockIdx.x * 16] = rgt(); if (NPF > 0 && cluster_id_x() == 1) { // ================= EARLY HEAD PUBLISHER (cluster 1): token lists of experts 0..NPF-1 only. // Their segment offsets are prefix sums over experts < NPF (identical to cluster 0's global scan), so // this cluster places their pairs without the full routing pass: per-CTA slice histogram (smem atomic // rank), DSMEM count exchange, scatter, cluster barrier, then rank 0 publishes into early[]: // [0] ready flag (st.release.gpu), [1] nhead, [2..] head_e[NPF], head_off[NPF], head_cnt[NPF] // so the fused kernel can run these experts' first-chunk gate/up items before route_kernel finishes. // (cluster 0 skips the scatter of experts < NPF.) __shared__ int ec[NPF > 0 ? NPF : 1], eoff[NPF > 0 ? NPF : 1]; const uint32_t rank = cluster_ctarank(); if (tid < NPF) ec[tid] = 0; __syncthreads(); const int NP = T * TOPK; const int per = ((NP + RCL - 1) / RCL + 1) & ~1; // even: 16 B-aligned vector sel loads const int lo = (int)rank * per, hi = min(NP, lo + per); // register-cached slice: pair i = lo + tid + j*RT (j < RCP) keeps (expert, rank, weight) in registers // for the scatter (no dependent L2 reloads of sel / pair_pos / rw after the barrier); pairs beyond the // cache (T > ~6.5k) take the pair_pos round trip. int ce[RCP], cr[RCP]; unsigned short cw[RCP];#pragma unroll for (int jj = 0; jj < RCP / 2; jj++) { // VECTOR LOADS: pair pair (i, i+1), i even (lo, per even): one 16 B sel load (2 x int64 -> int32 // narrowed in registers) + one 4 B load of the two bf16 routing weights const int i = lo + 2 * (tid + jj * RT); if (i < hi) { const longlong2 sv = __ldg(reinterpret_cast<const longlong2*>(sel + i)); const uint32_t wv = __ldg(reinterpret_cast<const unsigned int*>(rw + i)); ce[2 * jj] = (int)sv.x; ce[2 * jj + 1] = (int)sv.y; cw[2 * jj] = (unsigned short)(wv & 0xffffu); cw[2 * jj + 1] = (unsigned short)(wv >> 16); } else { ce[2 * jj] = NE; ce[2 * jj + 1] = NE; cw[2 * jj] = 0; cw[2 * jj + 1] = 0; } }#pragma unroll for (int j = 0; j < RCP; j++) cr[j] = (ce[j] < NPF) ? atomicAdd(&ec[ce[j]], 1) : 0; for (int i0 = lo + tid + RCP * RT; i0 < hi; i0 += 4 * RT) { int e[4];#pragma unroll for (int u = 0; u < 4; u++) { const int i = i0 + u * RT; e[u] = (i < hi) ? (int)__ldg(&sel[i]) : NE; }#pragma unroll for (int u = 0; u < 4; u++) if (e[u] < NPF) pair_pos[i0 + u * RT] = atomicAdd(&ec[e[u]], 1); } RMARK(1); __syncthreads(); cluster_arrive_release(); cluster_wait_acquire(); RMARK(2); if (tid < NPF) { int c = 0, bs = 0; for (int q = 0; q < RCL; q++) { const int v = ld_dsmem(&ec[tid], q); if (q < (int)rank) bs += v; c += v; } // exclusive prefix over experts < NPF (warp 0 shuffle scan) int incl = c;#pragma unroll for (int o = 1; o < 32; o <<= 1) { const int t = __shfl_up_sync((1u << NPF) - 1u, incl, o, 16); if (tid >= o) incl += t; } eoff[tid] = incl - c + bs; if (rank == 0) { const unsigned hm = __ballot_sync((1u << NPF) - 1u, c > 0); if (c > 0) { const int h = __popc(hm & ((1u << tid) - 1u)); early[2 + h] = tid; early[2 + NPF + h] = incl - c; early[2 + 2 * NPF + h] = c; } if (tid == 0) early[1] = __popc(hm); } } cluster_arrive_relaxed(); // remote reads of ec done __syncthreads();#pragma unroll for (int j = 0; j < RCP; j++) { if (ce[j] < NPF) { const int i = lo + 2 * (tid + (j >> 1) * RT) + (j & 1); // cached pair j (vector-load order) const int pos = eoff[ce[j]] + cr[j]; pair_token[pos] = i / TOPK; pair_w[pos] = __uint_as_float((uint32_t)cw[j] << 16); } } for (int i = lo + tid + RCP * RT; i < hi; i += RT) { const int e = (int)__ldg(&sel[i]); if (e < NPF) { const int pos = eoff[e] + pair_pos[i]; pair_token[pos] = i / TOPK; pair_w[pos] = __bfloat162float(rw[i]); } } RMARK(3);#if EPC // EPC (early publish counter): no second cluster barrier. Each CTA publishes its own scatter (and rank 0 its // early[] head lists, written before this point) with ONE gpu-scope release increment of early[0]; consumers // wait for early[0] >= RCL. The DSMEM-lifetime wait (peers' reads of ec done) follows the release. __syncthreads(); if (tid == 0) { __threadfence(); asm volatile("red.release.gpu.global.add.s32 [%0], 1;" ::"l"(early) : "memory"); } cluster_wait_acquire(); // (pairs with the relaxed arrive above: peers' DSMEM reads finished)#else __threadfence(); cluster_wait_acquire(); // (pairs with the relaxed arrive above: peers' DSMEM reads finished) cluster_arrive_release(); // second barrier: all CTAs' scatters done cluster_wait_acquire(); if (rank == 0 && tid == 0) { __threadfence(); asm volatile("st.release.gpu.global.s32 [%0], %1;" ::"l"(early), "r"(1) : "memory"); }#endif RMARK(4); if (!ZROW) { // after publishing, this cluster takes zero-fill share zb = nwb + rank (see worker clusters) const int nwb = gridDim.x - 2 * RCL, nzb = nwb + RCL; uint4* o = reinterpret_cast<uint4*>(out); const size_t n16 = (size_t)T * HID / 8; for (size_t i = (size_t)(nwb + rank) * RT + tid; i < n16; i += (size_t)nzb * RT) o[i] = make_uint4(0, 0, 0, 0); } return; } // RDIST (large-T variant): distributed routing. Ranks 1..RCL-1 of cluster 0 join the worker clusters as "dist" // CTAs; every dist CTA histograms a 1/ND slice of the pairs (smem rank) and claims its per-expert base slots with // global atomics (gcnt), then does its worker share, then (after the scanner's offsets flag) scatters its slice. // Cluster 0 rank 0 = scanner: waits for all ND histograms (hdone), scans the global counts, publishes offsets + // flag, then builds the chunk list. Counters live in the (otherwise unused, ZPUB=0) zfl block of the per-call set. int* const gcnt = early + ZOFF; // [NE] global expert counts int* const hdone = early + ZOFF + NE; // # dist CTAs whose histogram is published int* const gflag = early + ZOFF + NE + 1; // offsets published const int ndist = (int)gridDim.x - 2 * RCL + (RCL - 1); if (cluster_id_x() != 0 || (RDIST && cluster_ctarank() != 0)) { // ================= worker clusters: output zeroing + shared-expert gate const int skip = (NPF > 0) ? 2 * RCL : RCL; // cluster 1 is the early head publisher const int wb = RDIST ? (blockIdx.x < RCL ? (int)blockIdx.x - 1 : (int)blockIdx.x - 2 * RCL + (RCL - 1)) : (int)blockIdx.x - skip; const int nwb = RDIST ? ndist : (int)gridDim.x - skip;#if RDIST static_assert(NPF > 0, "RDIST needs the early publisher cluster"); __shared__ int dlc[NE], dbase[NE]; dlc[tid] = 0; __syncthreads(); const int DNP = T * TOPK; const int dper = ((DNP + ndist - 1) / ndist + 1) & ~1; // even (16 B sel vector loads) const int dlo = min(DNP, wb * dper), dhi = min(DNP, dlo + dper); constexpr int RDC = 4; // register-cached pairs per thread (overflow -> pair_pos, e >= NPF only) int de_[RDC], dr_[RDC]; unsigned short dw_[RDC];#pragma unroll for (int jj = 0; jj < RDC / 2; jj++) { const int i = dlo + 2 * (tid + jj * RT); if (i < dhi) { const longlong2 sv = __ldg(reinterpret_cast<const longlong2*>(sel + i)); const uint32_t wv = __ldg(reinterpret_cast<const unsigned int*>(rw + i)); de_[2 * jj] = (int)sv.x; de_[2 * jj + 1] = (int)sv.y; dw_[2 * jj] = (unsigned short)(wv & 0xffffu); dw_[2 * jj + 1] = (unsigned short)(wv >> 16); } else { de_[2 * jj] = -1; de_[2 * jj + 1] = -1; dw_[2 * jj] = 0; dw_[2 * jj + 1] = 0; } }#pragma unroll for (int j = 0; j < RDC; j++) dr_[j] = (de_[j] >= 0) ? atomicAdd(&dlc[de_[j]], 1) : 0; for (int i = dlo + tid + RDC * RT; i < dhi; i += RT) { const int e = (int)__ldg(&sel[i]); const int r = atomicAdd(&dlc[e], 1); if (e >= NPF) pair_pos[i] = r; // e < NPF: early publisher owns pair_pos } __syncthreads(); { const int v = dlc[tid]; dbase[tid] = v ? atomicAdd(gcnt + tid, v) : 0; __threadfence(); } __syncthreads(); if (tid == 0) asm volatile("red.release.gpu.global.add.s32 [%0], 1;" ::"l"(hdone) : "memory");#endif // cross-call counter reset: zero the counter set of the NEXT call (parity-alternating sets; the previous // user of that set, call N-1, completed before this grid started; this call's fused kernel uses the other set)#if RSV4 { // RSV4: next-call counter reset with 16-byte stores (scalar head up to the 16 B boundary, int4 body, scalar tail) const int gt = wb * RT + tid, gs = nwb * RT; const int hh = min(nrst, (int)(((16u - ((uint32_t)(uintptr_t)rst & 15u)) & 15u) >> 2)); if (gt < hh) rst[gt] = 0; int4* r4 = reinterpret_cast<int4*>(rst + hh); const int n4 = (nrst - hh) >> 2; for (int i = gt; i < n4; i += gs) r4[i] = make_int4(0, 0, 0, 0); const int t0 = hh + 4 * n4; if (gt < nrst - t0) rst[t0 + gt] = 0; }#else for (int i = wb * RT + tid; i < nrst; i += nwb * RT) rst[i] = 0;#endif // shared-expert gate sigmoid(x . w) on the TENSOR CORES (mma.sync m16n8k16 bf16, fp32 accumulate): // GEMV-as-GEMM [32 tokens x 2048] x [2048 x 8 (w replicated in all 8 columns)] per CTA iteration. // Warp (tg = warp>>3, ks = warp&7) owns 16 tokens (tg) x K slice [ks*256, +256). Since only the dot // product is needed, K may be PERMUTED as long as A and B use the same permutation: lane (g = lane>>2, // t = lane&3) loads one 16 B chunk (k = ks*256 + s*32 + t*8 .. +8) of token rows g and g+8 per step s // and the matching 16 B chunk of w; words x,y feed MMA 1 (logical k 2t | 2t+8), words z,w MMA 2. // -> 16 independent 16 B x loads per lane in flight, no per-element bf16->fp32 converts / FMAs. // The 8 K-slice partials (lanes t==0 hold D[g][0] / D[g+8][0]) are summed in smem. __shared__ float gred[2][8][16]; const int tg = (tid >> 5) >> 3, ks = (tid >> 5) & 7, gq = lane >> 2, tq = lane & 3; const uint4* wr = reinterpret_cast<const uint4*>(sgw); uint4 wv[8];#pragma unroll for (int s = 0; s < 8; s++) wv[s] = RWDV ? make_uint4(0, 0, 0, 0) : __ldg(&wr[(ks * 256 + s * 32 + tq * 8) / 8]); const int nzb = nwb + ((NPF > 0) ? RCL : 0); uint4* zo = reinterpret_cast<uint4*>(out); const size_t n16 = (size_t)T * HID / 8, zstep = (size_t)nzb * RT; size_t zi = (size_t)wb * RT + tid; const int giters = (wb * 32 < T) ? (T - wb * 32 + nwb * 32 - 1) / (nwb * 32) : 0; // CTA iterations const size_t nz = zi < n16 ? (n16 - zi + zstep - 1) / zstep : 0; const int zper = giters > 0 ? (int)((nz + giters - 1) / giters) : 0; if (XPG == 4 && RSGF && XRL && T < AUDBIG) { // XPG 4: X [T, 2048] is contiguous -> split it into XPGS-byte spans, round robin over the worker threads const size_t xbytes = (size_t)T * HID * 2; const size_t nsp = (xbytes + XPGS - 1) / XPGS; const char* xc = reinterpret_cast<const char*>(x); for (size_t sp = (size_t)wb * RT + tid; sp < nsp; sp += (size_t)nwb * RT) { const size_t o = sp * XPGS; xpf_bulk(xc + o, (uint32_t)min((size_t)XPGS, xbytes - o)); } } for (int tb = wb * 32; tb < T; tb += nwb * 32) { // CTA-uniform loop (contains __syncthreads) const int r0t = tb + tg * 16 + gq, r1t = r0t + 8; const uint4* xr0 = reinterpret_cast<const uint4*>(x + (size_t)min(r0t, T - 1) * HID + ks * 256 + tq * 8); const uint4* xr1 = reinterpret_cast<const uint4*>(x + (size_t)min(r1t, T - 1) * HID + ks * 256 + tq * 8); uint4 a0[8], a1[8]; if (RSGF) { // RSGF: shared gate computed in the fused kernel (shared GU epilogue) -> no X loads / GEMV here; the block's // X rows are still inserted into L2 as evict_last (fire-and-forget prefetch, keeps the XRL effect) if (XRL && T < AUDBIG) { const char* xb = reinterpret_cast<const char*>(x + (size_t)tb * HID); const int nl = min(32, T - tb) * (HID * 2 / 128); // 128 B lines of this 32-token block if (XPG == 3) { // XPG 3: the block's X rows are ONE contiguous range (nr x 4 KB): bulk L2 prefetches of XPGS bytes each const uint32_t nbx = (uint32_t)min(32, T - tb) * (HID * 2); const uint32_t nsp = (nbx + XPGS - 1) / XPGS; if ((uint32_t)tid < nsp) { const uint32_t sz = min((uint32_t)XPGS, nbx - (uint32_t)tid * XPGS); xpf_bulk(xb + (size_t)tid * XPGS, sz); } } else if (XPG == 4) { // XPG 4: whole-X contiguous spans, issued once before the loop (see below) } else if (XPG == 2) { uint64_t pxl; asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pxl)); const int nr = min(32, T - tb); if (tid < nr) asm volatile("cp.async.bulk.prefetch.L2.global.L2::cache_hint [%0], %1, %2;" ::"l"(xb + (size_t)tid * (HID * 2)), "r"(HID * 2), "l"(pxl) : "memory"); } else if (XPG == 1) { // XPG 1: one prefetch per 256 B granule for (int l = tid; l < nl / 2; l += RT) asm volatile("prefetch.global.L2::evict_last [%0];" ::"l"(xb + (size_t)l * 256)); } else for (int l = tid; l < nl; l += RT) asm volatile("prefetch.global.L2::evict_last [%0];" ::"l"(xb + (size_t)l * 128)); } } else if (XRL && T < AUDBIG) { // XRL (small T): the gate GEMV is the first reader of every X row -> insert X into L2 with evict_last so // the ~20 later gather reads per token (10 routed chunks x 2 pair tiles) hit L2 instead of DRAM uint64_t pxl; asm volatile("createpolicy.fractional.L2::evict_last.b64 %0, 1.0;" : "=l"(pxl));#pragma unroll for (int s = 0; s < 8; s++) { asm volatile("ld.global.nc.L2::cache_hint.v4.u32 {%0,%1,%2,%3}, [%4], %5;" : "=r"(a0[s].x), "=r"(a0[s].y), "=r"(a0[s].z), "=r"(a0[s].w) : "l"(xr0 + s * 4), "l"(pxl)); asm volatile("ld.global.nc.L2::cache_hint.v4.u32 {%0,%1,%2,%3}, [%4], %5;" : "=r"(a1[s].x), "=r"(a1[s].y), "=r"(a1[s].z), "=r"(a1[s].w) : "l"(xr1 + s * 4), "l"(pxl)); } } else {#pragma unroll for (int s = 0; s < 8; s++) { a0[s] = __ldg(xr0 + s * 4); a1[s] = __ldg(xr1 + s * 4); } } if (ZROW && !RNOZ) { // RNOZ (SHST): output written by the fused kernel's shared down stores // ZROW: this CTA zeroes exactly the output rows of its 32-token gate block (contiguous 128 KB), // so the block's rows + shared gate can be published together (zfl, see below) const int nrow = min(32, T - tb); uint4* zb4 = zo + (size_t)tb * (HID / 8); if (ZV8 && T < AUDBIG) { // ZV8: 32-byte st.global.v8.b32 zero stores (sm_100), half the store instructions of the uint4 loop char* zb8 = reinterpret_cast<char*>(zb4); const uint32_t z = 0u; for (int i = tid; i < nrow * (HID / 16); i += RT) asm volatile("st.global.v8.b32 [%0], {%1, %1, %1, %1, %1, %1, %1, %1};" ::"l"(zb8 + (size_t)i * 32), "r"(z) : "memory"); } else for (int i = tid; i < nrow * (HID / 8); i += RT) zb4[i] = make_uint4(0, 0, 0, 0); } else { for (int q = 0; q < zper && zi < n16; q++, zi += zstep) zo[zi] = make_uint4(0, 0, 0, 0); } float c0 = 0.f, c1 = 0.f, c2 = 0.f, c3 = 0.f;#pragma unroll for (int s = 0; s < (RSGF ? 0 : 8); s++) { asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) : "r"(a0[s].x), "r"(a1[s].x), "r"(a0[s].y), "r"(a1[s].y), "r"(wv[s].x), "r"(wv[s].y)); asm volatile("mma.sync.aligned.m16n8k16.row.col.f32.bf16.bf16.f32 {%0,%1,%2,%3}, {%4,%5,%6,%7}, {%8,%9}, {%0,%1,%2,%3};" : "+f"(c0), "+f"(c1), "+f"(c2), "+f"(c3) : "r"(a0[s].z), "r"(a1[s].z), "r"(a0[s].w), "r"(a1[s].w), "r"(wv[s].z), "r"(wv[s].w)); } if (RWDV) { // RWD (RSGF worker diet): no gate GEMV here -> no gred reduction / block barriers; only the shared pair_token if (tid < 32 && tb + tid < T) pair_token[T * TOPK + tb + tid] = tb + tid; continue; } if (tq == 0) { gred[tg][ks][gq] = c0; gred[tg][ks][gq + 8] = c2; } // column 0 of D (rows g, g+8) __syncthreads(); if (tid < 32) { const int g2 = tid >> 4, r = tid & 15, w = tb + g2 * 16 + r; float sum = 0.f;#pragma unroll for (int k = 0; k < 8; k++) sum += gred[g2][k][r]; if (w < T) { const float logit = __bfloat162float(__float2bfloat16(sum)); const int pos = T * TOPK + w; // shared-expert segment starts at T*TOPK pair_token[pos] = w; if (!RSGF) pair_w[pos] = __bfloat162float(__float2bfloat16(1.f / (1.f + expf(-logit)))); } } __syncthreads(); // gred reuse (+ all zero-fill / gate writes of the block done) if (ZROW && ZPUB && tid == 0) { // publish: rows tb..tb+32 zeroed and their shared gate / pair_token written. zfl[chunk] counts the // ready tokens of each shared chunk (CHS is a multiple of 32 -> a block lies in one chunk); the // fused kernel's pre-route shared down items acquire it before touching the output / pair data. __threadfence(); asm volatile("red.release.gpu.global.add.s32 [%0], %1;" ::"l"(early + ZOFF + tb / CHS), "r"(min(32, T - tb)) : "memory"); } } RMARK(2); if (!ZROW) for (; zi < n16; zi += zstep) zo[zi] = make_uint4(0, 0, 0, 0); // remainder (warps with no gate tokens)#if RDIST // scatter this CTA's slice once the scanner published the expert offsets if (tid == 0) { int f; do { asm volatile("ld.acquire.gpu.global.s32 %0, [%1];" : "=r"(f) : "l"(gflag) : "memory"); if (!f) __nanosleep(64); } while (!f); } __syncthreads(); dlc[tid] = __ldcg(offsets + tid) + dbase[tid]; // reuse dlc: global slot base of expert tid for this CTA __syncthreads();#pragma unroll for (int j = 0; j < RDC; j++) { const int e = de_[j]; if (e >= NPF) { const int i = dlo + 2 * (tid + (j >> 1) * RT) + (j & 1); const int pos = dlc[e] + dr_[j]; pair_token[pos] = i / TOPK; pair_w[pos] = __uint_as_float((uint32_t)dw_[j] << 16); } } for (int i = dlo + tid + RDC * RT; i < dhi; i += RT) { const int e = (int)__ldg(&sel[i]); if (e < NPF) continue; const int pos = dlc[e] + __ldcg(pair_pos + i); pair_token[pos] = i / TOPK; pair_w[pos] = __bfloat162float(rw[i]); }#endif RMARK(1); return; } // ================= routing cluster typedef cub::BlockScan<long long, RT> BS; extern __shared__ uint32_t rstage[]; // [stage_cap] tokens | [stage_cap] (expert << 16 | bf16 weight) __shared__ typename BS::TempStorage tmp; __shared__ int lc[NE]; // block-local histogram (rank counter); read remotely via DSMEM __shared__ int bb[NE]; // this block's base slot within each expert segment __shared__ int offs[NE]; // expert segment offsets (exclusive scan of counts) __shared__ int lof[NE + 1]; // this block's local (expert-sorted) offsets: exclusive scan of lc __shared__ int gb[NE]; // global pos of local slot k of expert e = gb[e] + k __shared__ int bh[17], bc[17], hwc[RT / 32]; __shared__ int s_end_sh, s_nhead; const uint32_t rank = cluster_ctarank(); lc[tid] = 0; if (tid < 17) bh[tid] = 0; // LPT bucket histogram (rank 0), zeroed before this sync __syncthreads(); const int NP = T * TOPK; // R0LIST: rank 0 owns NO pair slice -- it only scans and builds the LPT chunk list, concurrently with // ranks 1..RCL-1 scattering. // Ranks 1..RCL-1 own contiguous 1/(RCL-1) slices in rank order (base-slot prefix over q < rank unchanged). const int per = ((R0LIST ? (NP + RCL - 2) / (RCL - 1) : (NP + RCL - 1) / RCL) + 1) & ~1; // even (vector loads); host mirrors it const int lo = R0LIST ? (rank == 0 ? 0 : min(NP, ((int)rank - 1) * per)) : (int)rank * per; const int hi = R0LIST ? (rank == 0 ? 0 : min(NP, lo + per)) : min(NP, lo + per); // ---- phase 1: block-local expert histogram / ranks. The first RCP pairs of this thread // (i = lo + tid + j*RT) keep expert / rank / routing weight in registers for the scatter (all loads // issued before the smem atomics); the rest (large T only) go through pair_pos. int ce[RCP], cr[RCP]; unsigned short cw[RCP];#pragma unroll for (int jj = 0; jj < RCP / 2; jj++) { // VECTOR LOADS (see the early publisher): pairs (i, i+1), i even; hi even -> i < hi implies i+1 < hi const int i = lo + 2 * (tid + jj * RT); if (i < hi) { const longlong2 sv = __ldg(reinterpret_cast<const longlong2*>(sel + i)); const uint32_t wv = __ldg(reinterpret_cast<const unsigned int*>(rw + i)); ce[2 * jj] = (int)sv.x; ce[2 * jj + 1] = (int)sv.y; cw[2 * jj] = (unsigned short)(wv & 0xffffu); cw[2 * jj + 1] = (unsigned short)(wv >> 16); } else { ce[2 * jj] = -1; ce[2 * jj + 1] = -1; cw[2 * jj] = 0; cw[2 * jj + 1] = 0; } }#pragma unroll for (int j = 0; j < RCP; j++) cr[j] = (ce[j] >= 0) ? atomicAdd(&lc[ce[j]], 1) : 0; for (int i0 = lo + tid + RCP * RT; i0 < hi; i0 += 4 * RT) { int e[4];#pragma unroll for (int u = 0; u < 4; u++) { const int i = i0 + u * RT; e[u] = (i < hi) ? (int)__ldg(&sel[i]) : 0; }#pragma unroll for (int u = 0; u < 4; u++) { const int i = i0 + u * RT; if (i < hi) { const int r = atomicAdd(&lc[e[u]], 1); if (e[u] >= NPF) pair_pos[i] = r; } // e<NPF: cluster 1 owns pair_pos } } RMARK(1); __syncthreads(); if (!RDIST) { cluster_arrive_release(); cluster_wait_acquire(); } RMARK(2); // ---- phase 2: DSMEM-distributed histogram -> counts + per-CTA base slots int c = 0, base = 0; const int mylc = lc[tid];#if RDIST // scanner: wait until every dist CTA published its histogram, then read the global counts if (tid == 0) { int f; do { asm volatile("ld.acquire.gpu.global.s32 %0, [%1];" : "=r"(f) : "l"(hdone) : "memory"); if (f < ndist) __nanosleep(32); } while (f < ndist); } __syncthreads(); c = __ldcg(gcnt + tid);#else { int v[RCL];#pragma unroll for (int q = 0; q < RCL; q++) v[q] = ld_dsmem(&lc[tid], q);#pragma unroll for (int q = 0; q < RCL; q++) { if (q < (int)rank) base += v[q]; c += v[q]; } } cluster_arrive_relaxed(); // this CTA finished its remote reads (matching wait before exit)#endif bb[tid] = base; // ONE block scan of the packed (global count << 32 | local count): high word = global expert offset, // low word = this block's local expert-sorted offset (low sums <= per < 2^32: no carry into the high word) int off, tot, loff; { long long pk, ptot; BS(tmp).ExclusiveSum(((long long)c << 32) | (long long)(unsigned)mylc, pk, ptot); off = (int)(pk >> 32); loff = (int)(pk & 0xffffffffll); tot = (int)(ptot >> 32); // tot == T*TOPK } offs[tid] = off;#if RDIST // publish the expert offsets first (the dist CTAs' scatter needs only these), then build the chunk list offsets[tid] = off; __threadfence(); __syncthreads(); if (tid == 0) asm volatile("st.release.gpu.global.s32 [%0], %1;" ::"l"(gflag), "r"(1) : "memory");#endif lof[tid] = loff; gb[tid] = off + base - loff; if (tid == 0) lof[NE] = hi - lo; // rank 0 builds the LPT chunk list BEFORE its scatter (needs only counts/offsets): its scattered // chunk-list stores issue before the output zero-fill / scatter traffic peaks. if (rank == 0) { // HEAD: the first chunk of each expert e < NPF (with tokens) is placed at the head of the routed list, // in expert order, so the fused kernel can L2-prefetch those experts' Wg/Wu while route_kernel runs // (DRAM is otherwise nearly idle then). Remaining chunks keep the LPT (descending size bucket) order. const bool head = (NPF > 0) && (tid < NPF) && (c > 0); const unsigned hm = __ballot_sync(0xffffffff, head); // head experts are e < NPF <= 16 -> all in warp 0: head rank / count from warp 0's ballot alone // (no cross-warp smem pass + block sync). nhead is only valid in warp 0 here; the other warps read // s_nhead (published by warp 0 together with s_end_sh) after the bucket-scan sync. static_assert(NPF <= 32, "head experts must lie in warp 0"); const int hpos = __popc(hm & ((1u << lane) - 1u)); int nhead = __popc(hm); const int nt = (c + CH - 1) / CH; const int lb = nt > 0 ? (c - (nt - 1) * CH + 15) / 16 : 0; const int ntS = (SHT(T) + CHS - 1) / CHS; // shared expert = expert NE with T tokens // Parallel LPT chunk-list build (globaltimer diag T=3296: the old per-thread contended smem atomics const int n16 = nt > 1 ? nt - 1 - (head ? 1 : 0) : 0; const bool hasl = (nt > 0) && !(head && nt == 1); // warp-aggregated bucket histogram: bucket-16 counts by a warp shuffle sum, the lb bucket via // __match_any_sync peers (one smem atomic per distinct bucket per warp) int w16 = n16;#pragma unroll for (int o = 16; o > 0; o >>= 1) w16 += __shfl_xor_sync(0xffffffff, w16, o); const int key = hasl ? lb : 0; const unsigned peers = __match_any_sync(0xffffffff, key); const int leader = __ffs(peers) - 1; if (lane == 0 && w16 > 0) atomicAdd(&bh[16], w16); if (hasl && lane == leader) atomicAdd(&bh[lb], __popc(peers)); // shared-expert chunks [0, ntS): route-independent, written in parallel (the fused kernel's // static pre-wait items never read them; dynamic decode does after griddepcontrol.wait) for (int t = tid; t < ntS; t += RT) chunk_desc[t] = make_int4(NE, tot + t * CHS, min(CHS, SHT(T) - t * CHS), t * CHS); offsets[tid] = off; counts[tid] = c; __syncthreads(); if (tid < 32) { // warp 0: bucket start positions in descending bucket order (lane L <-> bucket 16-L, L < 16) const int b = 16 - lane; const int v = (lane < 16) ? bh[b] : 0; int incl = v;#pragma unroll for (int o = 1; o < 32; o <<= 1) { const int t = __shfl_up_sync(0xffffffff, incl, o); if (lane >= o) incl += t; } if (lane < 16) bc[b] = ntS + nhead + incl - v; const int s = __shfl_sync(0xffffffff, incl, 31) + ntS + nhead; if (lane == 0) { s_end_sh = s; s_nhead = nhead; } // (DOWN128 only, requires NPF == 0): routed chunks with Nm > 128 form a prefix of the routed list const unsigned bm = __ballot_sync(0xffffffff, lane < 16 && ((b == 16) ? CH : 16 * b) > 128); int nb = (bm >> lane & 1) ? v : 0;#pragma unroll for (int o = 16; o > 0; o >>= 1) nb += __shfl_xor_sync(0xffffffff, nb, o); if (lane == 0) { *num_chunks = s; num_chunks[-1] = nb; offsets[NE] = tot; offsets[NE1] = tot + SHT(T); counts[NE] = SHT(T); } } __syncthreads(); const int s_end = s_end_sh; // end of the routed chunk list (published by warp 0 before the sync) nhead = s_nhead; // reserve positions: bucket-16 run by a warp exclusive scan + one atomic per warp; lb slot via peers { int ex = n16;#pragma unroll for (int o = 1; o < 32; o <<= 1) { const int t = __shfl_up_sync(0xffffffff, ex, o); if (lane >= o) ex += t; } ex -= n16; int b16 = 0; if (lane == 0 && w16 > 0) b16 = atomicAdd(&bc[16], w16); b16 = __shfl_sync(0xffffffff, b16, 0) + ex; int bl = 0; if (hasl && lane == leader) bl = atomicAdd(&bc[lb], __popc(peers)); bl = __shfl_sync(0xffffffff, bl, leader) + __popc(peers & ((1u << lane) - 1u)); // GU ORDER variants over the routed non-head region [F0, s) (LPT rank rp = pos - F0, n chunks): // GUO 0: pure LPT. GUO 1: "mid-first" -- the FW chunks at LPT ranks [m0, m0+FW) (mid-sized) are // rotated to the front (ranks < m0 shift back by FW), so the first wave is mid-sized chunks; rest LPT. // GUO 2: chunks with LPT rank < cut (the largest (100-TAILP)%) in expert-index (DRAM address) order, // the smallest TAILP% keep LPT order at the end. const int F0 = ntS + nhead, n = s_end - F0; auto lpt_pos = [&](int t, int& b16c) -> int { if (head && t == 0) return ntS + hpos; if (t < nt - 1) return b16c++; return bl; }; if (GUOR == 2) { const int cut = (int)(((long long)n * (100 - TAILPR)) / 100); // # of this expert's non-head chunks in the address-ordered region (LPT pos - F0 < cut), in O(1): // its full chunks occupy LPT positions b16 .. b16+n16-1 (contiguous), its last chunk sits at bl#if MCADR // MCAD (large T): ALL non-head chunks of a MULTI-chunk expert stay in the expert-address-ordered region (its // small partial chunk would otherwise sit in the LPT tail, far from its full chunk -> that expert's Wg/Wu/Wd // tiles are streamed from DRAM a second time). The m such chunks whose LPT position lies in the tail are // removed from it (positions listed in smem), the address region grows to cut + m and the remaining tail // chunks compact to [F0 + cut + m, s_end) keeping their LPT order. Off (original order) if m > MCCAP. __shared__ int mc_n; __shared__ int mc_l[MCCAP]; if (tid == 0) mc_n = 0; __syncthreads(); if (nt > 1) { int bq0 = b16; for (int t = 0; t < nt; t++) { const int pos = lpt_pos(t, bq0); if (!(head && t == 0) && pos - F0 >= cut) { const int k = atomicAdd(&mc_n, 1); if (k < MCCAP) mc_l[k] = pos; } } } __syncthreads(); const int mcm = mc_n; const bool mcon = mcm <= MCCAP; const int cntn = (mcon && nt > 1) ? nt - (head ? 1 : 0) : max(0, min(n16, F0 + cut - b16)) + ((hasl && bl - F0 < cut) ? 1 : 0);#else const bool mcon = false; const int mcm = 0; const int cntn = max(0, min(n16, F0 + cut - b16)) + ((hasl && bl - F0 < cut) ? 1 : 0);#endif // exclusive prefix of cntn over experts (= threads, expert order): warp shuffle scan + one smem // pass over the 16 warp totals (replaces the cub BlockScan and its tmp-reuse sync) int inc = cntn;#pragma unroll for (int o = 1; o < 32; o <<= 1) { const int t = __shfl_up_sync(0xffffffff, inc, o); if (lane >= o) inc += t; } if (lane == 31) hwc[tid >> 5] = inc; __syncthreads(); int exn = inc - cntn; for (int w = 0; w < (tid >> 5); w++) exn += hwc[w]; int bq = b16; for (int t = 0; t < nt; t++) { int pos = lpt_pos(t, bq); if (!(head && t == 0) && (pos - F0 < cut || (mcon && nt > 1))) pos = F0 + exn++;#if MCADR else if (mcon && !(head && t == 0)) { // remaining tail chunk: shift past the m removed slots, minus those below its own LPT position int below = 0; for (int k = 0; k < mcm; k++) below += mc_l[k] < pos; pos += mcm - below; }#endif chunk_desc[pos] = make_int4(tid, off + t * CH, min(CH, c - t * CH), t * CH); // packed decode record } } else { const int fw = min(n, FWC); const int m0 = max(0, min(n - fw, (int)(((long long)n * MIDP) / 100) - fw / 2)); int bq = b16; for (int t = 0; t < nt; t++) { int pos = lpt_pos(t, bq); if (GUOR == 1 && !(head && t == 0)) { const int rp = pos - F0; if (rp < m0) pos += fw; else if (rp < m0 + fw) pos -= m0; } chunk_desc[pos] = make_int4(tid, off + t * CH, min(CH, c - t * CH), t * CH); // packed decode record } } } } RMARK(3); // ---- phase 3: scatter routed pairs (same pair partition as phase 1), BEFORE rank 0's chunk-list // build so the fire-and-forget stores drain while rank 0 builds the list. // Staged path (slice fits the dynamic smem stage): each pair goes to its local expert-sorted slot // k = lof[e] + rank in smem, then slot k is written to global pos gb[e] + k -> consecutive threads // write consecutive positions within each expert run (coalesced), instead of 2 random 4 B stores per // pair (LSU-bound: ~1 sector/clk). Experts < NPF occupy local slots [0, lof[NPF]) and are skipped // (scattered by the early publisher). if (hi - lo <= stage_cap) { uint32_t* s_tok = rstage; uint32_t* s_we = rstage + stage_cap; __syncthreads(); // lof[] / gb[] visible#pragma unroll for (int j = 0; j < RCP; j++) { const int e = ce[j]; if (e >= NPF) { const int i = lo + 2 * (tid + (j >> 1) * RT) + (j & 1); // cached pair j (vector-load order) const int k = lof[e] + cr[j]; s_tok[k] = (uint32_t)(i / TOPK); s_we[k] = ((uint32_t)e << 16) | cw[j]; } } for (int i = lo + tid + RCP * RT; i < hi; i += RT) { const int e = (int)__ldg(&sel[i]); if (e < NPF) continue; const int k = lof[e] + pair_pos[i]; s_tok[k] = (uint32_t)(i / TOPK); s_we[k] = ((uint32_t)e << 16) | __ldg(reinterpret_cast<const unsigned short*>(rw) + i); } __syncthreads(); const int nloc = hi - lo; for (int k = (NPF > 0 ? lof[NPF] : 0) + tid; k < nloc; k += RT) { const uint32_t we = s_we[k]; const int pos = gb[we >> 16] + k; pair_token[pos] = (int)s_tok[k]; pair_w[pos] = __uint_as_float(we << 16); } } else { __syncthreads(); // offs[] / bb[] visible (block-uniform branch)#pragma unroll for (int j = 0; j < RCP; j++) { const int e = ce[j]; if (e >= NPF) { // (e < 0: past the slice; e < NPF: early publisher) const int i = lo + 2 * (tid + (j >> 1) * RT) + (j & 1); // cached pair j (vector-load order) const int pos = offs[e] + bb[e] + cr[j]; pair_token[pos] = i / TOPK; pair_w[pos] = __uint_as_float((uint32_t)cw[j] << 16); } } for (int i = lo + tid + RCP * RT; i < hi; i += RT) { const int e = (int)__ldg(&sel[i]); if (e < NPF) continue; // experts < NPF scattered by the early publisher const int pos = offs[e] + bb[e] + pair_pos[i]; pair_token[pos] = i / TOPK; pair_w[pos] = __bfloat162float(rw[i]); } } RMARK(5); __syncthreads(); RMARK(4); if (!RDIST) cluster_wait_acquire(); // no CTA exits while a peer may still read its lc[] through DSMEM RMARK(6); // RFL: all ranks' scatters + rank 0's chunk list done -> release the routing flag early[ZOFF-2] (consumed by the // fused kernel's small-T routed items instead of the route-grid completion; same pattern as the early head flag)#if RFL && !RDIST __threadfence(); cluster_arrive_release(); cluster_wait_acquire(); if (rank == 0 && tid == 0) { __threadfence(); asm volatile("st.release.gpu.global.s32 [%0], %1;" ::"l"(early + (ZOFF - 2)), "r"(1) : "memory"); }#endif // (per-chunk H-ready counters are zeroed by the host memset BEFORE this grid: the fused kernel's // shared-expert gate/up items increment them before waiting on this grid.)}12345678910# Audio encoder varlen attention with chunking backward (L2 014)
Backward of chunked variable-length self-attention in an audio encoder: grads for the hidden states and for the Q, K, V and output weights and biases.
- Language: CUDA C++. Entry point: `main.cpp::run`. Files: 6 (11,073 lines).- Idea: Attention backward per (chunk, head) in custom tensor-core kernels picked by chunk length; projection grads via cuBLASLt or a persistent 2-SM tcgen05 GEMM; CUDA graph replay.- Result: SOL score 0.946; speedup 13.42x over the benchmark's baseline (geometric mean). Public SOL-ExecBench results as of 2026-11-11.- Origin: edited after the search by Claude agents.- Comments edited; the code that runs is identical to the scored submission.- Generated by Claude via Amazon Bedrock. Verified on the SOL-ExecBench site; not production-ready.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384{ "board": "L2", "id": "014_audio_encoder_varlen_attention_with_chunking_backward", "name": "Audio encoder varlen attention with chunking backward", "language": "CUDA C++", "files": [ { "path": "src/fastlaunch.h", "lines": 54, "bytes": 2897 }, { "path": "src/gemm.cu", "lines": 2891, "bytes": 189830 }, { "path": "src/gemm.h", "lines": 17, "bytes": 1857 }, { "path": "src/kernel.cu", "lines": 6842, "bytes": 379349 }, { "path": "src/kernel.h", "lines": 71, "bytes": 5789 }, { "path": "src/main.cpp", "lines": 1198, "bytes": 73803 } ], "origin": "edited after the search by Claude agents", "result": { "public": true, "sol_score": 0.945714, "speedup": 13.4225, "board_row": true, "note": "the row the public SOL-ExecBench board shows for this problem, as of 2026-11-11" }, "idea": "Attention backward per (chunk, head) in custom tensor-core kernels picked by chunk length; projection grads via cuBLASLt or a persistent 2-SM tcgen05 GEMM; CUDA graph replay.", "spec": { "languages": [ "cuda_cpp" ], "target_hardware": [ "B200", "LOCAL" ], "entry_point": "main.cpp::run", "binding": "torch", "destination_passing_style": false, "dependencies": [], "compile_options": { "cuda_cflags": [ "-std=c++17", "-O3", "-gencode=arch=compute_100a,code=sm_100a", "-Xptxas", "-O3", "-Xptxas", "--allow-expensive-optimizations=true", "-Xptxas", "-warn-spills" ], "cflags": [ "-O3" ] }, "sources": [ "kernel.h", "gemm.h", "fastlaunch.h", "kernel.cu", "gemm.cu", "main.cpp" ] }}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354#pragma once// FAST HOST LAUNCH: drop-in replacement for cudaLaunchKernelEx on the eager hot path.// The kernel's CUfunction is resolved ONCE per kernel (cudaGetFuncBySymbol, cached in a small linear table), the// runtime launch config / attribute array is copied verbatim into a CUlaunchConfig (binary-compatible attribute// layout, static_asserted), kernel parameters are packed into a typed tuple (exact kernel parameter types) and the// launch goes straight through the driver (cuLaunchKernelEx): no per-call runtime function lookup / argument// marshalling. Works inside stream capture. If the driver launch path is unavailable the runtime launch is used.#include <cuda.h>#include <cuda_runtime.h>#include <tuple>#include <utility>#include <type_traits>#include <cstring>
static_assert(sizeof(CUlaunchAttribute) == sizeof(cudaLaunchAttribute), "launch attribute layout");
struct FlFn { const void* k; CUfunction f; };static inline CUfunction fl_func(const void* k) { static FlFn tab[128]; static int n = 0; for (int i = 0; i < n; i++) if (tab[i].k == k) return tab[i].f; cudaFunction_t f = nullptr; if (cudaGetFuncBySymbol(&f, k) != cudaSuccess) { cudaGetLastError(); f = nullptr; } if (n < 128) { tab[n].k = k; tab[n].f = (CUfunction)f; n++; } return (CUfunction)f;}template <class Tup, size_t... I>static inline void fl_pack(Tup& t, void** a, std::index_sequence<I...>) { ((a[I] = const_cast<void*>(static_cast<const void*>(&std::get<I>(t)))), ...);}template <class... KA, class... A>static inline cudaError_t fl_launch(const cudaLaunchConfig_t* cfg, void (*k)(KA...), const A&... a) { CUfunction f = fl_func(reinterpret_cast<const void*>(k)); if (!f) return cudaLaunchKernelEx(cfg, k, a...); std::tuple<std::remove_cv_t<KA>...> t(a...); void* args[sizeof...(KA) > 0 ? sizeof...(KA) : 1]; fl_pack(t, args, std::index_sequence_for<KA...>{}); CUlaunchAttribute at[8]; const int na = (int)(cfg->numAttrs < 8 ? cfg->numAttrs : 8); if (na) std::memcpy(at, cfg->attrs, na * sizeof(CUlaunchAttribute)); CUlaunchConfig c; c.gridDimX = cfg->gridDim.x; c.gridDimY = cfg->gridDim.y; c.gridDimZ = cfg->gridDim.z; c.blockDimX = cfg->blockDim.x; c.blockDimY = cfg->blockDim.y; c.blockDimZ = cfg->blockDim.z; c.sharedMemBytes = (unsigned)cfg->dynamicSmemBytes; c.hStream = (CUstream)cfg->stream; c.attrs = na ? at : nullptr; c.numAttrs = (unsigned)na; return cuLaunchKernelEx(&c, f, args, nullptr) == CUDA_SUCCESS ? cudaSuccess : cudaErrorLaunchFailure;}// plain (no attribute) launch helper replacing <<<grid, block, 0, st>>>template <class... KA, class... A>static inline void fl_plain(dim3 g, dim3 b, cudaStream_t st, void (*k)(KA...), const A&... a) { cudaLaunchConfig_t cfg = {}; cfg.gridDim = g; cfg.blockDim = b; cfg.dynamicSmemBytes = 0; cfg.stream = st; cfg.attrs = nullptr; cfg.numAttrs = 0; fl_launch(&cfg, k, a...);}1234567891011121314151617#pragma once#include <cuda_runtime.h>#include <cuda_bf16.h>// Fused post-attention GEMM (gemm.cu): dX = dQKV @ [Wq;Wk;Wv] (read in place, no Wcat copy), dWqkv = dQKV^T @ X, dWo|outbias = dO^T @ [O|1] in ONE// persistent 2-SM (cta_group::2) tcgen05 launch. xcnt (post_gemm_counter_bytes(): per split-tile flags) must be zero// on entry and is left zero. force_ks = schedule mode: 1 = whole tiles (LPT), 2 = stream-K; 3 / 4 = same with 256x128 tiles; 5..8 = 1..4 with BK = 128 pipeline stages; 9 / 10 = 3 / 4 with 4 BK=128 stages (narrow-only ring); 14 = mixed-width LPT (BK=128); 15 = narrow LPT with split-K dX pieces (stream-K fp32 slots, 4 x BK=128 stages); +20 = without dWo tiles; 60..63 = WIDE 2-SM 256x256 plan with every dX tile cut into 6 / 3 / 12 / 4 fp32 k-pieces + dx_reduce. Returns false if it could// not launch (no plan during capture / tensor map failure / invalid mode).size_t post_gemm_counter_bytes();size_t post_gemm_scratch_bytes(); // xacc: fp32 accumulation slots of stream-K split tiles (scratch, no init needed)bool post_gemm_prepare(int S, int force_ks);bool post_gemm_launch(const __nv_bfloat16* dQKV, const __nv_bfloat16* Wq, const __nv_bfloat16* Wk, const __nv_bfloat16* Wv, const __nv_bfloat16* X, const __nv_bfloat16* dO, const __nv_bfloat16* Obuf, __nv_bfloat16* dX, __nv_bfloat16* dWqkv, __nv_bfloat16* dWo, int* xcnt, float* xacc, int S, int force_ks, cudaStream_t st, __nv_bfloat16* bias, float* kacc, const __nv_bfloat16* dQKVlo = nullptr);// force_ks >= 100 = PRECISE plan: dX = [dQKV | dQKVlo] @ [W; W] (K = 7680; short-chunk shapes), needs dQKVlo// bias = grad q/k/v bias [3840] bf16 (written by the dWqkv ones-column tail tiles); kacc = fp32 analytic k-bias// accumulator [1280] from attention (cast into bias[1280,2560) and re-zeroed)1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071#pragma once#include <cuda_runtime.h>#include <cuda_bf16.h>// O buffer row pitch (bf16 elements): 1344 = 21 x 64 -> 2688 B rows, 128 B aligned (was 1288 = 2576 B rows: odd rows// started 16 B into a 32 B sector, so every TMA {64,64} box row of the dWo / bias-tail B operand straddled an extra sector).// cols [0,1280) = O, col 1280 = 1.0 (ones column), cols 1281..1343 = 0.#define O_PITCH 1344// dWo output (grad_out_weight view + grad_out_bias col 1280) row pitch 1344 bf16 = 2688 B (128B-aligned; was 1288 =// 2576 B rows -> the dWo TMA store boxes straddled an extra 32B sector on odd rows)#define DWO_PITCH 1344// Launchers for the custom varlen flash-attention backward kernels (kernel.cu)// Precision scheme: attention-internal computed fp32 operands that feed a bf16 tensor-core product are split// into hi = bf16(x), lo = bf16(x - hi) ("bf16x2", ~16 mantissa bits) where needed (P in fwd PV, P in dV,// dO_attn, dS in dQ). dS in dK uses hi only: the dK *bias* (an exactly-cancelling column sum) is computed// analytically from fp32 values instead: sum_kv dK[kv][d] = scale * sum_q (sum_kv dS[q][kv]) Q[q][d].// GEMM operands O, dQ, dK, dV are plain bf16 (no lo rows); exact bf16 inputs are never split.// bacc (fp32, 5*1280): [0,1280) dQ bias, [1280,2560) dK bias, [2560,3840) dV bias, [3840,5120) dO bias.// bacc[5*1280] (uint) = attn last-CTA ticket counter. Self-cleaning: the last attn CTA (or final if nch==0) re-zeroes bacc, so the persistent workspace is zero on entry (no memset).// Attention: ONE fused PERSISTENT kernel, grid = min(#SMs, nch*H) CTAs of 512 threads (16 warps), each looping over// (chunk, head) work items with a static stride schedule; the next item's Q/K/V/dAO are cp.async-prefetched while// the current one computes.// Chunks <= 128 rows: everything (O, delta, dQ, dK, dV) from smem-resident Q/K/V/dO in a single pass.// Chunks > 128 rows: generic tiled path (forward+dQ per q tile, then dK/dV per kv tile) executed serially by the CTA.// colsum launch also builds Wcat (only when copy_w: weights not already one contiguous [3840,1280] block) = [Wq; Wk; Wv] (bf16 [3840,1280]) so dX is ONE GEMM with bf16 output.void launch_colsum(const __nv_bfloat16* dO, int S, float* bacc, const __nv_bfloat16* Wq, const __nv_bfloat16* Wk, const __nv_bfloat16* Wv, __nv_bfloat16* Wcat, bool copy_w, cudaStream_t st);void attn_bwd_init();void launch_attn_fused(const __nv_bfloat16* Q, const __nv_bfloat16* K, const __nv_bfloat16* V, const float* dAO, const int* cu, int nch, int S, int H, __nv_bfloat16* O, float* lse, float* delta, __nv_bfloat16* dQKV, float* bacc, __nv_bfloat16* bias, cudaStream_t st);void launch_final(float* bacc, __nv_bfloat16* bias, cudaStream_t st);// forward-only O = softmax(QK^T*scale)V into the [S,1288] O buffer (side graph branch, low-parallelism shapes only)void launch_attn_fwd(const __nv_bfloat16* Q, const __nv_bfloat16* K, const __nv_bfloat16* V, const int* cu, int nch, int S, int H, __nv_bfloat16* O, cudaStream_t st);// true when launch_attn_fused uses the split path (nch*H*2 <= #SMs): attn leaves SMs idlebool attn_is_split(int nch, int H);// split-path CTAs-per-item override (0 = default min(4, #SMs/items)); captured into graphs at enqueue timevoid set_split_G(int g);// largest single-wave split factor (capped at 8) for nch x H itemsint max_split_G(int nch, int H);// non-split path kernel choice (0 = persistent attn_fused, 1 = attn_small: 1 item / 128-thread CTA, 3 CTAs/SM);// captured into graphs at enqueue timevoid set_attn_small(int v);// q/v bias (column sums of the bf16 dQKV) + k bias (cast + re-zero of the fp32 analytic accumulator// bacc[1280,2560)) for the cuBLAS post-section path; the fused tcgen05 post GEMM does the same in its dWqkv// ones-column tail tilesvoid launch_qkv_bias(const __nv_bfloat16* dQKV, int S, __nv_bfloat16* bias, float* bacc, cudaStream_t st);// persistent attn_fused tail split (tail items shared by up to 4 CTAs via split_item); captured at enqueue timevoid set_tail_split(int v);// true when the tail split would change the attn_fused schedule for this shape (non-split, non-mid, small tail)bool attn_tail_possible(int nch, int S, int H);// PRECISE mode (short chunks, avg chunk rows <= 48): non-null lo = launch_attn_fused runs attn_small<LO> which also// stores the bf16 lo residual of dQ / dK / dV into lo [S,3840]; the post GEMM then uses K = 7680 for dX. Captured at enqueue.void set_prec_lo(__nv_bfloat16* lo);
// attn_fwd persistent grid cap = #SMs / div, launch priority (1 = highest); captured at enqueue timevoid set_fwd_cfg(int div, int prio);// half-head forward branch: attn_fwd computes O heads [0, hf) only (0 = all); attn_small / attn_mid skip O for// heads < h0. attn_oh0_ok: the shape's launch path honours h0. Captured at enqueue time.void set_fwd_heads(int hf);void set_attn_oh0(int h0);bool attn_oh0_ok(int nch, int S, int H, int small);
// L2 prefetch of n buffers (ptr, bytes) via cp.async.bulk.prefetch.L2 (side-stream hint kernel)void launch_l2_prefetch(const void* const* p, const size_t* nb, int n, cudaStream_t st, int grid = 32, int qS = 0, int qH = 0, const void* cu = nullptr, int cub = 0, const void* x1 = nullptr, int x1b = 0, const void* x2 = nullptr, int x2b = 0, int qrb = 0); // qrb: rows per Q/K/V prefetch unit (0 = 32)
// FUSED dAO (single chunk, S <= 128): non-null dO = launch_attn_fused computes dAO = dO @ Wo inside the attention// clusters (tcgen05) and no dAO GEMM must be enqueued; captured at enqueue time. attn_fdao_ok: the shape supports it.void set_fused_dao(const __nv_bfloat16* dO, const __nv_bfloat16* Wo);bool attn_fdao_ok(int nch, int S, int H);kernels/L2/007_multimodal_rotary_embedding_attention/src/kernel.hAdded+106
kernels/L2/007_multimodal_rotary_embedding_attention/src/main.cppAdded+1202
kernels/L2/008_moe_sparse_routing_and_dispatch/README.mdAdded+11
kernels/L2/008_moe_sparse_routing_and_dispatch/kernel.jsonAdded+65
kernels/L2/008_moe_sparse_routing_and_dispatch/src/kernel.cuAdded
kernels/L2/008_moe_sparse_routing_and_dispatch/src/kernel.hAdded+12
kernels/L2/008_moe_sparse_routing_and_dispatch/src/main.cppAdded+71
kernels/L2/008_moe_sparse_routing_and_dispatch/src/probe_cfg.hAdded+2
kernels/L2/009_decoder_layer_with_residual_connections/README.mdAdded+11
kernels/L2/009_decoder_layer_with_residual_connections/kernel.jsonAdded+78
kernels/L2/009_decoder_layer_with_residual_connections/src/fa4.cuAdded+1462
kernels/L2/009_decoder_layer_with_residual_connections/src/kernel.cuAdded
kernels/L2/009_decoder_layer_with_residual_connections/src/kernel.hAdded+106
kernels/L2/009_decoder_layer_with_residual_connections/src/main.cppAdded+292
kernels/L2/009_decoder_layer_with_residual_connections/src/side_steal.cuhAdded+300
kernels/L2/009_decoder_layer_with_residual_connections/src/ws_probe.cuAdded+162
kernels/L2/010_moe_expert_computation_with_weighted_accumulation/README.mdAdded+11
kernels/L2/010_moe_expert_computation_with_weighted_accumulation/kernel.jsonAdded+83
kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/fast_path.cuAdded
kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/g12fused.cuAdded
kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/graph_launch.hAdded+50
kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/kernel.cuAdded+997
kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/kernel.hAdded+4
kernels/L2/010_moe_expert_computation_with_weighted_accumulation/src/main.cppAdded+8
kernels/L2/011_moe_sparse_routing_and_dispatch_backward/README.mdAdded+11
kernels/L2/011_moe_sparse_routing_and_dispatch_backward/kernel.jsonAdded+78
kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/dg_xdyn.cuhAdded+374
kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/kernel.cuAdded
kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/main.cppAdded+482
kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/route_b.cuhAdded+318
kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/route_c.cuhAdded+778
kernels/L2/011_moe_sparse_routing_and_dispatch_backward/src/route_v.cuhAdded+107
kernels/L2/012_moe_expert_batched_execution_with_capacity_factor/README.mdAdded+10
kernels/L2/012_moe_expert_batched_execution_with_capacity_factor/kernel.jsonAdded+61
kernels/L2/012_moe_expert_batched_execution_with_capacity_factor/src/kernel.cuAdded
kernels/L2/012_moe_expert_batched_execution_with_capacity_factor/src/kernel.hAdded+12
kernels/L2/012_moe_expert_batched_execution_with_capacity_factor/src/main.cppAdded+76
kernels/L2/013_expert_weighted_aggregation_with_shared_expert/README.mdAdded+11
kernels/L2/013_expert_weighted_aggregation_with_shared_expert/kernel.jsonAdded+164
kernels/L2/013_expert_weighted_aggregation_with_shared_expert/src/fused_body.cuhAdded
kernels/L2/013_expert_weighted_aggregation_with_shared_expert/src/kernel.cuAdded+1678
kernels/L2/013_expert_weighted_aggregation_with_shared_expert/src/main.cppAdded+6
kernels/L2/013_expert_weighted_aggregation_with_shared_expert/src/route_body.cuhAdded+707
kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/README.mdAdded+10
kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/kernel.jsonAdded+84
kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/src/fastlaunch.hAdded+54
kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/src/gemm.cuAdded
kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/src/gemm.hAdded+17
kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/src/kernel.cuAdded
kernels/L2/014_audio_encoder_varlen_attention_with_chunking_backward/src/kernel.hAdded+71