Skip to content

Commit 15c5e55

Browse files
authored
[BACKEND] Improve detection of register to register conversion (#4991)
Specifically, it fixes problems when `srcLayout` and `dstLayout` have different number of registers but the same number of not free registers. We solved the problem by padding free registers to either `srcLayout` or `dstLayout`, but this can be improved by fixing the `invertAndCompose` function.
1 parent d31ccfe commit 15c5e55

File tree

7 files changed

+202
-24
lines changed

7 files changed

+202
-24
lines changed

include/triton/Analysis/Utility.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -212,7 +212,7 @@ bool cvtNeedsSharedMemory(RankedTensorType srcTy, RankedTensorType dstTy);
212212

213213
bool atomicNeedsSharedMemory(Value result);
214214

215-
bool isBlockedToDotShortcut(RankedTensorType &srcTy, RankedTensorType &dstT);
215+
bool isBlockedToDotShortcut(RankedTensorType srcTy, RankedTensorType dstTy);
216216

217217
bool isMfmaToDotShortcut(RankedTensorType srcTy, RankedTensorType dstTy);
218218

include/triton/Tools/LinearLayout.h

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -679,6 +679,13 @@ class LinearLayout {
679679
// (i.e. every input bit affects the output).
680680
llvm::MapVector<StringAttr, int32_t> getFreeVariableMasks() const;
681681

682+
// Increase an input dimension without affecting the output dimension. The
683+
// added free variables are mapped to 0, ensuring that the new input
684+
// dimensions correspond directly to the existing output space. The function
685+
// errors out if `newInDimSize` is less than the current size or the new size
686+
// is not a power of 2.
687+
LinearLayout resize(StringAttr inDim, int32_t newInDimSize) const;
688+
682689
std::string toString() const;
683690

684691
friend bool operator==(LinearLayout lhs, LinearLayout rhs);

lib/Analysis/Utility.cpp

Lines changed: 40 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -536,7 +536,7 @@ bool supportMMA(Value value, int version) {
536536
(elemTy.isInteger(8) && version >= 2);
537537
}
538538

539-
bool isBlockedToDotShortcut(RankedTensorType &srcTy, RankedTensorType &dstTy) {
539+
bool isBlockedToDotShortcut(RankedTensorType srcTy, RankedTensorType dstTy) {
540540
auto blockedLayout = dyn_cast<BlockedEncodingAttr>(srcTy.getEncoding());
541541
auto dotOperandLayout = dyn_cast<DotOperandEncodingAttr>(dstTy.getEncoding());
542542
if (blockedLayout == nullptr || dotOperandLayout == nullptr)
@@ -655,8 +655,46 @@ std::optional<LinearLayout> minimalCvtLayout(RankedTensorType srcTy,
655655
toLinearLayout(dstTy.getShape(), dstTy.getEncoding());
656656
if (!(srcLayout.has_value() && dstLayout.has_value()))
657657
return std::nullopt;
658+
StringAttr kRegister = StringAttr::get(ctx, "register");
659+
StringAttr kLane = StringAttr::get(ctx, "lane");
660+
StringAttr kWarp = StringAttr::get(ctx, "warp");
661+
StringAttr kBlock = StringAttr::get(ctx, "block");
662+
auto numSrcRegs = srcLayout->getInDimSize(kRegister);
663+
auto numDstRegs = dstLayout->getInDimSize(kRegister);
664+
// The `invertAndCompose` function will generate a layout that is injective
665+
// by assigning new output dimensions to free variables. For instance,
666+
// consider a scenario where `srcLayout` has a free variable in the lane
667+
// dimension, while `dstLayout` has two free variables in the lane
668+
// dimension and also a larger number of registers.
669+
// The injective form of `srcLayout` will add only a single additional row
670+
// to the transformation matrix, whereas the injective form of `dstLayout`
671+
// will add two additional rows. This discrepancy causes misleading results
672+
// because the matrices end up with a different number of rows.
673+
//
674+
// Take `dstLayout ⋅ srcLayout^-1` as an example:
675+
//
676+
// - `injective(dstLayout)`: [n, m] → [n + 2, m]
677+
// - `injective(srcLayout)`: [n, m] → [n + 1, m]
678+
// - `injective(srcLayout)^-1`: [n + 1, m] → [m, n + 1]
679+
// - `injective(dstLayout) ⋅ injective(srcLayout)^-1`: [n + 2, m] ⋅ [m, n +
680+
// 1] → [n + 2, n + 1]
681+
//
682+
// Here, the `(n + 1)`-th row added by `dstLayout` represents the free
683+
// variable in registers, and the `(n + 2)`-th row represents the free
684+
// variable in lanes. However, the `(n + 1)`-th row added by `srcLayout`
685+
// represents the free variable in lanes. As a result, the `(n + 1)`-th row
686+
// in two layouts do not correspond to the same free variable.
687+
//
688+
// To address this issue, we pad the free variables in `srcLayout` and
689+
// `dstLayout` to ensure they have the same number of registers. This
690+
// guarantees that the resulting matrices have the same number of rows,
691+
// ensuring consistency in the composition process.
692+
auto numRegs = std::max(numSrcRegs, numDstRegs);
693+
auto srcLayoutWithFreeRegs = srcLayout->resize(kRegister, numRegs);
694+
auto dstLayoutWithFreeRegs = dstLayout->resize(kRegister, numRegs);
658695
// comp describes the layout function to create dst from src.
659-
LinearLayout comp = dstLayout->invertAndCompose(*srcLayout);
696+
LinearLayout comp =
697+
dstLayoutWithFreeRegs.invertAndCompose(srcLayoutWithFreeRegs);
660698
// We try to quotient by the largest subspace first
661699
auto dims = SmallVector<StringRef>{"block", "warp", "lane", "register"};
662700
for (auto dim : dims) {

lib/Conversion/TritonGPUToLLVM/ConvertLayoutOpToLLVM.cpp

Lines changed: 32 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -288,60 +288,71 @@ struct ConvertLayoutOpUsingLinearLayoutsConversion
288288
return rewriter.notifyMatchFailure(
289289
op, "NYI. srcTy and/or dstTy don't implement LLs yet");
290290
}
291+
LinearLayout srcLayout =
292+
*toLinearLayout(srcTy.getShape(), srcTy.getEncoding());
293+
LinearLayout dstLayout =
294+
*toLinearLayout(dstTy.getShape(), dstTy.getEncoding());
295+
296+
StringAttr kBlock = str_attr("block");
297+
StringAttr kWarp = str_attr("warp");
298+
StringAttr kLane = str_attr("lane");
299+
StringAttr kRegister = str_attr("register");
291300

292301
assert(to_vector(conversion->getInDimNames()) ==
293302
to_vector(conversion->getOutDimNames()));
294303
auto dims = conversion->getInDimNames();
295-
if (llvm::is_contained(dims, str_attr("block"))) {
304+
if (llvm::is_contained(dims, kBlock)) {
296305
// Case 1: Transfer between values in different CTAs.
297306
// This requires moving values through distributed shared memory.
298307
return rewriter.notifyMatchFailure(
299308
op, "NYI: Transfer between different CTAs");
300-
} else if (llvm::is_contained(dims, str_attr("warp"))) {
309+
} else if (llvm::is_contained(dims, kWarp)) {
301310
// Case 2: Transfer between values in the same CTA, in which case we move
302311
// values through shared memory.
303-
LinearLayout srcLayout =
304-
*toLinearLayout(srcTy.getShape(), srcTy.getEncoding());
305-
LinearLayout dstLayout =
306-
*toLinearLayout(dstTy.getShape(), dstTy.getEncoding());
307312
return transferWithinBlock(op, srcLayout, dstLayout, adaptor, rewriter);
308-
} else if (llvm::is_contained(dims, str_attr("lane"))) {
313+
} else if (llvm::is_contained(dims, kLane)) {
309314
// Case 3. Transfer between values in the same warp, in which case we try
310315
// to move values using warp shuffles, though if the pattern is
311316
// complicated enough we may fall back to using shared memory
312317
// TODO(Keren): implement warp shuffle instead of using the general
313318
// approach that uses shared memory
314-
LinearLayout srcLayout =
315-
*toLinearLayout(srcTy.getShape(), srcTy.getEncoding());
316-
LinearLayout dstLayout =
317-
*toLinearLayout(dstTy.getShape(), dstTy.getEncoding());
318319
return transferWithinBlock(op, srcLayout, dstLayout, adaptor, rewriter);
319-
} else if (llvm::is_contained(dims, str_attr("register"))) {
320+
} else if (llvm::is_contained(dims, kRegister) ||
321+
dstLayout.getInDimSize(kRegister) !=
322+
srcLayout.getInDimSize(kRegister)) {
320323
// Case 4. Transfer between values in the same thread, in which case we
321324
// simply reorder the elements of adaptor.getSrc().
322-
return transferWithinThread(op, *conversion, adaptor, rewriter);
325+
return transferWithinThread(
326+
op, dstLayout.getFreeVariableMasks()[kRegister],
327+
dstLayout.getInDimSize(kRegister), *conversion, adaptor, rewriter);
323328
} else {
324-
// The two layouts are equivalent. We should probably remove these in
325-
// RemoveLayoutConversion.
329+
// Cast 5. The two layouts are equivalent. We should probably remove
330+
// these in RemoveLayoutConversion.
326331
rewriter.replaceOp(op, adaptor.getSrc());
327332
return success();
328333
}
329334
}
330335

331336
LogicalResult
332-
transferWithinThread(ConvertLayoutOp op, const LinearLayout &conversion,
333-
OpAdaptor adaptor,
337+
transferWithinThread(ConvertLayoutOp op, int32_t regMasks, int32_t numRegs,
338+
const LinearLayout &conversion, OpAdaptor adaptor,
334339
ConversionPatternRewriter &rewriter) const {
335340
MLIRContext *ctx = op.getContext();
336341
auto loc = op.getLoc();
337342
StringAttr kRegister = str_attr("register");
338343
assert(!cvtNeedsSharedMemory(op.getSrc().getType(), op.getType()));
339344

340345
auto inVals = unpackLLElements(loc, adaptor.getSrc(), rewriter);
341-
SmallVector<Value> outVals;
342-
outVals.resize(conversion.getInDimSize(kRegister));
343-
for (int i = 0; i < conversion.getInDimSize(kRegister); i++) {
344-
auto srcIdx = conversion.apply({{kRegister, i}}).begin()->second;
346+
SmallVector<Value> outVals(numRegs);
347+
for (int i = 0; i < outVals.size(); i++) {
348+
// Remove free masks from the register index
349+
// For example, if idx = 0b00111, and masks = 0b00100, then we get
350+
// 0b00011. It means that register 7 (0b111) has the same value as
351+
// register 3 (0b011).
352+
auto idx = i & (~regMasks);
353+
auto srcIdx = conversion.hasInDim(kRegister)
354+
? conversion.apply({{kRegister, idx}}).begin()->second
355+
: idx;
345356
outVals[i] = inVals[srcIdx];
346357
}
347358
Value result = packLLElements(loc, getTypeConverter(), outVals, rewriter,

lib/Tools/LinearLayout.cpp

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1016,6 +1016,21 @@ bool LinearLayout::equalIgnoringOutDimSizes(const LinearLayout &other) const {
10161016
return true;
10171017
}
10181018

1019+
LinearLayout LinearLayout::resize(StringAttr inDim,
1020+
int32_t newInDimSize) const {
1021+
BasesT bases = getBases();
1022+
assert(bases.contains(inDim) && "inDim not in layout");
1023+
assert(llvm::isPowerOf2_32(newInDimSize) &&
1024+
"newInDimSize must be a power of 2");
1025+
assert(newInDimSize >= getInDimSize(inDim) &&
1026+
"newInDimSize must be >= old size");
1027+
auto numFreeVariables = llvm::Log2_32(newInDimSize) - getInDimSizeLog2(inDim);
1028+
for (int i = 0; i < numFreeVariables; i++) {
1029+
bases[inDim].push_back(std::vector<int32_t>(getNumOutDims(), 0));
1030+
}
1031+
return LinearLayout(std::move(bases), llvm::to_vector(getOutDimNames()));
1032+
}
1033+
10191034
std::string LinearLayout::toString() const {
10201035
// Start with a newline because we print out a bulleted list; it doesn't
10211036
// make sense for the first line of this list to be on the same line as

test/Conversion/tritongpu_to_llvm.mlir

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -847,6 +847,80 @@ module attributes {"triton_gpu.num-ctas" = 1 : i32, "triton_gpu.num-warps" = 4 :
847847

848848
// -----
849849

850+
#mma = #triton_gpu.nvidia_mma<{versionMajor = 2, warpsPerCTA = [1, 1], CTAsPerCGA = [1, 1], CTASplitNum = [1, 1], CTAOrder = [0, 1], instrShape = [16, 8]}>
851+
#dot1 = #triton_gpu.dot_op<{opIdx=0, parent=#mma, kWidth=2}>
852+
module attributes {"triton_gpu.num-ctas" = 1 : i32, "triton_gpu.num-warps" = 1 : i32} {
853+
// CHECK-LABEL: convert_layout_mmav2_dot_reg
854+
tt.func @convert_layout_mmav2_dot_reg(%arg0: tensor<16x16xf16, #mma>) {
855+
// CHECK-NOT: st.shared
856+
// CHECK-NOT: llvm.load
857+
%0 = triton_gpu.convert_layout %arg0 : tensor<16x16xf16, #mma> -> tensor<16x16xf16, #dot1>
858+
tt.return
859+
}
860+
}
861+
862+
// -----
863+
864+
#mma0 = #triton_gpu.nvidia_mma<{versionMajor = 3, versionMinor = 0, warpsPerCTA = [4, 1], instrShape = [16, 64, 16]}>
865+
#mma1 = #triton_gpu.nvidia_mma<{versionMajor = 3, versionMinor = 0, warpsPerCTA = [4, 1], instrShape = [16, 128, 16]}>
866+
867+
module attributes {"triton_gpu.num-ctas" = 1 : i32, "triton_gpu.num-warps" = 4 : i32} {
868+
// CHECK-LABEL: convert_layout_mmav3_mmav3_0
869+
tt.func @convert_layout_mmav3_mmav3_0(%arg0: tensor<64x64xf16, #mma0>) {
870+
// CHECK-NOT: st.shared
871+
// CHECK-NOT: llvm.load
872+
%0 = triton_gpu.convert_layout %arg0 : tensor<64x64xf16, #mma0> -> tensor<64x64xf16, #mma1>
873+
tt.return
874+
}
875+
}
876+
877+
// -----
878+
879+
#mma0 = #triton_gpu.nvidia_mma<{versionMajor = 3, versionMinor = 0, warpsPerCTA = [4, 1], instrShape = [16, 64, 16]}>
880+
#mma1 = #triton_gpu.nvidia_mma<{versionMajor = 3, versionMinor = 0, warpsPerCTA = [4, 1], instrShape = [16, 128, 16]}>
881+
882+
module attributes {"triton_gpu.num-ctas" = 1 : i32, "triton_gpu.num-warps" = 4 : i32} {
883+
// CHECK-LABEL: convert_layout_mmav3_mmav3_1
884+
tt.func @convert_layout_mmav3_mmav3_1(%arg0: tensor<64x64xf16, #mma1>) {
885+
// CHECK-NOT: st.shared
886+
// CHECK-NOT: llvm.load
887+
%0 = triton_gpu.convert_layout %arg0 : tensor<64x64xf16, #mma1> -> tensor<64x64xf16, #mma0>
888+
tt.return
889+
}
890+
}
891+
892+
// -----
893+
894+
#mma0 = #triton_gpu.nvidia_mma<{versionMajor = 3, versionMinor = 0, warpsPerCTA = [4, 1], instrShape = [16, 64, 16]}>
895+
#mma1 = #triton_gpu.nvidia_mma<{versionMajor = 3, versionMinor = 0, warpsPerCTA = [4, 1], instrShape = [16, 128, 16]}>
896+
897+
module attributes {"triton_gpu.num-ctas" = 1 : i32, "triton_gpu.num-warps" = 4 : i32} {
898+
// CHECK-LABEL: convert_layout_mmav3_mmav3_2
899+
tt.func @convert_layout_mmav3_mmav3_2(%arg0: tensor<16x16xf16, #mma1>) {
900+
// CHECK-NOT: st.shared
901+
// CHECK-NOT: llvm.load
902+
%0 = triton_gpu.convert_layout %arg0 : tensor<16x16xf16, #mma1> -> tensor<16x16xf16, #mma0>
903+
tt.return
904+
}
905+
}
906+
907+
// -----
908+
909+
#mma0 = #triton_gpu.nvidia_mma<{versionMajor = 3, versionMinor = 0, warpsPerCTA = [4, 1], instrShape = [16, 64, 16]}>
910+
#mma1 = #triton_gpu.nvidia_mma<{versionMajor = 3, versionMinor = 0, warpsPerCTA = [4, 1], instrShape = [16, 128, 16]}>
911+
912+
module attributes {"triton_gpu.num-ctas" = 1 : i32, "triton_gpu.num-warps" = 4 : i32} {
913+
// CHECK-LABEL: convert_layout_mmav3_mmav3_3
914+
tt.func @convert_layout_mmav3_mmav3_3(%arg0: tensor<1x64xf16, #mma1>) {
915+
// CHECK-NOT: st.shared
916+
// CHECK-NOT: llvm.load
917+
%0 = triton_gpu.convert_layout %arg0 : tensor<1x64xf16, #mma1> -> tensor<1x64xf16, #mma0>
918+
tt.return
919+
}
920+
}
921+
922+
// -----
923+
850924
#blocked = #triton_gpu.blocked<{sizePerThread = [16, 1], threadsPerWarp = [8, 4], warpsPerCTA = [1, 8], order = [0, 1]}>
851925
#mma = #triton_gpu.nvidia_mma<{versionMajor = 3, versionMinor = 0, warpsPerCTA = [8, 1], instrShape = [16, 256, 32]}>
852926
module attributes {"triton_gpu.num-ctas" = 1 : i32, "triton_gpu.num-warps" = 8 : i32} {

unittest/Tools/LinearLayoutTest.cpp

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -747,6 +747,39 @@ TEST_F(LinearLayoutTest, QuotientIdentityMultipleDimensions) {
747747
ASSERT_TRUE(quotientLayout->quotient({S("dim2")}).has_value());
748748
}
749749

750+
TEST_F(LinearLayoutTest, Resize) {
751+
auto init = LinearLayout(
752+
{
753+
{S("in0"), {{0, 1}, {0, 2}}},
754+
{S("in1"), {{1, 0}, {2, 0}}},
755+
{S("in2"), {}},
756+
},
757+
{S("dim0"), S("dim1")});
758+
EXPECT_EQ(init.resize(S("in0"), 8),
759+
LinearLayout(
760+
{
761+
{S("in0"), {{0, 1}, {0, 2}, {0, 0}}},
762+
{S("in1"), {{1, 0}, {2, 0}}},
763+
{S("in2"), {}},
764+
},
765+
{S("dim0"), S("dim1")}));
766+
EXPECT_EQ(init.resize(S("in0"), 4), LinearLayout(
767+
{
768+
{S("in0"), {{0, 1}, {0, 2}}},
769+
{S("in1"), {{1, 0}, {2, 0}}},
770+
{S("in2"), {}},
771+
},
772+
{S("dim0"), S("dim1")}));
773+
EXPECT_EQ(init.resize(S("in1"), 8),
774+
LinearLayout(
775+
{
776+
{S("in0"), {{0, 1}, {0, 2}}},
777+
{S("in1"), {{1, 0}, {2, 0}, {0, 0}}},
778+
{S("in2"), {}},
779+
},
780+
{S("dim0"), S("dim1")}));
781+
}
782+
750783
} // anonymous namespace
751784
} // namespace mlir::triton
752785

0 commit comments

Comments
 (0)