forked from LearningInfiniTensor/TinyInfiniTensor
-
Notifications
You must be signed in to change notification settings - Fork 98
Expand file tree
/
Copy pathgraph.cc
More file actions
378 lines (333 loc) · 13.4 KB
/
graph.cc
File metadata and controls
378 lines (333 loc) · 13.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
#include "core/graph.h"
#include "core/blob.h"
#include "operators/transpose.h"
#include "operators/matmul.h"
#include <algorithm>
#include <numeric>
#include <queue>
namespace infini
{
void GraphObj::addOperatorAndConnect(const Operator &op)
{
sorted = false;
ops.push_back(op);
for (auto &input : op->getInputs())
{
if (input)
{
input->addTarget(op);
if (auto pred = input->getSource())
{
pred->addSuccessors(op);
op->addPredecessors(pred);
}
}
}
for (auto &output : op->getOutputs())
{
if (output)
{
output->setSource(op);
for (auto &succ : output->getTargets())
{
succ->addPredecessors(op);
op->addSuccessors(succ);
}
}
}
}
string GraphObj::toString() const
{
std::ostringstream oss;
oss << "Graph Tensors:\n";
for (const auto &tensor : tensors)
oss << tensor << "\n";
oss << "Graph operators:\n";
for (const auto &op : ops)
{
vector<UidBaseType> preds, succs;
for (auto &o : op->getPredecessors())
preds.emplace_back(o->getGuid());
for (auto &o : op->getSuccessors())
succs.emplace_back(o->getGuid());
oss << "OP " << op->getGuid();
oss << ", pred " << vecToString(preds);
oss << ", succ " << vecToString(succs);
oss << ", " << op << "\n";
}
return oss.str();
}
bool GraphObj::topo_sort()
{
if (this->sorted)
{
return true;
}
std::vector<Operator> sorted;
std::unordered_set<OperatorObj *> flags;
sorted.reserve(ops.size());
flags.reserve(ops.size());
while (sorted.size() < ops.size())
{
// Any node is move to sorted in this loop.
auto modified = false;
for (auto const &op : ops)
{
if (auto const &inputs = op->getInputs();
flags.find(op.get()) == flags.end() &&
std::all_of(inputs.begin(), inputs.end(),
[&flags](auto const &input)
{
auto ptr = input->getSource().get();
return !ptr || flags.find(ptr) != flags.end();
}))
{
modified = true;
sorted.emplace_back(op);
flags.insert(op.get());
}
}
if (!modified)
{
return false;
}
}
this->ops = std::move(sorted);
return this->sorted = true;
}
void GraphObj::optimize()
{
// =================================== 作业 ===================================
// TODO: 设计一个算法来实现指定的图优化规则
// 图优化规则如下:
// 1. 去除冗余的算子(例如,两个相邻的算子都是 transpose 算子,且做的是相反的操作,可以将其全部删除)
// 2. 合并算子(例如,矩阵乘算子中含有属性transA、transB,如果其输入存在transpose,且对最后两个维度做交换,就可以将transpose融入到矩阵乘算子的属性中去)
// =================================== 作业 ===================================
// 第一轮:消除相反的transpose
for (size_t i = 0; i < ops.size(); ++i) {
auto op = ops[i];
if (op->getOpType() != OpType::Transpose) continue;
auto transposeOp = as<TransposeObj>(op);
auto input = transposeOp->getInputs()[0];
auto output = transposeOp->getOutput();
auto permute = transposeOp->getPermute();
auto sourceOp = input->getSource();
if (!sourceOp) continue;
if (sourceOp->getOpType() != OpType::Transpose) continue;
auto prevTranspose = as<TransposeObj>(sourceOp);
auto prevPermute = prevTranspose->getPermute();
bool isInverse = true;
for (size_t j = 0; j < permute.size() && j < prevPermute.size(); ++j) {
if (permute[prevPermute[j]] != j) {
isInverse = false;
break;
}
}
if (isInverse) {
auto prevInput = prevTranspose->getInputs()[0];
auto prevOutput = prevTranspose->getOutput();
for (auto target : output->getTargets()) {
target->replaceInput(output, prevInput);
}
// 清理前驱/后继关系
for (auto suc : prevTranspose->getSuccessors()) {
auto it = std::find(suc->getPredecessors().begin(), suc->getPredecessors().end(), prevTranspose);
if (it != suc->getPredecessors().end()) {
suc->getPredecessors().erase(it);
}
}
for (auto suc : transposeOp->getSuccessors()) {
auto it = std::find(suc->getPredecessors().begin(), suc->getPredecessors().end(), transposeOp);
if (it != suc->getPredecessors().end()) {
suc->getPredecessors().erase(it);
}
}
prevTranspose->getSuccessors().clear();
transposeOp->getSuccessors().clear();
prevTranspose->getPredecessors().clear();
transposeOp->getPredecessors().clear();
removeOperator(prevTranspose);
removeOperator(transposeOp);
removeTensor(prevOutput);
removeTensor(output);
// 重新开始
i = 0;
}
}
// 第二轮:融合transpose到matmul
for (size_t i = 0; i < ops.size(); ++i) {
auto op = ops[i];
if (op->getOpType() != OpType::MatMul) continue;
auto matmulOp = as<MatmulObj>(op);
for (int j = 0; j < 2; ++j) {
auto input = matmulOp->getInputs(j);
if (!input) continue;
auto sourceOp = input->getSource();
if (!sourceOp) continue;
if (sourceOp->getOpType() != OpType::Transpose) continue;
auto transposeOp = as<TransposeObj>(sourceOp);
auto permute = transposeOp->getPermute();
auto inputShape = input->getDims();
int rank = inputShape.size();
if (rank < 2) continue;
bool swapsLastTwo = (permute[rank - 2] == rank - 1) &&
(permute[rank - 1] == rank - 2);
bool keepsOthers = true;
for (int k = 0; k < rank - 2; ++k) {
if (permute[k] != k) {
keepsOthers = false;
break;
}
}
if (swapsLastTwo && keepsOthers) {
auto transposeInput = transposeOp->getInputs()[0];
if (!transposeInput) continue;
matmulOp->replaceInput(input, transposeInput);
if (j == 0) {
matmulOp->setTransA(!matmulOp->getTransA());
} else {
matmulOp->setTransB(!matmulOp->getTransB());
}
// 清理前驱/后继关系
for (auto suc : transposeOp->getSuccessors()) {
auto it = std::find(suc->getPredecessors().begin(), suc->getPredecessors().end(), transposeOp);
if (it != suc->getPredecessors().end()) {
suc->getPredecessors().erase(it);
}
}
transposeOp->getSuccessors().clear();
transposeOp->getPredecessors().clear();
removeOperator(transposeOp);
removeTensor(input);
// 重新开始
i = 0;
break;
}
}
}
}
Tensor GraphObj::getTensor(int fuid) const
{
for (auto tensor : tensors)
{
if (tensor->getFuid() == fuid)
{
return tensor;
}
}
return nullptr;
}
void GraphObj::shape_infer()
{
for (auto &op : ops)
{
auto ans = op->inferShape();
IT_ASSERT(ans.has_value());
auto oldOutputs = op->getOutputs();
IT_ASSERT(ans.value().size() == oldOutputs.size());
// replace the old outputshape and size with new one
for (int i = 0; i < (int)ans.value().size(); ++i)
{
if (!oldOutputs[i]) continue;
auto newShape = ans.value()[i];
auto oldShape = oldOutputs[i]->getDims();
auto fuid = oldOutputs[i]->getFuid();
if (newShape != oldShape)
{
auto tensor = this->getTensor(fuid);
tensor->setShape(newShape);
}
}
}
}
void GraphObj::dataMalloc()
{
// topological sorting first
IT_ASSERT(topo_sort() == true);
// =================================== 作业 ===================================
// TODO:利用 allocator 给计算图分配内存
// HINT: 获取分配好的内存指针后,可以调用 tensor 的 setDataBlob 函数给 tensor 绑定内存
// =================================== 作业 ===================================
shape_infer();
std::vector<size_t> offsets;
offsets.reserve(tensors.size());
for (auto &tensor : tensors) {
size_t size = tensor->getBytes();
offsets.push_back(allocator.alloc(size));
}
void *base_ptr = allocator.getPtr();
for (size_t i = 0; i < tensors.size(); ++i) {
void *tensor_ptr = static_cast<char *>(base_ptr) + offsets[i];
Blob blob = make_ref<BlobObj>(runtime, tensor_ptr);
tensors[i]->setDataBlob(blob);
}
allocator.info();
}
Tensor GraphObj::addTensor(Shape dim, DataType dtype)
{
return tensors.emplace_back(make_ref<TensorObj>(dim, dtype, runtime));
}
Tensor GraphObj::addTensor(const Tensor &tensor)
{
IT_ASSERT(tensor->getRuntime() == runtime,
std::string("Tensor runtime mismatch: cannot add a tenosr in ") +
tensor->getRuntime()->toString() + " to " +
runtime->toString());
tensors.emplace_back(tensor);
return tensor;
}
TensorVec GraphObj::addTensor(const TensorVec &tensors)
{
for (auto &t : tensors)
addTensor(t);
return tensors;
}
// tensor's "source" and "target" must be in "ops".
// tensor has no "source" and no "target" must not exist.
// "inputs" or "outputs" of operators must be in "tensors"
// "predecessors" and "successors" of an operator of "ops" must be in "ops".
bool GraphObj::checkValid() const
{
for (auto tensor : tensors)
{
IT_ASSERT(!(tensor->getTargets().size() == 0 &&
nullptr == tensor->getSource()));
for (auto op : tensor->getTargets())
{
IT_ASSERT(std::find(ops.begin(), ops.end(), op) != ops.end());
}
auto op = tensor->getSource();
IT_ASSERT(!(op && std::find(ops.begin(), ops.end(), op) == ops.end()));
}
for (auto op : ops)
{
for (auto tensor : op->getInputs())
{
IT_ASSERT(std::find(tensors.begin(), tensors.end(), tensor) !=
tensors.end());
}
for (auto tensor : op->getOutputs())
{
IT_ASSERT(std::find(tensors.begin(), tensors.end(), tensor) !=
tensors.end());
}
for (auto pre : op->getPredecessors())
{
IT_ASSERT(std::find(ops.begin(), ops.end(), pre) != ops.end());
}
for (auto suc : op->getSuccessors())
{
IT_ASSERT(std::find(ops.begin(), ops.end(), suc) != ops.end());
}
}
std::set<UidBaseType> s;
// check whether two tensors with the same FUID exist
for (auto tensor : tensors)
{
int cnt = s.count(tensor->getFuid());
IT_ASSERT(cnt == 0, std::to_string(tensor->getFuid()));
s.insert(tensor->getFuid());
}
return true;
}
} // namespace infini