MLIR 24.0.0git
ShardOps.cpp
Go to the documentation of this file.
1//===- ShardOps.cpp - Shard Dialect 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//===----------------------------------------------------------------------===//
8
10
14#include "mlir/IR/Attributes.h"
18#include "mlir/IR/Diagnostics.h"
19#include "mlir/IR/IRMapping.h"
20#include "mlir/IR/Location.h"
23#include "mlir/IR/Value.h"
25#include "mlir/Support/LLVM.h"
27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SmallVector.h"
31#include <algorithm>
32#include <functional>
33#include <iterator>
34#include <numeric>
35#include <optional>
36#include <utility>
37
38#define DEBUG_TYPE "shard-ops"
39
40using namespace mlir;
41using namespace mlir::shard;
42
43#include "mlir/Dialect/Shard/IR/ShardDialect.cpp.inc"
44
45namespace {
46
47struct DimensionSize {
48 static DimensionSize dynamic() { return DimensionSize(ShapedType::kDynamic); }
49 DimensionSize(int64_t val) : val(val) {}
50 int64_t value() const { return val; }
51 operator int64_t() const { return val; }
52 bool isDynamic() const { return ShapedType::isDynamic(val); }
53
54private:
55 int64_t val;
56};
57
58} // namespace
59
60static DimensionSize operator/(DimensionSize lhs, DimensionSize rhs) {
61 if (lhs.isDynamic() || rhs.isDynamic()) {
62 return DimensionSize::dynamic();
63 }
64 return lhs.value() / rhs.value();
65}
66
67static DimensionSize operator*(DimensionSize lhs, DimensionSize rhs) {
68 if (lhs.isDynamic() || rhs.isDynamic()) {
69 return DimensionSize::dynamic();
70 }
71 return lhs.value() * rhs.value();
72}
73
77 ValueRange dynamics, Type type) {
78 SmallVector<Value> values;
79 auto dyn = dynamics.begin();
80 Type i64 = b.getI64Type();
81 if (!type)
82 type = i64;
83 assert((i64 == type || b.getIndexType() == type) &&
84 "expected an i64 or an intex type");
85 for (auto s : statics) {
86 if (s == ShapedType::kDynamic) {
87 values.emplace_back(*(dyn++));
88 } else {
89 TypedAttr val = type == i64 ? b.getI64IntegerAttr(s) : b.getIndexAttr(s);
90 values.emplace_back(arith::ConstantOp::create(b, loc, type, val));
91 }
92 }
93 return values;
94}
95
96//===----------------------------------------------------------------------===//
97// Inliner
98//===----------------------------------------------------------------------===//
99
100namespace {
101struct ShardInlinerinterface : public DialectInlinerInterface {
102 using DialectInlinerInterface::DialectInlinerInterface;
103 // Currently no restrictions are encoded for inlining.
104 bool isLegalToInline(Operation *, Operation *, bool) const final {
105 return true;
106 }
107 bool isLegalToInline(Region *, Region *, bool, IRMapping &) const final {
108 return true;
109 }
110 bool isLegalToInline(Operation *, Region *, bool, IRMapping &) const final {
111 return true;
112 }
113};
114} // namespace
115
116//===----------------------------------------------------------------------===//
117// Shard dialect
118//===----------------------------------------------------------------------===//
119
120void ShardDialect::initialize() { addInterface<ShardInlinerinterface>(); }
121
122Operation *ShardDialect::materializeConstant(OpBuilder &builder,
123 Attribute value, Type type,
124 Location loc) {
125 return arith::ConstantOp::materialize(builder, value, type, loc);
126}
127
128//===----------------------------------------------------------------------===//
129// Shard utilities
130//===----------------------------------------------------------------------===//
131
132static FailureOr<GridOp> getGridAndVerify(Operation *op,
133 FlatSymbolRefAttr gridSymbol,
134 SymbolTableCollection &symbolTable) {
135 shard::GridOp grid = getGridOrNull(op, gridSymbol, symbolTable);
136 if (!grid) {
137 return op->emitError() << "Undefined required grid symbol \""
138 << gridSymbol.getValue() << "\".";
139 }
140
141 return grid;
142}
143
144template <typename It>
145static bool isUnique(It begin, It end) {
146 if (begin == end) {
147 return true;
148 }
149 It next = std::next(begin);
150 if (next == end) {
151 return true;
152 }
153 for (; next != end; ++next, ++begin) {
154 if (*begin == *next) {
155 return false;
156 }
157 }
158 return true;
159}
160
161static LogicalResult verifyGridAxes(Location loc, ArrayRef<GridAxis> axes,
162 GridOp grid) {
163 SmallVector<GridAxis> sorted = llvm::to_vector(axes);
164 llvm::sort(sorted);
165 if (!isUnique(sorted.begin(), sorted.end())) {
166 return emitError(loc) << "Grid axes contains duplicate elements.";
167 }
168
169 GridAxis rank = grid.getRank();
170 for (auto axis : axes) {
171 if (axis >= rank || axis < 0) {
172 return emitError(loc)
173 << "0-based grid axis index " << axis
174 << " is out of bounds. The referenced grid \"" << grid.getSymName()
175 << "\" is of rank " << rank << ".";
176 }
177 }
178
179 return success();
180}
181
182template <typename Op>
183static FailureOr<GridOp>
185 auto grid =
186 ::getGridAndVerify(op.getOperation(), op.getGridAttr(), symbolTable);
187 if (failed(grid)) {
188 return failure();
189 }
190 if (failed(verifyGridAxes(op.getLoc(), op.getGridAxes(), grid.value()))) {
191 return failure();
192 }
193 return grid;
194}
195
196template <typename InShape, typename GridShape, typename SplitAxes,
197 typename OutShape>
198static void shardShape(const InShape &inShape, const GridShape &gridShape,
199 const SplitAxes &splitAxes, OutShape &outShape,
200 ArrayRef<int64_t> shardedDimsOffsets = {},
201 ArrayRef<int64_t> haloSizes = {}) {
202 // 0d tensors cannot be sharded and must get replicated
203 if (inShape.empty()) {
204 assert(outShape.empty());
205 return;
206 }
207
208 std::copy(llvm::adl_begin(inShape), llvm::adl_end(inShape),
209 llvm::adl_begin(outShape));
210
211 if (!shardedDimsOffsets.empty()) {
212 auto isDynShape = ShapedType::isDynamicShape(gridShape);
213 uint64_t pos = 1;
214 for (auto [tensorAxis, innerSplitAxes] : llvm::enumerate(splitAxes)) {
215 if (!innerSplitAxes.empty()) {
216 auto sz = shardedDimsOffsets[pos];
217 bool same = !isDynShape;
218 if (same) {
219 // Find sharded dims in shardedDimsOffsets with same static size on
220 // all devices. Use kDynamic for dimensions with dynamic or
221 // non-uniform offs in shardedDimsOffsets.
222 uint64_t numShards = 0;
223 for (auto i : innerSplitAxes.asArrayRef()) {
224 numShards += gridShape[i];
225 }
226 for (size_t i = 1; i < numShards; ++i) {
227 if (shardedDimsOffsets[pos + i] - shardedDimsOffsets[pos + i - 1] !=
228 sz) {
229 same = false;
230 break;
231 }
232 }
233 pos += numShards + 1;
234 }
235 outShape[tensorAxis] = same ? sz : ShapedType::kDynamic;
236 }
237 }
238 } else {
239 for (auto [tensorAxis, innerSplitAxes] : llvm::enumerate(splitAxes)) {
240 outShape[tensorAxis] = shardDimension(
241 inShape[tensorAxis],
242 collectiveProcessGroupSize(innerSplitAxes.asArrayRef(), gridShape));
243 }
244
245 if (!haloSizes.empty()) {
246 // add halo sizes if requested
247 int haloAxis = 0;
248 for (auto [tensorAxis, innerSplitAxes] : llvm::enumerate(splitAxes)) {
249 if (ShapedType::isStatic(outShape[tensorAxis]) &&
250 !innerSplitAxes.empty()) {
251 if (haloSizes[haloAxis * 2] >= 0 &&
252 haloSizes[haloAxis * 2 + 1] >= 0) {
253 outShape[tensorAxis] +=
254 haloSizes[haloAxis * 2] + haloSizes[haloAxis * 2 + 1];
255 ++haloAxis;
256 } else {
257 outShape[tensorAxis] = ShapedType::kDynamic;
258 }
259 }
260 }
261 }
262 }
263}
264
265ShapedType shard::shardShapedType(ShapedType shape, GridOp grid,
266 Sharding sharding) {
267 using Dim = std::decay_t<decltype(shape.getDimSize(0))>;
268 SmallVector<Dim> resShapeArr(shape.getShape().size());
269 shardShape(shape.getShape(), grid.getShape(), sharding.getSplitAxes(),
270 resShapeArr, sharding.getStaticShardedDimsOffsets(),
271 sharding.getStaticHaloSizes());
272 return shape.clone(resShapeArr);
273}
274
275Type shard::shardType(Type type, GridOp grid, Sharding sharding) {
276 RankedTensorType rankedTensorType = dyn_cast<RankedTensorType>(type);
277 if (rankedTensorType && !rankedTensorType.getShape().empty()) {
278 return shardShapedType(rankedTensorType, grid, sharding);
279 }
280 return type;
281}
282
284 Value &operandValue,
285 Operation *operandOp,
286 OpBuilder &builder,
287 ShardOp &newShardOp) {
288 OpBuilder::InsertionGuard insertionGuard(builder);
289 builder.setInsertionPointAfterValue(operandValue);
290 ShardOp shardOp = dyn_cast<ShardOp>(operandOp);
291 if (shardOp && sharding == shardOp.getSharding() &&
292 !shardOp.getAnnotateForUsers()) {
293 // No need for anything if the correct sharding is already set.
294 if (!newShardOp) {
295 newShardOp = shardOp;
296 }
297 return;
298 }
299
300 if (!newShardOp) {
301 auto shardingOp =
302 ShardingOp::create(builder, operandValue.getLoc(), sharding);
303 newShardOp = ShardOp::create(builder, operandValue.getLoc(), operandValue,
304 shardingOp,
305 /*annotate_for_users*/ false);
306 }
307 operandValue.replaceUsesWithIf(
308 newShardOp, [operandOp, operandValue](OpOperand &use) {
309 return use.getOwner() == operandOp && use.get() == operandValue;
310 });
311
312 if (!shardOp || shardOp.getAnnotateForUsers()) {
313 return;
314 }
315
316 auto newShardOp2 = ShardOp::create(builder, operandValue.getLoc(), newShardOp,
317 newShardOp.getSharding(),
318 /*annotate_for_users*/ true);
319 newShardOp.getResult().replaceAllUsesExcept(newShardOp2, newShardOp2);
320}
321
324 OpBuilder &builder) {
325 ShardOp newShardOp;
327 for (auto &use : result.getUses()) {
328 uses.emplace_back(use.get(), use.getOwner());
329 }
330 for (auto &[operandValue, operandOp] : uses) {
331 maybeInsertTargetShardingAnnotationImpl(sharding, operandValue, operandOp,
332 builder, newShardOp);
333 }
334}
335
337 OpOperand &operand,
338 OpBuilder &builder) {
339 OpBuilder::InsertionGuard insertionGuard(builder);
340 Value operandValue = operand.get();
341 Operation *operandSrcOp = operandValue.getDefiningOp();
342 bool isBlockArg = !operandSrcOp;
343 {
344 [[maybe_unused]] auto opType =
345 dyn_cast<mlir::RankedTensorType>(operandValue.getType());
346 assert(!opType || opType.getRank() > 0 || isFullReplication(sharding));
347 }
348 if (!isa<RankedTensorType>(operandValue.getType()) && operandSrcOp &&
349 operandSrcOp->hasTrait<OpTrait::ConstantLike>()) {
350 return;
351 }
352
353 Operation *operandOp = operand.getOwner();
354 ShardOp shardOp = dyn_cast_or_null<ShardOp>(operandSrcOp);
355
356 if (shardOp && sharding == shardOp.getSharding() &&
357 shardOp.getAnnotateForUsers()) {
358 // No need for anything the correct sharding is already set.
359 return;
360 }
361
362 builder.setInsertionPoint(operandOp);
363 auto shardingOp =
364 ShardingOp::create(builder, operand.get().getLoc(), sharding);
365 auto newShardOp =
366 ShardOp::create(builder, operandValue.getLoc(), operandValue, shardingOp,
367 /*annotate_for_users*/ true);
368 IRRewriter rewriter(builder);
369 rewriter.replaceUsesWithIf(
370 operandValue, newShardOp, [operandOp, operandValue](OpOperand &use) {
371 return use.getOwner() == operandOp && use.get() == operandValue;
372 });
373
374 if (isBlockArg || !shardOp || !shardOp.getAnnotateForUsers()) {
375 // No need for resharding.
376 return;
377 }
378
379 builder.setInsertionPoint(newShardOp);
380 auto newPreceedingShardOp =
381 ShardOp::create(builder, operandValue.getLoc(), operandValue, shardingOp,
382 /*annotate_for_users*/ false);
383 rewriter.replaceUsesWithIf(
384 newShardOp.getSrc(), newPreceedingShardOp, [&newShardOp](OpOperand &use) {
385 return use.getOwner() == newShardOp.getOperation();
386 });
387}
388
389//===----------------------------------------------------------------------===//
390// shard.grid op
391//===----------------------------------------------------------------------===//
392
393LogicalResult GridOp::verify() {
394 int64_t rank = getRank();
395
396 if (rank <= 0)
397 return emitOpError("rank of grid is expected to be a positive integer");
398
399 for (int64_t dimSize : getShape()) {
400 if (dimSize < 0 && ShapedType::isStatic(dimSize))
401 return emitOpError("dimension size of a grid is expected to be "
402 "non-negative or dynamic");
403 }
404
405 return success();
406}
407
408//===----------------------------------------------------------------------===//
409// shard.grid_shape op
410//===----------------------------------------------------------------------===//
411
412LogicalResult
413GridShapeOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
414 auto grid = ::getGridAndVerify(getOperation(), getGridAttr(), symbolTable);
415 if (failed(grid)) {
416 return failure();
417 }
418 if (failed(verifyGridAxes(getLoc(), getAxes(), grid.value()))) {
419 return failure();
420 }
421
422 size_t expectedResultsCount =
423 getAxes().empty() ? grid->getRank() : getAxes().size();
424 if (getResult().size() != expectedResultsCount) {
425 return emitError() << "Unexpected number of results " << getResult().size()
426 << ". Expected " << expectedResultsCount << ".";
427 }
428
429 return success();
430}
431
432void GridShapeOp::build(OpBuilder &odsBuilder, OperationState &odsState,
433 GridOp grid) {
434 build(odsBuilder, odsState, grid, SmallVector<GridAxis>());
435}
436
437void GridShapeOp::build(OpBuilder &odsBuilder, OperationState &odsState,
438 GridOp grid, ArrayRef<GridAxis> axes) {
439 build(odsBuilder, odsState,
440 SmallVector<Type>(axes.empty() ? grid.getRank() : axes.size(),
441 odsBuilder.getIndexType()),
442 grid.getSymName(), GridAxesAttr::get(odsBuilder.getContext(), axes));
443}
444
445void GridShapeOp::build(OpBuilder &odsBuilder, OperationState &odsState,
446 StringRef grid, ArrayRef<GridAxis> axes) {
447 assert(!axes.empty());
448 build(odsBuilder, odsState,
449 SmallVector<Type>(axes.size(), odsBuilder.getIndexType()), grid,
450 GridAxesAttr::get(odsBuilder.getContext(), axes));
451}
452
453void GridShapeOp::getAsmResultNames(
454 function_ref<void(Value, StringRef)> setNameFn) {
455 setNameFn(getResults()[0], "grid_shape");
456}
457
458//===----------------------------------------------------------------------===//
459// shard.sharding
460//===----------------------------------------------------------------------===//
461
462void ShardingOp::build(::mlir::OpBuilder &b, ::mlir::OperationState &odsState,
464 ArrayRef<int64_t> staticHalos,
465 ArrayRef<int64_t> staticOffsets) {
466 return build(
467 b, odsState, grid, GridAxesArrayAttr::get(b.getContext(), splitAxes),
468 ::mlir::DenseI64ArrayAttr::get(b.getContext(), staticHalos), {},
469 ::mlir::DenseI64ArrayAttr::get(b.getContext(), staticOffsets), {});
470}
471
472void ShardingOp::build(::mlir::OpBuilder &b, ::mlir::OperationState &odsState,
473 llvm::StringRef grid, ArrayRef<GridAxesAttr> splitAxes,
474 ArrayRef<int64_t> staticHalos,
475 ArrayRef<int64_t> staticOffsets) {
476 return build(b, odsState, FlatSymbolRefAttr::get(b.getContext(), grid),
477 GridAxesArrayAttr::get(b.getContext(), splitAxes),
478 ::mlir::DenseI64ArrayAttr::get(b.getContext(), staticHalos), {},
479 ::mlir::DenseI64ArrayAttr::get(b.getContext(), staticOffsets),
480 {});
481}
482
483void ShardingOp::build(
487 ::mlir::ArrayRef<::mlir::OpFoldResult> shardedDimsOffsets) {
488 mlir::SmallVector<int64_t> staticHalos, staticDims;
489 mlir::SmallVector<mlir::Value> dynamicHalos, dynamicDims;
490 dispatchIndexOpFoldResults(haloSizes, dynamicHalos, staticHalos);
491 dispatchIndexOpFoldResults(shardedDimsOffsets, dynamicDims, staticDims);
492 return build(
493 b, odsState, grid, GridAxesArrayAttr::get(b.getContext(), splitAxes),
494 ::mlir::DenseI64ArrayAttr::get(b.getContext(), staticHalos), dynamicHalos,
495 ::mlir::DenseI64ArrayAttr::get(b.getContext(), staticDims), dynamicDims);
496}
497
498void ShardingOp::build(::mlir::OpBuilder &b, ::mlir::OperationState &odsState,
500
501 build(b, odsState, ShardingType::get(b.getContext()), from.getGridAttr(),
502 GridAxesArrayAttr::get(b.getContext(), from.getSplitAxes()),
503 from.getStaticShardedDimsOffsets().empty()
505 : b.getDenseI64ArrayAttr(from.getStaticShardedDimsOffsets()),
507 from.getStaticHaloSizes().empty()
509 : b.getDenseI64ArrayAttr(from.getStaticHaloSizes()),
510 from.getDynamicHaloSizes());
511}
512
513LogicalResult ShardingOp::verify() {
514 llvm::SmallSet<GridAxis, 4> visitedAxes;
515
516 auto checkGridAxis = [&](ArrayRef<GridAxis> axesArray) -> LogicalResult {
517 for (GridAxis axis : axesArray) {
518 if (axis < 0)
519 return emitError() << "grid axis is expected to be non-negative";
520 if (!visitedAxes.insert(axis).second)
521 return emitError() << "grid axis duplicated";
522 }
523 return success();
524 };
525
526 for (auto subAxes : getSplitAxes().getAxes()) {
527 ArrayRef<GridAxis> subAxesArray = subAxes.asArrayRef();
528 if (failed(checkGridAxis(subAxesArray)))
529 return failure();
530 }
531
532 if (!getStaticHaloSizes().empty() && !getStaticShardedDimsOffsets().empty()) {
533 return emitOpError("halo sizes and shard offsets are mutually exclusive");
534 }
535
536 if (!getStaticHaloSizes().empty()) {
537 auto numSplitAxes = getSplitAxes().getAxes().size();
538 for (auto splitAxis : getSplitAxes().getAxes()) {
539 if (splitAxis.empty()) {
540 --numSplitAxes;
541 }
542 }
543 if (getStaticHaloSizes().size() != numSplitAxes * 2) {
544 return emitError() << "halo sizes must be specified for all split axes.";
545 }
546 }
547
548 return success();
549}
550
551void ShardingOp::getAsmResultNames(
552 function_ref<void(Value, StringRef)> setNameFn) {
553 setNameFn(getResult(), "sharding");
554}
555
556LogicalResult ShardingOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
557 auto grid = ::getGridAndVerify(getOperation(), getGridAttr(), symbolTable);
558 if (failed(grid)) {
559 return failure();
560 }
561 if (mlir::ShapedType::isDynamicShape(grid->getShape()) &&
562 !getStaticShardedDimsOffsets().empty()) {
563 return emitError() << "sharded dims offsets are not allowed for "
564 "device grids with dynamic shape.";
565 }
566
567 auto shardedDimsOffsets = getStaticShardedDimsOffsets();
568 if (!shardedDimsOffsets.empty()) {
569 auto gridShape = grid.value().getShape();
570 assert(ShapedType::isStaticShape(gridShape));
571 uint64_t pos = 0;
572 for (auto [tensorAxis, innerSplitAxes] : llvm::enumerate(getSplitAxes())) {
573 if (!innerSplitAxes.empty()) {
574 int64_t numShards = 0, off = 0;
575 for (auto i : innerSplitAxes.asArrayRef()) {
576 numShards += gridShape[i];
577 }
578 for (int64_t i = 0; i <= numShards; ++i) {
579 if (shardedDimsOffsets.size() <= pos + i) {
580 return emitError() << "sharded dims offsets has wrong size.";
581 }
582 if (ShapedType::isStatic(shardedDimsOffsets[pos + i])) {
583 if (shardedDimsOffsets[pos + i] < off) {
584 return emitError()
585 << "sharded dims offsets must be non-decreasing.";
586 }
587 off = shardedDimsOffsets[pos + i];
588 }
589 }
590 pos += numShards + 1;
591 }
592 }
593 }
594 return success();
595}
596
597namespace {
598// Sharding annotations "halo sizes" and "sharded dims offsets"
599// are a mix of attributes and dynamic values. This canonicalization moves
600// constant values to the respective attribute lists, minimizing the number
601// of values.
602// It also removes sharded_dims_sizes and halos if they are effectively "empty".
603class NormalizeSharding final : public OpRewritePattern<ShardingOp> {
604public:
605 using OpRewritePattern<ShardingOp>::OpRewritePattern;
606
607 LogicalResult matchAndRewrite(ShardingOp op,
608 PatternRewriter &b) const override {
609 auto mixedHalos =
610 getMixedValues(op.getStaticHaloSizes(), op.getDynamicHaloSizes(), b);
611 auto mixedOffs = getMixedValues(op.getStaticShardedDimsOffsets(),
612 op.getDynamicShardedDimsOffsets(), b);
613
614 // No constant operands were folded, just return;
615 bool modified = succeeded(foldDynamicIndexList(mixedHalos, true)) ||
616 succeeded(foldDynamicIndexList(mixedOffs, true));
617
618 auto decomposedHalos = decomposeMixedValues(mixedHalos);
619 auto staticHalos = decomposedHalos.first;
620 auto dynamicHalos = decomposedHalos.second;
621 auto decomposedOffs = decomposeMixedValues(mixedOffs);
622 auto staticOffs = decomposedOffs.first;
623 auto dynamicOffs = decomposedOffs.second;
624
625 if (dynamicHalos.empty() && !staticHalos.empty()) {
626 if (staticHalos[0] == 0 && llvm::all_equal(staticHalos)) {
627 staticHalos.clear();
628 modified = true;
629 }
630 }
631
632 // Remove sharded dims offsets if they are effectively the default values,
633 // e.g. if they define equi-distance between all neighboring shards.
634 // Requires static-only offsets. Compares the first distance as the
635 // difference between the first two offsets. Only if all consecutive
636 // distances are the same, the offsets are removed.
637 if (dynamicOffs.empty() && !staticOffs.empty()) {
638 assert(staticOffs.size() >= 2);
639 auto diff = staticOffs[1] - staticOffs[0];
640 bool allSame = staticOffs.size() > 2;
641 for (auto i = 2u; i < staticOffs.size(); ++i) {
642 if (staticOffs[i] - staticOffs[i - 1] != diff) {
643 allSame = false;
644 break;
645 }
646 }
647 if (allSame) {
648 staticOffs.clear();
649 modified = true;
650 }
651 }
652
653 if (!modified) {
654 return failure();
655 }
656
657 b.modifyOpInPlace(op, [&]() {
658 op.setStaticHaloSizes(staticHalos);
659 op.getDynamicHaloSizesMutable().assign(dynamicHalos);
660 op.setStaticShardedDimsOffsets(staticOffs);
661 op.getDynamicShardedDimsOffsetsMutable().assign(dynamicOffs);
662 });
663 return success();
664 }
665};
666} // namespace
667
668void ShardingOp::getCanonicalizationPatterns(mlir::RewritePatternSet &results,
669 mlir::MLIRContext *context) {
670 results.add<NormalizeSharding>(context);
671}
672
673//===----------------------------------------------------------------------===//
674// Sharding
675//===----------------------------------------------------------------------===//
676
677bool Sharding::equalSplitAxes(const Sharding &rhs) const {
678 if (getGrid() != rhs.getGrid()) {
679 return false;
680 }
681
682 auto minSize = std::min(getSplitAxes().size(), rhs.getSplitAxes().size());
683 if (!llvm::equal(llvm::make_range(getSplitAxes().begin(),
684 getSplitAxes().begin() + minSize),
685 llvm::make_range(rhs.getSplitAxes().begin(),
686 rhs.getSplitAxes().begin() + minSize))) {
687 return false;
688 }
689
690 return llvm::all_of(llvm::drop_begin(getSplitAxes(), minSize),
691 std::mem_fn(&GridAxesAttr::empty)) &&
692 llvm::all_of(llvm::drop_begin(rhs.getSplitAxes(), minSize),
693 std::mem_fn(&GridAxesAttr::empty));
694}
695
697 return equalShardSizes(rhs) && equalHaloSizes(rhs);
698}
699
700bool Sharding::equalShardSizes(const Sharding &rhs) const {
701 if (rhs.getStaticShardedDimsOffsets().size() !=
703 !llvm::equal(getStaticShardedDimsOffsets(),
704 rhs.getStaticShardedDimsOffsets())) {
705 return false;
706 }
707 if (rhs.getDynamicShardedDimsOffsets().size() !=
709 !llvm::equal(getDynamicShardedDimsOffsets(),
710 rhs.getDynamicShardedDimsOffsets())) {
711 return false;
712 }
713 return true;
714}
715
716bool Sharding::equalHaloSizes(const Sharding &rhs) const {
717 if (rhs.getStaticHaloSizes().size() != getStaticHaloSizes().size() ||
718 !llvm::equal(getStaticHaloSizes(), rhs.getStaticHaloSizes())) {
719 return false;
720 }
721 if (rhs.getDynamicHaloSizes().size() != getDynamicHaloSizes().size() ||
722 !llvm::equal(getDynamicHaloSizes(), rhs.getDynamicHaloSizes())) {
723 return false;
724 }
725 return true;
726}
727
729 return equalSplitAxes(rhs) && equalHaloAndShardSizes(rhs);
730}
731
732bool Sharding::operator!=(Value rhs) const { return !(*this == rhs); }
733
734bool Sharding::operator==(const Sharding &rhs) const {
735 return equalSplitAxes(rhs) && equalHaloAndShardSizes(rhs);
736}
737
738bool Sharding::operator!=(const Sharding &rhs) const { return !(*this == rhs); }
739
740llvm::raw_ostream &mlir::shard::operator<<(llvm::raw_ostream &os,
741 const Sharding &sharding) {
742 os << "Sharding<grid=" << sharding.getGrid() << ", split_axes=[";
743 llvm::interleaveComma(sharding.getSplitAxes(), os, [&](GridAxesAttr axes) {
744 os << "[";
745 llvm::interleaveComma(axes.asArrayRef(), os);
746 os << "]";
747 });
748 os << "]";
749 if (!sharding.getStaticHaloSizes().empty()) {
750 os << ", halo_sizes=[";
751 llvm::interleaveComma(sharding.getStaticHaloSizes(), os);
752 os << "]";
753 }
754 if (!sharding.getStaticShardedDimsOffsets().empty()) {
755 os << ", sharded_dims_offsets=[";
756 llvm::interleaveComma(sharding.getStaticShardedDimsOffsets(), os);
757 os << "]";
758 }
759 os << ">";
760 return os;
761}
762
764
766 auto shardingOp = rhs.getDefiningOp<ShardingOp>();
767 assert(shardingOp && "expected sharding op");
768 auto splitAxes = shardingOp.getSplitAxes().getAxes();
769 // If splitAxes are empty, use "empty" constructor.
770 if (splitAxes.empty()) {
771 *this = Sharding(shardingOp.getGridAttr());
772 return;
773 }
774 *this =
775 get(shardingOp.getGridAttr(), splitAxes, shardingOp.getStaticHaloSizes(),
776 shardingOp.getStaticShardedDimsOffsets(),
777 SmallVector<Value>(shardingOp.getDynamicHaloSizes()),
778 SmallVector<Value>(shardingOp.getDynamicShardedDimsOffsets()));
779}
780
782 ArrayRef<GridAxesAttr> splitAxes,
783 ArrayRef<int64_t> staticHaloSizes,
784 ArrayRef<int64_t> staticShardedDimsOffsets,
785 ArrayRef<Value> dynamicHaloSizes,
786 ArrayRef<Value> dynamicShardedDimsOffsets) {
787 Sharding res(grid);
788 if (splitAxes.empty()) {
789 return res;
790 }
791
792 res.split_axes.resize(splitAxes.size());
793 for (auto [i, axis] : llvm::enumerate(splitAxes)) {
794 res.split_axes[i] = GridAxesAttr::get(grid.getContext(), axis.asArrayRef());
795 }
796
797 auto clone = [](const auto src, auto &dst) {
798 dst.resize(src.size());
799 llvm::copy(src, dst.begin());
800 };
801
802 clone(staticHaloSizes, res.static_halo_sizes);
803 clone(staticShardedDimsOffsets, res.static_sharded_dims_offsets);
804 clone(dynamicHaloSizes, res.dynamic_halo_sizes);
805 clone(dynamicShardedDimsOffsets, res.dynamic_sharded_dims_offsets);
806
807 return res;
808}
809
810//===----------------------------------------------------------------------===//
811// shard.shard_shape
812//===----------------------------------------------------------------------===//
813
814void ShardShapeOp::getAsmResultNames(
815 function_ref<void(Value, StringRef)> setNameFn) {
816 setNameFn(getResult()[0], "shard_shape");
817}
818
819void ShardShapeOp::build(::mlir::OpBuilder &odsBuilder,
820 ::mlir::OperationState &odsState,
822 ArrayRef<Value> dimsDyn, ::mlir::Value sharding,
823 ::mlir::ValueRange device) {
824 SmallVector<mlir::Type> resType(dims.size(), odsBuilder.getIndexType());
825 build(odsBuilder, odsState, resType, dims, dimsDyn, sharding,
826 SmallVector<int64_t>(device.size(), ShapedType::kDynamic), device);
827}
828
829//===----------------------------------------------------------------------===//
830// shard.shard op
831//===----------------------------------------------------------------------===//
832
833void ShardOp::getAsmResultNames(
834 function_ref<void(Value, StringRef)> setNameFn) {
835 setNameFn(getResult(), "sharding_annotated");
836}
837
838namespace {
839// Determine if the given ShardOp is a duplicate of another ShardOp
840// on the same value. This can happen if constant values are sharded.
841class FoldDuplicateShardOp final : public OpRewritePattern<ShardOp> {
842public:
843 using OpRewritePattern<ShardOp>::OpRewritePattern;
844
845 LogicalResult matchAndRewrite(ShardOp op, PatternRewriter &b) const override {
846 // Get the use-list of the value being sharded and check if it has more than
847 // one use.
848 Value value = op.getSrc();
849 if (value.hasOneUse() || value.getDefiningOp<ShardOp>()) {
850 return failure();
851 }
852
853 // Iterate through the uses of the value to find a duplicate ShardOp.
854 for (auto &use : value.getUses()) {
855 if (use.getOwner() != op.getOperation()) {
856 auto otherOp = dyn_cast<ShardOp>(use.getOwner());
857 // Only fold duplicates in the same block; isBeforeInBlock requires it.
858 if (!otherOp || otherOp->getBlock() != op->getBlock() ||
859 !otherOp->isBeforeInBlock(op)) {
860 return failure();
861 }
862 // Create a Sharding object for the current and the other ShardOp
863 // If the two are equal replace current op with the other op.
864 Sharding currentSharding(op.getSharding());
865 Sharding otherSharding(otherOp.getSharding());
866 if (currentSharding == otherSharding) {
867 b.replaceAllUsesWith(op.getResult(), otherOp.getResult());
868 b.eraseOp(op.getOperation());
869 } else {
870 // use the other sharding as input for op
871 b.modifyOpInPlace(
872 op, [&]() { op.getSrcMutable().assign(otherOp.getResult()); });
873 }
874 return success();
875 }
876 }
877
878 return failure();
879 }
880};
881} // namespace
882
883void ShardOp::getCanonicalizationPatterns(mlir::RewritePatternSet &results,
884 mlir::MLIRContext *context) {
885 results.add<FoldDuplicateShardOp>(context);
886}
887
888//===----------------------------------------------------------------------===//
889// shard.process_multi_index op
890//===----------------------------------------------------------------------===//
891
892LogicalResult
893ProcessMultiIndexOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
894 auto grid = ::getGridAndVerify(getOperation(), getGridAttr(), symbolTable);
895 if (failed(grid)) {
896 return failure();
897 }
898 if (failed(verifyGridAxes(getLoc(), getAxes(), grid.value()))) {
899 return failure();
900 }
901
902 size_t expectedResultsCount =
903 getAxes().empty() ? grid->getRank() : getAxes().size();
904 if (getResult().size() != expectedResultsCount) {
905 return emitError() << "Unexpected number of results " << getResult().size()
906 << ". Expected " << expectedResultsCount << ".";
907 }
908
909 return success();
910}
911
912void ProcessMultiIndexOp::build(OpBuilder &odsBuilder, OperationState &odsState,
913 GridOp grid) {
914 build(odsBuilder, odsState,
915 SmallVector<Type>(grid.getRank(), odsBuilder.getIndexType()),
916 grid.getSymName(), ArrayRef<GridAxis>());
917}
918
919void ProcessMultiIndexOp::build(OpBuilder &odsBuilder, OperationState &odsState,
920 StringRef grid, ArrayRef<GridAxis> axes) {
921 build(odsBuilder, odsState,
922 SmallVector<Type>(axes.size(), odsBuilder.getIndexType()), grid,
923 GridAxesAttr::get(odsBuilder.getContext(), axes));
924}
925
926void ProcessMultiIndexOp::getAsmResultNames(
927 function_ref<void(Value, StringRef)> setNameFn) {
928 setNameFn(getResults()[0], "proc_linear_idx");
929}
930
931//===----------------------------------------------------------------------===//
932// shard.process_linear_index op
933//===----------------------------------------------------------------------===//
934
935LogicalResult
936ProcessLinearIndexOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
937 auto grid = ::getGridAndVerify(getOperation(), getGridAttr(), symbolTable);
938 if (failed(grid)) {
939 return failure();
940 }
941 return success();
942}
943
944void ProcessLinearIndexOp::build(OpBuilder &odsBuilder,
945 OperationState &odsState, GridOp grid) {
946 build(odsBuilder, odsState, grid.getSymName());
947}
948
949void ProcessLinearIndexOp::getAsmResultNames(
950 function_ref<void(Value, StringRef)> setNameFn) {
951 setNameFn(getResult(), "proc_linear_idx");
952}
953
954//===----------------------------------------------------------------------===//
955// shard.neighbors_linear_indices op
956//===----------------------------------------------------------------------===//
957
958LogicalResult
959NeighborsLinearIndicesOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
960 auto grid = ::getGridAndVerify(getOperation(), getGridAttr(), symbolTable);
961 if (failed(grid)) {
962 return failure();
963 }
964 return success();
965}
966
967void NeighborsLinearIndicesOp::getAsmResultNames(
968 function_ref<void(Value, StringRef)> setNameFn) {
969 setNameFn(getNeighborDown(), "down_linear_idx");
970 setNameFn(getNeighborUp(), "up_linear_idx");
971}
972
973//===----------------------------------------------------------------------===//
974// collective communication ops
975//===----------------------------------------------------------------------===//
976
977namespace {
978
979template <typename Op>
980struct EmptyGridAxesCanonicalizationPattern : OpRewritePattern<Op> {
981 using OpRewritePattern<Op>::OpRewritePattern;
982 LogicalResult matchAndRewrite(Op op,
983 PatternRewriter &rewriter) const override {
984 auto gridAxes = op.getGridAxes();
985 if (!gridAxes.empty()) {
986 return failure();
987 }
988 if (op.getInput().getType() != op.getResult().getType()) {
989 return failure();
990 }
991
992 rewriter.replaceAllUsesWith(op.getResult(), op.getInput());
993 rewriter.eraseOp(op.getOperation());
994 return success();
995 }
996};
997
998} // namespace
999
1000static LogicalResult verifyInGroupDevice(Location loc, StringRef deviceName,
1001 ArrayRef<int64_t> device,
1002 Operation::operand_range deviceDynamic,
1003 ArrayRef<GridAxis> gridAxes,
1004 ArrayRef<int64_t> gridShape) {
1005 if (device.size() != gridAxes.size()) {
1006 return emitError(loc) << "In-group device \"" << deviceName
1007 << "\" has unexpected multi-index size "
1008 << device.size() << ". Expected " << gridAxes.size()
1009 << ".";
1010 }
1011
1012 for (size_t i = 0; i < device.size(); ++i) {
1013 if (ShapedType::isStatic(device[i]) &&
1014 ShapedType::isStatic(gridShape[gridAxes[i]]) &&
1015 gridShape[gridAxes[i]] <= device[i]) {
1016 return emitError(loc)
1017 << "Out of bounds coordinate " << i << " for in-group device \""
1018 << deviceName << "\"."
1019 << " Got " << device[i] << ", but expected value in the range [0, "
1020 << (gridShape[gridAxes[i]] - 1) << "].";
1021 }
1022 }
1023 return success();
1024}
1025
1027 int64_t expectedDimSize,
1028 int64_t resultDimSize,
1029 int64_t resultAxis) {
1030 if (ShapedType::isStatic(resultDimSize) && expectedDimSize != resultDimSize) {
1031 return emitError(loc) << "Dimension size mismatch for result axis "
1032 << resultAxis << ". Expected "
1033 << (ShapedType::isDynamic(expectedDimSize)
1034 ? Twine("dynamic")
1035 : Twine(expectedDimSize))
1036 << ", but got " << resultDimSize << ".";
1037 }
1038
1039 return success();
1040}
1041
1043 Value operand, Value result, int64_t gatherAxis,
1044 ArrayRef<GridAxis> gridAxes, ArrayRef<int64_t> gridShape) {
1045 auto resultRank = cast<ShapedType>(result.getType()).getRank();
1046 if (gatherAxis < 0 || gatherAxis >= resultRank) {
1047 return emitError(result.getLoc())
1048 << "Gather axis " << gatherAxis << " is out of bounds [0, "
1049 << resultRank << ").";
1050 }
1051
1052 ShapedType operandType = cast<ShapedType>(operand.getType());
1053 ShapedType resultType = cast<ShapedType>(result.getType());
1054 auto deviceGroupSize =
1055 DimensionSize(collectiveProcessGroupSize(gridAxes, gridShape));
1056 for (int64_t axis = 0; axis < operandType.getRank(); ++axis) {
1057 auto operandDimSize = DimensionSize(operandType.getDimSize(axis));
1058 auto resultDimSize = DimensionSize(resultType.getDimSize(axis));
1059 auto expectedResultDimSize =
1060 axis == gatherAxis ? deviceGroupSize * operandDimSize : operandDimSize;
1062 result.getLoc(), expectedResultDimSize, resultDimSize, axis))) {
1063 return failure();
1064 }
1065 }
1066 return success();
1067}
1068
1070 Value operand, Value result, int64_t splitAxis, int64_t concatAxis,
1071 ArrayRef<GridAxis> gridAxes, ArrayRef<int64_t> gridShape) {
1072 ShapedType operandType = cast<ShapedType>(operand.getType());
1073 ShapedType resultType = cast<ShapedType>(result.getType());
1074 auto operandRank = operandType.getRank();
1075 if (splitAxis < 0 || splitAxis >= operandRank) {
1076 return emitError(result.getLoc())
1077 << "split_axis " << splitAxis << " is out of bounds [0, "
1078 << operandRank << ").";
1079 }
1080 if (concatAxis < 0 || concatAxis >= operandRank) {
1081 return emitError(result.getLoc())
1082 << "concat_axis " << concatAxis << " is out of bounds [0, "
1083 << operandRank << ").";
1084 }
1085 for (int64_t axis = 0; axis < operandType.getRank(); ++axis) {
1086 if ((axis != splitAxis && axis != concatAxis) || splitAxis == concatAxis) {
1088 result.getLoc(), operandType.getDimSize(axis),
1089 resultType.getDimSize(axis), axis))) {
1090 return failure();
1091 }
1092 }
1093 }
1094
1095 if (splitAxis == concatAxis) {
1096 return success();
1097 }
1098
1099 auto deviceGroupSize =
1100 DimensionSize(collectiveProcessGroupSize(gridAxes, gridShape));
1101 auto operandConcatDimSize = DimensionSize(operandType.getDimSize(concatAxis));
1102 auto operandSplitDimSize = DimensionSize(operandType.getDimSize(splitAxis));
1103 DimensionSize expectedResultConcatDimSize =
1104 operandConcatDimSize * deviceGroupSize;
1105 DimensionSize expectedResultSplitDimSize =
1106 operandSplitDimSize / deviceGroupSize;
1107 if (!expectedResultSplitDimSize.isDynamic() &&
1108 int64_t(operandSplitDimSize) % int64_t(deviceGroupSize) != 0) {
1109 expectedResultSplitDimSize = DimensionSize::dynamic();
1110 }
1112 result.getLoc(), expectedResultConcatDimSize.value(),
1113 resultType.getDimSize(concatAxis), concatAxis))) {
1114 return failure();
1115 }
1117 result.getLoc(), expectedResultSplitDimSize.value(),
1118 resultType.getDimSize(splitAxis), splitAxis))) {
1119 return failure();
1120 }
1121
1122 return success();
1123}
1124
1126 Value operand, Value result, int64_t tensorAxis,
1127 StringRef tensorAxisAttrName, ArrayRef<GridAxis> gridAxes,
1128 ArrayRef<int64_t> gridShape) {
1129 ShapedType operandType = cast<ShapedType>(operand.getType());
1130 ShapedType resultType = cast<ShapedType>(result.getType());
1131 auto operandRank = operandType.getRank();
1132 if (tensorAxis < 0 || tensorAxis >= operandRank) {
1133 return emitError(result.getLoc())
1134 << tensorAxisAttrName << " " << tensorAxis
1135 << " is out of bounds [0, " << operandRank << ").";
1136 }
1137 for (int64_t axis = 0; axis < operandType.getRank(); ++axis) {
1138 if (axis != tensorAxis) {
1140 result.getLoc(), operandType.getDimSize(axis),
1141 resultType.getDimSize(axis), axis))) {
1142 return failure();
1143 }
1144 }
1145 }
1146
1147 auto deviceGroupSize =
1148 DimensionSize(collectiveProcessGroupSize(gridAxes, gridShape));
1149 auto operandScatterDimSize =
1150 DimensionSize(operandType.getDimSize(tensorAxis));
1151 if (!operandScatterDimSize.isDynamic() && !deviceGroupSize.isDynamic() &&
1152 int64_t(operandScatterDimSize) % int64_t(deviceGroupSize) != 0) {
1153 return emitError(result.getLoc())
1154 << "Operand dimension size " << int64_t(operandScatterDimSize)
1155 << " is not divisible by collective device group size "
1156 << int64_t(deviceGroupSize) << " for tensor axis " << tensorAxis
1157 << ".";
1158 }
1159 DimensionSize expectedResultTensorDimSize =
1160 operandScatterDimSize / deviceGroupSize;
1162 result.getLoc(), expectedResultTensorDimSize.value(),
1163 resultType.getDimSize(tensorAxis), tensorAxis))) {
1164 return failure();
1165 }
1166
1167 return success();
1168}
1169
1170static RankedTensorType sliceResultType(Type operandType, GridOp grid,
1171 ArrayRef<GridAxis> gridAxes,
1172 int64_t sliceAxis) {
1173 RankedTensorType operandRankedTensorType =
1174 cast<RankedTensorType>(operandType);
1175 DimensionSize operandSliceAxisSize =
1176 operandRankedTensorType.getShape()[sliceAxis];
1177 SmallVector<int64_t> resultShape =
1178 llvm::to_vector(operandRankedTensorType.getShape());
1179
1180 resultShape[sliceAxis] =
1181 operandSliceAxisSize /
1182 DimensionSize(collectiveProcessGroupSize(gridAxes, grid));
1183 return operandRankedTensorType.clone(resultShape);
1184}
1185
1186//===----------------------------------------------------------------------===//
1187// shard.all_gather op
1188//===----------------------------------------------------------------------===//
1189
1190LogicalResult
1191AllGatherOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1192 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1193 if (failed(grid)) {
1194 return failure();
1195 }
1196 auto gatherAxis = getGatherAxis().getSExtValue();
1197 return verifyGatherOperandAndResultShape(getOperand(), getResult(),
1198 gatherAxis, getGridAxes(),
1199 grid.value().getShape());
1200}
1201
1202void AllGatherOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1203 MLIRContext *context) {
1204 patterns.add<EmptyGridAxesCanonicalizationPattern<AllGatherOp>>(context);
1205}
1206
1207void AllGatherOp::getAsmResultNames(
1208 function_ref<void(Value, StringRef)> setNameFn) {
1209 setNameFn(getResult(), "all_gather");
1210}
1211
1212//===----------------------------------------------------------------------===//
1213// shard.all_reduce op
1214//===----------------------------------------------------------------------===//
1215
1216LogicalResult
1217AllReduceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1218 return getGridAndVerifyAxes(*this, symbolTable);
1219}
1220
1221void AllReduceOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1222 MLIRContext *context) {
1223 patterns.add<EmptyGridAxesCanonicalizationPattern<AllReduceOp>>(context);
1224}
1225
1226void AllReduceOp::build(OpBuilder &odsBuilder, OperationState &odsState,
1227 Value input, StringRef grid,
1228 ArrayRef<GridAxis> gridAxes, ReductionKind reduction) {
1229 build(odsBuilder, odsState, input.getType(), grid, gridAxes, input,
1230 reduction);
1231}
1232
1233void AllReduceOp::getAsmResultNames(
1234 function_ref<void(Value, StringRef)> setNameFn) {
1235 setNameFn(getResult(), "all_reduce");
1236}
1237
1238//===----------------------------------------------------------------------===//
1239// shard.all_slice op
1240//===----------------------------------------------------------------------===//
1241
1242LogicalResult AllSliceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1243 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1244 if (failed(grid)) {
1245 return failure();
1246 }
1248 getOperand(), getResult(), getSliceAxis().getSExtValue(), "slice_axis",
1249 getGridAxes(), grid.value().getShape());
1250}
1251
1252void AllSliceOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1253 MLIRContext *context) {
1254 patterns.add<EmptyGridAxesCanonicalizationPattern<AllSliceOp>>(context);
1255}
1256
1257void AllSliceOp::build(OpBuilder &odsBuilder, OperationState &odsState,
1258 Value input, GridOp grid, ArrayRef<GridAxis> gridAxes,
1259 int64_t sliceAxis) {
1260 Type resultType = sliceResultType(input.getType(), grid, gridAxes, sliceAxis);
1261 build(odsBuilder, odsState, resultType, input, grid.getSymName(), gridAxes,
1262 sliceAxis);
1263}
1264
1265void AllSliceOp::build(OpBuilder &odsBuilder, OperationState &odsState,
1266 Type resultType, Value input, StringRef grid,
1267 ArrayRef<GridAxis> gridAxes, int64_t sliceAxis) {
1268 build(odsBuilder, odsState, resultType, grid, gridAxes, input,
1269 APInt(sizeof(sliceAxis) * CHAR_BIT, sliceAxis));
1270}
1271
1272void AllSliceOp::getAsmResultNames(
1273 function_ref<void(Value, StringRef)> setNameFn) {
1274 setNameFn(getResult(), "all_slice");
1275}
1276
1277//===----------------------------------------------------------------------===//
1278// shard.all_to_all op
1279//===----------------------------------------------------------------------===//
1280
1281LogicalResult AllToAllOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1282 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1283 if (failed(grid)) {
1284 return failure();
1285 }
1286
1288 getOperand(), getResult(), getSplitAxis().getSExtValue(),
1289 getConcatAxis().getSExtValue(), getGridAxes(), grid.value().getShape());
1290}
1291
1292void AllToAllOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1293 MLIRContext *context) {
1294 patterns.add<EmptyGridAxesCanonicalizationPattern<AllToAllOp>>(context);
1295}
1296
1297void AllToAllOp::getAsmResultNames(
1298 function_ref<void(Value, StringRef)> setNameFn) {
1299 setNameFn(getResult(), "all_to_all");
1300}
1301
1302//===----------------------------------------------------------------------===//
1303// shard.broadcast op
1304//===----------------------------------------------------------------------===//
1305
1306LogicalResult
1307BroadcastOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1308 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1309 if (failed(grid)) {
1310 return failure();
1311 }
1312 if (failed(verifyInGroupDevice(getLoc(), getRootAttrName(), getRoot(),
1313 getRootDynamic(), getGridAxes(),
1314 grid.value().getShape()))) {
1315 return failure();
1316 }
1317
1318 return success();
1319}
1320
1321void BroadcastOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1322 MLIRContext *context) {
1323 patterns.add<EmptyGridAxesCanonicalizationPattern<BroadcastOp>>(context);
1324}
1325
1326void BroadcastOp::getAsmResultNames(
1327 function_ref<void(Value, StringRef)> setNameFn) {
1328 setNameFn(getResult(), "broadcast");
1329}
1330
1331//===----------------------------------------------------------------------===//
1332// shard.gather op
1333//===----------------------------------------------------------------------===//
1334
1335LogicalResult GatherOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1336 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1337 if (failed(grid)) {
1338 return failure();
1339 }
1340 if (failed(verifyInGroupDevice(getLoc(), getRootAttrName(), getRoot(),
1341 getRootDynamic(), getGridAxes(),
1342 grid.value().getShape()))) {
1343 return failure();
1344 }
1345
1346 auto gatherAxis = getGatherAxis().getSExtValue();
1347 return verifyGatherOperandAndResultShape(getInput(), getResult(), gatherAxis,
1348 getGridAxes(),
1349 grid.value().getShape());
1350}
1351
1352void GatherOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1353 MLIRContext *context) {
1354 patterns.add<EmptyGridAxesCanonicalizationPattern<GatherOp>>(context);
1355}
1356
1357void GatherOp::getAsmResultNames(
1358 function_ref<void(Value, StringRef)> setNameFn) {
1359 setNameFn(getResult(), "gather");
1360}
1361
1362//===----------------------------------------------------------------------===//
1363// shard.recv op
1364//===----------------------------------------------------------------------===//
1365
1366LogicalResult RecvOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1367 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1368 if (failed(grid)) {
1369 return failure();
1370 }
1371 if (getSource() &&
1372 failed(verifyInGroupDevice(getLoc(), getSourceAttrName(),
1373 getSource().value(), getSourceDynamic(),
1374 getGridAxes(), grid.value().getShape()))) {
1375 return failure();
1376 }
1377 return success();
1378}
1379
1380void RecvOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1381 MLIRContext *context) {
1382 patterns.add<EmptyGridAxesCanonicalizationPattern<RecvOp>>(context);
1383}
1384
1385void RecvOp::getAsmResultNames(function_ref<void(Value, StringRef)> setNameFn) {
1386 setNameFn(getResult(), "recv");
1387}
1388
1389//===----------------------------------------------------------------------===//
1390// shard.reduce op
1391//===----------------------------------------------------------------------===//
1392
1393LogicalResult ReduceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1394 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1395 if (failed(grid)) {
1396 return failure();
1397 }
1398 if (failed(verifyInGroupDevice(getLoc(), getRootAttrName(), getRoot(),
1399 getRootDynamic(), getGridAxes(),
1400 grid.value().getShape()))) {
1401 return failure();
1402 }
1403
1404 return success();
1405}
1406
1407void ReduceOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1408 MLIRContext *context) {
1409 patterns.add<EmptyGridAxesCanonicalizationPattern<ReduceOp>>(context);
1410}
1411
1412void ReduceOp::getAsmResultNames(
1413 function_ref<void(Value, StringRef)> setNameFn) {
1414 setNameFn(getResult(), "reduce");
1415}
1416
1417//===----------------------------------------------------------------------===//
1418// shard.reduce_scatter op
1419//===----------------------------------------------------------------------===//
1420
1421LogicalResult
1422ReduceScatterOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1423 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1424 if (failed(grid)) {
1425 return failure();
1426 }
1427
1429 getOperand(), getResult(), getScatterDim().getSExtValue(), "scatter_dim",
1430 getGridAxes(), grid.value().getShape());
1431}
1432
1433void ReduceScatterOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1434 MLIRContext *context) {
1435 patterns.add<EmptyGridAxesCanonicalizationPattern<ReduceScatterOp>>(context);
1436}
1437
1438void ReduceScatterOp::getAsmResultNames(
1439 function_ref<void(Value, StringRef)> setNameFn) {
1440 setNameFn(getResult(), "reduce_scatter");
1441}
1442
1443//===----------------------------------------------------------------------===//
1444// shard.scatter op
1445//===----------------------------------------------------------------------===//
1446
1447LogicalResult ScatterOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1448 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1449 if (failed(grid)) {
1450 return failure();
1451 }
1452 if (failed(verifyInGroupDevice(getLoc(), getRootAttrName(), getRoot(),
1453 getRootDynamic(), getGridAxes(),
1454 grid.value().getShape()))) {
1455 return failure();
1456 }
1457
1458 auto scatterDim = getScatterDim().getSExtValue();
1460 getInput(), getResult(), scatterDim, "scatter_dim", getGridAxes(),
1461 grid.value().getShape());
1462}
1463
1464void ScatterOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1465 MLIRContext *context) {
1466 patterns.add<EmptyGridAxesCanonicalizationPattern<ScatterOp>>(context);
1467}
1468
1469void ScatterOp::getAsmResultNames(
1470 function_ref<void(Value, StringRef)> setNameFn) {
1471 setNameFn(getResult(), "scatter");
1472}
1473
1474//===----------------------------------------------------------------------===//
1475// shard.send op
1476//===----------------------------------------------------------------------===//
1477
1478LogicalResult SendOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1479 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1480 if (failed(grid)) {
1481 return failure();
1482 }
1483 if (failed(verifyInGroupDevice(getLoc(), getDestinationAttrName(),
1484 getDestination(), getDestinationDynamic(),
1485 getGridAxes(), grid.value().getShape()))) {
1486 return failure();
1487 }
1488 return success();
1489}
1490
1491void SendOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1492 MLIRContext *context) {
1493 patterns.add<EmptyGridAxesCanonicalizationPattern<SendOp>>(context);
1494}
1495
1496void SendOp::getAsmResultNames(function_ref<void(Value, StringRef)> setNameFn) {
1497 setNameFn(getResult(), "send");
1498}
1499
1500//===----------------------------------------------------------------------===//
1501// shard.shift op
1502//===----------------------------------------------------------------------===//
1503
1504LogicalResult ShiftOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1505 auto grid = getGridAndVerifyAxes(*this, symbolTable);
1506 if (failed(grid)) {
1507 return failure();
1508 }
1509
1510 auto gridAxes = getGridAxes();
1511 auto shiftAxis = getShiftAxis().getZExtValue();
1512 if (!llvm::is_contained(gridAxes, shiftAxis)) {
1513 return emitError() << "Invalid shift axis " << shiftAxis
1514 << ". It must be one of the grouping grid axes.";
1515 }
1516
1517 return success();
1518}
1519
1520void ShiftOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1521 MLIRContext *context) {
1522 // TODO: remove op when offset is 0 or if it is a rotate with and
1523 // offset % shift_axis_grid_dim_size == 0.
1524}
1525
1526void ShiftOp::getAsmResultNames(
1527 function_ref<void(Value, StringRef)> setNameFn) {
1528 setNameFn(getResult(), "shift");
1529}
1530
1531//===----------------------------------------------------------------------===//
1532// shard.update_halo op
1533//===----------------------------------------------------------------------===//
1534
1535LogicalResult
1536UpdateHaloOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1537 auto grid = getGridAndVerify(getOperation(), getGridAttr(), symbolTable);
1538 if (failed(grid)) {
1539 return failure();
1540 }
1541
1542 return success();
1543}
1544
1545//===----------------------------------------------------------------------===//
1546// TableGen'd op method definitions
1547//===----------------------------------------------------------------------===//
1548
1549#define GET_OP_CLASSES
1550#include "mlir/Dialect/Shard/IR/ShardOps.cpp.inc"
1551
1552#define GET_ATTRDEF_CLASSES
1553#include "mlir/Dialect/Shard/IR/ShardAttributes.cpp.inc"
1554
1555#define GET_TYPEDEF_CLASSES
1556#include "mlir/Dialect/Shard/IR/ShardTypes.cpp.inc"
1557
1558#include "mlir/Dialect/Shard/IR/ShardEnums.cpp.inc"
return success()
static bool isLegalToInline(InlinerInterface &interface, Region *src, Region *insertRegion, bool shouldCloneInlinedRegion, IRMapping &valueMapping)
Utility to check that all of the operations within 'src' can be inlined.
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
static LogicalResult verifyGatherOperandAndResultShape(Value operand, Value result, int64_t gatherAxis, ArrayRef< GridAxis > gridAxes, ArrayRef< int64_t > gridShape)
static LogicalResult verifyDimensionCompatibility(Location loc, int64_t expectedDimSize, int64_t resultDimSize, int64_t resultAxis)
static FailureOr< GridOp > getGridAndVerify(Operation *op, FlatSymbolRefAttr gridSymbol, SymbolTableCollection &symbolTable)
Definition ShardOps.cpp:132
static LogicalResult verifyGridAxes(Location loc, ArrayRef< GridAxis > axes, GridOp grid)
Definition ShardOps.cpp:161
static FailureOr< GridOp > getGridAndVerifyAxes(Op op, SymbolTableCollection &symbolTable)
Definition ShardOps.cpp:184
static LogicalResult verifyAllToAllOperandAndResultShape(Value operand, Value result, int64_t splitAxis, int64_t concatAxis, ArrayRef< GridAxis > gridAxes, ArrayRef< int64_t > gridShape)
static void shardShape(const InShape &inShape, const GridShape &gridShape, const SplitAxes &splitAxes, OutShape &outShape, ArrayRef< int64_t > shardedDimsOffsets={}, ArrayRef< int64_t > haloSizes={})
Definition ShardOps.cpp:198
static LogicalResult verifyScatterOrSliceOperandAndResultShape(Value operand, Value result, int64_t tensorAxis, StringRef tensorAxisAttrName, ArrayRef< GridAxis > gridAxes, ArrayRef< int64_t > gridShape)
static LogicalResult verifyInGroupDevice(Location loc, StringRef deviceName, ArrayRef< int64_t > device, Operation::operand_range deviceDynamic, ArrayRef< GridAxis > gridAxes, ArrayRef< int64_t > gridShape)
static RankedTensorType sliceResultType(Type operandType, GridOp grid, ArrayRef< GridAxis > gridAxes, int64_t sliceAxis)
static bool isUnique(It begin, It end)
Definition ShardOps.cpp:145
static void maybeInsertTargetShardingAnnotationImpl(Sharding sharding, Value &operandValue, Operation *operandOp, OpBuilder &builder, ShardOp &newShardOp)
Definition ShardOps.cpp:283
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
Attributes are known-constant values of operations.
Definition Attributes.h:25
MLIRContext * getContext() const
Definition Builders.h:56
IndexType getIndexType()
Definition Builders.cpp:59
A symbol reference with a reference path containing a single element.
static FlatSymbolRefAttr get(StringAttr value)
Construct a symbol reference for the given value name.
StringRef getValue() const
Returns the name of the held symbol reference.
This is a utility class for mapping one set of IR entities to another.
Definition IRMapping.h:26
IRValueT get() const
Return the current value being used by this operand.
This class coordinates rewriting a piece of IR outside of a pattern rewrite, providing a way to keep ...
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
RAII guard to reset the insertion point of the builder when destroyed.
Definition Builders.h:351
This class helps build Operations.
Definition Builders.h:210
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
Definition Builders.h:401
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
Definition Builders.h:424
This class represents an operand of an operation.
Definition Value.h:256
This is a value defined by a result of an operation.
Definition Value.h:456
Location getLoc()
The source location the operation was defined or derived from.
This class provides the API for a sub-set of ops that are known to be constant-like.
This provides public APIs that all operations should have.
Operation * getOperation()
Inherit getOperation from OpState.
Operation is the basic unit of execution within MLIR.
Definition Operation.h:87
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
Definition Operation.h:803
OperandRange operand_range
Definition Operation.h:398
InFlightDiagnostic emitError(const Twine &message={})
Emit an error about fatal conditions with this operation, reporting up to any diagnostic handlers tha...
This class contains a list of basic blocks and a link to the parent operation it is attached to.
Definition Region.h:26
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 eraseOp(Operation *op)
This method erases an operation that is known to have no uses.
virtual void replaceAllUsesWith(Value from, Value to)
Find uses of from and replace them with to.
virtual bool replaceUsesWithIf(Value from, Value to, function_ref< bool(OpOperand &)> functor, bool *allUsesReplaced=nullptr)
Find uses of from and replace them with to if the functor returns true.
This class represents a collection of SymbolTables.
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
This class provides an abstraction over the different types of ranges over Values.
Definition ValueRange.h:392
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
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
Definition Value.h:188
bool replaceUsesWithIf(Value newValue, function_ref< bool(OpOperand &)> shouldReplace)
Replace all uses of 'this' value with 'newValue' if the given callback returns true.
Definition Value.cpp:91
bool hasOneUse() const
Returns true if this value has exactly one use.
Definition Value.h:197
Location getLoc() const
Return the location of this value.
Definition Value.cpp:24
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
Definition Value.cpp:18
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int16_t > content)
Operation * getOwner() const
Return the owner of this operand.
Definition UseDefLists.h:38
ArrayRef< Value > getDynamicShardedDimsOffsets() const
Definition ShardOps.h:65
bool operator!=(Value rhs) const
Definition ShardOps.cpp:732
bool equalShardSizes(const Sharding &rhs) const
Definition ShardOps.cpp:700
Sharding(::mlir::FlatSymbolRefAttr grid_=nullptr)
Definition ShardOps.cpp:763
static Sharding get(::mlir::FlatSymbolRefAttr grid_, ArrayRef< GridAxesAttr > split_axes_, ArrayRef< int64_t > static_halo_sizes_={}, ArrayRef< int64_t > static_sharded_dims_offsets_={}, ArrayRef< Value > dynamic_halo_sizes_={}, ArrayRef< Value > dynamic_sharded_dims_offsets_={})
Definition ShardOps.cpp:781
bool equalSplitAxes(const Sharding &rhs) const
Definition ShardOps.cpp:677
ArrayRef< int64_t > getStaticHaloSizes() const
Definition ShardOps.h:60
::mlir::FlatSymbolRefAttr getGridAttr() const
Definition ShardOps.h:57
::llvm::StringRef getGrid() const
Definition ShardOps.h:58
bool equalHaloAndShardSizes(const Sharding &rhs) const
Definition ShardOps.cpp:696
bool operator==(Value rhs) const
Definition ShardOps.cpp:728
ArrayRef< Value > getDynamicHaloSizes() const
Definition ShardOps.h:64
ArrayRef< int64_t > getStaticShardedDimsOffsets() const
Definition ShardOps.h:61
ArrayRef< GridAxesAttr > getSplitAxes() const
Definition ShardOps.h:59
bool equalHaloSizes(const Sharding &rhs) const
Definition ShardOps.cpp:716
NestedPattern Op(FilterFunctionType filter=defaultFilterFunction)
shard::Sharding Sharding
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:886
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const Sharding &sharding)
Definition ShardOps.cpp:740
ShapedType shardShapedType(ShapedType shape, GridOp grid, Sharding sharding)
Definition ShardOps.cpp:265
void maybeInsertTargetShardingAnnotation(Sharding sharding, OpResult result, OpBuilder &builder)
Definition ShardOps.cpp:322
DenseI16ArrayAttr GridAxesAttr
Definition ShardOps.h:24
shard::GridOp getGridOrNull(Operation *op, FlatSymbolRefAttr gridSymbol, SymbolTableCollection &symbolTableCollection)
Definition ShardOps.h:119
bool isFullReplication(Sharding sharding)
Definition ShardOps.h:112
int16_t GridAxis
Definition ShardOps.h:23
void maybeInsertSourceShardingAnnotation(Sharding sharding, OpOperand &operand, OpBuilder &builder)
Definition ShardOps.cpp:336
int64_t shardDimension(int64_t dimSize, int64_t shardCount)
Definition ShardOps.h:174
Type shardType(Type type, GridOp grid, Sharding sharding)
Definition ShardOps.cpp:275
SmallVector< Value > getMixedAsValues(OpBuilder b, const Location &loc, llvm::ArrayRef< int64_t > statics, ValueRange dynamics, Type type=Type())
Converts a vector of OpFoldResults (ints) into vector of Values of the provided type.
Definition ShardOps.cpp:75
int64_t collectiveProcessGroupSize(GridAxesRange &&gridAxes, GridShapeRange &&gridShape)
Definition ShardOps.h:152
Include the generated interface declarations.
SmallVector< OpFoldResult > getMixedValues(ArrayRef< int64_t > staticValues, ValueRange dynamicValues, MLIRContext *context)
Return a vector of OpFoldResults with the same size a staticValues, but all elements for which Shaped...
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
InFlightDiagnostic emitError(Location loc)
Utility method to emit an error message using this location.
constexpr NonFloatComplex< T > operator/(const NonFloatComplex< T > &x, const NonFloatComplex< T > &y)
Definition Complex.h:188
AffineExpr operator*(int64_t val, AffineExpr expr)
Definition AffineExpr.h:254
void dispatchIndexOpFoldResults(ArrayRef< OpFoldResult > ofrs, SmallVectorImpl< Value > &dynamicVec, SmallVectorImpl< int64_t > &staticVec)
Helper function to dispatch multiple OpFoldResults according to the behavior of dispatchIndexOpFoldRe...
Operation * clone(OpBuilder &b, Operation *op, TypeRange newResultTypes, ValueRange newOperands)
llvm::function_ref< Fn > function_ref
Definition LLVM.h:155
std::pair< SmallVector< int64_t >, SmallVector< Value > > decomposeMixedValues(ArrayRef< OpFoldResult > mixedValues)
Decompose a vector of mixed static or dynamic values into the corresponding pair of arrays.
LogicalResult foldDynamicIndexList(SmallVectorImpl< OpFoldResult > &ofrs, bool onlyNonNegative=false, bool onlyNonZero=false)
Returns "success" when any of the elements in ofrs is a constant value.
OpRewritePattern is a wrapper around RewritePattern that allows for matching and rewriting against an...
This represents an operation in an abstracted form, suitable for use with the builder APIs.