File size: 32,987 Bytes
63d5e8f
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
// Host glue for the NVFP4 linear layer.
//  1) fused_quant (one grid-barrier kernel, kernel.cu): global max|x| (lightweight epoch-counter
//     grid barrier fused with an atomicMax amax slot), x -> packed E2M1 + E4M3 block scales
//     (blocked 128x4 layout), alpha = x_gd * w_gd in device memory (no host sync), and -- for the
//     CUTLASS GEMM -- the weight-scale re-layout into the (padded) blocked format.
//  2) GEMM, chosen per shape by a STATIC table keyed by Mp (kPins, no runtime timing selection):
//     * mode 3 (Mp 128): custom SWAP-AB tcgen05 NVFP4 GEMM (weight = MMA M, tokens = MMA N = 128,
//       KS = 2 sub-steps per stage, S = 2 split-K over a (1,1,2) cluster, transposed epilogue);
//     * mode 5 (Mp >= 256): CUTLASS 4.x sm100 block-scaled NVFP4 GEMM (cutlass_gemm_{b,h}.cu:
//       2SM 256x112 / 256x224 tiles), launched with PDL behind the quant kernel.
// Host-overhead reduction: per-shape plans/scratch created once (heap, never destructed);
// per (pointers, M, w_gd, stream) key the whole sequence is captured into a CUDA graph.
#include <torch/extension.h>
#include <torch/csrc/autograd/python_variable.h>
#include <ATen/cuda/EmptyTensor.h>
#include <ATen/cuda/CUDAContext.h>
#include <c10/cuda/CUDACachingAllocator.h>
#include <c10/core/StorageImpl.h>
#include <cuda.h>
#include <unordered_map>
#include <vector>
#include <utility>
#include <cstring>
#include "kernel.h"
#include "cutlass_api.h"
#include <algorithm>
#include <cstdio>
#include <string>
#include <cstdint>

static constexpr size_t kWorkspace = 32u << 20;

struct ShapePlan {
  bool tuned;
  int mode;      // 3 = custom swap-AB tcgen05 GEMM, 5 = CUTLASS GEMM
  int swbx;      // swap-AB token tile (128)
  int swks;      // swap-AB K=256 sub-steps per pipeline stage (2)
  int splitk;    // swap-AB split count
  at::Tensor* aux;      // [alpha, beta, pad, pad, sync_ws ...], zero-init
  at::Tensor* wsf_blk;  // weight scales, blocked (padded) layout (CUTLASS path)
  at::Tensor* xq;       // packed E2M1 x (Mp x K/2)
  at::Tensor* xsf_blk;  // x scales, blocked layout
  GemmOpts ccfg;        // mode 5: CUTLASS config + PDL flag
  bool cpdl;
  at::Tensor* cws;      // CUTLASS workspace (grown on demand at the first call only)
  size_t cws_bytes;
  at::Tensor* red_ws;   // swap-AB split-K fp32 partial exchange
  int qcarve;           // quant kernel carveout instantiation: -1 default per variant, 0 default
                        // L1/smem split, 1 max smem carveout
  // qearly: quant triggers PDL launch_dependents at kernel ENTRY even with do_wsf (CUTLASS mode 5
  // only: its producer warp's griddepcontrol.wait precedes every A/SFA/SFB TMA load, and the
  // epilogue reads alpha only after its own griddepcontrol.wait).
  bool qearly;
  int qipt;  // register-resident quant IPT override (0 default, 7 = IPT 7, 21 = IPT 2 x 128 thr)
  bool qbo;
  int swpf;  // swap-AB cold-L2 weight prefetch share of K (%), 0 = off
  int qpfb;  // weight-row prefix bytes of the qpf prefetch (default 1024)
  bool qpf;  // quant prefetches the fp4 weight prefix into L2 (CUTLASS mode 5 pins)
  // pass-1 L2 policy of the persistent quant: evict_last budget p1tail MB (-1 default) +
  // evict_first on the other pass-1 loads (p1first)
  int p1tail;
  bool p1first;
  int cuthint;  // CUTLASS mainloop A/B TMA L2 cache-hint code (g_cut_hint), 0 = normal
  int cutsms;   // CUTLASS persistent-scheduler SM budget (g_cut_sms), 0 = all SMs
  int p2bits;   // persistent-quant pass-2 bits (see kernel.cu fused_quant_kernel al32i)
  bool qdbo;    // register-resident quant: delayed-backoff epoch grid barrier (Mp 256 / 512)
  bool qslot;   // register-resident quant: fence-free slot grid barrier (Mp 256 IPT2x128 SP52 path)
  int qx;       // register-resident quant extra late bits (probe only: 4 PDL after arrival, 8 batched relayout)
  int chq0;     // chunk 0 quant CTAs per SM (0 = default 2)
  bool chser;   // probe: all chunk quants on the main stream (no overlap)
  int nchunk;   // > 1: chunked large-M pipeline (amax pre-pass, chunk quant overlapped with chunk GEMMs)
};

static ShapePlan* get_plan(int64_t Mp, int64_t N, int64_t K, const at::TensorOptions& opt) {
  static auto& cache = *new std::unordered_map<uint64_t, ShapePlan*>();
  uint64_t key = ((uint64_t)Mp << 40) ^ ((uint64_t)N << 20) ^ (uint64_t)K;
  auto it = cache.find(key);
  if (it != cache.end()) return it->second;
  ShapePlan* p = new ShapePlan();
  auto u8 = opt.dtype(torch::kUInt8);
  int64_t sfk = K / 16;
  // NOTE: the device allocations below keep the SAME order and sizes as the former multi-backend
  // plan (incl. buffers of removed backends, never touched now) so the caching allocator's segment
  // layout -- and with it the placement of the per-call output tensors -- is unchanged.
  p->aux = new at::Tensor(torch::zeros({4 + kMaxPartials}, opt.dtype(torch::kFloat32)));
  // weight scales, blocked: sized for the PADDED 256x224 / 256x112-tile layouts (virtual N > N);
  // zero-initialised once -> the never-written padding rows are 0
  p->wsf_blk = new at::Tensor(torch::zeros({std::max<int64_t>(std::max<int64_t>(N, (N + 223) / 224 * 256), (N + 111) / 112 * 128) * sfk}, u8));
  p->xq = new at::Tensor(torch::empty({Mp, K / 2}, u8));
  p->xsf_blk = new at::Tensor(torch::empty({Mp * sfk}, u8));
  new at::Tensor(torch::empty({(int64_t)kWorkspace}, u8));  // (former cuBLASLt workspace, layout only)
  // split-K partial-exchange workspace: the former sizing (max over the custom-GEMM candidates)
  int smax = 1;
  if (Mp <= 1024 && K % 256 == 0 && N % 256 == 0) {
    const int64_t tiles = (Mp / 128) * (N / 256);
    const int kt = (int)(K / 256);
    for (int sk : {1, 2, 4})
      if (kt % sk == 0 && (sk == 1 || tiles * sk <= 296)) smax = std::max(smax, sk);
  }
  if (Mp <= 1024 && K % 256 == 0 && N % 128 == 0) {
    const int kt = (int)(K / 256);
    for (int bx : {128, 256}) {
      if (Mp % bx) continue;
      const int64_t tiles = (N / 128) * (Mp / bx);
      for (int sk : {1, 2, 4})
        if (kt % sk == 0 && bx / sk >= 32 && (sk == 1 || tiles * sk <= 296)) smax = std::max(smax, sk);
    }
  }
  int64_t red_floats = smax > 1 ? Mp * N * smax : 1;
  if (Mp <= 1024 && K % 256 == 0 && N % 128 == 0) {
    int dev = 0, sms = 0;
    cudaGetDevice(&dev);
    cudaDeviceGetAttribute(&sms, cudaDevAttrMultiProcessorCount, dev);
    red_floats = std::max<int64_t>(red_floats, (int64_t)sms * 128 * 256);
  }
  new at::Tensor(torch::zeros({(N / 128) * (Mp / 128) + 1}, opt.dtype(torch::kInt32)));  // layout only
  new at::Tensor(torch::zeros({2 + Mp / 256 + 2}, opt.dtype(torch::kInt32)));            // layout only
  p->red_ws = new at::Tensor(torch::empty({red_floats}, opt.dtype(torch::kFloat32)));
  new at::Tensor(torch::zeros({N}, opt.dtype(torch::kFloat32)));                          // layout only
  p->qcarve = -1;
  p->qearly = false;
  p->qipt = 0;
  p->qbo = false;
  p->swpf = 0;
  p->qpf = false;
  p->qpfb = 1024;
  p->p1tail = -1;
  p->p1first = false;
  p->p2bits = 0;
  p->qx = 0;
  p->qslot = false;
  p->qdbo = false;
  p->nchunk = 0;
  p->chq0 = 0;
  p->chser = false;
  p->cuthint = 0;
  p->cutsms = 0;
  p->mode = 5;
  p->splitk = 1;
  p->swbx = 128;
  p->swks = 1;
  p->ccfg = GemmOpts{0, 0, 0, 0, 1};
  p->cpdl = false;
  p->cws = nullptr;
  p->cws_bytes = 0;
  p->tuned = false;
  cache[key] = p;
  return p;
}

void set_p2frac(int b);
void set_res_bo(bool on);
void set_res_xbits(int b);
void set_res_slot(bool on);
void set_res_dbo(bool on);
// enqueue the quant kernel (do_wsf: also re-layout the weight scales for the CUTLASS GEMM)
static void enqueue_quant(ShapePlan* p, const void* x, int M, int Mp, int K, int N, const void* wsf,
                          float w_gd, bool do_wsf, cudaStream_t s) {
  float* ab = p->aux->data_ptr<float>();
  set_tail_force_mb(p->p1tail);
  set_p1_first(p->p1first);
  set_p2frac(p->p2bits);
  set_res_bo(p->qbo);
  set_res_xbits(p->qx);
  set_res_slot(p->qslot);
  set_res_dbo(p->qdbo);
  launch_fused_quant(x, M, Mp, K, (const uint8_t*)wsf, p->wsf_blk->data_ptr<uint8_t>(), N, w_gd,
                     p->xq->data_ptr<uint8_t>(), p->xsf_blk->data_ptr<uint8_t>(), ab + 4, ab,
                     do_wsf, /*late_pdl=*/do_wsf && !p->qearly, p->qcarve, s, /*avec=*/nullptr,
                     p->qipt);
  set_p2frac(0);
  set_res_bo(false);
  set_res_xbits(0);
  set_res_slot(false);
  set_res_dbo(false);
  set_tail_force_mb(-1);
  set_p1_first(false);
}
static bool enqueue_swap_gemm(ShapePlan* p, int Mp, int K, int N, const void* wq,
                              const void* wsf, void* out, int S, int BX, int KS, cudaStream_t s) {
  set_swap_l2_prefetch(p->swpf);
  const bool ok = launch_nvfp4_gemm_swap(p->xq->data_ptr(), p->xsf_blk->data_ptr(), wq, wsf,
                                p->aux->data_ptr<float>(), out, p->red_ws->data_ptr<float>(), Mp,
                                N, K, S, BX, KS, s);
  return ok;
}
// CUTLASS NVFP4 GEMM over all Mp rows of the quantized x. Workspace grows on demand (heap, never
// freed; only at the first call of a shape, before any graph capture). Returns 0 on success.
static int enqueue_cutlass(ShapePlan* p, int Mp, int K, int N, const void* wq, void* out,
                           const GemmOpts& cfg, bool pdl, cudaStream_t s) {
  const float* ab = p->aux->data_ptr<float>();
  const uint8_t* xb = p->xq->data_ptr<uint8_t>();
  const uint8_t* sb = p->xsf_blk->data_ptr<uint8_t>();
  __nv_bfloat16* ob = (__nv_bfloat16*)out;
  size_t need = 0;
  int rc = cutlass_gemm_run(cfg, xb, sb, wq, p->wsf_blk->data_ptr(), ab, ob, Mp, N, K,
                            p->cws ? p->cws->data_ptr() : nullptr, p->cws_bytes, &need, pdl, s);
  if (rc == 2) {
    p->cws = new at::Tensor(torch::empty({(int64_t)need + 256}, p->xq->options()));
    p->cws_bytes = need + 256;
    rc = cutlass_gemm_run(cfg, xb, sb, wq, p->wsf_blk->data_ptr(), ab, ob, Mp, N, K,
                          p->cws->data_ptr(), p->cws_bytes, &need, pdl, s);
  }
  return rc;
}
static void enqueue_chunked(ShapePlan* p, const void* x, int M, int Mp, int K, int N, const void* wq,
                            const void* wsf, float w_gd, void* out, cudaStream_t s) {
  static cudaStream_t s2 = nullptr;
  static cudaEvent_t ev[9];
  if (!s2) {
    cudaStreamCreateWithFlags(&s2, cudaStreamNonBlocking);
    for (auto& e : ev) cudaEventCreateWithFlags(&e, cudaEventDisableTiming);
  }
  float* ab = p->aux->data_ptr<float>();
  uint8_t* xq = p->xq->data_ptr<uint8_t>();
  uint8_t* xsf = p->xsf_blk->data_ptr<uint8_t>();
  const int nch = std::min(p->nchunk, 8);
  const int rows = ((Mp + nch - 1) / nch + 255) / 256 * 256;
  int r0s[8], r1s[8], nc = 0;
  for (int c = 0; c < nch; ++c) {  // descending row chunks
    const int r1 = Mp - c * rows, r0 = std::max(0, r1 - rows);
    if (r1 <= 0) break;
    r0s[nc] = r0; r1s[nc] = r1; ++nc;
  }
  set_tail_force_mb(p->p1tail);
  set_p1_first(p->p1first);
  launch_quant_amax(x, M, Mp, K, (const uint8_t*)wsf, p->wsf_blk->data_ptr<uint8_t>(), N, w_gd, xq,
                    xsf, ab + 4, ab, ab + 2, s);
  set_tail_force_mb(-1);
  set_p1_first(false);
  launch_quant_rows(x, M, r0s[0], r1s[0], K, ab + 2, xq, xsf, s, p->chq0);
  if (nc > 1 && p->chser) {
    for (int c = 1; c < nc; ++c) launch_quant_rows(x, M, r0s[c], r1s[c], K, ab + 2, xq, xsf, s, p->chq0);
  } else if (nc > 1) {
    cudaEventRecord(ev[0], s);
    cudaStreamWaitEvent(s2, ev[0], 0);
    for (int c = 1; c < nc; ++c) {
      launch_quant_rows(x, M, r0s[c], r1s[c], K, ab + 2, xq, xsf, s2);
      cudaEventRecord(ev[c], s2);
    }
  }
  g_cut_hint = p->cuthint;
  g_cut_sms = p->cutsms;
  const float* abc = ab;
  for (int c = 0; c < nc; ++c) {
    if (c > 0 && !p->chser) cudaStreamWaitEvent(s, ev[c], 0);
    const int r0 = r0s[c], mr = r1s[c] - r0;
    size_t need = 0;
    const uint8_t* xa = xq + (size_t)r0 * (K / 2);
    const uint8_t* sa = xsf + (size_t)r0 * (K / 16);
    __nv_bfloat16* ob = (__nv_bfloat16*)out + (size_t)r0 * N;
    int rc = cutlass_gemm_run(p->ccfg, xa, sa, wq, p->wsf_blk->data_ptr(), abc, ob, mr, N, K,
                              p->cws ? p->cws->data_ptr() : nullptr, p->cws_bytes, &need, p->cpdl, s);
    if (rc == 2) {
      p->cws = new at::Tensor(torch::empty({(int64_t)need + 256}, p->xq->options()));
      p->cws_bytes = need + 256;
      rc = cutlass_gemm_run(p->ccfg, xa, sa, wq, p->wsf_blk->data_ptr(), abc, ob, mr, N, K,
                            p->cws->data_ptr(), p->cws_bytes, &need, p->cpdl, s);
    }
    TORCH_CHECK(rc == 0, "CUTLASS chunk GEMM launch failed");
  }
  g_cut_hint = 0;
  g_cut_sms = 0;
}
static void enqueue(ShapePlan* p, const void* x, int M, int Mp, int K, int N, const void* wq,
                    const void* wsf, float w_gd, void* out, cudaStream_t s) {
  if (p->mode == 6) {  // weight-stationary custom tcgen05 GEMM (Mp 128 pin)
    enqueue_quant(p, x, M, Mp, K, N, wsf, w_gd, false, s);
    TORCH_CHECK(launch_nvfp4_gemm_ws(p->xq->data_ptr(), p->xsf_blk->data_ptr(), wq, wsf,
                                     p->aux->data_ptr<float>(), out, Mp, N, K, s),
                "custom weight-stationary GEMM launch failed");
    return;
  }
  if (p->mode == 3) {
    enqueue_quant(p, x, M, Mp, K, N, wsf, w_gd, false, s);
    TORCH_CHECK(enqueue_swap_gemm(p, Mp, K, N, wq, wsf, out, p->splitk, p->swbx, p->swks, s),
                "custom swap-AB GEMM launch failed");
    return;
  }
  // mode 5: quant (+ padded weight-scale re-layout) -> PDL CUTLASS GEMM
  set_quant_l2_prefetch(p->qpf ? wq : nullptr, (long long)N * (K / 2));
  set_quant_pf_prefix(p->qpfb);
  set_wsf_pad(kern_n224(p->ccfg.kern) ? 1 : (kern_n112(p->ccfg.kern) ? 2 : 0));
  if (p->nchunk > 1) {
    enqueue_chunked(p, x, M, Mp, K, N, wq, wsf, w_gd, out, s);
    set_wsf_pad(0);
    set_quant_pf_prefix(1024);
    set_quant_l2_prefetch(nullptr, 0);
    return;
  }
  set_quant_l2_demote((p->p2bits & 65536) ? wq : nullptr, (long long)N * (K / 2));
  enqueue_quant(p, x, M, Mp, K, N, wsf, w_gd, true, s);
  set_quant_l2_demote(nullptr, 0);
  set_wsf_pad(0);
  set_quant_pf_prefix(1024);
  set_quant_l2_prefetch(nullptr, 0);
  g_cut_hint = p->cuthint;
  g_cut_sms = p->cutsms;
  const int crc = enqueue_cutlass(p, Mp, K, N, wq, out, p->ccfg, p->cpdl, s);
  g_cut_hint = 0;
  g_cut_sms = 0;
  TORCH_CHECK(crc == 0, "CUTLASS GEMM launch failed");
}

struct Pin { int Mp, mode, S, bx, ks; GemmOpts c; bool pdl; int qcv; };
static const Pin kPins[] = {
    // mode 6: weight-stationary GEMM (147 CTAs x 56 weight rows, full K; replaced swap-AB S2 split-K)
    {128, 6, 1, 128, 2, {0, 0, 0, 0, 1}, false, 0},
    {256, 5, 1, 128, 1, {52, 0, 0, 0, 1}, true, 0},
    {512, 5, 1, 128, 1, {39, 0, 0, 0, 1}, true, 0},  // k39 = k38 tile + no-smem epilogue
    {1024, 5, 1, 128, 1, {38, 1, 4, 0, 1}, true, 0},  // raster M (M fastest), swizzle 4: the 4 M-tiles of an N-column co-scheduled
    {2048, 5, 1, 128, 1, {38, 2, 8, 0, 1}, true, -1},
    {4096, 5, 1, 128, 1, {38, 1, 2, 0, 1}, true, -1},  // raster M swizzle 2 (16 is clamped to 8 by CUTLASS)
    {8192, 5, 1, 128, 1, {38, 0, 0, 0, 1}, true, -1},   // late quant PDL trigger (qearly off)
    {16384, 5, 1, 128, 1, {38, 0, 0, 0, 1}, true, -1},  // late quant PDL trigger (qearly off)
};
static void autotune(ShapePlan* p, const void* x, int M, int Mp, int K, int N,
                     const void* wq, const void* wsf, float w_gd, void* out, cudaStream_t s) {
  // pin key: smallest pinned Mp >= Mp (largest pin above the table)
  const Pin* q = &kPins[sizeof(kPins) / sizeof(kPins[0]) - 1];
  for (const Pin& c : kPins)
    if (c.Mp >= Mp) { q = &c; break; }
  const int key = q->Mp;
  p->mode = q->mode; p->splitk = q->S; p->swbx = q->bx; p->swks = q->ks;
  p->ccfg = q->c; p->cpdl = q->pdl; p->qcarve = q->qcv;
  p->swpf = 0;
  // persistent-quant pass-1 L2 policy (evict_last tail MB + evict_first rest)
  if (key == 8192 || key == 16384) { p->p1tail = key == 16384 ? 104 : 64; p->p1first = true; }
  if (key == 4096) { p->p1tail = 32; p->p1first = true; }
  // pass-2 bits: 1024 interleave off, 4096 no pre-barrier first-granule loads, 512 poll backoff
  if (key >= 8192) p->p2bits = 1024;
  if (key >= 4096) p->p2bits |= 4096 | 512;
  if (key == 16384) p->p2bits |= 65536;
  // Mp 16384 DRAM-energy cut: pass-2 xq / scale stores L2 evict_last fraction 1.0 (bit 32) so the
  // GEMM A reads hit L2 and xq lines are written back at most once. Cache hint only: bit-identical.
  if (key == 16384) p->p2bits |= 32;
  if (key == 16384) { p->cutsms = 0; p->cuthint = 2 | (2 << 2) | (2 << 4); }  // AUDIT: A (xq, 64 MB, re-read by all 37 N-tiles) evict_last added (hint only, bit-identical)  // + SFB (padded weight scales, re-read by all 64 M-tiles) evict_last  // A (xq) evict_normal (L2 hits on the evict_last xq stores), B (weight) evict_last
  if (key == 1024) p->cuthint = 2 | (2 << 2);  // A (xq) + B (weight) evict_last
  // Mp 256 (k2 256x128 2SM tiles): ONE M-tile -> each weight tile is read by one CTA pair only
  // -> B (fp4 weight) evict_first, A (xq, re-read by all 64 N-tile pairs) evict_last. Hint only.
  if (key == 256) p->cuthint = 2 | (1 << 2);
  // Mp 512 (k38, 2 M-tiles in one wave): both M-tile pairs read each weight tile ~concurrently ->
  // B (fp4 weight) + SFB evict_first, A (xq) evict_last. Hint only.
  if (key == 512) p->cuthint = 2 | (1 << 2) | (1 << 4);
  if (key == 2048) p->cuthint = 2 << 2;
  // Mp 4096 (k38): A (xq, 16 MB, re-read by 37 N-tiles) + B (weight) TMA loads L2 evict_last. Hint only.
  // Mp 4096: CUTLASS mainloop L2 hints OFF (cuthint 0) together with no weight demotion (NWPROBE)
  if (key == 4096) p->cuthint = 0;
  // k38 pins: A + B TMA descriptors with 256 B L2 promotion (patched, see nvfp4promo::patch)
  // every CUTLASS pin (k52 / k39 / k38, Mp 256..16384): A, B, SFA and SFB TMA descriptors with
  // 256 B L2 promotion (patched, see nvfp4promo::patch; cache-fill hint only, bit-identical)
  if (p->mode == 5) p->cuthint |= (3 | (3 << 2) | (3 << 4) | (3 << 6)) << 8;
  // early (entry) PDL trigger of the quant kernel for the CUTLASS pins below 8192
  p->qearly = (p->mode == 5 && p->cpdl && key < 8192);
  // weight-prefix L2 prefetch issued by the quant kernel after its stores
  if (p->mode == 5 && key <= 8192 && key >= 256) p->qpf = true;
  if (key == 4096 || key == 1024) p->qpfb = 512;
  if (key == 256) p->qipt = 21;
  if (key == 256 || key == 512) p->qdbo = true;
  if (key == 512) p->qipt = 3;
  if (key == 1024) p->qipt = 7;
  if (key == 128) p->qipt = 0;
  p->qbo = (key == 128 || key == 1024);
  // sanity run of the pinned pipeline (launch errors -> exception, no timing)
  enqueue(p, x, M, Mp, K, N, wq, wsf, w_gd, out, s);
  TORCH_CHECK(cudaStreamSynchronize(s) == cudaSuccess && cudaGetLastError() == cudaSuccess,
              "pinned NVFP4 pipeline failed");
  // DETERMINISTIC WARM-UP (reproduces the side effects of the removed first-call tuners, no timing,
  // no selection): (1) a 256 MB scratch tensor is taken from the caching allocator and released
  // again -> the allocator keeps that large cached segment, so later per-call output tensors are
  // carved from it (same placement as when the tuners' L2-flush buffer existed); (2) a fixed number
  // of executions of the pinned pipeline, each after an L2-flushing memset of that scratch, so every
  // kernel / descriptor / module of the pinned path is loaded and warm before graph capture.
  {
    at::Tensor fl = torch::empty({(int64_t)256 << 20}, p->xq->options());
    for (int c = 0; c < 16; ++c) {
      cudaMemsetAsync(fl.data_ptr(), c, (size_t)256 << 20, s);
      enqueue(p, x, M, Mp, K, N, wq, wsf, w_gd, out, s);
    }
    TORCH_CHECK(cudaStreamSynchronize(s) == cudaSuccess && cudaGetLastError() == cudaSuccess,
                "pinned NVFP4 pipeline warm-up failed");
  }
  p->tuned = true;
}





















struct GraphKey {
  const void *x, *wq, *wsf, *out;
  cudaStream_t s;
  int64_t M, N, K;
  uint64_t wgd;
  bool operator==(const GraphKey& o) const { return memcmp(this, &o, sizeof(GraphKey)) == 0; }
};
struct GraphKeyHash {
  size_t operator()(const GraphKey& k) const {
    const uint64_t* w = reinterpret_cast<const uint64_t*>(&k);
    uint64_t hh = 1469598103934665603ull;
    for (size_t i = 0; i < sizeof(GraphKey) / 8; ++i) hh = (hh ^ w[i]) * 1099511628211ull;
    return (size_t)hh;
  }
};

// Slow path: plan lookup (+ autotune on the first call of a shape), graph lookup / capture keyed
// by (pointers, sizes, w_gd, stream), launch. Fills the fast-path cache on success.
struct FastCache {
  const void *x, *wq, *wsf, *out;
  cudaStream_t s;
  int64_t B, S, K, N;
  uint32_t wgd;
  cudaGraphExec_t exec;
  ShapePlan* plan;
  bool valid;
};
// MULTI-ENTRY fast-path cache (kFC entries). A caller loop `out = layer(x, ...)` keeps the previous
// output alive while the next one is allocated, so the caching allocator alternates between (at
// least) two output blocks; with a single entry every other call missed the fast path and paid the
// whole slow path (contiguous() copies-checks, plan / graph hash lookups). Each graph exec bakes in
// its output pointer -> one entry per (pointers, out) combination, filled round robin.
static constexpr int kFC = 8;
static FastCache* fast_caches() { static FastCache* c = new FastCache[kFC](); return c; }
// slot to (re)fill for a new key: an entry with the same out pointer + stream (same graph role),
// else the next round-robin slot
static FastCache& fast_slot(const void* out, cudaStream_t s) {
  FastCache* c = fast_caches();
  for (int i = 0; i < kFC; ++i)
    if (c[i].valid && c[i].out == out && c[i].s == s) return c[i];
  static int rr = 0;
  FastCache& e = c[rr];
  rr = (rr + 1) % kFC;
  return e;
}

static void run_slow(const torch::Tensor& x, const torch::Tensor& weight_fp4,
                     const torch::Tensor& weight_scales, float w_gd, const torch::Tensor& out_full,
                     int64_t B, int64_t S, int64_t K, int64_t N, cudaStream_t stream) {
  int64_t M = B * S;
  int64_t Mp = (M + 127) / 128 * 128;
  int sfk = (int)(K / 16);
  TORCH_CHECK(K % 64 == 0 && N % 128 == 0, "K must be a multiple of 64 and N of 128");
  TORCH_CHECK(2 * Mp * (int64_t)sfk < (int64_t)INT32_MAX && (int64_t)N * sfk < (int64_t)INT32_MAX,
              "input too large for 32-bit indexing");
  // Edge case (cold path only): the quant kernels issue 16/32-byte vector loads of x and the GEMMs
  // need 16-byte aligned TMA global addresses for the weight / weight-scale tensors. A tensor that
  // is a view with an odd storage offset (contiguous but not 16 B aligned) is copied into fresh,
  // allocator-aligned storage first (the fast path never sees it: its pointers then differ).
  auto aligned16 = [](const torch::Tensor& t) {
    return (((uintptr_t)t.data_ptr()) & 15) == 0;
  };
  auto xc = x.contiguous();
  auto wq = weight_fp4.contiguous();
  auto ws = weight_scales.contiguous();
  if (!aligned16(xc)) xc = xc.clone(at::MemoryFormat::Contiguous);
  if (!aligned16(wq)) wq = wq.clone(at::MemoryFormat::Contiguous);
  if (!aligned16(ws)) ws = ws.clone(at::MemoryFormat::Contiguous);
  const bool contig = xc.data_ptr() == x.data_ptr() && wq.data_ptr() == weight_fp4.data_ptr() &&
                      ws.data_ptr() == weight_scales.data_ptr();
  ShapePlan* p = get_plan(Mp, N, K, x.options());
  void* outp = out_full.data_ptr();
  if (!p->tuned)
    autotune(p, xc.data_ptr(), (int)M, (int)Mp, (int)K, (int)N, wq.data_ptr(), ws.data_ptr(),
             w_gd, outp, stream);


  GraphKey key;
  memset(&key, 0, sizeof(key));
  key.x = xc.data_ptr(); key.wq = wq.data_ptr(); key.wsf = ws.data_ptr(); key.out = outp;
  key.s = stream; key.M = M; key.N = N; key.K = K;
  memcpy(&key.wgd, &w_gd, 4);

  static auto& graphs = *new std::unordered_map<GraphKey, cudaGraphExec_t, GraphKeyHash>();
  static bool graphs_ok = true;
  static cudaStream_t cap = nullptr;
  cudaGraphExec_t exec = nullptr;
  auto it = graphs.find(key);
  if (it != graphs.end()) {
    exec = it->second;
  } else if (graphs_ok) {
    if (graphs.size() >= 32) {
      for (auto& kv : graphs) cudaGraphExecDestroy(kv.second);
      graphs.clear();
      for (int i = 0; i < kFC; ++i) fast_caches()[i].valid = false;  // their execs were destroyed
    }
    if (!cap) cudaStreamCreateWithFlags(&cap, cudaStreamNonBlocking);
    cudaGraph_t g = nullptr;
    bool ok = cudaStreamBeginCapture(cap, cudaStreamCaptureModeThreadLocal) == cudaSuccess;
    if (ok) {
      enqueue(p, key.x, (int)M, (int)Mp, (int)K, (int)N, key.wq, key.wsf, w_gd, outp, cap);
      ok = cudaStreamEndCapture(cap, &g) == cudaSuccess && g != nullptr;
    }
    if (ok) ok = cudaGraphInstantiate(&exec, g, 0) == cudaSuccess;
    if (g) cudaGraphDestroy(g);
    if (ok) {
      cudaGraphUpload(exec, stream);  // upload once at instantiation (not on the first timed launch)
      graphs[key] = exec;
    } else {
      exec = nullptr;
      graphs_ok = false;
      cudaGetLastError();
    }
  }
  if (exec) {
    TORCH_CHECK(cudaGraphLaunch(exec, stream) == cudaSuccess, "graph launch failed");
    if (contig) {  // remember this call for the fast path
      FastCache& fc = fast_slot(outp, stream);
      fc.x = key.x; fc.wq = key.wq; fc.wsf = key.wsf; fc.out = outp; fc.s = stream;
      fc.B = B; fc.S = S; fc.K = K; fc.N = N; memcpy(&fc.wgd, &w_gd, 4);
      fc.exec = exec; fc.plan = p; fc.valid = true;
    }
  } else {
    enqueue(p, key.x, (int)M, (int)Mp, (int)K, (int)N, key.wq, key.wsf, w_gd, outp, stream);
  }
}




// Entry point. FAST PATH (steady state of repeated calls): raw-pointer / size / scalar compare
// against the last call, output allocated with cached TensorOptions directly in its final
// [B, S, N] shape when M is 128-aligned (no narrow/reshape), one cudaGraphLaunch. No
// .contiguous(), no BlasLt handle query, no hash-map lookups. Anything else -> run_slow.
torch::Tensor run(const torch::Tensor& x, const torch::Tensor& weight_fp4,
                  const torch::Tensor& weight_scales, double weight_global_decode_scale) {
  const int64_t B = x.size(0), S = x.size(1), K = x.size(2);
  const int64_t N = weight_fp4.size(0);
  const int64_t M = B * S, Mp = (M + 127) / 128 * 128;
  const float w_gd = (float)weight_global_decode_scale;
  uint32_t wgd;
  memcpy(&wgd, &w_gd, 4);
  static at::TensorOptions& oopt = *new at::TensorOptions();
  static int opt_dev = -1;
  const int dev = x.get_device();
  if (opt_dev != dev) { oopt = x.options().dtype(torch::kBFloat16); opt_dev = dev; }
  cudaStream_t stream = at::cuda::getCurrentCUDAStream(dev).stream();
  // Fresh output tensor every call, allocated straight from the CUDA caching allocator
  // (at::detail::empty_cuda with the pre-resolved options: no dispatcher round trip).
  const int64_t osz3[3] = {B, S, N}, osz2[2] = {Mp, N};
  const at::IntArrayRef osz = (Mp == M) ? at::IntArrayRef(osz3, 3) : at::IntArrayRef(osz2, 2);
  // DIRECT ALLOCATION (hot path): when x lives on the current device (the caching allocator
  // allocates on the current device / stream, same as empty_cuda after its device guard), the
  // output is built straight from the CUDA caching allocator: StorageImpl + TensorImpl with the
  // pre-resolved CUDA dispatch key set and bf16 dtype -- skips empty_cuda's device guard, options
  // resolution and empty_generic bookkeeping. Same fresh, uninitialised bf16 contiguous tensor.
  torch::Tensor out;
  {
    static c10::Allocator* calloc_ = nullptr;
    static const c10::DispatchKeySet cks(c10::DispatchKey::CUDA);
    if (!calloc_) calloc_ = c10::cuda::CUDACachingAllocator::get();
    // The caching allocator allocates on the CURRENT device (it queries it internally), so the
    // separate current_device() check (one extra cudaGetDevice per call) is replaced by checking
    // the device of the returned DataPtr: same buffer when x is on the current device; otherwise
    // the block is returned to the cache and empty_cuda (device-guarded) allocates on x's device.
    const size_t nbytes = (size_t)((Mp == M) ? M : Mp) * (size_t)N * sizeof(at::BFloat16);
    c10::DataPtr dp = calloc_->allocate(nbytes);
    if ((int)dp.device().index() == dev) {
      auto st = c10::make_intrusive<c10::StorageImpl>(c10::StorageImpl::use_byte_size_t(), nbytes,
                                                      std::move(dp), calloc_,
                                                      /*resizable=*/false);
      out = at::detail::make_tensor<c10::TensorImpl>(std::move(st), cks,
                                                     caffe2::TypeMeta::Make<at::BFloat16>());
      out.unsafeGetTensorImpl()->set_sizes_contiguous(osz);
    } else {
      dp.clear();
      out = at::Tensor(at::detail::empty_cuda(osz, oopt));
    }
  }
  const void* xp_ = x.data_ptr();
  const void* wp_ = weight_fp4.data_ptr();
  const void* sp_ = weight_scales.data_ptr();
  const void* op_ = out.data_ptr();
  FastCache* fcs = fast_caches();
  // HOST-PATH: probe the entries starting at the previous call's hit (steady-state loops alternate
  // between a couple of output blocks -> usually a hit on the first or second probe), same
  // match predicate as a full scan -> same entry semantics.
  static int last_hit = 0;
  int hit = -1;
  for (int j = 0; j < kFC; ++j) {
    const int i = (last_hit + j) & (kFC - 1);
    const FastCache& e = fcs[i];
    if (e.valid && e.out == op_ && e.x == xp_ && e.wq == wp_ && e.wsf == sp_ && e.s == stream &&
        e.B == B && e.S == S && e.K == K && e.N == N && e.wgd == wgd) {
      hit = i;
      break;
    }
  }
  if (hit >= 0) last_hit = hit;
  FastCache& fc = fcs[hit < 0 ? 0 : hit];
  if (hit >= 0 && x.is_contiguous() && weight_fp4.is_contiguous() && weight_scales.is_contiguous()) {
    // hot path: driver-API launch of the cached graph (cudaGraphExec_t == CUgraphExec,
    // cudaStream_t == CUstream) -- skips the runtime wrapper layer of cudaGraphLaunch
    TORCH_CHECK(cuGraphLaunch((CUgraphExec)fc.exec, (CUstream)stream) == CUDA_SUCCESS,
                "graph launch failed");
  } else {
    run_slow(x, weight_fp4, weight_scales, w_gd, out, B, S, K, N, stream);
  }
  if (Mp == M) return out;
  out.unsafeGetTensorImpl()->set_sizes_contiguous(at::IntArrayRef(osz3, 3));
  return out;
}

static const char* const kArgNames[4] = {"x", "weight_fp4", "weight_scales",
                                         "weight_global_decode_scale"};
static PyObject* g_module = nullptr;
static PyObject* run_fastcall(PyObject* /*self*/, PyObject* const* args, Py_ssize_t nargsf,
                              PyObject* kwnames) {
  const Py_ssize_t np = PyVectorcall_NARGS(nargsf);
  // HOT PATH: exactly 4 positional args, three exact torch.Tensor objects (no subclass ->
  // no isinstance walk), a Python float scalar: borrowed tensors handed straight to run().
  if (np == 4 && kwnames == nullptr && THPVariable_CheckExact(args[0]) &&
      THPVariable_CheckExact(args[1]) && THPVariable_CheckExact(args[2]) &&
      PyFloat_CheckExact(args[3])) {
    try {
      return THPVariable_Wrap(run(THPVariable_Unpack(args[0]), THPVariable_Unpack(args[1]),
                                  THPVariable_Unpack(args[2]), PyFloat_AS_DOUBLE(args[3])));
    } catch (const std::exception& e) {
      PyErr_SetString(PyExc_RuntimeError, e.what());
      return nullptr;
    }
  }
  PyObject* a[4] = {nullptr, nullptr, nullptr, nullptr};
  if (np > 4) { PyErr_SetString(PyExc_TypeError, "run() takes 4 arguments"); return nullptr; }
  for (Py_ssize_t i = 0; i < np; ++i) a[i] = args[i];
  if (kwnames) {
    const Py_ssize_t nk = PyTuple_GET_SIZE(kwnames);
    for (Py_ssize_t j = 0; j < nk; ++j) {
      const char* nm = PyUnicode_AsUTF8(PyTuple_GET_ITEM(kwnames, j));
      if (!nm) return nullptr;
      int idx = -1;
      for (int i = 0; i < 4; ++i) if (strcmp(nm, kArgNames[i]) == 0) idx = i;
      if (idx < 0 || a[idx]) { PyErr_Format(PyExc_TypeError, "run(): bad argument '%s'", nm); return nullptr; }
      a[idx] = args[np + j];
    }
  }
  for (int i = 0; i < 4; ++i)
    if (!a[i]) { PyErr_Format(PyExc_TypeError, "run(): missing argument '%s'", kArgNames[i]); return nullptr; }
  for (int i = 0; i < 3; ++i)
    if (!THPVariable_Check(a[i])) { PyErr_Format(PyExc_TypeError, "run(): '%s' must be a Tensor", kArgNames[i]); return nullptr; }
  const double wgd = PyFloat_AsDouble(a[3]);
  if (wgd == -1.0 && PyErr_Occurred()) return nullptr;
  try {
    return THPVariable_Wrap(run(THPVariable_Unpack(a[0]), THPVariable_Unpack(a[1]),
                                THPVariable_Unpack(a[2]), wgd));
  } catch (const std::exception& e) {
    PyErr_SetString(PyExc_RuntimeError, e.what());
    return nullptr;
  }
}
static PyMethodDef kRunDef = {"run", (PyCFunction)(void (*)(void))run_fastcall,
                              METH_FASTCALL | METH_KEYWORDS, "nvfp4 linear"};


PYBIND11_MODULE(TORCH_EXTENSION_NAME, m) {
  g_module = m.ptr();
  PyObject* f = PyCFunction_NewEx(&kRunDef, nullptr, m.attr("__name__").ptr());
  if (!f) throw pybind11::error_already_set();
  m.add_object("run", pybind11::reinterpret_steal<pybind11::object>(f));
}