Repository navigation
Expand file tree
/
Copy pathcopy.cc
More file actions
2825 lines (2518 loc) · 111 KB
/
Copy pathcopy.cc
File metadata and controls
2825 lines (2518 loc) · 111 KB
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
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*!
* \file tl/cuda/op/copy.cc
* \brief CUDA implementation for tl.copy lowering.
*/
#include "op/copy.h"
#include "support/check.h"
#include <tvm/ffi/extra/structural_equal.h>
#include <tvm/ir/cast.h>
#include <tvm/runtime/logging.h>
#include "cuda/op/builtin.h"
#include "cuda/op/copy.h"
#include "cuda/op/tma_layout.h"
#include "cuda/target_utils.h"
#include "cuda/transform/ptx_async_copy_injector.h"
#include "layout/cute_layout.h"
#include "layout/tcgen05_layout.h"
#include "op/utils.h"
#include "span_utils.h"
#include "transform/common/loop_fusion_utils.h"
#include "transform/loop_partition.h"
#include "transform/loop_vectorize.h"
#include <tvm/tirx/analysis.h>
#include <tvm/tirx/builtin.h>
#include <tvm/tirx/op.h>
#include <tvm/tirx/stmt_functor.h>
#include <tvm/tirx/transform.h>
#include <cctype>
#include <cstdint>
#include <optional>
#include <sstream>
#include <string>
#include <utility>
#include <vector>
namespace tvm {
namespace tl {
using namespace tirx;
using namespace ffi;
namespace {
PrimExpr MakeTmaLeaderCondition(PrimExpr thread_extent) {
return Call(DataType::Bool(), tl_shuffle_elect(), {std::move(thread_extent)});
}
int TMAPayloadElementBits(DataType dtype) {
// IR elements are 8-bit unpacked SMEM slots, but TMA/mbarrier transactions
// count the packed FP4 payload loaded from global memory.
if (dtype.is_float4_e2m1_unpacked()) {
return 4;
}
return dtype.bits();
}
PrimExpr TMABytesFromElements(PrimExpr elements, int bits) {
PrimExpr elements_i64 = cast(DataType::Int(64), elements);
if (bits % 8 == 0) {
return elements_i64 * IntImm(DataType::Int(64), bits / 8);
}
return FloorDiv(elements_i64 * IntImm(DataType::Int(64), bits) +
IntImm(DataType::Int(64), 7),
IntImm(DataType::Int(64), 8));
}
int64_t TMABytesFromElements(int64_t elements, int bits) {
return (elements * bits + 7) / 8;
}
PrimExpr TMABytesFromElements(PrimExpr elements, DataType dtype) {
return TMABytesFromElements(elements, dtype.bits());
}
int64_t TMABytesFromElements(int64_t elements, DataType dtype) {
return TMABytesFromElements(elements, dtype.bits());
}
PrimExpr TMAGlobalBytesFromElements(PrimExpr elements, DataType dtype) {
return TMABytesFromElements(elements, TMAPayloadElementBits(dtype));
}
int64_t TMAGlobalBytesFromElements(int64_t elements, DataType dtype) {
return TMABytesFromElements(elements, TMAPayloadElementBits(dtype));
}
PrimExpr TMATransactionBytesFromElements(PrimExpr elements, DataType dtype) {
return TMABytesFromElements(elements, TMAPayloadElementBits(dtype));
}
int64_t TMATransactionBytesFromElements(int64_t elements, DataType dtype) {
return TMABytesFromElements(elements, TMAPayloadElementBits(dtype));
}
int64_t TMAElementsForBytes(int64_t bytes, DataType dtype) {
ICHECK_EQ((bytes * 8) % dtype.bits(), 0)
<< bytes << " bytes cannot be represented as whole elements of " << dtype;
return bytes * 8 / dtype.bits();
}
bool IsProvably16ByteMultiple(const PrimExpr &bytes,
arith::Analyzer *analyzer) {
return analyzer->CanProveEqual(FloorMod(bytes, IntImm(bytes.dtype(), 16)),
IntImm(bytes.dtype(), 0));
}
PrimExpr GetCopyMbarPhaseExpr(const Map<String, ObjectRef> &annotations,
const LowerArgs &lower_args) {
PrimExpr phase = lower_args.mbar_phase_expr;
if (auto explicit_phase = GetAnnotatedMbarPhaseExpr(annotations)) {
phase = explicit_phase.value();
}
return phase;
}
std::string SanitizeIdentifierPart(const std::string &name) {
std::string sanitized;
sanitized.reserve(name.size());
for (unsigned char ch : name) {
sanitized.push_back(std::isalnum(ch) || ch == '_' ? static_cast<char>(ch)
: '_');
}
if (sanitized.empty()) {
sanitized = "buffer";
}
if (std::isdigit(static_cast<unsigned char>(sanitized.front()))) {
sanitized.insert(sanitized.begin(), '_');
}
return sanitized;
}
std::string MakeCopyMBarrierName(const Buffer &src, const Buffer &dst) {
return SanitizeIdentifierPart(src->name) + "_to_" +
SanitizeIdentifierPart(dst->name) + "_mbarrier";
}
bool GetBoolAnnotation(const CopyNode &op, const char *key) {
if (auto val = op.annotations.Get(key)) {
if (auto int_val = val->as<IntImmNode>()) {
return int_val->value != 0;
}
}
return false;
}
bool GetDisableTMA(const CopyNode &op) {
return GetBoolAnnotation(op, "disable_tma");
}
bool GetIsTmaCopy(const CopyNode &op) {
return GetBoolAnnotation(op, "is_tma_copy");
}
int TensorMapDataTypeForTMA(DataType global_dtype, DataType shared_dtype) {
// 16U4_ALIGN16B: f8f6f4 / mxf8f6f4 unpacked FP4 SMEM
// (float_e2m1_unpacksmem_t). 16U4_ALIGN8B: packed FP4 for mxf4 / mxf4nvf4
// (float_e2m1_t).
constexpr int kTensorMapDataType16U4Align16B = 14;
if (shared_dtype.is_float4_e2m1_unpacked()) {
ICHECK(global_dtype.is_float4_e2m1fn())
<< "FP4 packed global tensor required for unpacked shared TMA copy";
return kTensorMapDataType16U4Align16B;
}
return to_CUtensorMapDataType(global_dtype);
}
int GetEvictionPolicy(const CopyNode &op) {
if (auto val = op.annotations.Get("eviction_policy")) {
if (auto int_val = val->as<IntImmNode>()) {
return int_val->value;
}
}
return 0; // default: evict_normal
}
int64_t GetClusterMask(const CopyNode &op) {
if (auto val = op.annotations.Get("cluster_mask")) {
if (auto int_val = val->as<IntImmNode>()) {
return int_val->value;
}
}
return 0;
}
int MinRankInClusterMask(int64_t cluster_mask) {
ICHECK_GT(cluster_mask, 0);
uint64_t mask = static_cast<uint64_t>(cluster_mask);
int rank = 0;
while ((mask & 1U) == 0U) {
mask >>= 1;
++rank;
}
return rank;
}
Optional<PrimExpr> GetBarrier(const CopyNode &op) {
if (auto val = op.annotations.Get("barrier")) {
if (val->as<tirx::BufferLoadNode>()) {
return Downcast<PrimExpr>(val.value());
}
}
return Optional<PrimExpr>();
}
bool GetIsAsyncCopy(const CopyNode &op) {
if (GetBoolAnnotation(op, "is_async_copy")) {
return true;
}
// Backward-compatibility with historical annotation key.
return GetBoolAnnotation(op, "force_cp_async");
}
bool GetNoImplicitAsyncCommitWait(const CopyNode &op) {
return GetBoolAnnotation(op, attr::kAsyncCopyNoImplicitCommitWait);
}
PrimExpr GetLeaderScopeThreads(const CopyNode &op,
const LowerArgs &lower_args) {
if (auto val = op.annotations.Get("leader_scope_threads")) {
auto int_val = val->as<IntImmNode>();
ICHECK(int_val) << "T.tma_copy leader_scope_threads annotation must be an "
"integer constant.";
ICHECK_GT(int_val->value, 0)
<< "T.tma_copy leader_scope_threads must be positive.";
ICHECK_EQ(int_val->value % 32, 0)
<< "T.tma_copy leader_scope_threads must be a multiple of warp size "
"(32).";
return IntImm(DataType::Int(32), int_val->value);
}
return lower_args.thread_bounds->extent;
}
bool IsContiguousRegion(const Buffer &buf, const Array<Range> &ranges,
arith::Analyzer *analyzer) {
ICHECK_EQ(buf->shape.size(), ranges.size())
<< "IsContiguousRegion: buffer/range rank mismatch for " << buf->name;
int n = static_cast<int>(ranges.size());
int pivot = -1;
for (int i = 0; i < n; ++i) {
if (!analyzer->CanProveEqual(ranges[i]->extent, 1)) {
pivot = i;
break;
}
}
if (pivot == -1) {
return true;
}
for (int i = 0; i < pivot; ++i) {
ICHECK(analyzer->CanProveEqual(ranges[i]->extent, 1))
<< "IsContiguousRegion: dim " << i << " precedes pivot " << pivot
<< " but has non-unit extent " << ranges[i]->extent << " for buffer "
<< buf->name;
}
for (int i = pivot + 1; i < n; ++i) {
if (!analyzer->CanProveEqual(ranges[i]->min, 0) ||
!analyzer->CanProveEqual(ranges[i]->extent, buf->shape[i])) {
return false;
}
}
return true;
}
std::optional<std::pair<Array<Stmt>, PrimExpr>>
MakeTMARows(const Buffer &src, const Array<Range> &src_ranges,
const Buffer &dst, const Array<Range> &dst_ranges,
PrimExpr dst_block, PrimExpr barrier_load,
arith::Analyzer *analyzer) {
int n = static_cast<int>(src_ranges.size());
auto linear_off = [](const Buffer &buf,
const Array<Range> &ranges) -> PrimExpr {
int r = static_cast<int>(ranges.size());
PrimExpr off = 0, stride = 1;
for (int i = r - 1; i >= 0; --i) {
off = off + ranges[i]->min * stride;
if (i > 0) {
stride = stride * buf->shape[i];
}
}
return off;
};
if (IsContiguousRegion(src, src_ranges, analyzer) &&
IsContiguousRegion(dst, dst_ranges, analyzer)) {
PrimExpr total_elems = 1;
for (const auto &r : src_ranges) {
total_elems = total_elems * r->extent;
}
PrimExpr total_bytes = TMABytesFromElements(total_elems, src->dtype);
if (!IsProvably16ByteMultiple(total_bytes, analyzer)) {
return std::nullopt;
}
PrimExpr size_bytes = cast(DataType::UInt(32), total_bytes);
PrimExpr src_ptr = src.access_ptr(1, DataType::Handle(), 1,
linear_off(src, src_ranges), total_elems);
PrimExpr dst_ptr = dst.access_ptr(2, DataType::Handle(), 1,
linear_off(dst, dst_ranges), total_elems);
Stmt call =
Evaluate(Call(DataType::Handle(), tma_store_cluster(),
{dst_ptr, src_ptr, dst_block, size_bytes, barrier_load}));
return std::make_pair(Array<Stmt>{call},
PrimExpr(IntImm(DataType::Int(32), 1)));
}
int split_dim = -1;
for (int d = 0; d < n; ++d) {
if (!analyzer->CanProveEqual(src_ranges[d]->extent, 1)) {
split_dim = d;
break;
}
}
ICHECK(split_dim >= 0)
<< "MakeTMARows: all dimensions are trivial yet region is not "
"contiguous";
PrimExpr extent = src_ranges[split_dim]->extent;
const auto *ext_imm = extent.as<IntImmNode>();
if (ext_imm) {
Array<Stmt> all_stmts;
PrimExpr total = IntImm(DataType::Int(32), 0);
for (int64_t k = 0; k < ext_imm->value; ++k) {
Array<Range> new_src = src_ranges;
Array<Range> new_dst = dst_ranges;
PrimExpr kexpr = IntImm(DataType::Int(32), k);
new_src.Set(split_dim,
Range::FromMinExtent(src_ranges[split_dim]->min + kexpr, 1));
new_dst.Set(split_dim,
Range::FromMinExtent(dst_ranges[split_dim]->min + kexpr, 1));
auto sub = MakeTMARows(src, new_src, dst, new_dst, dst_block,
barrier_load, analyzer);
if (!sub.has_value()) {
return std::nullopt;
}
auto &[stmts, cnt] = sub.value();
for (const auto &s : stmts) {
all_stmts.push_back(s);
}
total = total + cnt;
}
return std::make_pair(all_stmts, total);
}
Var k("k_tma_row", DataType::Int(32));
Array<Range> body_src = src_ranges;
Array<Range> body_dst = dst_ranges;
body_src.Set(split_dim,
Range::FromMinExtent(src_ranges[split_dim]->min + k, 1));
body_dst.Set(split_dim,
Range::FromMinExtent(dst_ranges[split_dim]->min + k, 1));
auto body_result = MakeTMARows(src, body_src, dst, body_dst, dst_block,
barrier_load, analyzer);
if (!body_result.has_value()) {
return std::nullopt;
}
auto &[body_stmts, body_cnt] = body_result.value();
Stmt body = body_stmts.size() == 1 ? body_stmts[0]
: static_cast<Stmt>(SeqStmt(body_stmts));
Stmt for_loop =
For(k, IntImm(DataType::Int(32), 0), extent, ForKind::kSerial, body);
return std::make_pair(Array<Stmt>{for_loop}, extent * body_cnt);
}
// Recast a (datapath, value-column) tile to b32 columns (CuTe upcast on the
// column axis): b32 column = value column / values_per_b32, the sub-slot
// position dropping onto a stride-0 mode.
cute::Layout TmemTileToB32Columns(const cute::Layout &tile,
int64_t values_per_b32) {
cute::Layout value_to_b32 =
cute::MakeLayout({cute::Layout(1, cute::E({0})),
cute::Layout(cute::IntTupleTuple({values_per_b32, 1}),
cute::IntTupleTuple({0, cute::E({1})}))});
return cute::Composition(value_to_b32, tile);
}
// Whether a 16-bit fragment stores one value per b32 word (the low half:
// the MMA accumulator format, PTX "Packing format for matrix D in Tensor
// Memory") and so needs the tcgen05 pack::16b/unpack::16b modifiers. Its
// columns are then half-filled: size < occupied datapaths * column cosize.
// Decided on the WHOLE fragment (storage is a property of the buffer);
// counting only occupied datapaths keeps Layout F's datapath gaps from
// looking like holes.
bool TmemFragmentNeedsPack16b(const cute::Layout &fragment) {
int64_t datapaths = cute::AsConst(
cute::Size(cute::Filter(cute::Composition(kDpOnly, fragment))));
int64_t columns =
cute::AsConst(cute::Cosize(cute::Composition(kColOnly, fragment)));
return cute::AsConst(cute::Size(fragment)) < datapaths * columns;
}
} // namespace
namespace cuda {
struct TMAIm2ColDesc {
size_t rank;
int data_type;
Array<PrimExpr> global_shape;
Array<PrimExpr> global_stride;
Array<PrimExpr> elem_stride;
Array<PrimExpr> lower_corner;
Array<PrimExpr> upper_corner;
PrimExpr global_addr;
int smem_box_pixel;
int smem_box_channel;
int swizzle;
int interleave;
int oob_fill;
int l2_promotion;
Array<PrimExpr> EncodeCallArgs() const {
Array<PrimExpr> args;
args.reserve(rank * 5 + 5);
args.push_back(data_type);
args.push_back(static_cast<int>(rank));
args.push_back(global_addr);
for (auto e : global_shape)
args.push_back(e);
for (auto e : global_stride)
args.push_back(e);
for (auto e : elem_stride)
args.push_back(e);
for (auto e : lower_corner)
args.push_back(e);
for (auto e : upper_corner)
args.push_back(e);
args.push_back(smem_box_pixel);
args.push_back(smem_box_channel);
args.push_back(interleave);
args.push_back(swizzle);
args.push_back(l2_promotion);
args.push_back(oob_fill);
return args;
}
};
struct Copy {
static LayoutMap InferLayout(const CopyNode &op,
const LayoutInferArgs &layout_args,
InferLevel level);
static Stmt Lower(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer);
private:
static void CollectFragmentLayouts(const PrimExpr &expr,
const Map<Var, PrimExpr> &bind_var_to_expr,
const LayoutMap &existing_layouts,
PrimExpr thread_extent,
Range thread_bounds,
Map<Buffer, Layout> &result_map);
static CopyInst SelectInst(const CopyNode &op, Target target,
const LayoutMap &layout_map,
arith::Analyzer *analyzer);
static void CheckParallelLoopLayout(const CopyNode &op, CopyInst copy_inst);
static LayoutMap InferTMemLayout(const CopyNode &op,
const LayoutInferArgs &layout_args,
CopyInst copy_inst);
static LayoutMap InferBulkLayout(const CopyNode &op,
const LayoutInferArgs &layout_args,
InferLevel level, CopyInst copy_inst);
static Stmt LowerNormal(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer);
static Stmt LowerCluster(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer);
static Stmt LowerCPAsync(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer);
static Stmt LowerLDSM(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer, CopyInst copy_inst);
static Stmt LowerTmem(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer);
static Stmt LowerBulk(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer, CopyInst copy_inst);
static Stmt LowerBulkGather4(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer, CopyInst copy_inst);
static Stmt LowerBulk1D(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer, CopyInst copy_inst);
};
struct Im2Col {
static Stmt Lower(const Im2ColOpNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer);
};
void Copy::CollectFragmentLayouts(const PrimExpr &expr,
const Map<Var, PrimExpr> &bind_var_to_expr,
const LayoutMap &existing_layouts,
PrimExpr thread_extent, Range thread_bounds,
Map<Buffer, Layout> &result_map) {
PostOrderVisit(expr, [&](const ObjectRef &node) {
if (auto bl = node.as<BufferLoadNode>()) {
if (IsFragmentBuffer(bl->buffer) && !existing_layouts.count(bl->buffer) &&
!result_map.count(bl->buffer)) {
auto f = Fragment::FullyReplicated(bl->buffer->shape, thread_extent);
result_map.Set(bl->buffer, f->BindThreadRange(thread_bounds));
}
} else if (auto var_node = node.as<VarNode>()) {
auto var = GetRef<Var>(var_node);
if (bind_var_to_expr.count(var)) {
CollectFragmentLayouts(bind_var_to_expr[var], bind_var_to_expr,
existing_layouts, thread_extent, thread_bounds,
result_map);
}
}
});
}
LayoutMap Copy::InferLayout(const CopyNode &op,
const LayoutInferArgs &layout_args,
InferLevel level) {
CopyInst copy_inst = SelectInst(op, layout_args.target,
layout_args.layout_map, layout_args.analyzer);
CheckParallelLoopLayout(op, copy_inst);
if (copy_inst == CopyInst::kTMemLoad || copy_inst == CopyInst::kTMemStore) {
return InferTMemLayout(op, layout_args, copy_inst);
}
if (copy_inst == CopyInst::kBulkLoad || copy_inst == CopyInst::kBulkStore ||
copy_inst == CopyInst::kBulkLoad1D ||
copy_inst == CopyInst::kBulkStore1D) {
return InferBulkLayout(op, layout_args, level, copy_inst);
}
// For normal/cp.async/LDSM/STSM, layout inference follows the generated
// SIMT loop. CUDA-specific explicit layout cases are handled above.
return op.InferSIMTLayout(layout_args, level);
}
void Copy::CheckParallelLoopLayout(const CopyNode &op, CopyInst copy_inst) {
if (!op.annotations.count(attr::kParallelLoopLayout)) {
return;
}
if (copy_inst == CopyInst::kNormal || copy_inst == CopyInst::kCPAsync) {
return;
}
std::ostringstream oss;
oss << "T.copy loop layout annotation requires SIMT copy; got "
<< CopyInstToString(copy_inst) << " for src=" << op.src->name
<< ", dst=" << op.dst->name
<< ". Remove loop_layout or change copy pattern.";
LOG(FATAL) << oss.str();
}
// Infer the register Fragment of a TMEM<->fragment copy from the TMEM
// buffer's layout, so the copy lowers to tcgen05.ld/st (LowerTmem below).
//
// Running example (a split epilogue reading one accumulator in two halves,
// 128 threads):
// C_tmem = alloc_tmem((128, 128), f32), fragment (128,128):(1@0,1@1)
// C_local = alloc_fragment((128, 128), f32)
// T.copy(C_tmem[:, 0:64], C_local[:, 0:64]) <- this op
// T.copy(C_tmem[:, 64:128], C_local[:, 64:128]) <- later op, same result
LayoutMap Copy::InferTMemLayout(const CopyNode &op,
const LayoutInferArgs &layout_args,
CopyInst copy_inst) {
// TODO (mzw) Add support for tcgen05.cp in CUDA tmem lowering.
LayoutMap results;
bool is_tmem_load = copy_inst == CopyInst::kTMemLoad;
Buffer tmem_buf = is_tmem_load ? op.src : op.dst;
Buffer reg_buf = is_tmem_load ? op.dst : op.src;
if (!layout_args.layout_map.count(reg_buf) &&
layout_args.layout_map.count(tmem_buf)) {
Layout tmem_layout = layout_args.layout_map[tmem_buf];
// tmem_frag: logical buffer coord -> physical TMEM (datapath@0,
// column@1).
// E.g. (128,128):(1@0,1@1).
Optional<cute::Layout> tmem_frag =
cute::LayoutFromTileLangHierarchical(tmem_layout);
ICHECK(tmem_frag.defined())
<< "TMEM layout of " << tmem_buf->name
<< " is not decodable by the CuTe analyzer: " << tmem_layout;
// cute::Restrict splits the fragment into Region origin + tile: the
// (possibly dynamic) origin only moves the base address.
// tile: region-local coord -> (datapath, column) step from the origin.
// E.g. origin = (0,0), tile = (128,64):(1@0,1@1); the second copy
// differs only in origin = (0,64).
const Array<Range> &tmem_ranges =
is_tmem_load ? op.src_range : op.dst_range;
const Array<Range> ®_ranges = is_tmem_load ? op.dst_range : op.src_range;
cute::Layout tile = cute::Restrict(tmem_frag.value(), tmem_ranges).get<1>();
// A pack::16b tile is planned in b32 columns (shapes untouched: b32
// column j holds exactly value j); a packed-pair tile keeps value
// columns and moves whole columns with the plain instruction.
int64_t values_per_b32 = 32 / (tmem_buf->dtype.bits());
bool pack16b_tile =
values_per_b32 > 1 && TmemFragmentNeedsPack16b(tmem_frag.value());
if (pack16b_tile)
tile = TmemTileToB32Columns(tile, values_per_b32);
// The register buffer is a grid of such slices (a split epilogue issues
// one copy per slice), each appending its own registers.
// E.g. nrep = (1, 2): two column halves.
size_t rank = reg_ranges.size();
Array<int64_t> nrep;
int64_t total_reps = 1;
for (size_t dim = 0; dim < rank; ++dim) {
const auto *buf_ext = as_const_int(reg_buf->shape[dim]);
const auto *reg_ext = as_const_int(reg_ranges[dim]->extent);
ICHECK(buf_ext && reg_ext && *buf_ext % *reg_ext == 0);
nrep.push_back(*buf_ext / *reg_ext);
total_reps *= nrep.back();
}
constexpr int WARP_SIZE = 32;
constexpr int WARPGROUP_SIZE = 4 * WARP_SIZE;
ICHECK(is_const_int(layout_args.thread_bounds->extent))
<< "Tensor memory copy requires thread_bounds->extent (num_threads) "
"to be constant integers";
int num_threads = *as_const_int(layout_args.thread_bounds->extent);
ICHECK(num_threads % WARPGROUP_SIZE == 0)
<< "Tensor memory copy requires thread bounds to be aligned to "
"warpgroups, but found "
<< "thread range = " << layout_args.thread_bounds;
for (int num_useful_wgs = num_threads / WARPGROUP_SIZE; num_useful_wgs >= 1;
--num_useful_wgs) {
int num_useful_threads = num_useful_wgs * WARPGROUP_SIZE;
// local_frag: region-local coord -> (thread@0, value@1).
// E.g. (128,64):(1@0,1@1) for 32dp32b, 128 threads.
int64_t values_per_column = pack16b_tile ? 1 : values_per_b32;
Tcgen05CopyPlan expanded =
ExpandTcgen05Layout(GetTcgen05MetaLd32Dp32B(), tile,
num_useful_threads, values_per_column);
// A Layout F tile occupies only the low 16 datapaths per
// sub-partition, which no full-width atom can tile; fall back to the
// narrowest half-subpartition atom.
if (!expanded.defined())
expanded = ExpandTcgen05Layout(GetTcgen05MetaLd16Dp64B(), tile,
num_useful_threads, values_per_column);
if (!expanded.defined()) {
continue;
}
cute::Layout local_frag = expanded->fragment;
int64_t vals_per_slice =
cute::AsConst(cute::Size(local_frag)) / num_useful_threads;
// Repeat the slice along the value vector to cover the whole register
// buffer (row-major slice grid): each further slice appends one
// slice's worth of registers per thread, so both halves of a split
// copy infer the same full-buffer Fragment. Unit-extent region dims
// carry only their repetition mode.
// rep_grid: per-dim slice index -> value@1.
// E.g. (1,2):(128@1,64@1) -- the second half's 64 registers per
// thread follow the first's.
cute::Layout rep_grid = cute::Composition(
cute::Layout(total_reps, vals_per_slice * cute::E({1})),
cute::MakeRowMajorLayout(nrep));
Array<cute::Layout> modes;
int64_t tile_idx = 0;
for (size_t dim = 0; dim < rank; ++dim) {
if (is_one(reg_ranges[dim]->extent)) {
modes.push_back(rep_grid[dim]);
} else {
modes.push_back(
cute::MakeLayout({local_frag[tile_idx++], rep_grid[dim]}));
}
}
ICHECK_EQ(tile_idx, cute::Rank(tile))
<< "TMEM copy tile rank does not match the register loop rank";
// logical_coord2frag: full buffer coord -> (thread@0, value@1).
Fragment logical_coord2frag = FragmentToTileLang(cute::MakeLayout(modes));
results.Set(reg_buf, logical_coord2frag->BindThreadRange(
layout_args.thread_bounds));
break;
}
}
return results;
}
LayoutMap Copy::InferBulkLayout(const CopyNode &op,
const LayoutInferArgs &layout_args,
InferLevel level, CopyInst copy_inst) {
Map<Buffer, Layout> result_map;
bool is_tma_1d =
copy_inst == CopyInst::kBulkLoad1D || copy_inst == CopyInst::kBulkStore1D;
bool is_load =
copy_inst == CopyInst::kBulkLoad || copy_inst == CopyInst::kBulkLoad1D;
bool is_store =
copy_inst == CopyInst::kBulkStore || copy_inst == CopyInst::kBulkStore1D;
Buffer shared_tensor = is_load ? op.dst : op.src;
Array<Range> shared_range = is_load ? op.dst_range : op.src_range;
if (is_tma_1d && shared_range.size() == 1) {
// 1D TMA Store with single dimension can not be swizzled. 1D TMA can also
// have multiple dimensions when the last dimension is continuous.
return result_map;
}
// Fragment buffers used as TMA indices should be replicated on all threads.
PrimExpr thread_extent = layout_args.thread_bounds->extent;
for (const auto &range : op.src_range) {
CollectFragmentLayouts(range->min, layout_args.bind_var_to_expr,
layout_args.layout_map, thread_extent,
layout_args.thread_bounds, result_map);
CollectFragmentLayouts(range->extent, layout_args.bind_var_to_expr,
layout_args.layout_map, thread_extent,
layout_args.thread_bounds, result_map);
}
for (const auto &range : op.dst_range) {
CollectFragmentLayouts(range->min, layout_args.bind_var_to_expr,
layout_args.layout_map, thread_extent,
layout_args.thread_bounds, result_map);
CollectFragmentLayouts(range->extent, layout_args.bind_var_to_expr,
layout_args.layout_map, thread_extent,
layout_args.thread_bounds, result_map);
}
if (is_tma_1d) {
// 1D TMA requires contiguous shared memory. Do not infer a swizzled shared
// layout here, otherwise final instruction selection may fall back to
// descriptor-based multidimensional TMA.
return result_map;
}
if (level == InferLevel::kFree &&
!layout_args.layout_map.count(shared_tensor)) {
if (is_store && shared_tensor->shape.size() >= 2) {
// For BulkStore, infer a swizzled shared-memory layout when possible.
// Rank-1 shared buffers cannot be swizzled (there is no stride dim to
// index), so they take the linear-layout branch below. A rank-1 store
// can reach this multi-dim arm when its region is not provably in bounds,
// making the raw 1D TMA path unavailable. Without the rank guard,
// reading shape[dim - 2] would fault (see issue #2529).
int dim = shared_tensor->shape.size();
const int64_t mat_stride = *as_const_int(shared_tensor->shape[dim - 2]);
const int64_t mat_continuous =
*as_const_int(shared_tensor->shape[dim - 1]);
Layout swizzle_layout_2d =
MakeGemmABLayoutHopper(mat_stride, mat_continuous, mat_continuous,
shared_tensor->dtype.bits(),
/*k_inner=*/true);
if (StructuralEqual()(swizzle_layout_2d, MakeLinearLayout(Array<PrimExpr>{
Integer(mat_stride),
Integer(mat_continuous)}))) {
result_map.Set(shared_tensor,
MakeTmaLinearLayout(shared_tensor->shape, shared_range));
} else {
result_map.Set(shared_tensor, ExpandLayoutToMatchBuffer(
swizzle_layout_2d, shared_tensor));
}
} else {
result_map.Set(shared_tensor,
MakeTmaLinearLayout(shared_tensor->shape, shared_range));
}
}
return result_map;
}
CopyInst Copy::SelectInst(const CopyNode &op, Target target,
const LayoutMap &layout_map,
arith::Analyzer *analyzer) {
CopyAnalysisContext ctx;
ctx.target = target;
ctx.layout_map = &layout_map;
ctx.analyzer = analyzer;
ctx.emit_diagnostics = true;
auto result = SelectCopyInstForLowering(op, ctx);
ICHECK(result.supported) << result.reason
<< SpanHintSuffix({op.dst->span, op.src->span});
return result.inst;
}
Stmt Copy::Lower(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer) {
auto copy_inst =
SelectInst(op, lower_args.target, lower_args.layout_map, analyzer);
if (op.dst_block.defined()) {
ICHECK(TargetHasBulkCopy(lower_args.target))
<< "T.copy with dst_block requires cluster-copy support (CUDA SM90+). "
<< "Got class="pl-pds">" << lower_args.target;
return LowerCluster(op, lower_args, analyzer);
}
if (copy_inst == CopyInst::kTMemLoad || copy_inst == CopyInst::kTMemStore) {
auto tmem_copy = LowerTmem(op, lower_args, analyzer);
ICHECK(tmem_copy.defined()) << "Failed to lower tensor memory copy";
return tmem_copy;
} else if (copy_inst == CopyInst::kBulkLoad1D ||
copy_inst == CopyInst::kBulkStore1D) {
auto bulk_copy = LowerBulk1D(op, lower_args, analyzer, copy_inst);
ICHECK(bulk_copy.defined()) << "Failed to lower bulk load 1d";
return bulk_copy;
} else if (copy_inst == CopyInst::kBulkLoad ||
copy_inst == CopyInst::kBulkStore) {
auto bulk_copy = LowerBulk(op, lower_args, analyzer, copy_inst);
ICHECK(bulk_copy.defined()) << "Failed to lower bulk load/store";
return bulk_copy;
} else if (copy_inst == CopyInst::kBulkLoadGather4 ||
copy_inst == CopyInst::kBulkStoreScatter4) {
auto bulk_copy = LowerBulkGather4(op, lower_args, analyzer, copy_inst);
ICHECK(bulk_copy.defined()) << "Failed to lower tma gather4/scatter4";
return bulk_copy;
} else if (copy_inst == CopyInst::kLDSM || copy_inst == CopyInst::kSTSM) {
auto ldsm_copy = LowerLDSM(op, lower_args, analyzer, copy_inst);
ICHECK(ldsm_copy.defined()) << "Failed to lower ptx matrix copy";
return ldsm_copy;
} else if (copy_inst == CopyInst::kCPAsync) {
auto cp_async_copy = LowerCPAsync(op, lower_args, analyzer);
ICHECK(cp_async_copy.defined()) << "Failed to lower cp.async copy";
return cp_async_copy;
} else if (copy_inst == CopyInst::kNormal) {
return LowerNormal(op, lower_args, analyzer);
} else {
LOG(FATAL) << "Unsupported copy inst " << static_cast<int>(copy_inst);
}
}
Stmt Copy::LowerCPAsync(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer) {
using namespace tvm::transform;
PassContext pass_ctx = PassContext::Current();
bool enable_async_copy =
pass_ctx->GetConfig<Bool>(kEnableAsyncCopy, Bool(true)).value();
bool no_implicit_commit_wait = GetNoImplicitAsyncCommitWait(op);
bool explicit_async_semantics = no_implicit_commit_wait || GetIsAsyncCopy(op);
if (!enable_async_copy && !explicit_async_semantics) {
return LowerNormal(op, lower_args, analyzer);
}
auto simt_loop = op.MakeSIMTLoop(analyzer);
auto fused_loop = Downcast<For>(ParallelLoopFuser::Fuse(simt_loop));
auto par_op = ParallelOp(fused_loop);
std::vector<InferLevel> levels = {InferLevel::kCommon, InferLevel::kStrict,
InferLevel::kFree};
for (auto level : levels) {
par_op->InferLayout({lower_args.target,
lower_args.thread_bounds,
lower_args.layout_map,
analyzer,
lower_args.buffer_remap,
{}},
level);
}
auto loop_layout = par_op->GetLoopLayout();
Stmt lowered_loop = LowerParallelLoop(
par_op->GetRoot(), loop_layout, lower_args.thread_index, analyzer,
lower_args.layout_map, par_op->GetPredicate(lower_args.thread_index),
/*parallel_loop=*/true, par_op->LoopLayoutRequiresPaddingGuard());
auto inject_result =
InjectPTXAsyncCopy(lowered_loop, /*async_without_async_commit_wait=*/
no_implicit_commit_wait || GetIsAsyncCopy(op));
Stmt cp_async_loop = inject_result.stmt;
if (!inject_result.injected_ptx_async_copy) {
DLOG(WARNING) << "cp.async rewrite miss for copy src=" << op.src->name
<< " (scope=" << op.src.scope() << ", dtype=" << op.src->dtype
<< "), dst=" << op.dst->name << " (scope=" << op.dst.scope()
<< ", dtype=" << op.dst->dtype
<< "), no_implicit_async_commit_wait="
<< no_implicit_commit_wait
<< ", is_async_copy=" << GetIsAsyncCopy(op);
if (no_implicit_commit_wait) {
DLOG(WARNING)
<< "Pipeline-managed async copy fallback to normal copy because "
"cp.async rewrite found no eligible global->shared store.";
return lowered_loop;
}
if (explicit_async_semantics) {
LOG(FATAL) << "Explicit async copy semantics require cp.async lowering, "
"but no eligible global->shared store was rewritten.";
}
DLOG(WARNING) << "Fallback to normal copy because cp.async rewrite found "
"no eligible global->shared store.";
return LowerNormal(op, lower_args, analyzer);
}
if (no_implicit_commit_wait) {
return cp_async_loop;
}
if (GetIsAsyncCopy(op)) {
Stmt commit_group =
Evaluate(Call(DataType::Handle(), builtin::ptx_commit_group(), {}));
return SeqStmt({cp_async_loop, commit_group});
}
return cp_async_loop;
}
Stmt Copy::LowerNormal(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer) {
return tl::LowerNormalCopy(op, lower_args, analyzer);
}
Stmt Copy::LowerCluster(const CopyNode &op, const LowerArgs &lower_args,
arith::Analyzer *analyzer) {
const Buffer &src = op.src;
const Buffer &dst = op.dst;
const Array<Range> &src_range = op.src_range;
const Array<Range> &dst_range = op.dst_range;
ICHECK(op.dst_block.defined());
ICHECK(IsSharedBuffer(src));
ICHECK(IsSharedBuffer(dst));
if (auto barrier_opt = GetBarrier(op)) {
bool src_contiguous = IsContiguousRegion(src, src_range, analyzer);
bool dst_contiguous = IsContiguousRegion(dst, dst_range, analyzer);
PrimExpr src_elements = 1;
for (auto r : src_range) {
src_elements = src_elements * r->extent;
}
PrimExpr dst_elements = 1;
for (auto r : dst_range) {
dst_elements = dst_elements * r->extent;
}
bool element_match = analyzer->CanProveEqual(src_elements, dst_elements);
if (src_contiguous && dst_contiguous && element_match) {
PrimExpr barrier_load = barrier_opt.value();
auto compute_linear_offset = [](const Buffer &buf,
const Array<Range> &ranges) -> PrimExpr {
PrimExpr offset = 0;
PrimExpr stride = 1;
for (int i = static_cast<int>(ranges.size()) - 1; i >= 0; --i) {
offset = offset + ranges[i]->min * stride;
if (i > 0) {
stride = stride * buf->shape[i];
}
}
return offset;
};
PrimExpr dst_offset = compute_linear_offset(dst, dst_range);
PrimExpr src_offset = compute_linear_offset(src, src_range);
PrimExpr total_elements = 1;
for (auto r : src_range) {
total_elements = total_elements * r->extent;
}
PrimExpr total_bytes = TMABytesFromElements(total_elements, src->dtype);
if (IsProvably16ByteMultiple(total_bytes, analyzer)) {
PrimExpr size_bytes = cast(DataType::UInt(32), total_bytes);
PrimExpr dst_ptr = dst.access_ptr(2, DataType::Handle(), 1, dst_offset,
total_elements);
PrimExpr src_ptr = src.access_ptr(1, DataType::Handle(), 1, src_offset,
total_elements);
Stmt bulk_copy = Evaluate(Call(DataType::Handle(), tma_store_cluster(),
{dst_ptr, src_ptr, op.dst_block.value(),
size_bytes, barrier_load}));
return IfThenElse(
EQ(lower_args.thread_index, lower_args.thread_bounds->min),
bulk_copy);
}
LOG(WARNING) << "Cluster bulk copy size " << total_bytes
<< " bytes is not a multiple of 16 as required by "
"cp.async.bulk; falling back to element-wise cluster "
"copy. src="
<< src->name << ", dst=" << dst->name;
} else {
bool same_shape = (src_range.size() == dst_range.size());
for (size_t d = 0; d < src_range.size() && same_shape; ++d) {
if (!analyzer->CanProveEqual(src_range[d]->extent,
dst_range[d]->extent)) {
same_shape = false;
}
}
if (element_match && same_shape) {
PrimExpr barrier_load = barrier_opt.value();
const auto *barrier_buf_load = barrier_load.as<tirx::BufferLoadNode>();
ICHECK(barrier_buf_load)
<< "LowerCluster: expected BufferLoad for barrier annotation";
Var barrier_data_var = barrier_buf_load->buffer->data;
auto tma_rows =
MakeTMARows(src, src_range, dst, dst_range, op.dst_block.value(),
barrier_load, analyzer);