forked from alibaba/MNN
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathExpr.cpp
1375 lines (1324 loc) · 50.1 KB
/
Expr.cpp
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//
// Expr.cpp
// MNN
//
// Created by MNN on 2019/06/10.
// Copyright © 2018, Alibaba Group Holding Limited
//
#define FLATBUFFERS_PREFER_PRINTF
#include <MNN/expr/Expr.hpp>
#include <MNN/expr/Executor.hpp>
#include <MNN/expr/ExprCreator.hpp>
#include "Utils.hpp"
#include "RuntimeAttr.hpp"
#include "core/FileLoader.hpp"
#include "core/TensorUtils.hpp"
#include "core/WrapExecution.hpp"
#include "utils/InitNet.hpp"
//#define MNN_OPEN_TIME_TRACE
#include "MNN/AutoTime.hpp"
#include "MNN/expr/ExecutorScope.hpp"
#include "half.hpp"
#include "geometry/GeometryComputer.hpp"
#include "geometry/GeometryComputerUtils.hpp"
//#define MNN_EXPRESS_ERROR_REPORT
static inline std::string numberToString(int index) {
char s[10];
snprintf(s, 10, "%d", index);
return std::string(s);
}
static bool HasUnknownDim(const std::vector<int>& dims) {
for (const int& dim : dims) {
if (dim < 0) {
return true;
}
}
return false;
}
namespace MNN {
namespace Express {
void Variable::Info::syncSize() {
size = 1;
for (int i=0; i<dim.size(); ++i) {
if (dim[i] <= 0) {
// Not valid
size = 0;
return;
}
if (order == NC4HW4 && i == 1) {
size *= (UP_DIV(dim[1], 4) * 4);
} else {
size *= dim[i];
}
}
}
bool VARP::fix(VARP::InputType type) const {
if (nullptr == mContent->expr().first->get()) {
mContent->expr().first->mType = type;
return true;
}
auto info = mContent->getInfo();
if (nullptr == info) {
return false;
}
auto exprInfo = mContent->expr();
auto inside = exprInfo.first->inside();
auto mFrom = exprInfo.first;
auto cache = mFrom->inside()->mCache;
if (nullptr == cache) {
ExecutorScope::Current()->makeCache({mFrom}, false);
cache = mFrom->inside()->mCache;
}
if (nullptr == cache) {
return false;
}
if (NO_ERROR != cache->compute()) {
return false;
}
auto inputTensor = inside->mCache->getSession()->getTensor(inside->mCacheOffset + exprInfo.second);
auto tensor = Tensor::clone(inputTensor);
VARP newVARP = Express::Variable::create(Express::Expr::create(tensor, true));
newVARP->expr().first->mType = type;
auto& pipelineInfo = inside->mCache->getSession()->getPipelineInfo(0);
if (TensorUtils::getDescribeOrigin(tensor)->getBackend() == pipelineInfo.first.cache.first.get()) {
newVARP->expr().first->inside()->mHoldBackend = pipelineInfo.first.cache.first;
} else if (TensorUtils::getDescribeOrigin(tensor)->getBackend() == pipelineInfo.first.cache.second.get()) {
newVARP->expr().first->inside()->mHoldBackend = pipelineInfo.first.cache.second;
}
Variable::replace(VARP(mContent), newVARP);
inputTensor->wait(MNN::Tensor::MAP_TENSOR_READ, true);
return true;
}
Expr::Expr(int outputSize) {
mInside.reset(new Inside(outputSize));
mOutputNames.resize(outputSize);
}
Expr::Expr(Tensor* tensor, bool own) {
mInside.reset(new Inside(tensor, own));
mOutputNames.resize(1);
}
Expr::~Expr() {
mInside.reset();
}
Variable::Info* Expr::outputInfo(int index) const {
return mInside->mOutputInfos.data() + index;
}
void Expr::_addLinkForInputs(EXPRP expr) {
auto inputs = expr->inputs();
for (int i=0; i<inputs.size(); ++i) {
if (inputs[i].get() == nullptr) {
continue;
}
bool findEmpty = false;
auto inputExpr = inputs[i]->mFrom;
for (int j=0; j<inputExpr->mTo.size(); ++j) {
auto ref = inputExpr->mTo[j].lock();
if (nullptr == ref) {
inputExpr->mTo[j] = WeakEXPRP(expr);
findEmpty = true;
break;
}
}
if (!findEmpty) {
inputExpr->mTo.emplace_back(WeakEXPRP(expr));
}
}
}
EXPRP Expr::create(Tensor* tensor, bool own) {
EXPRP expr(new Expr(tensor, own));
expr->mOp = nullptr;
expr->mType = VARP::CONSTANT;
auto& dstInfo = expr->mInside->mOutputInfos[0];
expr->mInside->mInfoDirty = false;
expr->mInside->mContentDirty = false;
return expr;
}
EXPRP Expr::create(Variable::Info&& info, const void* ptr, VARP::InputType type, Expr::MemoryType memtype) {
EXPRP expr(new Expr(1));
expr->mOp = nullptr;
auto originPtr = ptr;
expr->mInside->mOutputInfos[0] = std::move(info);
auto& dstInfo = expr->mInside->mOutputInfos[0];
expr->mInside->mInfoDirty = false;
dstInfo.syncSize();
Utils::copyInfoToTensor(expr->mInside->mOutputTensors[0], expr->mInside->mOutputInfos.data());
expr->mType = type;
if (type == VARP::CONSTANT) {
TensorUtils::getDescribe(expr->mInside->mOutputTensors[0])->usage = Tensor::InsideDescribe::CONSTANT;
TensorUtils::getDescribe(expr->mInside->mOutputTensors[0])->isMutable = false;
} else if (type == VARP::INPUT) {
TensorUtils::getDescribe(expr->mInside->mOutputTensors[0])->usage = Tensor::InsideDescribe::INPUT;
} else {
// VARP::TRAINABLE
TensorUtils::getDescribe(expr->mInside->mOutputTensors[0])->usage = Tensor::InsideDescribe::TRAINABLE;
}
if (dstInfo.size > 0 && memtype == COPY) {
auto res = Utils::allocMemoryForHostTensor(expr->mInside->mOutputTensors[0]);
if (!res) {
MNN_ASSERT(false);
return nullptr;
}
} else {
expr->mInside->mOutputTensors[0]->buffer().host = nullptr;
}
if (nullptr == originPtr) {
if (type == VARP::INPUT && dstInfo.size > 0) {
expr->mInside->mContentDirty = true;
}
return expr;
}
expr->mInside->mContentDirty = false;
if (memtype == COPY) {
size_t total_size = dstInfo.size;
total_size *= dstInfo.type.bytes();
::memcpy(expr->mInside->mOutputTensors[0]->buffer().host, originPtr, total_size);
} else {
expr->mInside->mOutputTensors[0]->buffer().host = (uint8_t*)originPtr;
if (memtype == REF) {
TensorUtils::getDescribe(expr->mInside->mOutputTensors[0])->memoryType = Tensor::InsideDescribe::MEMORY_OUTSIDE;
}
}
return expr;
}
EXPRP Expr::create(std::shared_ptr<BufferStorage> extra, std::vector<VARP>&& inputs, int outputSize) {
EXPRP expr(new Expr(outputSize));
expr->mStorage = extra;
expr->mOp = flatbuffers::GetRoot<Op>(extra->buffer());
switch (expr->mOp->type()) {
case OpType_Const:
expr->mType = VARP::CONSTANT;
break;
case OpType_TrainableParam:
expr->mType = VARP::TRAINABLE;
break;
default:
expr->mType = VARP::INPUT;
break;
}
expr->mInputs = std::move(inputs);
auto exe = ExecutorScope::Current();
expr->mInside->mReq = exe->getRequirement(expr.get());
if ((!(exe->getLazyMode() & Executor::LAZY_COMPUTE_ONCE)) && exe->lazyEval) {
_addLinkForInputs(expr);
}
return expr;
}
EXPRP Expr::create(const OpT* op, std::vector<VARP> inputs, int outputSize) {
if (OpType_Input == op->type) {
Variable::Info info;
info.dim = op->main.AsInput()->dims;
if (info.dim.size() >= 1 && -1 == info.dim[0]) {
info.dim[0] = 1;
}
info.order = Utils::revertFormat(op->main.AsInput()->dformat);
info.type = Utils::revertDataType(op->main.AsInput()->dtype);
return create(std::move(info), nullptr, VARP::INPUT);
}
if (OpType_Const == op->type || OpType_TrainableParam == op->type) {
if (!op->externalPath.empty()) {
flatbuffers::FlatBufferBuilder builder;
auto offset = Op::Pack(builder, op);
builder.Finish(offset);
std::shared_ptr<BufferStorage> extra(new BufferStorage);
extra->storage = builder.ReleaseRaw(extra->allocated_size, extra->offset);
auto resExpr = Expr::create(extra, std::move(inputs), outputSize);
resExpr->setName(op->name);
return resExpr;
}
Variable::Info info;
info.dim = op->main.AsBlob()->dims;
info.order = Utils::revertFormat(op->main.AsBlob()->dataFormat);
void* ptr = nullptr;
info.type = Utils::revertDataType(op->main.AsBlob()->dataType);
info.syncSize();
switch (op->main.AsBlob()->dataType) {
case DataType_DT_INT8:
ptr = (void*)op->main.AsBlob()->int8s.data();
break;
case DataType_DT_INT32:
ptr = (void*)op->main.AsBlob()->int32s.data();
break;
case DataType_DT_UINT8:
ptr = (void*)op->main.AsBlob()->uint8s.data();
break;
case DataType_DT_FLOAT:
ptr = (void*)op->main.AsBlob()->float32s.data();
break;
case DataType_DT_BFLOAT16:
ptr = (void*)op->main.AsBlob()->uint8s.data();
break;
default:
break;
}
Expr::MemoryType memtype = Expr::MemoryType::COPY;
if (op->main.AsBlob()->dataType == DataType_DT_HALF) {
auto src = (half_float::half*)op->main.AsBlob()->uint8s.data();
ptr = MNNMemoryAllocAlign(info.size * sizeof(float), MNN_MEMORY_ALIGN_DEFAULT);
if (nullptr == src || nullptr == ptr) {
EXPRP empty;
return empty;
}
auto outputPtr = (float*)ptr;
for (int i=0; i<info.size; ++i) {
outputPtr[i] = src[i];
}
memtype = Expr::MemoryType::MOVE;
}
//MNN_ASSERT(nullptr != ptr);
auto expr = create(std::move(info), ptr, VARP::CONSTANT, memtype);
if (OpType_TrainableParam == op->type && nullptr != ptr) {
expr->mType = VARP::TRAINABLE;
}
return expr;
}
flatbuffers::FlatBufferBuilder builder;
auto offset = Op::Pack(builder, op);
builder.Finish(offset);
std::shared_ptr<BufferStorage> extra(new BufferStorage);
extra->storage = builder.ReleaseRaw(extra->allocated_size, extra->offset);
auto resExpr = Expr::create(extra, std::move(inputs), outputSize);
resExpr->setName(op->name);
return resExpr;
}
void Expr::setName(const std::string& name) {
mName = name;
}
bool Expr::requireInfo() {
if (!mInside->mInfoDirty) {
return true;
}
if (!mValid) {
return false;
}
if (nullptr == mOp) {
return !HasUnknownDim(mInside->mOutputInfos[0].dim);
}
if (!mCanDecompose) {
return true;
}
bool ready = true;
for (int i = 0; i < mInputs.size(); ++i) {
if (nullptr == mInputs[i] || nullptr == mInputs[i]->mFrom) {
// The Variable is set nullptr by api
return false;
}
auto inputInfo = mInputs[i]->getInfo();
if (nullptr == inputInfo) {
#ifdef MNN_EXPRESS_ERROR_REPORT
MNN_ERROR("%s, %d input not ready\n", mName.c_str(), i);
#endif
mValid = false;
return false;
}
}
for (int i = 0; i < mInputs.size(); ++i) {
auto& v = mInputs[i];
if (v->getInfo()->size == 0) {
// zero shape
continue;
}
if (mInside->mReq.shapeNeedContent[i]) {
// For shape need content, the content must not be nullptr
auto ptr = v->readInternal(true);
if (nullptr == ptr) {
ready = false;
break;
}
}
}
if (!ready) {
return false;
}
//MNN_PRINT("Info %s, %p Start\n", mName.c_str(), this);
auto res = ExecutorScope::Current()->computeInfo(this);
//MNN_PRINT("Info Compute %s\n", mName.c_str());
if (NO_ERROR == res) {
mInside->mInfoDirty = false;
} else {
mValid = false;
}
return NO_ERROR == res;
}
size_t Variable::linkNumber() const {
return mFrom->outputs().size();
}
const std::vector<WeakEXPRP>& Variable::toExprs() const {
return mFrom->outputs();
}
VARP Variable::create(EXPRP expr, int index) {
VARP res(new Variable(expr, index));
#ifdef MNN_EXPR_SHAPE_EAGER
auto info = expr->requireInfo();
if (!info) {
#ifdef MNN_EXPRESS_ERROR_REPORT
MNN_ERROR("Can't compute shape\n");
#endif
}
#endif
auto executor = ExecutorScope::Current();
if (!executor->lazyEval) {
res.fix(VARP::CONSTANT);
return res;
}
// CONTENT Mode, Use Geometry Computer to Decompress Expr
do {
if (!(executor->getLazyMode() & Executor::LAZY_CONTENT)) {
break;
}
if (expr->get() == nullptr) {
break;
}
if (!expr->mCanDecompose) {
break;
}
bool res = expr->requireInfo();
if (!res) {
break;
}
std::map<Tensor*, VARP> varMap;
std::vector<Tensor*> inputTensors(expr->mInputs.size());
std::vector<Tensor*> outputTensors(expr->outputSize());
for (int i=0; i<inputTensors.size(); ++i) {
inputTensors[i] = Utils::getTensor(expr->mInputs[i]);
varMap.insert(std::make_pair(inputTensors[i], expr->mInputs[i]));
}
for (int i=0; i<outputTensors.size(); ++i) {
outputTensors[i] = expr->mInside->mOutputTensors[i];
}
auto bn = executor->getAttr()->constantBackend;
// TODO: Support set mask
GeometryComputer::Context context(Interpreter::GeometryComputeMask::GEOMETRCOMPUTEMASK_ALL, bn);
auto geo = GeometryComputer::search(expr->get()->type(), Runtime::Compiler_Loop);
CommandBuffer cmd;
res = geo->onCompute(expr->get(), inputTensors, outputTensors, context, cmd);
if (!res) {
break;
}
for (int i=0; i<outputTensors.size(); ++i) {
// Avoid release from host tensor, the memory is owned by executor's cpu runtime
if (TensorUtils::getDescribe(outputTensors[i])->usage == Tensor::InsideDescribe::CONSTANT) {
TensorUtils::getDescribe(outputTensors[i])->memoryType = Tensor::InsideDescribe::MEMORY_BACKEND;
}
}
if (TensorUtils::getDescribe(outputTensors[index])->usage == Tensor::InsideDescribe::CONSTANT) {
auto constExpr = Expr::create(Tensor::clone(outputTensors[index]), true);
return Variable::create(constExpr);
}
// TODO: For multi-output expr, reduce dup compute
CommandBuffer cmdDst;
GeometryComputerUtils::makeRaster(cmd, cmdDst, context);
for (auto t : outputTensors) {
context.getRasterCacheCreateRecursive(t, cmdDst);
}
// Make New Exprs
for (int cmdIndex=0; cmdIndex < cmdDst.command.size(); ++cmdIndex) {
auto& cmd = cmdDst.command[cmdIndex];
std::vector<VARP> cmdInputs(cmd->inputs.size());
for (int i=0; i<cmd->inputs.size(); ++i) {
auto iter = varMap.find(cmd->inputs[i]);
if (iter == varMap.end()) {
// Extract Const Value
auto constExpr = Expr::create(Tensor::clone(cmd->inputs[i]), true);
VARP constVar(new Variable(constExpr, 0));
varMap.insert(std::make_pair(cmd->inputs[i], constVar));
cmdInputs[i] = constVar;
} else {
cmdInputs[i] = iter->second;
}
}
EXPRP currentExpr;
if (cmd->op->type() == OpType_Raster) {
// Rebuild raster buffer
auto cmdTensor = cmd->outputs[0];
auto cmdDes = TensorUtils::getDescribe(cmdTensor);
MNN_ASSERT(cmd->inputs.size() == cmdDes->regions.size());
std::vector<int> regions(cmdDes->regions.size() * 11);
for (int j=0; j<cmdDes->regions.size(); ++j) {
auto& srcReg = cmdDes->regions[j];
auto dstInt = regions.data() + 11 * j;
dstInt[0] = srcReg.src.offset;
::memcpy(dstInt + 1, srcReg.src.stride, 3 * sizeof(int));
dstInt[4] = srcReg.dst.offset;
::memcpy(dstInt + 5, srcReg.dst.stride, 3 * sizeof(int));
::memcpy(dstInt + 8, srcReg.size, 3 * sizeof(int));
}
auto cmdExpr = Utils::makeRaster(cmdInputs, regions, cmdTensor->shape(), cmdTensor->getType(), TensorUtils::getDescribe(cmdTensor)->dimensionFormat);
cmdExpr->mCanDecompose = false;
VARP cmdVar(new Variable(cmdExpr, 0));
varMap.insert(std::make_pair(cmdTensor, cmdVar));
currentExpr = cmdVar->mFrom;
} else {
EXPRP cmdExpr;
if (cmd->op == expr->get()) {
cmdExpr = Expr::create(expr->mStorage, std::move(cmdInputs), cmd->outputs.size());
} else {
cmdExpr = Expr::create(cmd->buffer, std::move(cmdInputs), cmd->outputs.size());
}
currentExpr = cmdExpr;
cmdExpr->mCanDecompose = false;
for (int j=0; j<cmd->outputs.size(); ++j) {
VARP cmdVar(new Variable(cmdExpr, j));
varMap.insert(std::make_pair(cmd->outputs[j], cmdVar));
}
}
for (int j=0; j<cmd->outputs.size(); ++j) {
Utils::copyTensorToInfo(currentExpr->inside()->mOutputInfos.data() + j, cmd->outputs[j]);
TensorUtils::copyShape(cmd->outputs[j], currentExpr->inside()->mOutputTensors[j], true, true);
}
}
return varMap.find(expr->inside()->mOutputTensors[index])->second;
} while (false);
return res;
}
void Expr::replace(EXPRP old, EXPRP from) {
if (old.get() == from.get()) {
return;
}
for (auto input : old->inputs()) {
if (input.get() == nullptr) {
continue;
}
for (int j=0; j<input->mFrom->mTo.size(); ++j) {
auto ref = input->mFrom->mTo[j].lock();
if (ref.get() == old.get()) {
input->mFrom->mTo[j].reset();
}
}
}
for (auto input : from->inputs()) {
if (input.get() == nullptr) {
continue;
}
bool hasSet = false;
for (int j=0; j<input->mFrom->mTo.size(); ++j) {
auto ref = input->mFrom->mTo[j].lock();
if (ref.get() == old.get()) {
hasSet = true;
break;
}
}
if (!hasSet) {
for (int j=0; j<input->mFrom->mTo.size(); ++j) {
auto ref = input->mFrom->mTo[j].lock();
if (nullptr == ref) {
input->mFrom->mTo[j] = WeakEXPRP(old);
hasSet = true;
break;
}
}
}
if (!hasSet) {
input->mFrom->mTo.emplace_back(WeakEXPRP(old));
}
}
old->mCanDecompose = from->mCanDecompose;
old->mOp = from->mOp;
old->mName = from->mName;
old->mOutputNames = from->mOutputNames;
old->mStorage = from->mStorage;
old->mType = from->mType;
old->mValid = from->mValid;
old->mInside = from->mInside;
old->mInputs = from->mInputs;
std::vector<Expr*> visited;
old->visitOutputs([&](EXPRP expr, int index) {
if (expr->visited()) {
return false;
}
visited.emplace_back(expr.get());
expr->setVisited(true);
expr->mInside->mCache.reset();
expr->mInside->mCacheOffset = 0;
expr->mValid = true;
expr->mInside->mInfoDirty = true;
return true;
});
for (auto e : visited) {
e->setVisited(false);
}
}
void Variable::setName(const std::string& name) {
mFrom->mOutputNames[mFromIndex] = name;
if (mFrom->name().empty()) {
mFrom->setName(name);
}
}
bool Variable::setDevicePtr(const void* devicePtr, int memoryType) {
if (nullptr != mFrom->get()) {
MNN_ERROR("Can't setDevicePtr to no-input op\n");
return false;
}
informDirty();
MNN_ASSERT(TensorUtils::getDescribe(mFrom->inside()->mOutputTensors[0])->quantAttr == nullptr || TensorUtils::getDescribe(mFrom->inside()->mOutputTensors[0])->type == DataType_DT_FLOAT);
mFrom->mInside->mContentDirty = false;
// Clear host address, Don't malloc hostPtr afterwards
Utils::releaseMemoryForHostTensor(mFrom->inside()->mOutputTensors[0]);
return mFrom->inside()->mOutputTensors[0]->setDevicePtr(devicePtr, memoryType);
}
bool Variable::copyToDevicePtr(void* devicePtr, int memoryType) {
if (nullptr != mFrom->get()) {
MNN_ERROR("Can't copyToDevicePtr to no-input op\n");
return false;
}
auto inside = mFrom->inside();
auto originTensor = inside->mOutputTensors[mFromIndex];
auto bn = TensorUtils::getDescribeOrigin(originTensor)->getBackend();
if(bn == nullptr) {
MNN_ERROR("Error: Varp copyToDevicePtr can't find backend\n");
return false;
}
MNN::Tensor tempTensor(originTensor->dimensions(), originTensor->getDimensionType());
tempTensor.setDevicePtr(devicePtr, memoryType);
TensorUtils::getDescribeOrigin(originTensor)->getBackend()->onCopyBuffer(originTensor, &tempTensor);
// Sync the result
tempTensor.wait(Tensor::MAP_TENSOR_READ, true);
return true;
}
const std::string& Variable::name() const {
return mFrom->outputName(mFromIndex);
}
const Tensor* Variable::getTensor() const {
auto inside = mFrom->inside();
auto inputTensor = inside->mOutputTensors[mFromIndex];
if (nullptr != inside->mCache) {
inputTensor = inside->mCache->getSession()->getTensor(inside->mCacheOffset + mFromIndex);
}
return inputTensor;
}
bool Variable::input(VARP src) {
if (nullptr != mFrom->get()) {
MNN_ERROR("Can't input to no-input op\n");
return false;
}
if (nullptr == src) {
/*Close the Input*/
mFrom->visitOutputs([](EXPRP expr, int index) {
auto recurse = expr->mValid; expr->mValid = false;
return recurse;
});
mFrom->mValid = false;
return false;
}
auto info = src->getInfo();
std::shared_ptr<Variable::Info> tempInfo;
if (nullptr == info) {
tempInfo.reset(new Variable::Info);
tempInfo->size = 0;
tempInfo->type = halide_type_of<float>();
info = tempInfo.get();
}
auto dstInfo = getInfo();
bool needChange = nullptr == dstInfo || info->order != dstInfo->order || info->dim.size() != dstInfo->dim.size() || info->type != dstInfo->type;
if (!needChange) {
for (int i=0; i<info->dim.size(); ++i) {
if (dstInfo->dim[i] != info->dim[i]) {
needChange = true;
break;
}
}
}
if (!mFrom->mInside->mCache) {
ExecutorScope::Current()->makeCache({mFrom}, false);
}
if (needChange) {
mFrom->mInside->mOutputInfos[0] = *info;
Utils::releaseMemoryForHostTensor(mFrom->inside()->mOutputTensors[0]);
Utils::copyInfoToTensor(mFrom->inside()->mOutputTensors[0], mFrom->inside()->mOutputInfos.data());
Utils::allocMemoryForHostTensor(mFrom->inside()->mOutputTensors[0]);
}
if (info->size) {
auto dstPtr = writeInternal(false);
auto srcPtr = src->readMap<void>();
if (nullptr == dstPtr || nullptr == srcPtr) {
//MNN_ERROR("Alloc memory error or compute src error in Variable::Input\n");
return false;
}
::memcpy(dstPtr, srcPtr, info->size * info->type.bytes());
}
if (needChange) {
mFrom->visitOutputs([](EXPRP expr, int index) { return expr->setInfoDirty(); });
} else {
informDirty();
}
mFrom->mInside->mContentDirty = false;
return true;
}
void Variable::replace(VARP dst, VARP src) {
if (nullptr == src) {
dst->setExpr(nullptr, 0);
return;
}
if (nullptr == dst) {
dst.mContent = src.mContent;
return;
}
if (src->mFrom.get() == dst->mFrom.get()) {
dst->mFromIndex = src->mFromIndex;
return;
}
if (src->mFrom->outputSize() != dst->mFrom->outputSize()) {
// Can't replace Expr, Just replace VARP
std::vector<Expr*> visited;
dst->mFrom->visitOutputs([src, dst, &visited](EXPRP expr, int index) {
if (expr->visited()) {
return false;
}
expr->setVisited(true);
visited.emplace_back(expr.get());
expr->mInside->mCache.reset();
expr->mInside->mCacheOffset = 0;
expr->mValid = true;
expr->mInside->mInfoDirty = true;
expr->mInside->mContentDirty = true;
return true;
});
for (auto v : visited) {
v->setVisited(false);
}
dst->mFrom->visitOutputs([src, dst](EXPRP expr, int index) {
for (int i =0; i< expr->inputs().size(); ++i) {
auto input = expr->inputs()[i];
if (input == dst) {
expr->mInputs[i] = src;
}
}
src->mFrom->mTo.emplace_back(expr);
return false;
});
dst->mFrom = src->mFrom;
dst->mFromIndex = src->mFromIndex;
return;
}
Expr::replace(dst->mFrom, src->mFrom);
dst->mFromIndex = src->mFromIndex;
}
const Variable::Info* Variable::getInfo() {
if (nullptr == mFrom) {
return nullptr;
}
auto res = mFrom->requireInfo();
if (!res) {
return nullptr;
}
return mFrom->mInside->mOutputInfos.data() + mFromIndex;
}
bool Variable::resize(INTS dims) {
if (nullptr != mFrom->get() && VARP::INPUT != mFrom->mType) {
MNN_ERROR("Can't resize variable not from input\n");
return false;
}
auto& info = mFrom->mInside->mOutputInfos[0];
if (dims.size() == info.dim.size()) {
bool theSame = true;
for (int i=0; i<dims.size(); ++i) {
if (info.dim[i] != dims[i]) {
theSame = false;
break;
}
}
if (theSame) {
return true;
}
}
info.dim = dims;
info.syncSize();
Utils::copyInfoToTensor(mFrom->inside()->mOutputTensors[0], mFrom->inside()->mOutputInfos.data());
Utils::releaseMemoryForHostTensor(mFrom->inside()->mOutputTensors[0]);
if (0 < info.size) {
bool res = Utils::allocMemoryForHostTensor(mFrom->inside()->mOutputTensors[0]);
if (!res) {
return false;
}
}
mFrom->mValid = true;
mFrom->inside()->mInfoDirty = false;
mFrom->inside()->mContentDirty = true;
mFrom->visitOutputs([](EXPRP expr, int index) { return expr->setInfoDirty(); });
return true;
}
void Expr::visit(EXPRP expr, const std::function<bool(EXPRP)>& before, const std::function<bool(EXPRP)>& after) {
bool next = before(expr);
if (!next) {
return;
}
for (int i = 0; i < expr->inputs().size(); ++i) {
if (expr->inputs()[i].get() == nullptr) {
continue;
}
visit(expr->inputs()[i]->mFrom, before, after);
}
after(expr);
}
void* Variable::readInternal(bool forShape) {
if (nullptr == mFrom->get()) {
if (VARP::INPUT == mFrom->mType) {
if (mFrom->mInside->mContentDirty) {
return nullptr;
}
}
//MNN_ASSERT(nullptr != mFrom->inside()->mOutputTensors[0]->buffer().host);
auto inside = mFrom->inside();
auto originTensor = inside->mOutputTensors[mFromIndex];
auto des = TensorUtils::getDescribe(originTensor);
if (WrapExecution::needWrap(originTensor, nullptr) || (des->quantAttr != nullptr && des->type == DataType_DT_INT8)) {
// For StaticModule will other-device runtime, we may create Variable with other-device's memory
// The case won't occurred for varibale = INPUT
// Need Copy
if (nullptr != inside->mHostTensor) {
// The Varp will not be created as input, so we just need copy once
return inside->mHostTensor->host<void>();
}
inside->mHostTensor = new Tensor;
TensorUtils::copyShape(originTensor, inside->mHostTensor, true);
inside->mHostTensor->buffer().type = originTensor->getType();
inside->mHostTensor->buffer().host = (uint8_t*)MNNMemoryAllocAlign(inside->mHostTensor->size(), MNN_MEMORY_ALIGN_DEFAULT);
TensorUtils::getDescribe(inside->mHostTensor)->memoryType = Tensor::InsideDescribe::MEMORY_HOST;
originTensor->copyToHostTensor(inside->mHostTensor);
return inside->mHostTensor->host<void>();
}
return originTensor->buffer().host;
}
auto res = mFrom->requireInfo();
if (false == res) {
return nullptr;
}
auto cache = mFrom->inside()->mCache;
if (nullptr == cache) {
ExecutorScope::Current()->makeCache({mFrom}, forShape);
cache = mFrom->inside()->mCache;
}
if (nullptr == cache) {
return nullptr;
}
if (NO_ERROR != cache->compute()) {
return nullptr;
}
return cache->mapOutput(mFrom->mInside->mCacheOffset + mFromIndex, mFrom->mInside->mOutputTensors[mFromIndex]);
}
void Variable::informDirty() {
std::vector<Expr*> visited;
mFrom->visitOutputs([&visited](EXPRP expr, int index) {
if (expr->visited()) {
return false;
}
visited.emplace_back(expr.get());
expr->setVisited(true);
if (expr->inside()->mReq.shapeNeedContent.empty()) {
// Not init
return false;
}
if (expr->inside()->mReq.shapeNeedContent[index]) {
expr->setInfoDirty();
expr->visitOutputs([](EXPRP e, int index) { return e->setInfoDirty(); });
return false;
}
if (expr->inside()->mReq.contentNeedContent[index]) {
if (expr->inside()->mCache != nullptr) {
expr->inside()->mCache->setContentDirty();
}
return true;
}
return false;
});
for (auto e : visited) {
e->setVisited(false);
}
}
void Variable::prepareCompute(const std::vector<VARP>& vars, bool forceCpu) {
std::vector<EXPRP> exprs;
for (auto v : vars) {
if (nullptr != v && nullptr != v->mFrom->get()) {
if (!v->expr().first->visited() && nullptr == v->expr().first->inside()->mCache) {
v->expr().first->requireInfo();
v->expr().first->setVisited(true);
exprs.emplace_back(v->expr().first);
}
}
}
for (auto v : vars) {
if (nullptr != v && nullptr != v->mFrom->get()) {
v->expr().first->setVisited(false);
}
}
ExecutorScope::Current()->makeCache(std::move(exprs), forceCpu);
}
void Variable::compute(const std::vector<VARP>& vars, bool forceCPU) {
prepareCompute(vars, forceCPU);
for (auto& v : vars) {
if (nullptr != v && nullptr != v->mFrom->get()) {
auto inside = v->mFrom->inside();
if (nullptr != inside && nullptr != inside->mCache) {
inside->mCache->compute();
}
}
}
}
void* Variable::writeInternal(bool inform) {
if (nullptr != mFrom->get()) {
return nullptr;
}
if (inform) {
informDirty();
}
MNN_ASSERT(TensorUtils::getDescribe(mFrom->inside()->mOutputTensors[0])->quantAttr == nullptr || TensorUtils::getDescribe(mFrom->inside()->mOutputTensors[0])->type == DataType_DT_FLOAT);
mFrom->mInside->mContentDirty = false;
return mFrom->inside()->mOutputTensors[0]->host<void>();
}
void Variable::writeScaleInternal(float scaleValue, float zeroPoint, bool inform) {
MNN_ASSERT(TensorUtils::getDescribe(mFrom->inside()->mOutputTensors[0])->quantAttr == nullptr || TensorUtils::getDescribe(mFrom->inside()->mOutputTensors[0])->type == DataType_DT_FLOAT);
if (inform) {
informDirty();
}
mFrom->mInside->mContentDirty = true;
TensorUtils::getDescribe(mFrom->inside()->mOutputTensors[0])->quantAttr.reset(new QuantAttr);
auto quant = TensorUtils::getDescribe(mFrom->inside()->mOutputTensors[0])->quantAttr.get();
quant->scale = scaleValue;
quant->zero = zeroPoint;
}
void Variable::unMap() {
//mFrom->inside()->onUnMapContent(mFromIndex);
}
void Expr::visitOutputs(const std::function<bool(EXPRP, int)>& visit) {
for (auto iter = mTo.begin(); iter != mTo.end();) {
auto expr = iter->lock();
if (nullptr == expr) {
iter = mTo.erase(iter);
continue;
}
bool recurse = false;
auto inputs = expr->inputs();
for (int i=0; i<inputs.size(); ++i) {
if (inputs[i].get() == nullptr) {
continue;
}
if (inputs[i]->mFrom.get() == this) {
recurse = recurse || visit(expr, i);
}
}
if (recurse) {
expr->visitOutputs(visit);
}
iter++;
}
}
bool Expr::setInfoDirty() {
if (mInside->mInfoDirty && mValid) {
//MNN_PRINT("End Info Dirty for %s\n", mName.c_str());
return false;
}
//MNN_PRINT("Set Info Dirty for %s\n", mName.c_str());
mInside->mInfoDirty = true;
mInside->mContentDirty = true;
mValid = true;
if (mInside->mCache != nullptr) {
mInside->mCache->setShapeDirty();
}
for (auto o : mInside->mOutputTensors) {
Utils::releaseMemoryForHostTensor(o);
}
return true;
}
std::vector<VARP> Variable::load(const char* fileName) {
AutoStorage<uint8_t> buffer;
{
FileLoader loader(fileName, true);
if (!loader.valid()) {
MNN_ERROR("Error for open %s\n", fileName);
return {};
}
loader.read();
if (!loader.valid()) {
return {};
}
loader.merge(buffer);
if (buffer.get() == nullptr) {
return {};
}
}
return load(buffer.get(), buffer.size());
}
std::vector<VARP> Variable::load(const uint8_t* buffer, size_t length) {
AUTOTIME;
flatbuffers::Verifier verify((const uint8_t*)(buffer), length);
if (false == VerifyNetBuffer(verify)) {
MNN_PRINT("Invalidate buffer to create variable\n");
return {};
}
std::unique_ptr<NetT> source(UnPackNet(buffer));
if (nullptr == source) {
return {};
}
if (source->oplists.empty()) {
MNN_ERROR("Invalid net\n");
return {};
}
// FUNC_PRINT(source->oplists.size());
auto opSize = source->oplists.size();
auto tensorCount = source->tensorName.size();
if (tensorCount == 0) {
tensorCount = source->tensorNumber;
}
std::vector<VARP> variable;
variable.reserve(tensorCount);
std::map<int, VARP> variableMap;