tvm
data_layout.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 
25 #ifndef TVM_TIR_DATA_LAYOUT_H_
26 #define TVM_TIR_DATA_LAYOUT_H_
27 
28 #include <tvm/tir/expr.h>
29 #include <tvm/tir/op.h>
30 
31 #include <algorithm>
32 #include <sstream>
33 #include <string>
34 #include <utility>
35 #include <vector>
36 
37 namespace tvm {
38 namespace tir {
39 
40 class Layout;
41 
42 class LayoutAxis {
43  public:
44  static const LayoutAxis& Get(const char name);
45 
46  // Get the singleton LayoutAxis using itvar->var->name_hint
47  static const LayoutAxis& Get(const tir::IterVar& itvar);
48 
49  // Get the singleton LayoutAxis using name[0] (size of name must be 1).
50  static const LayoutAxis& Get(const std::string& name);
51 
52  inline bool IsPrimal() const { return name_ >= 'A' && name_ <= 'Z'; }
53  inline std::string name() const { return std::string(1, name_); }
54 
55  // if current axis is primal, switch the axis to its subordinate one,
56  // else switch to the primal.
57  inline const LayoutAxis& ToDual() const {
58  if (name_ >= 'A' && name_ <= 'Z') {
59  return LayoutAxis::Get(name_ - 'A' + 'a');
60  } else {
61  return LayoutAxis::Get(name_ - 'a' + 'A');
62  }
63  }
64 
65  // return the primal axis. If it is already primal, return itself.
66  const LayoutAxis& ToPrimal() const { return IsPrimal() ? *this : ToDual(); }
67 
68  // return the subordinate axis. If it is already subordinate, return itself.
69  const LayoutAxis& ToSubordinate() const { return IsPrimal() ? ToDual() : *this; }
70 
71  inline bool operator==(const LayoutAxis& rhs) const { return name_ == rhs.name_; }
72 
73  friend std::ostream& operator<<(std::ostream& os, const LayoutAxis& l) {
74  os << l.name();
75  return os;
76  }
77 
78  private:
79  static const LayoutAxis UPPER_CASE[];
80  static const LayoutAxis LOWER_CASE[];
81  LayoutAxis(const LayoutAxis&);
82  LayoutAxis& operator=(const LayoutAxis&);
83  explicit LayoutAxis(const char name) : name_(name) {}
84 
85  const char name_;
86 };
87 
98 class LayoutNode : public Object {
99  public:
109 
111  v->Visit("name", &name);
112  v->Visit("axes", &axes);
113  }
114 
115  static constexpr const char* _type_key = "tir.Layout";
117 };
118 
123 class Layout : public ObjectRef {
124  public:
125  explicit Layout(const Array<tir::IterVar>& axes);
126 
128  Layout(const tvm::String& name) : Layout(name.operator std::string()) {} // NOLINT(*)
129 
131  Layout(const char* name) : Layout(std::string(name)) {} // NOLINT(*)
132 
143  TVM_DLL Layout(const std::string& name, DataType dtype = DataType::Int(32)); // NOLINT(*)
144 
149  LayoutNode* operator->() { return static_cast<LayoutNode*>(get_mutable()); }
150 
155  static const Layout& Undef() {
156  static Layout undef;
157  return undef;
158  }
159 
168  Layout SubLayout(size_t pos, size_t len) const;
169 
177  Layout Split(const LayoutAxis& axis, size_t target_pos, int32_t factor) const;
178 
180  inline size_t ndim() const {
181  if (!defined()) return 0;
182  return operator->()->axes.size();
183  }
184 
186  inline size_t ndim_primal() const {
187  if (!defined()) return 0;
188  size_t ct = 0;
189  for (auto x : operator->()->axes) {
190  if (LayoutAxis::Get(x).IsPrimal()) {
191  ct++;
192  }
193  }
194  return ct;
195  }
196 
202  inline Layout ExpandPrimal(const Layout& dst_layout) {
203  Layout new_src_layout;
204  // 1) Find the axis which are missing in the current layout. Make them the prefix.
205  std::string new_src_layout_str = "";
206  for (auto dst_axis : dst_layout->axes) {
207  if (LayoutAxis::Get(dst_axis).IsPrimal()) {
208  if (!this->Contains(LayoutAxis::Get(dst_axis))) {
209  new_src_layout_str += dst_axis->var->name_hint;
210  }
211  }
212  }
213  // 2) Now, add the primal axis of the current layout.
214  new_src_layout_str += this->name();
215  new_src_layout = Layout(new_src_layout_str);
216  return new_src_layout;
217  }
218 
226  inline int32_t IndexOf(const LayoutAxis& axis) const {
227  if (!this->defined()) return -1;
228  const auto axes = operator->()->axes;
229  for (size_t i = 0; i < axes.size(); ++i) {
230  if (axes[i]->var->name_hint == axis.name()) return static_cast<int32_t>(i);
231  }
232  return -1;
233  }
234 
242  int32_t FactorOf(const LayoutAxis& axis) const;
243 
249  bool Contains(const LayoutAxis& axis) const {
250  if (!defined()) return false;
251  for (const tir::IterVar var : operator->()->axes) {
252  if (var->var->name_hint == axis.name()) {
253  return true;
254  }
255  }
256  return false;
257  }
258 
259  const LayoutAxis& operator[](int32_t i) const {
260  ICHECK(defined()) << "Try to access axis from an undefined layout.";
261  int32_t index = i < 0 ? static_cast<int32_t>(ndim() + i) : i;
262  ICHECK(index >= 0 && static_cast<size_t>(index) < ndim()) << "Invalid index " << i;
263  const tir::IterVar axis = operator->()->axes[index];
264  return LayoutAxis::Get(axis);
265  }
266 
268  inline std::string name() const {
269  if (!defined()) return "__undef__";
270  return operator->()->name;
271  }
272 
278  inline bool Equals(const Layout& rhs) const { return name() == rhs.name(); }
279 
286  friend std::ostream& operator<<(std::ostream& os, const Layout& l) {
287  os << l.name();
288  return os;
289  }
290 
292 };
293 
294 // Internal node container BijectiveLayout
295 class BijectiveLayoutNode : public Object {
296  public:
307 
312 
314  v->Visit("src_layout", &src_layout);
315  v->Visit("dst_layout", &dst_layout);
316  v->Visit("index_forward_rule", &index_forward_rule);
317  v->Visit("index_backward_rule", &index_backward_rule);
318  v->Visit("shape_forward_rule", &shape_forward_rule);
319  v->Visit("shape_backward_rule", &shape_backward_rule);
320  }
321 
322  static constexpr const char* _type_key = "tir.BijectiveLayout";
324 };
325 
332 class BijectiveLayout : public ObjectRef {
333  public:
339  TVM_DLL BijectiveLayout(Layout src_layout, Layout dst_layout);
340 
341  // Given the source shape, infer the destination shape.
343  // Given the destination shape, recover the source shape.
344  TVM_DLL Array<PrimExpr> BackwardShape(const Array<PrimExpr>& dst_shape) const;
345  // Given the destination indices, infer the destination indices.
346  TVM_DLL Array<PrimExpr> ForwardIndex(const Array<PrimExpr>& index) const;
347  // Given the destination indices, recover the source indices.
348  TVM_DLL Array<PrimExpr> BackwardIndex(const Array<PrimExpr>& dst_index) const;
349 
351 };
352 
353 } // namespace tir
354 } // namespace tvm
355 
356 #endif // TVM_TIR_DATA_LAYOUT_H_
Visitor class to get the attributes of an AST/IR node. The content is going to be called for each fie...
Definition: reflection.h:52
Array, container representing a contiguous sequence of ObjectRefs.
Definition: array.h:289
Runtime primitive data type.
Definition: data_type.h:43
static DataType Int(int bits, int lanes=1)
Construct an int type.
Definition: data_type.h:219
Base class of all object reference.
Definition: object.h:519
bool defined() const
Definition: object.h:552
Object * get_mutable() const
Definition: object.h:607
base class of all object containers.
Definition: object.h:171
Reference to string objects.
Definition: string.h:98
Definition: data_layout.h:295
Array< PrimExpr > shape_backward_rule
Describes how destination shapes can be mapped to the source shapes.
Definition: data_layout.h:306
Layout src_layout
The source layout.
Definition: data_layout.h:309
Layout dst_layout
The destination layout.
Definition: data_layout.h:311
void VisitAttrs(AttrVisitor *v)
Definition: data_layout.h:313
Array< PrimExpr > index_forward_rule
Describes how source axes can be mapped to the destination axes, e.g., [i0 / 16, i1,...
Definition: data_layout.h:300
Array< PrimExpr > index_backward_rule
Describes how destination axes can be mapped to the source axes.
Definition: data_layout.h:302
Array< PrimExpr > shape_forward_rule
Describes how source shapes can be mapped to the destination shapes.
Definition: data_layout.h:304
TVM_DECLARE_FINAL_OBJECT_INFO(BijectiveLayoutNode, Object)
static constexpr const char * _type_key
Definition: data_layout.h:322
Bijective function mapping for data layout transformation. Given two Layout, BijectiveLayout build an...
Definition: data_layout.h:332
BijectiveLayout(Layout src_layout, Layout dst_layout)
The constructor.
Array< PrimExpr > ForwardShape(const Array< PrimExpr > &shape) const
TVM_DEFINE_OBJECT_REF_METHODS(BijectiveLayout, ObjectRef, BijectiveLayoutNode)
Array< PrimExpr > BackwardShape(const Array< PrimExpr > &dst_shape) const
Array< PrimExpr > BackwardIndex(const Array< PrimExpr > &dst_index) const
Array< PrimExpr > ForwardIndex(const Array< PrimExpr > &index) const
Iteration Variable, represents an iteration over an integer interval.
Definition: var.h:315
Definition: data_layout.h:42
std::string name() const
Definition: data_layout.h:53
static const LayoutAxis & Get(const char name)
const LayoutAxis & ToPrimal() const
Definition: data_layout.h:66
bool IsPrimal() const
Definition: data_layout.h:52
static const LayoutAxis & Get(const tir::IterVar &itvar)
const LayoutAxis & ToSubordinate() const
Definition: data_layout.h:69
const LayoutAxis & ToDual() const
Definition: data_layout.h:57
friend std::ostream & operator<<(std::ostream &os, const LayoutAxis &l)
Definition: data_layout.h:73
static const LayoutAxis & Get(const std::string &name)
bool operator==(const LayoutAxis &rhs) const
Definition: data_layout.h:71
Layout is to describe how data is organized within an N-dimention tensor. It is composed of upper cas...
Definition: data_layout.h:98
void VisitAttrs(AttrVisitor *v)
Definition: data_layout.h:110
Array< tir::IterVar > axes
specify each axis of the layout, in which the variable name is the name of the axis....
Definition: data_layout.h:108
TVM_DECLARE_FINAL_OBJECT_INFO(LayoutNode, Object)
static constexpr const char * _type_key
Definition: data_layout.h:115
String name
string representation of layout, "" for scalar.
Definition: data_layout.h:101
Managed reference to LayoutNode.
Definition: data_layout.h:123
Layout(const char *name)
construct from a string
Definition: data_layout.h:131
static const Layout & Undef()
Return an undefined layout.
Definition: data_layout.h:155
LayoutNode * operator->()
access the internal node container
Definition: data_layout.h:149
size_t ndim_primal() const
Definition: data_layout.h:186
bool Equals(const Layout &rhs) const
Whether the two layouts are equal.
Definition: data_layout.h:278
TVM_DEFINE_OBJECT_REF_METHODS(Layout, ObjectRef, LayoutNode)
friend std::ostream & operator<<(std::ostream &os, const Layout &l)
allow output string of layout to ostream
Definition: data_layout.h:286
Layout SubLayout(size_t pos, size_t len) const
Returns a sub-layout which is the portion of the object that starts at dimension pos and spans len di...
int32_t IndexOf(const LayoutAxis &axis) const
return the index of the input axis. If it is not found in the layout or the layout is undefined,...
Definition: data_layout.h:226
size_t ndim() const
Definition: data_layout.h:180
Layout ExpandPrimal(const Layout &dst_layout)
Returns a new layout where the dims have been expanded to match the primal dimensions.
Definition: data_layout.h:202
std::string name() const
Definition: data_layout.h:268
bool Contains(const LayoutAxis &axis) const
Whether the layout contains an axis.
Definition: data_layout.h:249
const LayoutAxis & operator[](int32_t i) const
Definition: data_layout.h:259
int32_t FactorOf(const LayoutAxis &axis) const
Get the factor size of the subordinate axis.
Layout(const tvm::String &name)
construct from a string
Definition: data_layout.h:128
Layout(const std::string &name, DataType dtype=DataType::Int(32))
construct from a string.
Layout(const Array< tir::IterVar > &axes)
Layout Split(const LayoutAxis &axis, size_t target_pos, int32_t factor) const
Split axis by size and put the sub-axis to position target_pos.
String name_hint
The hint to the variable name.
Definition: var.h:54
Var var(std::string name_hint, DataType t=DataType::Int(32))
Construct a new Var expression.
const Op & undef()
Returns an initialized but arbitrary value.
Tensor shape(const Tensor &src, DataType dtype, const std::string name="T_shape", const std::string tag=kInjective)
Get the shape of input tensor.
Definition: transform.h:1913
runtime implementation for LibTorch/TorchScript.
Definition: analyzer.h:36
TIR expressions.
Common operators defined for Expr.