22#include "llvm/ADT/STLExtras.h"
27#include "mlir/Dialect/NVGPU/IR/NVGPUDialect.cpp.inc"
29void NVGPUDialect::initialize() {
30 declarePromisedInterfaces<memref::IndexedAccessOpInterface, LdMatrixOp>();
31 declarePromisedInterfaces<memref::IndexedMemCopyOpInterface,
35bool NVGPUDialect::isSharedMemoryAddressSpace(
Attribute memorySpace) {
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;
46bool NVGPUDialect::hasSharedMemoryAddressSpace(MemRefType type) {
47 Attribute memorySpace = type.getMemorySpace();
48 return isSharedMemoryAddressSpace(memorySpace);
55LogicalResult DeviceAsyncCopyOp::verify() {
56 auto srcMemref = llvm::cast<MemRefType>(getSrc().
getType());
57 auto dstMemref = llvm::cast<MemRefType>(getDst().
getType());
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))
65 <<
"destination memref must have a memory space attribute of "
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) <<
".";
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 "
100 <<
". Unset bypassL1, or set "
101 "destination element to "
114 build(odsBuilder, odsState, matrixC.
getType(), matrixA, matrixB, matrixC,
115 mmaShape, UnitAttr());
122 build(odsBuilder, odsState, matrixC.
getType(), matrixA, matrixB, matrixC,
124 tf32Enabled ? odsBuilder.
getUnitAttr() : UnitAttr());
132 const std::array<int64_t, 3> &mmaShape,
133 bool tf32Enabled,
bool sparse =
false) {
151 auto aVector = matrixA.getType();
152 auto bVector = matrixB.getType();
153 auto cVector = matrixC.getType();
161 Type aType = aVector.getElementType();
164 if (sparse && aType.
isF64())
165 return op->
emitError() <<
"f64 is not supported for sparse mode";
177 shapeK = 128 / operandBitwidth;
179 numElementA = 32 / operandBitwidth;
180 numElementB = 32 / operandBitwidth;
183 <<
"expected input data type (i4,i8,f16,bf16,tf32,f64,"
184 "f8E4M3FN,f8E5M2) supported by "
192 if (aShape.size() != 2) {
193 return op->
emitError() <<
"matrixA must be 2 dimensional vector";
196 if (bShape.size() != 2) {
197 return op->
emitError() <<
"matrixB must be 2 dimensional vector";
200 if (cShape.size() != 2) {
201 return op->
emitError() <<
"matrixC must be 2 dimensional vector";
204 auto [m, n, k] = mmaShape;
207 int64_t sparseFactor = sparse ? 2 : 1;
208 if (aShape[0] * aShape[1] *
kWarpSize != m * k / sparseFactor)
210 <<
"expected " << m * k <<
" warp-wide matrix A elements";
213 if (bShape[0] * bShape[1] *
kWarpSize != k * n)
215 <<
"expected " << k * n <<
" warp-wide matrix B elements";
218 if (cShape[0] * cShape[1] *
kWarpSize != m * n)
220 <<
"expected " << m * n <<
" warp-wide matrix C elements";
223 if (tf32Enabled && !(aType.
isF32()))
225 <<
"expected tf32 tensor cores only for F32 operands";
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 <<
")";
243 if ((bShape[0] != kTile * nTile) || (bShape[1] != numElementB))
244 return op->
emitOpError() <<
"expected matrix B to be shaped ("
245 << kTile * nTile <<
" x " << numElementB <<
")";
248 if ((cShape[0] != mTile * nTile) || (cShape[1] != numElementC))
249 return op->
emitOpError() <<
"expected matrix C to be shaped ("
250 << mTile * nTile <<
" x " << numElementC <<
")";
255LogicalResult MmaSyncOp::verify() {
256 if (getMmaShape().size() != 3)
257 return emitOpError() <<
"mmaShape must have exactly 3 elements";
259 return verifyMmaSyncOp(this->getOperation(), getMatrixA(), getMatrixB(),
260 getMatrixC(), getMmaShapeAsArray(),
261 getTf32Enabled().value_or(
false));
271 build(odsBuilder, odsState, matrixC.
getType(), matrixA, matrixB, matrixC,
275LogicalResult MmaSparseSyncOp::verify() {
276 unsigned sparsitySelector = getSparsitySelector();
277 if (sparsitySelector > 1)
278 return emitOpError() <<
"sparsity selector should be 0 or 1";
280 if (getMmaShape().size() != 3)
281 return emitOpError() <<
"mmaShape must have exactly 3 elements";
283 return verifyMmaSyncOp(this->getOperation(), getMatrixA(), getMatrixB(),
284 getMatrixC(), getMmaShapeAsArray(),
285 getTf32Enabled().value_or(
false),
true);
291LogicalResult LdMatrixOp::verify() {
293 auto srcMemref = llvm::cast<MemRefType>(getSrcMemref().
getType());
296 auto resVector = llvm::cast<VectorType>(getRes().
getType());
300 Type resType = resVector.getElementType();
304 int64_t numElementsPer32b = 32 / elementBitWidth;
307 int64_t numTiles = getNumTiles();
310 bool isTranspose = getTranspose();
316 if (!NVGPUDialect::hasSharedMemoryAddressSpace(srcMemref))
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))
326 <<
"nvgpu.ldmatrix transpose works only at 16b granularity";
327 if (resShape.size() != 2) {
328 return emitError() <<
"results must be 2 dimensional vector";
330 if (!(resShape[1] == numElementsPer32b))
331 return emitError() <<
"expected vector register shape[1] = "
332 << numElementsPer32b;
333 if (!(resShape[0] == numTiles))
335 <<
"expected vector register shape[0] and numTiles to match";
346 case TensorMapSwizzleKind::SWIZZLE_32B:
348 case TensorMapSwizzleKind::SWIZZLE_64B:
350 case TensorMapSwizzleKind::SWIZZLE_128B:
358 Operation *op, TensorMapDescriptorType descType,
359 std::optional<MemRefType> memrefType = std::nullopt) {
360 MemRefType descMemref = descType.getTensor();
362 if (descType.getInterleave() != TensorMapInterleaveKind::INTERLEAVE_NONE)
363 return op->
emitError() <<
"Interleave options are not supported yet.";
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.";
371 if (!descMemref.hasStaticShape())
372 return op->
emitError() <<
"the tensor map descriptor must be static shaped";
374 for (
auto dim : descMemref.getShape()) {
376 return op->
emitError() <<
"the tensor map descriptor must have "
377 "dimensions between 1 and "
381 if (descMemref.getRank() > 1 &&
382 descType.getSwizzle() != TensorMapSwizzleKind::SWIZZLE_NONE) {
383 unsigned lastDimensionByte =
384 descMemref.getElementTypeBitWidth() * descMemref.getShape().back() / 8;
386 if (lastDimensionByte != expectByte)
387 return op->
emitError() <<
"the tensormap descriptor must have last "
389 << expectByte <<
" bytes but it is "
390 << lastDimensionByte <<
" bytes";
394 if (!memrefType.has_value())
397 MemRefType dstMemref = memrefType.value();
400 if (descMemref.getElementType() != dstMemref.getElementType()) {
401 return op->
emitError() <<
"the element type of tensor map descriptor and "
402 "memref must be same";
405 if (!NVGPUDialect::hasSharedMemoryAddressSpace(dstMemref)) {
406 return op->
emitError() <<
"the destination memref has incorrect address "
407 "space, it must be shared memory address space.";
409 if (!dstMemref.hasStaticShape())
410 return op->
emitError() <<
"the destination memref must be static shaped";
412 if (dstMemref.getRank() != descMemref.getRank()) {
413 return op->
emitError() <<
"the shape of tensor map descriptor and "
414 "memref must have same rank";
416 if (!descMemref.getShape().equals(dstMemref.getShape())) {
417 return op->
emitError() <<
"memref and tensor map shapes mismatch "
418 << descMemref <<
" != " << dstMemref;
422 descMemref.getShape().back() * descMemref.getElementTypeBitWidth() / 8;
424 return op->
emitError() <<
"the bytes in the last dimension of the tensor "
425 "map must be a multiple of 16";
430LogicalResult TmaAsyncLoadOp::verify() {
433 if (error.has_value())
434 return error.value();
438 <<
" coordinates are supported.";
441 size_t(getTensorMapDescriptor().
getType().getTensor().getRank())) {
442 return emitError() <<
"number of coordinates do not match with the rank of "
443 "tensor descriptor map.";
453LogicalResult TmaAsyncStoreOp::verify() {
456 if (error.has_value())
457 return error.value();
461 <<
" coordinates are supported.";
464 size_t(getTensorMapDescriptor().
getType().getTensor().getRank())) {
465 return emitError() <<
"number of coordinates do not match with the rank of "
466 "tensor descriptor map.";
472LogicalResult TmaCreateDescriptorOp::verify() {
475 <<
" coordinates are supported.";
478 std::optional<InFlightDiagnostic> error =
480 if (error.has_value())
481 return error.value();
490LogicalResult WarpgroupGenerateDescriptorOp::verify() {
491 std::optional<InFlightDiagnostic> error =
493 if (error.has_value())
494 return error.value();
496 if (getTensorMap().
getType().getSwizzle() !=
497 TensorMapSwizzleKind::SWIZZLE_128B) {
499 << stringifyTensorMapSwizzleKind(
500 TensorMapSwizzleKind::SWIZZLE_128B)
501 <<
" is supported for the time being";
504 if (getTensorMap().
getType().getInterleave() !=
505 TensorMapInterleaveKind::INTERLEAVE_NONE) {
507 << stringifyTensorMapInterleaveKind(
508 TensorMapInterleaveKind::INTERLEAVE_NONE)
509 <<
" is supported for the time being";
539 if (isa<Float8E5M2Type, Float8E4M3FNType>(typeA) &&
540 isa<Float8E5M2Type, Float8E4M3FNType>(typeB) &&
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};
559 80, 96, 112, 128, 144, 160,
560 176, 192, 208, 224, 240, 256};
562 isa<Float8E5M2Type, Float8E4M3FNType>(typeA))
563 if (llvm::is_contained(allowedN, sizeN))
567 if (llvm::is_contained(allowedNshort, sizeN))
572LogicalResult WarpgroupMmaOp::verify() {
573 if (getTransposeA() && !getTransposeB())
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();
582 if (matrixC != matrixD)
583 return emitOpError() <<
"type of matrix C and matrix D must be the same";
585 if (matrixA.getRank() != 2 || matrixB.getRank() != 2 ||
586 matrixC.getRank() != 2 || matrixD.getRank() != 2) {
588 <<
"has matrices A, B, C and D, they must be 2 dimensional";
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]
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]
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]
605 matrixA.getElementType(),
606 matrixB.getElementType())))
607 return emitOpError() << matrixC.getElementType()
608 <<
" += " << matrixA.getElementType() <<
" * "
609 << matrixB.getElementType()
610 <<
", it is not supported.";
613 return emitOpError() <<
"has input type " << matrixB <<
" n is set to "
614 << matrixB.getDimSize(1) <<
", it is not 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";
629LogicalResult WarpgroupMmaStoreOp::verify() {
630 MemRefType dstMemrefType = getDstMemref().getType();
631 VectorType vtype = getMatrixD().getType().getFragmented();
634 if (!vtype.getElementType().isF32()) {
636 <<
"hit a limitation: only f32 results for the time being";
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";
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();
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)";
673LogicalResult RcpOp::verify() {
675 bool approx = getApprox();
676 mlir::NVVM::FPRoundingModeAttr rnd = getRoundingAttr();
678 if (!approx || !ftz) {
680 <<
"has a limitation. non-approx or non-ftz is not supported yet.";
682 if (rnd.getValue() != mlir::NVVM::FPRoundingMode::NONE) {
683 return emitOpError() <<
"has a limitation. " << rnd
684 <<
" is not supported yet.";
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 "
700 << inType <<
" and " << outType;
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;
711LogicalResult TruncfOp::verify() {
712 Type inType = getIn().getType();
724 if (srcBitWidth <= dstBitWidth)
725 return emitOpError(
"result type ")
726 << dstType <<
" must be narrower than operand type " << srcType;
728 if (!(srcBitWidth == 64 || srcBitWidth == 32 || srcBitWidth == 16))
729 return emitOpError(
"input type must be 64/32/16 bitwidth, but got ")
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 "
738 }
else if (rnd == mlir::NVVM::FPRoundingMode::RS) {
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 ")
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, "
757 }
else if (rnd != mlir::NVVM::FPRoundingMode::RN) {
758 return emitOpError(
"expects RN rounding mode, but got ") << getRndAttr();
761 if (getRandomBits() && rnd != mlir::NVVM::FPRoundingMode::RS)
762 return emitOpError(
"random_bits can only be used with RS rounding mode");
771LogicalResult ExtfOp::verify() {
772 Type inType = getIn().getType();
783 if (srcBitWidth >= dstBitWidth)
784 return emitOpError(
"result type ")
785 << dstType <<
" must be wider than operand type " << srcType;
787 if (dstBitWidth != 16 && dstBitWidth != 32 && dstBitWidth != 64)
788 return emitOpError(
"result type must be 16, 32, or 64 bitwidth, but got ")
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 "
796 if (rnd != mlir::NVVM::FPRoundingMode::RN)
797 return emitOpError(
"expects RN rounding mode, but got ") << getRndAttr();
799 if (getRelu() && llvm::isa<BFloat16Type>(dstType))
800 return emitOpError(
"relu is not supported for bf16 destination");
809#define GET_ATTRDEF_CLASSES
810#include "mlir/Dialect/NVGPU/IR/NVGPUAttrDefs.cpp.inc"
812#include "mlir/Dialect/NVGPU/IR/NVGPUEnums.cpp.inc"
814#define GET_OP_CLASSES
815#include "mlir/Dialect/NVGPU/IR/NVGPUOps.cpp.inc"
817#define GET_TYPEDEF_CLASSES
818#include "mlir/Dialect/NVGPU/IR/NVGPUTypeDefs.cpp.inc"
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 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.
ArrayAttr getI64ArrayAttr(ArrayRef< int64_t > values)
This class represents a diagnostic that is inflight and set to be reported.
This class helps build Operations.
Operation is the basic unit of execution within MLIR.
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.
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...
bool isInteger() const
Return true if this is an integer type (with the specified width).
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
This class represents an instance of an SSA value in the MLIR system, representing a computable value...
Type getType() const
Return the type of this value.
SmallVector< int64_t, 4 > getCoordinates(ArrayRef< int64_t > basis, unsigned linearIndex)
Include the generated interface declarations.
Type getType(OpFoldResult ofr)
Returns the int type of the integer in ofr.
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.
This represents an operation in an abstracted form, suitable for use with the builder APIs.