tvm
Loading...
Searching...
No Matches
axis_group_graph.h
Go to the documentation of this file.
1/*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 */
19
20#ifndef TVM_RELAX_DISTRIBUTED_AXIS_GROUP_GRAPH_H_
21#define TVM_RELAX_DISTRIBUTED_AXIS_GROUP_GRAPH_H_
22
24#include <tvm/relax/expr.h>
25#include <tvm/s_tir/stmt.h>
28#include <tvm/tirx/function.h>
29
30#include <algorithm>
31#include <limits>
32#include <optional>
33#include <string>
34#include <tuple>
35#include <unordered_map>
36#include <unordered_set>
37#include <utility>
38#include <vector>
39
40namespace tvm {
41namespace tirx {
42// (var, axis)
43using TIRVarAxis = std::pair<Var, int>;
44// (tensor, axis)
45using TensorAxis = std::pair<TensorVar, int>;
47 public:
48 size_t operator()(const TensorAxis& tensor_axis) const {
49 size_t const h1(ffi::ObjectPtrHash()(tensor_axis.first));
50 size_t const h2(std::hash<int>()(tensor_axis.second));
51 return h1 ^ (h2 << 1);
52 }
53};
63ffi::Optional<Var> GetShardingVarFromIndex(PrimExpr index, ffi::Map<Var, Range> var_range,
64 const sym::Analyzer& analyzer);
65
71 public:
72 static std::vector<std::vector<TIRVarAxis>> GetTIRVarAxisGraph(const tirx::Function& function) {
73 auto extractor = ffi::make_object<TensorAxisGraphExtractor>();
74 extractor->Visit(function->body);
75 ffi::Map<TensorVar, Var> inverse_tensor_map;
76 for (const Var& param : function->params) {
77 if (param->ty.as<TensorTypeObj>()) {
78 inverse_tensor_map.Set(param.as_or_throw<TensorVar>(), param);
79 }
80 }
81 std::vector<std::vector<TIRVarAxis>> tir_var_axis_group_list;
82 std::unordered_set<TensorAxis, TensorAxisHash> visited;
83 for (const Var& param : function->params) {
84 if (!param->ty.as<TensorTypeObj>()) {
85 continue;
86 }
87 TensorVar tensor = param.as_or_throw<TensorVar>();
88 for (int i = 0; i < static_cast<int>(tensor.shape().size()); i++) {
89 if (extractor->tensor_axis_graph_.count({tensor, i})) {
90 std::vector<TensorAxis> tensor_axis_group;
91 extractor->DFSGraph({tensor, i}, &visited, &tensor_axis_group);
92 if (tensor_axis_group.size() <= 1) {
93 continue;
94 }
95 std::vector<TIRVarAxis> tir_var_axis_group;
96 for (const auto& tensor_axis : tensor_axis_group) {
97 if (!inverse_tensor_map.count(tensor_axis.first)) {
98 continue;
99 }
100 tir_var_axis_group.push_back(
101 {inverse_tensor_map[tensor_axis.first], tensor_axis.second});
102 }
103 tir_var_axis_group_list.push_back(tir_var_axis_group);
104 }
105 }
106 }
107 return tir_var_axis_group_list;
108 }
109
110 void DFSGraph(TensorAxis cur, std::unordered_set<TensorAxis, TensorAxisHash>* visited,
111 std::vector<TensorAxis>* tensor_axis_group) {
112 if (visited->count(cur)) {
113 return;
114 }
115 visited->insert(cur);
116 tensor_axis_group->push_back(cur);
117 for (const auto& next : tensor_axis_graph_[cur]) {
118 DFSGraph(next, visited, tensor_axis_group);
119 }
120 }
121
122 private:
123 ffi::Optional<VisitInterrupt> Visit_(const TensorStoreObj* op) final {
124 TVM_FFI_S_VISIT_MAYBE_EARLY_RETURN(s_tir::StmtExprVisitor::Visit_(op));
125 tensor_access_indices_.push_back({op->dest.as_or_throw<tvm::tirx::TensorVar>(), op->indices});
126
127 return std::nullopt;
128 }
129
130 ffi::Optional<VisitInterrupt> Visit_(const TensorLoadObj* op) final {
131 TVM_FFI_S_VISIT_MAYBE_EARLY_RETURN(s_tir::StmtExprVisitor::Visit_(op));
132 tensor_access_indices_.push_back({op->source.as_or_throw<tvm::tirx::TensorVar>(), op->indices});
133
134 return std::nullopt;
135 }
136
137 bool Match(PrimExpr a, PrimExpr tensor_shape_a, PrimExpr b, PrimExpr tensor_shape_b,
138 const sym::Analyzer& analyzer) {
139 if (b.as<PrimVar>()) {
140 std::swap(a, b);
141 std::swap(tensor_shape_a, tensor_shape_b);
142 }
143 auto prim_var = a.as<PrimVar>();
144 if (!prim_var) {
145 return false;
146 }
147 Var var = *prim_var;
148 b = analyzer->Simplify(b);
149 // index var `a` must access whole range of a specific tensor dimension
150 sym::IntSet intset_b = sym::EvalSet(b, sym::AsIntSet(iter_var_range_));
151 if (!analyzer->CanProveEqual(tensor_shape_a, iter_var_range_[var]->extent) ||
152 !intset_b.MatchRange(Range::FromMinExtent(0, tensor_shape_b))) {
153 return false;
154 }
155 auto matched_var = GetShardingVarFromIndex(b, iter_var_range_, analyzer);
156 if (!matched_var.has_value() || !matched_var.value().same_as(var)) {
157 return false;
158 }
159 return true;
160 }
161
162 ffi::Optional<VisitInterrupt> Visit_(const s_tir::SBlockObj* op) final {
163 if (op->name_hint == "root") {
165 }
166 tensor_access_indices_.clear();
167 TVM_FFI_S_VISIT_MAYBE_EARLY_RETURN(s_tir::StmtExprVisitor::Visit_(op));
168 iter_var_range_.clear();
169 for (const auto& iter_var : op->iter_vars) {
170 iter_var_range_.Set(iter_var->var, iter_var->dom.value());
171 }
172 sym::Analyzer analyzer;
173 sym::ConstraintContext context;
174 for (const auto& [var, range] : iter_var_range_) {
175 context->Append(sym::RangeConstraint(var, range));
176 }
177 analyzer->SyncConstraintContext(context);
178 for (const auto& access_pr : tensor_access_indices_) {
179 TensorVar tensor = access_pr.first;
180 ffi::Array<PrimExpr> indices = access_pr.second;
181 for (int i = 0; i < static_cast<int>(indices.size()); i++) {
182 for (const auto& another_access_pr : tensor_access_indices_) {
183 if (another_access_pr.first.same_as(tensor)) {
184 continue;
185 }
186 TensorVar another_tensor = another_access_pr.first;
187 ffi::Array<PrimExpr> another_indices = another_access_pr.second;
188 for (int j = 0; j < static_cast<int>(another_indices.size()); j++) {
189 if (Match(indices[i], tensor.shape()[i], another_indices[j], another_tensor.shape()[j],
190 analyzer)) {
191 JoinTensorAxis({tensor, i}, {another_tensor, j});
192 }
193 }
194 }
195 }
196 }
197
198 return std::nullopt;
199 }
200
201 void JoinTensorAxis(TensorAxis axis1, TensorAxis axis2) {
202 if (!tensor_axis_graph_.count(axis1)) {
203 tensor_axis_graph_[axis1] = {};
204 }
205 if (!tensor_axis_graph_.count(axis2)) {
206 tensor_axis_graph_[axis2] = {};
207 }
208 tensor_axis_graph_[axis1].push_back(axis2);
209 tensor_axis_graph_[axis2].push_back(axis1);
210 }
211
212 std::vector<std::pair<TensorVar, ffi::Array<PrimExpr>>> tensor_access_indices_;
213 std::unordered_map<TensorAxis, std::vector<TensorAxis>, TensorAxisHash> tensor_axis_graph_;
214 ffi::Map<Var, Range> iter_var_range_;
215 std::string func_name;
216};
217} // namespace tirx
218} // namespace tvm
219
220namespace tvm {
221namespace relax {
222namespace distributed {
223
225struct Axis {
226 const ExprObj* tensor;
227 int dim = 0;
228 int tuple_index = 0;
229
230 Axis(const ExprObj* tensor, int dim, int tuple_index = 0)
231 : tensor(tensor), dim(dim), tuple_index(tuple_index) {
232 TVM_FFI_ICHECK(tensor->IsInstance<GenericConstObj>() || tensor->IsInstance<VarObj>());
233 }
234
235 bool operator==(const Axis& other) const {
236 return tensor == other.tensor && dim == other.dim && tuple_index == other.tuple_index;
237 }
238};
239
240class AxisHash {
241 public:
242 size_t operator()(const Axis& axis) const {
243 size_t const h1(std::hash<const ExprObj*>()(axis.tensor));
244 size_t const h2(std::hash<int>()(axis.dim));
245 size_t const h3(std::hash<int>()(axis.tuple_index));
246 return h1 ^ (h2 << 1) ^ (h3 << 2);
247 }
248};
249
250using AxisGroup = std::unordered_set<Axis, AxisHash>;
251
252class AxisGroupHash {
253 public:
254 size_t operator()(const AxisGroup& axis_group) const {
255 size_t seed = 0;
256 for (auto axis : axis_group) {
257 seed ^= AxisHash()(axis) + 0x9e3779b9 + (seed << 6) + (seed >> 2);
258 }
259 return seed;
260 }
261};
262
263using ShardingSpec = std::pair<DeviceMesh, Placement>;
264
265// device mesh and the device mesh axis that the tensor axis maps to
266using AxisShardingSpec = std::pair<DeviceMesh, int>;
267class AxisShardingSpecEqual {
268 public:
269 bool operator()(const AxisShardingSpec& lhs, const AxisShardingSpec& rhs) const {
270 return ffi::StructuralEqual()(lhs.first, rhs.first) && lhs.second == rhs.second;
271 }
272};
273
274class AxisShardingSpecHash {
275 public:
276 size_t operator()(const AxisShardingSpec& sharding_spec) const {
277 size_t seed = 0;
278 seed ^= ffi::StructuralHash()(sharding_spec.first);
279 seed ^= std::hash<int>()(sharding_spec.second) << 1;
280 return seed;
281 }
282};
283
289class AxisGroupGraph {
290 public:
291 enum class EdgeType { kAscend, kDescend, kSimbling };
292
293 private:
294 static EdgeType ReverseEdgeType(EdgeType type) {
295 switch (type) {
296 case EdgeType::kAscend:
297 return EdgeType::kDescend;
298 case EdgeType::kDescend:
299 return EdgeType::kAscend;
300 case EdgeType::kSimbling:
301 return EdgeType::kSimbling;
302 }
303 TVM_FFI_THROW(InternalError) << "Unreachable code";
304 throw;
305 }
306
307 static int GetEdgePriority(EdgeType type) {
308 switch (type) {
309 case EdgeType::kAscend:
310 return 0;
311 case EdgeType::kDescend:
312 return 2;
313 case EdgeType::kSimbling:
314 return 1;
315 }
316 TVM_FFI_THROW(InternalError) << "Unreachable code";
317 throw;
318 }
319
320 struct AxisGraphEdge {
321 Axis src;
322 Axis dst;
323
324 // the producer-consumer relationship between src tensor and dst tensor
325 // kAscend means consumer->producer
326 // kDescend means producer->consumer
327 // kSimbling means other cases
328 EdgeType type;
329
330 bool operator==(const AxisGraphEdge& other) const {
331 return src == other.src && dst == other.dst && type == other.type;
332 }
333 };
334
335 struct Path {
336 int direction = 0;
337
338 Path AddEdge(EdgeType type) { return {direction |= (1 << GetEdgePriority(type))}; }
339
340 int GetPriority() const {
341 switch (direction) {
342 case 1: // ascend only
343 return 0;
344 case 4: // descend only
345 return 2;
346 case 0: // empty path (source node)
347 return 3; // source node must have max priority
348 default: // mixed path
349 return 1;
350 }
351 }
352 };
353
354 public:
355 AxisGroupGraph() = default;
356
366 void JoinAxis(Axis axis1, Axis axis2, EdgeType type) {
367 AddEdge(axis1, axis2, type);
368 AddEdge(axis2, axis1, ReverseEdgeType(type));
369 }
370
376 void AddSrcShardingPoint(Axis axis, AxisShardingSpec spec) {
377 src_axis_sharding_spec_.insert_or_assign(axis, spec);
378 }
379
383 void PropagateShardingSpec() {
384 axis_sharding_specs_priority_.clear();
385 for (const auto& pr : src_axis_sharding_spec_) {
386 std::unordered_set<Axis, AxisHash> visited;
387 PropagateShardingSpec(pr.first, pr.second, Path(), &visited);
388 }
389 ChooseAxisShardingSpec();
390 }
391
398 void AddPropagationCutPoint(Axis axis, AxisShardingSpec spec) {
399 cutpoint_axis_sharding_spec_.insert_or_assign(axis, spec);
400 }
401
409 std::tuple<std::optional<AxisShardingSpec>, bool> GetAxisShardingSpec(Axis axis) {
410 if (axis_sharding_specs_priority_.count(axis)) {
411 return {axis_sharding_specs_priority_[axis].begin()->first, true};
412 } else {
413 return {std::nullopt, false};
414 }
415 }
416
417 private:
418 void AddEdge(Axis src, Axis dst, EdgeType type) {
419 if (!graph_.count(src)) {
420 graph_[src] = {};
421 }
422 graph_[src].push_back({src, dst, type});
423 }
424
425 void PropagateShardingSpec(Axis axis, AxisShardingSpec spec, Path path,
426 std::unordered_set<Axis, AxisHash>* visited) {
427 if (cutpoint_axis_sharding_spec_.count(axis) ||
428 (src_axis_sharding_spec_.count(axis) &&
429 !AxisShardingSpecEqual()(src_axis_sharding_spec_.at(axis), spec)) ||
430 visited->count(axis)) {
431 return;
432 }
433 visited->insert(axis);
434 if (!axis_sharding_specs_priority_.count(axis)) {
435 axis_sharding_specs_priority_[axis] = {};
436 }
437 axis_sharding_specs_priority_[axis][spec] = path.GetPriority();
438 for (auto edge : graph_[axis]) {
439 PropagateShardingSpec(edge.dst, spec, path.AddEdge(edge.type), visited);
440 }
441 }
442
443 void ChooseAxisShardingSpec() {
444 for (auto& pr : axis_sharding_specs_priority_) {
445 auto& axis = pr.first;
446 auto& specs = pr.second;
447 int max_priority = std::numeric_limits<int>::min();
448 for (auto& pr2 : specs) {
449 max_priority = std::max(max_priority, pr2.second);
450 }
451 for (auto it = specs.begin(); it != specs.end();) {
452 if (it->second != max_priority) {
453 it = specs.erase(it);
454 } else {
455 it++;
456 }
457 }
458 TVM_FFI_ICHECK(specs.size() == 1)
459 << "multiple possible sharding for axis: (" << ffi::GetRef<Expr>(axis.tensor) << ", "
460 << axis.dim << ")";
461 }
462 }
463
464 // union set
465 std::unordered_map<Axis, std::vector<AxisGraphEdge>, AxisHash> graph_;
466 std::unordered_map<Axis, AxisShardingSpec, AxisHash> src_axis_sharding_spec_;
467 std::unordered_map<Axis, AxisShardingSpec, AxisHash> cutpoint_axis_sharding_spec_;
468 std::unordered_map<
469 Axis, std::unordered_map<AxisShardingSpec, int, AxisShardingSpecHash, AxisShardingSpecEqual>,
470 AxisHash>
471 axis_sharding_specs_priority_;
472};
473
474using FBuildAxisGraph = std::function<void(const Var& output_var, const Call& call,
475 distributed::AxisGroupGraph* axis_group_graph)>;
476
477void BuildAxisGraphUnary(const Var& output_var, const Call& call,
478 distributed::AxisGroupGraph* axis_group_graph);
479void BuildAxisGraphBinary(const Var& output_var, const Call& call,
480 distributed::AxisGroupGraph* axis_group_graph);
481void BuildAxisGraphReduce(const Var& output_var, const Call& call,
482 distributed::AxisGroupGraph* axis_group_graph);
483void BuildAxisGraphMatmul(const Var& output_var, const Call& call,
484 distributed::AxisGroupGraph* axis_group_graph);
485void BuildAxisGraphPermuteDims(const Var& output_var, const Call& call,
486 distributed::AxisGroupGraph* axis_group_graph);
487void BuildAxisGraphReshape(const Var& output_var, const Call& call,
488 distributed::AxisGroupGraph* axis_group_graph);
489void BuildAxisGraphCallTIR(const Var& output_var, const Call& call, const tirx::Function& func,
490 distributed::AxisGroupGraph* axis_group_graph);
491
492} // namespace distributed
493} // namespace relax
494} // namespace tvm
495
496#endif // TVM_RELAX_DISTRIBUTED_AXIS_GROUP_GRAPH_H_
TIR Function.
Managed reference to CallObj.
Definition expr.h:825
Base type of all the expressions.
Definition expr.h:66
A constant whose payload is separate from its expression type.
Definition expr.h:245
Typed reference/view over any Expr whose ExprObj::ty is PrimType.
Definition expr.h:187
static TVM_TIRX_DLL Range FromMinExtent(PrimExpr min, PrimExpr extent, Location loc=UnknownLoc())
construct a new range with min and extent The corresponding constructor is removed,...
Store a primitive value to an indexed destination expression.
Definition stmt.h:315
A local variable in the IR.
Definition expr.h:552
Managed reference to VarObj.
Definition expr.h:571
Extend native TIRX traversal with schedulable block semantics.
Definition stmt_functor.h:77
virtual ffi::Optional< VisitInterrupt > Visit_(const SBlockObj *op)
Managed reference to AnalyzerObj.
Definition analyzer.h:750
Managed reference to FunctionObj.
Definition function.h:107
Construct an axis group graph from a tirx::Function. Two tensor axis are connected if they are access...
Definition axis_group_graph.h:70
static std::vector< std::vector< TIRVarAxis > > GetTIRVarAxisGraph(const tirx::Function &function)
Definition axis_group_graph.h:72
void DFSGraph(TensorAxis cur, std::unordered_set< TensorAxis, TensorAxisHash > *visited, std::vector< TensorAxis > *tensor_axis_group)
Definition axis_group_graph.h:110
Definition axis_group_graph.h:46
size_t operator()(const TensorAxis &tensor_axis) const
Definition axis_group_graph.h:48
Structural type of a TIRx tensor variable.
Definition type.h:59
Checked zero-state view over an ordinary VarObj with TensorType.
Definition expr.h:48
const ffi::Array< PrimExpr > & shape() const
Return the shape of the tensor.
Definition expr.h:63
Type definitions for DTensor (Distributed Tensor)
S-TIR (Schedulable TIR) statements and attributes.
Native traversal and statement dispatch for schedulable TIR.
Iterator quasi-affine mapping patterns.
TVM_TIRX_DLL IntSet EvalSet(PrimExpr e, const ffi::Map< Var, IntSet > &dom_map)
Find an symbolic integer set that contains all possible values of e given the domain of each variable...
TVM_TIRX_DLL ffi::Map< Var, sym::IntSet > AsIntSet(const ffi::Map< Var, Range > &var_dom)
Converts the Ranges to IntSets.
PrimVar var(std::string name_hint, PrimType t=PrimType::Int(32))
Construct a new Var expression.
std::pair< TensorVar, int > TensorAxis
Definition axis_group_graph.h:45
std::pair< Var, int > TIRVarAxis
Definition axis_group_graph.h:43
ffi::Optional< Var > GetShardingVarFromIndex(PrimExpr index, ffi::Map< Var, Range > var_range, const sym::Analyzer &analyzer)
Suppose we want to shard a tensor along a specific dimension, we need to know how to rewrite the acce...
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition analysis.h:41