MLIR 24.0.0git
ShardOps.h
Go to the documentation of this file.
1//===- ShardOps.h - Shard Dialect Operations --------------------*- C++ -*-===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8
9#ifndef MLIR_DIALECT_SHARD_IR_SHARDOPS_H
10#define MLIR_DIALECT_SHARD_IR_SHARDOPS_H
11
14#include "mlir/IR/Diagnostics.h"
17#include "mlir/IR/SymbolTable.h"
21#include "llvm/Support/MathExtras.h"
22
23namespace mlir {
24namespace shard {
25
26using GridAxis = int16_t;
30
31} // namespace shard
32} // namespace mlir
33
34#include "mlir/Dialect/Shard/IR/ShardEnums.h.inc"
35
36#define GET_ATTRDEF_CLASSES
37#include "mlir/Dialect/Shard/IR/ShardAttributes.h.inc"
38
39namespace mlir {
40namespace shard {
41
42class Sharding {
43private:
46 SmallVector<int64_t> static_halo_sizes;
47 SmallVector<int64_t> static_sharded_dims_offsets;
48 SmallVector<Value> dynamic_halo_sizes;
49 SmallVector<Value> dynamic_sharded_dims_offsets;
50
51public:
52 Sharding(::mlir::FlatSymbolRefAttr grid_ = nullptr);
53 Sharding(Value rhs);
55 ArrayRef<GridAxesAttr> split_axes_,
56 ArrayRef<int64_t> static_halo_sizes_ = {},
57 ArrayRef<int64_t> static_sharded_dims_offsets_ = {},
58 ArrayRef<Value> dynamic_halo_sizes_ = {},
59 ArrayRef<Value> dynamic_sharded_dims_offsets_ = {});
60 ::mlir::FlatSymbolRefAttr getGridAttr() const { return grid; }
61 ::llvm::StringRef getGrid() const { return grid ? grid.getValue() : ""; }
62 ArrayRef<GridAxesAttr> getSplitAxes() const { return split_axes; }
63 ArrayRef<int64_t> getStaticHaloSizes() const { return static_halo_sizes; }
65 return static_sharded_dims_offsets;
66 }
67 ArrayRef<Value> getDynamicHaloSizes() const { return dynamic_halo_sizes; }
69 return dynamic_sharded_dims_offsets;
70 }
71 operator bool() const { return (!grid) == false; }
72 bool operator==(Value rhs) const;
73 bool operator!=(Value rhs) const;
74 bool operator==(const Sharding &rhs) const;
75 bool operator!=(const Sharding &rhs) const;
76 bool equalSplitAxes(const Sharding &rhs) const;
77 bool equalHaloAndShardSizes(const Sharding &rhs) const;
78 bool equalHaloSizes(const Sharding &rhs) const;
79 bool equalShardSizes(const Sharding &rhs) const;
80};
81
82llvm::raw_ostream &operator<<(llvm::raw_ostream &os, const Sharding &sharding);
83
84inline Diagnostic &operator<<(Diagnostic &diag, const Sharding &sharding) {
85 std::string str;
86 llvm::raw_string_ostream os(str);
87 os << sharding;
88 return diag << os.str();
89}
90
91} // namespace shard
92} // namespace mlir
93
94#define GET_TYPEDEF_CLASSES
95#include "mlir/Dialect/Shard/IR/ShardTypes.h.inc"
96
97#define GET_OP_CLASSES
98#include "mlir/Dialect/Shard/IR/ShardOps.h.inc"
99
100namespace mlir {
101namespace shard {
102
103inline bool isReductionLoop(utils::IteratorType iType) {
104 return iType == utils::IteratorType::reduction;
105}
106
107// Remove empty subarrays of `array` until a minimum lengh of one is reached.
108template <typename T>
110 while (array.size() > 1 && array.back().empty())
111 array.pop_back();
112}
113
114// Is the same tensor replicated on all processes.
115inline bool isFullReplication(Sharding sharding) {
116 return llvm::all_of(sharding.getSplitAxes(), [](GridAxesAttr axes) {
117 return axes.asArrayRef().empty();
118 });
119}
120
121inline shard::GridOp
123 SymbolTableCollection &symbolTableCollection) {
124 if (!gridSymbol)
125 return nullptr;
126 return symbolTableCollection.lookupNearestSymbolFrom<shard::GridOp>(
127 op, gridSymbol);
128}
129
130inline shard::GridOp getGrid(Operation *op, FlatSymbolRefAttr gridSymbol,
131 SymbolTableCollection &symbolTableCollection) {
132 shard::GridOp gridOp = getGridOrNull(op, gridSymbol, symbolTableCollection);
133 assert(gridOp);
134 return gridOp;
135}
136
137// Get the corresponding grid op using the standard attribute nomenclature.
138template <typename Op>
139shard::GridOp getGrid(Op op, SymbolTableCollection &symbolTableCollection) {
140 return getGrid(op.getOperation(), op.getGridAttr(), symbolTableCollection);
141}
142
143template <>
144inline shard::GridOp
145getGrid<ShardOp>(ShardOp op, SymbolTableCollection &symbolTableCollection) {
146 return getGrid(
147 op.getOperation(),
148 cast<ShardingOp>(op.getSharding().getDefiningOp()).getGridAttr(),
149 symbolTableCollection);
150}
151
152// Get the number of processes that participate in each group
153// induced by `gridAxes`.
154template <typename GridAxesRange, typename GridShapeRange>
155int64_t collectiveProcessGroupSize(GridAxesRange &&gridAxes,
156 GridShapeRange &&gridShape) {
157 int64_t res = 1;
158
159 for (GridAxis axis : gridAxes) {
160 auto axisSize = *(std::begin(gridShape) + axis);
161 if (ShapedType::isDynamic(axisSize)) {
162 return ShapedType::kDynamic;
163 }
164 res *= axisSize;
165 }
166
167 return res;
168}
169
170template <typename GridAxesRange>
171int64_t collectiveProcessGroupSize(GridAxesRange &&gridAxes, GridOp grid) {
172 return collectiveProcessGroupSize(std::forward<GridAxesRange>(gridAxes),
173 grid.getShape());
174}
175
176// Get the size of a sharded dimension.
177inline int64_t shardDimension(int64_t dimSize, int64_t shardCount) {
178 if (ShapedType::isDynamic(dimSize) || ShapedType::isDynamic(shardCount))
179 return ShapedType::kDynamic;
180
181 assert(dimSize % shardCount == 0);
182 return dimSize / shardCount;
183}
184
185// Get the size of an unsharded dimension.
186inline int64_t gatherDimension(int64_t dimSize, int64_t shardCount) {
187 if (ShapedType::isDynamic(dimSize) || ShapedType::isDynamic(shardCount))
188 return ShapedType::kDynamic;
189
190 return dimSize * shardCount;
191}
192
193// Return the per-device sharded type for `shape` based on `sharding`.
194// This is the tensor shape on each grid partition.
195// Example:
196// On a 2x4x? grid with split axes = [[0], [1], [2]] the shape ?x5x1 would
197// result in a shape for each shard of ?x2x?.
198ShapedType shardShapedType(ShapedType shape, GridOp grid, Sharding sharding);
199
200// If ranked tensor type return its sharded counterpart.
201//
202// If not ranked tensor type return `type`.
203// `sharding` in that case must be null.
204Type shardType(Type type, GridOp grid, Sharding sharding);
205
206// Insert shard op if there is not one that already has the same sharding.
207// Use newShardOp if it is not null. Otherwise create a new one.
208// May insert resharding if required.
209// Potentially updates newShardOp.
211 OpBuilder &builder);
212void maybeInsertSourceShardingAnnotation(Sharding sharding, OpOperand &operand,
213 OpBuilder &builder);
214
215/// Converts a vector of OpFoldResults (ints) into vector of Values of the
216/// provided type.
219 ValueRange dynamics, Type type = Type());
220} // namespace shard
221} // namespace mlir
222
223#endif // MLIR_DIALECT_SHARD_IR_SHARDOPS_H
b
Return true if permutation is a valid permutation of the outer_dims_perm (case OuterOrInnerPerm::Oute...
This class contains all of the information necessary to report a diagnostic to the DiagnosticEngine.
A symbol reference with a reference path containing a single element.
This class defines the main interface for locations in MLIR and acts as a non-nullable wrapper around...
Definition Location.h:76
This class helps build Operations.
Definition Builders.h:210
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
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
This class represents a collection of SymbolTables.
virtual Operation * lookupNearestSymbolFrom(Operation *from, StringAttr symbol)
Returns the operation registered with the given symbol name within the closest parent operation of,...
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
ArrayRef< Value > getDynamicShardedDimsOffsets() const
Definition ShardOps.h:68
bool operator!=(Value rhs) const
Definition ShardOps.cpp:746
bool equalShardSizes(const Sharding &rhs) const
Definition ShardOps.cpp:714
Sharding(::mlir::FlatSymbolRefAttr grid_=nullptr)
Definition ShardOps.cpp:777
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:795
bool equalSplitAxes(const Sharding &rhs) const
Definition ShardOps.cpp:691
ArrayRef< int64_t > getStaticHaloSizes() const
Definition ShardOps.h:63
::mlir::FlatSymbolRefAttr getGridAttr() const
Definition ShardOps.h:60
::llvm::StringRef getGrid() const
Definition ShardOps.h:61
bool equalHaloAndShardSizes(const Sharding &rhs) const
Definition ShardOps.cpp:710
bool operator==(Value rhs) const
Definition ShardOps.cpp:742
ArrayRef< Value > getDynamicHaloSizes() const
Definition ShardOps.h:67
ArrayRef< int64_t > getStaticShardedDimsOffsets() const
Definition ShardOps.h:64
ArrayRef< GridAxesAttr > getSplitAxes() const
Definition ShardOps.h:62
bool equalHaloSizes(const Sharding &rhs) const
Definition ShardOps.cpp:730
llvm::raw_ostream & operator<<(llvm::raw_ostream &os, const Sharding &sharding)
Definition ShardOps.cpp:754
ShapedType shardShapedType(ShapedType shape, GridOp grid, Sharding sharding)
Definition ShardOps.cpp:279
shard::GridOp getGrid< ShardOp >(ShardOp op, SymbolTableCollection &symbolTableCollection)
Definition ShardOps.h:145
void maybeInsertTargetShardingAnnotation(Sharding sharding, OpResult result, OpBuilder &builder)
Definition ShardOps.cpp:336
DenseI16ArrayAttr GridAxesAttr
Definition ShardOps.h:27
void removeTrailingEmptySubArray(SmallVector< SmallVector< T > > &array)
Definition ShardOps.h:109
shard::GridOp getGridOrNull(Operation *op, FlatSymbolRefAttr gridSymbol, SymbolTableCollection &symbolTableCollection)
Definition ShardOps.h:122
bool isFullReplication(Sharding sharding)
Definition ShardOps.h:115
int16_t GridAxis
Definition ShardOps.h:26
DenseI64ArrayAttr HaloSizePairAttr
Definition ShardOps.h:29
void maybeInsertSourceShardingAnnotation(Sharding sharding, OpOperand &operand, OpBuilder &builder)
Definition ShardOps.cpp:350
bool isReductionLoop(utils::IteratorType iType)
Definition ShardOps.h:103
DenseI64ArrayAttr ShardShapeAttr
Definition ShardOps.h:28
int64_t shardDimension(int64_t dimSize, int64_t shardCount)
Definition ShardOps.h:177
Type shardType(Type type, GridOp grid, Sharding sharding)
Definition ShardOps.cpp:289
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:155
shard::GridOp getGrid(Operation *op, FlatSymbolRefAttr gridSymbol, SymbolTableCollection &symbolTableCollection)
Definition ShardOps.h:130
int64_t gatherDimension(int64_t dimSize, int64_t shardCount)
Definition ShardOps.h:186
Include the generated interface declarations.
detail::DenseArrayAttrImpl< int64_t > DenseI64ArrayAttr
detail::DenseArrayAttrImpl< int16_t > DenseI16ArrayAttr