forked from flagos-ai/FlagTree
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUtility.h
More file actions
1513 lines (1378 loc) · 62.2 KB
/
Utility.h
File metadata and controls
1513 lines (1378 loc) · 62.2 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
#ifndef TRITON_CONVERSION_TRITONGPU_TO_LLVM_UTILITY_H
#define TRITON_CONVERSION_TRITONGPU_TO_LLVM_UTILITY_H
#include <set>
#include "mlir/Conversion/LLVMCommon/Pattern.h"
#include "mlir/Dialect/ControlFlow/IR/ControlFlowOps.h"
#include "mlir/Dialect/LLVMIR/LLVMDialect.h"
#include "triton/Analysis/Utility.h"
#include "triton/Conversion/MLIRTypes.h"
#include "triton/Conversion/TritonGPUToLLVM/TargetInfoBase.h"
#include "triton/Dialect/Triton/IR/Utility.h"
#include "triton/Dialect/TritonGPU/IR/Dialect.h"
#include "triton/Dialect/TritonGPU/IR/LinearLayoutConversions.h"
#include "triton/Dialect/TritonHCUGPU/IR/Dialect.h"
#include "triton/Tools/LinearLayout.h"
#include "triton/Tools/StrUtil.h"
#include "triton/Tools/Sys/GetEnv.hpp"
#include "llvm/ADT/STLExtras.h"
#include "llvm/Support/ErrorHandling.h"
#define DEBUG_TYPE "ttgpu_to_llvm"
#define DBGS() (llvm::dbgs() << "[" DEBUG_TYPE "]: ")
#define LDBG(X) LLVM_DEBUG(DBGS() << X << "\n")
using namespace mlir;
using namespace mlir::triton;
// Shortcuts for some commonly used LLVM ops to keep code simple and intuitive
// Operators
#define inttofloat(...) rewriter.create<LLVM::SIToFPOp>(loc, __VA_ARGS__)
#define inttoptr(...) rewriter.create<LLVM::IntToPtrOp>(loc, __VA_ARGS__)
#define ptrtoint(...) rewriter.create<LLVM::PtrToIntOp>(loc, __VA_ARGS__)
#define zext(...) rewriter.create<LLVM::ZExtOp>(loc, __VA_ARGS__)
#define sext(...) rewriter.create<LLVM::SExtOp>(loc, __VA_ARGS__)
#define fpext(...) rewriter.create<LLVM::FPExtOp>(loc, __VA_ARGS__)
#define trunc(...) rewriter.create<LLVM::TruncOp>(loc, __VA_ARGS__)
#define udiv(...) rewriter.create<LLVM::UDivOp>(loc, __VA_ARGS__)
#define urem(...) rewriter.create<LLVM::URemOp>(loc, __VA_ARGS__)
#define add(...) rewriter.create<LLVM::AddOp>(loc, __VA_ARGS__)
#define sub(...) rewriter.create<LLVM::SubOp>(loc, __VA_ARGS__)
#define fadd(...) rewriter.create<LLVM::FAddOp>(loc, __VA_ARGS__)
#define mul(...) rewriter.create<LLVM::MulOp>(loc, __VA_ARGS__)
#define fmul(...) rewriter.create<LLVM::FMulOp>(loc, __VA_ARGS__)
#define smax(...) rewriter.create<LLVM::SMaxOp>(loc, __VA_ARGS__)
#define umax(...) rewriter.create<LLVM::UMaxOp>(loc, __VA_ARGS__)
#define fmax(...) rewriter.create<LLVM::MaxNumOp>(loc, __VA_ARGS__)
#define smin(...) rewriter.create<LLVM::SMinOp>(loc, __VA_ARGS__)
#define umin(...) rewriter.create<LLVM::UMinOp>(loc, __VA_ARGS__)
#define fmin(...) rewriter.create<LLVM::MinNumOp>(loc, __VA_ARGS__)
#define shl(...) rewriter.create<LLVM::ShlOp>(loc, __VA_ARGS__)
#define lshr(...) rewriter.create<LLVM::LShrOp>(loc, __VA_ARGS__)
#define and_(...) rewriter.create<LLVM::AndOp>(loc, __VA_ARGS__)
#define xor_(...) rewriter.create<LLVM::XOrOp>(loc, __VA_ARGS__)
#define or_(...) rewriter.create<LLVM::OrOp>(loc, __VA_ARGS__)
#define bitcast(val__, type__) \
rewriter.create<LLVM::BitcastOp>(loc, type__, val__)
#define addrspacecast(...) \
rewriter.create<LLVM::AddrSpaceCastOp>(loc, __VA_ARGS__)
#define gep(...) rewriter.create<LLVM::GEPOp>(loc, __VA_ARGS__)
#define ptr_ty(...) LLVM::LLVMPointerType::get(__VA_ARGS__)
#define insert_val(...) rewriter.create<LLVM::InsertValueOp>(loc, __VA_ARGS__)
#define extract_val(...) rewriter.create<LLVM::ExtractValueOp>(loc, __VA_ARGS__)
#define insert_element(...) \
rewriter.create<LLVM::InsertElementOp>(loc, __VA_ARGS__)
#define extract_element(...) \
rewriter.create<LLVM::ExtractElementOp>(loc, __VA_ARGS__)
#define load(...) rewriter.create<LLVM::LoadOp>(loc, __VA_ARGS__)
#define store(...) rewriter.create<LLVM::StoreOp>(loc, __VA_ARGS__)
#define fcmp_ogt(lhs, rhs) \
rewriter.create<LLVM::FCmpOp>(loc, rewriter.getI1Type(), \
LLVM::FCmpPredicate::ogt, lhs, rhs)
#define fcmp_olt(lhs, rhs) \
rewriter.create<LLVM::FCmpOp>(loc, rewriter.getI1Type(), \
LLVM::FCmpPredicate::olt, lhs, rhs)
#define fcmp_eq(lhs, rhs) \
rewriter.create<LLVM::FCmpOp>(loc, rewriter.getI1Type(), \
LLVM::FCmpPredicate::oeq, lhs, rhs)
#define icmp_eq(...) \
rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::eq, __VA_ARGS__)
#define icmp_ne(...) \
rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::ne, __VA_ARGS__)
#define icmp_slt(...) \
rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::slt, __VA_ARGS__)
#define icmp_sle(...) \
rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::sle, __VA_ARGS__)
#define icmp_sgt(...) \
rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::sgt, __VA_ARGS__)
#define icmp_sge(...) \
rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::sge, __VA_ARGS__)
#define icmp_ult(...) \
rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::ult, __VA_ARGS__)
#define icmp_ule(...) \
rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::ule, __VA_ARGS__)
#define icmp_ugt(...) \
rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::ugt, __VA_ARGS__)
#define icmp_uge(...) \
rewriter.create<LLVM::ICmpOp>(loc, LLVM::ICmpPredicate::uge, __VA_ARGS__)
#define select(...) rewriter.create<LLVM::SelectOp>(loc, __VA_ARGS__)
#define address_of(...) rewriter.create<LLVM::AddressOfOp>(loc, __VA_ARGS__)
#define barrier() rewriter.create<mlir::gpu::BarrierOp>(loc)
#define undef(...) rewriter.create<LLVM::UndefOp>(loc, __VA_ARGS__)
#define null(...) rewriter.create<LLVM::ZeroOp>(loc, __VA_ARGS__)
#define call(...) rewriter.create<LLVM::CallOp>(loc, __VA_ARGS__)
// Types
#define int_ty(width) rewriter.getIntegerType(width)
#define i64_ty rewriter.getIntegerType(64)
#define i32_ty rewriter.getIntegerType(32)
#define i16_ty rewriter.getIntegerType(16)
#define i32_ty rewriter.getIntegerType(32)
#define i64_ty rewriter.getIntegerType(64)
#define ui32_ty rewriter.getIntegerType(32, false)
#define ui64_ty rewriter.getIntegerType(64, false)
#define f16_ty rewriter.getF16Type()
#define bf16_ty rewriter.getBF16Type()
#define i8_ty rewriter.getIntegerType(8)
#define i1_ty rewriter.getI1Type()
#define f32_ty rewriter.getF32Type()
#define f64_ty rewriter.getF64Type()
#define vec_ty(type, num) VectorType::get(num, type)
#define void_ty(ctx) LLVM::LLVMVoidType::get(ctx)
#define struct_ty(...) LLVM::LLVMStructType::getLiteral(ctx, __VA_ARGS__)
#define array_ty(elemTy, count) LLVM::LLVMArrayType::get(elemTy, count)
// Constants
#define i1_val(val) LLVM::createConstantI1(loc, rewriter, val)
#define true_val() i1_val(true)
#define false_val() i1_val(false)
#define f16_val(...) LLVM::createConstantF16(loc, rewriter, __VA_ARGS__)
#define f32_val(...) LLVM::createConstantF32(loc, rewriter, __VA_ARGS__)
#define f64_val(...) LLVM::createConstantF64(loc, rewriter, __VA_ARGS__)
#define i32_val(...) LLVM::createConstantI32(loc, rewriter, __VA_ARGS__)
#define i64_val(...) LLVM::createConstantI64(loc, rewriter, __VA_ARGS__)
#define int_val(width, val) \
LLVM::createLLVMIntegerConstant(rewriter, loc, width, val)
#define i8_val(val) int_val(8, val)
#define i16_val(val) int_val(16, val)
#define tid_val() getThreadId(rewriter, loc)
// Attributes
#define i32_arr_attr(...) rewriter.getI32ArrayAttr({__VA_ARGS__})
#define i64_arr_attr(...) rewriter.getI64ArrayAttr({__VA_ARGS__})
#define str_attr(str) ::mlir::StringAttr::get(ctx, (str))
namespace mlir {
namespace triton {
// Delinearize supposing order is [0, 1, .. , n]
template <typename T>
llvm::SmallVector<T> getMultiDimIndexImpl(T linearIndex,
llvm::ArrayRef<T> shape) {
// shape: {a, b, c, d} -> accMul: {1, a, a*b, a*b*c}
size_t rank = shape.size();
T accMul = product(shape.drop_back());
T linearRemain = linearIndex;
llvm::SmallVector<T> multiDimIndex(rank);
for (int i = rank - 1; i >= 0; --i) {
multiDimIndex[i] = linearRemain / accMul;
linearRemain = linearRemain % accMul;
if (i != 0) {
accMul = accMul / shape[i - 1];
}
}
return multiDimIndex;
}
template <typename T>
llvm::SmallVector<T> getMultiDimIndex(T linearIndex, llvm::ArrayRef<T> shape,
llvm::ArrayRef<unsigned> order) {
size_t rank = shape.size();
assert(rank == order.size());
auto reordered = applyPermutation(shape, order);
auto reorderedMultiDim = getMultiDimIndexImpl<T>(linearIndex, reordered);
llvm::SmallVector<T> multiDim(rank);
for (unsigned i = 0; i < rank; ++i) {
multiDim[order[i]] = reorderedMultiDim[i];
}
return multiDim;
}
// Linearize supposing order is [0, 1, .. , n]
template <typename T>
T getLinearIndexImpl(llvm::ArrayRef<T> multiDimIndex, llvm::ArrayRef<T> shape) {
assert(multiDimIndex.size() == shape.size());
// shape: {a, b, c, d} -> accMul: {1, a, a*b, a*b*c}
size_t rank = shape.size();
T accMul = product(shape.drop_back());
T linearIndex = 0;
for (int i = rank - 1; i >= 0; --i) {
linearIndex += multiDimIndex[i] * accMul;
if (i != 0) {
accMul = accMul / shape[i - 1];
}
}
return linearIndex;
}
template <typename T>
T getLinearIndex(llvm::ArrayRef<T> multiDimIndex, llvm::ArrayRef<T> shape,
llvm::ArrayRef<unsigned> order) {
assert(shape.size() == order.size());
return getLinearIndexImpl<T>(applyPermutation(multiDimIndex, order),
applyPermutation(shape, order));
}
namespace gpu {
Type getFunctionType(Type resultType, ValueRange operands);
LLVM::LLVMFuncOp appendOrGetExternFuncOp(RewriterBase &rewriter, Operation *op,
StringRef funcName, Type funcType,
StringRef libname = "",
StringRef libpath = "");
} // namespace gpu
} // namespace triton
namespace LLVM {
using namespace mlir::triton;
Value createConstantI1(Location loc, OpBuilder &rewriter, bool v);
Value createConstantI32(Location loc, OpBuilder &rewriter, int32_t v);
Value createConstantI64(Location loc, OpBuilder &rewriter, int64_t v);
Value createConstantF16(Location loc, OpBuilder &rewriter, float v);
Value createConstantF32(Location loc, OpBuilder &rewriter, float v);
Value createConstantF64(Location loc, OpBuilder &rewriter, double v);
Value createNaNConstant(Location loc, OpBuilder &rewriter, Type type);
Value createIndexConstant(OpBuilder &builder, Location loc,
const TypeConverter *converter, int64_t value);
Value createLLVMIntegerConstant(OpBuilder &builder, Location loc, short width,
int64_t value);
// Is v an integer or floating-point scalar constant equal to 0?
bool isConstantZero(Value v);
/// Helper function to get strides from a given shape and its order
SmallVector<Value> getStridesFromShapeAndOrder(ArrayRef<int64_t> shape,
ArrayRef<unsigned> order,
Location loc,
RewriterBase &rewriter);
struct SharedMemoryObject {
Value base; // i32 ptr. The start address of the shared memory object after
// the initial allocation or the last slicing operation.
Type baseElemType;
// We need to store strides as Values, not integers, because the
// extract_slice instruction can take a slice at arbitrary offsets.
// Take $a[16:32, 16:32] as an example; though we know the stride of $a[0] is
// 32, we need to let the instruction that uses $a be aware of that.
// Otherwise, when we use $a, we only know that the shape of $a is 16x16. If
// we store strides into an attribute array of integers, the information
// cannot pass through block argument assignment because attributes are
// associated with operations, not Values.
// TODO(Keren): We may need to figure out a way to store strides as integers
// if we want to support more optimizations.
SmallVector<Value>
strides; // i32 int. The strides of the shared memory object.
SmallVector<Value> offsets; // i32 int.
// Offsets are applied at the last slicing operation.
// We can use offsets to recover the previous base.
// The offsets are zero at the initial allocation.
SharedMemoryObject(Value base, Type baseElemType, ArrayRef<Value> strides,
ArrayRef<Value> offsets)
: base(base), baseElemType(baseElemType),
strides(strides.begin(), strides.end()),
offsets(offsets.begin(), offsets.end()) {}
SharedMemoryObject(Value base, Type baseElemType, ArrayRef<int64_t> shape,
ArrayRef<unsigned> order, Location loc,
RewriterBase &rewriter)
: base(base), baseElemType(baseElemType) {
strides = getStridesFromShapeAndOrder(shape, order, loc, rewriter);
offsets.append(order.size(), i32_val(0));
}
SmallVector<Value> getStrides() const { return strides; }
SmallVector<Value> getOffsets() const { return offsets; }
Value getBase() const { return base; }
Type getBaseElemType() const { return baseElemType; }
SmallVector<Value> getElems() const {
SmallVector<Value> elems;
elems.push_back(base);
elems.append(strides.begin(), strides.end());
elems.append(offsets.begin(), offsets.end());
return elems;
}
SmallVector<Type> getTypes() const {
SmallVector<Type> types;
types.push_back(base.getType());
types.append(strides.size(), IntegerType::get(base.getContext(), 32));
types.append(offsets.size(), IntegerType::get(base.getContext(), 32));
return types;
}
Value getCSwizzleOffset(int order) const {
assert(order >= 0 && order < strides.size());
return offsets[order];
}
Value getBaseBeforeSlice(int order, Location loc,
RewriterBase &rewriter) const {
Value cSwizzleOffset = getCSwizzleOffset(order);
Value offset = sub(i32_val(0), cSwizzleOffset);
Type type = base.getType();
return gep(type, baseElemType, base, offset);
}
};
SharedMemoryObject getSharedMemoryObjectFromStruct(Location loc,
Value llvmStruct,
Type elemTy,
RewriterBase &rewriter);
// Convert an \param index to a multi-dim coordinate given \param shape and
// \param order.
SmallVector<Value> delinearize(RewriterBase &rewriter, Location loc,
Value linear, ArrayRef<unsigned> shape,
ArrayRef<unsigned> order);
SmallVector<Value> delinearize(RewriterBase &rewriter, Location loc,
unsigned linear, ArrayRef<unsigned> shape);
SmallVector<Value> delinearize(RewriterBase &rewriter, Location loc,
Value linear, ArrayRef<unsigned> shape);
Value linearize(RewriterBase &rewriter, Location loc, ArrayRef<Value> multiDim,
ArrayRef<unsigned> shape, ArrayRef<unsigned> order);
Value linearize(RewriterBase &rewriter, Location loc, ArrayRef<Value> multiDim,
ArrayRef<unsigned> shape);
Value addStringToModule(Location loc, RewriterBase &rewriter, StringRef key,
StringRef content);
// Given an elemId which represents the index of an element from the list of
// elements that are in the thread's registers (i.e. total of
// numel(sizePerThread)), it calculates the multi dim offset of the element in
// the smem buffer. Recall that the smem buffer will only store a single replica
// when converting distributed to distributed layout. Also, a replica is the
// smallest CTA tile that is common between input and output layouts.
SmallVector<Value> getMultiDimOffset(Attribute layout, Location loc,
RewriterBase &rewriter,
const TargetInfoBase &targetInfo,
unsigned elemId, RankedTensorType type,
ArrayRef<unsigned> multiDimCTAInRepId,
ArrayRef<unsigned> shapePerCTATile);
// Given a multiDimOffset, this function wraps around each dimension to be
// within shape.
SmallVector<Value> getWrappedMultiDimOffset(
RewriterBase &rewriter, Location loc, ArrayRef<Value> multiDimOffset,
ArrayRef<unsigned> shape, SmallVector<unsigned> shapePerCTATile,
SmallVector<int64_t> shapePerCTA);
inline bool isKernel(FunctionOpInterface funcOp) {
return funcOp.getVisibility() == SymbolTable::Visibility::Public;
}
inline Value getStackPointer(RewriterBase &rewriter,
FunctionOpInterface funcOp) {
auto mod = funcOp->getParentOfType<ModuleOp>();
LLVM::GlobalOp globalBase = nullptr;
mod.walk([&](LLVM::GlobalOp op) {
if (op.getSymName() == "global_smem")
globalBase = op;
});
assert(globalBase);
if (isKernel(funcOp))
return rewriter.create<LLVM::AddressOfOp>(funcOp.getLoc(), globalBase);
else
return funcOp.getArgument(funcOp.getNumArguments() - 1);
}
inline Value getSharedMemoryBase(Location loc, RewriterBase &rewriter,
Operation *op) {
auto ptrTy = LLVM::LLVMPointerType::get(rewriter.getContext(), 3);
FunctionOpInterface func =
op->template getParentOfType<FunctionOpInterface>();
assert(op->hasAttr("allocation.offset"));
size_t offset = cast<IntegerAttr>(op->getAttr("allocation.offset"))
.getValue()
.getZExtValue();
Value offVal = i32_val(offset);
Value base = gep(ptrTy, i8_ty, LLVM::getStackPointer(rewriter, func), offVal);
return base;
}
} // namespace LLVM
/* ------------------------------------ */
// Returns CTA level thread idx
inline Value getThreadId(RewriterBase &rewriter, Location loc) {
Value tid =
rewriter.create<::mlir::gpu::ThreadIdOp>(loc, ::mlir::gpu::Dimension::x);
return rewriter.create<arith::IndexCastOp>(loc, i32_ty, tid);
}
// -----------------------------------------------------------------------
// Shared memory utilities
// -----------------------------------------------------------------------
using LLVM::getMultiDimIndex;
using LLVM::SharedMemoryObject;
using ::mlir::LLVM::delinearize;
using ::mlir::LLVM::SharedMemoryObject;
using ::mlir::triton::gpu::BlockedEncodingAttr;
using ::mlir::triton::gpu::CTALayoutAttr;
using ::mlir::triton::gpu::DotOperandEncodingAttr;
using ::mlir::triton::gpu::HCUMfmaEncodingAttr;
using ::mlir::triton::gpu::HCUWmmaEncodingAttr;
using ::mlir::triton::gpu::NvidiaMmaEncodingAttr;
using ::mlir::triton::gpu::SliceEncodingAttr;
inline Value dot(RewriterBase &rewriter, Location loc, ArrayRef<Value> offsets,
ArrayRef<Value> strides) {
assert(offsets.size() == strides.size());
Value ret = i32_val(0);
for (auto [offset, stride] : llvm::zip(offsets, strides)) {
ret = add(ret, mul(offset, stride));
}
return ret;
}
// -----------------------------------------------------------------------
// Blocked layout indices
// -----------------------------------------------------------------------
// "Applies" the given layout by computing layout(indices) and returning the
// resulting Values.
//
// In other words, this generates LLVM-dialect MLIR code to "run" the layout
// function.
SmallVector<std::pair<StringAttr, Value>>
applyLinearLayout(Location loc, RewriterBase &rewriter,
const LinearLayout &layout,
ArrayRef<std::pair<StringAttr, Value>> indices);
inline SmallVector<Value>
emitBaseIndexWithinCTAForBlockedLayout(Location loc, RewriterBase &rewriter,
const BlockedEncodingAttr &blockedLayout,
RankedTensorType type) {
MLIRContext *ctx = rewriter.getContext();
auto shape = type.getShape();
Value threadId = getThreadId(rewriter, loc);
Value warpSize = i32_val(triton::gpu::getWarpSize(blockedLayout));
Value laneId = urem(threadId, warpSize);
Value warpId = udiv(threadId, warpSize);
auto sizePerThread = blockedLayout.getSizePerThread();
auto threadsPerWarp = blockedLayout.getThreadsPerWarp();
auto warpsPerCTA = blockedLayout.getWarpsPerCTA();
auto order = blockedLayout.getOrder();
auto shapePerCTA = triton::gpu::getShapePerCTA(blockedLayout, shape);
unsigned rank = shape.size();
// delinearize threadId to get the base index
SmallVector<Value> multiDimWarpId =
delinearize(rewriter, loc, warpId, warpsPerCTA, order);
SmallVector<Value> multiDimThreadId =
delinearize(rewriter, loc, laneId, threadsPerWarp, order);
SmallVector<Value> multiDimBase(rank);
for (unsigned k = 0; k < rank; ++k) {
// Wrap around multiDimWarpId/multiDimThreadId in case
// shapePerCTATile[k] > shapePerCTA[k]
auto maxWarps =
ceil<unsigned>(shapePerCTA[k], sizePerThread[k] * threadsPerWarp[k]);
auto maxThreads = ceil<unsigned>(shapePerCTA[k], sizePerThread[k]);
multiDimWarpId[k] = urem(multiDimWarpId[k], i32_val(maxWarps));
multiDimThreadId[k] = urem(multiDimThreadId[k], i32_val(maxThreads));
// multiDimBase[k] = (multiDimThreadId[k] +
// multiDimWarpId[k] * threadsPerWarp[k]) *
// sizePerThread[k];
Value threadsPerWarpK = i32_val(threadsPerWarp[k]);
Value sizePerThreadK = i32_val(sizePerThread[k]);
multiDimBase[k] =
mul(sizePerThreadK,
add(multiDimThreadId[k], mul(multiDimWarpId[k], threadsPerWarpK)));
}
return multiDimBase;
}
inline SmallVector<SmallVector<unsigned>>
emitOffsetForBlockedLayout(const BlockedEncodingAttr &blockedLayout,
RankedTensorType type) {
auto ctx = type.getContext();
auto shape = type.getShape();
auto sizePerThread = blockedLayout.getSizePerThread();
auto threadsPerWarp = blockedLayout.getThreadsPerWarp();
auto warpsPerCTA = blockedLayout.getWarpsPerCTA();
auto order = blockedLayout.getOrder();
auto shapePerCTATile = getShapePerCTATile(blockedLayout);
auto shapePerCTA = triton::gpu::getShapePerCTA(blockedLayout, shape);
unsigned rank = shape.size();
SmallVector<unsigned> tilesPerDim(rank);
for (unsigned k = 0; k < rank; ++k)
tilesPerDim[k] = ceil<unsigned>(shapePerCTA[k], shapePerCTATile[k]);
unsigned elemsPerThread = triton::gpu::getTotalElemsPerThread(type);
unsigned totalSizePerThread = product<unsigned>(sizePerThread);
SmallVector<SmallVector<unsigned>> reorderedOffset(elemsPerThread);
for (unsigned n = 0; n < elemsPerThread; ++n) {
unsigned linearNanoTileId = n / totalSizePerThread;
unsigned linearNanoTileElemId = n % totalSizePerThread;
SmallVector<unsigned> multiDimNanoTileId =
getMultiDimIndex<unsigned>(linearNanoTileId, tilesPerDim, order);
SmallVector<unsigned> multiDimNanoTileElemId =
getMultiDimIndex<unsigned>(linearNanoTileElemId, sizePerThread, order);
for (unsigned k = 0; k < rank; ++k) {
unsigned reorderedMultiDimId =
(multiDimNanoTileId[k] *
(sizePerThread[k] * threadsPerWarp[k] * warpsPerCTA[k]) +
multiDimNanoTileElemId[k]) %
shapePerCTA[k];
reorderedOffset[n].push_back(reorderedMultiDimId);
}
}
return reorderedOffset;
}
// -----------------------------------------------------------------------
// Mma layout indices
// -----------------------------------------------------------------------
inline SmallVector<Value>
emitBaseIndexWithinCTAForMmaLayoutV1(Location loc, RewriterBase &rewriter,
const NvidiaMmaEncodingAttr &mmaLayout,
RankedTensorType type) {
auto shape = type.getShape();
auto wpt = mmaLayout.getWarpsPerCTA();
static constexpr std::array<int, 3> fpw{{2, 2, 1}};
auto [isARow, isBRow, isAVec4, isBVec4, _] =
mmaLayout.decodeVoltaLayoutStates();
Value thread = getThreadId(rewriter, loc);
auto *ctx = thread.getContext();
Value _1 = i32_val(1);
Value _2 = i32_val(2);
Value _4 = i32_val(4);
Value _16 = i32_val(16);
Value _32 = i32_val(32);
Value _fpw0 = i32_val(fpw[0]);
Value _fpw1 = i32_val(fpw[1]);
// A info
auto aRep = mmaLayout.getMMAv1Rep(0);
auto aSpw = mmaLayout.getMMAv1ShapePerWarp(0);
// B info
auto bSpw = mmaLayout.getMMAv1ShapePerWarp(1);
auto bRep = mmaLayout.getMMAv1Rep(1);
SmallVector<int, 2> rep({aRep[0], bRep[1]});
SmallVector<int, 2> spw({aSpw[0], bSpw[1]});
SmallVector<unsigned, 2> shapePerCTA({spw[0] * wpt[0], spw[1] * wpt[1]});
Value lane = urem(thread, _32);
Value warp = udiv(thread, _32);
Value warp0 = urem(warp, i32_val(wpt[0]));
Value warp12 = udiv(warp, i32_val(wpt[0]));
Value warp1 = urem(warp12, i32_val(wpt[1]));
// warp offset
Value offWarpM = mul(warp0, i32_val(spw[0]));
Value offWarpN = mul(warp1, i32_val(spw[1]));
// quad offset
Value offQuadM = mul(udiv(and_(lane, _16), _4), _fpw0);
Value offQuadN = mul(udiv(and_(lane, _16), _4), _fpw1);
// pair offset
Value offPairM = udiv(urem(lane, _16), _4);
offPairM = urem(offPairM, _fpw0);
offPairM = mul(offPairM, _4);
Value offPairN = udiv(urem(lane, _16), _4);
offPairN = udiv(offPairN, _fpw0);
offPairN = urem(offPairN, _fpw1);
offPairN = mul(offPairN, _4);
offPairM = mul(offPairM, i32_val(rep[0] / 2));
offQuadM = mul(offQuadM, i32_val(rep[0] / 2));
offPairN = mul(offPairN, i32_val(rep[1] / 2));
offQuadN = mul(offQuadN, i32_val(rep[1] / 2));
// quad pair offset
Value offLaneM = add(offPairM, offQuadM);
Value offLaneN = add(offPairN, offQuadN);
// a, b offset
Value offsetAM = add(offWarpM, offLaneM);
Value offsetBN = add(offWarpN, offLaneN);
// m indices
Value offsetCM = add(and_(lane, _1), offsetAM);
// n indices
Value offsetCN = add((and_(lane, _2)), (add(offWarpN, offPairN)));
return {offsetCM, offsetCN};
}
inline SmallVector<SmallVector<unsigned>>
emitOffsetForMmaLayoutV1(const NvidiaMmaEncodingAttr &mmaLayout,
RankedTensorType type) {
auto shape = type.getShape();
auto [isARow, isBRow, isAVec4, isBVec4, _] =
mmaLayout.decodeVoltaLayoutStates();
// TODO: seems like the pattern below to get `rep`/`spw` appears quite often
// A info
auto aRep = mmaLayout.getMMAv1Rep(0);
auto aSpw = mmaLayout.getMMAv1ShapePerWarp(0);
// B info
auto bSpw = mmaLayout.getMMAv1ShapePerWarp(1);
auto bRep = mmaLayout.getMMAv1Rep(1);
auto wpt = mmaLayout.getWarpsPerCTA();
static constexpr std::array<int, 3> fpw{{2, 2, 1}};
SmallVector<int, 2> rep({aRep[0], bRep[1]});
SmallVector<int, 2> spw({aSpw[0], bSpw[1]});
SmallVector<unsigned, 2> shapePerCTA({spw[0] * wpt[0], spw[1] * wpt[1]});
SmallVector<unsigned> idxM;
for (unsigned m = 0; m < shape[0]; m += shapePerCTA[0])
for (unsigned mm = 0; mm < rep[0]; ++mm)
idxM.push_back(m + mm * 2);
SmallVector<unsigned> idxN;
for (int n = 0; n < shape[1]; n += shapePerCTA[1]) {
for (int nn = 0; nn < rep[1]; ++nn) {
idxN.push_back(n + nn / 2 * 4 + (nn % 2) * 2 * fpw[1] * rep[1]);
idxN.push_back(n + nn / 2 * 4 + (nn % 2) * 2 * fpw[1] * rep[1] + 1);
}
}
SmallVector<SmallVector<unsigned>> ret;
for (unsigned x1 : idxN) { // N
for (unsigned x0 : idxM) { // M
SmallVector<unsigned> idx(2);
idx[0] = x0; // M
idx[1] = x1; // N
ret.push_back(std::move(idx));
}
}
return ret;
}
inline SmallVector<SmallVector<unsigned>>
emitOffsetForMmaLayoutV2(const NvidiaMmaEncodingAttr &mmaLayout,
RankedTensorType type) {
auto shape = type.getShape();
auto shapePerCTA = getShapePerCTA(mmaLayout, shape);
SmallVector<SmallVector<unsigned>> ret;
auto rank = shape.size();
for (unsigned i = 0; i < shapePerCTA[rank - 2];
i += getShapePerCTATile(mmaLayout)[rank - 2]) {
for (unsigned j = 0; j < shapePerCTA[rank - 1];
j += getShapePerCTATile(mmaLayout)[rank - 1]) {
if (rank == 3) {
ret.push_back({0, i, j});
ret.push_back({0, i, j + 1});
ret.push_back({0, i + 8, j});
ret.push_back({0, i + 8, j + 1});
} else {
ret.push_back({i, j});
ret.push_back({i, j + 1});
ret.push_back({i + 8, j});
ret.push_back({i + 8, j + 1});
}
}
}
return ret;
}
// Note that this may return a null Value for one or more dimensions. This is
// valid only if you're going to slice off the relevant dimension.
inline SmallVector<Value>
emitBaseIndexWithinCTAForMmaLayoutV2V3(Location loc, RewriterBase &rewriter,
const NvidiaMmaEncodingAttr &mmaLayout,
RankedTensorType type) {
auto shape = type.getShape();
auto _warpsPerCTA = mmaLayout.getWarpsPerCTA();
auto rank = shape.size();
assert(rank == 2 || rank == 3);
auto warpOrder = triton::gpu::getWarpOrder(mmaLayout);
ArrayRef<unsigned int> instrShape = mmaLayout.getInstrShape();
SmallVector<Value> warpsPerCTA;
for (unsigned i = 0; i < rank; ++i)
warpsPerCTA.push_back(i32_val(_warpsPerCTA[i]));
auto shapePerCTA = getShapePerCTA(mmaLayout, shape);
Value threadId = getThreadId(rewriter, loc);
Value warpSize = i32_val(32);
Value laneId = urem(threadId, warpSize);
Value warpId = udiv(threadId, warpSize);
uint32_t repM =
(_warpsPerCTA[rank - 2] * instrShape[rank - 2]) / shapePerCTA[rank - 2];
uint32_t repN =
(_warpsPerCTA[rank - 1] * instrShape[rank - 1]) / shapePerCTA[rank - 1];
uint32_t warpsM;
if (repM > 1)
warpsM = _warpsPerCTA[rank - 2] / repM;
else
warpsM = shape[rank - 2] / instrShape[rank - 2];
uint32_t warpsN;
if (repN > 1)
warpsN = _warpsPerCTA[rank - 1] / repN;
else
warpsN = shape[rank - 1] / instrShape[rank - 1];
SmallVector<Value> multiDimWarpId(rank);
multiDimWarpId = delinearize(rewriter, loc, warpId, _warpsPerCTA, warpOrder);
Value warpIdM = urem(multiDimWarpId[rank - 2], i32_val(warpsM));
Value warpIdN = urem(multiDimWarpId[rank - 1], i32_val(warpsN));
Value offWarpM = mul(warpIdM, i32_val(instrShape[rank - 2]));
Value offWarpN = mul(warpIdN, i32_val(instrShape[rank - 1]));
SmallVector<Value> multiDimBase(rank);
if (rank == 3)
multiDimBase[0] = multiDimWarpId[0];
// warpsM/N may be 0, in which case warpIDM/N is poison (division by 0), which
// will cause LLVM to eliminate all ops that depend on the poison value. This
// *can* be okay, if the bad dimension is filtered out by a slice layout. So
// we rely on the caller to check. Worst case we crash, which is better than
// silently producing bad code.
if (warpsM != 0)
multiDimBase[rank - 2] = add(udiv(laneId, i32_val(4)), offWarpM);
if (warpsN != 0)
multiDimBase[rank - 1] =
add(mul(i32_val(2), urem(laneId, i32_val(4))), offWarpN);
return multiDimBase;
}
inline SmallVector<SmallVector<unsigned>>
emitOffsetForMmaLayoutV3(const NvidiaMmaEncodingAttr &mmaLayout,
RankedTensorType type) {
auto shape = type.getShape();
auto shapePerCTA = getShapePerCTA(mmaLayout, shape);
SmallVector<SmallVector<unsigned>> ret;
ArrayRef<unsigned int> instrShape = mmaLayout.getInstrShape();
for (unsigned i = 0; i < shapePerCTA[0];
i += getShapePerCTATile(mmaLayout)[0]) {
for (unsigned j = 0; j < shapePerCTA[1];
j += getShapePerCTATile(mmaLayout)[1]) {
for (unsigned k = 0; k < instrShape[1]; k += 8) {
ret.push_back({i, j + k});
ret.push_back({i, j + k + 1});
ret.push_back({i + 8, j + k});
ret.push_back({i + 8, j + k + 1});
}
}
}
return ret;
}
inline SmallVector<Value>
emitBaseIndexForMfmaLayout(Location loc, RewriterBase &rewriter,
const HCUMfmaEncodingAttr &mfmaLayout,
RankedTensorType type) {
auto shape = type.getShape();
auto rank = shape.size();
assert(rank == 2 || rank == 3);
auto _warpsPerCTA = mfmaLayout.getWarpsPerCTA();
SmallVector<Value> warpsPerCTA;
for (unsigned i = 0; i < rank; ++i)
warpsPerCTA.push_back(i32_val(_warpsPerCTA[i]));
unsigned mDim = mfmaLayout.getMDim();
unsigned nDim = mfmaLayout.getNDim();
assert((mDim == nDim && (mDim == 32 || mDim == 16 || mDim == 4)) ||
(mDim == 64 && nDim == 4) || (mDim == 4 && nDim == 64) ||
(mDim == 16 && nDim == 32) || (mDim == 16 && nDim == 64));
Value threadId = getThreadId(rewriter, loc);
Value warpSize = i32_val(triton::gpu::getWarpSize(mfmaLayout));
Value effectiveWarpSize = warpSize;
if (mDim == 4 && nDim == 4) {
const int uniqueValuesPerWarp = 4;
effectiveWarpSize = i32_val(uniqueValuesPerWarp);
}
Value laneId = urem(threadId, effectiveWarpSize);
Value warpId = udiv(threadId, warpSize);
SmallVector<Value> multiDimWarpId =
delinearize(rewriter, loc, warpId, _warpsPerCTA,
triton::gpu::getWarpOrder(mfmaLayout));
if (shape[rank - 2] >= mDim) {
assert(shape[rank - 2] % mDim == 0);
multiDimWarpId[rank - 2] =
urem(multiDimWarpId[rank - 2],
i32_val(ceil<unsigned>(shape[rank - 2], mDim)));
}
if (shape[rank - 1] >= nDim) {
assert(shape[rank - 1] % nDim == 0);
multiDimWarpId[rank - 1] =
urem(multiDimWarpId[rank - 1],
i32_val(ceil<unsigned>(shape[rank - 1], nDim)));
}
Value offWarp0 = mul(multiDimWarpId[rank - 2], i32_val(mDim));
Value offWarp1 = mul(multiDimWarpId[rank - 1], i32_val(nDim));
bool isMmacFuse = false;
if ((mDim == 32 && nDim == 32) || (mDim == 16 && nDim == 32)) {
mDim = 16; // real m/nDim
nDim = 16;
} else if (mDim == 16 && nDim == 64) {
mDim = 16; // real m/nDim
nDim = 16;
isMmacFuse = true;
}
SmallVector<Value> multiDimBase(rank);
if (!mfmaLayout.getIsTransposed()) {
if (isMmacFuse) {
multiDimBase[rank - 1] =
add(mul(udiv(laneId, i32_val(mDim)), i32_val(4)), offWarp1);
} else {
multiDimBase[rank - 1] = add(udiv(laneId, i32_val(mDim)), offWarp1);
}
multiDimBase[rank - 2] = add(urem(laneId, i32_val(mDim)), offWarp0);
} else {
if (isMmacFuse) {
multiDimBase[rank - 2] =
add(mul(udiv(laneId, i32_val(nDim)), i32_val(4)), offWarp0);
} else {
multiDimBase[rank - 2] = add(udiv(laneId, i32_val(nDim)), offWarp0);
}
multiDimBase[rank - 1] = add(urem(laneId, i32_val(nDim)), offWarp1);
}
// TODO(Lixun): It is assumed when rank = 3, warpsPerCTA is set to
// {numWarps, 1, 1}. We need to generalize the offset computation.
if (rank == 3) {
assert(_warpsPerCTA[1] == 1 && _warpsPerCTA[2] == 1);
multiDimBase[0] = urem(warpId, i32_val(shape[0]));
}
return multiDimBase;
}
inline void emitMfmaOffsetForCTA(const HCUMfmaEncodingAttr &mfmaLayout,
SmallVector<SmallVector<unsigned>> &offsets,
unsigned bOff, unsigned ctaOffsetX,
unsigned ctaOffsetY) {
auto mDim = mfmaLayout.getMDim();
auto nDim = mfmaLayout.getNDim();
assert((mDim == nDim && (mDim == 32 || mDim == 16 || mDim == 4)) ||
(mDim == 64 && nDim == 4) || (mDim == 4 && nDim == 64) ||
(mDim == 16 && nDim == 32) || (mDim == 16 && nDim == 64));
// MFMA output tile consists of repeated "dot operand B" layout groups along
// row axis. This variable defines number of these groups.
DenseMap<int, int> groups{{4, 1}, {16, 1}, {32, 4}};
unsigned numGroups = groups.at(std::min(mDim, nDim));
unsigned elemsPerThreadPerGroup = 4;
bool isMmacFuse = false;
if ((mDim == 32 && nDim == 32) || (mDim == 16 && nDim == 32)) {
numGroups = mDim / 16;
elemsPerThreadPerGroup = 8;
} else if (mDim == 16 && nDim == 64) {
isMmacFuse = true;
numGroups = mDim / 16;
elemsPerThreadPerGroup = 16;
}
auto warpSize = getWarpSize(mfmaLayout);
assert(warpSize == 64);
auto shapePerCta = getShapePerCTATile(mfmaLayout);
auto rank = shapePerCta.size();
SmallVector<unsigned> elemOff(rank, 0);
for (unsigned block = 0; block < numGroups; block++) {
unsigned rowOrColOffset =
block * elemsPerThreadPerGroup * warpSize / std::min(mDim, nDim);
for (unsigned elem = 0; elem < elemsPerThreadPerGroup; elem++) {
if (!mfmaLayout.getIsTransposed()) {
elemOff[rank - 2] = ctaOffsetX * shapePerCta[rank - 2] + rowOrColOffset;
if (isMmacFuse) {
elemOff[rank - 1] =
ctaOffsetY * shapePerCta[rank - 1] + (elem % 4) * 16 + elem / 4;
} else
elemOff[rank - 1] = ctaOffsetY * shapePerCta[rank - 1] + elem * 4;
} else {
if (isMmacFuse) {
elemOff[rank - 2] =
ctaOffsetX * shapePerCta[rank - 2] + (elem % 4) * 16 + elem / 4;
} else
elemOff[rank - 2] = ctaOffsetX * shapePerCta[rank - 2] + elem * 4;
elemOff[rank - 1] = ctaOffsetY * shapePerCta[rank - 1] + rowOrColOffset;
}
if (rank == 3)
elemOff[0] = bOff;
offsets.push_back(elemOff);
}
}
}
inline SmallVector<SmallVector<unsigned>>
emitOffsetForMfmaLayout(const HCUMfmaEncodingAttr &mfmaLayout,
RankedTensorType type) {
auto tensorShape = type.getShape();
SmallVector<SmallVector<unsigned>> offsets;
auto shapePerCTA = getShapePerCTA(mfmaLayout, tensorShape);
auto warpsPerCTA = mfmaLayout.getWarpsPerCTA();
auto rank = type.getRank();
SmallVector<unsigned> numReps(rank);
unsigned mDim = mfmaLayout.getMDim();
unsigned nDim = mfmaLayout.getNDim();
assert((mDim == nDim && (mDim == 32 || mDim == 16 || mDim == 4)) ||
(mDim == 64 && nDim == 4) || (mDim == 4 && nDim == 64));
SmallVector<unsigned> shapePerWarp(rank, 1);
shapePerWarp[rank - 2] = mDim;
shapePerWarp[rank - 1] = nDim;
for (unsigned d = 0; d < rank; ++d) {
unsigned inPerCTA = std::min<unsigned>(tensorShape[d], shapePerCTA[d]);
unsigned inPerWarp = ceil<unsigned>(inPerCTA, warpsPerCTA[d]);
numReps[d] = ceil<unsigned>(inPerWarp, shapePerWarp[d]);
}
unsigned repBatch = rank == 3 ? numReps[0] : 1;
auto warpsPerBatch =
rank == 3 ? std::min<unsigned>(tensorShape[0], warpsPerCTA[0]) : 1;
for (unsigned b = 0; b < repBatch; ++b) {
for (unsigned i = 0; i < numReps[rank - 2]; ++i) {
for (unsigned j = 0; j < numReps[rank - 1]; ++j) {
emitMfmaOffsetForCTA(mfmaLayout, offsets, b * warpsPerBatch, i, j);
}
}
}
return offsets;
}
inline void emitWmmaOffsetForCTA(const HCUWmmaEncodingAttr &wmmaLayout,
SmallVector<SmallVector<unsigned>> &offsets,
unsigned ctaBatchOffset, unsigned ctaOffsetX,
unsigned ctaOffsetY) {
const unsigned elemsPerThreadPerGroup = 8;
auto warpSize = getWarpSize(wmmaLayout);
assert(warpSize == 32);
auto shapePerCta = getShapePerCTATile(wmmaLayout);
auto rank = shapePerCta.size();
assert(rank == 2 || rank == 3);
SmallVector<unsigned> elemOffset(rank, 0);
auto elemStride = wmmaLayout.getVersion() == 1 ? 2 : 1;
if (rank == 3)
elemOffset[0] = ctaBatchOffset;
for (unsigned elem = 0; elem < elemsPerThreadPerGroup; elem++) {
elemOffset[rank - 2] =
ctaOffsetX * shapePerCta[rank - 2] + elemStride * elem;
elemOffset[rank - 1] = ctaOffsetY * shapePerCta[rank - 1];
offsets.push_back(elemOffset);
}
}
inline SmallVector<Value>
emitBaseIndexForWmmaLayout(Location loc, RewriterBase &rewriter,
const HCUWmmaEncodingAttr &wmmaLayout,
RankedTensorType type) {
auto shape = type.getShape();
auto _warpsPerCTA = wmmaLayout.getWarpsPerCTA();
auto rank = _warpsPerCTA.size();
assert(rank == 2 || rank == 3);
SmallVector<Value> warpsPerCTA;
for (unsigned i = 0; i < rank; ++i)
warpsPerCTA.push_back(i32_val(_warpsPerCTA[i]));
auto mnkDim = HCUWmmaEncodingAttr::getMNKDimPerInstr();
Value threadId = getThreadId(rewriter, loc);
Value warpSize = i32_val(triton::gpu::getWarpSize(wmmaLayout));
Value laneId =
urem(threadId, i32_val(triton::gpu::getWarpSize(wmmaLayout) / 2));
Value threadIdPerWarp = urem(threadId, warpSize);
Value warpId = udiv(threadId, warpSize);
SmallVector<Value> multiDimWarpId =
delinearize(rewriter, loc, warpId, _warpsPerCTA,
triton::gpu::getWarpOrder(wmmaLayout));
if (shape[rank - 2] >= mnkDim[0]) {
assert(shape[rank - 2] % mnkDim[0] == 0);
multiDimWarpId[rank - 2] =
urem(multiDimWarpId[rank - 2],
i32_val(ceil<unsigned>(shape[rank - 2], mnkDim[0])));
}
if (shape[rank - 1] >= mnkDim[1]) {
assert(shape[rank - 1] % mnkDim[1] == 0);
multiDimWarpId[rank - 1] =
urem(multiDimWarpId[rank - 1],
i32_val(ceil<unsigned>(shape[rank - 1], mnkDim[1])));
}
Value offWarp0 = mul(multiDimWarpId[rank - 2], i32_val(mnkDim[0]));
Value offWarp1 = mul(multiDimWarpId[rank - 1], i32_val(mnkDim[1]));
SmallVector<Value> multiDimBase(rank);
auto ver = wmmaLayout.getVersion();
if (ver == 1) {
multiDimBase[rank - 2] =
add(udiv(threadIdPerWarp, i32_val(mnkDim[2])), offWarp0);
} else {
assert(ver == 2);
multiDimBase[rank - 2] =
add(mul(udiv(threadIdPerWarp, i32_val(mnkDim[2])),
i32_val(wmmaLayout.getSizePerThread()[rank - 2])),
offWarp0);