MLIR 24.0.0git
MMAUtils.cpp
Go to the documentation of this file.
1//===- MMAUtils.cpp - MLIR NVGPU dialect utils for MMA operations----------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
9
12
13using namespace mlir;
14using namespace mlir::nvgpu;
15
16/// There are always 4 threads per [128|256|512] bit row.
17static constexpr int64_t kThreadsPerRow = 4;
18static constexpr int64_t kNumRowsPerTile = 8;
19
20static bool isAccumulatorOrResult(MatMulOperandRole operandType) {
21 return operandType == MatMulOperandRole::C;
22}
23
24/// Returns the number of registers which compose a matrix fragment held by a
25/// single thread.
27 int64_t lineSize = inferTileWidthInBits(type);
28 auto shape = type.vectorType.getShape();
29 return (shape[0] / kNumRowsPerTile) *
30 (shape[1] * type.vectorType.getElementType().getIntOrFloatBitWidth()) /
31 lineSize;
32}
33
34/// Returns the number of 8 x [128|256|512] bit tiles that compose the given
35/// operand shape.
36static std::array<int64_t, 2> getTileShape(ArrayRef<int64_t> operandShape,
37 Type elementType,
38 int64_t lineSizeBits) {
39 // For each 8x128bit square, a thread is responsible for one 32bit register.
40 return {operandShape[0] / kNumRowsPerTile,
41 (operandShape[1] * elementType.getIntOrFloatBitWidth()) /
42 lineSizeBits};
43}
44
45/// Returns the first user of the `op` that is vector.contract. If no
46/// vector.contract user exists, return failure.
47FailureOr<vector::ContractionOp> nvgpu::getUserContract(Operation *op) {
48 for (Operation *user : op->getUsers()) {
49 if (auto contractOp = dyn_cast<vector::ContractionOp>(user))
50 return contractOp;
51 }
52 return failure();
53}
54
55FailureOr<WarpMatrixInfo> nvgpu::getWarpMatrixInfo(Operation *op) {
56 WarpMatrixInfo info;
57
58 // Determine the vector type at warp-level.
59 if (vector::TransferWriteOp writeOp = dyn_cast<vector::TransferWriteOp>(op)) {
60 info.vectorType = writeOp.getVectorType();
61 } else if (isa<vector::TransferReadOp, vector::ContractionOp,
62 vector::ExtractStridedSliceOp, arith::ConstantOp>(op)) {
63 info.vectorType = cast<VectorType>(op->getResult(0).getType());
64 } else {
65 return op->emitError()
66 << "unhandled operation type in nvgpu.mma.sync conversion path";
67 }
68
69 // Determine the operand role. We assume it is an accumulator/result unless it
70 // is directly consumed by a `vector.contract` op.
72 FailureOr<vector::ContractionOp> contractOp = getUserContract(op);
73 if (failed(contractOp))
74 return info;
75
76 if ((*contractOp).getLhs() == op->getResult(0))
78 else if ((*contractOp).getRhs() == op->getResult(0))
80
81 return info;
82}
83
84int64_t nvgpu::inferTileWidthInBits(const WarpMatrixInfo &type) {
85 bool isAcc = isAccumulatorOrResult(type.operandRole);
86 Type elType = type.vectorType.getElementType();
87 if (isAcc && elType.getIntOrFloatBitWidth() == 32) {
88 return 256;
89 }
90 if (elType.getIntOrFloatBitWidth() == 64) {
91 return isAcc ? 512 : 256;
92 }
93 return 128;
94}
95
96FailureOr<FragmentElementInfo>
97nvgpu::getMmaSyncRegisterType(const WarpMatrixInfo &type) {
98 MLIRContext *ctx = type.vectorType.getContext();
99 const bool isAccum = isAccumulatorOrResult(type.operandRole);
100
101 Type elType = type.vectorType.getElementType();
102 if (elType.isF16()) {
103 return FragmentElementInfo{VectorType::get(2, Float16Type::get(ctx)), 2, 32,
105 }
106
107 // f64 operand
108 Type f64Ty = Float64Type::get(ctx);
109 if (elType.isF64()) {
110 return isAccum
111 ? FragmentElementInfo{VectorType::get(2, f64Ty), 2, 128,
113 : FragmentElementInfo{f64Ty, 1, 64,
115 }
116
117 // int8 operand
118 if (elType.isInteger(8)) {
119 return FragmentElementInfo{VectorType::get(4, IntegerType::get(ctx, 8)), 4,
121 }
122
123 // int4 operand
124 if (elType.isInteger(4)) {
125 return FragmentElementInfo{VectorType::get(8, IntegerType::get(ctx, 4)), 8,
127 }
128
129 // Integer 32bit acc operands
130 if (elType.isInteger(32)) {
131 return FragmentElementInfo{VectorType::get(2, IntegerType::get(ctx, 32)), 2,
133 }
134
135 // Floating point 32bit operands
136 if (elType.isF32()) {
137 Type f32Ty = Float32Type::get(ctx);
138 return isAccum
139 ? FragmentElementInfo{VectorType::get(2, f32Ty), 2, 64,
141 : FragmentElementInfo{f32Ty, 1, 32,
143 }
144 return failure();
145}
146
148 Type elementType,
149 ArrayRef<int64_t> operandShape,
150 bool isAccumulator,
151 int64_t elementsPerRegister,
152 AffineExpr logicalValueId) {
153 const int64_t elementsPerLine =
154 lineSize / elementType.getIntOrFloatBitWidth();
155 const std::array<int64_t, 2> num8x128bTiles =
156 getTileShape(operandShape, elementType, lineSize);
157 AffineExpr registerIdx = logicalValueId.floorDiv(elementsPerRegister);
158 return AffineMap::get(
159 2, 0,
160 {(registerIdx % num8x128bTiles[0]) * 8,
161 (registerIdx.floorDiv(num8x128bTiles[0])) * elementsPerLine},
162 elementType.getContext());
163}
164
165FailureOr<AffineMap>
166nvgpu::getLaneIdAndValueIdToOperandCoord(OpBuilder &builder, Location loc,
167 const WarpMatrixInfo &fragmentType) {
168 Type elementType = fragmentType.vectorType.getElementType();
169 ArrayRef<int64_t> operandShape = fragmentType.vectorType.getShape();
170 FailureOr<FragmentElementInfo> regInfo = getMmaSyncRegisterType(fragmentType);
171 if (failed(regInfo))
172 return failure();
173
174 const int64_t elementBitWidth = elementType.getIntOrFloatBitWidth();
175 const int64_t elementsPerRegister =
176 regInfo->registerWidthBits / elementBitWidth;
177 const int64_t lineSize = inferTileWidthInBits(fragmentType);
178
179 AffineExpr laneId, logicalValueIdDim;
180 bindDims(builder.getContext(), laneId, logicalValueIdDim);
181
182 // Determine what register logicalValueId corresponds to. Use that as a
183 // linear index into the coordinate mapping `index -> (tile row, tile col)`.
184 AffineMap registerIndexToTileCoord = getRegisterIndexToTileOffsetMap(
185 lineSize, elementType, operandShape,
186 isAccumulatorOrResult(fragmentType.operandRole), elementsPerRegister,
187 logicalValueIdDim);
188
189 auto makeMap = [&](ArrayRef<AffineExpr> dimExprs) -> AffineMap {
190 return AffineMap::get(2, 0, dimExprs, builder.getContext());
191 };
192
193 auto tileRow = registerIndexToTileCoord.getResult(0);
194 auto tileCol = registerIndexToTileCoord.getResult(1);
195 return makeMap({tileRow + laneId.floorDiv(kThreadsPerRow),
196 tileCol + (laneId % kThreadsPerRow) * elementsPerRegister +
197 (logicalValueIdDim % elementsPerRegister)});
198}
199
200FailureOr<LdMatrixParams> nvgpu::getLdMatrixParams(const WarpMatrixInfo &type,
201 bool transpose) {
202 LdMatrixParams params;
203 Type elType = type.vectorType.getElementType();
204 params.fragmentType = type.vectorType;
205 if (type.operandRole == MatMulOperandRole::A ||
207 params.targetLayout = NVVM::MMALayout::row;
208 } else {
209 params.targetLayout = NVVM::MMALayout::col;
210 }
211 ArrayRef<int64_t> shape = type.vectorType.getShape();
212 params.contiguousDimType = transpose ? vector::IteratorType::parallel
213 : vector::IteratorType::reduction;
214
215 if (params.contiguousDimType == vector::IteratorType::reduction) {
216 params.numTiles = (shape[0] / kNumRowsPerTile) *
217 ((shape[1] * elType.getIntOrFloatBitWidth()) / 128);
218 } else {
219 params.numTiles = (shape[1] / kNumRowsPerTile) *
220 ((shape[0] * elType.getIntOrFloatBitWidth()) / 128);
221 }
222
223 if (params.numTiles == 0)
224 return failure();
225
226 return params;
227}
228
229FailureOr<AffineMap>
230nvgpu::getLaneIdToLdMatrixMatrixCoord(OpBuilder &builder, Location loc,
231 const LdMatrixParams &params) {
232 // One thread per 128b row.
233 const int bitsPerElement = static_cast<int>(
234 params.fragmentType.getElementType().getIntOrFloatBitWidth());
235 const int kElementsPer128b = (128 / bitsPerElement);
236 ArrayRef<int64_t> operandShape = params.fragmentType.getShape();
237 AffineExpr d0 = getAffineDimExpr(0, builder.getContext());
238
239 auto makeMap = [&](ArrayRef<AffineExpr> dimExprs) -> AffineMap {
240 return AffineMap::get(1, 0, dimExprs, builder.getContext());
241 };
242
243 // Index `idx` in vectorType `operandShape` maps to the strided dimension of
244 // the `srcMemref` memory of the LdMatrixOp.
245 int idx =
246 (params.contiguousDimType == vector::IteratorType::reduction) ? 0 : 1;
247
248 // Affine expr in strided and contiguous dimension encodes the coordinate
249 // mapping for the element a thread points to for warp-wide LdMatrixOp.
250 AffineExpr strided = d0 % (operandShape[idx]);
251 AffineExpr contiguous = d0.floorDiv(operandShape[idx]) * (kElementsPer128b);
252
253 // This case corresponds to row-major matrixA or col-major matrixB or
254 // row-major matrixC. This is when the memory layout in `srcMemref`
255 // match mma.sync hardware vector register operand layout.
256 if (params.contiguousDimType == vector::IteratorType::reduction)
257 return makeMap({strided, contiguous});
258
259 // This case corresponds to col-major matrixA or row-major matrixB or
260 // col-major matrixC. This is when the memory layout in `srcMemref` does not
261 // match mma.sync hardware vector register operand layout.
262 if (params.contiguousDimType == vector::IteratorType::parallel)
263 return makeMap({contiguous, strided});
264
265 return failure();
266}
267
268bool nvgpu::canLowerToWarpMatrixOperation(vector::TransferReadOp op) {
269 if (op.getMask() || op.hasOutOfBoundsDim())
270 return false;
271 VectorType type = op.getType();
272 // The result type should be 2D. Note that it is possible to expand support so
273 // that we are robust to extra unit dimensions that failed to fold, but that
274 // would significantly increase downstream code complexity in the conversion
275 // step. For now, we rely on other patterns to ensure canonical 2D form is
276 // used when targeting the `nvgpu.mma.sync` lowering path.
277 if (!type.hasStaticShape() || type.getRank() != 2)
278 return false;
279
280 // Currently we can't support reads on tensor types because we need stride
281 // information to ensure correctness of downstream assumptions. It is possible
282 // to enable this if caller can assert that tensor will be lowered in a
283 // particular manner.
284 auto sourceType = dyn_cast<MemRefType>(op.getBase().getType());
285 if (!sourceType)
286 return false;
287
288 // Check that the last dimension of the read is contiguous. Note that it is
289 // possible to expand support for this by scalarizing all the loads during
290 // conversion.
291 auto [strides, offset] = sourceType.getStridesAndOffset();
292 return strides.back() == 1;
293}
294
295bool nvgpu::canLowerToWarpMatrixOperation(vector::TransferWriteOp op) {
296 if (op.getMask() || op.hasOutOfBoundsDim() || op.getTransferRank() == 0)
297 return false;
298 VectorType type = op.getVectorType();
299 if (!type.hasStaticShape() || type.getRank() != 2)
300 return false;
301 // TODO: Currently we rely on lowering to a `vector.store` operation. We could
302 // support the transposed write case by lowering to scalarized `memref.store`
303 // operations.
304 if (!op.getPermutationMap().isMinorIdentity())
305 return false;
306 // Currently we can't support reads on tensor types because we need stride
307 // information to ensure correctness of downstream assumptions.
308 auto sourceType = dyn_cast<MemRefType>(op.getBase().getType());
309 if (!sourceType)
310 return false;
311
312 // Check that the last dimension of the target memref is contiguous. Note that
313 // it is possible to expand support for this by scalarizing all the stores
314 // during conversion.
315 auto [strides, offset] = sourceType.getStridesAndOffset();
316 return strides.back() == 1;
317}
static constexpr int64_t kNumRowsPerTile
Definition MMAUtils.cpp:18
static AffineMap getRegisterIndexToTileOffsetMap(int64_t lineSize, Type elementType, ArrayRef< int64_t > operandShape, bool isAccumulator, int64_t elementsPerRegister, AffineExpr logicalValueId)
Definition MMAUtils.cpp:147
static constexpr int64_t kThreadsPerRow
There are always 4 threads per [128|256|512] bit row.
Definition MMAUtils.cpp:17
static bool isAccumulatorOrResult(MatMulOperandRole operandType)
Definition MMAUtils.cpp:20
static int64_t inferNumRegistersPerMatrixFragment(const WarpMatrixInfo &type)
Returns the number of registers which compose a matrix fragment held by a single thread.
Definition MMAUtils.cpp:26
static std::array< int64_t, 2 > getTileShape(ArrayRef< int64_t > operandShape, Type elementType, int64_t lineSizeBits)
Returns the number of 8 x [128|256|512] bit tiles that compose the given operand shape.
Definition MMAUtils.cpp:36
Base type for affine expression.
Definition AffineExpr.h:68
AffineExpr floorDiv(uint64_t v) const
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
static AffineMap get(MLIRContext *context)
Returns a zero result affine map with no dimensions or symbols: () -> ().
AffineExpr getResult(unsigned idx) const
MLIRContext * getContext() const
Definition Builders.h:56
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
MLIRContext is the top-level object for a collection of MLIR operations.
Definition MLIRContext.h:71
This class helps build Operations.
Definition Builders.h:210
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
OpResult getResult(unsigned idx)
Get the 'idx'th result of this operation.
Definition Operation.h:434
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
user_range getUsers()
Returns a range of all users.
Definition Operation.h:927
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isF64() const
Definition Types.cpp:41
MLIRContext * getContext() const
Return the MLIRContext in which this type was uniqued.
Definition Types.cpp:35
bool isF32() const
Definition Types.cpp:40
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
bool isF16() const
Definition Types.cpp:38
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
Type getType() const
Return the type of this value.
Definition Value.h:105
FailureOr< vector::ContractionOp > getUserContract(Operation *op)
Returns the first user of the op that is vector.contract.
Definition MMAUtils.cpp:47
FailureOr< WarpMatrixInfo > getWarpMatrixInfo(Operation *op)
If op is a vector.transfer_write, return the WarpMatrixInfo for the vector operand.
Definition MMAUtils.cpp:55
bool canLowerToWarpMatrixOperation(vector::TransferWriteOp op)
Returns the number of bits in a single tile row.
Definition MMAUtils.cpp:295
MatMulOperandRole
Represents the role of an operand in an MMA instruction: result := matmul(A, B) + C
Definition MMAUtils.h:26
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
void bindDims(MLIRContext *ctx, AffineExprTy &...exprs)
Bind a list of AffineExpr references to DimExpr at positions: [0 .
Definition AffineExpr.h:313
AffineExpr getAffineDimExpr(unsigned position, MLIRContext *context)
These free functions allow clients of the API to not use classes in detail.
Collects information about a warp-level matrix operand represented by a VectorType.
Definition MMAUtils.h:34
MatMulOperandRole operandRole
Definition MMAUtils.h:36