-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdnnobf.patch
More file actions
5600 lines (5432 loc) · 289 KB
/
dnnobf.patch
File metadata and controls
5600 lines (5432 loc) · 289 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
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
diff --git a/include/tvm/ir/attrs.h b/include/tvm/ir/attrs.h
index 18d0f025c..5ed85ec71 100644
--- a/include/tvm/ir/attrs.h
+++ b/include/tvm/ir/attrs.h
@@ -298,6 +298,11 @@ class DictAttrs : public Attrs {
return GetAttr<Integer>(attr_key, 0).value_or(0).IntValue() != 0;
}
+ // zz: for obfuscation
+ bool HasIntAttr(const std::string& attr_key) const {
+ return GetAttr<Integer>(attr_key, 0).defined();
+ }
+
TVM_DEFINE_OBJECT_REF_METHODS(DictAttrs, Attrs, DictAttrsNode);
TVM_DEFINE_OBJECT_REF_COW_METHOD(DictAttrsNode);
};
diff --git a/include/tvm/relay/expr.h b/include/tvm/relay/expr.h
index 854050464..f30398fca 100644
--- a/include/tvm/relay/expr.h
+++ b/include/tvm/relay/expr.h
@@ -300,6 +300,9 @@ class CallNode : public ExprNode {
/*! \brief The additional attributes */
Attrs attrs;
+ // zz: add attrs for obfuscation
+ DictAttrs obf_attrs;
+
/*!
* \brief The type arguments passed to polymorphic(template) function.
*
@@ -324,6 +327,7 @@ class CallNode : public ExprNode {
v->Visit("op", &op);
v->Visit("args", &args);
v->Visit("attrs", &attrs);
+ v->Visit("obf_attrs", &obf_attrs); // zz: add obf_attrs
v->Visit("type_args", &type_args);
v->Visit("virtual_device_", &virtual_device_);
v->Visit("span", &span);
@@ -342,6 +346,7 @@ class CallNode : public ExprNode {
hash_reduce(op);
hash_reduce(args);
hash_reduce(attrs);
+ hash_reduce(obf_attrs); // zz: add obf_attrs
if (!IsPrimitiveOp(op)) {
hash_reduce(type_args);
}
@@ -370,7 +375,8 @@ class Call : public Expr {
* \param span The source span of the expression.
*/
TVM_DLL Call(Expr op, Array<Expr> args, Attrs attrs = Attrs(),
- Array<Type> type_args = Array<Type>(), Span span = Span());
+ // Array<Type> type_args = Array<Type>(), Span span = Span());
+ Array<Type> type_args = Array<Type>(), Span span = Span(), DictAttrs obf_attrs = DictAttrs()); // zz: add obf_attrs
TVM_DEFINE_OBJECT_REF_METHODS(Call, RelayExpr, CallNode);
TVM_DEFINE_OBJECT_REF_COW_METHOD(CallNode);
@@ -386,7 +392,20 @@ Call WithFields(Call call, Optional<Expr> opt_op = Optional<Expr>(),
Optional<Attrs> opt_attrs = Optional<Attrs>(),
Optional<Array<Type>> opt_type_args = Optional<Array<Type>>(),
Optional<VirtualDevice> opt_virtual_device = Optional<VirtualDevice>(),
- Optional<Span> opt_span = Optional<Span>());
+ // Optional<Span> opt_span = Optional<Span>());
+ Optional<Span> opt_span = Optional<Span>(), Optional<DictAttrs> opt_obf_attrs = Optional<DictAttrs>()); // zz: add obf_attrs
+
+// zz: for obfuscation
+Call WithObfAttr(Call input, const std::string& attr_key, ObjectRef attr_value);
+// zz: ref include/tvm/ir/module.h GetAttr
+template <typename TObjectRef>
+Optional<TObjectRef> GetObfAttr(
+ Call call,
+ const std::string& attr_key,
+ Optional<TObjectRef> default_value = Optional<TObjectRef>(nullptr)) {
+ return call->obf_attrs.GetAttr<ObjectRef>(attr_key, default_value);
+}
+
/*!
* \brief Let binding that binds a local var and optionally a type annotation.
diff --git a/include/tvm/relay/function.h b/include/tvm/relay/function.h
index 874d4f233..ef240d88c 100644
--- a/include/tvm/relay/function.h
+++ b/include/tvm/relay/function.h
@@ -172,6 +172,11 @@ constexpr const char* kPrimitive = "Primitive";
*/
constexpr const char* kExtern = "Extern";
+/*!
+ added by zz: indicate function to be obfuscated
+ */
+constexpr const char* kObf = "Obf";
+
/*!
* \brief Indicates the name of the external codegen 'compiler' that should be used to lower
* or compile the function other than TVM's default lowering pipeline. The name may correspond
diff --git a/include/tvm/relay/transform.h b/include/tvm/relay/transform.h
index 35f0852f3..bba2ccaf1 100644
--- a/include/tvm/relay/transform.h
+++ b/include/tvm/relay/transform.h
@@ -146,7 +146,14 @@ TVM_DLL Pass SplitArgs(uint64_t max_function_args);
*
* \return The pass.
*/
-TVM_DLL Pass FuseOps(int fuse_opt_level = -1);
+TVM_DLL Pass FuseOps(int fuse_opt_level = -1, bool enable_flex_fuse = false, bool enable_fakeop_insert = false); // zz: add obf switches
+// added by zz: for dnnobuse impl
+// TVM_DLL Pass FuseOps(int fuse_opt_level = -1, bool skip_fuse = false);
+// TVM_DLL Pass FuseOps_faked(int fuse_opt_level = -1);
+TVM_DLL Pass FuseOpsObf(int fuse_opt_level = -1, bool enable_flex_fuse = true, bool enable_fakeop_insert = true); // zz: obf switches
+
+TVM_DLL Pass AnnotateObfAttrs(); // zz: neuron range annotation for obfuscation
+TVM_DLL Pass InterestingExprExaminer(); // zz: for neuron range profiling
/*!
* \brief The inverse operation of FuseOps. It transforms a fused program returned by
@@ -591,6 +598,9 @@ TVM_DLL Pass FlattenAtrousConv();
*/
TVM_DLL Pass AnnotateUsedMemory();
+// zz: for obfuscated function, used in AOTExecutorCodegen::CodegenObfCall
+TVM_DLL Pass AnnotateUsedMemoryWithMainFuncName(String main_func_name);
+
/*!
* \brief Captures the post-dfs index and dominator post-dfs index of (most) expression nodes in
* their span, in the form "index:<post-dfs index>:<dominator post-dfs index>". This is useful for
@@ -618,6 +628,9 @@ TVM_DLL Pass AnnotateMemoryScope();
*/
TVM_DLL Pass RemoveStandaloneReshapes();
+// zz: for obfuscated function, used in AOTExecutorCodegen::CodegenObfCall
+TVM_DLL Pass RemoveStandaloneReshapesWithMainFuncName(String main_func_name);
+
} // namespace transform
/*!
diff --git a/include/tvm/runtime/metadata.h b/include/tvm/runtime/metadata.h
index f921f3e39..a44a80a1e 100644
--- a/include/tvm/runtime/metadata.h
+++ b/include/tvm/runtime/metadata.h
@@ -69,6 +69,9 @@ class MetadataNode : public MetadataBaseNode {
inline int64_t num_constant_pools() const { return data_->num_constant_pools; }
TVM_DECLARE_FINAL_OBJECT_INFO(MetadataNode, MetadataBaseNode);
+ // zz: for debug purpose (see src/target/metadata_module.cc)
+ const struct ::TVMMetadata* get_metadata() { return data_; }
+
private:
const struct ::TVMMetadata* data_;
};
diff --git a/include/tvm/runtime/ndarray.h b/include/tvm/runtime/ndarray.h
index 8400344bf..4a06d1514 100644
--- a/include/tvm/runtime/ndarray.h
+++ b/include/tvm/runtime/ndarray.h
@@ -125,6 +125,8 @@ class NDArray : public ObjectRef {
* \param stream The output data stream
*/
inline void Save(dmlc::Stream* stream) const;
+ // zz: for save metadata, i.e., params in aot build (check src/target/metadata_module.cc, ref: Save())
+ inline size_t SaveData(dmlc::Stream* stream) const;
/*!
* \brief Create a NDArray that shares the data memory with the current one.
* \param shape The shape of the new array.
@@ -440,10 +442,13 @@ inline Object* TVMArrayHandleToObjectHandle(TVMArrayHandle handle) {
/*! \brief Magic number for NDArray file */
constexpr uint64_t kTVMNDArrayMagic = 0xDD5E40F096B4A13F;
+// zz: add some debug info in this function for tensor data inspection (check src/target/metadata.h InMemoryMetadataNode)
inline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor) {
uint64_t header = kTVMNDArrayMagic, reserved = 0;
strm->Write(header);
+ std::cout << " (zz) SaveDLTensor Write " << sizeof(header) << " bytes header" << std::endl;
strm->Write(reserved);
+ std::cout << " (zz) SaveDLTensor Write " << sizeof(reserved) << " bytes reserved" << std::endl;
// Always save data as CPU context
//
// Parameters that get serialized should be in CPU by default.
@@ -457,10 +462,14 @@ inline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor) {
cpu_dev.device_type = kDLCPU;
cpu_dev.device_id = 0;
strm->Write(cpu_dev);
+ std::cout << " (zz) SaveDLTensor Write " << sizeof(cpu_dev) << " bytes cpu_dev" << std::endl;
strm->Write(tensor->ndim);
+ std::cout << " (zz) SaveDLTensor Write " << sizeof(tensor->ndim) << " bytes tensor->ndim" << std::endl;
strm->Write(tensor->dtype);
+ std::cout << " (zz) SaveDLTensor Write " << sizeof(tensor->dtype) << " bytes tensor->dtype" << std::endl;
int ndim = tensor->ndim;
strm->WriteArray(tensor->shape, ndim);
+ std::cout << " (zz) SaveDLTensor Write " << sizeof(*tensor->shape) * ndim << " bytes tensor->shape" << std::endl;
int type_bytes = (tensor->dtype.bits + 7) / 8;
int64_t num_elems = 1;
for (int i = 0; i < ndim; ++i) {
@@ -468,11 +477,13 @@ inline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor) {
}
int64_t data_byte_size = type_bytes * num_elems;
strm->Write(data_byte_size);
+ std::cout << " (zz) SaveDLTensor Write " << sizeof(data_byte_size) << " bytes data_byte_size" << std::endl;
if (DMLC_IO_NO_ENDIAN_SWAP && tensor->device.device_type == kDLCPU &&
tensor->strides == nullptr && tensor->byte_offset == 0) {
// quick path
strm->Write(tensor->data, data_byte_size);
+ std::cout << " (zz) SaveDLTensor Write " << data_byte_size << " bytes tensor->data" << std::endl;
} else {
std::vector<uint8_t> bytes(data_byte_size);
ICHECK_EQ(
@@ -483,12 +494,67 @@ inline bool SaveDLTensor(dmlc::Stream* strm, const DLTensor* tensor) {
dmlc::ByteSwap(dmlc::BeginPtr(bytes), type_bytes, num_elems);
}
strm->Write(dmlc::BeginPtr(bytes), data_byte_size);
+ std::cout << " (zz) SaveDLTensor Write " << data_byte_size << " bytes dmlc::BeginPtr(bytes) (not in example)" << std::endl;
}
return true;
}
+// zz: for save metadata, i.e., params in aot build (check src/target/metadata_module.cc, ref: SaveDLTensor())
+// in this function we only save tensor elements seuqentially (SaveDLTensor also save metadata, e.g., ndim, shape, dtype, etc.)
+inline size_t SaveDLTensorData(dmlc::Stream* strm, const DLTensor* tensor) {
+ // uint64_t header = kTVMNDArrayMagic, reserved = 0;
+ // strm->Write(header);
+ // std::cout << " SaveDLTensor Write " << sizeof(header) << " bytes header" << std::endl;
+ // strm->Write(reserved);
+ // std::cout << " SaveDLTensor Write " << sizeof(reserved) << " bytes reserved" << std::endl;
+
+ // Device cpu_dev;
+ // cpu_dev.device_type = kDLCPU;
+ // cpu_dev.device_id = 0;
+ // strm->Write(cpu_dev);
+ // std::cout << " SaveDLTensor Write " << sizeof(cpu_dev) << " bytes cpu_dev" << std::endl;
+ // strm->Write(tensor->ndim);
+ // std::cout << " SaveDLTensor Write " << sizeof(tensor->ndim) << " bytes tensor->ndim" << std::endl;
+ // strm->Write(tensor->dtype);
+ // std::cout << " SaveDLTensor Write " << sizeof(tensor->dtype) << " bytes tensor->dtype" << std::endl;
+ int ndim = tensor->ndim;
+ // strm->WriteArray(tensor->shape, ndim);
+ // std::cout << " SaveDLTensor Write " << sizeof(*tensor->shape) * ndim << " bytes tensor->shape" << std::endl;
+ int type_bytes = (tensor->dtype.bits + 7) / 8;
+ int64_t num_elems = 1;
+ for (int i = 0; i < ndim; ++i) {
+ num_elems *= tensor->shape[i];
+ }
+ int64_t data_byte_size = type_bytes * num_elems;
+ // strm->Write(data_byte_size);
+ // std::cout << " SaveDLTensor Write " << sizeof(data_byte_size) << " bytes data_byte_size" << std::endl;
+
+ if (DMLC_IO_NO_ENDIAN_SWAP && tensor->device.device_type == kDLCPU &&
+ tensor->strides == nullptr && tensor->byte_offset == 0) {
+ // quick path
+ strm->Write(tensor->data, data_byte_size);
+ // std::cout << " SaveDLTensor Write " << data_byte_size << " bytes tensor->data" << std::endl;
+ } else {
+ std::vector<uint8_t> bytes(data_byte_size);
+ ICHECK_EQ(
+ TVMArrayCopyToBytes(const_cast<DLTensor*>(tensor), dmlc::BeginPtr(bytes), data_byte_size),
+ 0)
+ << TVMGetLastError();
+ if (!DMLC_IO_NO_ENDIAN_SWAP) {
+ dmlc::ByteSwap(dmlc::BeginPtr(bytes), type_bytes, num_elems);
+ }
+ strm->Write(dmlc::BeginPtr(bytes), data_byte_size);
+ // std::cout << " SaveDLTensor Write " << data_byte_size << " bytes dmlc::BeginPtr(bytes) (not in lenet)" << std::endl;
+ }
+ // return true;
+ return data_byte_size;
+}
+
inline void NDArray::Save(dmlc::Stream* strm) const { SaveDLTensor(strm, operator->()); }
+// zz: for save metadata, i.e., params in aot build (check src/target/metadata_module.cc, ref: Save())
+inline size_t NDArray::SaveData(dmlc::Stream* strm) const { return SaveDLTensorData(strm, operator->()); }
+
inline bool NDArray::Load(dmlc::Stream* strm) {
uint64_t header, reserved;
ICHECK(strm->Read(&header)) << "Invalid DLTensor file format";
diff --git a/include/tvm/tir/transform.h b/include/tvm/tir/transform.h
index a1697d807..2b2dac340 100644
--- a/include/tvm/tir/transform.h
+++ b/include/tvm/tir/transform.h
@@ -627,6 +627,9 @@ TVM_DLL Pass ConvertForLoopsToSerial();
*/
TVM_DLL Pass UnifiedStaticMemoryPlanner();
+// zz: for obfuscated function, used in AOTExecutorCodegen::CodegenObfCall
+TVM_DLL Pass UnifiedStaticMemoryPlannerWithMainFuncName(String main_func_name);
+
/*!
* \brief This pass transforms annotated loops into pipelined ones where producers and consumers
* are overlapped with the information provided in loop annotations, which enables optimization
diff --git a/include/tvm/tir/usmp/transform.h b/include/tvm/tir/usmp/transform.h
index ccb684463..eb701e492 100644
--- a/include/tvm/tir/usmp/transform.h
+++ b/include/tvm/tir/usmp/transform.h
@@ -46,6 +46,10 @@ using Pass = tvm::transform::Pass;
TVM_DLL Pass ConvertPoolAllocationsToOffsets(const Map<tir::Stmt, PoolAllocation>& pool_allocations,
Bool emit_tvmscript_printable = Bool(false));
+// zz: for obfuscated function, used in PlanMemoryWithMainFuncName
+TVM_DLL Pass ConvertPoolAllocationsToOffsetsWithMainFuncName(const Map<tir::Stmt, PoolAllocation>& pool_allocations,
+ String main_func_name, Bool emit_tvmscript_printable = Bool(false));
+
/*!
* \brief Assign PoolInfo objects to tir.allocate nodes depending on the PrimFunc's target
*
@@ -56,6 +60,9 @@ TVM_DLL Pass ConvertPoolAllocationsToOffsets(const Map<tir::Stmt, PoolAllocation
*/
TVM_DLL Pass AssignPoolInfo();
+// zz: for obfuscated function, used in PlanMemoryWithMainFuncName
+TVM_DLL Pass AssignPoolInfoWithMainFuncName(String main_func_name);
+
/*!
* \brief This pass creates Allocate nodes for I/O tensors
*
diff --git a/include/tvm/tir/usmp/utils.h b/include/tvm/tir/usmp/utils.h
index a67350a2b..e0a7c2cb9 100644
--- a/include/tvm/tir/usmp/utils.h
+++ b/include/tvm/tir/usmp/utils.h
@@ -250,6 +250,9 @@ Array<BufferInfo> ConvertToArrayOfBufferInfo(const Map<BufferInfo, Stmt>& buffer
*/
Integer CalculateModuleWorkspaceSize(const IRModule& mod);
+// zz: for obfuscated function, used in PlanMemoryWithMainFuncName
+Integer CalculateModuleWorkspaceSizeWithMainFuncName(const IRModule& mod, String main_func_name);
+
/*!
* \brief The allocate node attribute to indicate candidate memory pools.
* This needs to be kept in sync with CANDIDATE_MEMORY_POOL_ATTR in
diff --git a/python/tvm/relay/expr.py b/python/tvm/relay/expr.py
index 5239eaa88..cb5ad96ff 100644
--- a/python/tvm/relay/expr.py
+++ b/python/tvm/relay/expr.py
@@ -344,6 +344,12 @@ def CallWithFields(
"""
return _ffi_api.CallWithFields(call, op, args, attrs, type_args, virtual_device, span)
+# zz: for obfuscation
+def CallWithObfAttr(call, attr_key, attr_value):
+ return _ffi_api.CallWithObfAttr(call, attr_key, tvm.runtime.convert(attr_value))
+
+def CallGetObfAttr(call, attr_key):
+ return _ffi_api.CallGetObfAttr(call, attr_key)
@tvm._ffi.register_object("relay.Let")
class Let(ExprWithOp):
diff --git a/src/relay/analysis/graph_partitioner.cc b/src/relay/analysis/graph_partitioner.cc
index d233d43ad..6f7c32e35 100644
--- a/src/relay/analysis/graph_partitioner.cc
+++ b/src/relay/analysis/graph_partitioner.cc
@@ -24,6 +24,27 @@
namespace tvm {
namespace relay {
+// zz: helper function
+bool isComputeOp(const CallNode* call_node) {
+ if (auto call_op = call_node->op.as<OpNode>()) {
+ // check if call_op is conv2d, dense, max_pool2d
+ if (call_op->name == "nn.conv2d" || call_op->name == "nn.dense" || call_op->name == "nn.max_pool2d" || call_op->name == "nn.batch_matmul") {
+ return true;
+ }
+ }
+ return false;
+}
+
+bool isSmallComputeOp(const CallNode* call_node) {
+ if (auto call_op = call_node->op.as<OpNode>()) {
+ // check if call_op is conv2d, dense, max_pool2d
+ if (call_op->name == "add" || call_op->name == "nn.relu") {
+ return true;
+ }
+ }
+ return false;
+}
+
DominatorTree DominatorTree::PostDom(support::Arena* arena, const IndexedForwardGraph& graph) {
DominatorTree tree;
tree.nodes.resize(graph.post_dfs_order.size(), nullptr);
@@ -104,10 +125,200 @@ std::vector<GraphPartitioner::Group*> GraphPartitioner::Partition(
if (opt_level_ == 0) return std::move(groups_);
// get post dominator tree
auto post_dom_tree = DominatorTree::PostDom(arena_, graph);
+ // zz: original fusion
// run fusion algorithm.
for (int phase = 0; phase < 3; ++phase) {
this->RunFuse(graph, post_dom_tree, phase);
}
+
+ // zz: test flexible fusion
+ // std::cout << "[ZZDEBUG] GraphPartitioner::Partition before RunFuseObfFlex" << std::endl;
+ // this->RunFuse(graph, post_dom_tree, 0);
+ // this->RunFuseObfFlex(graph, post_dom_tree); // zz: test flexible fusion for obfuscation
+ // std::cout << "[ZZDEBUG] GraphPartitioner::Partition after RunFuseObfFlex" << std::endl;
+
+ // zz: print group summary
+ // std::cout << "==========================================================================================================================" << std::endl;
+ // std::cout << std::endl << "[ZZDEBUG] RunFuse Summary:" << std::endl;
+ ICHECK(groups_.size() == graph.post_dfs_order.size());
+ ICHECK(groups_.size() == post_dom_tree.nodes.size());
+ for (size_t i = 0; i < groups_.size(); i++) {
+ ICHECK(groups_[i]->root_ref == graph.post_dfs_order[i]->ref);
+ ICHECK(post_dom_tree.nodes[i]->gnode == graph.post_dfs_order[i]);
+ // std::cout << "------------------ nid " << i << std::endl;
+ // std::cout << "node ir: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph.post_dfs_order[i]->ref))) << std::endl;
+ // std::cout << "node type key: " << graph.post_dfs_order[i]->ref->GetTypeKey() << std::endl;
+ // std::cout << "node tensor type: " << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph.post_dfs_order[i]->ref))->checked_type()) << std::endl;
+ // std::cout << "#nodes: " << groups_[i]->num_nodes << std::endl;
+ // std::cout << "#args: " << groups_[i]->args_num << std::endl;
+ // std::cout << "#compute nodes: " << groups_[i]->num_compute_nodes << std::endl;
+ auto root_group = groups_[i]->FindRoot();
+ // find root_group index in groups_
+ size_t root_group_index = 0xffffffff;
+ for (size_t j = 0; j < groups_.size(); j++) {
+ if (groups_[j] == root_group) {
+ root_group_index = j;
+ break;
+ }
+ }
+ // std::cout << "root nid: " << root_group_index << std::endl;
+ }
+
+ return std::move(groups_);
+}
+
+// zz: for random fuse testing, split Partition() into PartitionWithoutMov() and GetGroups(), ref Partition()
+void GraphPartitioner::PartitionWithoutMov(
+ const IndexedForwardGraph& graph) {
+ // ----------------------------------------------------------------------------------
+ // zz: for obf flex fuse
+ // ----------------------------------------------------------------------------------
+ this->InitGroups(graph);
+ if (opt_level_ == 0) return;
+ // get post dominator tree
+ auto post_dom_tree = DominatorTree::PostDom(arena_, graph);
+ // run fusion algorithm.
+ // for (size_t i = 0; i < groups_.size(); i++) {
+ // std::cout << " groups_[" << i << "]: group_id = " << std::hex << (uintptr_t)groups_[i] << ", root_id = " << (uintptr_t)(groups_[i]->FindRoot()) << ", num_nodes = " << std::dec << groups_[i]->num_nodes << std::endl;
+ // std::cout << std::endl << " group node: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph.post_dfs_order[i]->ref))) << std::endl << " group node end." << std::endl;
+ // }
+ // std::cout << std::endl << "[ZZDEBUG] GraphPartitioner::Partition: max_fuse_depth_ = " << std::dec << max_fuse_depth_ << ", max_function_args_ = " << max_function_args_ << std::endl;
+
+ // zz: original fuse
+ // for (int phase = 0; phase < 3; ++phase) {
+ // this->RunFuse(graph, post_dom_tree, phase);
+ // }
+
+ // zz: flexible fuse for obfuscation
+ // std::cout << "[ZZDEBUG] GraphPartitioner::Partition before RunFuseObfFlex" << std::endl;
+ this->RunFuse(graph, post_dom_tree, 0); // resue phase 0 for 0-dim scalar op attr fusion, e.g., nn.pad(%Input3, 0f, ...). (Remove this for transformer to avoid bug) (TODO: make this configurable)
+ this->RunFuseObfFlex(graph, post_dom_tree); // flexible fuse for obfuscation
+ // std::cout << "[ZZDEBUG] GraphPartitioner::Partition after RunFuseObfFlex" << std::endl;
+
+ // zz: print group summary
+ // std::cout << "==========================================================================================================================" << std::endl;
+ // std::cout << std::endl << "[ZZDEBUG] RunFuse Summary:" << std::endl;
+ ICHECK(groups_.size() == graph.post_dfs_order.size());
+ ICHECK(groups_.size() == post_dom_tree.nodes.size());
+ for (size_t i = 0; i < groups_.size(); i++) {
+ ICHECK(groups_[i]->root_ref == graph.post_dfs_order[i]->ref);
+ ICHECK(post_dom_tree.nodes[i]->gnode == graph.post_dfs_order[i]);
+ // std::cout << "------------------ nid " << i << std::endl;
+ // std::cout << "node ir: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph.post_dfs_order[i]->ref))) << std::endl;
+ Expr node_expr = GetRef<Expr>(static_cast<const ExprNode*>(graph.post_dfs_order[i]->ref));
+ if (node_expr->IsInstance<CallNode>()) {
+ auto call_node = node_expr.as<CallNode>();
+ // std::cout << "node op: " << call_node->op << std::endl;
+ }
+ // std::cout << "node type key: " << graph.post_dfs_order[i]->ref->GetTypeKey() << std::endl;
+ // std::cout << "node tensor type: " << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph.post_dfs_order[i]->ref))->checked_type()) << std::endl;
+ // std::cout << "#nodes: " << groups_[i]->num_nodes << std::endl;
+ // std::cout << "#args: " << groups_[i]->args_num << std::endl;
+ // std::cout << "#compute nodes: " << groups_[i]->num_compute_nodes << std::endl;
+ // find dominator tree node idx
+ auto dom_tree_parent = post_dom_tree.nodes[i]->parent;
+ if (dom_tree_parent != nullptr) {
+ // find index of dom_tree_node
+ auto parent_node = dom_tree_parent->gnode;
+ size_t dom_tree_node_index = 0xffffffff;
+ for (size_t j = 0; j < groups_.size(); j++) {
+ if (groups_[j]->root_ref == parent_node->ref) {
+ dom_tree_node_index = j;
+ break;
+ }
+ }
+ // std::cout << "dom tree node nid: " << dom_tree_node_index << std::endl;
+ } else {
+ // std::cout << "dom tree node: nullptr" << std::endl;
+ }
+ auto root_group = groups_[i]->FindRoot();
+ // find root_group index in groups_
+ size_t root_group_index = 0xffffffff;
+ for (size_t j = 0; j < groups_.size(); j++) {
+ if (groups_[j] == root_group) {
+ root_group_index = j;
+ break;
+ }
+ }
+ // std::cout << "root nid: " << root_group_index << std::endl;
+ }
+
+ // zz: select fake ops from partitioned groups
+ this->SelectFops(graph, post_dom_tree, 0);
+ this->SelectFops(graph, post_dom_tree, 1);
+
+ // return std::move(groups_);
+ // ----------------------------------------------------------------------------------
+ // zz: for obf flex fuse end
+ // ----------------------------------------------------------------------------------
+
+ // ----------------------------------------------------------------------------------
+ // zz: for manual fusion
+ // ----------------------------------------------------------------------------------
+ // this->InitGroups(graph);
+ // if (opt_level_ == 0) return;
+ // // get post dominator tree
+ // auto post_dom_tree = DominatorTree::PostDom(arena_, graph);
+ // // zz: original fusion
+ // // run fusion algorithm.
+ // for (int phase = 0; phase < 3; ++phase) {
+ // this->RunFuse(graph, post_dom_tree, phase);
+ // }
+
+ // // zz: print group summary
+ // std::cout << "==========================================================================================================================" << std::endl;
+ // std::cout << std::endl << "[ZZDEBUG] RunFuse Summary:" << std::endl;
+ // ICHECK(groups_.size() == graph.post_dfs_order.size());
+ // ICHECK(groups_.size() == post_dom_tree.nodes.size());
+ // for (size_t i = 0; i < groups_.size(); i++) {
+ // ICHECK(groups_[i]->root_ref == graph.post_dfs_order[i]->ref);
+ // ICHECK(post_dom_tree.nodes[i]->gnode == graph.post_dfs_order[i]);
+ // std::cout << "------------------ nid " << i << std::endl;
+ // // std::cout << "node ir: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph.post_dfs_order[i]->ref))) << std::endl;
+ // Expr node_expr = GetRef<Expr>(static_cast<const ExprNode*>(graph.post_dfs_order[i]->ref));
+ // if (node_expr->IsInstance<CallNode>()) {
+ // auto call_node = node_expr.as<CallNode>();
+ // std::cout << "node op: " << call_node->op << std::endl;
+ // }
+ // std::cout << "node type key: " << graph.post_dfs_order[i]->ref->GetTypeKey() << std::endl;
+ // std::cout << "node tensor type: " << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph.post_dfs_order[i]->ref))->checked_type()) << std::endl;
+ // std::cout << "#nodes: " << groups_[i]->num_nodes << std::endl;
+ // std::cout << "#args: " << groups_[i]->args_num << std::endl;
+ // std::cout << "#compute nodes: " << groups_[i]->num_compute_nodes << std::endl;
+ // // find dominator tree node idx
+ // auto dom_tree_parent = post_dom_tree.nodes[i]->parent;
+ // if (dom_tree_parent != nullptr) {
+ // // find index of dom_tree_node
+ // auto parent_node = dom_tree_parent->gnode;
+ // size_t dom_tree_node_index = 0xffffffff;
+ // for (size_t j = 0; j < groups_.size(); j++) {
+ // if (groups_[j]->root_ref == parent_node->ref) {
+ // dom_tree_node_index = j;
+ // break;
+ // }
+ // }
+ // std::cout << "dom tree node nid: " << dom_tree_node_index << std::endl;
+ // } else {
+ // std::cout << "dom tree node: nullptr" << std::endl;
+ // }
+ // auto root_group = groups_[i]->FindRoot();
+ // // find root_group index in groups_
+ // size_t root_group_index = 0xffffffff;
+ // for (size_t j = 0; j < groups_.size(); j++) {
+ // if (groups_[j] == root_group) {
+ // root_group_index = j;
+ // break;
+ // }
+ // }
+ // std::cout << "root nid: " << root_group_index << std::endl;
+ // }
+ // ----------------------------------------------------------------------------------
+ // zz: for manual fusion end
+ // ----------------------------------------------------------------------------------
+}
+
+// zz: for random fuse testing
+std::vector<GraphPartitioner::Group*> GraphPartitioner::GetGroups() {
return std::move(groups_);
}
@@ -156,9 +367,9 @@ bool GraphPartitioner::CheckPath(IndexedForwardGraph::Node* src, IndexedForwardG
}
OpPatternKind CombinePattern(OpPatternKind lhs, OpPatternKind rhs) {
- if (lhs > relay::kBroadcast && rhs > relay::kBroadcast) {
- LOG(FATAL) << "Cannot merge two complex group together";
- }
+ // if (lhs > relay::kBroadcast && rhs > relay::kBroadcast) {
+ // LOG(FATAL) << "Cannot merge two complex group together";
+ // } // zz: comment this to enable complex fuse first
if (lhs > rhs) return lhs;
return rhs;
}
@@ -170,10 +381,11 @@ void GraphPartitioner::MergeFromTo(Group* child, Group* parent) {
// update the number of nodes of the parent group
parent->num_nodes += child->num_nodes;
parent->args_num += child->args_num;
+ parent->num_compute_nodes += child->num_compute_nodes; // zz: add num_compute_nodes
child->parent = parent;
// update anchor ref and pattern
if (child->anchor_ref != nullptr) {
- ICHECK(parent->anchor_ref == nullptr);
+ // ICHECK(parent->anchor_ref == nullptr); // zz: comment this to enable complex fuse first
parent->anchor_ref = child->anchor_ref;
parent->pattern = CombinePattern(child->pattern, parent->pattern);
}
@@ -233,6 +445,7 @@ size_t GraphPartitioner::CountAdditionalArgs_(const TensorTypeNode* ttype, bool
}
}
if (with_strides && any_dims > 0) any_dims += ttype->shape.size();
+ // std::cout << "[ZZDEBUG] GraphPartitioner::CountAdditionalArgs_: any_dims = (all 0 in example) " << any_dims << std::endl;
return any_dims;
}
@@ -344,9 +557,24 @@ void GraphPartitioner::InitGroups(const IndexedForwardGraph& graph) {
}
group_node->args_num = args_counter(graph_node->ref);
groups_[nid] = group_node;
+
+ // zz: check whether the node is a compute node
+ group_node->num_compute_nodes = 0;
+ if (auto call_node = GetRef<ObjectRef>(graph_node->ref).as<CallNode>()) {
+ // if (auto call_op = call_node->op.as<OpNode>()) {
+ // check if call_op is conv2d, dense, max_pool2d
+ // if (call_op->name == "nn.conv2d" || call_op->name == "nn.dense" || call_op->name == "nn.max_pool2d") {
+ if (isComputeOp(call_node)) {
+ group_node->num_compute_nodes = 1;
+ }
+ // }
+ }
+ // zz: set num_fop_nodes
+ group_node->num_fop_nodes = 0;
}
}
+// zz: debug log added
void GraphPartitioner::RunFuse(const IndexedForwardGraph& graph, //
const DominatorTree& post_dom_tree, //
int phase) {
@@ -356,6 +584,15 @@ void GraphPartitioner::RunFuse(const IndexedForwardGraph& graph, //
auto* dom_node = post_dom_tree.nodes[nid];
Group* group_node = groups_[nid];
ICHECK(group_node != nullptr);
+ // std::cout << "================================================================================================================================================================================" << std::endl;
+ // std::cout << "[ZZDEBUG] RunFuse phase " << std::dec << phase << " nid " << nid << ":" << std::endl;
+ // std::cout << " (zz) try to fuse node: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph_node->ref))) << std::endl;
+ // if (dom_node->parent != nullptr) {
+ // std::cout << " (zz) to node:" << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(dom_node->parent->gnode->ref))) << std::endl;
+ // }
+ // else {
+ // std::cout << " (zz) to node: nullptr" << std::endl;
+ // }
postpone_node_ = nullptr;
// Check if the fusing of some inputs was postponed
if (postponed_fusing_map_.count(graph_node)) {
@@ -366,26 +603,47 @@ void GraphPartitioner::RunFuse(const IndexedForwardGraph& graph, //
auto* src = it->second;
auto* snode = post_dom_tree.nodes[src->index]->parent->gnode;
if (groups_[snode->index]->anchor_ref != nullptr) continue;
+ // std::cout << " (zz) CommitFuse CountArgs_ (not in example): src= " << std::hex << (uintptr_t)src << ", dst = " << (uintptr_t)snode << std::endl;
+ // std::cout << " [fuse] postponed_fusing_map_: " << std::endl;
+ // std::cout << " zz: fuse node: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(src->ref))) << std::endl;
+ // std::cout << " zz: to node: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(snode->ref))) << std::endl;
CommitFuse(src, snode);
}
}
postponed_fusing_map_.erase(graph_node);
}
+ // std::cout << " ----- (zz) after postponed_fusing_map_" << std::endl;
// no actions for opaque nodes
- if (group_node->pattern == kOpaque) continue;
+ // if (group_node->pattern == kOpaque) continue;
+ if (group_node->pattern == kOpaque) {
+ // std::cout << " [no fuse] opaque node" << std::endl;
+ continue;
+ }
// no actions needed if the current node have no dominator
- if (dom_node->parent == nullptr) continue;
+ // if (dom_node->parent == nullptr) continue;
+ if (dom_node->parent == nullptr) {
+ // std::cout << " [no fuse] no dominator" << std::endl;
+ continue;
+ }
ICHECK(!graph_node->extern_ref);
size_t dom_parent_gindex = dom_node->parent->gnode->index;
// refuse the fusion if too many ops are going to be fused together
- if (CountFusedNodesWithNewChild(graph_node, dom_node->parent->gnode) > max_fuse_depth_)
+ // if (CountFusedNodesWithNewChild(graph_node, dom_node->parent->gnode) > max_fuse_depth_)
+ // continue;
+ if (CountFusedNodesWithNewChild(graph_node, dom_node->parent->gnode) > max_fuse_depth_) {
+ // std::cout << " [no fuse] CountFusedNodesWithNewChild exceed" << std::endl;
continue;
+ }
// Refuse the fusion if too many arguments are going to be in the fused function
if (max_function_args_ > 0) {
auto limit = CountArgsLimit_(graph_node);
if (limit > 0) {
+ // if (CountFusedArgs(graph, graph_node) > limit) {
+ // continue;
+ // }
if (CountFusedArgs(graph, graph_node) > limit) {
+ // std::cout << " [no fuse] CountFusedArgs exceed" << std::endl;
continue;
}
}
@@ -393,33 +651,58 @@ void GraphPartitioner::RunFuse(const IndexedForwardGraph& graph, //
if (phase == 2) {
// Fuse injective ops into intermediate tuples, if any
- if (group_node->pattern > relay::kInjective) continue;
+ // if (group_node->pattern > relay::kInjective) continue;
+ if (group_node->pattern > relay::kInjective) {
+ // std::cout << " [no fuse] phase2 pattern > kInjective (need to be finished in phase 0/1)" << std::endl;
+ continue;
+ }
Group* dom_parent_group = groups_[dom_parent_gindex];
Group* dom_root_group = dom_parent_group->FindRoot();
// If dom node group has a tuple as its root, we do not fuse tuple fields into it
- if (dom_root_group->pattern == relay::kTuple) continue;
+ // if (dom_root_group->pattern == relay::kTuple) continue;
+ if (dom_root_group->pattern == relay::kTuple) {
+ // std::cout << " [no fuse] phase2 dom_root_group->pattern == kTuple" << std::endl;
+ continue;
+ }
if (dom_parent_group->pattern == kTuple && dom_root_group->pattern <= relay::kInjective) {
// Now we know the tuple has been fused into subsequent injective ops
auto fcond = [](OpPatternKind kind, bool is_sink) { return kind <= kInjective; };
// dom_root_group can also be tuple, as in inception layers
// CheckPath is needed to avoid fusing two intermediate tuples
if (CheckPath(graph_node, dom_node->parent->gnode, fcond)) {
+ // std::cout << " (zz) CommitFuse phase == 2 (not in example): src= " << std::hex << (uintptr_t)graph_node << ", dst = " << (uintptr_t)(dom_node->parent->gnode) << std::endl;
+ // std::cout << " [fuse] phase 2 " << std::endl;
CommitFuse(graph_node, dom_node->parent->gnode);
}
+ // else {
+ // std::cout << " [no fuse] phase2 CheckPath failed" << std::endl;
+ // }
}
+ // std::cout << " [no fuse] phase2 not fuse case" << std::endl;
continue;
}
+ // std::cout << " ----- (zz) after phase == 2" << std::endl;
// Skip if current node is already fused to the parent.
if (groups_[dom_parent_gindex] != nullptr &&
group_node->FindRoot() == groups_[dom_parent_gindex]->FindRoot()) {
+ // std::cout << " [no fuse] already fused to parent" << std::endl;
continue;
}
// Do not fuse into tuple for now
- if (groups_[dom_parent_gindex]->pattern == kTuple) continue;
+ // if (groups_[dom_parent_gindex]->pattern == kTuple) continue;
+ if (groups_[dom_parent_gindex]->pattern == kTuple) {
+ // std::cout << " [no fuse] dom kTuple" << std::endl;
+ continue;
+ }
// Try to fuse current node to its post-dominator.
if (group_node->pattern == kOutEWiseFusable) {
- if (phase != 0) continue;
+ // std::cout << " ----- (zz) kOutEWiseFusable" << std::endl;
+ // if (phase != 0) continue;
+ if (phase != 0) {
+ // std::cout << " [no fuse] src kOutEWiseFusable, phase != 0" << std::endl;
+ continue;
+ }
// Path for OutEWiseFusable: conv2d
// Check if the dominator relation is elemwise.
if (dom_node->parent != nullptr && dom_node->pattern == kElemWise) {
@@ -427,10 +710,19 @@ void GraphPartitioner::RunFuse(const IndexedForwardGraph& graph, //
// The fuse can be executed if all the intermediate ops are still broadcast.
auto fcond = [](OpPatternKind kind, bool is_sink) { return kind <= kBroadcast; };
if (CheckPath(graph_node, dom_node->parent->gnode, fcond)) {
+ // std::cout << " [fuse] src kOutEWiseFusable" << std::endl;
CommitFuse(graph_node, dom_node->parent->gnode);
+ // std::cout << " after CommitFuse: dom_node->parent->gnode = " << std::hex << (uintptr_t)(dom_node->parent->gnode) << ", dom_node->pattern = " << std::dec << dom_node->pattern << std::endl;
}
+ // else {
+ // std::cout << " [no fuse] src kOutEWiseFusable CheckPath failed" << std::endl;
+ // }
}
+ // else {
+ // std::cout << " [no fuse] src kOutEWiseFusable, dom !kElemWise" << std::endl;
+ // }
} else if (group_node->pattern <= kBroadcast) {
+ // std::cout << " ----- (zz) <= kBroadcast" << std::endl;
// Pre-condition: can only be fused to parent which is injective or reduction.
if (dom_node->parent != nullptr &&
(dom_node->pattern <= kInjective || dom_node->pattern == kCommReduce)) {
@@ -447,24 +739,189 @@ void GraphPartitioner::RunFuse(const IndexedForwardGraph& graph, //
}
};
if (CheckPath(graph_node, dom_node->parent->gnode, fcond)) {
+ // std::cout << " [fuse] src <= kBroadcast" << std::endl;
CommitFuse(graph_node, dom_node->parent->gnode);
}
}
} else if (group_node->pattern == kInjective || group_node->pattern == kTuple) {
+ // std::cout << " ----- (zz) kInjective - kTuple" << std::endl;
+ // std::cout << " (zz) try fuse to dom_parent: group_node->pattern == kInjective || kTuple" << std::endl;
// defer injective fusion to second phase.
// so conv2d always finishes fusing.
- if (phase != 1) continue;
+ // if (phase != 1) continue;
+ if (phase != 1) {
+ // std::cout << " [no fuse] src kInjective || kTuple, phase != 1" << std::endl;
+ continue;
+ }
// Check if all path are injective.
auto fcond = [](OpPatternKind kind, bool is_sink) { return kind <= kInjective; };
if (CheckPath(graph_node, dom_node->parent->gnode, fcond)) {
+ // std::cout << " (zz) CommitFuse kInjective || kInjective: src= " << std::hex << (uintptr_t)graph_node << ", dst = " << (uintptr_t)(dom_node->parent->gnode) << std::endl;
+ // std::cout << " [fuse] src kInjective || kTuple" << std::endl;
CommitFuse(graph_node, dom_node->parent->gnode);
}
+ else {
+ // std::cout << " [no fuse] src kInjective || kTuple CheckPath failed" << std::endl;
+ }
} else {
// do nothing.
ICHECK(group_node->pattern == kCommReduce);
+ // std::cout << " [no fuse] src kCommReduce" << std::endl;
}
}
}
+// zz: path checker for flexible fusion
+bool GraphPartitioner::CheckPathObfFlex(IndexedForwardGraph::Node* src, IndexedForwardGraph::Node* sink) {
+ // src and sink must be call node
+ if (!src->ref->IsInstance<CallNode>() || !sink->ref->IsInstance<CallNode>()) {
+ // std::cout << "[ZZDEBUG] CheckPathObfFlex: src or sink not CallNode" << std::endl;
+ return false;
+ }
+ // sink call not arg only contain one call node input (which is src)
+ auto sink_call = Downcast<Call>(GetRef<Call>(static_cast<const CallNode*>(sink->ref)));
+ size_t sink_input_size = 0;
+ for (auto arg : sink_call->args) {
+ if (arg->IsInstance<CallNode>()) {
+ sink_input_size++;
+ }
+ }
+ if (sink_input_size != 1) {
+ // std::cout << "[ZZDEBUG] CheckPathObfFlex: sink_input_size != 1" << std::endl;
+ return false;
+ }
+
+ // src outpus size must be 1, and the output is sink
+ size_t src_output_size = 0;
+ for (auto link = src->outputs.head; link != nullptr; link = link->next) {
+ src_output_size++;
+ }
+ if (src_output_size != 1) {
+ return false;
+ }
+ if (src->outputs.head->value.node != sink) {
+ return false;
+ }
+ return true;
+}
+
+// zz: compute op checker for flexible fusion
+size_t GraphPartitioner::CountComputeOp(IndexedForwardGraph::Node* src, IndexedForwardGraph::Node* sink) {
+ // find root
+ Group* src_grp = groups_[src->index];
+ Group* sink_grp = groups_[sink->index];
+ Group* src_root = src_grp->FindRoot();
+ Group* sink_root = sink_grp->FindRoot();
+ // check if src and sink are in the same group
+ if (src_root == sink_root) {
+ return src_root->num_compute_nodes;
+ }
+ return src_root->num_compute_nodes + sink_root->num_compute_nodes;
+}
+
+// zz: flexible fusion for obfuscation
+void GraphPartitioner::RunFuseObfFlex(const IndexedForwardGraph& graph, const DominatorTree& post_dom_tree) {
+ for (size_t nid = 0; nid < groups_.size(); ++nid) {
+ // the group of current node has been specified already.
+ auto* graph_node = graph.post_dfs_order[nid];
+ auto* dom_node = post_dom_tree.nodes[nid];
+ Group* group_node = groups_[nid];
+
+ // std::cout << "================================================================================================================================================================================" << std::endl;
+ // std::cout << "[ZZDEBUG] RunFuseObfFlex " << std::dec << " nid " << nid << ":" << std::endl;
+ // std::cout << " (zz) try to fuse node: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph_node->ref))) << std::endl;
+ // if (dom_node->parent != nullptr) {
+ // std::cout << " (zz) to node:" << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(dom_node->parent->gnode->ref))) << std::endl;
+ // }
+ // else {
+ // std::cout << " (zz) to node: nullptr" << std::endl;
+ // }
+
+ // skip if no dom parent
+ if (dom_node->parent == nullptr) {
+ // std::cout << " [RunFuseObfFlex, no fuse] no dominator" << std::endl;
+ continue;
+ }
+
+ // skip if current node is already fused to the parent.
+ size_t dom_parent_gindex = dom_node->parent->gnode->index;
+ if (groups_[dom_parent_gindex] != nullptr &&
+ group_node->FindRoot() == groups_[dom_parent_gindex]->FindRoot()) {
+ // std::cout << " [RunFuseObfFlex, no fuse] already fused to parent" << std::endl;
+ continue;
+ }
+
+ // try to fuse
+ if (CheckPathObfFlex(graph_node, dom_node->parent->gnode)) {
+ if (CountComputeOp(graph_node, dom_node->parent->gnode) <= max_compute_nodes_) {
+ // std::cout << " [RunFuseObfFlex, fuse] CountComputeOp <= max_compute_nodes_" << std::endl;
+ CommitFuse(graph_node, dom_node->parent->gnode);
+ }
+ // else {
+ // std::cout << " [RunFuseObfFlex, no fuse] CountComputeOp > max_compute_nodes_" << std::endl;
+ // }
+ }
+ }
+}
+
+
+// zz: determine fops
+void GraphPartitioner::SelectFops(const IndexedForwardGraph& graph, const DominatorTree& post_dom_tree, int phase) {
+ for (size_t nid = 0; nid < groups_.size(); ++nid) {
+ auto* graph_node = graph.post_dfs_order[nid];
+ // auto* dom_node = post_dom_tree.nodes[nid];
+ Group* group_node = groups_[nid];
+ // std::cout << "================================================================================================================================================================================" << std::endl;
+ // std::cout << "[ZZDEBUG] SelectFops phase " << std::dec << phase << " nid " << nid << ":" << std::endl;
+ // std::cout << " (zz) try to select fops: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph_node->ref))) << std::endl;
+
+ auto root_group = group_node->FindRoot();
+ if (root_group->num_fop_nodes >= max_fop_depth_) {
+ // std::cout << " [SelectFops, no select] num_fop_nodes >= max_fop_depth_ (" << std::dec << root_group->num_fop_nodes << " vs. " << max_fop_depth_ << ")" << std::endl;
+ continue;
+ }
+
+ // add compute nodes
+ if (auto call_node = GetRef<ObjectRef>(graph_node->ref).as<CallNode>()) {
+ // if (auto call_op = call_node->op.as<OpNode>()) {
+ if (fake_ops_.count(graph_node->ref)) {
+ // std::cout << " [SelectFops, no select] already in fake_ops_" << std::endl;
+ continue;
+ }
+
+ if (isComputeOp(call_node)) {
+ root_group->num_fop_nodes++;
+ fake_ops_.insert(graph_node->ref);
+ // std::cout << " [SelectFops, select] compute node: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph_node->ref))) << std::endl;
+ }
+
+ if (phase > 0 && isSmallComputeOp(call_node)) {
+ root_group->num_fop_nodes++;
+ fake_ops_.insert(graph_node->ref);
+ // std::cout << " [SelectFops, select] small compute node: " << std::endl << PrettyPrint(GetRef<Expr>(static_cast<const ExprNode*>(graph_node->ref))) << std::endl;
+ }
+ // }
+
+ // std::cout << " [SelectFops, no select] not compute node" << std::endl;
+ }
+ // else {
+ // std::cout << " [SelectFops, no select] not call node" << std::endl;
+ // }
+ }
+}
+
+std::unordered_set<const Object*> GraphPartitioner::GetFops() {
+ return std::move(fake_ops_);
+}
+
+// zz: for random fuse testing
+void GraphPartitioner::MannualFuse(const IndexedForwardGraph& graph, int src_inx) {
+ auto post_dom_tree = DominatorTree::PostDom(arena_, graph);
+ auto* graph_node = graph.post_dfs_order[src_inx];
+ auto* dom_node = post_dom_tree.nodes[src_inx];
+ // Group* group_node = groups_[src_inx];
+ CommitFuse(graph_node, dom_node->parent->gnode);
+}
+
} // namespace relay
} // namespace tvm
diff --git a/src/relay/analysis/graph_partitioner.h b/src/relay/analysis/graph_partitioner.h
index b3f934b97..8bbbd51a8 100644
--- a/src/relay/analysis/graph_partitioner.h
+++ b/src/relay/analysis/graph_partitioner.h
@@ -163,11 +163,17 @@ class DominatorTree {
class GraphPartitioner {
public:
explicit GraphPartitioner(support::Arena* arena, int opt_level, size_t max_fuse_depth,
- size_t max_function_args)
+ // size_t max_function_args)
+ size_t max_function_args,
+ size_t max_compute_nodes=3, size_t max_fop_depth=3) // zz: add max_compute_nodes, max_fop_depth
+ // size_t max_compute_nodes=2, size_t max_fop_depth=3) // zz: max_compute_nodes 2 for transformers to avoid bug (todo: make this configurable)
: arena_(arena),
opt_level_(opt_level),
max_fuse_depth_(max_fuse_depth),
- max_function_args_(max_function_args) {}
+ // max_function_args_(max_function_args) {}
+ max_function_args_(max_function_args),
+ max_compute_nodes_(max_compute_nodes), // zz: add max_compute_nodes
+ max_fop_depth_(max_fop_depth) {} // zz: add max_fop_depth
/*!
* \brief Group as a union find data structure.
*/
@@ -187,6 +193,10 @@ class GraphPartitioner {