MLIR 24.0.0git
VectorContract16BitFPToFMA.cpp
Go to the documentation of this file.
1//===- VectorContract16BitFPToFMA.cpp--------------------------------------===//
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
17
19#include "mlir/IR/Dominance.h"
21
22#include "mlir/Pass/Pass.h"
24#include "llvm/Support/Casting.h"
25
26using namespace mlir;
27using namespace mlir::vector;
28using namespace mlir::x86;
29
30// Verifies that the LHS and RHS operands of a vector.contract are load or
31// vector.transfer_read operations on a memref source buffer, and checks
32// their bounds, dimensions, offsets, and strides.
33static bool validateVectorContractOperands(Value prodOp, bool isVnni) {
34 Operation *defOp = prodOp.getDefiningOp();
35 if (!defOp)
36 return false;
37
38 if (auto readOp = prodOp.getDefiningOp<mlir::vector::TransferReadOp>()) {
39 if (readOp.hasOutOfBoundsDim())
40 return false;
41
42 // The x86 packed loads read every lane, so they cannot keep a mask. A read
43 // in `vector.mask` never gets here: the operand is then the `vector.mask`
44 // result, which is rejected below as it is not a load.
45 if (readOp.getMask())
46 return false;
47
48 if (!readOp.getPermutationMap().isMinorIdentity())
49 return false;
50 }
51
52 Value srcBuff;
54 llvm::TypeSwitch<Operation *>(defOp).Case<TransferReadOp, LoadOp>(
55 [&](auto readOp) {
56 srcBuff = readOp.getOperand(0);
57 indexVals = SmallVector<OpFoldResult>(readOp.getIndices().begin(),
58 readOp.getIndices().end());
59 });
60
61 if (!srcBuff)
62 return false;
63
64 // Return false, if the source is not a memref type
65 Type srcType = srcBuff.getType();
66 if (!llvm::isa<MemRefType>(srcType))
67 return false;
68
69 // Return false if the two innermost strides of the memref are not contiguous.
70 // The x86.avx.cvt.packed.even/odd.indexed_to_f32 operations require
71 // an eight-element tuple of bf16 values to be contiguous.
72 int dimsToCheck = isVnni ? 2 : 1;
73 if (!cast<mlir::MemRefType>(srcType).areTrailingDimsContiguous(dimsToCheck))
74 return false;
75
76 // Return false if the vnni offset of load or transfer_read is not zero.
77 if (isVnni && getConstantIntValue(indexVals.back()) != 0)
78 return false;
79
80 return true;
81}
82
83// This function retrieves the source operation of the load or transfer
84// reads and creates subviews for the BF16 packed-operations to
85// broadcast or load BF16 elements as F32 packed elements.
86//
87// Example(1) Unit Dim:
88// ```
89// vector.load %arg0[%c0, %c0, %c0]:memref<4x1x2xbf16>,vector<1x1x2xbf16>
90// ```
91// to
92// ```
93// memref.subview %arg0[%c0,%c0,%c1]:memref<4x1x2xbf16> to memref<1x1x1xbf16>
94// memref.subview %arg0[%c0,%c0,%c0]:memref<4x1x2xbf16> to memref<1x1x1xbf16>
95// ```
96//
97// Example(2) Non-unit Dim:
98// ```
99// vector.load %arg1[%c0, %c0, %c0]:memref<1x32x2xbf16>,vector<1x8x2xbf16>
100// ```
101// to
102// ```
103// memref.subview %arg1[%c0,%c0,%c0]:memref<1x32x2xbf16> to memref<1x8x2xbf16>
104// ```
107 ArrayRef<int64_t> nonUnitDimShape, bool isUnitDim,
108 bool isVNNI) {
109
110 Operation *defOp = prodOp.getDefiningOp();
111
112 Value srcBuff;
114 llvm::TypeSwitch<Operation *>(defOp).Case<TransferReadOp, LoadOp>(
115 [&](auto readOp) {
116 srcBuff = readOp.getOperand(0);
117 indexVals = SmallVector<OpFoldResult>(readOp.getIndices().begin(),
118 readOp.getIndices().end());
119 });
120
121 int64_t mnDimSize = 1;
122 unsigned mnDimIdx = 0;
123
124 if (!isUnitDim) {
125 for (auto it : llvm::enumerate(nonUnitDimShape)) {
126 if (it.value() != 1) {
127 mnDimSize = it.value();
128 mnDimIdx = it.index();
129 break;
130 }
131 }
132 }
133
134 auto one = rewriter.getIndexAttr(1);
136
137 if (!isVNNI) {
138 SmallVector<OpFoldResult> strides(indexVals.size(), one);
139 SmallVector<OpFoldResult> sizes(indexVals.size(), one);
140 // Retrive twice the nonUnit dim BF16 element for both even and odd
141 // index elements.
142 if (!isUnitDim)
143 mnDimSize = 2 * mnDimSize;
144 sizes[mnDimIdx] = rewriter.getIndexAttr(mnDimSize);
145 auto subview = memref::SubViewOp::create(rewriter, loc, srcBuff, indexVals,
146 sizes, strides);
147 subviews.push_back(subview);
148 return subviews;
149 }
150
151 int vnniDimSize = isUnitDim ? 1 : 2;
152 auto nonVNNIDimSize = indexVals.size() - 1;
153 // Create the size and stride offsets.
154 SmallVector<OpFoldResult> strides(indexVals.size(), one);
155 SmallVector<OpFoldResult> sizes(nonVNNIDimSize, one);
156
157 sizes.push_back(rewriter.getIndexAttr(vnniDimSize));
158
159 // update the unit/nonUnit Dim size either it is A(LHS) or B(RHS).
160 sizes[mnDimIdx] = rewriter.getIndexAttr(mnDimSize);
161
162 // for unitDim, first broadcast odd element, so index is set to 1.
163 if (isUnitDim)
164 indexVals[indexVals.size() - 1] = rewriter.getIndexAttr(1);
165
166 auto subview = memref::SubViewOp::create(rewriter, loc, srcBuff, indexVals,
167 sizes, strides);
168 subviews.push_back(subview);
169
170 // For unit-dims, two subviews should be created for the odd and even
171 // element in the VNNI tuple (2xbf16) because x86.avx.bcst_to_f32.packed
172 // op loads and broadcast the first BF16 element into packed F32. It
173 // cannot distinguish between even and odd BF16 elements within a
174 // packed pair.
175 //
176 // Example:
177 // memref.subview %arg0[%c0,%c1]:memref<1x2xbf16> to memref<1x1xbf16> // Odd
178 // memref.subview %arg0[%c0,%c0]:memref<1x2xbf16> to memref<1x1xbf16> // Even
179 if (mnDimSize == 1) {
180 indexVals[indexVals.size() - 1] = rewriter.getIndexAttr(0);
181 sizes[indexVals.size() - 1] = rewriter.getIndexAttr(1);
182
183 auto unitDimEvenIdxSubview = memref::SubViewOp::create(
184 rewriter, loc, srcBuff, indexVals, sizes, strides);
185 subviews.push_back(unitDimEvenIdxSubview);
186 }
187
188 return subviews;
189}
190
191// Lowers a BF16 vector.contract to FMAs by up-converting BF16 to F32 with
192// integer bit ops (BF16 is the upper half of F32), without AVX2_BF16 ops2_BF16
193// ops.
194//
195// VNNI: each i32 holds an (even, odd) BF16 pair; `shl 16` yields the even
196// element and `and 0xFFFF0000` the odd one. Flat: `extui` + `shl 16`.
198 vector::ContractionOp contractOp, Value unitSrc,
199 Value nonUnitSrc, int64_t vecLen, bool isVnni) {
200 Location loc = contractOp.getLoc();
201 Type i16Ty = rewriter.getI16Type();
202 Type i32Ty = rewriter.getI32Type();
203 auto i32VecTy = VectorType::get(vecLen, i32Ty);
204 auto f32VecTy = VectorType::get(vecLen, rewriter.getF32Type());
205 auto accTy = cast<VectorType>(contractOp.getAccType());
206
207 auto flatten = [&](Value v) -> Value {
208 auto ty = cast<VectorType>(v.getType());
209 return vector::ShapeCastOp::create(
210 rewriter, loc,
211 VectorType::get(ty.getNumElements(), ty.getElementType()), v);
212 };
213 auto splat = [&](uint32_t v) -> Value {
214 return arith::ConstantOp::create(
215 rewriter, loc, i32VecTy,
216 DenseElementsAttr::get(i32VecTy, static_cast<int32_t>(v)));
217 };
218 auto toF32 = [&](Value v) -> Value {
219 return vector::BitCastOp::create(rewriter, loc, f32VecTy, v);
220 };
221
222 Value shift16 = splat(16);
223 Value acc =
224 vector::ShapeCastOp::create(rewriter, loc, f32VecTy, contractOp.getAcc());
226
227 if (isVnni) {
228 Value unitI32 = vector::BitCastOp::create(
229 rewriter, loc, VectorType::get(1, i32Ty), flatten(unitSrc));
230 Value unitBcst =
231 vector::BroadcastOp::create(rewriter, loc, i32VecTy, unitI32);
232 Value nonUnitI32 =
233 vector::BitCastOp::create(rewriter, loc, i32VecTy, flatten(nonUnitSrc));
234
235 Value oddMask = splat(0xFFFF0000u);
236 Value unitOdd =
237 toF32(arith::AndIOp::create(rewriter, loc, unitBcst, oddMask));
238 Value nonUnitOdd =
239 toF32(arith::AndIOp::create(rewriter, loc, nonUnitI32, oddMask));
240 Value oddFma =
241 vector::FMAOp::create(rewriter, loc, unitOdd, nonUnitOdd, acc);
242
243 Value unitEven =
244 toF32(arith::ShLIOp::create(rewriter, loc, unitBcst, shift16));
245 Value nonUnitEven =
246 toF32(arith::ShLIOp::create(rewriter, loc, nonUnitI32, shift16));
247 result =
248 vector::FMAOp::create(rewriter, loc, unitEven, nonUnitEven, oddFma);
249 } else {
250 auto extToI32 = [&](Value v, int64_t len) -> Value {
251 Value i16 = vector::BitCastOp::create(
252 rewriter, loc, VectorType::get(len, i16Ty), flatten(v));
253 return arith::ExtUIOp::create(rewriter, loc, VectorType::get(len, i32Ty),
254 i16);
255 };
256 Value unitBcst = vector::BroadcastOp::create(rewriter, loc, i32VecTy,
257 extToI32(unitSrc, 1));
258 Value unitF32 =
259 toF32(arith::ShLIOp::create(rewriter, loc, unitBcst, shift16));
260 Value nonUnitF32 = toF32(arith::ShLIOp::create(
261 rewriter, loc, extToI32(nonUnitSrc, vecLen), shift16));
262 result = vector::FMAOp::create(rewriter, loc, unitF32, nonUnitF32, acc);
263 }
264
265 rewriter.replaceOpWithNewOp<vector::ShapeCastOp>(contractOp, accTy, result);
266}
267
268// Implements outer product contraction as a sequence of BF16-packed
269// operation even/odd loads and FMA operations.
270//
271// For example (VNNI packed):
272// ```
273// %1 = vector.load from memref (%m1) -> vector<1x1x2xbf16>
274// %2 = vector.load from memref (%m2) -> vector<1x8x2xbf16>
275// return vector.contract %1, %2, %arg1
276// ```
277// to
278// ```
279// %1 = x86.avx.bcst_to_f32.packed %m1[c1] -> vector<8xf32>
280// %2 = x86.avx.cvt.packed.odd.indexed_to_f32 %m2 -> vector<8xf32>
281// %3 = vector.fma %1, %2, %arg1
282// %4 = x86.avx.bcst_to_f32.packed %m1[c0] -> vector<8xf32>
283// %5 = x86.avx.cvt.packed.even.indexed_to_f32 %m2 -> vector<8xf32>
284// return vector.fma %4, %5, %3
285// ```
286//
287// For example (Flat layout):
288// ```
289// %1 = vector.load from memref (%m1) -> vector<1x1xbf16>
290// %2 = vector.load from memref (%m2) -> vector<1x8xbf16>
291// %3 = vector.contract %1, %2, %arg1
292// %4 = vector.load from memref (%m2) -> vector<1x8xbf16>
293// %5 = vector.contract %1, %4, %arg2
294// scf.yield %3, %4
295// ```
296// to
297// ```
298// %1 = x86.avx.bcst_to_f32.packed %m1[c0] -> vector<8xf32>
299// %2 = x86.avx.cvt.packed.even.indexed_to_f32 %m2 -> vector<8xf32>
300// %3 = vector.fma %1, %2, %arg1
301// %4 = x86.avx.cvt.packed.odd.indexed_to_f32 %m2 -> vector<8xf32>
302// %5 = vector.fma %1, %4, %arg2
303// scf.yield %3, %5
306 : AddContractionOpRewritePattern(ctx), fallback(fallback) {}
307
308 LogicalResult
309 matchAndRewriteAddContractOp(vector::ContractionOp contractOp,
310 PatternRewriter &rewriter) const override {
311
312 // TODO: Move this validation to a common utility folder. Planned to
313 // do once (code refactoring), all architecture specific nanokernel
314 // passes are merged into the repo.
315 VectorType lhsTy = contractOp.getLhsType();
316 Type elemTy = lhsTy.getElementType();
317 if (!elemTy.isBF16() && !elemTy.isF16())
318 return rewriter.notifyMatchFailure(
319 contractOp, "Only BF16/F16 lowering is supported.");
320
321 if (fallback && elemTy.isF16())
322 return rewriter.notifyMatchFailure(
323 contractOp, "The BF16 fallback does not support F16.");
324
325 bool isVnni = isInVnniLayout(contractOp.getOperation(),
326 contractOp.getIndexingMapsArray(),
327 /*blockingFactor=*/2);
328
329 VectorType accTy = dyn_cast<VectorType>(contractOp.getAccType());
330 if (!accTy)
331 return rewriter.notifyMatchFailure(contractOp, "Wrong accmulator type.");
332
333 if (!accTy.getElementType().isF32())
334 return rewriter.notifyMatchFailure(
335 contractOp, "Only F32 acumulation supported for BF16/F16 type.");
336
337 ArrayRef<int64_t> accShape = accTy.getShape();
338 llvm::SmallVector<int64_t> nonUnitDimAcc;
339 llvm::copy_if(accShape, std::back_inserter(nonUnitDimAcc),
340 [](int64_t dim) { return dim != 1; });
341 if (nonUnitDimAcc.size() != 1)
342 return rewriter.notifyMatchFailure(
343 contractOp, "A or B should be a non-unit dim in acc.");
344
345 ArrayRef<int64_t> lhsShape = lhsTy.getShape();
346 llvm::SmallVector<int64_t> nonUnitDimLhs;
347 llvm::copy_if(lhsShape, std::back_inserter(nonUnitDimLhs),
348 [](int64_t dim) { return dim != 1; });
349
350 VectorType rhsTy = contractOp.getRhsType();
351 ArrayRef<int64_t> rhsShape = rhsTy.getShape();
352 llvm::SmallVector<int64_t> nonUnitDimRhs;
353 llvm::copy_if(rhsShape, std::back_inserter(nonUnitDimRhs),
354 [](int64_t dim) { return dim != 1; });
355
356 if (isVnni && (nonUnitDimLhs.size() - 1) > 0 &&
357 (nonUnitDimRhs.size() - 1) > 0)
358 return rewriter.notifyMatchFailure(contractOp,
359 "Excepts unit dimensions for either "
360 "LHS or RHS shape other than VNNI.");
361
362 if (isVnni && (nonUnitDimLhs.size() - 1) != 1 &&
363 (nonUnitDimRhs.size() - 1) != 1)
364 return rewriter.notifyMatchFailure(
365 contractOp,
366 "Excepts a one non-unit A/B dimension for either LHS or RHS shape.");
367
368 if (!isVnni && nonUnitDimLhs.size() > 0 && nonUnitDimRhs.size() > 0)
369 return rewriter.notifyMatchFailure(contractOp,
370 "Excepts unit dimensions for either "
371 "LHS or RHS shape.");
372
373 if (!isVnni && nonUnitDimLhs.size() != 1 && nonUnitDimRhs.size() != 1)
374 return rewriter.notifyMatchFailure(
375 contractOp,
376 "Excepts a one non-unit A/B dimension for either LHS or RHS shape.");
377
378 // Non-unit dimensions should match the vector length of BF16.
379 unsigned int nonUnitDim = nonUnitDimAcc.front();
380 // The fallback uses generic vector ops, so it can also target AVX512.
381 if (fallback && nonUnitDim != 4 && nonUnitDim != 8 && nonUnitDim != 16)
382 return rewriter.notifyMatchFailure(
383 contractOp, "BF16 fallback expects non-unit (LHS or RHS) dim and "
384 "acc dim of size 4/8/16.");
385
386 if (!fallback && nonUnitDim != 4 && nonUnitDim != 8)
387 return rewriter.notifyMatchFailure(
388 contractOp, "BF16 packed load operation expects non-unit (LHR or "
389 "RHS) dim and acc dim of size 4/8.");
390
391 if (!validateVectorContractOperands(contractOp.getLhs(), isVnni) ||
392 !validateVectorContractOperands(contractOp.getRhs(), isVnni)) {
393 return rewriter.notifyMatchFailure(
394 contractOp, "The LHS or RHS is in an invalid format. Either it has "
395 "false in-bounds, a mask, "
396 "a non-identity permutation map, a non-zero VNNI offset, "
397 "a non-memref "
398 "source, or a non-unit VNNI stride");
399 }
400
401 // Lower vector.contract to FMAs with help of BF16 packed ops.
402 auto loc = contractOp.getLoc();
403
404 // create the unit-dimension LHS or RHS subview and the
405 // corresponding non-unit dimension LHS or RHS subview on the other-side.
406 // For example, if LHS has type vector<1x1x2xbf16> and RHS has type
407 // vector<1x8x2xbf16>, we create two subview for the LHS and one subview
408 // for the RHS. In the opposite case (non-unit dimension on the LHS), we
409 // do vice-versa.
410
411 bool rhsHasMultipleNonUnitDims = nonUnitDimRhs.size() > 0;
412 if (isVnni) {
413 rhsHasMultipleNonUnitDims = (nonUnitDimRhs.size() - 1) > 0;
414 }
415
416 // Select which operand is "unit" and which is "non-unit".
417 Value unitSrc =
418 rhsHasMultipleNonUnitDims ? contractOp.getLhs() : contractOp.getRhs();
419 Value nonUnitSrc =
420 rhsHasMultipleNonUnitDims ? contractOp.getRhs() : contractOp.getLhs();
421
422 ArrayRef<int64_t> nonUnitDimShape =
423 rhsHasMultipleNonUnitDims ? rhsShape : lhsShape;
424
425 // The fallback rewrites each contract alone, so flat layouts need no pair.
426 if (fallback) {
427 upconvertBF16ToFMA(rewriter, contractOp, unitSrc, nonUnitSrc, nonUnitDim,
428 isVnni);
429 return success();
430 }
431
432 // Get the pair vector.contract operation. The pair is decided on:
433 // (1) - the unitDim operand Lhs or Rhs should be same,
434 // (2) - the defining source memref should be same for nonUnitDim
435 // operation, (3) - the nonUnit dim offset difference between the
436 // vector.contracts should be 8.
437 vector::ContractionOp pairContractOp;
438 if (!isVnni) {
439 Operation *nextOp = contractOp;
440 while ((nextOp = nextOp->getNextNode())) {
441 auto contOp = dyn_cast<vector::ContractionOp>(nextOp);
442
443 if (!contOp)
444 continue;
445
446 if (validatePairVectorContract(contractOp, contOp,
447 rhsHasMultipleNonUnitDims,
448 nonUnitDimAcc.front())) {
449 pairContractOp = contOp;
450 break;
451 }
452 }
453
454 if (!pairContractOp)
455 return failure();
456
457 // The pair is rewritten too, so its reads need the same checks.
458 if (!validateVectorContractOperands(pairContractOp.getLhs(), isVnni) ||
459 !validateVectorContractOperands(pairContractOp.getRhs(), isVnni))
460 return rewriter.notifyMatchFailure(
461 contractOp, "The LHS or RHS of the pair contract is in an invalid "
462 "format.");
463
464 Operation *accReadOp0 =
465 traceToVectorReadLikeParentOperation(contractOp.getAcc());
466 Operation *accReadOp1 =
467 traceToVectorReadLikeParentOperation(pairContractOp.getAcc());
468
469 // Iterate down to find the users of contact operations until it is store
470 // or transfer_write.
471 Operation *resultWriteOp0 =
472 traceToVectorWriteLikeUserOperation(contractOp.getResult());
473 Operation *resultWriteOp1 =
474 traceToVectorWriteLikeUserOperation(pairContractOp.getResult());
475
476 if (!accReadOp0 || !accReadOp1)
477 return rewriter.notifyMatchFailure(
478 contractOp,
479 "Operand doesn't have load or transfer_read as its parent op");
480
481 if (!resultWriteOp0 || !resultWriteOp1)
482 return rewriter.notifyMatchFailure(
483 contractOp,
484 "The use of contract operations are neither vector.store "
485 "or transfer_write or has multiple users");
486
487 if (contractOp->getBlock() == accReadOp1->getBlock() &&
488 contractOp->isBeforeInBlock(accReadOp1))
489 return rewriter.notifyMatchFailure(
490 contractOp, "The load/read operation of pair contract operation is "
491 "after the contractOp");
492
493 if (pairContractOp->getBlock() == resultWriteOp0->getBlock() &&
494 resultWriteOp0->isBeforeInBlock(pairContractOp)) {
495 return rewriter.notifyMatchFailure(
496 contractOp, "The store/write operation of contract operation is "
497 "before the pair contract operation");
498 }
499 }
500
501 // Build subviews.
502 auto unitDimSubview = getSubviewFromVectorInput(
503 loc, rewriter, unitSrc, nonUnitDimShape, true, isVnni);
504
505 auto nonUnitDimSubview = getSubviewFromVectorInput(
506 loc, rewriter, nonUnitSrc, nonUnitDimShape, false, isVnni);
507
508 auto castAcc = vector::ShapeCastOp::create(
509 rewriter, loc,
510 VectorType::get(nonUnitDimAcc.front(), accTy.getElementType()),
511 contractOp.getAcc());
512 VectorType dstType =
513 VectorType::get(nonUnitDimAcc.front(), rewriter.getF32Type());
514
515 if (!isVnni) {
516
517 // Validate and shuffle the accumulator
518 Operation *accReadOp0 =
519 traceToVectorReadLikeParentOperation(contractOp.getAcc());
520 Operation *accReadOp1 =
521 traceToVectorReadLikeParentOperation(pairContractOp.getAcc());
522
523 if (!isa<arith::ConstantOp>(accReadOp0)) {
524 // Shuffle the accumulators of the contract operations.
525 LogicalResult readShuffle =
526 shuffleAfterReadLikeOp(rewriter, accReadOp0, accReadOp1, contractOp,
527 pairContractOp, nonUnitDim, accTy);
528
529 if (failed(readShuffle))
530 return rewriter.notifyMatchFailure(
531 contractOp, "Accumulator read is not by transfer_read or load");
532 }
533
534 // Shuffle the output of contract operations before its use.
535 LogicalResult writeShuffle = shuffleBeforeWriteLikeOp(
536 rewriter, contractOp.getResult(), pairContractOp.getResult(),
537 nonUnitDim, accTy);
538
539 if (failed(writeShuffle))
540 return rewriter.notifyMatchFailure(
541 contractOp,
542 "Write to accumulator is not by transfer_write or store");
543
544 rewriter.setInsertionPoint(contractOp);
545 castAcc = vector::ShapeCastOp::create(
546 rewriter, loc,
547 VectorType::get(nonUnitDimAcc.front(), accTy.getElementType()),
548 contractOp.getAcc());
549
550 auto loadBcstBF16ElementToF32 = x86::avx::BcstToPackedF32Op::create(
551 rewriter, loc, dstType, unitDimSubview[0]);
552 auto loadEvenIdxElementF32 =
553 x86::avx::CvtPackedEvenIndexedToF32Op::create(rewriter, loc, dstType,
554 nonUnitDimSubview[0]);
555 auto evenIdxFMA =
556 vector::FMAOp::create(rewriter, loc, loadBcstBF16ElementToF32,
557 loadEvenIdxElementF32, castAcc);
558 auto castEvenFma =
559 vector::ShapeCastOp::create(rewriter, loc, accTy, evenIdxFMA);
560 rewriter.replaceOp(contractOp, castEvenFma);
561
562 rewriter.setInsertionPoint(pairContractOp);
563 auto pairContOpLoc = pairContractOp.getLoc();
564 VectorType accTyPairCont =
565 dyn_cast<VectorType>(pairContractOp.getAccType());
566 auto castAccPairCont = vector::ShapeCastOp::create(
567 rewriter, pairContOpLoc,
568 VectorType::get(nonUnitDimAcc.front(),
569 accTyPairCont.getElementType()),
570 pairContractOp.getAcc());
571
572 auto loadOddIdxElementF32 = x86::avx::CvtPackedOddIndexedToF32Op::create(
573 rewriter, pairContOpLoc, dstType, nonUnitDimSubview[0]);
574 auto oddIdxFMA = vector::FMAOp::create(
575 rewriter, pairContOpLoc, loadBcstBF16ElementToF32,
576 loadOddIdxElementF32, castAccPairCont);
577 auto castOddFma = vector::ShapeCastOp::create(rewriter, pairContOpLoc,
578 accTyPairCont, oddIdxFMA);
579 rewriter.replaceOp(pairContractOp, castOddFma);
580
581 return success();
582 }
583
584 // Load, broadcast, and do FMA for odd indexed BF16 elements.
585 auto loadBcstOddIdxElementToF32 = x86::avx::BcstToPackedF32Op::create(
586 rewriter, loc, dstType, unitDimSubview[0]);
587 auto loadOddIdxElementF32 = x86::avx::CvtPackedOddIndexedToF32Op::create(
588 rewriter, loc, dstType, nonUnitDimSubview[0]);
589 auto oddIdxFMA =
590 vector::FMAOp::create(rewriter, loc, loadBcstOddIdxElementToF32,
591 loadOddIdxElementF32, castAcc);
592
593 // Load, broadcast, and do FMA for even indexed BF16 elements.
594 auto loadBcstEvenIdxElementToF32 = x86::avx::BcstToPackedF32Op::create(
595 rewriter, loc, dstType, unitDimSubview[1]);
596 auto loadEvenIdxElementF32 = x86::avx::CvtPackedEvenIndexedToF32Op::create(
597 rewriter, loc, dstType, nonUnitDimSubview[0]);
598 vector::FMAOp fma =
599 vector::FMAOp::create(rewriter, loc, loadBcstEvenIdxElementToF32,
600 loadEvenIdxElementF32, oddIdxFMA);
601
602 auto castFma = vector::ShapeCastOp::create(rewriter, loc, accTy, fma);
603 rewriter.replaceOp(contractOp, castFma);
604 return success();
605 }
606
607private:
608 bool fallback;
609};
610
612 RewritePatternSet &patterns, bool fallback) {
613 patterns.add<VectorContract16BitFPToFMA>(patterns.getContext(), fallback);
614}
return success()
static SmallVector< memref::SubViewOp > getSubviewFromVectorInput(Location loc, PatternRewriter &rewriter, Value prodOp, ArrayRef< int64_t > nonUnitDimShape, bool isUnitDim, bool isVNNI)
static void upconvertBF16ToFMA(PatternRewriter &rewriter, vector::ContractionOp contractOp, Value unitSrc, Value nonUnitSrc, int64_t vecLen, bool isVnni)
static bool validateVectorContractOperands(Value prodOp, bool isVnni)
IntegerAttr getIndexAttr(int64_t value)
Definition Builders.cpp:116
IntegerType getI16Type()
Definition Builders.cpp:69
FloatType getF32Type()
Definition Builders.cpp:51
IntegerType getI32Type()
Definition Builders.cpp:71
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
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
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool isBeforeInBlock(Operation *other)
Given an operation 'other' that is within the same parent block, return whether the current operation...
Block * getBlock()
Returns the operation block that contains this operation.
Definition Operation.h:230
A special type of RewriterBase that coordinates the application of a rewrite pattern on the current I...
MLIRContext * getContext() const
RewritePatternSet & add(ConstructorArg &&arg, ConstructorArgs &&...args)
Add an instance of each of the pattern types 'Ts' to the pattern list with the given arguments.
virtual void replaceOp(Operation *op, ValueRange newValues)
Replace the results of the given (original) operation with the specified list of values (replacements...
std::enable_if_t<!std::is_convertible< CallbackT, Twine >::value, LogicalResult > notifyMatchFailure(Location loc, CallbackT &&reasonCallback)
Used to notify the listener that the IR failed to be rewritten because of a match failure,...
OpTy replaceOpWithNewOp(Operation *op, Args &&...args)
Replace the results of the given (original) op with a new op that is created without verification (re...
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isF16() const
Definition Types.cpp:38
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
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
LogicalResult shuffleBeforeWriteLikeOp(PatternRewriter &rewriter, Value contractARes, Value contractBRes, int64_t nonUnitDimAcc, VectorType accTy)
Definition X86Utils.cpp:333
void populateVectorContract16BitFPToFMAPatterns(RewritePatternSet &patterns, bool fallback=false)
Operation * traceToVectorWriteLikeUserOperation(Value v)
Definition X86Utils.cpp:233
bool isInVnniLayout(Operation *op, llvm::ArrayRef< AffineMap > indexingMaps, std::optional< unsigned > blockingFactor=std::nullopt)
Definition X86Utils.cpp:42
Operation * traceToVectorReadLikeParentOperation(Value v)
Definition X86Utils.cpp:173
LogicalResult shuffleAfterReadLikeOp(PatternRewriter &rewriter, Operation *opA, Operation *opB, vector::ContractionOp contractA, vector::ContractionOp contractB, int64_t nonUnitDimAcc, VectorType accTy)
Definition X86Utils.cpp:283
bool validatePairVectorContract(vector::ContractionOp contractOp, vector::ContractionOp pairContOp, bool rhsHasMultipleNonUnitDims, int64_t nonUnitDimValue)
Definition X86Utils.cpp:391
Include the generated interface declarations.
std::optional< int64_t > getConstantIntValue(OpFoldResult ofr)
If ofr is a constant integer or an IntegerAttr, return the integer.
LogicalResult matchAndRewriteAddContractOp(vector::ContractionOp contractOp, PatternRewriter &rewriter) const override
VectorContract16BitFPToFMA(MLIRContext *ctx, bool fallback)
Convenience wrapper for patterns that are only intended for default contractions, i....