MLIR 24.0.0git
NVGPUDialect.cpp
Go to the documentation of this file.
1//===- NVGPUDialect.cpp - MLIR NVGPU ops implementation -------------------===//
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//===----------------------------------------------------------------------===//
8//
9// This file implements the NVGPU dialect and its operations.
10//
11//===----------------------------------------------------------------------===//
12
16#include "mlir/IR/Builders.h"
19#include "mlir/IR/Diagnostics.h"
21#include "mlir/IR/Verifier.h"
22#include "llvm/ADT/STLExtras.h"
23
24using namespace mlir;
25using namespace mlir::nvgpu;
26
27#include "mlir/Dialect/NVGPU/IR/NVGPUDialect.cpp.inc"
28
29void NVGPUDialect::initialize() {
30 declarePromisedInterfaces<memref::IndexedAccessOpInterface, LdMatrixOp>();
31 declarePromisedInterfaces<memref::IndexedMemCopyOpInterface,
32 DeviceAsyncCopyOp>();
33}
34
35bool NVGPUDialect::isSharedMemoryAddressSpace(Attribute memorySpace) {
36 if (!memorySpace)
37 return false;
38 if (auto intAttr = llvm::dyn_cast<IntegerAttr>(memorySpace))
39 return intAttr.getValue().getZExtValue() ==
40 NVGPUDialect::kSharedMemoryAddressSpace;
41 if (auto gpuAttr = llvm::dyn_cast<gpu::AddressSpaceAttr>(memorySpace))
42 return gpuAttr.getValue() == gpu::AddressSpace::Workgroup;
43 return false;
44}
45
46bool NVGPUDialect::hasSharedMemoryAddressSpace(MemRefType type) {
47 Attribute memorySpace = type.getMemorySpace();
48 return isSharedMemoryAddressSpace(memorySpace);
49}
50
51//===----------------------------------------------------------------------===//
52// NVGPU_DeviceAsyncCopyOp
53//===----------------------------------------------------------------------===//
54
55LogicalResult DeviceAsyncCopyOp::verify() {
56 auto srcMemref = llvm::cast<MemRefType>(getSrc().getType());
57 auto dstMemref = llvm::cast<MemRefType>(getDst().getType());
58
59 if (!srcMemref.isLastDimUnitStride())
60 return emitError("source memref most minor dim must have unit stride");
61 if (!dstMemref.isLastDimUnitStride())
62 return emitError("destination memref most minor dim must have unit stride");
63 if (!NVGPUDialect::hasSharedMemoryAddressSpace(dstMemref))
64 return emitError()
65 << "destination memref must have a memory space attribute of "
66 "IntegerAttr("
67 << NVGPUDialect::kSharedMemoryAddressSpace
68 << ") or gpu::AddressSpaceAttr(Workgroup)";
69 if (dstMemref.getElementType() != srcMemref.getElementType())
70 return emitError("source and destination must have the same element type");
71 if (size_t(srcMemref.getRank()) != getSrcIndices().size())
72 return emitOpError() << "expected " << srcMemref.getRank()
73 << " source indices, got " << getSrcIndices().size();
74 if (size_t(dstMemref.getRank()) != getDstIndices().size())
75 return emitOpError() << "expected " << dstMemref.getRank()
76 << " destination indices, got "
77 << getDstIndices().size();
78 int64_t dstElements = getDstElements().getZExtValue();
79 int64_t sizeInBytes = (dstMemref.getElementTypeBitWidth() * dstElements) / 8;
80 if (sizeInBytes != 4 && sizeInBytes != 8 && sizeInBytes != 16) {
81 unsigned dstWidth = dstMemref.getElementTypeBitWidth();
83 diag << "Requested copy elements is " << dstElements << " with width "
84 << dstMemref.getElementTypeBitWidth()
85 << ". But copy elements could be one of ";
86 if ((32 / dstWidth) > 0)
87 diag << (32 / dstWidth) << ", ";
88 if ((64 / dstWidth) > 0)
89 diag << (64 / dstWidth) << ", ";
90 if ((128 / dstWidth) > 0)
91 diag << (128 / dstWidth) << ".";
92 return diag;
93 }
94 if (getBypassL1().has_value()) {
95 int64_t req = 16 * 8 / dstMemref.getElementTypeBitWidth();
96 if (getBypassL1().value() && sizeInBytes != 16) {
97 return emitOpError() << "bypassL1 does not satify alignment for "
98 << dstMemref << " with destination element "
99 << dstElements
100 << ". Unset bypassL1, or set "
101 "destination element to "
102 << req;
103 }
104 }
105 return success();
106}
107
108//===----------------------------------------------------------------------===//
109// NVGPU_MmaSyncOp
110//===----------------------------------------------------------------------===//
111void MmaSyncOp::build(::mlir::OpBuilder &odsBuilder,
112 ::mlir::OperationState &odsState, Value matrixA,
113 Value matrixB, Value matrixC, ArrayAttr mmaShape) {
114 build(odsBuilder, odsState, matrixC.getType(), matrixA, matrixB, matrixC,
115 mmaShape, UnitAttr());
116}
117
118void MmaSyncOp::build(::mlir::OpBuilder &odsBuilder,
119 ::mlir::OperationState &odsState, Value matrixA,
120 Value matrixB, Value matrixC, ArrayRef<int64_t> mmaShape,
121 bool tf32Enabled) {
122 build(odsBuilder, odsState, matrixC.getType(), matrixA, matrixB, matrixC,
123 odsBuilder.getI64ArrayAttr(mmaShape),
124 tf32Enabled ? odsBuilder.getUnitAttr() : UnitAttr());
125}
126
127/// Performs verification for MmaSyncOp and MmaSparseSyncOp.
128static LogicalResult verifyMmaSyncOp(Operation *op,
132 const std::array<int64_t, 3> &mmaShape,
133 bool tf32Enabled, bool sparse = false) {
134 // The verification for mma.sync covering various shapes and data types is
135 // based on the fundamental tensor core shape.
136
137 // "Fundamental" tensor core shapes:
138 // - For F32 (TF32), F16, S8, and S4 data
139 // types the fundamental tensor core operation is of shape 8-by-8-by-128b.
140 // - F64 is an exception and is of shape 8-by-8-by-256b.
141 int64_t shapeM = 8;
142 int64_t shapeN = 8;
143 int64_t shapeK; // set based on data type (128b for all data types except F64)
144
145 // Number of elements A, B, and C per thread per fundamental tensor core tile
146 int64_t numElementA; // set based on data type (32b except F64)
147 int64_t numElementB; // set based on data type (32b except F64)
148 int64_t numElementC{2}; // two accumulator elements per fundamental tile
149
150 // nvgpu.mma.sync vector operands (per thread)
151 auto aVector = matrixA.getType();
152 auto bVector = matrixB.getType();
153 auto cVector = matrixC.getType();
154
155 // vector shapes
156 ArrayRef<int64_t> aShape = aVector.getShape();
157 ArrayRef<int64_t> bShape = bVector.getShape();
158 ArrayRef<int64_t> cShape = cVector.getShape();
159
160 // vector element type
161 Type aType = aVector.getElementType();
162
163 // Certain data types are not allowed in sparse mode.
164 if (sparse && aType.isF64())
165 return op->emitError() << "f64 is not supported for sparse mode";
166
167 if (aType.isF64()) {
168 // exception to 8-by-8-128b fundamental tensor core tile size
169 shapeK = 4;
170 numElementA = 1;
171 numElementB = 1;
172 } else if (aType.isF32() || aType.isBF16() || aType.isF16() ||
173 aType.isInteger(8) || aType.isInteger(4) || aType.isF8E4M3FN() ||
174 aType.isF8E5M2()) {
175 // 8-by-8-128b fundamental tensor core tile size
176 int operandBitwidth = aType.getIntOrFloatBitWidth();
177 shapeK = 128 / operandBitwidth; // 128b wide shapeK
178
179 numElementA = 32 / operandBitwidth; // 32b wide operand A
180 numElementB = 32 / operandBitwidth; // 32b wide operand B
181 } else {
182 return op->emitError()
183 << "expected input data type (i4,i8,f16,bf16,tf32,f64,"
184 "f8E4M3FN,f8E5M2) supported by "
185 << op->getName();
186 }
187
188 //
189 // Basic verification
190 //
191
192 if (aShape.size() != 2) {
193 return op->emitError() << "matrixA must be 2 dimensional vector";
194 }
195
196 if (bShape.size() != 2) {
197 return op->emitError() << "matrixB must be 2 dimensional vector";
198 }
199
200 if (cShape.size() != 2) {
201 return op->emitError() << "matrixC must be 2 dimensional vector";
202 }
203
204 auto [m, n, k] = mmaShape;
205
206 // verify warp-wide size for vector a
207 int64_t sparseFactor = sparse ? 2 : 1;
208 if (aShape[0] * aShape[1] * kWarpSize != m * k / sparseFactor)
209 return op->emitOpError()
210 << "expected " << m * k << " warp-wide matrix A elements";
211
212 // verify warp-wide size for vector b
213 if (bShape[0] * bShape[1] * kWarpSize != k * n)
214 return op->emitOpError()
215 << "expected " << k * n << " warp-wide matrix B elements";
216
217 // verify warp-wide size for vector c
218 if (cShape[0] * cShape[1] * kWarpSize != m * n)
219 return op->emitOpError()
220 << "expected " << m * n << " warp-wide matrix C elements";
221
222 // verify tf32 tensor cores are enabled for only F32 datatype
223 if (tf32Enabled && !(aType.isF32()))
224 return op->emitOpError()
225 << "expected tf32 tensor cores only for F32 operands";
226
227 //
228 // Extended verification
229 //
230
231 // tiles of fundamental tensor core operations
232 int64_t mTile = m / shapeM;
233 int64_t nTile = n / shapeN;
234 int64_t kTile = k / shapeK;
235
236 // verify shape of aVector
237 if ((aShape[0] != mTile * kTile / (sparse ? 2 : 1)) ||
238 (aShape[1] != numElementA))
239 return op->emitOpError() << "expected matrix A to be shaped ("
240 << mTile * kTile << " x " << numElementA << ")";
241
242 // verify shape of bVector
243 if ((bShape[0] != kTile * nTile) || (bShape[1] != numElementB))
244 return op->emitOpError() << "expected matrix B to be shaped ("
245 << kTile * nTile << " x " << numElementB << ")";
246
247 // verify shape of cVector
248 if ((cShape[0] != mTile * nTile) || (cShape[1] != numElementC))
249 return op->emitOpError() << "expected matrix C to be shaped ("
250 << mTile * nTile << " x " << numElementC << ")";
251
252 return success();
253}
254
255LogicalResult MmaSyncOp::verify() {
256 if (getMmaShape().size() != 3)
257 return emitOpError() << "mmaShape must have exactly 3 elements";
258
259 return verifyMmaSyncOp(this->getOperation(), getMatrixA(), getMatrixB(),
260 getMatrixC(), getMmaShapeAsArray(),
261 getTf32Enabled().value_or(false));
262}
263
264//===----------------------------------------------------------------------===//
265// NVGPU_MmaSparseSyncOp
266//===----------------------------------------------------------------------===//
267void MmaSparseSyncOp::build(::mlir::OpBuilder &odsBuilder,
268 ::mlir::OperationState &odsState, Value matrixA,
269 Value matrixB, Value matrixC, Value sparseMetadata,
270 ArrayRef<int64_t> mmaShape) {
271 build(odsBuilder, odsState, matrixC.getType(), matrixA, matrixB, matrixC,
272 sparseMetadata, odsBuilder.getI64ArrayAttr(mmaShape), 0, UnitAttr());
273}
274
275LogicalResult MmaSparseSyncOp::verify() {
276 unsigned sparsitySelector = getSparsitySelector();
277 if (sparsitySelector > 1)
278 return emitOpError() << "sparsity selector should be 0 or 1";
279
280 if (getMmaShape().size() != 3)
281 return emitOpError() << "mmaShape must have exactly 3 elements";
282
283 return verifyMmaSyncOp(this->getOperation(), getMatrixA(), getMatrixB(),
284 getMatrixC(), getMmaShapeAsArray(),
285 getTf32Enabled().value_or(false), true);
286}
287
288//===----------------------------------------------------------------------===//
289// NVGPU_LdMatrixOp
290//===----------------------------------------------------------------------===//
291LogicalResult LdMatrixOp::verify() {
292 // ldmatrix reads data from source in shared memory
293 auto srcMemref = llvm::cast<MemRefType>(getSrcMemref().getType());
294
295 // ldmatrix writes data to result/destination in vector registers
296 auto resVector = llvm::cast<VectorType>(getRes().getType());
297
298 // vector register shape, element type, and bitwidth
299 ArrayRef<int64_t> resShape = resVector.getShape();
300 Type resType = resVector.getElementType();
301 int64_t elementBitWidth = resType.getIntOrFloatBitWidth();
302
303 // ldmatrix loads 32 bits into vector registers per 8-by-8 tile per thread
304 int64_t numElementsPer32b = 32 / elementBitWidth;
305
306 // number of 8-by-8 tiles
307 int64_t numTiles = getNumTiles();
308
309 // transpose elements in vector registers at 16b granularity when true
310 bool isTranspose = getTranspose();
311
312 //
313 // verification
314 //
315
316 if (!NVGPUDialect::hasSharedMemoryAddressSpace(srcMemref))
317 return emitError()
318 << "expected nvgpu.ldmatrix srcMemref must have a memory space "
319 "attribute of IntegerAttr("
320 << NVGPUDialect::kSharedMemoryAddressSpace
321 << ") or gpu::AddressSpaceAttr(Workgroup)";
322 if (elementBitWidth > 32)
323 return emitError() << "nvgpu.ldmatrix works for 32b or lower";
324 if (isTranspose && !(elementBitWidth == 16))
325 return emitError()
326 << "nvgpu.ldmatrix transpose works only at 16b granularity";
327 if (resShape.size() != 2) {
328 return emitError() << "results must be 2 dimensional vector";
329 }
330 if (!(resShape[1] == numElementsPer32b))
331 return emitError() << "expected vector register shape[1] = "
332 << numElementsPer32b;
333 if (!(resShape[0] == numTiles))
334 return emitError()
335 << "expected vector register shape[0] and numTiles to match";
336
337 return success();
338}
339
340//===----------------------------------------------------------------------===//
341// NVGPU_TmaAsyncLoadOp
342//===----------------------------------------------------------------------===//
343
344static unsigned getSwizzleBytes(TensorMapSwizzleKind kind) {
345 switch (kind) {
346 case TensorMapSwizzleKind::SWIZZLE_32B:
347 return 32;
348 case TensorMapSwizzleKind::SWIZZLE_64B:
349 return 64;
350 case TensorMapSwizzleKind::SWIZZLE_128B:
351 return 128;
352 default:
353 return 0;
354 }
355}
356
357std::optional<InFlightDiagnostic> verifyTmaDescriptorWithMemref(
358 Operation *op, TensorMapDescriptorType descType,
359 std::optional<MemRefType> memrefType = std::nullopt) {
360 MemRefType descMemref = descType.getTensor();
361 // Limitation
362 if (descType.getInterleave() != TensorMapInterleaveKind::INTERLEAVE_NONE)
363 return op->emitError() << "Interleave options are not supported yet.";
364
365 // Address space check for shared memory check
366 if (!NVGPUDialect::hasSharedMemoryAddressSpace(descMemref)) {
367 return op->emitError() << "the tensor map descriptor has incorrect address "
368 "space, it must be shared memory address space.";
369 }
370 // Support only static shape for the time being
371 if (!descMemref.hasStaticShape())
372 return op->emitError() << "the tensor map descriptor must be static shaped";
373
374 for (auto dim : descMemref.getShape()) {
375 if (dim <= 0 || dim > kMaxTMADimension) {
376 return op->emitError() << "the tensor map descriptor must have "
377 "dimensions between 1 and "
378 << kMaxTMADimension << " but it is " << dim;
379 }
380 }
381 if (descMemref.getRank() > 1 &&
382 descType.getSwizzle() != TensorMapSwizzleKind::SWIZZLE_NONE) {
383 unsigned lastDimensionByte =
384 descMemref.getElementTypeBitWidth() * descMemref.getShape().back() / 8;
385 unsigned expectByte = getSwizzleBytes(descType.getSwizzle());
386 if (lastDimensionByte != expectByte)
387 return op->emitError() << "the tensormap descriptor must have last "
388 "dimension of "
389 << expectByte << " bytes but it is "
390 << lastDimensionByte << " bytes";
391 }
392
393 // No verification if memref type is not provided
394 if (!memrefType.has_value())
395 return std::nullopt;
396
397 MemRefType dstMemref = memrefType.value();
398
399 // Check element type
400 if (descMemref.getElementType() != dstMemref.getElementType()) {
401 return op->emitError() << "the element type of tensor map descriptor and "
402 "memref must be same";
403 }
404
405 if (!NVGPUDialect::hasSharedMemoryAddressSpace(dstMemref)) {
406 return op->emitError() << "the destination memref has incorrect address "
407 "space, it must be shared memory address space.";
408 }
409 if (!dstMemref.hasStaticShape())
410 return op->emitError() << "the destination memref must be static shaped";
411
412 if (dstMemref.getRank() != descMemref.getRank()) {
413 return op->emitError() << "the shape of tensor map descriptor and "
414 "memref must have same rank";
415 }
416 if (!descMemref.getShape().equals(dstMemref.getShape())) {
417 return op->emitError() << "memref and tensor map shapes mismatch "
418 << descMemref << " != " << dstMemref;
419 }
420
421 int lastDimBytes =
422 descMemref.getShape().back() * descMemref.getElementTypeBitWidth() / 8;
423 if (lastDimBytes % kTMALastdimByte != 0) {
424 return op->emitError() << "the bytes in the last dimension of the tensor "
425 "map must be a multiple of 16";
426 }
427 return std::nullopt;
428}
429
430LogicalResult TmaAsyncLoadOp::verify() {
431 std::optional<InFlightDiagnostic> error = verifyTmaDescriptorWithMemref(
432 *this, getTensorMapDescriptor().getType(), getDst().getType());
433 if (error.has_value())
434 return error.value();
435
436 if (getCoordinates().size() > kMaxTMATensorDimension) {
437 return emitError() << "Maximum " << kMaxTMATensorDimension
438 << " coordinates are supported.";
439 }
440 if (getCoordinates().size() !=
441 size_t(getTensorMapDescriptor().getType().getTensor().getRank())) {
442 return emitError() << "number of coordinates do not match with the rank of "
443 "tensor descriptor map.";
444 }
445
446 return success();
447}
448
449//===----------------------------------------------------------------------===//
450// NVGPU_TmaAsyncStoreOp
451//===----------------------------------------------------------------------===//
452
453LogicalResult TmaAsyncStoreOp::verify() {
454 std::optional<InFlightDiagnostic> error = verifyTmaDescriptorWithMemref(
455 *this, getTensorMapDescriptor().getType(), getSrc().getType());
456 if (error.has_value())
457 return error.value();
458
459 if (getCoordinates().size() > kMaxTMATensorDimension) {
460 return emitError() << "Maximum " << kMaxTMATensorDimension
461 << " coordinates are supported.";
462 }
463 if (getCoordinates().size() !=
464 size_t(getTensorMapDescriptor().getType().getTensor().getRank())) {
465 return emitError() << "number of coordinates do not match with the rank of "
466 "tensor descriptor map.";
467 }
468
469 return success();
470}
471
472LogicalResult TmaCreateDescriptorOp::verify() {
473 if (getBoxDimensions().size() > kMaxTMATensorDimension) {
474 return emitError() << "Maximum " << kMaxTMATensorDimension
475 << " coordinates are supported.";
476 }
477
478 std::optional<InFlightDiagnostic> error =
479 verifyTmaDescriptorWithMemref(*this, getTensorMap().getType());
480 if (error.has_value())
481 return error.value();
482
483 return success();
484}
485
486//===----------------------------------------------------------------------===//
487// NVGPU_WarpgroupGenerateDescriptorOp
488//===----------------------------------------------------------------------===//
489
490LogicalResult WarpgroupGenerateDescriptorOp::verify() {
491 std::optional<InFlightDiagnostic> error =
492 verifyTmaDescriptorWithMemref(*this, getTensorMap().getType());
493 if (error.has_value())
494 return error.value();
495
496 if (getTensorMap().getType().getSwizzle() !=
497 TensorMapSwizzleKind::SWIZZLE_128B) {
498 return emitError() << "supports only "
499 << stringifyTensorMapSwizzleKind(
500 TensorMapSwizzleKind::SWIZZLE_128B)
501 << " is supported for the time being";
502 }
503
504 if (getTensorMap().getType().getInterleave() !=
505 TensorMapInterleaveKind::INTERLEAVE_NONE) {
506 return emitError() << "supports only "
507 << stringifyTensorMapInterleaveKind(
508 TensorMapInterleaveKind::INTERLEAVE_NONE)
509 << " is supported for the time being";
510 }
511
512 return success();
513}
514
515//===----------------------------------------------------------------------===//
516// WarpgroupMmaOp
517//===----------------------------------------------------------------------===//
518
519LogicalResult isAllowedWGMMADataType(Type typeD, Type typeA, Type typeB) {
520 // F32 += F16 + F16
521 // F16 += F16 + F16
522 if (typeA.isF16() && typeB.isF16() && (typeD.isF32() || typeD.isF16()))
523 return success();
524 // F32 += TF32 + TF32
525 if (typeA.isTF32() && typeD.isF32() && typeB.isTF32())
526 return success();
527 // s32 += i8 + i8
528 if (typeA.isInteger(8) && typeB.isInteger(8) && typeD.isInteger(32))
529 return success();
530 // s32 += i1 + i1
531 if (typeA.isInteger(1) && typeB.isInteger(1) && typeD.isInteger(32))
532 return success();
533 // F32 += BF16 + BF16
534 // F16 += BF16 + BF16
535 if (typeA.isBF16() && typeB.isBF16() && (typeD.isF32() || typeD.isF16()))
536 return success();
537 // F16 += f8 + f8
538 // F32 += f8 + f8
539 if (isa<Float8E5M2Type, Float8E4M3FNType>(typeA) &&
540 isa<Float8E5M2Type, Float8E4M3FNType>(typeB) &&
541 (typeD.isF32() || typeD.isF16()))
542 return success();
543
544 return failure();
545}
546
547LogicalResult isAllowedSizeM(int sizeM) {
548 if (sizeM % kWgmmaSizeM)
549 return failure();
550 return success();
551}
552
553LogicalResult isAllowedSizeN(int sizeN, Type typeA) {
554 SmallVector<int> allowedN = {8, 16, 24, 32, 40, 48, 56, 64,
555 72, 80, 88, 96, 104, 112, 120, 128,
556 136, 144, 152, 160, 168, 176, 184, 192,
557 200, 208, 216, 224, 232, 240, 248, 256};
558 SmallVector<int> allowedNshort = {8, 16, 24, 32, 48, 64,
559 80, 96, 112, 128, 144, 160,
560 176, 192, 208, 224, 240, 256};
561 if (typeA.isBF16() || typeA.isF16() || typeA.isF32() || typeA.isTF32() ||
562 isa<Float8E5M2Type, Float8E4M3FNType>(typeA))
563 if (llvm::is_contained(allowedN, sizeN))
564 return success();
565
566 if (typeA.isInteger(8) || typeA.isInteger(1))
567 if (llvm::is_contained(allowedNshort, sizeN))
568 return success();
569 return failure();
570}
571
572LogicalResult WarpgroupMmaOp::verify() {
573 if (getTransposeA() && !getTransposeB())
574 return emitOpError()
575 << "supports non-transpose A (Row Major) "
576 "and transpose B (Column Major) for the time being ";
577 MemRefType matrixA = getDescriptorA().getType().getTensor();
578 MemRefType matrixB = getDescriptorB().getType().getTensor();
579 VectorType matrixC = getMatrixC().getType().getFragmented();
580 VectorType matrixD = getMatrixD().getType().getFragmented();
581
582 if (matrixC != matrixD)
583 return emitOpError() << "type of matrix C and matrix D must be the same";
584
585 if (matrixA.getRank() != 2 || matrixB.getRank() != 2 ||
586 matrixC.getRank() != 2 || matrixD.getRank() != 2) {
587 return emitOpError()
588 << "has matrices A, B, C and D, they must be 2 dimensional";
589 }
590
591 if (matrixA.getShape()[1] != matrixB.getShape()[0])
592 return emitOpError() << "2nd dim matrix-A (" << matrixA.getShape()[1]
593 << ")!= 1st dim matrix-B (" << matrixB.getShape()[0]
594 << " )";
595 if (matrixA.getShape()[0] != matrixC.getShape()[0])
596 return emitOpError() << "1st dim matrix-A ( " << matrixA.getShape()[0]
597 << " )!= 1st dim matrix-C ( " << matrixC.getShape()[0]
598 << " )";
599 if (matrixB.getShape()[1] != matrixC.getShape()[1])
600 return emitOpError() << "2nd dim matrix-B ( " << matrixB.getShape()[1]
601 << " ) != 2nd dim matrix-C ( " << matrixC.getShape()[1]
602 << " )";
603
604 if (failed(isAllowedWGMMADataType(matrixC.getElementType(),
605 matrixA.getElementType(),
606 matrixB.getElementType())))
607 return emitOpError() << matrixC.getElementType()
608 << " += " << matrixA.getElementType() << " * "
609 << matrixB.getElementType()
610 << ", it is not supported.";
611 // Check N
612 if (failed(isAllowedSizeN(matrixB.getDimSize(1), matrixA.getElementType()))) {
613 return emitOpError() << "has input type " << matrixB << " n is set to "
614 << matrixB.getDimSize(1) << ", it is not supported";
615 }
616
617 // Currently, f16/bf16 supported
618 if (!matrixC.getElementType().isF32() && !matrixA.getElementType().isF16() &&
619 !matrixA.getElementType().isBF16()) {
620 return emitOpError() << "hit a limitation: " << matrixC.getElementType()
621 << " += " << matrixA.getElementType() << " * "
622 << matrixB.getElementType()
623 << ", it is not supported yet";
624 }
625
626 return success();
627}
628
629LogicalResult WarpgroupMmaStoreOp::verify() {
630 MemRefType dstMemrefType = getDstMemref().getType();
631 VectorType vtype = getMatrixD().getType().getFragmented();
632
633 // Limitation
634 if (!vtype.getElementType().isF32()) {
635 return emitOpError()
636 << "hit a limitation: only f32 results for the time being";
637 }
638 if (vtype.getDimSize(0) != dstMemrefType.getDimSize(0) ||
639 vtype.getDimSize(1) != dstMemrefType.getDimSize(1)) {
640 return emitOpError() << "results [" << vtype << "][" << vtype.getDimSize(1)
641 << "] values. However, destination memref["
642 << dstMemrefType.getDimSize(0) << "]["
643 << dstMemrefType.getDimSize(1)
644 << "] does not have same size as results";
645 }
646 return success();
647}
648
649//===----------------------------------------------------------------------===//
650// WarpgroupMmaInitAccumulatorOp
651//===----------------------------------------------------------------------===//
652
653LogicalResult WarpgroupMmaInitAccumulatorOp::verify() {
654 WarpgroupAccumulatorType accType = getMatrixC().getType();
655 int64_t sizeM = accType.getFragmented().getDimSize(0);
656 int64_t sizeN = accType.getFragmented().getDimSize(1);
657 Type elemType = accType.getFragmented().getElementType();
658
659 if (failed(isAllowedSizeM(sizeM)) ||
660 failed(isAllowedSizeN(sizeN, elemType))) {
661 return emitOpError() << "has type " << accType.getFragmented()
662 << ". It does not fit into warp-group "
663 "level (wgmma) matrix multiplication instruction "
664 "(or not supported yet)";
665 }
666 return success();
667}
668
669//===----------------------------------------------------------------------===//
670// RcpOp
671//===----------------------------------------------------------------------===//
672
673LogicalResult RcpOp::verify() {
674 bool ftz = getFtz();
675 bool approx = getApprox();
676 mlir::NVVM::FPRoundingModeAttr rnd = getRoundingAttr();
677 // Currently, only `rcp_approx` and `ftz` is supported.
678 if (!approx || !ftz) {
679 return emitOpError()
680 << "has a limitation. non-approx or non-ftz is not supported yet.";
681 }
682 if (rnd.getValue() != mlir::NVVM::FPRoundingMode::NONE) {
683 return emitOpError() << "has a limitation. " << rnd
684 << " is not supported yet.";
685 }
686 return success();
687}
688
689//===----------------------------------------------------------------------===//
690// NVGPU_TruncfOp
691//===----------------------------------------------------------------------===//
692
693static LogicalResult verifyConversionShapes(Operation *op, Type inType,
694 Type outType) {
695 bool srcIsVector = llvm::isa<VectorType>(inType);
696 bool dstIsVector = llvm::isa<VectorType>(outType);
697 if (srcIsVector != dstIsVector)
698 return op->emitOpError("input and output must both be scalars or both be "
699 "vectors, got ")
700 << inType << " and " << outType;
701 if (srcIsVector) {
702 auto srcVector = llvm::cast<VectorType>(inType);
703 auto dstVector = llvm::cast<VectorType>(outType);
704 if (srcVector.getShape() != dstVector.getShape())
705 return op->emitOpError("input and output shapes must match, got ")
706 << inType << " and " << outType;
707 }
708 return success();
709}
710
711LogicalResult TruncfOp::verify() {
712 Type inType = getIn().getType();
713 Type outType = getType();
714 Type srcType = getElementTypeOrSelf(inType);
715 Type dstType = getElementTypeOrSelf(outType);
716 int srcBitWidth = srcType.getIntOrFloatBitWidth();
717 int dstBitWidth = dstType.getIntOrFloatBitWidth();
718 auto rnd = getRnd();
719
720 if (auto result = verifyConversionShapes(getOperation(), inType, outType);
721 failed(result))
722 return result;
723
724 if (srcBitWidth <= dstBitWidth)
725 return emitOpError("result type ")
726 << dstType << " must be narrower than operand type " << srcType;
727
728 if (!(srcBitWidth == 64 || srcBitWidth == 32 || srcBitWidth == 16))
729 return emitOpError("input type must be 64/32/16 bitwidth, but got ")
730 << srcBitWidth;
731
732 if (llvm::isa<Float8E8M0FNUType>(dstType)) {
733 if (rnd != mlir::NVVM::FPRoundingMode::RZ &&
734 rnd != mlir::NVVM::FPRoundingMode::RP)
735 return emitOpError("expects RZ or RP rounding mode when result type is "
736 "e8m0, but got ")
737 << getRndAttr();
738 } else if (rnd == mlir::NVVM::FPRoundingMode::RS) {
739 // TODO: Currently, we only support conversions which fit into a single i32
740 // register. Support f32->f8/f6/f4 conversions with RS rounding.
741 if (!(srcBitWidth == 32 && dstBitWidth == 16))
742 return emitOpError("RS (stochastic) rounding is only supported for "
743 "f32->f16/bf16, got ")
744 << srcType << " -> " << dstType;
745 if (!getRandomBits())
746 return emitOpError("random_bits operand is required with RS rounding");
747 } else if (srcType.isF64() && dstBitWidth >= 16) {
748 if (rnd != mlir::NVVM::FPRoundingMode::RN)
749 return emitOpError("expects RN rounding mode for f64 input, but got ")
750 << getRndAttr();
751 } else if (srcBitWidth == 32 && dstBitWidth == 16) {
752 if (rnd != mlir::NVVM::FPRoundingMode::RN &&
753 rnd != mlir::NVVM::FPRoundingMode::RZ)
754 return emitOpError("expects RN or RZ rounding mode for f32 to f16/bf16, "
755 "but got ")
756 << getRndAttr();
757 } else if (rnd != mlir::NVVM::FPRoundingMode::RN) {
758 return emitOpError("expects RN rounding mode, but got ") << getRndAttr();
759 }
760
761 if (getRandomBits() && rnd != mlir::NVVM::FPRoundingMode::RS)
762 return emitOpError("random_bits can only be used with RS rounding mode");
763
764 return success();
765}
766
767//===----------------------------------------------------------------------===//
768// NVGPU_ExtfOp
769//===----------------------------------------------------------------------===//
770
771LogicalResult ExtfOp::verify() {
772 Type inType = getIn().getType();
773 Type outType = getType();
774 Type srcType = getElementTypeOrSelf(inType);
775 Type dstType = getElementTypeOrSelf(outType);
776 int srcBitWidth = srcType.getIntOrFloatBitWidth();
777 int dstBitWidth = dstType.getIntOrFloatBitWidth();
778 auto rnd = getRnd();
779
780 if (failed(verifyConversionShapes(getOperation(), inType, outType)))
781 return failure();
782
783 if (srcBitWidth >= dstBitWidth)
784 return emitOpError("result type ")
785 << dstType << " must be wider than operand type " << srcType;
786
787 if (dstBitWidth != 16 && dstBitWidth != 32 && dstBitWidth != 64)
788 return emitOpError("result type must be 16, 32, or 64 bitwidth, but got ")
789 << dstBitWidth;
790
791 if (llvm::isa<Float8E8M0FNUType>(srcType) &&
792 !llvm::isa<BFloat16Type>(dstType) && !dstType.isF32())
793 return emitOpError("expects bf16 or f32 output type when input type is "
794 "e8m0.");
795
796 if (rnd != mlir::NVVM::FPRoundingMode::RN)
797 return emitOpError("expects RN rounding mode, but got ") << getRndAttr();
798
799 if (getRelu() && llvm::isa<BFloat16Type>(dstType))
800 return emitOpError("relu is not supported for bf16 destination");
801
802 return success();
803}
804
805//===----------------------------------------------------------------------===//
806// TableGen'd dialect, type, and op definitions
807//===----------------------------------------------------------------------===//
808
809#define GET_ATTRDEF_CLASSES
810#include "mlir/Dialect/NVGPU/IR/NVGPUAttrDefs.cpp.inc"
811
812#include "mlir/Dialect/NVGPU/IR/NVGPUEnums.cpp.inc"
813
814#define GET_OP_CLASSES
815#include "mlir/Dialect/NVGPU/IR/NVGPUOps.cpp.inc"
816
817#define GET_TYPEDEF_CLASSES
818#include "mlir/Dialect/NVGPU/IR/NVGPUTypeDefs.cpp.inc"
return success()
ArrayAttr()
LogicalResult isAllowedSizeM(int sizeM)
static LogicalResult verifyMmaSyncOp(Operation *op, TypedValue< VectorType > matrixA, TypedValue< VectorType > matrixB, TypedValue< VectorType > matrixC, const std::array< int64_t, 3 > &mmaShape, bool tf32Enabled, bool sparse=false)
Performs verification for MmaSyncOp and MmaSparseSyncOp.
std::optional< InFlightDiagnostic > verifyTmaDescriptorWithMemref(Operation *op, TensorMapDescriptorType descType, std::optional< MemRefType > memrefType=std::nullopt)
LogicalResult isAllowedSizeN(int sizeN, Type typeA)
LogicalResult isAllowedWGMMADataType(Type typeD, Type typeA, Type typeB)
static LogicalResult verifyConversionShapes(Operation *op, Type inType, Type outType)
static unsigned getSwizzleBytes(TensorMapSwizzleKind kind)
constexpr unsigned kTMALastdimByte
The bytes in the last dimension of the tensor map must be a multiple of 16.
constexpr int kWgmmaSizeM
M size of wgmma.mma_async instruction.
constexpr int kWarpSize
constexpr unsigned kMaxTMATensorDimension
Maximum TMA tile dimension (tensorRank) must be non-zero and less than or equal to the maximum suppor...
constexpr unsigned kMaxTMADimension
Maximum TMA tile size (boxDim), which specifies number of elements to be traversed along each of the ...
Attributes are known-constant values of operations.
Definition Attributes.h:25
UnitAttr getUnitAttr()
Definition Builders.cpp:106
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
Definition Builders.cpp:290
This class represents a diagnostic that is inflight and set to be reported.
This class helps build Operations.
Definition Builders.h:210
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
OperationName getName()
The name of an operation is the key identifier for it.
Definition Operation.h:115
InFlightDiagnostic emitOpError(const Twine &message={})
Emit an error with the op name prefixed, like "'dim' op " which is convenient for verifiers.
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
bool isTF32() const
Definition Types.cpp:39
bool isF8E5M2() const
Definition Types.cpp:45
bool isF8E4M3FN() const
Definition Types.cpp:44
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
bool isBF16() const
Definition Types.cpp:37
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Definition Value.h:96
Type getType() const
Return the type of this value.
Definition Value.h:105
SmallVector< int64_t, 4 > getCoordinates(ArrayRef< int64_t > basis, unsigned linearIndex)
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
Definition Utils.cpp:311
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
Type getElementTypeOrSelf(Type type)
Return the element type or return the type itself.
std::conditional_t< std::is_same_v< Ty, mlir::Type >, mlir::Value, detail::TypedValue< Ty > > TypedValue
If Ty is mlir::Type this will select Value instead of having a wrapper around it.
Definition Value.h:496
This represents an operation in an abstracted form, suitable for use with the builder APIs.