tvm
Loading...
Searching...
No Matches
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_S_TIR_DATA_LAYOUT_H_
26#define TVM_S_TIR_DATA_LAYOUT_H_
27
28#include <tvm/base.h>
29#include <tvm/ffi/optional.h>
30#include <tvm/ffi/reflection/registry.h>
31#include <tvm/ir/prim/expr.h>
32#include <tvm/ir/prim/op.h>
33#include <tvm/s_tir/iter_var.h>
34
35#include <algorithm>
36#include <sstream>
37#include <string>
38#include <utility>
39#include <vector>
40
41#include "tvm/ir/expr.h"
42
43namespace tvm {
44namespace tirx {
45
46class SLayout;
47
49 public:
50 static const SLayoutAxis& Get(const char name);
51
52 // Get the singleton SLayoutAxis using itvar->var->name
53 static const SLayoutAxis& Get(const s_tir::IterVar& itvar);
54
55 // Get the singleton SLayoutAxis using name[0] (size of name must be 1).
56 static const SLayoutAxis& Get(const std::string& name);
57
58 inline bool IsPrimal() const { return name_ >= 'A' && name_ <= 'Z'; }
59 inline std::string name() const { return std::string(1, name_); }
60
61 // if current axis is primal, switch the axis to its subordinate one,
62 // else switch to the primal.
63 inline const SLayoutAxis& ToDual() const {
64 if (name_ >= 'A' && name_ <= 'Z') {
65 return SLayoutAxis::Get(name_ - 'A' + 'a');
66 } else {
67 return SLayoutAxis::Get(name_ - 'a' + 'A');
68 }
69 }
70
71 // return the primal axis. If it is already primal, return itself.
72 const SLayoutAxis& ToPrimal() const { return IsPrimal() ? *this : ToDual(); }
73
74 // return the subordinate axis. If it is already subordinate, return itself.
75 const SLayoutAxis& ToSubordinate() const { return IsPrimal() ? ToDual() : *this; }
76
77 inline bool operator==(const SLayoutAxis& rhs) const { return name_ == rhs.name_; }
78
79 friend std::ostream& operator<<(std::ostream& os, const SLayoutAxis& l) {
80 os << l.name();
81 return os;
82 }
83
84 private:
85 static const SLayoutAxis UPPER_CASE[];
86 static const SLayoutAxis LOWER_CASE[];
88 SLayoutAxis& operator=(const SLayoutAxis&);
89 explicit SLayoutAxis(const char name) : name_(name) {}
90
91 const char name_;
92};
93
104class SLayoutObj : public ffi::Object {
105 public:
107 ffi::String name;
114 ffi::Array<s_tir::IterVar> axes;
115
116 static void RegisterReflection() {
117 namespace refl = tvm::ffi::reflection;
118 refl::ObjectDef<SLayoutObj>()
119 .def_ro("name", &SLayoutObj::name)
120 .def_ro("axes", &SLayoutObj::axes);
121 }
122 TVM_FFI_DECLARE_OBJECT_INFO_FINAL("s_tir.SLayout", SLayoutObj, ffi::Object);
123};
124
129class SLayout : public ffi::ObjectRef {
130 public:
131 explicit SLayout(const ffi::Array<s_tir::IterVar>& axes);
132
134 SLayout(const tvm::ffi::String& name) : SLayout(name.operator std::string()) {} // NOLINT(*)
135
137 SLayout(const char* name) : SLayout(std::string(name)) {} // NOLINT(*)
138
149 TVM_DLL SLayout(const std::string& name, PrimType index_ty = PrimType::Int(32)); // NOLINT(*)
150 TVM_DLL static ffi::Optional<SLayout> Create(const std::string& name,
151 PrimType index_ty = PrimType::Int(32));
152
157 SLayoutObj* operator->() { return static_cast<SLayoutObj*>(get_mutable()); }
158
163 static ffi::Optional<SLayout> Undef() { return std::nullopt; }
164
171 static s_tir::IterVar PackIterVar(ffi::Array<s_tir::IterVar> iters);
172
179 static ffi::Array<s_tir::IterVar> UnpackIterVar(s_tir::IterVar packed_iter);
180
189 ffi::Optional<SLayout> SubLayout(size_t pos, size_t len) const;
190
198 SLayout Split(const SLayoutAxis& axis, size_t target_pos, int32_t factor) const;
199
201 inline size_t ndim() const {
202 if (!defined()) return 0;
203 return operator->()->axes.size();
204 }
205
207 inline size_t ndim_primal() const {
208 if (!defined()) return 0;
209 size_t ct = 0;
210 for (auto px : operator->()->axes) {
211 auto iter_vars = UnpackIterVar(px);
212 for (auto x : iter_vars) {
213 if (SLayoutAxis::Get(x).IsPrimal()) {
214 ct++;
215 }
216 }
217 }
218 return ct;
219 }
220
226 inline ffi::Optional<SLayout> ExpandPrimal(const SLayout& dst_layout) {
227 // 1) Find the axis which are missing in the current layout. Make them the prefix.
228 std::string new_src_layout_str = "";
229 for (auto packed_axis : dst_layout->axes) {
230 auto iter_vars = UnpackIterVar(packed_axis);
231 for (auto dst_axis : iter_vars) {
232 if (SLayoutAxis::Get(dst_axis).IsPrimal()) {
233 if (!this->Contains(SLayoutAxis::Get(dst_axis))) {
234 new_src_layout_str += dst_axis->var->name;
235 }
236 }
237 }
238 }
239 // 2) Now, add the primal axis of the current layout.
240 new_src_layout_str += this->name();
241 return SLayout::Create(new_src_layout_str);
242 }
243
251 inline int32_t IndexOf(const std::string& axis) const {
252 if (!this->defined()) return -1;
253 const auto axes = operator->()->axes;
254 for (size_t i = 0; i < axes.size(); ++i) {
255 if (axes[i]->var->name == axis) return static_cast<int32_t>(i);
256 }
257 return -1;
258 }
259
267 inline int32_t IndexOf(const SLayoutAxis& axis) const { return IndexOf(axis.name()); }
268
276 inline int32_t IndexOf(const s_tir::IterVar& iter) const { return IndexOf(iter->var->name); }
277
285 int32_t FactorOf(const SLayoutAxis& axis) const;
286
292 bool Contains(const SLayoutAxis& axis) const {
293 if (!defined()) return false;
294 for (const s_tir::IterVar packed_var : operator->()->axes) {
295 auto iter_vars = UnpackIterVar(packed_var);
296 for (auto var : iter_vars) {
297 if (var->var->name == axis.name()) {
298 return true;
299 }
300 }
301 }
302 return false;
303 }
304
305 const SLayoutAxis& operator[](int32_t i) const {
306 TVM_FFI_ICHECK(defined()) << "Try to access axis from an undefined layout.";
307 int32_t index = i < 0 ? static_cast<int32_t>(ndim() + i) : i;
308 TVM_FFI_ICHECK(index >= 0 && static_cast<size_t>(index) < ndim()) << "Invalid index " << i;
309 const s_tir::IterVar axis = operator->()->axes[index];
310 return SLayoutAxis::Get(axis);
311 }
312
313 s_tir::IterVar PackedAxisAt(int32_t i) const {
314 TVM_FFI_ICHECK(defined()) << "Try to access axis from an undefined layout.";
315 int32_t index = i < 0 ? static_cast<int32_t>(ndim() + i) : i;
316 TVM_FFI_ICHECK(index >= 0 && static_cast<size_t>(index) < ndim()) << "Invalid index " << i;
317 const s_tir::IterVar axis = operator->()->axes[index];
318 return axis;
319 }
320
322 inline std::string name() const {
323 if (!defined()) return "__undef__";
324 return operator->()->name;
325 }
326
332 inline bool Equals(const SLayout& rhs) const { return name() == rhs.name(); }
333
340 friend std::ostream& operator<<(std::ostream& os, const SLayout& l) {
341 os << l.name();
342 return os;
343 }
344
346};
347
348// Internal node container SBijectiveLayout
349class SBijectiveLayoutObj : public ffi::Object {
350 public:
351 explicit SBijectiveLayoutObj(ffi::UnsafeInit tag) : src_layout(tag), dst_layout(tag) {}
352
354 : src_layout(std::move(src)), dst_layout(std::move(dst)) {}
358 ffi::Array<PrimExpr> index_forward_rule;
360 ffi::Array<PrimExpr> index_backward_rule;
362 ffi::Array<PrimExpr> shape_forward_rule;
364 ffi::Array<PrimExpr> shape_backward_rule;
365
370
371 static void RegisterReflection() {
372 namespace refl = tvm::ffi::reflection;
373 refl::ObjectDef<SBijectiveLayoutObj>()
374 .def_ro("src_layout", &SBijectiveLayoutObj::src_layout)
375 .def_ro("dst_layout", &SBijectiveLayoutObj::dst_layout)
376 .def_ro("index_forward_rule", &SBijectiveLayoutObj::index_forward_rule)
377 .def_ro("index_backward_rule", &SBijectiveLayoutObj::index_backward_rule)
378 .def_ro("shape_forward_rule", &SBijectiveLayoutObj::shape_forward_rule)
379 .def_ro("shape_backward_rule", &SBijectiveLayoutObj::shape_backward_rule);
380 }
381 TVM_FFI_DECLARE_OBJECT_INFO_FINAL("s_tir.SBijectiveLayout", SBijectiveLayoutObj, ffi::Object);
382};
383
390class SBijectiveLayout : public ffi::ObjectRef {
391 public:
392 explicit SBijectiveLayout(ffi::UnsafeInit tag, ffi::ObjectPtr<SBijectiveLayoutObj> data)
393 : ffi::ObjectRef(tag) {
394 data_ = std::move(data);
395 }
396
402 TVM_DLL SBijectiveLayout(SLayout src_layout, SLayout dst_layout);
403 TVM_DLL static ffi::Optional<SBijectiveLayout> Create(SLayout src_layout, SLayout dst_layout);
404
405 // Given the source shape, infer the destination shape.
406 TVM_DLL ffi::Array<PrimExpr> ForwardShape(const ffi::Array<PrimExpr>& shape) const;
407 // Given the destination shape, recover the source shape.
408 TVM_DLL ffi::Array<PrimExpr> BackwardShape(const ffi::Array<PrimExpr>& dst_shape) const;
409 // Given the destination indices, infer the destination indices.
410 TVM_DLL ffi::Array<PrimExpr> ForwardIndex(const ffi::Array<PrimExpr>& index) const;
411 // Given the destination indices, recover the source indices.
412 TVM_DLL ffi::Array<PrimExpr> BackwardIndex(const ffi::Array<PrimExpr>& dst_index) const;
413
416};
417
418} // namespace tirx
419} // namespace tvm
420
421#endif // TVM_S_TIR_DATA_LAYOUT_H_
Base expr nodes in TVM.
TIR expressions.
Shared primitive construction and constant helpers.
Definition type.h:182
static TVM_TIRX_DLL PrimType Int(int bits, int lanes=1)
Construct a signed integer type with fixed lanes.
Iteration Variable, represents an iteration over an integer interval.
Definition iter_var.h:148
Definition data_layout.h:349
static void RegisterReflection()
Definition data_layout.h:371
SLayout src_layout
The source layout.
Definition data_layout.h:367
SBijectiveLayoutObj(ffi::UnsafeInit tag)
Definition data_layout.h:351
ffi::Array< PrimExpr > index_backward_rule
Describes how destination axes can be mapped to the source axes.
Definition data_layout.h:360
ffi::Array< PrimExpr > shape_forward_rule
Describes how source shapes can be mapped to the destination shapes.
Definition data_layout.h:362
SLayout dst_layout
The destination layout.
Definition data_layout.h:369
ffi::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:358
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("s_tir.SBijectiveLayout", SBijectiveLayoutObj, ffi::Object)
ffi::Array< PrimExpr > shape_backward_rule
Describes how destination shapes can be mapped to the source shapes.
Definition data_layout.h:364
SBijectiveLayoutObj(SLayout src, SLayout dst)
Definition data_layout.h:353
Bijective function mapping for data layout transformation. Given two SLayout, SBijectiveLayout build ...
Definition data_layout.h:390
static ffi::Optional< SBijectiveLayout > Create(SLayout src_layout, SLayout dst_layout)
SBijectiveLayout(SLayout src_layout, SLayout dst_layout)
The constructor.
ffi::Array< PrimExpr > BackwardIndex(const ffi::Array< PrimExpr > &dst_index) const
SBijectiveLayout(ffi::UnsafeInit tag, ffi::ObjectPtr< SBijectiveLayoutObj > data)
Definition data_layout.h:392
ffi::Array< PrimExpr > BackwardShape(const ffi::Array< PrimExpr > &dst_shape) const
ffi::Array< PrimExpr > ForwardIndex(const ffi::Array< PrimExpr > &index) const
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(SBijectiveLayout, ffi::ObjectRef, SBijectiveLayoutObj)
ffi::Array< PrimExpr > ForwardShape(const ffi::Array< PrimExpr > &shape) const
Definition data_layout.h:48
static const SLayoutAxis & Get(const char name)
bool IsPrimal() const
Definition data_layout.h:58
static const SLayoutAxis & Get(const s_tir::IterVar &itvar)
static const SLayoutAxis & Get(const std::string &name)
const SLayoutAxis & ToSubordinate() const
Definition data_layout.h:75
friend std::ostream & operator<<(std::ostream &os, const SLayoutAxis &l)
Definition data_layout.h:79
std::string name() const
Definition data_layout.h:59
bool operator==(const SLayoutAxis &rhs) const
Definition data_layout.h:77
const SLayoutAxis & ToDual() const
Definition data_layout.h:63
const SLayoutAxis & ToPrimal() const
Definition data_layout.h:72
SLayout is to describe how data is organized within an N-dimention tensor. It is composed of upper ca...
Definition data_layout.h:104
TVM_FFI_DECLARE_OBJECT_INFO_FINAL("s_tir.SLayout", SLayoutObj, ffi::Object)
ffi::Array< s_tir::IterVar > axes
specify each axis of the layout, in which the variable name is the name of the axis....
Definition data_layout.h:114
ffi::String name
string representation of layout, "" for scalar.
Definition data_layout.h:107
static void RegisterReflection()
Definition data_layout.h:116
Managed reference to SLayoutObj.
Definition data_layout.h:129
int32_t IndexOf(const std::string &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:251
friend std::ostream & operator<<(std::ostream &os, const SLayout &l)
allow output string of layout to ostream
Definition data_layout.h:340
size_t ndim() const
Definition data_layout.h:201
ffi::Optional< SLayout > ExpandPrimal(const SLayout &dst_layout)
Returns a new layout where the dims have been expanded to match the primal dimensions.
Definition data_layout.h:226
SLayout(const tvm::ffi::String &name)
construct from a string
Definition data_layout.h:134
int32_t IndexOf(const SLayoutAxis &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:267
static s_tir::IterVar PackIterVar(ffi::Array< s_tir::IterVar > iters)
Packs the Given Array of IterVars into a Single s_tir::IterVar. Each s_tir::IterVar in the Array shou...
s_tir::IterVar PackedAxisAt(int32_t i) const
Definition data_layout.h:313
SLayout Split(const SLayoutAxis &axis, size_t target_pos, int32_t factor) const
Split axis by size and put the sub-axis to position target_pos.
std::string name() const
Definition data_layout.h:322
bool Equals(const SLayout &rhs) const
Whether the two layouts are equal.
Definition data_layout.h:332
int32_t IndexOf(const s_tir::IterVar &iter) 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:276
SLayout(const char *name)
construct from a string
Definition data_layout.h:137
size_t ndim_primal() const
Definition data_layout.h:207
SLayout(const std::string &name, PrimType index_ty=PrimType::Int(32))
construct from a string.
ffi::Optional< SLayout > 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...
bool Contains(const SLayoutAxis &axis) const
Whether the layout contains an axis.
Definition data_layout.h:292
SLayoutObj * operator->()
access the internal node container
Definition data_layout.h:157
static ffi::Array< s_tir::IterVar > UnpackIterVar(s_tir::IterVar packed_iter)
Unpacks a Packed s_tir::IterVar into its constituents.
static ffi::Optional< SLayout > Undef()
Return an undefined layout.
Definition data_layout.h:163
const SLayoutAxis & operator[](int32_t i) const
Definition data_layout.h:305
TVM_FFI_DEFINE_OBJECT_REF_METHODS_NOTNULLABLE(SLayout, ffi::ObjectRef, SLayoutObj)
static ffi::Optional< SLayout > Create(const std::string &name, PrimType index_ty=PrimType::Int(32))
int32_t FactorOf(const SLayoutAxis &axis) const
Get the factor size of the subordinate axis.
SLayout(const ffi::Array< s_tir::IterVar > &axes)
Parent compiler symbol visibility.
Axis metadata for schedulable tensor computations.
An object that builds and maintains block scope and StmtSref mapping for Dependence analysis.
Definition analysis.h:41