-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
eager_generator.cc
2922 lines (2582 loc) · 112 KB
/
eager_generator.cc
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
// Copyright (c) 2021 PaddlePaddle Authors. All Rights Reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <algorithm>
#include <fstream>
#include <iostream>
#include <string>
#include <unordered_set>
#include "paddle/fluid/framework/op_info.h"
#include "paddle/fluid/framework/op_registry.h"
#include "paddle/fluid/framework/operator.h"
#include "paddle/fluid/framework/program_desc.h"
#include "paddle/fluid/framework/variable.h"
#include "paddle/fluid/pybind/op_function_generator.h"
#include "paddle/fluid/pybind/pybind.h"
#include "paddle/fluid/string/string_helper.h"
// phi
#include "paddle/phi/kernels/declarations.h"
#define NUM_CREATED_DUP_INPUTS 4
namespace paddle {
namespace framework {
// To handle append_op at python-level
std::unordered_map<std::string, std::vector<std::string>>
core_ops_returns_info = {};
std::unordered_map<std::string, std::vector<std::string>> core_ops_args_info =
{};
std::unordered_map<std::string, std::vector<std::string>>
core_ops_args_type_info = {};
/* --- Static maps to handle corner cases --- */
static std::unordered_map<std::string, paddle::framework::AttributeMap>
operators_with_attrs = {};
static std::unordered_set<std::string> ops_to_fill_zero_for_empty_grads = {
"split", "rnn"};
/* --- Black Ops list that's NO NEED to apply code generation --- */
static std::unordered_set<std::string> black_ops_list = {"run_program"};
static std::string LegalizeVariableName(const std::string& var_name) {
std::string ret = var_name;
std::replace(ret.begin(), ret.end(), '-', '_'); // replace all '-' to '_'
std::replace(ret.begin(), ret.end(), '@', '_'); // replace all '-' to '_'
return ret;
}
static std::string LegalizeVarName(const std::string& var_name) {
std::string ret = var_name;
std::replace(ret.begin(), ret.end(), '@', '_'); // replace all '-' to '_'
return ret;
}
static std::string HandleDynamicGradAttributes(const std::string& fwd_op_type,
const std::string& attrs_name) {
std::string additional_grad_attrs_str = "";
if (fwd_op_type == "sum") {
const char* GRAD_ATTRS_TEMPLATE = " %s[\"%s\"] = %s;\n";
additional_grad_attrs_str = paddle::string::Sprintf(
GRAD_ATTRS_TEMPLATE, attrs_name, "scale", "float(1.0)");
additional_grad_attrs_str += paddle::string::Sprintf(
GRAD_ATTRS_TEMPLATE, attrs_name, "bias", "float(0.0f)");
additional_grad_attrs_str += paddle::string::Sprintf(
GRAD_ATTRS_TEMPLATE, attrs_name, "bias_after_scale", "bool(true)");
} else if (fwd_op_type == "scale") {
const char* GRAD_ATTRS_TEMPLATE = " %s[\"%s\"] = %s;\n";
additional_grad_attrs_str += paddle::string::Sprintf(
GRAD_ATTRS_TEMPLATE, attrs_name, "bias", "float(0.0f)");
additional_grad_attrs_str += paddle::string::Sprintf(
GRAD_ATTRS_TEMPLATE, attrs_name, "bias_after_scale", "bool(true)");
}
return additional_grad_attrs_str;
}
static void PrepareAttrMapForOps() {
// Handle "fused_elemwise_add_activation"
std::vector<std::string> functor_list = {"a", "b"};
operators_with_attrs["fused_elemwise_add_activation"] = {};
operators_with_attrs["fused_elemwise_add_activation"]["functor_list"] =
functor_list;
// Handle "fused_elemwise_activation"
operators_with_attrs["fused_elemwise_activation"] = {};
operators_with_attrs["fused_elemwise_activation"]["functor_list"] =
functor_list;
// Handle "reverse"
std::vector<int> axis = {0};
operators_with_attrs["reverse"] = {};
operators_with_attrs["reverse"]["axis"] = axis;
// Handle "flip"
operators_with_attrs["flip"] = {};
operators_with_attrs["flip"]["axis"] = axis;
// Handle "cast"
operators_with_attrs["cast"] = {};
operators_with_attrs["cast"]["out_dtype"] = 5;
operators_with_attrs["cast"]["in_dtype"] = 5;
// Handle "transfer_dtype"
operators_with_attrs["transfer_dtype"] = {};
operators_with_attrs["transfer_dtype"]["out_dtype"] = 5;
operators_with_attrs["transfer_dtype"]["in_dtype"] = 5;
// Handle "c_split"
operators_with_attrs["c_split"] = {};
operators_with_attrs["c_split"]["nranks"] = 1;
}
/* --- Helper Objects --- */
class ForwardGenerationInfo {
public:
const std::string& GetOpType() const { return op_type_; }
void SetOpType(const std::string& op_type) { op_type_ = op_type; }
const std::unordered_map<std::string, size_t>& GetFwdInputsNamePosMap()
const {
return fwd_inputs_name_pos_map_;
}
std::unordered_map<std::string, size_t>* GetMutableFwdInputsNamePosMap() {
return &fwd_inputs_name_pos_map_;
}
const std::unordered_map<std::string, size_t>& GetFwdOutputsNamePosMap()
const {
return fwd_outputs_name_pos_map_;
}
std::unordered_map<std::string, size_t>* GetMutableFwdOutputsNamePosMap() {
return &fwd_outputs_name_pos_map_;
}
const std::vector<proto::OpProto::Var>& GetInVars() const { return in_vars_; }
std::vector<proto::OpProto::Var>* GetMutableInVars() { return &in_vars_; }
const std::vector<proto::OpProto::Var>& GetOutVars() const {
return out_vars_;
}
std::vector<proto::OpProto::Var>* GetMutableOutVars() { return &out_vars_; }
private:
std::string op_type_;
std::unordered_map<std::string, size_t> fwd_inputs_name_pos_map_;
std::unordered_map<std::string, size_t> fwd_outputs_name_pos_map_;
std::vector<proto::OpProto::Var> in_vars_;
std::vector<proto::OpProto::Var> out_vars_;
};
class GradNodeGenerationInfo {
class OpBaseGenerationInfo {
public:
const std::string& GetOpBaseType() const { return op_base_type_; }
void SetOpBaseType(const std::string& op_type) { op_base_type_ = op_type; }
const std::map<std::string, std::string>& GetGradOutsSlotnameMap() const {
return grad_outs_slotname_map_;
}
std::map<std::string, std::string>* GetMutableGradOutsSlotnameMap() {
return &grad_outs_slotname_map_;
}
const std::map<std::string, std::string>& GetGradInsFwdSlotnameMap() const {
return grad_ins_fwd_slotname_map_;
}
std::map<std::string, std::string>* GetMutableGradInsFwdSlotnameMap() {
return &grad_ins_fwd_slotname_map_;
}
const std::map<std::string, std::string>& GetGradInsGradSlotnameMap()
const {
return grad_ins_grad_slotname_map_;
}
std::map<std::string, std::string>* GetMutableGradInsGradSlotnameMap() {
return &grad_ins_grad_slotname_map_;
}
const std::map<
std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>&
GetGradIns() const {
return grad_ins_;
}
std::map<std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>*
GetMutableGradIns() {
return &grad_ins_;
}
const std::map<
std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>&
GetGradOuts() const {
return grad_outs_;
}
std::map<std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>*
GetMutableGradOuts() {
return &grad_outs_;
}
const paddle::framework::AttributeMap& GetGradAttrs() const {
return grad_attrs_;
}
paddle::framework::AttributeMap* GetMutableGradAttrs() {
return &grad_attrs_;
}
const std::unordered_set<std::string>& GetNoNeedBufferInputs() const {
return no_need_buffer_ins_;
}
std::unordered_set<std::string>* GetMutableNoNeedBufferInputs() {
return &no_need_buffer_ins_;
}
private:
std::string op_base_type_;
std::map<std::string, std::string> grad_outs_slotname_map_;
std::map<std::string, std::string> grad_ins_fwd_slotname_map_;
std::map<std::string, std::string> grad_ins_grad_slotname_map_;
std::map<std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>
grad_ins_;
std::map<std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>
grad_outs_;
paddle::framework::AttributeMap grad_attrs_;
std::unordered_set<std::string> no_need_buffer_ins_;
};
public:
const std::string& GetFwdOpType() const { return fwd_op_type_; }
void SetFwdOpType(const std::string& op_type) { fwd_op_type_ = op_type; }
bool GenerateForwardOnly() const { return generate_forward_only_; }
void SetGenerateForwardOnly(bool generate_forward_only) {
generate_forward_only_ = generate_forward_only;
}
const std::vector<OpBaseGenerationInfo>& GetOpBaseInfos() const {
return op_base_infos_;
}
std::vector<OpBaseGenerationInfo>* GetMutableOpBaseInfos() {
return &op_base_infos_;
}
private:
std::string fwd_op_type_;
bool generate_forward_only_ = false;
std::vector<OpBaseGenerationInfo> op_base_infos_;
};
/* --- Helper Functions --- */
static std::string AttrTypeToString(const proto::AttrType& type) {
std::string ret;
switch (type) {
case (proto::AttrType::INT): {
ret = "int";
break;
}
case (proto::AttrType::FLOAT): {
ret = "float";
break;
}
case (proto::AttrType::STRING): {
ret = "std::string&";
break;
}
case (proto::AttrType::INTS): {
ret = "std::vector<int>&";
break;
}
case (proto::AttrType::FLOATS): {
ret = "std::vector<float>&";
break;
}
case (proto::AttrType::STRINGS): {
ret = "std::vector<std::string>&";
break;
}
case (proto::AttrType::BOOLEAN): {
ret = "bool";
break;
}
case (proto::AttrType::BOOLEANS): {
ret = "std::vector<bool>&";
break;
}
case (proto::AttrType::LONG): {
ret = "int64_t";
break;
}
case (proto::AttrType::LONGS): {
ret = "std::vector<int64_t>&";
break;
}
case (proto::AttrType::BLOCK): {
ret = "paddle::framework::BlockDesc*";
break;
}
case (proto::AttrType::BLOCKS): {
ret = "std::vector<paddle::framework::BlockDesc*>&";
break;
}
case (proto::AttrType::FLOAT64S): {
ret = "std::vector<double>&";
break;
}
default: {
PADDLE_THROW(platform::errors::Fatal(
"AttrType of type boost::variant only supports specific data types."
"However, detected unrecognized AttrType: %d",
type));
}
}
return ret;
}
template <typename T>
static std::string GetAttrValue(const framework::Attribute& attr,
bool is_vector) {
std::string val = "";
if (is_vector) {
val += "{";
for (auto x : BOOST_GET_CONST(std::vector<T>, attr)) {
val += std::to_string(x) + ",";
}
if (val.size() > 1) val.pop_back();
val += "}";
} else {
val = std::to_string(BOOST_GET_CONST(T, attr));
}
return val;
}
static std::pair<std::string, std::string> GetAttrType(
const framework::Attribute& attr, bool is_arg) {
std::string ret = "";
std::string val = "";
size_t variant_pos = attr.which();
switch (variant_pos) {
case (1): {
ret = "int";
val = GetAttrValue<int>(attr, false);
break;
}
case (2): {
ret = "float";
val = GetAttrValue<float>(attr, false);
break;
}
case (3): {
ret = "std::string";
if (is_arg) ret += "&";
val = "\"" + BOOST_GET_CONST(std::string, attr) + "\"";
break;
}
case (4): {
ret = "std::vector<int>";
if (is_arg) ret += "&";
val = GetAttrValue<int>(attr, true);
break;
}
case (5): {
ret = "std::vector<float>";
if (is_arg) ret += "&";
val = GetAttrValue<float>(attr, true);
break;
}
case (6): {
ret = "std::vector<std::string>";
if (is_arg) ret += "&";
val += "{";
for (auto x : BOOST_GET_CONST(std::vector<std::string>, attr)) {
val += "\"" + x + "\"" + ",";
}
if (val.size() > 1) val.pop_back();
val += "};";
break;
}
case (7): {
ret = "bool";
val = GetAttrValue<bool>(attr, false);
break;
}
case (8): {
ret = "std::vector<bool>";
if (is_arg) ret += "&";
val = GetAttrValue<bool>(attr, true);
break;
}
case (9): {
ret = "BlockDesc*";
break;
}
case (10): {
ret = "int64_t";
val = GetAttrValue<int64_t>(attr, false);
break;
}
case (11): {
ret = "std::vector<BlockDesc*>";
if (is_arg) ret += "&";
break;
}
case (12): {
ret = "std::vector<int64_t>";
if (is_arg) ret += "&";
val = GetAttrValue<int64_t>(attr, true);
break;
}
case (13): {
ret = "std::vector<double>";
if (is_arg) ret += "&";
val = GetAttrValue<double>(attr, true);
break;
}
default: {
PADDLE_THROW(platform::errors::Fatal(
"AttrType of type boost::variant only supports specific data types."
"However, detected unrecognized AttrType: %d",
variant_pos));
}
}
return {ret, val};
}
static void SlotNameMatching(
const std::map<
std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>&
grad_map,
const std::map<
std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>&
fwd_ins,
const std::map<
std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>&
fwd_outs,
std::map<std::string, std::string>* grad_fwd_slotname_map_ptr,
std::map<std::string, std::string>* grad_grad_slotname_map_ptr) {
std::map<std::string, std::string>& grad_fwd_slotname_map =
*grad_fwd_slotname_map_ptr;
std::map<std::string, std::string>& grad_grad_slotname_map =
*grad_grad_slotname_map_ptr;
for (const auto& iter : grad_map) {
const std::string& grad_slot_name = iter.first;
const std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>&
grad_vars = iter.second;
// Find matching fwd_slot_name
bool found_matching = false;
for (const std::shared_ptr<paddle::imperative::VariableWrapper>& grad_var :
grad_vars) {
for (const auto& fwd_iter : fwd_ins) {
const std::string& fwd_slot_name = fwd_iter.first;
const std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>&
fwd_vars = fwd_iter.second;
for (const std::shared_ptr<paddle::imperative::VariableWrapper>&
fwd_var : fwd_vars) {
if (grad_var == fwd_var) {
if (grad_fwd_slotname_map.count(grad_slot_name) &&
grad_fwd_slotname_map[grad_slot_name] != fwd_slot_name) {
PADDLE_THROW(platform::errors::Fatal(
"Detected mismatched slot names."
"grad_slot_name %s matches both %s and %s fwd_slot_name",
grad_slot_name, grad_fwd_slotname_map[grad_slot_name],
fwd_slot_name));
}
grad_fwd_slotname_map[grad_slot_name] = fwd_slot_name;
found_matching = true;
}
if (fwd_var->GetGradVar() && grad_var == fwd_var->GetGradVar()) {
if (grad_grad_slotname_map.count(grad_slot_name) &&
grad_grad_slotname_map[grad_slot_name] != fwd_slot_name) {
PADDLE_THROW(platform::errors::Fatal(
"Detected mismatched slot names."
"grad_slot_name %s matches both %s and %s fwd_slot_name",
grad_slot_name, grad_grad_slotname_map[grad_slot_name],
fwd_slot_name));
}
grad_grad_slotname_map[grad_slot_name] = fwd_slot_name;
found_matching = true;
}
}
}
for (const auto& fwd_iter : fwd_outs) {
const std::string& fwd_slot_name = fwd_iter.first;
const std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>&
fwd_vars = fwd_iter.second;
for (const std::shared_ptr<paddle::imperative::VariableWrapper>&
fwd_var : fwd_vars) {
if (grad_var == fwd_var) {
if (grad_fwd_slotname_map.count(grad_slot_name) &&
grad_fwd_slotname_map[grad_slot_name] != fwd_slot_name) {
PADDLE_THROW(platform::errors::Fatal(
"Detected mismatched slot names"
"grad_slot_name %s matches both %s and %s fwd_slot_name",
grad_slot_name, grad_fwd_slotname_map[grad_slot_name],
fwd_slot_name));
}
grad_fwd_slotname_map[grad_slot_name] = fwd_slot_name;
found_matching = true;
}
if (fwd_var->GetGradVar() && grad_var == fwd_var->GetGradVar()) {
if (grad_grad_slotname_map.count(grad_slot_name) &&
grad_grad_slotname_map[grad_slot_name] != fwd_slot_name) {
PADDLE_THROW(platform::errors::Fatal(
"Detected mismatched slot names."
"grad_slot_name %s matches both %s and %s fwd_slot_name",
grad_slot_name, grad_grad_slotname_map[grad_slot_name],
fwd_slot_name));
}
grad_grad_slotname_map[grad_slot_name] = fwd_slot_name;
found_matching = true;
}
}
}
}
if (!found_matching) {
PADDLE_THROW(platform::errors::Fatal(
"Detected mismatched slot names."
"Found no matching fwd_slot_name for grad_slot_name: %s",
grad_slot_name));
} else {
std::string fwd_slot_name = grad_grad_slotname_map.count(grad_slot_name)
? grad_grad_slotname_map[grad_slot_name]
: grad_fwd_slotname_map[grad_slot_name];
VLOG(6) << "Found matching fwd_slot_name: " << fwd_slot_name
<< " for grad_slot_name: " << grad_slot_name;
}
}
}
static bool CheckOpProto(proto::OpProto* op_proto) {
if (op_proto == nullptr) {
return false;
}
const std::string& op_type = op_proto->type();
// Skip ooerator which is not inherit form OperatorWithKernel, like while,
// since only OperatorWithKernel can run in dygraph mode.
auto& all_kernels = paddle::framework::OperatorWithKernel::AllOpKernels();
if (!all_kernels.count(op_type) &&
!phi::KernelFactory::Instance().HasCompatiblePhiKernel(op_type)) {
return false;
}
// Only handle matmul_v2 for now
VLOG(1) << "------ Analyzing Op ------: " << op_type;
return true;
}
static bool BeSameAsInput(const std::string& output_name,
const std::set<std::string>& input_names) {
if (output_name.size() < 4) {
return false;
}
if (output_name.substr(output_name.size() - 3, 3) == "Out") {
if (input_names.count(output_name.substr(0, output_name.size() - 3))) {
return true;
}
}
return false;
}
/* --------------------------------------- */
/* --------- Preprocess Ins/Outs --------- */
/* --------------------------------------- */
static void PurifyForwardOpProto(const proto::OpProto& op_proto,
ForwardGenerationInfo* fwd_info) {
// Op Name
const std::string op_name = op_proto.type();
auto* in_vars = fwd_info->GetMutableInVars();
auto* out_vars = fwd_info->GetMutableOutVars();
auto* fwd_inputs_name_pos_map = fwd_info->GetMutableFwdInputsNamePosMap();
auto* fwd_outputs_name_pos_map = fwd_info->GetMutableFwdOutputsNamePosMap();
// Handle dispensable inputs
for (const proto::OpProto::Var& input : op_proto.inputs()) {
std::string input_name = input.name();
// Delete dispensable tensor unless specified in op_ins_map
if (input.dispensable()) {
if (!op_ins_map.count(op_name) ||
!op_ins_map[op_name].count(input_name)) {
VLOG(6) << "Removing Dispensable Input: " << input_name;
// in_vars
auto iter = in_vars->begin();
for (iter = in_vars->begin(); iter != in_vars->end(); iter++) {
if (iter->name() == input_name) {
break;
}
}
in_vars->erase(iter);
}
}
}
for (const proto::OpProto::Var& output : op_proto.outputs()) {
std::string output_name = output.name();
// Delete dispensable tensor unless specified in op_outs_map
if (output.dispensable()) {
if (!op_outs_map.count(op_name) ||
!op_outs_map[op_name].count(output_name)) {
VLOG(6) << "Removing Dispensable Output: " << output_name;
// out_vars
auto iter = out_vars->begin();
for (iter = out_vars->begin(); iter != out_vars->end(); iter++) {
if (iter->name() == output_name) {
break;
}
}
out_vars->erase(iter);
}
}
}
/* ------ Maping forward slot name to fwd position ------ */
size_t in_pos = 0;
for (const auto& var : *in_vars) {
VLOG(6) << "Mapping input tensor: " << var.name()
<< " To position: " << in_pos;
(*fwd_inputs_name_pos_map)[var.name()] = in_pos;
in_pos++;
}
size_t out_pos = 0;
for (const auto& var : *out_vars) {
VLOG(6) << "Mapping output tensor: " << var.name()
<< " To position: " << out_pos;
(*fwd_outputs_name_pos_map)[var.name()] = out_pos;
out_pos++;
}
}
static void PurifyGradNodeGenerationInfo(const proto::OpProto& op_proto,
GradNodeGenerationInfo* bwd_info) {
auto* op_base_infos = bwd_info->GetMutableOpBaseInfos();
for (auto& iter : *op_base_infos) {
std::map<std::string, std::string>* grad_outs_slotname_map =
iter.GetMutableGradOutsSlotnameMap();
std::map<std::string, std::string>* grad_ins_fwd_slotname_map =
iter.GetMutableGradInsFwdSlotnameMap();
std::map<std::string, std::string>* grad_ins_grad_slotname_map =
iter.GetMutableGradInsGradSlotnameMap();
std::map<std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>*
grad_ins = iter.GetMutableGradIns();
std::map<std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>*
grad_outs = iter.GetMutableGradOuts();
// Op Name
const std::string op_name = op_proto.type();
// Handle dispensable inputs
for (const proto::OpProto::Var& input : op_proto.inputs()) {
std::string input_name = input.name();
// Delete dispensable tensor unless specified in op_ins_map
if (input.dispensable()) {
if (!op_ins_map.count(op_name) ||
!op_ins_map[op_name].count(input_name)) {
VLOG(6) << "Removing Dispensable Input: " << input_name;
// grad_outs_slotname_map
auto grad_outs_slotname_map_purified = *grad_outs_slotname_map;
for (const auto& iter : *grad_outs_slotname_map) {
const std::string& grad_output_name = iter.first;
const std::string& matched_input_name = iter.second;
if (matched_input_name == input_name) {
grad_outs_slotname_map_purified.erase(grad_output_name);
PADDLE_ENFORCE(
grad_outs->count(grad_output_name) > 0,
paddle::platform::errors::Fatal(
"Unable to find gradient output name in grad_outs."));
// grad_outs
grad_outs->erase(grad_output_name);
}
}
*grad_outs_slotname_map = grad_outs_slotname_map_purified;
// grad_ins_fwd_slotname_map: output as tensorwrapper
if (grad_ins_fwd_slotname_map->count(input_name))
grad_ins_fwd_slotname_map->erase(input_name);
// grad_ins: output as tensorwrapper
if (grad_ins->count(input_name)) grad_ins->erase(input_name);
}
}
}
for (const proto::OpProto::Var& output : op_proto.outputs()) {
std::string output_name = output.name();
// Delete dispensable tensor unless specified in op_outs_map
if (output.dispensable()) {
if (!op_outs_map.count(op_name) ||
!op_outs_map[op_name].count(output_name)) {
VLOG(6) << "Removing Dispensable Output: " << output_name;
// grad_ins_grad_slotname_map
auto grad_ins_grad_slotname_map_purified =
*grad_ins_grad_slotname_map;
for (const auto& iter : *grad_ins_grad_slotname_map) {
const std::string& grad_input_name = iter.first;
const std::string& matched_output_name = iter.second;
if (matched_output_name == output_name) {
grad_ins_grad_slotname_map_purified.erase(grad_input_name);
PADDLE_ENFORCE(
grad_ins->count(grad_input_name) > 0,
paddle::platform::errors::Fatal(
"Unable to find gradient input name in grad_ins."));
// grad_ins
grad_ins->erase(grad_input_name);
}
}
*grad_ins_grad_slotname_map = grad_ins_grad_slotname_map_purified;
// grad_ins_fwd_slotname_map: output as tensorwrapper
if (grad_ins_fwd_slotname_map->count(output_name))
grad_ins_fwd_slotname_map->erase(output_name);
// grad_ins: output as tensorwrapper
if (grad_ins->count(output_name)) grad_ins->erase(output_name);
}
}
}
}
}
/* -------------------------------- */
/* --------- Collect Info --------- */
/* -------------------------------- */
static void CollectForwardInformationFromOpInfo(
const paddle::framework::OpInfo& op_info, ForwardGenerationInfo* fwd_info) {
const proto::OpProto& op_proto = *op_info.proto_;
fwd_info->SetOpType(op_proto.type());
for (const proto::OpProto::Var& input : op_proto.inputs()) {
fwd_info->GetMutableInVars()->push_back(input);
}
for (const proto::OpProto::Var& output : op_proto.outputs()) {
fwd_info->GetMutableOutVars()->push_back(output);
}
}
static bool CollectGradInformationFromOpInfo(
const paddle::framework::OpInfo& op_info,
GradNodeGenerationInfo* bwd_info) {
const proto::OpProto& op_proto = *op_info.proto_;
const std::string& op_type = op_proto.type();
std::vector<int64_t> dims = {1, 1, 1, 1};
/* ------ Prepare "ins" ------ */
std::map<std::string,
std::vector<std::shared_ptr<paddle::imperative::VarBase>>>
ins;
if (op_proto.inputs().size() == 1 && op_proto.outputs().size() == 1 &&
op_proto.inputs()[0].duplicable() &&
!op_proto.outputs()[0].duplicable()) {
VLOG(6) << "Handle op with special op_bases: " << op_type;
// @special case (sum_op): for ops with single duplicable input and single
// non-duplicable output
// feed in NUM_CREATED_DUP_INPUTS inputs to detect a
// special scenario.
const std::string& in_name = op_proto.inputs()[0].name();
ins[in_name] = {};
for (size_t i = 0; i < NUM_CREATED_DUP_INPUTS; i++) {
ins[in_name].emplace_back(std::shared_ptr<paddle::imperative::VarBase>(
new paddle::imperative::VarBase("auto_" + in_name + "_" +
std::to_string(i))));
ins[in_name][i]->SetOverridedStopGradient(false);
ins[in_name][i]->MutableVar()->GetMutable<framework::LoDTensor>();
}
} else {
for (const proto::OpProto::Var& input : op_proto.inputs()) {
const std::string& in_name = input.name();
// Handle dispensable input:
// 1. At python level, dispensable input will be detected at Python-C
// interface and filled with an empty vector
// 2. At C++ level, customers should always pass an empty vector for any
// dispensable input
// 3. During further lowering, there will always be a placeholder VarBase
// in ins/outs no matter whether it's dispensable or not
// As a result, we always create input VarBase regardless of its
// dispensability.
// Handle duplicable input: list(VarBase) or VarBase
// We dont know the exact number of inputs expected,
// but we only need to identify the slot name order,
// therefore fill in 1 single input VarBase is enough in this scenario
ins[in_name] = {std::shared_ptr<paddle::imperative::VarBase>(
new paddle::imperative::VarBase("auto_" + in_name))};
ins[in_name][0]->SetOverridedStopGradient(false);
ins[in_name][0]->MutableVar()->GetMutable<framework::LoDTensor>();
}
}
VLOG(6) << "Prepared Forward Ins Map, size = " << ins.size();
/* ------ Prepare "outs" ------ */
std::map<std::string,
std::vector<std::shared_ptr<paddle::imperative::VarBase>>>
outs;
for (const proto::OpProto::Var& output : op_proto.outputs()) {
const std::string& out_name = output.name();
// We always create output VarBase regardless of its dispensability.
// We dont know the exact number of outputs during code generation,
// however, simply identifying the slot name order would be enough
outs[out_name] = {std::shared_ptr<paddle::imperative::VarBase>(
new paddle::imperative::VarBase("auto_" + out_name))};
outs[out_name][0]->SetOverridedStopGradient(false);
outs[out_name][0]->MutableVar()->GetMutable<framework::LoDTensor>();
}
VLOG(6) << "Prepared Forward Outs Map, size = " << outs.size();
framework::AttributeMap attrs;
paddle::framework::AttributeMap default_attrs;
auto* attr_checker = op_info.Checker();
if (attr_checker) {
VLOG(6) << "Checking AttributeMap Settings";
attr_checker->Check(&attrs, true, /*only_check_exist_value=*/true);
default_attrs = attr_checker->GetDefaultAttrMap();
} else {
VLOG(6) << "Detected Null Attribute Checker, use empty default_attrs";
}
if (operators_with_attrs.count(op_type)) {
VLOG(6) << "Found operator " << op_type << " using special AttributeMap";
attrs = operators_with_attrs[op_type];
}
VLOG(6) << "Prepared Default Attributes Map, size = " << default_attrs.size();
for (const auto& iter : default_attrs) {
VLOG(6) << iter.first;
}
/* ---------------------------- */
/* --------- Backward --------- */
/* ---------------------------- */
/* ------ Fwd paddle::imperative::VariableWrapper Map ------ */
std::map<std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>
fwd_ins;
std::map<std::string,
std::vector<std::shared_ptr<paddle::imperative::VariableWrapper>>>
fwd_outs;
for (const auto& iter : ins) {
fwd_ins[iter.first] = {};
for (const std::shared_ptr<paddle::imperative::VarBase>& var_base :
iter.second) {
fwd_ins[iter.first].push_back(var_base->SharedVar());
}
}
for (const auto& iter : outs) {
fwd_outs[iter.first] = {};
for (const std::shared_ptr<paddle::imperative::VarBase>& var_base :
iter.second) {
fwd_outs[iter.first].push_back(var_base->SharedVar());
}
}
VLOG(6) << "Constructed Forward paddle::imperative::VariableWrapper Map";
/* ------ Run GradOpMaker ------ */
if (!op_info.dygraph_grad_op_maker_) {
VLOG(6) << op_type << " has no GradOpMaker";
bwd_info->SetGenerateForwardOnly(true);
return false;
}
std::shared_ptr<paddle::imperative::GradOpNode> grad_node =
op_info.dygraph_grad_op_maker_(op_type, ins, outs, attrs, default_attrs,
{});
if (!grad_node) {
VLOG(6) << "Got nullptr GradOpNode for " << op_type
<< " likely registered EmptyGradOpMaker";
bwd_info->SetGenerateForwardOnly(true);
return false;
}
VLOG(6) << "Prepared GradOpNode";
/* ---- Collect OpBase's op_types ---- */
bwd_info->SetFwdOpType(op_type);
auto* op_base_infos = bwd_info->GetMutableOpBaseInfos();
op_base_infos->resize(grad_node->size());
for (auto iter = grad_node->begin(); iter < grad_node->end(); iter++) {
// Each OpBase
int index = std::distance(grad_node->begin(), iter);
paddle::imperative::OpBase& op_base = *iter;
(*op_base_infos)[index].SetOpBaseType(op_base.Type());
}
/* ------ Get Grad ins/outs/attrs ---- */
VLOG(6) << "In function size: " << grad_node->size();
for (auto iter = grad_node->begin(); iter < grad_node->end(); iter++) {
int index = std::distance(grad_node->begin(), iter);
auto* op_base_grad_ins = (*op_base_infos)[index].GetMutableGradIns();
auto* op_base_grad_outs = (*op_base_infos)[index].GetMutableGradOuts();
auto* op_base_grad_attrs = (*op_base_infos)[index].GetMutableGradAttrs();
const paddle::imperative::OpBase& op_base = *iter;
const std::map<std::string, paddle::imperative::SavedVariableWrapperList>&
g_ins = op_base.GetInsMap();
const std::map<std::string, paddle::imperative::SavedVariableWrapperList>&
g_outs = op_base.GetOutsMap();
*op_base_grad_attrs = op_base.Attrs();
for (const auto& it : g_ins) {
if (!op_base_grad_ins->count(it.first))
(*op_base_grad_ins)[it.first] = {};
for (auto vw_iter = it.second.begin(); vw_iter != it.second.end();
vw_iter++) {
std::shared_ptr<paddle::imperative::VariableWrapper> vw = *vw_iter;
(*op_base_grad_ins)[it.first].push_back(vw);
VLOG(6) << "GradIns Name: " << it.first;
}
}
for (const auto& it : g_outs) {
if (!op_base_grad_outs->count(it.first))
(*op_base_grad_outs)[it.first] = {};
for (auto vw_iter = it.second.begin(); vw_iter != it.second.end();
vw_iter++) {
std::shared_ptr<paddle::imperative::VariableWrapper> vw = *vw_iter;
(*op_base_grad_outs)[it.first].push_back(vw);
VLOG(6) << "GradOuts Name: " << it.first;
}
}
auto& inferer = op_base.Info().NoNeedBufferVarsInferer();
if (inferer && !special_no_need_buffer_op_set.count(op_type)) {
*(*op_base_infos)[index].GetMutableNoNeedBufferInputs() =
inferer(g_ins, g_outs, *op_base_grad_attrs);
}
}
/* ------ Slot Name Matching ---- */
for (auto& iter : *op_base_infos) {
// grad_ins -> fwd_ins, fwd_outs
SlotNameMatching(iter.GetGradIns(), fwd_ins, fwd_outs,
iter.GetMutableGradInsFwdSlotnameMap(),
iter.GetMutableGradInsGradSlotnameMap());
// grad_outs -> fwd_ins, fwd_outs
SlotNameMatching(iter.GetGradOuts(), fwd_ins, fwd_outs,
iter.GetMutableGradOutsSlotnameMap(),
iter.GetMutableGradOutsSlotnameMap());
}
VLOG(6) << "Finished Slotname Matching";
return true;
}