-
Notifications
You must be signed in to change notification settings - Fork 114
Expand file tree
/
Copy pathStructuredToMemref.cpp
More file actions
1209 lines (1024 loc) · 47.9 KB
/
Copy pathStructuredToMemref.cpp
File metadata and controls
1209 lines (1024 loc) · 47.9 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
//===----------------------------------------------------------------------===//
//
// Copyright (c) Microsoft Corporation, Meta Platforms.
// Licensed under the MIT license.
//
//===----------------------------------------------------------------------===//
#include "triton/Dialect/Triton/IR/Types.h"
#include "triton-shared/Analysis/OpFoldResultUtils.h"
#include "triton-shared/Conversion/StructuredToMemref/StructuredToMemref.h"
#include "triton-shared/Dialect/TritonStructured/IR/TritonStructuredDialect.h"
#include "mlir/IR/Builders.h"
#include "mlir/IR/BuiltinOps.h"
#include "mlir/IR/BuiltinTypeInterfaces.h"
#include "mlir/IR/BuiltinTypes.h"
#include "mlir/IR/MLIRContext.h"
#include "mlir/IR/OpDefinition.h"
#include "mlir/IR/TypeUtilities.h"
#include "mlir/IR/Types.h"
#include "mlir/Support/LogicalResult.h"
#include "mlir/Transforms/DialectConversion.h"
#include "mlir/Dialect/Arith/IR/Arith.h"
#include "mlir/Dialect/Bufferization/IR/Bufferization.h"
#include "mlir/Dialect/Linalg/IR/Linalg.h"
#include "mlir/Dialect/MemRef/IR//MemRef.h"
#include "mlir/Dialect/SCF/IR/SCF.h"
#include "mlir/Dialect/Utils/StaticValueUtils.h"
#include "llvm/ADT/ArrayRef.h"
#include "llvm/ADT/STLExtras.h"
#include "llvm/ADT/SmallVector.h"
#include "llvm/Support/ErrorHandling.h"
#include <algorithm>
#include <cassert>
#include <cstdint>
#define DEBUG_TYPE "structured-to-memref"
using namespace mlir;
#define GEN_PASS_CLASSES
#include "triton-shared/Conversion/TritonArithToLinalg/Passes.h.inc"
static const std::string WRAP_SIDE_BY_SIDE = "wrap_side_by_side";
static const std::string WRAP_STACKED = "wrap_stacked";
static memref::SubViewOp getSubview(int rank, ArrayRef<OpFoldResult> dims,
Value source, Location loc, OpBuilder &b) {
auto sourceType = cast<MemRefType>(source.getType());
SmallVector<OpFoldResult> offsets(rank, b.getIndexAttr(0));
SmallVector<OpFoldResult> strides(rank, b.getIndexAttr(1));
auto dstType =
memref::SubViewOp::inferResultType(sourceType, offsets, dims, strides);
return b.create<memref::SubViewOp>(loc, cast<MemRefType>(dstType), source,
offsets, dims, strides);
}
static Type getElementTypeStructuredPtr(tts::MakeTensorPtrOp op) {
assert(!op.isBlockPtr());
// tensor<1024x!tt.ptr<f32>>
auto ptrType = cast<triton::PointerType>(
cast<RankedTensorType>(op.getType()).getElementType());
return ptrType.getPointeeType();
}
static Type getElementTypeBlockPtr(tts::MakeTensorPtrOp op) {
assert(op.isBlockPtr());
// !tt.ptr<tensor<128x64xbf16>, 1>
auto shapedType = cast<ShapedType>(
cast<triton::PointerType>(op.getType()).getPointeeType());
return shapedType.getElementType();
}
static MemRefType getResultMemrefType(tts::MakeTensorPtrOp op, int64_t offset,
ArrayRef<int64_t> staticStrides,
ArrayRef<int64_t> resultShape) {
auto layout = StridedLayoutAttr::get(op.getContext(), offset, staticStrides);
Type elemType;
if (op.isBlockPtr()) {
elemType = getElementTypeBlockPtr(op);
} else {
elemType = getElementTypeStructuredPtr(op);
}
return MemRefType::get(resultShape, elemType, layout);
}
static MemRefType getResultMemrefType(tts::MakeGatherScatterTensorPtrOp op,
int64_t offset,
ArrayRef<int64_t> staticStrides,
ArrayRef<int64_t> resultShape) {
auto layout = StridedLayoutAttr::get(op.getContext(), offset, staticStrides);
auto ptrType = cast<triton::PointerType>(op.getType());
Type elemType = ptrType.getPointeeType();
Type realEltTy = cast<RankedTensorType>(elemType).getElementType();
return MemRefType::get(resultShape, realEltTy, layout);
}
// If there are dimensions with size 1 and stride 0, replace 0 stride with
// the product of sizes of all lower dimensions. This avoids creating memref
// with zero stride.
template <class OpType>
llvm::SmallVector<OpFoldResult> getMixedStridesForMemref(OpType op,
OpBuilder &b) {
llvm::SmallVector<OpFoldResult> strides;
auto accumulate = 1;
for (auto [size, stride] :
llvm::reverse(llvm::zip(op.getSizes(), op.getMixedStrides()))) {
auto strideIntAttr = getIntAttr(stride);
if (size == 1 && strideIntAttr && strideIntAttr.value() == 0) {
strides.push_back(b.getIndexAttr(accumulate));
} else if (auto v = llvm::dyn_cast_if_present<Value>(stride)) {
OpFoldResult result = getAsOpFoldResult(v);
strides.push_back(result);
} else {
strides.push_back(stride);
}
accumulate *= size;
}
std::reverse(strides.begin(), strides.end());
return strides;
}
static OpFoldResult accumulateTargetOffset(Location loc,
ArrayRef<OpFoldResult> offsets,
OpBuilder &b) {
OpFoldResult targetOffset = b.getIndexAttr(0);
for (auto o : offsets) {
targetOffset = addOFRs(targetOffset, o, loc, b);
}
return targetOffset;
}
static OpFoldResult accumulateTargetOffset(Location loc,
ArrayRef<OpFoldResult> offsets,
ArrayRef<OpFoldResult> strides,
int gatherDim, OpBuilder &b) {
OpFoldResult targetOffset = b.getIndexAttr(0);
for (int i = 0; i < offsets.size(); i++) {
OpFoldResult offset = offsets[i];
// If this is the gather dimension, multiply the offset by the stride.
// Non-gather dimensions are already multiplied by the stride
// in the offsets in PtrAnalysis.
if (i == gatherDim) {
OpFoldResult stride = strides[i];
offset = mulOFRs(offset, stride, loc, b);
}
targetOffset = addOFRs(targetOffset, offset, loc, b);
}
return targetOffset;
}
static Value rewriteGatherScatterPtrElement(
ArrayRef<int64_t> resultShape, tts::MakeGatherScatterTensorPtrOp op,
Value basePtr, Value gatherOffsetElt, int gatherDim,
ConversionPatternRewriter &rewriter) {
auto mixedStrides = getMixedStridesForMemref(op, rewriter);
SmallVector<int64_t> staticStrides;
SmallVector<Value> dynamicStrides;
dispatchIndexOpFoldResults(mixedStrides, dynamicStrides, staticStrides);
auto offsets = op.getMixedOffsets();
offsets[gatherDim] = gatherOffsetElt;
auto targetOffset = accumulateTargetOffset(op.getLoc(), offsets, mixedStrides,
gatherDim, rewriter);
auto staticTargetOffset = getIntAttr(targetOffset);
auto resultType =
getResultMemrefType(op, staticTargetOffset.value_or(ShapedType::kDynamic),
staticStrides, resultShape);
std::vector<int64_t> staticSizes = op.getSizes();
staticSizes[gatherDim] = 1;
SmallVector<Value> dynSizes; // sizes are always static
auto sizes = mlir::getMixedValues(staticSizes, dynSizes, rewriter);
auto castOp = rewriter.create<memref::ReinterpretCastOp>(
op.getLoc(), resultType, basePtr, targetOffset, sizes, mixedStrides);
return castOp.getResult();
}
// Fill load destination with other value for mask.
static void fillWithValue(Location loc, Value alloc, Value other,
ArrayRef<int64_t> shape,
SmallVector<OpFoldResult> &&mixedDims,
ArrayRef<int64_t> staticMaskDims,
ConversionPatternRewriter &rewriter) {
// Fill load destination with other value
// For each dimension check if dims[i] < shape[i], or-accumulate
// the result
auto accBase =
rewriter.create<arith::ConstantOp>(loc, rewriter.getBoolAttr(false))
.getResult();
for (size_t i = 0; i < shape.size(); i++) {
auto shapei = rewriter.create<arith::ConstantOp>(
loc, rewriter.getIndexAttr(shape[i]));
Value dimi = dyn_cast<Value>(mixedDims[i]);
if (!dimi) {
dimi = rewriter.create<arith::ConstantOp>(
loc, rewriter.getIndexAttr(staticMaskDims[i]));
}
Value cmp = rewriter.create<arith::CmpIOp>(loc, arith::CmpIPredicate::slt,
dimi, shapei);
accBase = rewriter.create<arith::OrIOp>(loc, accBase, cmp);
}
// condition the memset on the or-accumulation
// initialize with padding prior to CopyOp
rewriter.create<scf::IfOp>(loc, accBase, [&](OpBuilder &b, Location loc) {
b.create<linalg::FillOp>(loc, ValueRange{other}, ValueRange{alloc});
b.create<scf::YieldOp>(loc);
});
}
namespace {
struct MakeTensorPtrConverter
: public OpConversionPattern<tts::MakeTensorPtrOp> {
private:
using OpConversionPattern<tts::MakeTensorPtrOp>::OpConversionPattern;
static Type getElementTypeStructuredPtr(tts::MakeTensorPtrOp op) {
assert(!op.isBlockPtr());
// tensor<1024x!tt.ptr<f32>>
auto ptrType = cast<triton::PointerType>(
cast<RankedTensorType>(op.getType()).getElementType());
return ptrType.getPointeeType();
}
static Type getElementTypeBlockPtr(tts::MakeTensorPtrOp op) {
assert(op.isBlockPtr());
// !tt.ptr<tensor<128x64xbf16>, 1>
auto shapedType = cast<ShapedType>(
cast<triton::PointerType>(op.getType()).getPointeeType());
return shapedType.getElementType();
}
static MemRefType getResultMemrefType(tts::MakeTensorPtrOp op, int64_t offset,
ArrayRef<int64_t> staticStrides,
ArrayRef<int64_t> resultShape) {
auto layout =
StridedLayoutAttr::get(op.getContext(), offset, staticStrides);
Type elemType;
if (op.isBlockPtr()) {
elemType = getElementTypeBlockPtr(op);
} else {
elemType = getElementTypeStructuredPtr(op);
}
return MemRefType::get(resultShape, elemType, layout);
}
std::pair<memref::ReinterpretCastOp, memref::ReinterpretCastOp>
createSideBySideCastOps(tts::MakeTensorPtrOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const {
auto loc = op->getLoc();
auto resultShape = cast<RankedTensorType>(op.getType()).getShape();
auto targetOffset = ofrToIndexValue(
accumulateTargetOffset(op.getLoc(), op.getMixedOffsets(), rewriter),
loc, rewriter);
////////////////////////////////////////////////////////////////////////////
//
// Handling side-by-side wraparound
//
// Note: We do not support cases where the target has already overflown the
// number of columns! This is because in PtrAnalysis, the offset has already
// been collapsed into a single dimension, so it is ambiguous to determine
// whether the offset actually overflows or just refers to an element on the
// subsequent rows.
//
// Same limitations apply to the stacked wraparound case.
//
////////////////////////////////////////////////////////////////////////////
//
// nextOffset - targetOffset = colSize
// d1 + d2 = colSize
// N
// x clampedOffset
// --------------------------*----------------*-----*
// | | nextOffset (might
// | targetOffset | overflow)
// y *----- *----------------|
// | | | |
// M |----- -----------------|
// | d2 d1 |
// --------------------------------------------
//
// x = targetOffset % N
// nextOffset = x + colSize
// clampedOffset = min(nextOffset, N)
// d1 = clampedOffset - x
//
////////////////////////////////////////////////////////////////////////////
auto resultType = getResultMemrefType(
op, /* offset */ ShapedType::kDynamic,
/* staticStrides */
SmallVector<int64_t>(resultShape.size(), ShapedType::kDynamic),
/* result shape */
SmallVector<int64_t>{
// Row stays the same, but mlir doesn't allow this anymore. Put
// dynamic.
ShapedType::kDynamic,
// Column is dynamic, in most cases, this
// should be the same as the original column.
// The last chunk may be smaller due to
// wrapping around.
ShapedType::kDynamic});
Value rowSize = rewriter.create<arith::ConstantOp>(
loc, rewriter.getIndexAttr(op.getSizes()[0]));
Value colSize = rewriter.create<arith::ConstantOp>(
loc, rewriter.getIndexAttr(op.getSizes()[1]));
Value modN = ofrToIndexValue(op.getMixedShape()[1], loc, rewriter);
Value x = rewriter.create<arith::RemSIOp>(loc, targetOffset, modN);
Value y = rewriter.create<arith::SubIOp>(loc, targetOffset, x);
SmallVector<Value> strideVals =
ofrsToIndexValues(op.getMixedStrides(), loc, rewriter);
// First chunk
Value nextOffset = rewriter.create<arith::AddIOp>(loc, x, colSize);
Value clampedOffset =
rewriter.create<arith::MinSIOp>(loc, nextOffset, modN);
Value d1 = rewriter.create<arith::SubIOp>(loc, clampedOffset, x);
SmallVector<Value> sizes1{rowSize, d1};
auto cast1 = rewriter.create<memref::ReinterpretCastOp>(
loc, resultType, adaptor.getBase(), targetOffset, sizes1, strideVals);
// Second chunk
Value d2 = rewriter.create<arith::SubIOp>(loc, colSize, d1);
SmallVector<Value> sizes2{rowSize, d2};
auto cast2 = rewriter.create<memref::ReinterpretCastOp>(
loc, resultType, adaptor.getBase(), y, sizes2, strideVals);
return {cast1, cast2};
}
std::pair<memref::ReinterpretCastOp, memref::ReinterpretCastOp>
createStackedCastOps(tts::MakeTensorPtrOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const {
auto loc = op->getLoc();
auto resultShape = cast<RankedTensorType>(op.getType()).getShape();
assert(resultShape.size() == 2);
auto targetOffset = ofrToIndexValue(
accumulateTargetOffset(op.getLoc(), op.getMixedOffsets(), rewriter),
loc, rewriter);
////////////////////////////////////////////////////////////////////////////
//
// Handling stacked wraparound
//
// We do not support cases where the target offset has already overflown the
// number of rows. See side-by-side wraparound for details.
//
////////////////////////////////////////////////////////////////////////////
// We're loading a tensor of dim (rowSize, colSize)
// d1 + d2 = rowSize
// d2 is the number of rows that overflow
//
// cols
//
// wrappedAroundOff
// --------------*------------*--------
// | d2 | | |
// | |------------| |
// rows| |
// | |
// | targetOffset |
// | *------------| |
// | | | |
// | d1 | | |
// | | clampedOff | |
// --------------*---------------------
// | overflow |
// *-------------
// nextOff
//
// wrappedAroundOff = targetOffset % cols
// clampedOff = (rows * strideRows) + wrappedAroundOff
// ~~~~~~~~~~~~~~~~~
// ^
// |
// We have already computed
// rows * strideRows = modRow = shape[1]
// in TritonToStructured
//
// clampedOff - targetOffset
// d1 = --------------------
// strideRows
//
////////////////////////////////////////////////////////////////////////////
//
// cols
//
// wrappedAroundOff
// --------------*---------------------
// | |
// | targetOffset |
// | *------------| |
// | | | |
// | | | |
// rows| rowSize | | |
// | | | |
// | | | |
// | *------------| |
// | nextOff |
// | |
// | clampedOff |
// --------------*---------------------
//
// For the case that clampedOff is not overflown
// d1 = min(d1, rowSize)
//
auto resultType = getResultMemrefType(
op, /* offset */ ShapedType::kDynamic,
/* staticStrides */
SmallVector<int64_t>(resultShape.size(), ShapedType::kDynamic),
/* result shape */
SmallVector<int64_t>{
// Row is dynamic, in most cases, this should
// be the same as the original row. The last
// chunk may be smaller due to wrapping
// around.
ShapedType::kDynamic,
// Col stays the same, which is resultShape[1], but mlir doesn't
// allow this anymore. So we put dynamic instead.
ShapedType::kDynamic});
Value rowSize = rewriter.create<arith::ConstantOp>(
loc, rewriter.getIndexAttr(op.getSizes()[0]));
Value colSize = rewriter.create<arith::ConstantOp>(
loc, rewriter.getIndexAttr(op.getSizes()[1]));
Value strideRow = ofrToIndexValue(op.getMixedStrides()[0], loc, rewriter);
Value strideCol = ofrToIndexValue(op.getMixedStrides()[1], loc, rewriter);
Value modRow = ofrToIndexValue(op.getMixedShape()[0], loc, rewriter);
// First chunk
Value wrappedAroundOff =
rewriter.create<arith::RemSIOp>(loc, targetOffset, strideRow);
Value clampedOff =
rewriter.create<arith::AddIOp>(loc, modRow, wrappedAroundOff);
Value d1 = rewriter.create<arith::SubIOp>(loc, clampedOff, targetOffset);
d1 = rewriter.create<arith::DivSIOp>(loc, d1, strideRow);
d1 = rewriter.create<arith::MinSIOp>(loc, d1, rowSize);
SmallVector<Value> sizes1{d1, colSize};
memref::ReinterpretCastOp cast1 =
rewriter.create<memref::ReinterpretCastOp>(
loc, resultType, adaptor.getBase(), targetOffset, sizes1,
ValueRange{strideRow, strideCol});
// Second chunk
Value d2 = rewriter.create<arith::SubIOp>(loc, rowSize, d1);
SmallVector<Value> sizes2{d2, colSize};
memref::ReinterpretCastOp cast2 =
rewriter.create<memref::ReinterpretCastOp>(
loc, resultType, adaptor.getBase(), wrappedAroundOff, sizes2,
ValueRange{strideRow, strideCol});
return {cast1, cast2};
}
LogicalResult rewriteSplitPtr(tts::MakeTensorPtrOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const {
auto parentShape = op.getStaticShape();
assert(parentShape.size() == 2 &&
"Only support split pointer for 2D tensors only");
SmallVector<Value> casts;
StringRef wrapType;
// For split pointers, a split dimension is either a dynamic or a non-zero
// value. The other dimension must be zero.
auto isSplitDimension = [](int64_t dim) {
return dim == ShapedType::kDynamic || dim != 0;
};
if (isSplitDimension(parentShape[0])) {
// Stacked case
assert(parentShape[1] == 0);
auto [cast1, cast2] = createStackedCastOps(op, adaptor, rewriter);
casts = {cast1.getResult(), cast2.getResult()};
wrapType = WRAP_STACKED;
} else if (isSplitDimension(parentShape[1])) {
assert(parentShape[0] == 0);
auto [cast1, cast2] = createSideBySideCastOps(op, adaptor, rewriter);
casts = {cast1.getResult(), cast2.getResult()};
wrapType = WRAP_SIDE_BY_SIDE;
} else {
llvm_unreachable("Unexpected split pointer shape");
}
auto combinedCast = rewriter.create<UnrealizedConversionCastOp>(
op.getLoc(), op.getType(), casts);
combinedCast->setAttr(wrapType, rewriter.getUnitAttr());
rewriter.replaceOp(op, combinedCast);
return success();
}
LogicalResult rewritePtr(ArrayRef<int64_t> resultShape, bool isBlockPtr,
tts::MakeTensorPtrOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const {
auto mixedStrides = getMixedStridesForMemref(op, rewriter);
SmallVector<int64_t> staticStrides;
SmallVector<Value> dynamicStrides;
dispatchIndexOpFoldResults(mixedStrides, dynamicStrides, staticStrides);
auto targetOffset =
accumulateTargetOffset(op.getLoc(), op.getMixedOffsets(), rewriter);
auto staticTargetOffset = getIntAttr(targetOffset);
auto resultType = getResultMemrefType(
op, staticTargetOffset.value_or(ShapedType::kDynamic), staticStrides,
resultShape);
auto castOp = rewriter.create<memref::ReinterpretCastOp>(
op.getLoc(), resultType, adaptor.getBase(), targetOffset,
op.getMixedSizes(), mixedStrides);
rewriter.replaceOp(op, castOp);
return success();
}
LogicalResult
rewriteStructuredPtr(tts::MakeTensorPtrOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const {
ArrayRef<int64_t> resultShape = cast<ShapedType>(op.getType()).getShape();
return rewritePtr(resultShape, false, op, adaptor, rewriter);
}
LogicalResult rewriteBlockPtr(tts::MakeTensorPtrOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const {
// Block pointers are basically the same as structured pointers except that
// the return types are !tt.ptr<tensor<AxBxCxbf16>> instead of
// tensor<AxBxCx!tt.ptr<bf16>>
ArrayRef<int64_t> resultShape =
cast<ShapedType>(
cast<triton::PointerType>(op.getType()).getPointeeType())
.getShape();
return rewritePtr(resultShape, true, op, adaptor, rewriter);
}
public:
MakeTensorPtrConverter(const TypeConverter &typeConverter,
MLIRContext *context)
: OpConversionPattern<tts::MakeTensorPtrOp>(typeConverter, context) {}
LogicalResult
matchAndRewrite(tts::MakeTensorPtrOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
if (!llvm::is_sorted(op.getOrder(), std::greater<>())) {
emitError(op.getLoc()) << "non-decreasing dimension order on tensor "
"pointers are not yet supported";
return failure();
}
if (op.isBlockPtr()) {
return rewriteBlockPtr(op, adaptor, rewriter);
}
if (op.isStructuredPtr()) {
return rewriteStructuredPtr(op, adaptor, rewriter);
}
if (op.isSplitPtr()) {
return rewriteSplitPtr(op, adaptor, rewriter);
}
return failure();
}
};
struct MakeGatherScatterTensorPtrConverter
: public OpConversionPattern<tts::MakeGatherScatterTensorPtrOp> {
using OpConversionPattern::OpConversionPattern;
LogicalResult
matchAndRewrite(tts::MakeGatherScatterTensorPtrOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const override {
// The gatherScatterPtr is rewritten as separate rows during load/store
// operations. Therefore, no action is needed here except saving
// adaptor.getBase(). DialectConversion will ignore pure type conversion if
// we were to simply replace the op with adaptor.getBase(). To circumvent
// this we create an identity cast.
rewriter.replaceOpWithNewOp<UnrealizedConversionCastOp>(
op, adaptor.getBase().getType(), adaptor.getBase());
return success();
}
};
struct LoadConverter : public OpConversionPattern<tts::LoadOp> {
private:
using OpConversionPattern<tts::LoadOp>::OpConversionPattern;
void createSideBySideCopies(Value block1, Value block2, Value dst,
Location loc,
ConversionPatternRewriter &rewriter) const {
auto zero =
rewriter.create<arith::ConstantOp>(loc, rewriter.getIndexAttr(0));
auto one =
rewriter.create<arith::ConstantOp>(loc, rewriter.getIndexAttr(1));
Value block1Row = rewriter.create<memref::DimOp>(loc, block1, 0);
Value block1Col = rewriter.create<memref::DimOp>(loc, block1, 1);
Value block2Row = rewriter.create<memref::DimOp>(loc, block2, 0);
Value block2Col = rewriter.create<memref::DimOp>(loc, block2, 1);
auto block1Dst =
rewriter.create<memref::SubViewOp>(loc, dst, /* offsets */
ValueRange{zero, zero},
/* sizes */
ValueRange{block1Row, block1Col},
/* strides */
ValueRange{one, one});
auto block2Dst =
rewriter.create<memref::SubViewOp>(loc, dst,
/* offsets */
ValueRange{zero, block1Col},
/* sizes */
ValueRange{block2Row, block2Col},
/* strides */
ValueRange{one, one});
rewriter.create<memref::CopyOp>(loc, block1, block1Dst);
rewriter.create<memref::CopyOp>(loc, block2, block2Dst);
}
void createStackedCopies(Value block1, Value block2, Value dst, Location loc,
ConversionPatternRewriter &rewriter) const {
auto zero =
rewriter.create<arith::ConstantOp>(loc, rewriter.getIndexAttr(0));
auto one =
rewriter.create<arith::ConstantOp>(loc, rewriter.getIndexAttr(1));
Value block1Row = rewriter.create<memref::DimOp>(loc, block1, 0);
Value block1Col = rewriter.create<memref::DimOp>(loc, block1, 1);
Value block2Row = rewriter.create<memref::DimOp>(loc, block2, 0);
Value block2Col = rewriter.create<memref::DimOp>(loc, block2, 1);
auto block1Dst =
rewriter.create<memref::SubViewOp>(loc, dst, /* offsets */
ValueRange{zero, zero},
/* sizes */
ValueRange{block1Row, block1Col},
/* strides */
ValueRange{one, one});
auto block2Dst =
rewriter.create<memref::SubViewOp>(loc, dst,
/* offsets */
ValueRange{block1Row, zero},
/* sizes */
ValueRange{block2Row, block2Col},
/* strides */
ValueRange{one, one});
rewriter.create<memref::CopyOp>(loc, block1, block1Dst);
rewriter.create<memref::CopyOp>(loc, block2, block2Dst);
}
memref::SubViewOp createSubview(Value src, ArrayRef<OpFoldResult> offsets,
ArrayRef<OpFoldResult> sizes,
ArrayRef<OpFoldResult> strides, Location loc,
ConversionPatternRewriter &rewriter) const {
auto srcType = cast<MemRefType>(src.getType());
auto dstType =
memref::SubViewOp::inferResultType(srcType, offsets, sizes, strides);
return rewriter.create<memref::SubViewOp>(loc, cast<MemRefType>(dstType),
src, offsets, sizes, strides);
}
std::pair<memref::SubViewOp, memref::SubViewOp>
getSideBySideSubviews(ArrayRef<OpFoldResult> dims, Value block1, Value block2,
Location loc,
ConversionPatternRewriter &rewriter) const {
OpFoldResult subviewRowFull = dims[0];
OpFoldResult subviewColFull = dims[1];
OpFoldResult subviewCol1 =
rewriter.create<memref::DimOp>(loc, block1, 1).getResult();
OpFoldResult subviewCol2 =
rewriter.create<memref::DimOp>(loc, block2, 1).getResult();
SmallVector<OpFoldResult> offsets(dims.size(), rewriter.getIndexAttr(0));
SmallVector<OpFoldResult> strides(dims.size(), rewriter.getIndexAttr(1));
auto sv1 = createSubview(block1, offsets, {subviewRowFull, subviewCol1},
strides, loc, rewriter);
auto sv2 = createSubview(block2, offsets, {subviewRowFull, subviewCol2},
strides, loc, rewriter);
return {sv1, sv2};
}
std::pair<memref::SubViewOp, memref::SubViewOp>
getStackedSubviews(ArrayRef<OpFoldResult> dims, Value block1, Value block2,
const Location loc,
ConversionPatternRewriter &rewriter) const {
OpFoldResult subviewRowFull = dims[0];
OpFoldResult subviewColFull = dims[1];
OpFoldResult subviewRow1 =
rewriter.create<memref::DimOp>(loc, block1, 0).getResult();
OpFoldResult subviewRow2 =
rewriter.create<memref::DimOp>(loc, block2, 0).getResult();
SmallVector<OpFoldResult> offsets(dims.size(), rewriter.getIndexAttr(0));
SmallVector<OpFoldResult> strides(dims.size(), rewriter.getIndexAttr(1));
auto sv1 = createSubview(block1, offsets, {subviewRow1, subviewColFull},
strides, loc, rewriter);
auto sv2 = createSubview(block2, offsets, {subviewRow2, subviewColFull},
strides, loc, rewriter);
return {sv1, sv2};
}
LogicalResult
rewriteStructuredLoad(tts::LoadOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const {
assert(!op.hasMask());
auto loc = op->getLoc();
auto ptr = adaptor.getPtr();
auto other = op.getOther();
auto tensorType = cast<RankedTensorType>(op.getType());
auto elemType = tensorType.getElementType();
auto alloc = rewriter.create<memref::AllocOp>(
loc, MemRefType::get(tensorType.getShape(), elemType));
// No mask
assert(!other && "other value used in non-masked load");
auto ptrDefiningOp = ptr.getDefiningOp();
if (ptrDefiningOp->hasAttr(WRAP_SIDE_BY_SIDE) ||
ptrDefiningOp->hasAttr(WRAP_STACKED)) {
auto unrealizedCast = cast<UnrealizedConversionCastOp>(ptrDefiningOp);
auto memrefs = unrealizedCast.getOperands();
assert(memrefs.size() == 2);
auto block1 = memrefs[0];
auto block2 = memrefs[1];
if (unrealizedCast->hasAttr(WRAP_SIDE_BY_SIDE)) {
createSideBySideCopies(block1, block2, alloc, loc, rewriter);
} else if (unrealizedCast->hasAttr(WRAP_STACKED)) {
createStackedCopies(block1, block2, alloc, loc, rewriter);
} else {
llvm_unreachable("unexpected wraparound type");
}
} else {
rewriter.create<memref::CopyOp>(loc, ptr, alloc);
}
Value tensor = rewriter.create<bufferization::ToTensorOp>(
loc, tensorType, alloc, true /* restrict */, true /* writable */);
rewriter.replaceOp(op, tensor);
return success();
}
LogicalResult rewriteMaskedLoad(tts::LoadOp op, OpAdaptor adaptor,
ConversionPatternRewriter &rewriter) const {
assert(op.hasMask());
auto loc = op->getLoc();
auto ptr = adaptor.getPtr();
auto tensorType = cast<RankedTensorType>(op.getType());
auto elemType = tensorType.getElementType();
auto alloc = rewriter.create<memref::AllocOp>(
loc, MemRefType::get(tensorType.getShape(), elemType));
SmallVector<OpFoldResult> mixedDims = op.getMixedMaskDims();
// Fill load destination with other value
Value other = op.getOther();
if (!other) {
other = rewriter.create<arith::ConstantOp>(
loc, rewriter.getZeroAttr(elemType));
}
fillWithValue(loc, alloc, other, tensorType.getShape(),
op.getMixedMaskDims(), op.getStaticMaskDims(), rewriter);
auto ptrDefiningOp = ptr.getDefiningOp();
if (ptrDefiningOp->hasAttr(WRAP_SIDE_BY_SIDE) ||
ptrDefiningOp->hasAttr(WRAP_STACKED)) {
auto unrealizedCast = cast<UnrealizedConversionCastOp>(ptrDefiningOp);
auto memrefs = unrealizedCast.getOperands();
assert(memrefs.size() == 2);
auto block1 = memrefs[0];
auto block2 = memrefs[1];
if (unrealizedCast->hasAttr(WRAP_SIDE_BY_SIDE)) {
auto [subview1, subview2] =
getSideBySideSubviews(mixedDims, block1, block2, loc, rewriter);
createSideBySideCopies(subview1, subview2, alloc, loc, rewriter);
} else if (unrealizedCast->hasAttr(WRAP_STACKED)) {
auto [subview1, subview2] =
getStackedSubviews(mixedDims, block1, block2, loc, rewriter);
createStackedCopies(subview1, subview2, alloc, loc, rewriter);
} else {
llvm_unreachable("unexpected wraparound type");
}
rewriter.eraseOp(unrealizedCast);
} else {
memref::SubViewOp srcSubview =
getSubview(tensorType.getRank(), mixedDims, ptr, loc, rewriter);
memref::SubViewOp dstSubview =
getSubview(tensorType.getRank(), mixedDims, alloc, loc, rewriter);
rewriter.create<memref::CopyOp>(loc, srcSubview, dstSubview);
}
Value tensor = rewriter.create<bufferization::ToTensorOp>(
loc, tensorType, alloc, true /* restrict */, true /* writable */);
rewriter.replaceOp(op, tensor);
return success();
}
LogicalResult rewriteGather(tts::MakeGatherScatterTensorPtrOp ptr,
tts::LoadOp op, Value memRefPtr,
ConversionPatternRewriter &rewriter) const {
auto loc = op.getLoc();
Value gatherOffset = ptr.getGatherScatterOffset();
// Cast gatherOffset to index
auto offsetShapedType = cast<ShapedType>(gatherOffset.getType());
unsigned offsetSize = offsetShapedType.getShape()[0];
auto indexOffsetTy = RankedTensorType::get(offsetShapedType.getShape(),
rewriter.getIndexType());
gatherOffset =
rewriter.create<arith::IndexCastOp>(loc, indexOffsetTy, gatherOffset)
.getResult();
int gatherDim = ptr.getGatherScatterDim();
auto offsets = ptr.getMixedOffsets();
auto strides = ptr.getMixedStrides();
std::vector<int64_t> staticSizes = ptr.getSizes();
staticSizes[gatherDim] = 1;
SmallVector<Value> dynSizes; // sizes are always static
auto sizes = mlir::getMixedValues(staticSizes, dynSizes, rewriter);
// Create alloc to save the result.
auto resultType = dyn_cast<RankedTensorType>(op.getResult().getType());
auto allocType =
MemRefType::get(resultType.getShape(), resultType.getElementType());
auto alloc = rewriter.create<memref::AllocOp>(loc, allocType);
auto allocStrides = mlir::getMixedValues(
allocType.getStridesAndOffset().first, dynSizes, rewriter);
// Fill load destination with other value
if (Value other = op.getOther()) {
fillWithValue(loc, alloc, other, resultType.getShape(),
op.getMixedMaskDims(), op.getStaticMaskDims(), rewriter);
}
// Create loop to iterate every offset in gatherOffset.
auto lowerBound = rewriter.create<arith::ConstantIndexOp>(loc, 0);
Value upperBound =
rewriter.create<arith::ConstantIndexOp>(loc, offsetSize).getResult();
if (op.hasMask()) {
SmallVector<OpFoldResult> mixedDims = op.getMixedMaskDims();
OpFoldResult gatherMaskDim = mixedDims[gatherDim];
// If gatherMaskDim is a immediate, we can just update the offsetSize
// to the value of gatherMaskDim.
// Otherwise, we will need to compare the induction variable with
// gatherMaskDim to guard the load.
if (auto gatherMaskDimIndex = getIntAttr(gatherMaskDim)) {
// If the gather mask dimension is a constant, we can use it directly.
unsigned gatherMaskDimValue = gatherMaskDimIndex.value();
if (gatherMaskDimValue == 0 && ptr.getGatherScatterMask()) {
// For unstructured mask case, loop over all elements and use the
// unstructured mask to guard the store.
gatherMaskDimValue = offsetSize;
}
offsetSize = std::min(offsetSize, gatherMaskDimValue);
upperBound = rewriter.create<arith::ConstantIndexOp>(loc, offsetSize)
.getResult();
} else {
// Use arith::MinSIOp to get the minimum value of gatherMaskDim
// and offsetSize.
auto gatherMaskDimVal = cast<Value>(gatherMaskDim);
auto offsetSizeVal =
rewriter.create<arith::ConstantIndexOp>(loc, offsetSize);
upperBound =
rewriter
.create<arith::MinSIOp>(loc, gatherMaskDimVal, offsetSizeVal)
.getResult();
}
}
auto step = rewriter.create<arith::ConstantIndexOp>(loc, 1);
auto loop = rewriter.create<scf::ForOp>(loc, lowerBound, upperBound, step);
// Create tensor from alloc and use it as the result to replace op.
Value tensor = rewriter.create<bufferization::ToTensorOp>(
loc, op.getType(), alloc, true /* restrict */, true /* writable */);
rewriter.replaceOp(op, tensor);
// Build loop body.
rewriter.setInsertionPointToStart(loop.getBody());
Value inductionVar = loop.getInductionVar();
if (Value unstructuredMask = ptr.getGatherScatterMask()) {
// If the gather scatter mask is present, we need to use it to guard the
// load.
auto maskValue = rewriter.create<tensor::ExtractOp>(
loc, unstructuredMask, ValueRange{inductionVar});
auto ifOp = rewriter.create<scf::IfOp>(loc, maskValue);
rewriter.setInsertionPointToStart(&ifOp.getThenRegion().front());
}
// Load the offsetElt first.
auto gatherOffsetElt = rewriter.create<tensor::ExtractOp>(
loc, gatherOffset, ValueRange{inductionVar});
// reinterpret_cast to current row as memRefPtr[gatherOffsetElt].
Value srcPtr = rewriteGatherScatterPtrElement(staticSizes, ptr, memRefPtr,
gatherOffsetElt.getResult(),
gatherDim, rewriter);
unsigned rank = ptr.getSizes().size();
// The subview should not apply an additional stride to the source.
SmallVector<OpFoldResult> oneStrides(rank, OpFoldResult(step));
// subview from srcPtr for mask.
// With offsets[gatherDim] set to 0 since the offset already in
// reinterpret_cast. With sizes[gatherDim] set to 1 since we are load one
// row each time.
if (op.hasMask()) {
SmallVector<OpFoldResult> mixedDims = op.getMixedMaskDims();
mixedDims[gatherDim] = sizes[gatherDim];
sizes = mixedDims;
// maskOffsets should be all zero, since srcPtr already has the offsets.
SmallVector<OpFoldResult> maskOffsets(rank, OpFoldResult(lowerBound));
// Use oneStrides for subview.
auto dstSubViewType = memref::SubViewOp::inferResultType(
cast<MemRefType>(srcPtr.getType()), maskOffsets, sizes, oneStrides);
srcPtr =
rewriter
.create<memref::SubViewOp>(loc, cast<MemRefType>(dstSubViewType),
srcPtr, maskOffsets, sizes, oneStrides)
.getResult();
}
// alloc[inductionVar]
SmallVector<OpFoldResult> allocOffsets(rank, OpFoldResult(lowerBound));
allocOffsets[gatherDim] = inductionVar;
auto dstAllocType = memref::SubViewOp::inferResultType(
allocType, allocOffsets, sizes, oneStrides);
auto dstSubview = rewriter.create<memref::SubViewOp>(
loc, cast<MemRefType>(dstAllocType), alloc, allocOffsets, sizes,
oneStrides);
// Copy srcPtr to alloc[inductionVar].
rewriter.create<memref::CopyOp>(loc, srcPtr, dstSubview);
return success();
}
public:
LoadConverter(const TypeConverter &typeConverter, MLIRContext *context)
: OpConversionPattern<tts::LoadOp>(typeConverter, context) {}