27#include "llvm/ADT/ArrayRef.h"
28#include "llvm/ADT/STLExtras.h"
29#include "llvm/ADT/SmallSet.h"
30#include "llvm/ADT/SmallVector.h"
38#define DEBUG_TYPE "shard-ops"
43#include "mlir/Dialect/Shard/IR/ShardDialect.cpp.inc"
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); }
60static DimensionSize
operator/(DimensionSize lhs, DimensionSize rhs) {
61 if (lhs.isDynamic() || rhs.isDynamic()) {
62 return DimensionSize::dynamic();
64 return lhs.value() / rhs.value();
67static DimensionSize
operator*(DimensionSize lhs, DimensionSize rhs) {
68 if (lhs.isDynamic() || rhs.isDynamic()) {
69 return DimensionSize::dynamic();
71 return lhs.value() * rhs.value();
79 auto dyn = dynamics.begin();
80 Type i64 =
b.getI64Type();
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++));
89 TypedAttr val = type == i64 ?
b.getI64IntegerAttr(s) :
b.getIndexAttr(s);
90 values.emplace_back(arith::ConstantOp::create(
b, loc, type, val));
101struct ShardInlinerinterface :
public DialectInlinerInterface {
102 using DialectInlinerInterface::DialectInlinerInterface;
110 bool isLegalToInline(Operation *, Region *,
bool, IRMapping &)
const final {
120void ShardDialect::initialize() { addInterface<ShardInlinerinterface>(); }
125 return arith::ConstantOp::materialize(builder, value, type, loc);
135 shard::GridOp grid =
getGridOrNull(op, gridSymbol, symbolTable);
137 return op->
emitError() <<
"Undefined required grid symbol \""
144template <
typename It>
149 It next = std::next(begin);
153 for (; next != end; ++next, ++begin) {
154 if (*begin == *next) {
165 if (!
isUnique(sorted.begin(), sorted.end())) {
166 return emitError(loc) <<
"Grid axes contains duplicate elements.";
170 for (
auto axis : axes) {
171 if (axis >= rank || axis < 0) {
173 <<
"0-based grid axis index " << axis
174 <<
" is out of bounds. The referenced grid \"" << grid.getSymName()
175 <<
"\" is of rank " << rank <<
".";
182template <
typename Op>
183static FailureOr<GridOp>
196template <
typename InShape,
typename GridShape,
typename SplitAxes,
198static void shardShape(
const InShape &inShape,
const GridShape &gridShape,
199 const SplitAxes &splitAxes, OutShape &outShape,
203 if (inShape.empty()) {
204 assert(outShape.empty());
208 std::copy(llvm::adl_begin(inShape), llvm::adl_end(inShape),
209 llvm::adl_begin(outShape));
211 if (!shardedDimsOffsets.empty()) {
212 auto isDynShape = ShapedType::isDynamicShape(gridShape);
214 for (
auto [tensorAxis, innerSplitAxes] : llvm::enumerate(splitAxes)) {
215 if (!innerSplitAxes.empty()) {
216 auto sz = shardedDimsOffsets[pos];
217 bool same = !isDynShape;
222 uint64_t numShards = 0;
223 for (
auto i : innerSplitAxes.asArrayRef()) {
224 numShards += gridShape[i];
226 for (
size_t i = 1; i < numShards; ++i) {
227 if (shardedDimsOffsets[pos + i] - shardedDimsOffsets[pos + i - 1] !=
233 pos += numShards + 1;
235 outShape[tensorAxis] = same ? sz : ShapedType::kDynamic;
239 for (
auto [tensorAxis, innerSplitAxes] : llvm::enumerate(splitAxes)) {
245 if (!haloSizes.empty()) {
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];
257 outShape[tensorAxis] = ShapedType::kDynamic;
267 using Dim = std::decay_t<
decltype(
shape.getDimSize(0))>;
272 return shape.clone(resShapeArr);
276 RankedTensorType rankedTensorType = dyn_cast<RankedTensorType>(type);
277 if (rankedTensorType && !rankedTensorType.getShape().empty()) {
287 ShardOp &newShardOp) {
290 ShardOp shardOp = dyn_cast<ShardOp>(operandOp);
291 if (shardOp && sharding == shardOp.getSharding() &&
292 !shardOp.getAnnotateForUsers()) {
295 newShardOp = shardOp;
302 ShardingOp::create(builder, operandValue.
getLoc(), sharding);
303 newShardOp = ShardOp::create(builder, operandValue.
getLoc(), operandValue,
308 newShardOp, [operandOp, operandValue](
OpOperand &use) {
309 return use.
getOwner() == operandOp && use.
get() == operandValue;
312 if (!shardOp || shardOp.getAnnotateForUsers()) {
316 auto newShardOp2 = ShardOp::create(builder, operandValue.
getLoc(), newShardOp,
317 newShardOp.getSharding(),
319 newShardOp.getResult().replaceAllUsesExcept(newShardOp2, newShardOp2);
327 for (
auto &use :
result.getUses()) {
328 uses.emplace_back(use.get(), use.getOwner());
330 for (
auto &[operandValue, operandOp] : uses) {
332 builder, newShardOp);
342 bool isBlockArg = !operandSrcOp;
344 [[maybe_unused]]
auto opType =
345 dyn_cast<mlir::RankedTensorType>(operandValue.
getType());
348 if (!isa<RankedTensorType>(operandValue.
getType()) && operandSrcOp &&
354 ShardOp shardOp = dyn_cast_or_null<ShardOp>(operandSrcOp);
356 if (shardOp && sharding == shardOp.getSharding() &&
357 shardOp.getAnnotateForUsers()) {
364 ShardingOp::create(builder, operand.
get().
getLoc(), sharding);
366 ShardOp::create(builder, operandValue.
getLoc(), operandValue, shardingOp,
370 operandValue, newShardOp, [operandOp, operandValue](
OpOperand &use) {
371 return use.
getOwner() == operandOp && use.
get() == operandValue;
374 if (isBlockArg || !shardOp || !shardOp.getAnnotateForUsers()) {
380 auto newPreceedingShardOp =
381 ShardOp::create(builder, operandValue.
getLoc(), operandValue, shardingOp,
384 newShardOp.getSrc(), newPreceedingShardOp, [&newShardOp](
OpOperand &use) {
385 return use.getOwner() == newShardOp.getOperation();
393LogicalResult GridOp::verify() {
397 return emitOpError(
"rank of grid is expected to be a positive integer");
400 if (dimSize < 0 && ShapedType::isStatic(dimSize))
401 return emitOpError(
"dimension size of a grid is expected to be "
402 "non-negative or dynamic");
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 <<
".";
439 build(odsBuilder, odsState,
447 assert(!axes.empty());
448 build(odsBuilder, odsState,
453void GridShapeOp::getAsmResultNames(
455 setNameFn(getResults()[0],
"grid_shape");
467 b, odsState, grid, GridAxesArrayAttr::get(
b.getContext(), splitAxes),
477 GridAxesArrayAttr::get(
b.getContext(), splitAxes),
483void ShardingOp::build(
493 b, odsState, grid, GridAxesArrayAttr::get(
b.getContext(), splitAxes),
501 build(
b, odsState, ShardingType::get(
b.getContext()), from.
getGridAttr(),
513LogicalResult ShardingOp::verify() {
514 llvm::SmallSet<GridAxis, 4> visitedAxes;
519 return emitError() <<
"grid axis is expected to be non-negative";
520 if (!visitedAxes.insert(axis).second)
521 return emitError() <<
"grid axis duplicated";
526 for (
auto subAxes : getSplitAxes().getAxes()) {
528 if (
failed(checkGridAxis(subAxesArray)))
532 if (!getStaticHaloSizes().empty() && !getStaticShardedDimsOffsets().empty()) {
533 return emitOpError(
"halo sizes and shard offsets are mutually exclusive");
536 if (!getStaticHaloSizes().empty()) {
537 auto numSplitAxes = getSplitAxes().getAxes().size();
538 for (
auto splitAxis : getSplitAxes().getAxes()) {
539 if (splitAxis.empty()) {
543 if (getStaticHaloSizes().size() != numSplitAxes * 2) {
544 return emitError() <<
"halo sizes must be specified for all split axes.";
551void ShardingOp::getAsmResultNames(
553 setNameFn(getResult(),
"sharding");
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.";
567 auto shardedDimsOffsets = getStaticShardedDimsOffsets();
568 if (!shardedDimsOffsets.empty()) {
569 auto gridShape = grid.value().getShape();
570 assert(ShapedType::isStaticShape(gridShape));
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];
578 for (
int64_t i = 0; i <= numShards; ++i) {
579 if (shardedDimsOffsets.size() <= pos + i) {
580 return emitError() <<
"sharded dims offsets has wrong size.";
582 if (ShapedType::isStatic(shardedDimsOffsets[pos + i])) {
583 if (shardedDimsOffsets[pos + i] < off) {
585 <<
"sharded dims offsets must be non-decreasing.";
587 off = shardedDimsOffsets[pos + i];
590 pos += numShards + 1;
605 using OpRewritePattern<ShardingOp>::OpRewritePattern;
607 LogicalResult matchAndRewrite(ShardingOp op,
608 PatternRewriter &
b)
const override {
612 op.getDynamicShardedDimsOffsets(),
b);
619 auto staticHalos = decomposedHalos.first;
620 auto dynamicHalos = decomposedHalos.second;
622 auto staticOffs = decomposedOffs.first;
623 auto dynamicOffs = decomposedOffs.second;
625 if (dynamicHalos.empty() && !staticHalos.empty()) {
626 if (staticHalos[0] == 0 && llvm::all_equal(staticHalos)) {
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) {
657 b.modifyOpInPlace(op, [&]() {
658 op.setStaticHaloSizes(staticHalos);
659 op.getDynamicHaloSizesMutable().assign(dynamicHalos);
660 op.setStaticShardedDimsOffsets(staticOffs);
661 op.getDynamicShardedDimsOffsetsMutable().assign(dynamicOffs);
670 results.
add<NormalizeSharding>(context);
678 if (
getGrid() != rhs.getGrid()) {
682 auto minSize = std::min(
getSplitAxes().size(), rhs.getSplitAxes().size());
683 if (!llvm::equal(llvm::make_range(
getSplitAxes().begin(),
685 llvm::make_range(rhs.getSplitAxes().begin(),
686 rhs.getSplitAxes().begin() + minSize))) {
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));
701 if (rhs.getStaticShardedDimsOffsets().size() !=
704 rhs.getStaticShardedDimsOffsets())) {
707 if (rhs.getDynamicShardedDimsOffsets().size() !=
710 rhs.getDynamicShardedDimsOffsets())) {
742 os <<
"Sharding<grid=" << sharding.
getGrid() <<
", split_axes=[";
745 llvm::interleaveComma(axes.asArrayRef(), os);
750 os <<
", halo_sizes=[";
755 os <<
", sharded_dims_offsets=[";
766 auto shardingOp = rhs.getDefiningOp<ShardingOp>();
767 assert(shardingOp &&
"expected sharding op");
768 auto splitAxes = shardingOp.getSplitAxes().getAxes();
770 if (splitAxes.empty()) {
771 *
this =
Sharding(shardingOp.getGridAttr());
775 get(shardingOp.getGridAttr(), splitAxes, shardingOp.getStaticHaloSizes(),
776 shardingOp.getStaticShardedDimsOffsets(),
788 if (splitAxes.empty()) {
792 res.split_axes.resize(splitAxes.size());
793 for (
auto [i, axis] : llvm::enumerate(splitAxes)) {
797 auto clone = [](
const auto src,
auto &dst) {
798 dst.resize(src.size());
799 llvm::copy(src, dst.begin());
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);
814void ShardShapeOp::getAsmResultNames(
816 setNameFn(getResult()[0],
"shard_shape");
825 build(odsBuilder, odsState, resType, dims, dimsDyn, sharding,
833void ShardOp::getAsmResultNames(
835 setNameFn(getResult(),
"sharding_annotated");
841class FoldDuplicateShardOp final :
public OpRewritePattern<ShardOp> {
843 using OpRewritePattern<ShardOp>::OpRewritePattern;
845 LogicalResult matchAndRewrite(ShardOp op, PatternRewriter &
b)
const override {
848 Value value = op.getSrc();
854 for (
auto &use : value.
getUses()) {
855 if (use.getOwner() != op.getOperation()) {
856 auto otherOp = dyn_cast<ShardOp>(use.getOwner());
858 if (!otherOp || otherOp->getBlock() != op->getBlock() ||
859 !otherOp->isBeforeInBlock(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());
872 op, [&]() { op.getSrcMutable().assign(otherOp.getResult()); });
883void ShardOp::getCanonicalizationPatterns(mlir::RewritePatternSet &results,
884 mlir::MLIRContext *context) {
885 results.
add<FoldDuplicateShardOp>(context);
893ProcessMultiIndexOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
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 <<
".";
912void ProcessMultiIndexOp::build(OpBuilder &odsBuilder, OperationState &odsState,
914 build(odsBuilder, odsState,
915 SmallVector<Type>(grid.getRank(), odsBuilder.
getIndexType()),
916 grid.getSymName(), ArrayRef<GridAxis>());
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,
926void ProcessMultiIndexOp::getAsmResultNames(
928 setNameFn(getResults()[0],
"proc_linear_idx");
936ProcessLinearIndexOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
944void ProcessLinearIndexOp::build(OpBuilder &odsBuilder,
945 OperationState &odsState, GridOp grid) {
946 build(odsBuilder, odsState, grid.getSymName());
949void ProcessLinearIndexOp::getAsmResultNames(
951 setNameFn(getResult(),
"proc_linear_idx");
959NeighborsLinearIndicesOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
967void NeighborsLinearIndicesOp::getAsmResultNames(
969 setNameFn(getNeighborDown(),
"down_linear_idx");
970 setNameFn(getNeighborUp(),
"up_linear_idx");
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()) {
988 if (op.getInput().getType() != op.getResult().getType()) {
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()
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]) {
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) <<
"].";
1030 if (ShapedType::isStatic(resultDimSize) && expectedDimSize != resultDimSize) {
1031 return emitError(loc) <<
"Dimension size mismatch for result axis "
1032 << resultAxis <<
". Expected "
1033 << (ShapedType::isDynamic(expectedDimSize)
1035 : Twine(expectedDimSize))
1036 <<
", but got " << resultDimSize <<
".";
1045 auto resultRank = cast<ShapedType>(
result.getType()).getRank();
1046 if (gatherAxis < 0 || gatherAxis >= resultRank) {
1048 <<
"Gather axis " << gatherAxis <<
" is out of bounds [0, "
1049 << resultRank <<
").";
1052 ShapedType operandType = cast<ShapedType>(operand.
getType());
1053 ShapedType resultType = cast<ShapedType>(
result.getType());
1054 auto deviceGroupSize =
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))) {
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) {
1077 <<
"split_axis " << splitAxis <<
" is out of bounds [0, "
1078 << operandRank <<
").";
1080 if (concatAxis < 0 || concatAxis >= operandRank) {
1082 <<
"concat_axis " << concatAxis <<
" is out of bounds [0, "
1083 << operandRank <<
").";
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))) {
1095 if (splitAxis == concatAxis) {
1099 auto deviceGroupSize =
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() &&
1109 expectedResultSplitDimSize = DimensionSize::dynamic();
1112 result.getLoc(), expectedResultConcatDimSize.value(),
1113 resultType.getDimSize(concatAxis), concatAxis))) {
1117 result.getLoc(), expectedResultSplitDimSize.value(),
1118 resultType.getDimSize(splitAxis), splitAxis))) {
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) {
1134 << tensorAxisAttrName <<
" " << tensorAxis
1135 <<
" is out of bounds [0, " << operandRank <<
").";
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))) {
1147 auto deviceGroupSize =
1149 auto operandScatterDimSize =
1150 DimensionSize(operandType.getDimSize(tensorAxis));
1151 if (!operandScatterDimSize.isDynamic() && !deviceGroupSize.isDynamic() &&
1152 int64_t(operandScatterDimSize) %
int64_t(deviceGroupSize) != 0) {
1154 <<
"Operand dimension size " <<
int64_t(operandScatterDimSize)
1155 <<
" is not divisible by collective device group size "
1156 <<
int64_t(deviceGroupSize) <<
" for tensor axis " << tensorAxis
1159 DimensionSize expectedResultTensorDimSize =
1160 operandScatterDimSize / deviceGroupSize;
1162 result.getLoc(), expectedResultTensorDimSize.value(),
1163 resultType.getDimSize(tensorAxis), tensorAxis))) {
1173 RankedTensorType operandRankedTensorType =
1174 cast<RankedTensorType>(operandType);
1175 DimensionSize operandSliceAxisSize =
1176 operandRankedTensorType.getShape()[sliceAxis];
1178 llvm::to_vector(operandRankedTensorType.getShape());
1180 resultShape[sliceAxis] =
1181 operandSliceAxisSize /
1183 return operandRankedTensorType.clone(resultShape);
1191AllGatherOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1196 auto gatherAxis = getGatherAxis().getSExtValue();
1198 gatherAxis, getGridAxes(),
1199 grid.value().getShape());
1202void AllGatherOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1203 MLIRContext *context) {
1204 patterns.
add<EmptyGridAxesCanonicalizationPattern<AllGatherOp>>(context);
1207void AllGatherOp::getAsmResultNames(
1209 setNameFn(getResult(),
"all_gather");
1217AllReduceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1221void AllReduceOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1222 MLIRContext *context) {
1223 patterns.
add<EmptyGridAxesCanonicalizationPattern<AllReduceOp>>(context);
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,
1233void AllReduceOp::getAsmResultNames(
1235 setNameFn(getResult(),
"all_reduce");
1242LogicalResult AllSliceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1248 getOperand(), getResult(), getSliceAxis().getSExtValue(),
"slice_axis",
1249 getGridAxes(), grid.value().getShape());
1252void AllSliceOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1253 MLIRContext *context) {
1254 patterns.
add<EmptyGridAxesCanonicalizationPattern<AllSliceOp>>(context);
1257void AllSliceOp::build(OpBuilder &odsBuilder, OperationState &odsState,
1258 Value input, GridOp grid, ArrayRef<GridAxis> gridAxes,
1259 int64_t sliceAxis) {
1261 build(odsBuilder, odsState, resultType, input, grid.getSymName(), gridAxes,
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));
1272void AllSliceOp::getAsmResultNames(
1274 setNameFn(getResult(),
"all_slice");
1281LogicalResult AllToAllOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1288 getOperand(), getResult(), getSplitAxis().getSExtValue(),
1289 getConcatAxis().getSExtValue(), getGridAxes(), grid.value().getShape());
1292void AllToAllOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1293 MLIRContext *context) {
1294 patterns.
add<EmptyGridAxesCanonicalizationPattern<AllToAllOp>>(context);
1297void AllToAllOp::getAsmResultNames(
1299 setNameFn(getResult(),
"all_to_all");
1307BroadcastOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1313 getRootDynamic(), getGridAxes(),
1314 grid.value().getShape()))) {
1321void BroadcastOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1322 MLIRContext *context) {
1323 patterns.
add<EmptyGridAxesCanonicalizationPattern<BroadcastOp>>(context);
1326void BroadcastOp::getAsmResultNames(
1328 setNameFn(getResult(),
"broadcast");
1335LogicalResult GatherOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1341 getRootDynamic(), getGridAxes(),
1342 grid.value().getShape()))) {
1346 auto gatherAxis = getGatherAxis().getSExtValue();
1349 grid.value().getShape());
1352void GatherOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1353 MLIRContext *context) {
1354 patterns.
add<EmptyGridAxesCanonicalizationPattern<GatherOp>>(context);
1357void GatherOp::getAsmResultNames(
1359 setNameFn(getResult(),
"gather");
1366LogicalResult RecvOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1373 getSource().value(), getSourceDynamic(),
1374 getGridAxes(), grid.value().getShape()))) {
1380void RecvOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1381 MLIRContext *context) {
1382 patterns.
add<EmptyGridAxesCanonicalizationPattern<RecvOp>>(context);
1385void RecvOp::getAsmResultNames(
function_ref<
void(Value, StringRef)> setNameFn) {
1386 setNameFn(getResult(),
"recv");
1393LogicalResult ReduceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1399 getRootDynamic(), getGridAxes(),
1400 grid.value().getShape()))) {
1407void ReduceOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1408 MLIRContext *context) {
1409 patterns.
add<EmptyGridAxesCanonicalizationPattern<ReduceOp>>(context);
1412void ReduceOp::getAsmResultNames(
1414 setNameFn(getResult(),
"reduce");
1422ReduceScatterOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1429 getOperand(), getResult(), getScatterDim().getSExtValue(),
"scatter_dim",
1430 getGridAxes(), grid.value().getShape());
1433void ReduceScatterOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1434 MLIRContext *context) {
1435 patterns.
add<EmptyGridAxesCanonicalizationPattern<ReduceScatterOp>>(context);
1438void ReduceScatterOp::getAsmResultNames(
1440 setNameFn(getResult(),
"reduce_scatter");
1447LogicalResult ScatterOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1453 getRootDynamic(), getGridAxes(),
1454 grid.value().getShape()))) {
1458 auto scatterDim = getScatterDim().getSExtValue();
1460 getInput(), getResult(), scatterDim,
"scatter_dim", getGridAxes(),
1461 grid.value().getShape());
1464void ScatterOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1465 MLIRContext *context) {
1466 patterns.
add<EmptyGridAxesCanonicalizationPattern<ScatterOp>>(context);
1469void ScatterOp::getAsmResultNames(
1471 setNameFn(getResult(),
"scatter");
1478LogicalResult SendOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1484 getDestination(), getDestinationDynamic(),
1485 getGridAxes(), grid.value().getShape()))) {
1491void SendOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1492 MLIRContext *context) {
1493 patterns.
add<EmptyGridAxesCanonicalizationPattern<SendOp>>(context);
1496void SendOp::getAsmResultNames(
function_ref<
void(Value, StringRef)> setNameFn) {
1497 setNameFn(getResult(),
"send");
1504LogicalResult ShiftOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
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.";
1520void ShiftOp::getCanonicalizationPatterns(RewritePatternSet &patterns,
1521 MLIRContext *context) {
1526void ShiftOp::getAsmResultNames(
1528 setNameFn(getResult(),
"shift");
1536UpdateHaloOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1549#define GET_OP_CLASSES
1550#include "mlir/Dialect/Shard/IR/ShardOps.cpp.inc"
1552#define GET_ATTRDEF_CLASSES
1553#include "mlir/Dialect/Shard/IR/ShardAttributes.cpp.inc"
1555#define GET_TYPEDEF_CLASSES
1556#include "mlir/Dialect/Shard/IR/ShardTypes.cpp.inc"
1558#include "mlir/Dialect/Shard/IR/ShardEnums.cpp.inc"
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.
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)
static LogicalResult verifyGridAxes(Location loc, ArrayRef< GridAxis > axes, GridOp grid)
static FailureOr< GridOp > getGridAndVerifyAxes(Op op, SymbolTableCollection &symbolTable)
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={})
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)
static void maybeInsertTargetShardingAnnotationImpl(Sharding sharding, Value &operandValue, Operation *operandOp, OpBuilder &builder, ShardOp &newShardOp)
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Attributes are known-constant values of operations.
MLIRContext * getContext() const
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.
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...
MLIRContext is the top-level object for a collection of MLIR operations.
RAII guard to reset the insertion point of the builder when destroyed.
This class helps build Operations.
void setInsertionPoint(Block *block, Block::iterator insertPoint)
Set the insertion point to the specified location.
void setInsertionPointAfterValue(Value val)
Sets the insertion point to the node after the specified value.
This class represents an operand of an operation.
This is a value defined by a result of an operation.
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.
bool hasTrait()
Returns true if the operation was registered with a particular trait, e.g.
OperandRange operand_range
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.
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...
This class provides an abstraction over the different types of ranges over Values.
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.
use_range getUses() const
Returns a range of all uses, which is useful for iterating over all uses.
bool replaceUsesWithIf(Value newValue, function_ref< bool(OpOperand &)> shouldReplace)
Replace all uses of 'this' value with 'newValue' if the given callback returns true.
bool hasOneUse() const
Returns true if this value has exactly one use.
Location getLoc() const
Return the location of this value.
Operation * getDefiningOp() const
If this value is the result of an operation, return the operation that defines it.
static DenseArrayAttrImpl get(MLIRContext *context, ArrayRef< int16_t > content)
Operation * getOwner() const
Return the owner of this operand.
ArrayRef< Value > getDynamicShardedDimsOffsets() const
bool operator!=(Value rhs) const
bool equalShardSizes(const Sharding &rhs) const
Sharding(::mlir::FlatSymbolRefAttr grid_=nullptr)
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_={})
bool equalSplitAxes(const Sharding &rhs) const
ArrayRef< int64_t > getStaticHaloSizes() const
::mlir::FlatSymbolRefAttr getGridAttr() const
::llvm::StringRef getGrid() const
bool equalHaloAndShardSizes(const Sharding &rhs) const
bool operator==(Value rhs) const
ArrayRef< Value > getDynamicHaloSizes() const
ArrayRef< int64_t > getStaticShardedDimsOffsets() const
ArrayRef< GridAxesAttr > getSplitAxes() const
bool equalHaloSizes(const Sharding &rhs) const
NestedPattern Op(FilterFunctionType filter=defaultFilterFunction)
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const Sharding &sharding)
ShapedType shardShapedType(ShapedType shape, GridOp grid, Sharding sharding)
void maybeInsertTargetShardingAnnotation(Sharding sharding, OpResult result, OpBuilder &builder)
DenseI16ArrayAttr GridAxesAttr
shard::GridOp getGridOrNull(Operation *op, FlatSymbolRefAttr gridSymbol, SymbolTableCollection &symbolTableCollection)
bool isFullReplication(Sharding sharding)
void maybeInsertSourceShardingAnnotation(Sharding sharding, OpOperand &operand, OpBuilder &builder)
int64_t shardDimension(int64_t dimSize, int64_t shardCount)
Type shardType(Type type, GridOp grid, Sharding sharding)
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.
int64_t collectiveProcessGroupSize(GridAxesRange &&gridAxes, GridShapeRange &&gridShape)
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)
AffineExpr operator*(int64_t val, AffineExpr expr)
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
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.